简体   繁体   English

重复数组

[英]Repeating array

So I'm trying to repeat an int[] array by the values that are in it. 因此,我试图通过其中的值重复一个int []数组。 So basically if you have an array {1,2,3,4} your output will be 因此,基本上,如果您有一个数组{1,2,3,4}输出将为

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

or if you get 或者如果你得到

{0,1,2,3}

your output is 你的输出是

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

I know for sure there has to be two for loops in here but I can't seem to figure out the code to make it copy the value in the array. 我知道这里肯定有两个for循环,但是我似乎无法弄清楚使它复制数组中值的代码。 I can't get 2 to out 2,2, Any help will be much appreciated, thank you. 我无法得到2淘汰2,2,任何帮助将不胜感激,谢谢。

edit here the code I thought would work 在这里编辑我认为可行的代码

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;
}

I thought that this would work but it just returns the same list, or sometime if I change it around ill just get 4 in the new array. 我以为这会行得通,但是它只会返回相同的列表,或者如果我将其更改为某个时间,则只需在新数组中获取4。

Try: 尝试:

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

This will dynamically build a new array of the correct size and then populate it. 这将动态构建正确大小的新数组,然后进行填充。

    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);
    }

Try this: 尝试这个:

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