Go Down

Topic: Swap() functoin (Read 1 time) previous topic - next topic

sydkahn

I want to swap two pins in a charliplex array randomly.  problem is what code i came up with is WAY to slow. you can see a noticeable pause in the display every time it is called.  I dug around in the forums and online until i got cross eyed without any luck.


Code: [Select]

void swap(int numswaps){
 int from=0;
 int to=0;
 for (int i=0;i < numswaps  ; i++){
 from= random(numHeartPins);
 to= random(numHeartPins);
 int temp[2] ={0,0};
 temp[0]=heartpins[from][0];
 temp[1]=heartpins[from][1];
 heartpins[from][0]=heartpins[to][0];
 heartpins[from][1]=heartpins[to][1];
 heartpins[to][0]=temp[0];
 heartpins[to][1]=temp[1];
 }
}


Is there a faster way to do this (in c?)  I program all day long in Java - but some of this syntax is a bit hard to comprehend.

AWOL

Just a couple of things - no point in initialising the automatic variables "from" "to" and "temp" - they're going to get assigned anyway.
Maybe make them "byte".
You're probably spending a fair amount of time in "random"  - look at a simpler/faster homebrew "random".
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

westfw

The code you posted does not LOOK like it should consume "noticeable" time, unless numswaps is quite large.  Are you sure the delay is due to this function?

sydkahn

I agree it should not take noticeable time if run once, but to get the job done i has to be run multiple time to achieve the shuffle of the values - right now i have 12 leds in the charliplex array so i have narrowed it down to 6 time thorough.

I'll live with it for now - the Christmas tree is going to work - and if they notice a delay i'll work on it a little more....

AWOL

Why not calculate the swap pins in the background, and then simply do a bulk assignment in one hit?
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

sydkahn

It took a few minutes until the suggestion sunk in - not enough coffee i guess.
home brew solution:  in setup() create a large array of values created by the random() generator - no one cares how long that takes - make sure it has odd number of members. cycle through the array in the code.  Close enough to mix up the blinking of a little christmas tree lights - this isn't cryptography after all....  ;)

AWOL

Don't forget to reduce the array element size to "byte".
You could pre-calculate the whole lot and put it in PROGMEM, which would allow for longer sequences.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up