Java Exercise Set Array Best for freshman

Posted by Daveyz83 on Mon, 03 Jan 2022 05:56:45 +0100

  1. Averaging arrays
  2. Sum of all elements of an array
  3. Change the value of the original array element
  4. Print Array
  5. Array created with an initial value
  6. Array with three consecutive odd numbers
  7. Most Elements
  8. Numbers that appear only once
  9. Sum of Two Numbers
  10. Bubble sort
  11. Is the array ordered
  12. Binary Search
  13. Copy of Array
  14. Array to String

1. Average the array

Implement a method avg that takes an array as a parameter and averages all elements in the array (note the return value type of the method).

public class array {
    //Array-based daily exercises
    public static void main(String[] args) {
        //Averaging arrays
        //Implement a method avg that takes an array as a parameter and averages all elements in the array (note the return value type of the method).
        int[] arr = {1,9,3,5,4};
        System.out.println(arrAvg(arr));
    }
    //Define an array first, traverse the array, find the length of the array, find the element and/or length = mean
    public static int arrSum(int[] arr){
        int ret = 0;
        for (int i = 0; i < arr.length; i++) {
            ret += arr[i];
        }
        return ret;
    }
    public static double arrAvg(int[] arr){
        double ret = 0.0;
        double sum = arrSum(arr);
        ret = sum / arr.length;
        return ret;
    }
}

 

2. Sum of all elements of an array

Implement a method sum that takes an array as a parameter and sums all elements of the array.

public class array {
    public static void main(String[] args) {
        int[] arr = {1,9,3,5,4};
        //2. Sum of all elements of an array
        System.out.println(arrSum(arr));//22
    }
    public static int arrSum(int[] arr){
        int ret = 0;
        for (int i = 0; i < arr.length; i++) {
            ret += arr[i];
        }
        return ret;
    }
}

3. Change the value of the original array element

Implement a method transform that takes an array as a parameter and loops through each element of the array by multiplying it by 2 and setting it on the corresponding array element. For example, the original array is {1, 2, 3} and modified to {2, 4, 6}

public class array {
    public static void main(String[] args) {
//        int[] arr = new int[3];
//        arr[0]=1;
//        arr[1]=2;
//        arr[2]=3
        int[] arr = {1,2,3};//Define an array and initialize it
        int[] ret = transform(arr);
        printArr(arr);
        System.out.println();
        printArr(ret);
    }
    //Print array elements
    private static void printArr(int[] arr){
        for (int i : arr) { //Do not change the elements inside the array
            System.out.print(i + " ");
        }
    }
    public static int[] transform(int[] arr){
        int[] ret = new int[arr.length] ;  //Create a new array equal to the length of the original array without changing the elements of the original array
        for (int i = 0; i < arr.length; i++) {
            ret[i] = arr[i]*2;
        }
        return ret;
    }
}

4. Print Array

Implement a method, printArray, that takes an array as a parameter, iterates through each element in the array, and prints the value of each element.

public class array {
    public static void main(String[] args) {
        int[] arr = {1,9,3,5,4};
        String ret = arrPrint(arr);
        System.out.print(ret);//[1,9,3,5,4]
    }
//    Implement a method, printArray, with arrays as parameters.
//    Loop through each element in the array and print the value of each element.
    public static String arrPrint(int[] arr){
        String ret = "[";
        for (int i = 0; i < arr.length; i++) {
            ret+=arr[i];
            if (i != arr.length-1){ // i < arr.length-1
                ret += ",";
            }
        }
        ret += "]";
        return ret;
    }
}

 

5. Array created with an initial value

Create an array of type int with 100 elements and set each element to 1 - 100 in turn

import java.util.Arrays;

public class array {
    public static void main(String[] args) {
        int[] a=new int[100];
        setNumber(a);
        System.out.println(Arrays.toString(a));
    }
//Create an array of type int with 100 elements and set each element to 1 - 100 in turn
    public static int[] setNumber(int[] arr){
        for (int i = 0; i < 100; i++) {
            arr[i] = i+1;
        }
        return arr;
    }
}

