Accessing array elements in a random fashion?
in
Programming Questions
•
2 years ago
Hi Everyone,
I am struggling with realizing an idea and it drives mad already, so I was wondering if anyone could help me?
Basically I'd like to develop an algorithm that accesses array elements randomly, not like a for loop would. It seemed like a pretty easy and straightforward task first (choosing a random element, accessing the random element, then making a new array not containing the already accessed element, replacing the old array with the new one, then starting over) but my code just wont work and I truly don't see why...
So here's the code:
Thanks a lot in advance,
Ben
UPDATE:
In the meantime I figured that maybe I should just use ArrayList instead of arrays... But still, I cant wrap my head around why my code would not work, so if anyone has an idea please share!
I am struggling with realizing an idea and it drives mad already, so I was wondering if anyone could help me?
Basically I'd like to develop an algorithm that accesses array elements randomly, not like a for loop would. It seemed like a pretty easy and straightforward task first (choosing a random element, accessing the random element, then making a new array not containing the already accessed element, replacing the old array with the new one, then starting over) but my code just wont work and I truly don't see why...
So here's the code:
- while(oldArray.length>0) {
- int which=floor(random(oldArray.length));
- oldArray[which].doSomething();
- OldArrayClass[] tempArray=new OldArrayClass[0];
- for(int i=0; i<oldArray.length; i++) {
- if(i!=which) {
- tempArray=(OldArrayClass[]) append(tempArray,oldArray[i]);
- }
- }
- arrayCopy(tempArray,oldArray);
- }
Thanks a lot in advance,
Ben
UPDATE:
In the meantime I figured that maybe I should just use ArrayList instead of arrays... But still, I cant wrap my head around why my code would not work, so if anyone has an idea please share!
1