How do I iterate in Ruby? - ruby

What's wrong with this Ruby code? I'm trying to solve the first Project Euler question.
I think the problem is in the syntax of sum += num, but I can't figure out what the proper syntax for this would be.
sum = 0
num = 0
num2 = 0
loop do
num += 1
if num % 3 == 0
sum += num
break if num > 1000
end
end
loop do
num2 += 1
if num2 % 5 == 0
sum += num2
break if num2 > 1000
end
end
puts sum

Here's an alternative:
(1...1000).select { |x| x % 3 == 0 || x % 5 == 0 }.reduce(:+)

You are making this way more complicated than it needs to be. Also, if the number is a multiple of 3 and 5, it gets added twice. Try something like this:
sum = 0 # initialize the sum
(1...1000).each { |x| # loop from 1 to 1000
sum += x if x % 3 == 0 || x % 5 == 0 # add the number to the sum if it is
# divisible by 3 or 5
}
puts sum # output the sum

This runs, your syntax is okay, but does not give the right answer because, as mentioned, you add multiples of both 3 and 5 twice, once in the first loop, with num, and the second loop, with num2.
So you have two loops, but you actually only need one.
You only need to consider each number once, you can check it to see if it is a multiple of either 3 or 5. This will solve your double-counting issue and also make your code more concise.
Also, like Doorknob shows, the each syntax would save you some lines on those loops. You could also use the for syntax:
for num in (1..1000)
<stuff here>
end
Check out the kinds of loops in "Loops: How to do thousands of operations with a few lines of code.".

Related

Ruby: find multiples of 3 and 5 up to n. Can't figure out what's wrong with my code. Advice based on my code please

I have been attempting the test below on codewars. I am relatively new to coding and will look for more appropriate solutions as well as asking you for feedback on my code. I have written the solution at the bottom and for the life of me cannot understand what is missing as the resultant figure is always 0. I'd very much appreciate feedback on my code for the problem and not just giving your best solution to the problem. Although both would be much appreciated. Thank you in advance!
The test posed is:
If we list all the natural numbers below 10 that are multiples of 3 or
5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of
3 or 5 below the number passed in. Additionally, if the number is
negative, return 0 (for languages that do have them).
Note: If the number is a multiple of both 3 and 5, only count it once.
My code is as follows:
def solution(number)
array = [1..number]
multiples = []
if number < 0
return 0
else
array.each { |x|
if x % 3 == 0 || x % 5 == 0
multiples << x
end
}
end
return multiples.sum
end
In a situation like this, when something in your code produces an unexpected result you should debug it, meaning, run it line by line with the same argument and see what each variable holds. Using some kind of interactive console for running code (like irb) is very helpfull.
Moving to your example, let's start from the beginning:
number = 10
array = [1..number]
puts array.size # => 1 - wait what?
puts array[0].class # => Range
As you can see the array variable doesn't contain numbers but rather a Range object. After you finish filtering the array the result is an empty array that sums to 0.
Regardless of that, Ruby has a lot of built-in methods that can help you accomplish the same problem typing fewer words, for example:
multiples_of_3_and_5 = array.select { |number| number % 3 == 0 || number % 5 == 0 }
When writing a multiline block of code, prefer the do, end syntax, for example:
array.each do |x|
if x % 3 == 0 || x % 5 == 0
multiples << x
end
end
I'm not suggesting that this is the best approach per se, but using your specific code, you could fix the MAIN problem by editing the first line of your code in one of 2 ways:
By either converting your range to an array. Something like this would do the trick:
array = (1..number).to_a
or by just using a range INSTEAD of an array like so:
range = 1..number
The latter solution inserted into your code might look like this:
number = 17
range = 1..number
multiples = []
if number < 0
return 0
else range.each{|x|
if x % 3 == 0 || x % 5 == 0
multiples << x
end
}
end
multiples.sum
#=> 60
The statement return followed by end suggests that you were writing a method, but the def statement is missing. I believe that should be
def tot_sum(number, array)
multiples = []
if number < 0
return 0
else array.each{|x|
if x % 3 == 0 || x % 5 == 0
multiples << x
end
}
end
return multiples.sum
end
As you point out, however, this double-counts numbers that are multiples of 15.
Let me suggest a more efficient way of writing that. First consider the sum of numbers that are multiples of 3 that do not exceed a given number n.
Suppose
n = 3
m = 16
then the total of numbers that are multiples of three that do not exceed 16 can be computed as follows:
3 * 1 + 3 * 2 + 3 * 3 + 3 * 4 + 3 * 5
= 3 * (1 + 2 + 3 + 4 + 5)
= 3 * 5 * (1 + 5)/2
= 45
This makes use of the fact that 5 * (1 + 5)/2 equals the sum of an algebraic series: (1 + 2 + 3 + 4 + 5).
We may write a helper method to compute this sum for any number n, with m being the number that multiples of n cannot exceed:
def tot_sum(n, m)
p = m/n
n * p * (1 + p)/2
end
For example,
tot_sum(3, 16)
#=> 45
We may now write a method that gives the desired result (remembering that we need to account for the fact that multiples of 15 are multiples of both 3 and 5):
def tot(m)
tot_sum(3, m) + tot_sum(5, m) - tot_sum(15, m)
end
tot( 9) #=> 23
tot( 16) #=> 60
tot(9999) #=> 23331668

