Reputation: 107
So I'm trying to repeat an int[] array by the values that are in it.
So basically if you have an array
{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 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. I can't get 2 to out 2,2, Any help will be much appreciated, thank you.
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.
Upvotes: 4
Views: 3276
Reputation: 28528
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++;
}
}
Upvotes: 0
Reputation: 1240
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);
}
Upvotes: 1
Reputation: 53819
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
Upvotes: 1