CSc 398 Mid-Term Test 19 March 1999 Page 1 >>>>>>>>>>>>>>>>>>>>>>>>>>ANSWERS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 1. (15 points) Assume that T is an array of numbers. Write three different code fragments, each using a different collection method, to find the sum of the squares of the numbers in T. T:=0. S do:[:each| T:=T+each squared] T:=0. S with:S do:[:i :j|T:=i*j+T] S inject:0 into:[:tot :each| tot+each squared] 2. (10 points) Assume that T is an array of points. Write code which returns the points in an array sorted by the squared Euclidean distance of the points from the origin. (The squared Euclidean distance of (x,y) from the origin is x*x + (y*y). Thus, the squared Euclidean distance of (2,3) is 13, the squared Euclidean distance of (3,3) is 18, etc.) (T asSortedCollection sortBlock:[:a :b| a x squared + a y squared < (b x squared + b y squared)]) asArray 3. (15 points) Assume that T is an array with a variety of entries (e.g., strings, points, numbers, characters, etc.). Let R:=ReadStream on:T and W:=WriteStream on:String new. Write code such that after the code is executed, evaluating the expression "W contents" returns a string with (only) the numbers appearing in T. For example, if T is #(a = 2 2@3 'hello' 44 (33)), then W contents would return '2 44'. R:=ReadStream on:T W:=WriteStream on:String new [R atEnd] whileFalse:[ (X:=R next) isNumber ifTrue:[W nextPutAll:X printString,' ']]. W contents 4. (10 points) After the following code is finished executing, what is returned when the expression "T printString" is evaluated? T:=OrderedCollection new. X:=[1 to:20 by:3 do:[:each|T addLast:each. Processor yield]]. Y:=[ 11 to:17 do:[:i| T addLast:i. Processor yield]] X fork. Y fork 'OrderedCollection(1 4 11 7 12 10 13 13 14 16 15 19 16 17 )' CSc 398 Mid-Term Test 19 March 1999 Page 2 5. (50 points) Write the description of a class Counter. An instance of Counter can only count between some limits which are specified when the instance is instantiated. (Such an object could provide protection against accessing arrays outside some given bounds. Thus, if you have an array of size 10 and only accessed the array via an instance of Counter limited to 1, 2, ..., 10, then you could not go beyond the limits of the array.) You should state the instance variable(s), and you should write the instance and class methods. "Test Example 17 March 1999" Object subclass: #Counter instanceVariableNames: 'bottom top count ' classVariableNames: '' poolDictionaries: '' ! !Counter class methods ! bottom:bottom top:top ^super new bottom:bottom top:top! new ^self bottom:0 top:100! ! !Counter methods ! +inc (count+inc)>top | ((count+inc)top | ((count-dec)=top ifTrue:[self error:'Trying to increment aCounter past top'] ifFalse:[count:=count+1]! reset count:=bottom! !