6. Arrays with three consecutive odd numbers

Give you an array of integers, arr, to determine if there are three consecutive elements in the array that are odd numbers: if there are, return true; Otherwise, return false.

Example 1: Input: arr = [2,6,4,1] * Output: false

Explanation: There is no case where three consecutive elements are odd numbers.

Example 2: Input: arr = [1,2,34,3,4,5,7,23,12]. Output: true

Explanation: There is a case where three consecutive elements are odd numbers, that is, [5,7,23].

public class array {
    public static void main(String[] args) {
        int[] a1 = {2,6,4,1};
        numOdd(a1);
        int[] a2 ={1,2,34,3,4,5,7,23,12};
        numOdd(a2);
    }
//6. Give you an array of integers arr. Please tell if there are three elements in the array that are all odd in succession:
// Return true if it exists; Otherwise, return false.
    public static int numOdd(int[] arr){
        int count = 0;
        for (int i = 0; i < arr.length-2; i++) {
            if(arr[i]%2==1 && arr[i+1]%2==1 && arr[i+2]%2==1){
                count++;
            }
        }
        if (count!=0){
            System.out.println(true);
        } else{
            System.out.println(false);
        }
        return count;
    }
}

7. Most Elements

Given an array of size n, find most of the elements. Most elements are elements that occur more than n/2 times in an array. You can assume that the array is not empty and that there is always a majority of elements in the given array.

Example 1: Input: [3,2,3], Output: 3

Example 2: Input: [2,2,1,1,1,2,2]] Output: 2

import java.util.Arrays;

public class array {
    public static void main(String[] args) {
        System.out.print("arr1 Most elements are:");
        int[] arr1 = {3,2,3};
        System.out.print(searchMost(arr1));
        System.out.print("\narr2 Most elements are:");
        int[] arr2 = {2,2,1,1,1,2,2};
        System.out.print(searchMost(arr2));
    }
//Given an array of size n, find most of the elements. Most elements are the number of occurrences in an array
//Elements larger than n/2. You can assume that the array is not empty and that there is always a majority of elements in the given array.
    /**
     * Sort the array so that the middle element must be the majority element
     * The time complexity of the code is O (NlogN)
     * @param arr Integer array
     * @return
     */
    public static int searchMost(int[] arr){
        Arrays.sort(arr);  //Sort Array Elements
        return arr[arr.length/2];
    }
}

8. Numbers that occur only once

Given a non-empty integer array, each element occurs twice, except for one element that occurs only once. Find the element that only appears once.

Example 1: Input: [2,2,1]; Output: 1

Example 2: Input: [4,1,2,1,2] Output: 4

public class array {
    public static void main(String[] args) {
        int[] arr1 = {2,2,1};
        System.out.println(searchOne(arr1));
        int[] arr2 = {4,1,2,1,2};
        System.out.println(searchOne(arr2));
    }
//8. Given a non-empty integer array, each element is
//Occurs twice. Find the element that only appears once.
//XOR operation - any number XOR 0 equals any number  
    public static int searchOne(int[] arr){
        int temp = 0;
        for (int i = 0; i < arr.length; i++) {
            temp^=arr[i];
        }
        return temp;
    }
}

9. Sum of Two Numbers

Given an array of integers nums and an integer scalar target, find the two integers in the array that are the target and return their array subscripts. You can assume that each input corresponds to only one answer. However, the same element in the array cannot be repeated in the answer. You can return the answers in any order.

Example:

Input: nums = [2,7,11,15], target = 9, output: [0,1]

Interpretation: Because nums[0] + nums[1] == 9, returns [0, 1].

public class array {
    public static void main(String[] args) {
        int[] nums = {2,7,11,15};
        searchSum(nums,9);
    }
//9. Given an integer array nums and an integer scalar target, you can find it in the array
// And the two integers for the target value target, and return their array subscripts. You can assume each
// The input corresponds to only one answer. However, the same element in the array cannot be repeated in the answer. You can
// Return the answers in any order.
// target = nums[i] + nums[j]   ->return   i , j

