Java Arrays
private int[] myArray;
private void printAll(int[] a) {
for (int x : a) {
System.out.print(x + " ");
}
System.out.println();
}
public static void main(String[] args) {
myArray = new int[10];
a[0] = 10;
a[1] = 9;
a[2] = 8;
...
a[9] = 1;
printAll(myArray);
}
Write these methods:
/** returns index k such that a[k] == x
* but if x is not in a, then returns -1
*/
private int findInArray(int[] a, int x);
/** returns the maximum value of the elements in a
*/
private int findMaxValue(int[] a);
/** returns the minimum value of the elements in a
*/
private int findMinValue(int[] a);
/** Returns a new array whose elements are a reversal of array a
* For example, if a = [1 2 3 4 5]
* then reverseArray(a) = [5 4 3 2 1]
* Array a should not be modified.
*/
private int[] reverseArray(int[] a);
/** Merge a and b together, put a first, then b
*/
private int[] mergeArrays(int[] a, int[] b)
/** Assume a and b are sorted in ascending order
* Returns the merged array in sorted order.
*/
private int[] mergeInOrder(int[] a, int[] b)
/** Returns array b such that
* b[i] = products of all elements in a except a[i]
*/
private int[] product(int[] a)
Note: the last 2 problems are similar to Google's interview questions.
Random
What if you want to make an array of size 10 that contains 10 random integers between 1 and 100?We use:
public static double random()
- Returns:
- a pseudorandom
double
greater than or equal to0.0
and less than1.0
.
int[] a = new int[10];
for (int i=0; i<10; i++) a[i] = (Math.random()*100)+1;
Would that compile? What did we miss?
No comments:
Post a Comment