數組(Array)習題總結

學了關於數組的知識點,這次我們一起來看一些關於數組的編程題!

思路分析:這道題有兩種思路,所以提供兩種解法。思路一就是func1(),思路二是func2()。

思路一:題目當中讀取的整數的個數不確定,即數組的長度不固定,所以我們需要每讀取一個數據,然後進行數組擴容,再填入數據,數據填入之後再進行排序,最後遍歷數組依次判斷數據的個數。

第一步:獲取用戶輸入的數據,動態的擴容數組填充數據;

第二步:按照輸出結果,將數據中的數據進行排序;

第三步:輸出連續相等的數字;

第四步:編寫代碼。

思路二:藉助計數排序的思想,將數組固定起來,然後進行操作。具體來看代碼:

import java.util.*;
class Demo05_01{
    public static void main(String[] args){
        /*
        思路1:數組長度不固定,需要讀取一個數據,數組擴容,填入數據
        數據填入之後進行排序,然後遍歷數組依次判斷數據的個數
        連續相等
        2 2 2 2 3 3 4 4 4 4 5 5 6 6 6 6 7 7
        思路2:藉助計數排序的思想,將數組固定起來。
        */
        //func1();
        func2();
    }
    public static void func2(){
        //arr[i] 就表示數字i出現的次數
        int[] arr = new int[101];
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the integers between 1 and 100:");
        while(true){
            int num = scanner.nextInt();
            if(num == 0){
                break;
            }
            arr[num]++;
        }
        for(int i = 0;i < arr.length;i++){
            if(arr[i] != 0){
                System.out.println(i + " occurs " + arr[i] + (arr[i] > 1?" times":" time"));
            }
        }
    }
    public static void func1(){
        //1.獲取用戶輸入的數據 動態的擴容數組填充數據
        int[] arr = new int[0];
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the integers between 1 and 100:");
        int num = 0;
        while(true){
            num = scanner.nextInt();
            if(num == 0){
                break;
            }
            //驗證用戶輸入數據的正確性
            if(num < 1 || num > 100){
                System.out.println("有非法數據!");
                return;
            }
            arr = copyOf(arr,arr.length + 1);
            arr[arr.length - 1] = num;
        }
        //2.按照輸出結果,將數據中的數據進行排序
        insertSort(arr);
        //3.輸出連續相等的數字
        show(arr);
    }
    public static int[] copyOf(int[] arr,int newLen){
        int[] newArr = new int[newLen];
        for(int i = 0;i < arr.length;i++){
            newArr[i] = arr[i];
        }
        return newArr;
    }
    public static void insertSort(int[] arr){
        for(int i = 1;i < arr.length;i++){
            int e = arr[i];
            int j;
            for(j = i;j > 0 && arr[j - 1] > e;j--){
                arr[j] = arr[j - 1];
            }
            arr[j] = e;
        }
    }
    /*
    Arrays Math都是屬於工具類
    Arrays 特殊的是數組的工具類
        toString(arr) 就是將數據的每個元素進行拼接 並返回拼接後的字符串數據
        "[1,2,3,4]"
    */
    public static void show(int[] arr){
        //System.out.println(Arrays.toString(arr));
        //此時就將問題轉成了如何判斷連續相等的數據分別出現多少次
        //[1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5, 6]
        for(int i = 0;i < arr.length;){
            int count = 1;
            for(int j = i + 1;j < arr.length;j++){
                if(arr[j] == arr[i]){
                    count++;
                }else{
                    break;
                }
            }
            System.out.println(arr[i] + " occurs "  + count + (count>1?" times":" time"));
            i+=count;
        }
    }
}

運行結果:

Enter the integers between 1 and 100:2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time

 

思路分析:這道題也有兩個思路,所以提供兩種解法。思路一就是func1(),思路二是func2()。

思路一:在10個數全部輸入之後再去重複;

第一步:循環遍歷數組進行賦值;

第二步:開始對已有的數據進行去重複操作,這一步又提供了三種方法,method1、method2、method3;

