samedi 6 mai 2017

Is sequential or random comparison more efficient?

I am wondering (purely out of curiosity) if it is more efficient to compare numbers sequentially or randomly. I initially thought that it would be more efficient to compare numbers sequentially, but I was not sure and I have know idea how I would go about figuring this out, so I figured that I would ask the community.

Here is some pseudo code to help explain what I am thinking:

Sequential:

x = 1
y = random (1 to 5)

if (x == y){
  //finished
} else {
  x++
}

This will just add one to x every time until it gets to the same value as y. If, for example, x was 5 it would take five rounds for it to be finished, however if x was 1 it would get it on the first try.

Random:

x = random (1 to 5)
y = random (1 to 5)

if (x == y){
  //finished
} else {
  x = New random (1 to 5)
}

This one will set x to a new number every time. If, for example, x was 5 and y was 5 it may get it on the first try, but in theory it may never get it.




Aucun commentaire:

Enregistrer un commentaire