Generate Random Numbers Until a certain - ruby

I am trying to write some code (using a while loop) that will generate random numbers (between 1 and 10) until the number 7 is generated.
Here is what I've got so far, but it's just stuck in a loop of printing random numbers between 1 and 10.
num = ""
while num != 7
print rand(1..10).to_s
end
puts "over"
I understand why it's looping without end, but I'm unsure of how else to generate the random numbers and still end the loop when a 7 appears.

There are many ways to do it, for example:
loop do
num = rand(1..10)
print num
break if num == 7
end
Also, to make your code work:
num = ""
while num != '7'
num = rand(1..10).to_s
print num
end
puts "over"
reason in that you convert num to string and compare it with integer

puts (number = rand(1..10)) until number == 7

The problem for this code is that you generate an infinite loop because num is always "", you need to update the variable num inside the while loop like this:
num = ""
while num != 7
num = rand(1..10)
puts num
end
puts "over"
in this case, you do not know when the loop will stop, but in each loop it can stop with probability 1/10, this is not a good practice, you nedd to know when the loop stops, so will be better to add a variable for maximum number of tries like this. And also you do not need to transform dthe number to string to print it:
num = 0
max_tries = 100
try = 1
guess = 7
while (try < max_tries && num != guess)
num = rand(1..10)
try = try + 1
puts num
end
if (try >= max_tries)
puts "you do not get the guess"
else
puts "over"
end
and you get this:
[4] pry(main)> 9
9
3
4
9
6
9
8
4
5
9
10
4
3
7
over
=> true

Try this out
$num = 0
while $num != 7
$num = rand(1..10)
print $num.to_s + "\n"
end
puts "over"

You have to assign the rand generated value into num variable,
$ num = ''
$ while num != 7
$ num = rand(1..10)
$ print num
$ end
$ # 6168510267=> nil

Related

Ruby- prime number unique and duplicates

I'm just learning Ruby :) and Im trying to create a simple prime-number program where all the primes of a number are printed.
I'm getting errors where the prime and nonprime numbers are mixed up
(ie: input of 9 will get you all nonprimes).
I'm sorry for such a beginner question - I'm struggling alot and need some help :)
puts "Enter a number please "
num = gets.chomp.to_i
i = 2
number = 2
while i < num
if number % i == 0
prime = false
end
i += 1
end
if prime == true
puts "#{number} is prime"
else
puts "#{number} is not prime"
end
number += 1
end
while i < num
if number % i == 0
prime = false
end
i += 1
end
# ...
It looks like that first end is meant to be an else.
It's easier to catch these things when you simplify your code, e.g. this method reduces to this (although there are other issues with it):
i = 2
number = 2
while i < num
(number % i).zero? ? prime = false : i += 1
puts "#{number} is #{'not ' unless prime}prime"
number += 1
end
End error is because of else
while i < num
if number % i == 0
prime = false
else
i += 1
end
if you have a short If - neater is writing it like:
if-condition ? 1 : 0
and in your case while is.. not the nicest choice - you should use range
(1...3).map{|x| puts(x) }
{} - allows multiline(with do end end)
this prints [1,2]
(1..3).map{|x| x*2 }
would be [2,4,9]
This should be enough hints of how to play around with your code without ruining the process.

Getting a 'nil:Nil Class' error in Ruby, but the array doesn't seem to empty

I'm trying to code the 'Sieve of Eratosthenes' in Ruby and I'm having difficulty in the second 'while' loop. I want to test to see if integers[j] % integers[0] == 0, but the compiler keeps giving me a nil:Nil Class error at this line. I can't figure out the problem.
n = gets.chomp.to_i
puts
while n < 2
puts 'Please enter an integer >= 2.'
puts
n = gets.chomp.to_i
puts
end
integers = []
i = 0
while i <= n - 3
integers[i] = i + 2
i += 1
end
primes = []
j = 1
while integers != []
primes.push integers[0]
while j <= integers.length
if integers[j] % integers[0] == 0
integers.delete(integers[j])
end
j += 1
end
integers.shift
j = 1
end
puts integers
puts
puts primes
Thanks in advance for any help!
It's an off-by-one error. You're testing for j <= integers.length. So, for example, if you array has five items, the last iteration will be integers[5]. But the last index in a five-item array is 4 (because it starts at 0). You want j < integers.length.

Ruby - Prime Number calculator

I need some feedback to figure out why I cant puts or print anything from my methods on the screen. This is a simple script I wrote to solve the problem of finding the 1001st prime number. Thanks
def primes
# iterates through numbers until it has the 1001th prime number and returns it.
# I chose to create the num_primes variable instead of counting the number of
# elements in in_prime_array every iteration
# based upon a guess that it would be faster to check.
is_prime_array = []
num_primes = 0
i = 2
loop do
is_prime_array << i && num_primes += 1 if is_prime?(i) == true
i += 1
break if num_primes == 1001
end
is_prime_array[1001]
end
def is_prime? (num)
# Checks to see if the individual number given is a prime number or not.
i = 2
loop do
if i == num
return true
elsif num % i == 0
return false
else
i += 1
end
end
end
Thanks for any help!
EDIT
I took your advice and tried this pice of code:
def is_prime? (num)
# Checks to see if the individual number given is a prime number or not.
i = 2
loop do
if i == num
return true
elsif num % i == 0
return false
else
i += 1
end
end
end
i = 0
count = 0
loop do
count += 1 if is_prime?(x)
puts "#{i}" if count == 1001
break
end
It still returns nothing. Hummm
i = 0
count = 0
loop do
if is_prime(i)
count += 1
end
if count == 10001
puts "#{i}"
break
end
end
Simple method :)
It's an off-by-one error. If you have 1001 elements in an array, the last element will be at index 1000.
Where you have
is_prime_array[1001]
Change it to
is_prime_array[1000]
And you can do this:
puts primes
=> 7927
You could also have
is_prime_array.last
instead of a specific index number.
What are you trying to "puts"? The first thing I notice is that there is no call to primes in the file, so nothing will happen if you try to run this code by itself. Maybe that's why you don't see anything printed.
Here's an example of how to print a few variables inside your loop:
loop do
...
puts "At iteration #{i}, we have prime=#{is_prime?(i)}"
If you don't know, enclosing a statement with #{<statement goes here>} inside a string is the same as appending the return value of <statement goes here> to the string at that position. This is the same as "Str " + blah + " rest of str" in a language like Java.

Ruby Each Statement gets stuck on while loop

New to StackOverflow here. I'm working on the first Euler problem and have run into an issue where I can get the statement to iterate through the array. It seems like it has something to do with the way I have the while loop setup but I can't figure it out.
Here's my code:
#euler problem 1
numbers = [3,5]
sum = 0
i=1
total=0
numbers.each do |number|
while i * number < 10
adder = i * number
total += adder
i += 1
puts total
end
end
puts total
The output is 3
9
18
18
Any idea why it isn't processing the 5 in the array numbers?
Your problem is that i is declared outside the block so when number is five, i is already four and the while loop's condition fails immediately because 20 < 10 is false. Try it like this:
numbers = [3,5]
sum = 0
total=0
numbers.each do |number|
i = 1
while i * number < 10
#...
end
end
puts total
If you put a little puts in your code you'll see what's going on:
i = 1
numbers.each do |number|
puts "#{number}\ti = #{i}"
while i * number < 10
puts "\ti = #{i}"
adder = i * number
total += adder
i += 1
end
end
That will give you this output:
3 i = 1
i = 1
i = 2
i = 3
5 i = 4
and you'll see the problem with i.

Why doesn't my conversion code for roman numbers ('mcmxcix' for e.g) to real numbers work?

I want to convert Roman numerals, such as "mcmxcix", to arabic integers like "1999".
My code looks like:
#~ I = 1 V = 5 X = 10 L = 50
#~ C = 100 D = 500 M = 1000
def roman_to_integer roman
len = roman.length
x = 1
while x <= len
arr = Array.new
arr.push roman[x]
x += 1
end
num = 0
arr.each do |i|
if i == 'I'
num += 1
elsif i == 'V'
num += 5
elsif i == 'X'
num += 10
elsif i == 'L'
num += 50
elsif i == 'C'
num += 100
elsif i == 'D'
num += 500
elsif i == 'M'
num += 1000
end
end
num
end
puts(roman_to_integer('MCMXCIX'))
The output is 0, but I don't understand why?
Ruby doesn't have a post-increment operator. When it sees ++ it interprets that as one infix + followed by one prefix (unary) +. Since it expects an operand to follow after that, but instead finds the keyword end, you get a syntax error.
You need to replace x++ with x += 1.
Furthermore note that x isn't actually in scope inside the roman_to_integer method (which isn't a syntax error, but nevertheless wrong).
Additionally you'll have to replace all your ifs except the first with elsifs. The way you wrote it all the ifs are nested, which means that a) you don't have enough ends and b) the code doesn't have the semantics you want.
You are missing a closing parentheses so
puts(roman_to_integer('mcmxcix')
should be
puts roman_to_integer('mcmxcix')
or
puts(roman_to_integer('mcmxcix'))
The arr keeps getting annihilated in your while loop, and it is not in the scope outside of the loop. Move the following line above the while statement:
arr = Array.new

Resources