Syntax error in simple program - ruby

I'm new to programming and I'm trying to program something but there's some kind of syntax error which I can't work out. Any help would be much appreciated. Here's my code:
begin
puts"Enter a number to count, or to exit type 0."
y = gets.chomp.to_i
if y == 0
exit
end
puts"Now put the number you're starting with"
x = gets.chomp.to_i
if y + x == 12 or y + x < 12
print x + y
end
if y + x > 12
n = y + x - 12
end
begin
if n < 12 or n == 12
print n
end
if n > 12
n = n - 12
end
end until if n < 12 or n == 12
end until y == 0
end

Your use of until if if wrong. They are each control sequences. You shouldn't need both.

Your n is not visible later in the code. Declare n=0 for example before if y + x > 12 to make it visible and accessible in the relevant code blocks.
Then, until if is wrong, this should simply be until
Lastly, delete the last end keyword.

Related

How can I count number of iterations/steps to find answers of a method - RUBY

How can I get the number of iterations/steps that this method takes to find an answer?
def binary_search(array, n)
min = 0
max = (array.length) - 1
while min <= max
middle = (min + max) / 2
if array[middle] == n
return middle
elsif array[middle] > n
max = middle - 1
elsif array[middle] < n
min = middle + 1
end
end
"#{n} not found in this array"
end
One option to use instead of a counter is the .with_index keyword. To use this you'll need to use loop instead of while, but it should work the same. Here's a basic example with output.
arr = [1,2,3,4,5,6,7,8]
loop.with_index do |_, index| # The underscore is to ignore the first variable as it's not used
if (arr[index] % 2).zero?
puts "even: #{arr[index]}"
else
puts "odd: #{arr[index]}"
end
break if index.eql?(arr.length - 1)
end
=>
odd: 1
even: 2
odd: 3
even: 4
odd: 5
even: 6
odd: 7
even: 8
Just count the number of iterations.
Set a variable to 0 outside the loop
Add 1 to it inside the loop
When you return the index, return the count with it (return [middle, count]).
I assume the code to count numbers of interations required by binary_search is to be used for testing or optimization. If so, the method binary_search should be modified in such a way that to produce production code it is only necessary to remove (or comment out) lines of code, as opposed to modifying statements. Here is one way that might be done.
def binary_search(array, n)
# remove from production code lines marked -> #******
_bin_srch_iters = 0 #******
begin #******
min = 0
max = (array.length) - 1
loop do
_bin_srch_iters += 1 #******
middle = (min + max) / 2
break middle if array[middle] == n
break nil if min == max
if array[middle] > n
max = middle - 1
else # array[middle] < n
min = middle + 1
end
end
ensure #******
puts "binary_search reqd #{_bin_srch_iters} interations" #******
end #******
end
x = binary_search([1,3,6,7,9,11], 3)
# binary_search reqd 3 interations
#=> 1
binary_search([1,3,6,7,9,11], 5)
# binary_search reqd 3 interations
#=> nil

my code result in an infinite loop

puts "enter a number"
x = gets.chomp.to_i
y = 0
while x != 1
y += 1
if x % 2 == 0
x = x / 2
else
x = x*3 + 1
end
print "#{x} "
end
puts "\nThe number of sequence is #{y+1}"
Hi, if I key in negative number or 0, I will get an infinite loop. How do I avoid entering the loop if my number is 0 or negative.
You can use x > 1 i.e
puts "enter a number"
x = gets.chomp.to_i
# if you want to consider negative as positive then x = gets.chomp.to_i.abs
y = 0
while (x > 1)
y += 1
if x % 2 == 0
x = x / 2
else
x = x*3 + 1
end
print "#{x} "
end
puts "\nThe number of sequence is #{y+1}"
Hope it helps
To answer your question:
Your code works perfectly well and does exactly what it is told to do:
while x is not 1 OR x is smaller than 0 do this codeblock.
If you set x to a negative number, x will never be a positive number, so it runs forever (because x is always smaller 0).
So, the code is correct, but there is a flaw in the logic behind it :)

Ruby armstrong numbers in a range

puts "Enter range(starts at 1), ends at the number that you enter: "
range = gets.chomp.to_i
number = 1
while number <= range
temporary_number = number
sum_angstrom = 0
number += number
while(temporary_number != 0)
digit = temporary_number % 10
temporary_number /= 10
sum_angstrom = sum_angstrom + (digit ** 3)
end
if (sum_angstrom == number)
puts number
end
end
This time, I tried to make a program to show the armstrong numbers in a range that's taken from the user's input. The program just stops after I enter the number and press enter and i can't figure out why.
Keep in mind that i can't use for(each), that's why i'm using while so often.
First of all, change number += number to number += 1; otherwise you will only test the powers of 2.
Second, move the number += 1 line at the bottom of the while block it is in. Otherwise you will always test if sum_armstrong(n) == n+1.
This works:
puts "Enter range(starts at 1), ends at the number that you enter: "
range = gets.chomp.to_i
number = 1
while number <= range
temporary_number = number
sum_angstrom = 0
while(temporary_number != 0)
digit = temporary_number % 10
temporary_number /= 10
sum_angstrom = sum_angstrom + (digit ** 3)
end
if (sum_angstrom == number)
puts number
end
number += 1
end
Armstrong Number in Ruby one liner
n = 153
s = 0
n.to_s.split("").map{|e| s+=(e.to_i*e.to_i*e.to_i)}
puts (n==s ? "Armstrong number" : "Not Armstrong number")
You can iterate in a range to print the value based on your requirement.
Main logic lies in below line.
n.to_s.split("").map{|e| s+=(e.to_i*e.to_i*e.to_i)}
Improving my answer a little bit
n.digits.map{|e| s+=(e**3)}

How to nest while loops in Ruby

I'm trying to make a simple * pyramid using while loops but it stops at the first five *. I can't figure out why.
This is my code:
x = 5
y = 0
while x > 0
while y < x
print "*"
y +=1
end
x -= 1
end
You never reset y or print a new line
x = 5
y = 0
while x > 0
while y < x
print "*"
y +=1
end
print "\n"
y = 0
x -= 1
end
Output
*****
****
***
**
*
That is bad Ruby tho
This is a much more idiomatic solution
5.downto(1) do |x|
1.upto(x) do |y|
print "*"
end
print "\n"
end
Output
*****
****
***
**
*
I don't know what the final shape of "pyramid" you're looking for, but you can likely adapt the technique above to get the desired output

Can't get factorial function to work

Factorial 1 and 2 works but 3 and 4 do not. I've worked the steps out on paper and do not see why they do not work. Any help is much appreciated.
def factorial(n)
x = 1
y = n
while x < n
n = n * (y-x)
x = x + 1
end
return n
end
puts("factorial(1) == 1: #{factorial(1) == 1}")
puts("factorial(2) == 2: #{factorial(2) == 2}")
puts("factorial(3) == 6: #{factorial(3) == 6}")
puts("factorial(4) == 24: #{factorial(4) == 24}")
The reason it's not working is that after each loop the value of n gets bigger and the condition x < n keeps executing until it hits a point where n becomes zero. If you pass 3 to the function on the third loop you will have:
while x(3) < n(6)
n(6) = n(6) * (y(3) - x(3))
end
therefore n becomes 0 causing the loop to exit on the next round and the return value is obviously 0. To fix it you just need to replace n with y in the while condition:
while x < y
As a side note just another interesting way you could solve the factorial problem using recursion is:
def factorial(n)
n <= 1 ? 1 : n * factorial(n - 1)
end
Try this:
def factorial(n)
if n < 0
return nil
end
x = 1
while n > 0
x = x * n
n -= 1
end
return x
end

Resources