0% found this document useful (0 votes)
52 views

[key] csa u4l5 random extra practice

Uploaded by

Zeyna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

[key] csa u4l5 random extra practice

Uploaded by

Zeyna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

CSA Unit 4 Lesson 5

Name(s) __________________________________________________ Period _______ Date _____________________

[KEY] Extra Practice - Random

Check for Understanding

Assume that the following variable declarations have been made.

double j = Math.random();
double k;

Which of the following assigns a value to k between 0.75 to 4.75?

A. k = j + 0.75;

B. k = j + 0.75 * 4.0;

C. k = j * 4.0;

D. k = j * 4.0 + 0.75;

E. k = j * 4.75;

1
AP Exam Prep

Consider the following code segment.

/*
* Returns a 1D array of random int values between 0 and 100, inclusive
*/
public int[] createRandomNumbers() {
int[] tempNumbers = new int[10];

for (int index = 0; index < tempNumbers.length; index++) {


/* missing code */
}

return tempNumbers;
}

Which line of code should replace /* missing code */ to produce the intended result?

A. tempNumbers[index] = (int)(Math.random() * 101);

B. tempNumbers[index] = Math.random() * 101;

C. tempNumbers[index] = (int)(Math.random() * 100);

D. tempNumbers[index] = Math.random * 100;

E. tempNumbers[index] = (int)(Math.random() * 100) + 1;

2
Extra Practice

Do This: Using Math.random(), implement an algorithm for each of the following prompts.

Given a 1D String array names, randomly select and print a name.

// selects a random index


int randomIndex = (int)(Math.random() * names.length);

// prints the name located at the randomly generated index


String selectedName = names[randomIndex];
System.out.println(selectedName);

Given 1D array of int values called nums, randomly shuffle the array. To shuffle, repeatedly swap the values of
two randomly selected elements of the array.

Student responses will vary. Example:

// to shuffle the array, this algorithm swaps randomly selected elements 100 times
for (int count = 0; count < 100; count++) {

// generates two random indexes for nums


int firstIndex = (int)(Math.random() * nums.length);
int secondIndex = (int)(Math.random() * nums.length;

// swaps the elements of the two selected indexes


int temp = nums[firstIndex];
nums[firstIndex] = nums[secondIndex];
nums[secondIndex] = temp;
}

You might also like