Search code examples
arraysrubyrandominclude

.include? array[rand(array.length)]


I'm trying to write an alternative to shuffle method and can't understand why it returns duplicates. Does anyone see the problem? Thanks so much!

def return_random_songs(songs)
  returned_songs = []
  while returned_songs.length < songs.length
    unless returned_songs.include?(songs[rand(songs.length)])
      returned_songs << songs[rand(songs.length)]
    end
  end
  return returned_songs
end

songs = ["song 1", "song 2", "song 3", "song 4"]
pp return_random_songs(songs)
=> ["song 2", "song 4", "song 1", "song 1"] #duplicates!

Solution

  • Because you compute twice the random song: for the check and when you add the song (so you don't know what ends up in the returned_songs array). Try

    def return_random_songs(songs)
      returned_songs = []
      while returned_songs.length < songs.length
        random_song = songs[rand(songs.length)]
        unless returned_songs.include?(random_song)
          returned_songs << random_song
        end
      end
      return returned_songs
    end