Why Can't This Code Find Powers? (Ruby)

App Academy's practice test says their chosen way of finding if an input is a power of 2 is to keep dividing it by 2 on a loop and check whether the end result is 1 or 0 (after having tested for the numbers 1 and 0 as inputs), which makes sense, but why won't this way work?
def try
gets(num)
counter = 0
go = 2 ** counter
if num % go == 0
return true
else
counter = counter + 1
end
return false
end
I can't figure out why this won't work, unless the counter isn't working.
There are a number of problems with your code.
First of all, there is no loop and your counter will reset to zero each time if you intend to use the method in a loop, because of counter = 0.
counter = 0; go = 2 ** counter basically means go = 2 ** 0 which is 1. Therefore num % 1 will always be 0
You actually need to divide the number and change it in the process. 12 % 4 will return 0 but you don't know by that if 12 is a power of 2.
IO#gets returns a string and takes a separator as an argument, so you need to use num = gets.to_i to actually get a number in the variable num. You are giving num to gets as an argument, this does not do what you want.
Try:
# Check if num is a power of 2
#
# #param num [Integer] number to check
# #return [Boolean] true if power of 2, false otherwise
def power_of_2(num)
while num > 1 # runs as long as num is larger than 1
return false if (num % 2) == 1 # if number is odd it's not a power of 2
num /= 2 # divides num by 2 on each run
end
true # if num reached 1 without returning false, it's a power of 2
end
I add some checks for your code. Note, that gets(num) returns a String. Your code is fine, but not for Ruby. Ruby hates type-cross-transform like Perl does.
def try(num = 0)
# here we assure that num is number
unless (num.is_a?(Integer))
puts "oh!"
return false
end
counter = 0
go = 2 ** counter
if num % go == 0
return true
else
counter = counter + 1
end
return false
end
The general problem is "how string could use '%' operator with number?"
Try some code in the interpretator (irb):
"5" % 2
or
"5" % 0

Problems with Modulo operator Ruby: Why am I getting "undefined method `%' for 1..100:Range"?

For some reason I'm getting the error undefined method '%' for 1..100:Range when I run the following code:
[1..100].each do |x|
if x % 3 == 0 && x % 5 == 0
puts "CracklePop"
elsif x % 3 == 0
puts "Crackle"
elsif x % 5 == 0
puts "Pop"
else
puts x
end
end
Any idea what's going on? Any help is much appreciated.
That's the wrong syntax for ranges.
You've made an array with 1 element, and that element is itself the range 1..100. What you've written is equivalent to [(1.100)]. You're iterating over the outer array one time, and setting x to (1..100)
You want (1..100).each, which invokes each on the range, not on an array containing the range.
By doing [1..100] you are not looping from 1 to 100 but on 1..100, which is a Range object, what you really want to do is:-
(1..100).step do |x|
if x % 3 == 0 && x % 5 == 0
puts "CracklePop"
elsif x % 3 == 0
puts "Crackle"
elsif x % 5 == 0
puts "Pop"
else
puts x
end
end
Basically, Range represents an interval, you can iterate over Range as explained here, create an array from Range as explained here and more details on range can be found here.
Just as it says. 1..100 does not have a method %. The expression (1..100) % 3 is undefined.

Ruby file reading

