We have an array of some length(say 3) and some counting sequence: 0,1,2,3,4,...
to infinity. Out of that input sequence we need to produce sequence that will traverse through array back and forth, like that: 0,1,2,1,0,1,2,1,0,...
and so on for a length=3
.
I think this task is a very common one in a many programming books, but i was not able to find standard solution, so i created my own solution. Are there any other more efficient and elegant solution, because i dont like my solution???
#define LENGTH 5
int main()
{
char arr[LENGTH] = {'a','b','c','d','e'};
int i;
int base=0;
for(i=0;i<100;i++){
if(i%(LENGTH-1)==0){
if(base==0) base=LENGTH-1;
else base =0;
}
int j = abs(base-i%(LENGTH-1));
printf("%c ",arr[j]);
}
}
Java code (for your convenience):
public static void traverse(){
char arr[] = {'a','b','c','d','e'};
int base=0;
for(int i=0;i<100;i++){
if(i%(arr.length-1)==0){
if(base==0) base=arr.length-1;
else base =0;
}
int j = Math.abs(base-i%(arr.length-1));
System.out.println(arr[j]+" ");
}
}