第三步:編寫代碼。

思路二:邊輸入邊去重複。具體來看代碼:

import java.util.*;
class Demo05_02{
    public static void main(String[] args){
        /*
        思路1
            在全部輸入之後去重複 func1
        思路2
            邊輸入邊去重複 func2
        */
        //func1();
        func2();
    }
    public static void func2(){
        int[] arr = new int[0];
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter ten numbers:");
        for(int i = 0;i < 10;i++){
            int num = scanner.nextInt();
            if(!contains(arr,num)){
                arr = copyOf(arr,arr.length + 1);
                arr[arr.length-1] = num;
            }
        }
        System.out.println("The number of distinct number is: " + arr.length);
        System.out.println("The distinct numbers are: " + Arrays.toString(arr));
    }
    public static void func1(){
        //1.循環遍歷數組進行賦值
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter ten numbers:");
        int[] arr = new int[10];
        for(int i = 0;i < arr.length;i++){
            arr[i] = scanner.nextInt();
        }
        //2.開始對已有的數據進行去重複操作
        // 1 2 3 3 2 4 3 2 4 1
        // 1 2 3 4
        // method1(arr);        //空間S(n) 時間O(nm)
        // method2(arr);        //空間S(1) 時間O(n^2)
        // method3(arr);
    }
    public static void method3(int[] arr){
        //不創建額外空間 不許改變原先的順序
        int i = 0;
        int size = arr.length;
        while(i < size){
            for(int j = i + 1;j < size;){
                if(arr[j] == arr[i]){
                    for(int k = j + 1;k < size;k++){
                        arr[k - 1] = arr[k];
                    }
                    size--;
                }else{
                    j++;
                }
            }
            i++;
        }
        for(i = 0;i < size;i++){
            System.out.print(arr[i] + " ");
        }
    }
    public static void method2(int[] arr){
        //插入排序
        for(int i = 1;i < arr.length;i++){
            int e = arr[i];
            int j;
            for(j = i;j > 0 && arr[j - 1] > e;j--){
                arr[j] = arr[j - 1];
            }
            arr[j] = e;
        }
        //連續相等
        for(int i = 0;i < arr.length;){ //O(n)
            System.out.print(arr[i] + " ");
            int count = 1;
            for(int j = i + 1;j < arr.length;j++){
                if(arr[j] == arr[i]){
                    count++;
                }else{
                    break;
                }
            }
            i+=count;
        }
    }
    public static void method1(int[] arr){
        int[] newArr = new int[0];
        for(int i = 0;i < arr.length;i++){ //O(n)
            if(!contains(newArr,arr[i])){ //O(m)
                newArr = copyOf(newArr,newArr.length + 1);
                newArr[newArr.length - 1] = arr[i];
            }
        }
        System.out.println(Arrays.toString(newArr));
    }
    public static boolean contains(int[] arr,int key){
        for(int i = 0;i < arr.length;i++){
            if(arr[i] == key){
                return true;
            }
        }
        return false;
    }
    public static int[] copyOf(int[] arr,int newLen){
        int[] newArr = new int[newLen];
        for(int i = 0;i < arr.length;i++){
            newArr[i] = arr[i];
        }
        return newArr;
    }
}

運行結果:

Enter ten numbers:1 2 3 2 1 6 3 4 5 2
The number of distinct number is: 6
The distinct numbers are: [1, 2, 3, 6, 4, 5]

 

思路分析:這道題是讓我們判斷一個數組是不是升序序列,很簡單,來看步驟。

第一步:獲取用戶的輸入,第一個輸入的數據是數據的個數(數組的長度);

第二步:對數組進行有序的判斷;

第三步:編寫代碼。

import java.util.*;
class Demo05_03{
    public static void main(String[] args){
        //1.獲取用戶的輸入,第一個輸入的數據是數據的個數(數組的長度)
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a list:");
        int len = scanner.nextInt();//獲取的第一個數值就是數組的長度
        int[] arr = new int[len];
        for(int i = 0;i < arr.length;i++){
            arr[i] = scanner.nextInt();
        }
        //2.對數組進行有序的判斷
        if(isSorted(arr)){
            System.out.println("The list is already sorted.");
        }else{
            System.out.println("The list is not sorted.");
        }
    }
    public static boolean isSorted(int[] list){
        //如果不是升序排列 那麼勢必會出現有一組數據 左大右小的情況
        for(int i = 1;i < list.length;i++){
            if(list[i - 1] > list[i]){
                return false;
            }
        }
        return true;
    }
}

運行結果:

Enter a list:8 10 1 5 16 61 9 11 1
The list is not sorted.
Enter a list:10 1 1 3 4 4 5 7 9 11 21 
The list is already sorted.

 

思路分析:這道題看起來挺複雜的,但是隻要我們弄清楚題目到底要我們做什麼,題目有什麼數據,然後按照要求做就行了。

第一步:提示用戶輸入槽子的個數和小球的個數;

第二步:根據已有的槽子的個數去創建槽子容器;

第三步:根據已有的球和槽子的個數去隨機創建一個小球下落的路徑;

第四步:思考路徑中經過幾個釘子?路徑的步驟有幾步?這都和和槽子的個數有關;

第五步:思考如何通過路徑的經過得知最終所落入的槽子;

第六步:編寫代碼。

