Does anyone like doing arrays? if so, please help!! Please be detailed with comm
ID: 3626224 • Letter: D
Question
Does anyone like doing arrays? if so, please help!! Please be detailed with comment in the codes so I can follow whats happening and learn =) thanks!
int n = count(list, 3);
would return 2 because there are 2 occurrences of the value 3 in the list.
[18, 7, 4, 24, 11]
The number 18 is stretched into the pair (9, 9), the number 7 is stretched into (4, 3), the number 4 is stretched into (2, 2), the number 24 is stretched into (12, 12) and the number 11 is stretched into (6, 5). Thus,the call:
stretch(list);
should replace list with the following list which is twice the length of the original:
[9, 9, 4, 3, 2, 2, 12, 12, 6, 5]
Explanation / Answer
// Write a function rotateRight that takes an array of integers as an argument and rotates values in the array one to the right (i.e., one forward in position), shifting the value at the end of the array to the front.
public void rotateRight(int[] array)
{
int temp = array[array.length-1];
for(int i = 0; i < array.length-1; i++)
array[i+1] = array[i];
array[0] = temp;
}
// Write a function count that takes an array of integers and a target value as parameters and returns the number of occurrences of the target value in the array.
public int count(int[] array, int target)
{
int output = 0;
for(int x : array)
if(x == target)
output++;
return output;
}
// Write a function called stretch that takes an array of integers as an argument, replaces the array with a new array twice as large as the original that replaces every integer from the original list with a pair of integers, each half the original, and then returns it. If a number in the original list is odd, then the first number in the new pair should be one higher than the second so that the sum equals the original number.
public int[] stretch(int[] array)
{
int[] output = new int[array.length*2];
for(int i = 0; i < array.length; i++)
{
output[i*2] = (int)Math.floor(array[i]/2.0);
output[i*2+1] = (int)Math.ceil(array[i]/2.0);
}
return output;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.