簡體   English   中英

將兩個數組合並為一個交替元素?

[英]Combine two arrays into the one alternating elements?

我一直在嘗試使用以下算法解決問題,但是它不起作用。

import java.util.Scanner;
import java.lang.Math;

public class AlterConcatenateArrays {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        System.out.println("How many elements do you want the first array have?");
        int N = s.nextInt();
        s.nextLine();
        System.out.println("How many elements do you want the second array have?");
        int M = s.nextInt();
        int[] a = new int[N];
        int[] b = new int[M];
        System.out.println("The elements of the first array are: ");
        for (int i = 0; i < N; i++) {
            a[i] = (int) (Math.random() * 20);
            System.out.print(a[i] + " \n");
        }
        System.out.println("The elements of the second array are: ");
        for (int i = 0; i < M; i++) {
            b[i] = (int) (Math.random() * 20);
            System.out.print(b[i] + " \n");
        }
        System.out.println("Now we are going to concatenate the arrays by alternatingly choosing");
        int[] c = new int[N + M];
        for (int i = 0; i < ((N + M) / 2); i++) {
            a[i] = c[2 * i + 0];
            b[i] = c[2 * i + 1];
        }
        System.out.println("The new array is: ");
        for (int i = 0; i < N + M; i++) {
            System.out.print(c[i] + "\t");
        }
    }
}

該程序的輸出是這樣的:

How many elements do you want the first array have?
2
How many elements do you want the second array have?
3
The elements of the first array are: 
17 
18 
The elements of the second array are: 
6 
14 
15 
Now we are going to concatenate the arrays by alternatingly choosing
The new array is: 
0   0   0   0   0   

您已在此處交換了作業。

{
    a[i] = c[2*i+0];
    b[i] = c[2*i+1];
}

應該從ab分配給c

{
    c[2*i+0] = a[i];
    c[2*i+1] = b[i];
}

記住L值和R值之間的差異。 在編程中始終很重要

a[i] = c[2*i+0];
b[i] = c[2*i+1];

這是錯的

你好
c數組隱式初始化為零。 我想在for循環中,您要填充c數組,而不是a和b。

//程序合並兩個長度相同或不同的數組的替換元素

public class MergeAlternateElements {
public static void mergeAlternateElements(int[] a, int[] b) {
    int n = a.length, m = b.length;
    int mergedArray[] = new int[n + m];
    int p = 0;
    int i = 0;
    for (i = 0; i < n; i++) {
        mergedArray[p] = a[i];
        p++;
        if (i < m) {
            mergedArray[p] = b[i];
            p++;
        }
    }
    if (n < m) {
        System.arraycopy(b, i, mergedArray, p, m - n);
    }
    System.out.println("Merged Array:");
    for (int k : mergedArray)
        System.out.print(k + " ");

}

public static void main(String[] args) {
    int[] a = { 24, 2, 45, 20, 56, 75, 21, 56, 99, 53 };
    int b[] = { 112, 234, 500, 123, 432, 567, 787, 909, 808, 600, 678, 900};
    mergeAlternateElements(b, a);
    System.out.println();
    mergeAlternateElements(a, b);
 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM