0

I'm new to the study of programming, in my opinion in this code everything is correct, but it does not work properly. Could you show me the reason. Thank you very much!!!

Task condition:

In one array the number of goals scored by the football team in each of the 20 games is recorded, in the other - the number of goals conceded in the same game. For each game, determine the verbal outcome of the game (win, lose or draw).

scoredGoals = Array.new(20) { rand(0...10) } #20 matches. scoredGoals
concededGoals = Array.new(20) { rand(-10...0) } #20 matches. concedeGoals

i = 0

while (i < 20)
  if scoredGoals[i] == concededGoals[i]
    puts "Friendship won";
  elsif scoredGoals[i] < concededGoals[i]
    puts "Defeat";
  elsif scoredGoals[i] > concededGoals[i]
    puts "Victory";
  end
  i = i + 1;
end

puts "==========================="
puts scoredGoals
puts "==========================="
puts concededGoals

The output shows "Victory" every time.

1
  • 2
    It's because concededGoals array contains negative numbers. Any positive number will be larger than a negative number. Quick fix: use rand(0...10) for both arrays. Commented May 17, 2022 at 8:49

1 Answer 1

1

It's not really a Ruby or a programming issue.

It happens because you have positive numbers in scoredGoals but negative numbers in concededGoals, e.g.

scoredGoals = [2, 4]
concededGoals = [-3, -1]

When comparing these, the value from scoredGoals will always be larger: (unless both are 0 which won't happen with your ranges1)

2 > -3 #=> true
4 > -1 #=> true

You most likely want both arrays to contain positive numbers, e.g.

scoredGoals = [2, 4]
concededGoals = [3, 1]

Which gives:

2 > 3 #=> false
4 > 1 #=> true

Here's a more idiomatic version of your code using zip to combine both arrays in a pair-wise manner:

scored_goals   = Array.new(20) { rand(0...10) }
conceded_goals = Array.new(20) { rand(0...10) }

scored_goals.zip(conceded_goals) do |a, b|
  if a == b
    puts "Friendship won"
  elsif a < b
    puts "Defeat"
  elsif a > b
    puts "Victory"
  end
end

1 an exclusive range (three dots) excludes the last value:

  • rand(0...10) will return a random number between 0 and 9 (excluding 10)
  • rand(-10...0) will return a random number between -10 and -1 (excluding 0)

In particular, the latter will never return 0.

Sign up to request clarification or add additional context in comments.

2 Comments

Nitpick - they can't both be zero due to the use of ...
@BroiSatse I've noticed that but wasn't sure if it's worth mentioning. It seemed like an edge case that becomes irrelevant once the problem's root cause is fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.