36S-CS106A-Practice-Solution

36S-CS106A-Practice-Solution - CS106A Handout 36S May 20th,...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS106A Handout 36S Spring 2011 May 20 th , 2011 CS106A Practice Solution Solution 1—Short Answer 1a) As written, the program leaves the array in the following state: list 50 10 10 10 10 If you had wanted mystery to "rotate" the array elements, you would need to run the loop in the opposite order to ensure that no elements are overwritten, like this: private void mystery( int [] array) { int tmp = array[array.length - 1]; for ( int i = array.length - 1; i > 0; i--) { array[i] = array[i - 1]; } array[0] = tmp; } 1b) private int[] insertValue(int value, int[] array) { int[] result = new int[array.length + 1]; for (int i = 0; i < result.length; i++) { result[i] = array[i]; } int pos = 0; for (int i = 0; i < array.length; i++) { if (value > array[i]) { pos = i; break; } } for (int i = result.length; i >= pos; i--) { result[i] = result[i - 1]; } result[pos] = value; return result; } This is the wrong default value; it fails if value is larger than the existing ones. Off by one; past end of array. Also off by one; want >. Wrong array; goes past end Incorrect sign; should be <.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 Solution 2—Using the graphics and random number libraries public class Frogger extends GraphicsProgram { public void
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 5

36S-CS106A-Practice-Solution - CS106A Handout 36S May 20th,...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online