簡體   English   中英

重復數組

[英]Repeating array

因此,我試圖通過其中的值重復一個int []數組。 因此,基本上,如果您有一個數組{1,2,3,4}輸出將為

{1,2,2,3,3,3,4,4,4,4}

或者如果你得到

{0,1,2,3}

你的輸出是

{1,2,2,3,3,3}.

我知道這里肯定有兩個for循環,但是我似乎無法弄清楚使它復制數組中值的代碼。 我無法得到2淘汰2,2,任何幫助將不勝感激,謝謝。

在這里編輯我認為可行的代碼

public static int[] repeat(int []in){
    int[] newarray = new int[100];

    for(int i = 0; i<=in.length-1;i++){

        for(int k= in[i]-1;k<=in[i];k++){

            newarray[i] = in[i];   

        }
    }
    return newarray;
}

我以為這會行得通,但是它只會返回相同的列表,或者如果我將其更改為某個時間,則只需在新數組中獲取4。

嘗試:

LinkedList<Integer> resList = new LinkedList<Integer>();
for(int i = 0 ; i < myArray.length ;  ++i) {
    int myInt = myArray[i];
    for(int j = 0 ; j < myInt ; ++j) { // insert it myInt-times
        resList.add(myInt);
    }
}
// TODO: build the result as an array : convert the List into an array

這將動態構建正確大小的新數組,然后進行填充。

    int[] base = { 1, 2, 3, 4 };
    int size = 0;
    for( int count : base ){
        size += count;
    }

    int[] product = new int[size];

    int index = 0;
    for( int value : base ){
        for(int i = 0; i < value; i++){
            product[index] = value;
            index++;
        }
    }

    for( int value : product ){
        System.out.println(mine);
    }

嘗試這個:

int[] anArray = { 
    0, 1, 2
};
int[] newArray = new int[100];
int cnt=0;
for(int i=0; i<anArray.length; i++)
{
    for(j=1;j>0;j--)
    {
        newArray[cnt]=anArray[i];
        cnt++;
    }
}

暫無
暫無

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

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