Power ball in Ruby

Asked

Viewed 51 times

1

I did 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

His goal is to pull five white balls out of a 49-ball bucket without repetition and pull a red ball out of a 42-ball bucket and repeat some taken 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 mistake is?

  • 1

    x is always 0. It is not the index of the array in the loop, it is each value (and its array only contains zeros). I think it also has logic errors, but start from there.

1 answer

2

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

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

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

for x in 0...array.size

or:

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

or:

array.size.times do |x|

Second of all, you executed x -= 1 inside the loop. This doesn’t exist, you can’t 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 else:

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

Or form 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.