2

I am new to coding and am trying to learn Ruby. I am working in a Rake. What should I use to ensure that the random selection never repeats the same response back to back?

array = ["1", "2", "3", "4", "5"]

task :array do 
  array = ["1", "2", "3", "4", "5"]
  ap(array.sample) 
end
jvillian
  • 19,953
  • 5
  • 31
  • 44
JimmyC003
  • 17
  • 3
  • Could you say more (by editing your question) about what you mean by *never repeats the same response back to back*? Do you *never* want the same number twice? Or just not *twice in a row*? – jvillian Jul 03 '18 at 20:13
  • not twice in a row. thanks! – JimmyC003 Jul 03 '18 at 20:17

1 Answers1

2

With array.shuffle.each{|x|} you can reorder the array, then traverse the new order, pulling items in a random order without repeating them.

Phlip
  • 5,253
  • 5
  • 32
  • 48
  • This is not true if the array has repeated items, like `[1, 2, 3, 3, 4, 5]`, the case might be that 3 is pulled consecutive. For his answer he would need state. – Alex.U Jul 03 '18 at 20:20
  • 1
    I would just add a `.uniq` to clobber the duplicates, but the OP might indeed need almost-random-but-also-not-repeating-with-shuffled-duplicates, for whatever reason. Maybe they are building a radio station that plays songs in a random order, but at least by different artists... – Phlip Jul 03 '18 at 20:40
  • Where did the other answer go? It may have handled the "no duplicates back-to-back" requirement. But as `[3, 3, 3, 3, 3].uniq == [3]` the OP must declare what they need there! – Phlip Jul 03 '18 at 21:30