import java.util.*;
class Demo05_04{
    /*
    輸入的數據:槽子的個數 球的個數=路徑的個數
               創建槽子的具體的容器int[]
               每一個小球下落的路徑L R 字符串
               對於每一個小球而言其路徑中的步驟是隨機產生L R
    1.提示用戶輸入槽子的個數和小球的個數
    2.根據已有的槽子的個數去創建槽子容器
    3.根據已有的球和槽子的個數去隨機創建一個小球下落的路徑
    4.路徑中經過幾個釘子?路徑的步驟有幾步 和槽子的個數有關
    5.如何通過路徑的經過得知最終所落入的槽子?
    */
    public static void main(String[] args){
        //1.獲取球的個數和路徑槽子的個數
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of balls to drop:");
        int balls = scanner.nextInt();
        System.out.print("Enter the number of slots in the bean machine:");
        int slots = scanner.nextInt();
        //2.創建槽子具體的容器
        int[] arr = new int[slots];
        //3.幾個球幾個路徑path
        for(int i = 0;i < balls;i++){
            String path = getPath(slots);
            System.out.println(path);
            //5.只要看當前路徑中R的個數即可
            arr[getR(path)]++;
        }
        //6.輸出
        System.out.println(Arrays.toString(arr));
        show(arr);
    }
    public static void show(int[] arr){
        int w = arr.length;
        int h = 0;
        for(int i = 0;i < arr.length;i++){
            if(arr[i] > h){
                h = arr[i];
            }
        }
        for(int i = h - 1;i >= 0;i--){
            for(int j = 0;j < w;j++){
                if(i < arr[j]){
                    System.out.print("O");
                }else{
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
    public static int getR(String path){
        int count = 0;
        for(int i = 0;i < path.length();i++){
            if(path.charAt(i) == 'R'){
                count++;
            }
        }
        return count;
    }
    public static String getPath(int slots){
        //4.根據槽子的個數計算每一個球下落的路徑
        Random random = new Random();
        String path = "";
        for(int j = 0;j < slots - 1;j++){
            if(random.nextInt(2) == 0){   //向左
                path+="L";
            }else{  //向右
                path+="R";
            }
        }
        return path;
    }
}

運行結果:

LRLRRLR
LLLLLRL
LRLRRLL
LRRLRLL
RRLLLRR
[0, 1, 0, 2, 2, 0, 0, 0]
   OO
 O OO

 

 

思路分析:這道題是讓我們判斷兩個數組是否完全相同,具體來看步驟。

第一步:提示用戶輸入第一個數組list1,第二個數組list2,然後獲取數值;

第二步:判斷兩個數組的長度是否相等;

第三步:緊接着再依次判斷元素大小;

第四步:編寫代碼。

import java.util.*;
class Demo05_05{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        //第一個數組list1
        System.out.print("Enter list1:");
        int len1 = scanner.nextInt();
        int[] list1=new int[len1];
        for(int i=0;i<list1.length;i++){
            list1[i]=scanner.nextInt();
        }
        //第二個數組list2
        System.out.print("Enter list2:");
        int len2 = scanner.nextInt();
        int[] list2=new int[len2];
        for(int j=0;j<list2.length;j++){
            list2[j]=scanner.nextInt();
        }
        equals(list1,list2);
    }
    public static void equals(int[] list1,int[] list2){
        //判斷兩個數組是否完全相同
        //1.先判斷長度
        if(list1.length!=list2.length){
            System.out.println("Two lists are not strictly identical");
            return;
        }
        //2.再依次判斷元素大小
        for(int i=0;i<list1.length;i++){
            if(list1[i]!=list2[i]){
                System.out.println("Two lists are not strictly identical");
                return;
            }
        }
        System.out.println("Two lists are strictly identical");
    }
}

運行結果:

Enter list1:5 2 5 6 1 6
Enter list2:5 2 5 6 1 6
Two lists are strictly identical
Enter list1:5 2 5 6 1 6
Enter list2:5 2 5 6 6 1
Two lists are not strictly identical

 

 

思路分析:這道題是讓用戶輸入一個整數列表,然後讓我們判斷這個列表當中是否有四個連續的具有相同值的數,然後返回true或false,這道題很簡單,來看步驟:

第一步:提示用戶輸入列表中數字的總數和具體的數字;

第二步:判斷列表中是否含有四個連續相等的數;

第三步:編寫代碼。

import java.util.*;
class Demo05_06{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        //1.提示用戶輸入列表中數字的總數和具體的數字
        System.out.print("Enter the number of values:");
        int num = scanner.nextInt();
        System.out.print("Enter the values:");
        int[] arr = new int[num];
        for(int i = 0;i < num;i++){
            arr[i] = scanner.nextInt();
        }
        //2.判斷列表中是否含有四個連續相等的數
        if(isConsecutiveFour(arr) == true){
            System.out.println("The list has consecutive fours");
        }else{
            System.out.println("The list has no consecutive fours");
        }
    }
    public static boolean isConsecutiveFour(int[] arr){
        for(int i = 0;i < arr.length;){
            int count = 1;
            for(int j = i + 1;j < arr.length;j++){
                if(arr[i] == arr[j]){
                    count++;
                }else{
                    break;
                }
            }
            if(count >= 4){
                return true;//列表中含有四個連續相等的數
            }
            i+=count;
        }
        return false;////列表中不含有四個連續相等的數
    }
}

運行結果:

Enter the number of values:8
Enter the values:3 4 5 5 5 5 4 5
The list has consecutive fours
Enter the number of values:9
Enter the values:3 4 5 5 6 5 5 4 5
The list has no consecutive fours

 

思路分析:這道題是讓用戶輸入兩個有序列表,然後讓我們將這兩個有序列表合併成一個有序列表,來看步驟:

第一步:提示用戶輸入第一個數組list1,第二個數組list2,然後獲取數值;

第二步:先判斷列表是否有空列表;

第三步:兩個都不是null,再考慮具體操作;

第四步:編寫代碼。

import java.util.*;
class Demo05_07{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        //第一個數組list1
        System.out.print("Enter list1:");
        int len1 = scanner.nextInt();
        int[] list1 = new int[len1];
        for(int i = 0;i < list1.length;i++){
            list1[i] = scanner.nextInt();
        }
        //第二個數組list2
        System.out.print("Enter list2:");
        int len2 = scanner.nextInt();
        int[] list2 = new int[len2];
        for(int j = 0;j < list2.length;j++){
            list2[j] = scanner.nextInt();
        }
        System.out.println("The merged list is " + Arrays.toString(merge(list1,list2)));
    }
    /*
    有序數組的合併
    最主要的問題在於 數組之間有長有短
    */
    public static int[] merge(int[] list1,int[] list2){
        if(list1 == null && list2 == null){
            return null;
        }
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        //只有兩個都不是null,再考慮具體操作
        int[] list3 = new int[list1.length + list2.length];
        int p1 = 0;
        int p2 = 0;
        int p3 = 0;
        while(true){
            if(p1 == list1.length && p2 == list2.length){
                break;
            }
            if(p1 < list1.length && p2 == list2.length){
                list3[p3++] = list1[p1++];
            }else if(p1 == list1.length && p2 < list2.length){
                list3[p3++] = list2[p2++];
            }else{
                if(list1[p1] <= list2[p2]){
                    list3[p3++] = list1[p1++];
                }else{
                    list3[p3++] = list2[p2++];
                }
            }
        }
        return list3;
    }
}

運行結果:

Enter list1:5 1 5 16 61 111
Enter list2:4 2 4 5 6
The merged list is [1, 2, 4, 5, 5, 6, 16, 61, 111]

 

思路分析,這道題很有意思,也有一定的難度,考慮的比較多,我們來看步驟:

第一步:創建一個單詞表;

第二步:隨機從單詞表中抽取一個單詞;

第三步:創建一個該單詞的狀態表 默認值是false(密文);

第四步:開始猜一個單詞,根據單詞和狀態表決定密文形式;

第五步:輸出密文並提示用戶輸入字母;

第六步:判斷單詞中是否有該字母;

第七步:改變單詞狀態表,看是否結束;

第八步:最後再去做多單詞猜測;

第九步:編寫代碼。

import java.util.*;
class Demo05_08{
    /*
    數據 一組單詞的明文  單詞的密文  單詞的狀態
    program
    1000000 r r
    pr**r**
    */
    public static void main(String[] args){
        Scanner scanner=new Scanner(System.in);
        Random random=new Random();
        //1.創建一個單詞表
        String[] words={"apple","banana","orange","watermelon","java","program"};
        //10.最後再去做多單詞猜測
        while(true){
            //2.隨機從單詞表中抽取一個單詞
            String word=words[random.nextInt(words.length)];
            //3.創建一個該單詞的狀態表 默認值是false(密文)
            boolean[] status=new boolean[word.length()];
            int miss=0; //猜錯的個數
            //4.開始猜一個單詞
            while(true){
                //5.根據單詞和狀態表 決定密文形式
                String ciphertext=getCipherText(word,status);
                //6.輸出密文並提示用戶輸入字母
                System.out.print("Enter a letter in word "+ciphertext+" >");
                char letter=scanner.nextLine().charAt(0);//"p".charAt(0)
                //7.判斷單詞中是否有該字母
                if(isContainsLetter(word,letter)){
                    //8.改變單詞狀態表 已修改/未修改 
                    //true 表示從未修改 第一次來的
                    //false 表示已修改  不是第一次來 提示已經存在
                    if(!changeWordStatus(word,status,letter)){
                        System.out.println("\t "+letter+" is already in the word");
                    }
                }else{
                    System.out.println("\t "+letter+" is not in the word");
                    miss++;
                }
                //9.是否結束
                if(isFinish(status)){
                    System.out.println("The word is "+word+". You miss "+miss+" time");
                    break;
                }
            }
            System.out.print("Do you want to guess another word?Enter y or n:");
            String choice=scanner.nextLine();
            if(choice.equals("n")){
                System.out.println("Welcome!Thank you! FUCK PROGRAM!");
                break;
            }
        }
    }
    public static boolean isFinish(boolean[] status){
        for(int i=0;i<status.length;i++){
            if(!status[i]){
                return false;
            }
        }
        return true;
    }
    public static boolean changeWordStatus(String word,boolean[] status,char letter){
        for(int i=0;i<word.length();i++){
            if(word.charAt(i)==letter){
                if(status[i]){
                    return false;   //說明已經修改
                }else{
                    status[i]=true;
                }
            }
        }
        return true;
    }
    public static boolean isContainsLetter(String word,char letter){
        for(int i=0;i<word.length();i++){
            if(word.charAt(i)==letter){
                return true;
            }
        }
        return false;
    }
    public static String getCipherText(String word,boolean[] status){
        String ciphertext="";
        for(int i=0;i<status.length;i++){
            if(status[i]){
                ciphertext+=word.charAt(i);
            }else{
                ciphertext+="*";
            }
        }
        return ciphertext;
    }
}

運行結果:

Enter a letter in word ***** >a
Enter a letter in word a**** >p
Enter a letter in word app** >l
Enter a letter in word appl* >e
The word is apple. You miss 0 time

 

思路分析:這道題是讓我們求二維數組中特定列的所有元素之和,我們只需要記住一個原則:累加行的時候,行不動列動,累加列的時候,列不動行動。

第一步:提示用戶輸入一個3*4的矩陣;

第二步:打印每列的和;

第三步:編寫代碼。

import java.util.*;
class Demo05_09{
    public static void main(String[] args){
        /*
            (0,0) (0,1) (0,2) (0,3)
            (1,0) (1,1) (1,2) (1,3)
            (2,0) (2,1) (2,2) (2,3)
            累加行的時候 行不動 列動
            累加列的時候 列不動 行動
        */
        //1.輸入一個3*4的矩陣
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a 3-by-4 matrix row by row:");
        double[][] matrix = new double[3][4];
        //System.out.println(matrix.length);
        for(int i = 0;i < matrix.length;i++){
            for(int j = 0;j < matrix[i].length;j++){
                matrix[i][j] = scanner.nextDouble();
            }
        }
        //2.打印每列的和
        for(int col = 0;col < matrix[0].length;col++){
            System.out.println("Sum of the elements at column " + col + " is " + sumColumn(matrix,col));
        }
    }
    public static double sumColumn(double[][] m,int columnIndex){
        double sum = 0;
        for(int row = 0;row < m.length;row++){
            sum+=m[row][columnIndex];
        }
        return sum;
    }
}

運行結果:

Enter a 3-by-4 matrix row by row:
1.5 2 3 4
5.5 6 7 8
9.5 1 3 1
Sum of the elements at column 0 is 16.5
Sum of the elements at column 1 is 9.0
Sum of the elements at column 2 is 13.0
Sum of the elements at column 3 is 13.0

 

思路分析:這道題其實和上一道題有相似之處,只不過這一道題是讓我們求對角線的所有元素之和。

第一步:提示用戶輸入一個4*4的矩陣;

第二步:計算對角線之和,這裏我把剛開始用的方法註釋掉了,因爲比較耗費內存。又寫了另一種方法;

第三步:編寫代碼。

import java.util.*;
class Demo05_10{
    public static void main(String[] args){
        //1.輸入一個4*4的矩陣
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a 4-by-4 matrix row by row:");
        double[][] m = new double[4][4];
        //System.out.println(m.length);
        for(int i = 0;i < m.length;i++){
            for(int j = 0;j < m[i].length;j++){
                m[i][j] = scanner.nextDouble();
            }
        }
        System.out.println("Sum of the elements in the major diagonal is " + sumMajorDiagonal(m));
    }
    //2.求對角線之和
    public static double sumMajorDiagonal(double[][] m){  
        //①主對角線
        double sum = 0;
        for(int i = 0;i < m.length;i++){
            sum+=m[i][i];
        }
        return sum;

        /*②副對角線
        int subsum = 0;
        for(int i = 0;i < m.length;i++){
            subsum+=m[i][m.length - 1 - i];
        }
        System.out.println(subsum);
        */

        /*我們首先能想到的就是這種方法,但是此方法不是很好,需要遍歷數組中每一個元素,有點"大材小用"。
        for(int i = 0;i < m.length;i++){
            for(int j = 0;j < m[i].length;j++){
                if(i==j){
                    sum+=m[i][j];
                }
            }
        }
        */
    }
}

運行結果:

Enter a 4-by-4 matrix row by row:
1 2 3 4.0
5 6.5 7 8
9 10 11 12
13 14 15 16
Sum of the elements in the major diagonal is 34.5

 

 

思路分析:像這種數學上的一些運算,如果直接通過看,計算流程還是比較麻煩的,這個時候推薦使用已知公式計算!步驟還是跟上面題目步驟一樣,我們直接來看代碼。

 

import java.util.*;
class Demo05_11{
    public static void main(String[] args){
        //m*n n*p m*p 矩陣相乘 前者的列 必須等於 後者的行
        /*
        1 2 3        1 2    1*1+2*3+3*5   1*2+2*4+3*6
                ×    3 4  = 
        4 5 6        5 6    4*1+5*3+6*5   4*2+5*4+6*6
        對於數學上的一些運算公式 如果直接通過看計算流程還是比較麻煩的
        此時推薦使用已知公式計算!
        */
        //1.提示用戶輸入兩個3*3的矩陣
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter matrix1:");
        double[][] a = new double[3][3];
        for(int i = 0;i < a.length;i++){
            for(int j = 0;j < a[i].length;j++){
                a[i][j] = scanner.nextDouble();
            }
        }
        System.out.print("Enter matrix2:");
        double[][] b = new double[3][3];
        for(int i = 0;i < b.length;i++){
            for(int j = 0;j < b[i].length;j++){
                b[i][j] = scanner.nextDouble();
            }
        }
        multiplyMatrix(a,b);
    }
    //2.計算它們的乘積
    public static void multiplyMatrix(double[][] a,double[][] b){
        double[][] c = new double[a.length][b[0].length];//m*n
        for(int i = 0;i < c.length;i++){
            for(int j = 0;j < c[i].length;j++){
                double sum = 0;
                for(int k = 0;k < b.length;k++){
                    sum+=a[i][k] * b[k][j];
                }
                //c[i][j] = sum;
                System.out.printf("%.2f ",sum);
            }
            System.out.println();
        }
    }
}

運行結果:
 

Enter matrix1:1 2 3 4 5 6 7 8 9
Enter matrix2:0 2 4 1 4.5 2.2 1.1 4.3 5.2
5.30 23.90 24.00
11.60 56.30 58.20
17.90 88.70 92.40

 

思路分析:這道題是讓用戶輸入一個方陣的長度,隨機的在矩陣中填入0和1,然後讓我們找出整行、整列或者對角線都是0或1的行、列和對角線,很簡單,來看步驟。

第一步:輸入方針的尺寸 創建方陣;

第二步:隨機的給方陣中填入0或1;

第三步:讓行,列,對角線累加,累加爲0說明都是0,累加爲size說明都是1,即都相等;

第四步:編寫代碼。

import java.util.*;
class Demo05_12{
    public static void main(String[] args){
        //1.輸入方針的尺寸 創建方陣
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the size for the matrix:");
        int size = scanner.nextInt();
        int[][] m = new int[size][size];
        //2.隨機的給方陣中填入0或1
        Random random = new Random();
        for(int i = 0;i < size;i++){
            for(int j = 0;j < size;j++){
                m[i][j] = random.nextInt(2);
                System.out.print(m[i][j]+" ");
            }
            System.out.println();
        }
        //3.讓行,列,對角線累加,累加爲0說明都是0,累加爲size說明都是1,即都相等 sum==0 sum==size
        checkRow(m);
        checkCol(m);
        checkMajorDiagonal(m);
        checkSubDiagonal(m);
    }
    public static void checkSubDiagonal(int[][] m){
        int sum = 0;
        for(int i = 0;i < m.length;i++){
            sum+=m[i][m.length - 1 - i];
        }
        if(sum==m.length || sum==0){
            System.out.printf("副主對角線全相等且是%d\n",sum==0?0:1);
        }else{
            System.out.println("No same numbers on the sub-diagonal");
        }
    }
    public static void checkMajorDiagonal(int[][] m){
        int sum = 0;
        for(int i = 0;i < m.length;i++){
            sum+=m[i][i];
        }
        if(sum==m.length || sum==0){
            System.out.printf("主對角線全相等且是%d\n",sum==0?0:1);
        }else{
            System.out.println("No same numbers on the major diagonal");
            return;
        }
    }
    public static void checkRow(int[][] m){
        for(int i = 0;i < m.length;i++){
            int sum = 0;
            for(int j = 0;j < m[i].length;j++){
                sum+=m[i][j];
            }
            if(sum==m.length || sum==0){
                System.out.printf("第%d行全相等且是%d\n",i + 1,sum==0?0:1);
                return;
            }
        }
        System.out.println("No same numbers on a row");
    }
    public static void checkCol(int[][] m){
        for(int j = 0;j < m.length;j++){
            int sum = 0;
            for(int i = 0;i < m.length;i++){
                sum+=m[i][j];
            }
            if(sum==m.length || sum==0){
                System.out.printf("第%d列全相等且是%d\n",j + 1,sum==0?0:1);
                return;
            }
        }
        System.out.println("No same numbers on a column");
    }
}

運行結果:

Enter the size for the matrix:5
0 0 0 0 0
0 0 0 1 0
1 1 1 0 1
0 0 1 0 1
0 1 1 0 0
第1行全相等且是0
No same numbers on a column
No same numbers on the major diagonal
No same numbers on the sub-diagonal

 

 

思路分析:這道題其實是上面那道題的進階版,難度提升了一點。創建完二維數組之後,我們需要看右邊、下邊、右下和右上四種情況,具體來看:

import java.util.*;
class Demo05_13{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter row and col:");
        int row = scanner.nextInt();
        int col = scanner.nextInt();
        int[][] m = new int[row][col];
        System.out.println("請輸入數組中的數字:");
        for(int i = 0;i < row;i++){
            for(int j = 0;j < col;j++){
                m[i][j] = scanner.nextInt();
            }
        }
        System.out.println(isConsecutiveFour(m));
    }
    public static boolean isConsecutiveFour(int[][] m){
        for(int i = 0;i < m.length;i++){
            for(int j = 0;j < m[i].length;j++){
                //向右
                if(j<=m[i].length - 4){
                    boolean flag = true;
                    for(int c = j + 1;c<=j+3;c++){
                        if(m[i][j] != m[i][c]){
                            flag = false;
                            break;
                        }
                    }
                    if(flag){
                        return true;
                    }
                }
                //向下
                if(i<=m.length - 4){
                    boolean flag = true;
                    for(int r = i + 1;r<=i + 3;r++){
                        if(m[i][j]!=m[r][j]){
                            flag = false;
                            break;
                        }
                    }
                    if(flag){
                        return true;
                    }
                }
                //向右下
                if(i<=m.length-4 && j<=m[i].length-4){
                    boolean flag = true;
                    for(int r = i + 1,c = j + 1;r<=i + 3;r++,c++){
                        if(m[i][j] != m[r][c]){
                            flag = false;
                            break;
                        }
                    }
                    if(flag){
                        return true;
                    }
                }
                //向右上
                if(i>=3 && j<=m[i].length-4){
                    boolean flag = true;
                    for(int r = i - 1,c = j + 1 ;c<=j + 3;r--,c++){
                        if(m[i][j] != m[r][c]){
                            flag = false;
                            break;
                        }
                    }
                    if(flag){
                        return true;
                    }
                }
            }
        }
        return false;//四個方向都沒有連續的
    }
}

 運行結果:

Enter row and col:5 5
請輸入數組中的數字:
1 2 3 4 5
2 1 5 4 3
3 2 1 5 4
2 5 4 1 3
8 5 6 1 2
true

 

好了,關於數組的練習題我們就說到這裏,拜拜!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章