Power ball in Ruby

1

I made the following program:

class PowerBall

  def jogo

    brancas = Array.new
    50.times{brancas << false}

    brancasSorteadas = Array.new
    5.times{brancasSorteadas << 0}

    for x in brancasSorteadas
      j = rand(48) + 1
      if brancas[j-1] == false
        brancas[j-1] = true
        brancasSorteadas[x] = j
      else
        x -= 1
      end
    end

    for x in brancasSorteadas 
      puts "A bola branca eh: #{brancasSorteadas[x]}"
    end

    puts "A bola vermelha eh: #{rand(42)}"
  end
end

a = PowerBall.new
a.jogo

The goal is to remove five white balls from a bucket of 49 balls without repetition and draw a red ball from a bucket of 42 balls and can repeat some drawing from the white bucket.

Only the result is giving the following:

A bola branca eh: 
A bola branca eh:38
A bola branca eh:38
A bola branca eh:38
A bola branca eh:38
A bola vermelha eh:numero aleatorio

Varying the number that repeats each time the program is called. Does anyone know where the error is?

    
asked by anonymous 29.08.2014 / 03:16

1 answer

2

You probably came from the javascript universe where loops of type for x in array iterated x varying between array indices. Here in ruby the structure is:

for <variável> in <algo enumerável>

And the variable will be the elements of this enumerable object, in your case the array. If you want to loop using the indices you can do this:

for x in 0...array.size

or:

0.upto(array.size) do |x|

or:

array.size.times do |x|

Secondly, you ran x -= 1 within the loop. This does not exist, you can not change the loop variable since it will receive the next sequence value regardless of what you do with it.

Your loop can then be written like this:

for x in 0...brancasSorteadas.size
  j = rand(48) + 1
  if brancas[j-1] == false
    brancas[j-1] = true
    brancasSorteadas[x] = j
  else
    redo    # reinicia esta iteração do loop sem mudar o x
  end
end

Or:

brancasSorteadas.map do
  j = rand(48) + 1
  if brancas[j-1] == false
    brancas[j-1] = true
    next j
  else
    redo
  end
end

Or much simpler :

# Cria uma array com os números de 1 a 48, então escolhe 5 aleatóriamente
brancasSorteadas = (1..48).to_a.sample(5)
    
20.09.2014 / 16:30