We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › translating content of an array
Page Index Toggle Pages: 1
translating content of an array (Read 426 times)
translating content of an array
Aug 14th, 2009, 6:22am
 
Good morning, i have an array with values, for example [2, 4, 6, 3] , i need to insert a new value to my array each time i call a function , everytime i insert a new value i need to translate my existing value and then add the new value at the end of the array , for example if my new value is 9 then my array is gonna be: [4,6,3,9] and then if i add 1  then my array is going to be [6,3,9,1], ive made a code that works fine, i just want to know if the way i made it is fine or maybe there is a better way of doing it in terms of cpu consumption and clarity, any ideas?

here is the code i made:


Code:


float[] corre = new float[5];

float[] nuevo_corre = new float[5];


void setup(){
size(200, 200);
for(int i=0 ; i<4 ; i++){
corre[i]= i;
nuevo_corre[i] = corre[i];
print(" corre " + corre[i]);
print(" nuevo_corre " + nuevo_corre[i]);
}
}


void draw(){
if(keyPressed) {
for(int i=0 ; i<4 ; i++){
if(i < 3) {
nuevo_corre[i ] = corre[i + 1 ];
}

else if (i ==3 ){
nuevo_corre[i] = random(12 );
}
print(" i es " + i + " corre[] " + nuevo_corre[i]);
}

for(int i=0 ; i<4 ; i++){
corre[i ] = nuevo_corre[i ];
}
}
}

Re: translating content of an array
Reply #1 - Aug 14th, 2009, 6:56am
 
Your way is just fine. If you want to reduce the number of lines it takes to complete the action, you could use the subset() and expand() functions. Here's an example of how that would work:

Code:

int[] numbers = { 1, 2, 3, 4 };
numbers = subset(numbers, 1);
numbers = expand(numbers, numbers.length+1);
numbers[numbers.length-1] = 9;
println(numbers); //prints "[0]2, [1]3, [2]4, [3]9
Page Index Toggle Pages: 1