Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
def sum_of_3_or_5_multiples(final_number)
final_sum = 0 #cette variable est la somme finale qui sera retournée. Ici on l'initialise à zéro
while final_sum < 1000
final_sum += 1
end
current_number = final_sum
if is_multiple_of_3_or_5?(current_number)
puts current_number%3 == 0 || puts current_number%5 == 0
else
# si la réponse est "false"…ben y a pas de else : ce "current_number" n'est pas multiple,
# donc on passe au suivant en oubliant celui-là. On repart dans la boucle.
end
#Ici, positionne la fin de la boucle
return final_sum #on retourne la variable qui contient la somme du tout
end
sum_of_3_or_5_multiples(11) #=> 33
sum_of_3_or_5_multiples(10) #=> 23def sum_of_3_or_5_multiples(final_number)
I need to make a program that calculates the multiples of 3 and the multiples of 5 in a given pattern. So I did the loop that goes from 0 to 1000 with the right variables.
But I have a problem with the "if" loop. I don't see how I can put my formula when the "if" is already declared?
Hope this is clear enough.
I show you my code, the comments are those of the exercise.
your current code is broken in major ways ...
you could replace all of your code with:
def sum_of_3_or_5_multiples(final_number)
puts true if is_multiple_of_3_or_5?(1000)
return 1000
end
I'm making a lot of assumptions here, as it's hard to tell exactly what you're trying to do.
Assuming that you are looking for the sum of all values that are a multiple of 3 or 5, and that final_number is the maximum number of the highest possible multiple to sum, you will really be needing something more like the following:
def is_multiple_of_3_or_5? (number)
return (number%3).zero? || (number%5).zero?
end
def sum_of_3_or_5_multiples(final_number)
final_sum = 0
1.upto(final_number) do |i|
final_sum += i if is_multiple_of_3_or_5?(i)
end
final_sum
end
Here is a minimal change to your code, which hopefully achieves what you wanted:
def sum_of_3_or_5_multiples(final_number)
final_sum = 0
current_number = 1
while(current_number <= final_number) do
if is_multiple_of_3_or_5?(current_number)
final_sum += current_number
end
current_number += 1
end
return final_sum
end
Notes:
There are many ways to implement this "loop", and keep incrementing the current_number. You could use a for loop, or (1..final_number).each, or use recursion, or use 1.upto(final_number), or use final_number.times, ... But however you do it, the critical thing that you needed to add to the final_sum inside the loop.
I removed the part of your code saying while final_sum < 1000. I don't understand what this was trying to achieve. Why is there any condition of the final_sum, and what's the significant of 1000?!
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
A
B B
C C C
D D D D
E E E E E
I don't know, how to print alpahbets
You can do the following to work it out:
('A'..'F').each.with_index(1) { |letter,index| puts "#{letter} "*index }
Alternatives include making the ranges variable:
lower_limit = 'A' # could be read in rather than wired
upper_limit = 'F' # ditto
(lower_limit..upper_limit).each.with_index(1) { |letter,index| puts "#{letter} "*index }
or using an array with join to get the spaces without introducing a trailing blank:
(lower_limit..upper_limit).each.with_index(1) { |letter,index| puts Array.new(index) { letter }.join(' ') }
You can do something like -
(1..5).each do |index|
(1..index).each do
print (64+index).chr
end
puts "\n"
end
What it does -
(1..5) - Run a loop with index starting from 1 up until 5.
(1..index) - run another loop so for each of the above loop, it runs from 1 up till index, which will be controlled from the (1..5).each loop.
(65).chr -> A, (66).chr -> B and so on..
puts "\n" to add a new line
That will give you the output -
A
BB
CCC
DDDD
EEEEE
If you want to add anything additional to whatever you are printing you can do something like -
print "#{(64+index).chr} - random text"
#{} construct will allow you to write ruby interpret-able code within a string block`
Note: #{} only works when you use double quotes :)
Its not for RUBY nor for any other language, its just a flow :
Print alphabets like :
for (ch = 'a'; ch <= 'z'; ch++)
{
System.out.println(ch);
}
Now initialise counter i = 0
Increment i++ in every loop.
Print the current outer loops current char, i times
This question already has answers here:
How to break out from a ruby block?
(8 answers)
Closed 5 years ago.
How can I make the following loop end when the user writes stop, otherwise if they answer correctly how can it call the method again so that the number to be guessed is different?
The idea of the game is that the user tries to get the number from the class, if they get it correctly then the game asks if they want to guess a new number generated by the class or if they want to stop;if so they write Stop and the game would end.
Thanks in advance for the help
class NumberGuessingGame
#clase NumberGuessingGame
def initialize
#metodo que inicia
#number= rand(0..9)
#number es igual a un numero random entre 0 y 9
end
def guess(numer)
#metodo guess que dice que hay una condicion dada por el usuario, si no se da entonces se pide que el usuario la escriba manualmente
if numer<#number
#si el numero es mas pequeño que el numero entonces "Too low"
"Too low"
elsif numer>#number
#si el numero es mayor a el numero entonces "too high"
"Too high"
elsif numer == #number
#si el numero es igual al numero random que pone la computadora entonces "you got it!"
"you got it!"
end
end
end
game = NumberGuessingGame.new
# Pruebas
a = ""
p "Welcome to Guess the Number"
p "Human VS Machine"
while a != "Stop"
x = ""
while x != "you got it!"
p"Write a number between 0 and 9"
y = gets.chomp.to_i
p x = game.guess(y)
end
p "WOOOOW!! Very Impresive. Want to defeat the machine again? If not write
stop or guess the new number"
NumberGuessingGame
a = gets.chomp
end
Here is a code solution I produced for this problem. Try it out and see if it is to your liking:
https://gist.github.com/BKSpurgeon/1a2346e278836d5b4448424cb93fd0e9
class NumberGuessingGame
def initialize
welcome
end
def welcome
puts "Welcome to Guess the Number \n Human VS Machine"
end
def guess
loop do
#number= rand(0..9)
p "Write a number between 0 and 9"
numer = -1
while numer != #number
numer = gets.chomp.to_i
if numer<#number
p "Too low"
elsif numer>#number
p "Too high"
elsif numer == #number
p "You got it!"
puts "WOOOOW!! Very Impresive. Want to defeat the machine again? If not write stop otherwise press any key."
break
end
end
answer = gets.chomp # The Critical Line to break out of the Loop is here:
break if answer.downcase == "stop"
end
end
end
and you'd call it like this:
g = NumberGuessingGame.new
g.guess
that escapes if you write 'stop'. i made minor modifications of the functionality. The loop is broken if the "stop" answer is detected. that is the critical line.
I can't see a good reason for client code to be doing this type of thing:
game = NumberGuessingGame.new
# Pruebas
a = ""
p "Welcome to Guess the Number"
p "Human VS Machine"
while a != "Stop"
x = ""
while x != "you got it!"
p"Write a number between 0 and 9"
y = gets.chomp.to_i
p x = game.guess(y)
end
p "WOOOOW!! Very Impresive. Want to defeat the machine again? If not write
stop or guess the new number"
NumberGuessingGame
a = gets.chomp
end
ideally you want to let all the methods in a class to do all the work - you should not have to write 'welcome to the game etc' from outside the class - that should be the responsibility of the NumberGuessingGame class.
hope this helps.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm trying to set up a pretty simple dice roll and response in the prompt and it's not working right. I wanted the loop to keep asking until the user inputs roll, Roll or ROLL.
def roll()
x = rand(5) + 1
y = rand(5) + 1
z = rand(5) + 1
puts "You rolled #{x},#{y},#{z}"
if x == y && y == z
puts "TRIPS! Trip #{x}s"
elsif x == y || y == z || x == z
puts "Pair!"
else
if x > y && x > z
puts "#{x} high"
end
if y > x && y > z
puts "#{z} high"
end
if z > x && z > y
puts "#{z} high"
end
end
end
puts "Type 'roll' when you're ready."
entry = gets.chomp
until entry == roll || Roll || ROLL
puts "Type 'roll' when you're ready."
entry = gets.chomp
end
roll()
# Remove these two lines and just use them in the while / until
# puts "Type 'roll' when you're ready"
# entry = gets.chomp
entry = ''
# Use String.downcase on entry because the user could type rOLL or RoLl
while entry.downcase != 'roll' # or you can use until entry.downcase == 'roll'
puts "Type 'roll' when you're ready."
entry = gets.chomp
end
You are comparing entry to values that do not exist. You need to compare to a string.
Roll by convention should be a class / model / object of some kind. For example
class Roll
# create roll
def initialize()
end
end
roll = Roll.new
# or for an existing class like Arrays
array = Array.new
ROLL by convention would be a previously defined constant.
ROLL = 7
# => 7
ROLL = 4
# => warning: already initialized constant ROLL
Here's an example of how you can do it in a more Ruby fashion that makes it more extensible.
Start with making your roll method focused on one very simple thing:
def roll(sides = 6, count = 3)
Array.new(count) { rand(sides) + 1 }
end
Note that rand(5) produces values in the range of 0..4, it never yields 5. The idea here is to return an array that's of arbitrary length, and by having exposed arguments with defaults you can re-purpose this method easily for other situations.
Then move all of the display logic to the main loop:
loop do
puts "Type 'roll' when you're ready."
entry = gets.chomp
case (entry.downcase)
when 'roll'
rolls = roll
puts "You rolled #{rolls.join(', ')}"
case (rolls.uniq.length)
when 1
puts "TRIPS! Trip #{rolls[0]}s"
when 2
puts "Pair!"
else
puts "#{rolls.max} high"
end
break
when 'quit'
break
end
end
Using an array structure instead of three arbitrary variables helps considerably when working with them in aggregate. You can see how things like uniq and max are effortless in this situation.
Hello I'm new to programming and I started with ruby. I'm trying to do my first program. I found online this code that generate a dice roll
class Die
def initialize(sides)
#sides = sides
end
def generate_die_roll
rand(#sides) + 1
end
def roll(number=1)
roll_array = []
number.times do
roll_array << generate_die_roll
end
total = 0
roll_array.each do |roll|
new_total = total + roll
total = new_total
end
total
end
end
and I would like to use in they way that if the number generated is inferior o equal to another print something otherwise something else.
It's probably very easy but i'm trying in every way and now I will need some help please.
that's my code:
require "./newdado.rb"
energia_vitale = 30
puts "Lancia un dado scrivendo (D) da sommare alla tua Energia Vitale iniziale di #{energia_vitale} punti"
scelta = gets.chomp
case scelta
when "D"
SIX_SIDED_DIE = "#{Die.new(6)}"
values = Array[]
values.push(SIX_SIDED_DIE.roll)
puts values
if values < 2
puts "c"
else puts "b"
end
end
when I run it i receive this error
C:/Users/fix/workspace/D&D Ruby/energia vitale.rb:11:in <main>': undefined methodroll' for "#":String (NoMethodError)
Sorry to bother the community with this beginner problem
Why as string?
this line
SIX_SIDED_DIE = "#{Die.new(6)}"`
should be something like
die = Die.new(6)
then you can do die.roll
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The first code works, but I don't understand why the second one doesn't. Any insight would be appreciated. I know in this example I really don't need an array, I just wanted to get it to work for the sake of learning.
def stamps(input)
if input % 5 == 0
puts 'Zero!'
else
puts 'NO!'
end
end
print stamps(8)
But this doesn't work:
array_of_numbers = [8]
def stamps(input_array)
if input_array % 5 == 0
puts 'Zero!'
else
puts 'NO!'
end
end
print stamps(array_of_numbers)
Because input_array is an array and 8 is a number. Use first to retrieve the first element of the array.
array_of_numbers = [8]
def stamps(input_array)
if input_array.first % 5 == 0
puts 'Zero!'
else
puts 'NO!'
end
end
print stamps(array_of_numbers)
The following function works in case the input is number or array:
def stamps(input)
input = [input] unless input.is_a?(Array)
if input.first % 5 == 0
puts 'Zero!'
else
puts 'NO!'
end
end