lundi 25 avril 2016

Shuffling 2 elements in an Array

As my fellow students and I are struggling for hours with our first exercise in C, could you help us out?

Given a sequence of integers, say {17,9,5,23,21}, we must mingle it with the following algorithm:

for i increasing form 1 to 4, select a random j : j=rand(1,5) and swap ai and aj.

For instance if i=1 and j=3, then the result of the first step would be {5,9,17,23,21}.

  • Suppose for i=2, j=rand(2,5)=5, the result would be {5,21,17,23,9}
  • Suppose for i=3, j=rand(3,5)=3, the sequence doesn't change
  • Suppose then for i=4. j=rand(4,5)=5, the result would be {5,21,17,9,23}

'note that the result varies depending on random choices'




Aucun commentaire:

Enregistrer un commentaire