Solution

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/s10-max

public static int max(int[] data) {
    int max_n = data[0];
    for(int i=1; i<data.length; i++) {
        if(data[i] > max_n) {
            max_n = data[i];
        }
    }
	return max_n;
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/s11-average

public static double average(int[] a) {
    double sum = 0;
    for(int num: a) {
        sum = sum+num;
    }
	return sum/a.length;
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/s16a-countStrings

public static int countStrings(String[] list, String target) {
    int result = 0;
    for(int i=0; i<list.length; i++) {
        if(list[i].equals(target)) {
            result++;
        }
    }
    return result;
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/e3-countInRange

public static int countInRange(int[] a, int min, int max) {
    int count = 0;
    for(int num: a) {
        if(num>=min && num <=max)
            count++;
    }
    return count;
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/s16b-equalsStrings

public static boolean equals(String[] list1, String[] list2) {
    if(list1.length!=list2.length) return false; //如果执行语句只有一行,可以不加花括号
    for(int i=0; i<list1.length; i++) {
        if(!list1[i].equals(list2[i])) return false; 
    }
    return true;
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/s17-allLess

public static boolean allLess(int[] lessArray, int[] moreArray) {
    if(lessArray.length != moreArray.length) return false;
    for(int i=0; i<lessArray.length; i++) {
        if(lessArray[i] >= moreArray[i]) return false;
    }
    return true;
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/e1-lastIndexOf

int lastIndexOf(int[] array, int value) {
    for(int i = array.length-1; i>=0; i--) {
        if(array[i] == value) {
            return i;
        }
    }
    return -1;
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/e10-percentEven

public static double percentEven(int[] list) {
    int count = 0;
    for(int i: list) {
        if(i%2 == 0) count++;
    }
    if(list.length == 0) return 0;
    else
        return (double)count/list.length * 100;
	
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/e12-priceIsRight

public static int priceIsRight(int[] bids, int price) {
    int result = -1;
    for(int i: bids) {
        if(i <= price && i> result) {
            result = i;
        }
    }
    return result;
}

https://practiceit.cs.washington.edu/problem/view/bjp5/chapter7/e16-append

public static int[] append(int[] list1, int[] list2) {
    int[] array = new int[list1.length+list2.length];
    for(int i=0; i<list1.length; i++) {
        array[i] = list1[i];
    }
    
    for(int j=0; j<list2.length; j++) {
        array[list1.length+j] = list2[j];
    }
    return array;
}

Last updated