I have a problem reading a file in ruby.
I am trying to read each line of a file, split it based on characters, and store that into an array. That array, which corresponds to each line, has information. I want to check if that array includes the characters "u" "d" "l" or "r" as you can see below.
IF that line doesn't include ANY of those characters, I increase a count variable by one.
The count -= 1 just takes into account a base case.
My problem is that this gives me a wrong count. For example with a text file that reads:
4 0 0 3 3
0 0 d 0.391538986557049
0 1 ur 63.1258159853081 3.14882640637611
0 2 rd 0.0148854629087619 0.019301544005463
0 3 u 15.6415340291405
count is supposed to be 0.
def compute_closed(file)
count = 0
while line = file.gets do
array = line.split(//)
answer = array.include?("u" || "d" || "l" || "r")
if answer != true
count += 1
end
end
count -= 1
puts count
end
Maybe you have a reason for splitting the line up into bits, but if you're just checking for those characters somewhere in the line, why not use a regex?
def compute_closed(file)
count = 0
while line = file.gets do
count += 1 if line =~ /[udlr]/
end
count -= 1
puts count
end
If you absolutely need to split the lines up by character, then you may want to use sets instead of arrays:
def compute_closed(file)
count = 0
while line = file.gets do
cmp_set = Set.new ['u', 'd', 'l', 'r']
input_set = Set.new(line.split(//))
if input_set.intersection(cmp_set).size == 0
count += 1
end
end
count -= 1
puts count
end
Edit: after posting I see my answer is essentially the same as #Philip's, but I'll leave it up for the slightly different treatment.
There are many ways to do this. Here's another:
File.read('f1').each_line.reduce(0) {|t,s| t + (s =~ /[udlr]/ ? 0 : 1)} - 1
Let's try it:
text =<<_
Now is the time
for all good
Rubiests to
spend some
time in Hawaii.
_
File.write('f1', text)
File.read('f1').each_line.reduce(0) {|t,s| t+(s =~ /[udlr]/ ? 0 : 1)} - 1 #=> 1
It returns 2 - 1 => 1 because if finds a 'u,' 'd', 'l' or 'r' in all but the the first and last rows.
Initially, I had
File.read(fname).each_line.each_with_object(0) {|s,t|
t += 1 unless s =~ /[udlr]/ } - 1
but t would not increment. I was puzzled, so emailed my friend #ArupRakshit, who I can always count on to know the answer, or dig until he finds it. It turns out that in
...each_with_object(memo) {|s,memo|
memo must be a mutable object, an important difference between that method and reduce/inject (which is not made clear in the Ruby docs for Enumerable#each_with_object). Thanks, Arup.

Is there an infinite loop in my code for solving Collatz sequence?

My code is trying to find the answer to this problem: The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
And here is my code:
step_count = 1
score = {}
largest_score = 1
(1..1000000).map do |n|
while n >= 1 do
if n%2 == 0 then
n/2
step_count += 1
else
(3*n)+1
step_count += 1
end
end
score = {n => step_count}
end
score.each {|n, step_count| largest_score = step_count if largest_score < step_count}
puts score.key(largest_score)
I ran it for over an hour and still no answer. Is there an infinite loop in my code, or maybe some different problem, and if so what is it?
I am using Ruby 1.8.7
Yes, you've got an infinite loop. It's here:
while n >= 1 do
if n%2 == 0 then
n/2
step_count += 1
else
(3*n)+1
step_count += 1
end
end
The condition in your while loop is testing n, but nothing within the loop is changing its value. What you probably meant to do is this:
while n >= 1 do
if n % 2 == 0
n = n / 2
step_count += 1
else
n = (3 * n) + 1
step_count += 1
end
end
A few sidenotes:
It looks like you mean to be updating the score hash with new key-value pairs, but as written, score = { n => step_count } will replace it entirely on each iteration. To add new pairs to the existing Hash, use score[n] = step_count.
It's much more efficient to look up a value in a Hash by its key than the other way around, so you might want to reverse your Hash storage: score[step_count] = n, finding the largest score with score.each { |step_count, n| #... and reading it out with score[largest_score]. This has the added advantage that you won't have to store all million results; it'll only store the last number you reach that results in a chain of a given length. Of course, it also means that you'll only see one number that results in the largest chain, even if there are multiple numbers that have the same, highest chain length! The problem is worded as though the answer is unique, but if it isn't, you won't find out.
To debug problems like this in the future, it's handy to drop your loop iterations to something tiny (ten, say) and sprinkle some puts statements within your loops to watch what's happening and get a feel for the execution flow.
Try the following solution for your problem:
def solve(n)
max_collatz = 0; max_steps = 0
(1..n).each do |k|
next if k % 2 == 0
next if k % 3 != 1
steps = collatz_sequence_count(k)
if steps > max_steps
max_steps = steps
max_collatz = k
end
end
max_collatz
# answer: 837799 with 525 steps, in nearly 2.2 seconds on my machine
end
def collatz_sequence_count(k)
counter = 1
while true
return counter if k == 1
k = k % 2 == 0 ? k/2 : 3 * k + 1
counter += 1
end
end
# You can then use the above methods to get your answer, like this:
answer = solve 1000000
puts "answer is: #{answer}"
Results (uses a custom home-brewed gem to solve ProjectEuler problems):
nikhgupta at MacBookPro in ~/Code/git/ProjectEuler [ master: ✗ ] 48d
± time euler solve 14 +next: 2 | total: 22 | ▸▸▸▹▹▹▹▹▹▹
0014 | Longest Collatz sequence | It took me: 2.166033 seconds. | Solution: 837799
euler solve 14 3.30s user 0.13s system 99% cpu 3.454 total

Resources