Repeating array

So, I'm trying to repeat the int [] array with the values โ€‹โ€‹that are in it. So basically, if you have an array of {1,2,3,4} your output will be

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

or if you get

 {0,1,2,3} 

your result

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

I know for sure that there should be two loops here, but I canโ€™t understand the code so that it copies the value in the array. I can not get 2 to 2.2, Any help would be greatly appreciated, thanks.

edit the code here that 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 this would work, but it will just return the same list, or someday, if I change it around badly, just get 4 in a new array.

+4
source share
3 answers

This will dynamically build a new array of the correct size and then fill 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); } 
+1
source

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 
+1
source

Try the following:

 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++; } } 
0
source

Source: https://habr.com/ru/post/1446688/


All Articles