    public static int searchSum(int[] nums, int target){
        for (int i = 0; i < nums.length; i++) {
            for (int j = 1; j < nums.length; j++) {
                if (target == nums[i]+nums[j]){
                    System.out.print("["+i+","+j+"]");//Simple control output format
                }
            }
        }
        return target;
    }
}

10. Bubble sorting

Given an integer array, achieve bubble sort (ascending sort)

public class array {
    public static void main(String[] args) {
//10. Bubble Sort Ascending Sort
//Double cycle
        int[] arr = {1, 8, 5, 0, 3, 7, 4};
//        Number of outer cycle control coils
        for (int i = 0; i < arr.length / 2; i++) {
//  The inner loop controls the two adjacent numbers, swapping the two if the previous number is greater than the latter
//   PS: j Cross Border Issue
            for (int j = 0; j < arr.length - i-1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
        System.out.println("The ascending order is:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");  //0 1 3 4 5 7 8 
        }
    }
}

 

11. Is the array ordered

Given an integer array, determine if the array is ordered (incremental)

public class array {
    public static void main(String[] args) {
        int[] arr1 = {1,2,3,4,5,6,7};
        System.out.println(arryJudge(arr1));
        int[] arr2 = {3,6,2,5,1,4};
        System.out.print(arryJudge(arr2));
    }
//Given an integer array, determine if the array is ordered (incremental)
    public static boolean arryJudge(int[] arr){
        for (int i = 0; i < arr.length-1; i++) {
            if (arr[i] > arr[i+1]){
                return false;
            }
        }
       return true;
    }
}

 

12. Binary Search

Given an ordered integer array, implement binary lookup

public class array {
    public static void main(String[] args) {
        int[] arr = {1,3,5,7,9,11,13,17};
        System.out.println(searchBinary(arr,2));  //-1
        System.out.println(searchBinary(arr,17));  //17
    }

//   12. Binary Search

    /**
     * Ordered integer array for binary lookup
     * @param arr
     * @param target Number to find
     * @return
     */
    public static int searchBinary(int[] arr,int target){
        int left = 0;
        int right = arr.length-1;
        while(left <= right){
            int middle = (left+right)>>1;
            if (target == arr[middle]){
                return arr[middle]; //Returns the value you are looking for
            }else if (target < arr[middle]){
                right = middle-1;
            }else{
                left = middle+1;
            }
        }
        return -1;//not found
    }
}

 

13. Copies of arrays

Implement a method called copyOf, copy an integer array, and get a new array.

import java.util.Arrays;

public class array {
    public static void main(String[] args) {
//    13.
        int[] arr = {3,7,2,4,8};
        int[] newarr = arryCopy(arr);//Call method arryCopy
        System.out.println(Arrays.toString(newarr));//Arrays.toString Converts an Array to String Type Output
    }
//13. Implement a method, copyOf, to copy an integer array and get a new array.
    public static int[] arryCopy(int[] arr) {
        int[] ret = new int[arr.length];//Keep the array size constant
        for (int i = 0; i < arr.length; i++) {
            ret[i] = arr[i];
        }
        return ret;
    }
}

 

14. Array to String

Implement a method, toString, to convert an integer array to a string. For example, the array {1, 2, 3}, returns a string of'[1, 2, 3]', noting the position and number of commas.

public class array {
    public static void main(String[] args) {
        int[] arr = {3,7,2,4,8};
        System.out.println(arrToStr(arr));
    }
// 14. Implement a method, toString, to convert an integer array to a string.
// For example, the array {1, 2, 3}, returns a string of'[1, 2, 3]', noting the position and number of commas.
    public static String arrToStr(int[] arr){
        String ret = "[";
        for (int i = 0; i < arr.length; i++) {
            ret += arr[i];
            if (i<arr.length-1){
                ret += ",";
            }
        }
        ret += "]";
        return ret;
    }
}

 

End of this section ^^

Topics: Java Back-end