I have the following code
#!/usr/bin/ruby -w
c = 1
d = Array.new(6965) #6965 is the amount of abundant numbers below 28123 of which all numbers greater than that can be written as the sum of two abundant numbers
f = 0
while c < 28124 # no need to go beyond 28123 for this problem
a = 0
b = 1
i = true # this will be set to false if a number can be written as the sum of two abundant numbers
while b <= c/2 + 1 # checks will go until they reach just over half of a number
if c % b == 0 # checks for integer divisors
a += b # sums integer divisors
end
b += 1 # iterates to check for new divisor
end
if a > c # checks to see if sum of divisors is greater than the original number
d << c # if true it is read into an array
end
d.each{|j| # iterates through array
d.each{|k| # iterates through iterations to check all possible sums for number
# false is declared if a match is found. does ruby have and exit statement i could use here?
i = false if c - j - k == 0
}
}
c+=1 # number that we are checking is increased by one
# if a number cannot be found as the sum of two abundant number it is summed into f
f += c if i == true
end
puts f
For the following code, whenever I try to do a double iteration for my d array, I come up with the following errors:
euler23:21:in -': nil can't be coerced into Fixnum (TypeError)
from euler23:21:inblock (2 levels) in '
from euler23:20:in each'
from euler23:20:inblock in '
from euler23:19:in each'
from euler23:19:in'
As I'm not familiar with Ruby, my various attempts at resolving this have been for naught. I get the feeling that there are some libraries I need to include, but my research hasn't mentioned any libraries, and I am at a loss. This code is meant to sum all the numbers that cannot be written as the sum of two abundant numbers; it is the twenty third question from Project Euler.
When you do this:
d = Array.new(6965)
you create an array of 6965 nil values.
If before line 21 you add this test code:
p [c,j,k]
then you get the result:
[1, nil, nil]
which shows that j and k are both nil values. You are iterating through empty items in your array.
If you change your creation of d to just:
d = [] # an empty array, which in Ruby can change size whenever you want
...then your code runs. (I've not let it run long enough to see if it runs correctly, but it runs without error for quite some time at least.)
Finally, a few bits of random style advice:
This code:
while b <= c/2 + 1
if c % b == 0
a += b
end
b += 1
end
can be rewritten more concisely and more Ruby-esque as:
b.upto(c/2+1){ a+=b if c%b==0 }
Similarly, this loop:
c=1
while c < 28124
# ...
c += 1
end
can be rewritten as:
1.upto(28123) do |c|
# ...
end
When you ask about breaking out of a loop, you can use break or next as appropriate, or throw and catch—which is NOT used for error handling in Ruby— to jump to a particular nested loop level.
The code below is faulty:
d.each{|j|
d.each{ |k|
p c,j,k #1,nil,nil
i = false if c - j - k == 0 }}
Because of:
1 - nil - nil
#TypeError: nil can't be coerced into Fixnum
# from (irb):2:in `-'
# from (irb):2
# from C:/Ruby193/bin/irb:12:in `<main>'
Related
Question is a user gives 3 sides and identifies triangles, like equilateral, isosceles and scalene. Here is my coding, I don't know why gives any sides that always show up "invalid". I think it's logic wrong, but I can't figure out.
puts "please input the length of 3 sides:"
a = gets.chomp.to_i
b = gets.chomp.to_i
c = gets.chomp.to_i
if a + b <= c
puts "invalid"
elsif a <= 0 || b <= 0 || c <= 0
puts "invalid"
else
if a == b && b == c
puts"equilateral triangle"
elsif a == b
puts"isosceles triangle"
else
puts"scalene triangle"
end
end
The fact that your code always prints "invalid" makes me think that input is passed in on one line instead of being on separate lines. For example, when the input is:
50 50 50
instead of getting 50 in all three variables you would get 50 in a and 0 in b, c. This is because gets takes in an entire line instead of taking one value.
In such an event, this is what you need:
a, b, c = gets.split.map{ |value| value.to_i }
A better more effective way to do this is to store the values of the triangle sides into a hash first, the value of of each triangle side will be the keys, and the value of each key can be the repeats. This will work with strings too.
Here is an Example.
# First you get an array, you can use gets.chomp as string and split to array, whichever way you choose, but in the end we end up with an array, and we pass the array to the method.
def triangle_type(arr)
# Create new empty hash
repeated_sides = Hash.new(0)
# First make sure the array is only a length of three. (this is optional)
if arr.length == 3
# Iterate through each value in the array and store it to to a hash to find duplicates
arr.each do |x|
repeated_sides[x] += 1
end
# sort the hash by it's values in descending order, for logic to work later.
repeated_sides = repeated_sides.sort_by {|k,v| v}.reverse.to_h
# uncomment this below to see the duplicate sides hash
#puts "#{repeated_sides}"
# Iterate through the sorted hash, apply logic starting from highest and first value the iterator will find.
repeated_sides.each do |k,v|
return v == 3 ? 'Equilateral Triangle' : v == 2 ? 'Isosceles Triangle' : 'Scalene Triangle'
end
end
# Return Not a triangle if the condition fails
return 'Not a triangle'
end
# Test with integers
puts triangle_type([4,1,2,5]) # output: Not a triangle
puts triangle_type([3,3,3]) # output: Equilateral Triangle
puts triangle_type([4,3,3]) # output: Isosceles Triangle
puts triangle_type([4,2,3]) # output: Scalene Triangle
# Test with strings
puts triangle_type(['4','1','2','5']) # output: Not a triangle
puts triangle_type(['3','3','3']) # output: Equilateral Triangle
puts triangle_type(['4','3','3']) # output: Isosceles Triangle
puts triangle_type(['4','2','3']) # output: Scalene Triangle
puts triangle_type(['a','a','a']) # output: Equilateral Triangle
puts triangle_type(['a','c','c']) # output: Isosceles Triangle
puts triangle_type(['a','b','c']) # output: Scalene Triangle
Skipping user inputs, since I can not reproduce the error (even if Unihedron found a fix) there is still a problem with the logic.
When the input is a = 1000, b = 1, c = 1, the result is "scalene triangle", but it should return "invalid". Below a fix I suggest.
Let's store the input in an array (already converted into integer or float):
sides = [a, b, c]
First you need to check that all sides are positive:
sides.all? { |x| x > 0 }
Then, check that the sum of two sides is greater than the other:
sides.combination(2).map{ |x| x.sum }.zip(sides.reverse).all? { |xy, z| xy > z }
Finally (I'm missing something?), to pick the triangle denomination you can use an hash accessing it by sides.uniq result:
triangle_kinds = {1 => 'equilateral', 2 => 'isosceles', 3 => 'scalene'}
triangle_kinds[sides.uniq.size]
Used the following methods over array (enumerable):
https://ruby-doc.org/core-2.5.1/Enumerable.html#method-i-all-3F
https://ruby-doc.org/core-2.5.1/Array.html#method-i-combination
https://ruby-doc.org/core-2.5.1/Array.html#method-i-map
https://ruby-doc.org/core-2.5.1/Array.html#method-i-zip
https://ruby-doc.org/core-2.5.1/Array.html#method-i-reverse
https://ruby-doc.org/core-2.5.1/Array.html#method-i-sum
https://ruby-doc.org/core-2.5.1/Array.html#method-i-uniq
I'm a beginner in Ruby and I don't understand what this code is doing, could you explain it to me, please?
def a(n)
s = 0
for i in 0..n-1
s += i
end
s
end
def defines a method. Methods can be used to run the same code on different values. For example, lets say you wanted to get the square of a number:
def square(n)
n * n
end
Now I can do that with different values and I don't have to repeat n * n:
square(1) # => 1
square(2) # => 4
square(3) # => 9
= is an assignment.
s = 0 basically says, behind the name s, there is now a zero.
0..n-1 - constructs a range that holds all numbers between 0 and n - 1. For example:
puts (0..3).to_a
# 0
# 1
# 2
# 3
for assigns i each consecutive value of the range. It loops through all values. So first i is 0, then 1, then ... n - 1.
s += i is a shorthand for s = s + i. In other words, increments the existing value of s by i on each iteration.
The s at the end just says that the method (remember the thing we opened with def) will give you back the value of s. In other words - the sum we accumulated so far.
There is your programming lesson in 5 minutes.
This example isn't idiomatic Ruby code even if it is syntactically valid. Ruby hardly ever uses the for construct, iterators are more flexible. This might seem strange if you come from another language background where for is the backbone of many programs.
In any case, the program breaks down to this:
# Define a method called a which takes an argument n
def a(n)
# Assign 0 to the local variable s
s = 0
# For each value i in the range 0 through n minus one...
for i in 0..n-1
# ...add that value to s.
s += i
end
# The result of this method is s, the sum of those values.
s
end
The more Ruby way of expressing this is to use times:
def a(n)
s = 0
# Repeat this block n times, and in each iteration i will represent
# a value in the range 0 to n-1 in order.
n.times do |i|
s += i
end
s
end
That's just addressing the for issue. Already the code is more readable, mind you, where it's n.times do something. The do ... end block represents a chunk of code that's used for each iteration. Ruby blocks might be a little bewildering at first but understanding them is absolutely essential to being effective in Ruby.
Taking this one step further:
def a(n)
# For each element i in the range 0 to n-1...
(0..n-1).reduce |sum, i|
# ...add i to the sum and use that as the sum in the next round.
sum + i
end
end
The reduce method is one of the simple tools in Ruby that's quite potent if used effectively. It allows you to quickly spin through lists of things and compact them down to a single value, hence the name. It's also known as inject which is just an alias for the same thing.
You can also use short-hand for this:
def a(n)
# For each element in the range 0 to n-1, combine them with +
# and return that as the result of this method.
(0..n-1).reduce(&:+)
end
Where here &:+ is shorthand for { |a,b| a + b }, just as &:x would be short for { |a,b| a.x(b) }.
As you are a beginner in Ruby, let's start from the small slices.
0..n-1 => [0, n-1]. E.g. 0..3 => 0, 1, 2, 3 => [0, 3]
for i in 0.. n-1 => this is a for loop. i traverses [0, n-1].
s += i is same as s = s + i
So. Method a(n) initializes s = 0 then in the for loop i traverse [0, n - 1] and s = s + i
At the end of this method there is an s. Ruby omits key words return. so you can see it as return s
def a(n)
s = 0
for i in 0..n-1
s += i
end
s
end
is same as
def a(n)
s = 0
for i in 0..n-1
s = s + i
end
return s
end
a(4) = 0 + 1 + 2 + 3 = 6
Hope this is helpful.
The method a(n) calculates the sums of the first n natural numbers.
Example:
when n=4, then s = 0+1+2+3 = 6
Let's go symbol by symbol!
def a(n)
This is the start of a function definition, and you're defining the function a that takes a single parameter, n - all typical software stuff. Notably, you can define a function on other things, too:
foo = "foo"
def foo.bar
"bar"
end
foo.bar() # "bar"
"foo".bar # NoMethodError
Next line:
s = 0
In this line, you're both declaring the variable s, and setting it's initial value to 0. Also typical programming stuff.
Notably, the value of the entire expression; s = 0, is the value of s after the assignment:
s = 0
r = t = s += 1 # You can think: r = (t = (s += 1) )
# r and t are now 1
Next line:
for i in 0..n-1
This is starting a loop; specifically a for ... in ... loop. This one a little harder to unpack, but the entire statement is basically: "for each integer between 0 and n-1, assign that number to i and then do something". In fact, in Ruby, another way to write this line is:
(0..n-1).each do |i|
This line and your line are exactly the same.
For single line loops, you can use { and } instead of do and end:
(0..n-1).each{|i| s += i }
This line and your for loop are exactly the same.
(0..n-1) is a range. Ranges are super fun! You can use a lot of things to make up a range, particularly, time:
(Time.now..Time.new(2017, 1, 1)) # Now, until Jan 1st in 2017
You can also change the "step size", so that instead of every integer, it's, say, every 1/10:
(0..5).step(0.1).to_a # [0.0, 0.1, 0.2, ...]
Also, you can make the range exclude the last value:
(0..5).to_a # [0, 1, 2, 3, 4, 5]
(0...5).to_a # [0, 1, 2, 3, 4]
Next line!
s += i
Usually read aloud a "plus-equals". It's literally the same as: s = s + 1. AFAIK, almost every operator in Ruby can be paired up this way:
s = 5
s -= 2 # 3
s *= 4 # 12
s /= 2 # 6
s %= 4 # 2
# etc
Final lines (we'll take these as a group):
end
s
end
The "blocks" (groups of code) that are started by def and for need to be ended, that's what you're doing here.
But also!
Everything in Ruby has a value. Every expression has a value (including assignment, as you saw with line 2), and every block of code. The default value of a block is the value of the last expression in that block.
For your function, the last expression is simply s, and so the value of the expression is the value of s, after all is said and done. This is literally the same as:
return s
end
For the loop, it's weirder - it ends up being the evaluated range.
This example may make it clearer:
n = 5
s = 0
x = for i in (0..n-1)
s += i
end
# x is (0..4)
To recap, another way to write you function is:
def a(n)
s = 0
(0..n-1).each{ |i| s = s + i }
return s
end
Questions?
def num_repeats(string)
letters = string.chars
idx = 0
n = 1
arr = []
lettercount = 0
while idx < letters.length
lettercount = 0
while n < letters.length
if letters[idx] == letters[n]
lettercount = 1
end
n+=1
end
if lettercount > 0
arr.push(idx)
end
idx += 1
end
return arr.length
end
puts(num_repeats("abdbccc"))
# == 2 since 2 letters are repeated across the string of characters
I keep getting zero, although as i see it if a number is repeated the value of numbercount should shift from zero to one and then allow some value to get pushed into the array where I later get the length of said array to determine the number of repeated characters. Is there an issue with my loops?
UPDATE
If you really want to use the same kind of code and algorithm to do that, then here are the problems of it :
In your second while loop the variable n is supposed to start from idx+1, considering you are trying to pick up an index and then find whether the character at that index is repeated somewhere after the index.
But even if you fix that you will get 3 for abdbccc. That kinda shows that your algorithm is wrong. When there are more than 2 occurrences of a repeated character, just like the process I said in the above para, you do that for every such character except for the last one, without checking whether the character had already been detected for repetition. Illustration :
str = 'aaa'
When idx = 0, you get str[idx] == str[n=1], adds it to the result.
When idx = 1, you get str[idx] == str[n=2], adds it to the result.
Now you counted a twice for repetition. I think you can fix that alone.
I think you are just trying to do the same as this (assumes you need to check lower case letters only) :
str = "abdbccc"
('a'..'z').count { |x| str.count(x) > 1 }
# => 2
Or if you need to check the number of repeated characters for any character :
str = "12233aabc"
str.chars.group_by(&:to_s).count do |k, v|
v.size > 1
end
# => 3
It's Ruby we are talking about. It's not really a good idea to write code like that in Ruby, I mean you are using a lot of while loops and manually tracking down their counters, while in Ruby you usually do not have to deal with those, considering all the convenient, less error-prone and shorter alternatives Ruby provides. I think you have a C like background, I recommend that you learn more of Ruby and Ruby way of doing things.
Didn't understood what you were trying to do, maybe you could use a hash to assist:
def num_repeats(string)
letters = string.chars
counter_hash = Hash.new(0)
letters.each { |l| counter_hash[l] += 1 }
counter_hash
end
You have this inner loop
while n < letters.length
if letters[idx] == letters[n]
lettercount = 1
end
n+=1
But nowhere are you resetting n, so after this loop has scanned once, it will skip past every subsequent time
You can mostly fix that by setting n to idx + 1 here
while idx < letters.length
lettercount = 0
n = idx + 1
while n < letters.length
You still will get a result of 3 because you are not detecting that c has already been counted
You can fix this final problem with a couple more tweaks
def num_repeats(string)
letters = string.chars
idx = 0
arr = []
lettercount = 0
while idx < letters.length
lettercount = 0
n = idx + 1 # <== start looking after idx char
while n < letters.length
if letters[idx] == letters[n]
lettercount += 1 # <== incrementing here
end
n+=1
end
if lettercount == 1 # <== check for exactly one
arr.push(idx)
end
idx += 1
end
return arr.length
end
This works because now lettercount == 2 for the first c so the duplicate is not counted until you get to the second c where lettercount == 1
This is still considered a poor solution as it has O(n**2) complexity. There are solutions - for example using Hash which are O(n)
I try to implement shell sort by ruby.
def shell_sort(list)
d = list.length
return -1 if d == 0
(0...list.length).each do |i|
d = d / 2
puts "d:#{d}"
(0...(list.length-d)).each do |j|
if list[j] >= list[j+d]
list[j], list[j+d] = list[j+d], list[j]
end
end
puts list.inspect
break if d == 1
end
list
end
puts shell_sort([10,9,8,7,6,5,4,3,2,1]).inspect
but the result is incorrect.
=>[2, 1, 3, 4, 5, 7, 6, 8, 9, 10]
I don't know where going wrong, hope someone can help me. Thanks in advance!
I referenced Shell Sort in here : Shell Sort - Wikepedia, and from that I have understood your algorithm is wrong. Iteration of gap sequence is alright, I mean you iterate only upto d/2 == 1.
But for a gap, let's say 2, you simply iterate from 0 to list.length-2 and swap every j and j+2 elements if list[j] is greater than list[j+2]. That isn't even a proper insertion sort, and Shell Sort requires Insertion sorts on gaps. Also Shell Sort requires that after you do an x gap sort, every xth element, starting from anywhere will be sorted (see the example run on the link and you can verify yourself).
A case where it can wrong in a 2 gap sort pass :
list = 5,4,3,2,1
j = 0 passed :
list = 3,4,5,2,1
j = 1 passed :
list = 3,2,5,4,1
j = 2 passed
list = 3,2,1,4,5
After it completes, you can see that every 2nd element starting from 0 isn't in a sorted order. I suggest that you learn Insertion Sort first, then understand where and how it is used in Shell Sort, and try again, if you want to do it by yourself.
Anyway, I have written one (save it for later if you want) taking your method as a base, with a lot of comments. Hope you get the idea through this. Also tried to make the outputs clarify the how the algorithm works.
def shell_sort(list)
d = list.length
return -1 if d == 0
# You select and iterate over your gap sequence here.
until d/2 == 0 do
d = d / 2
# Now you pick up an index i, and make sure every dth element,
# starting from i is sorted.
# i = 0
# while i < list.length do
0.step(list.length) do |i|
# Okay we picked up index i. Now it's just plain insertion sort.
# Only difference is that we take elements with constant gap,
# rather than taking them up serially.
# igap = i + d
# while igap < list.length do
(i+d).step(list.length-1, d) do |igap|
# Just like insertion sort, we take up the last most value.
# So that we can shift values greater than list[igap] to its side,
# and assign it to a proper position we find for it later.
temp = list[igap]
j = igap
while j >= i do
break if list[j] >= list[j - d]
list[j] = list[j-d]
j -= d
end
# Okay this is where it belongs.
list[j] = temp
#igap += d
end
# i += 1
end
puts "#{d} sort done, the list now : "
puts list.inspect
end
list
end
list = [10,9,8,7,6,5,4,3,2,1]
puts "List before sort : "
puts list.inspect
shell_sort(list)
puts "Sorted list : "
puts list.inspect
I think your algorithm needs a little tweaking.
The reason it fails is simply because on the last run (when d == 1) the smallest element (1) isn't near enough the first element to swap it in in one go.
The easiest way to make it work is to "restart" your inner loop whenever elements switch places. So, a little bit rough solution would be something like
(0...(list.length-d)).each do |j|
if list[j] >= list[j+d]
list[j], list[j+d] = list[j+d], list[j]
d *= 2
break
end
end
This solution is of course far from optimal, but should achieve required results with as little code as possible.
You should just do a last run on array. To simplify your code I extracted exchange part into standalone fucntion so you could see now where you should do this:
def exchange e, list
(0...(list.length-e)).each do |j|
if list[j] >= list[j+e]
list[j], list[j+e] = list[j+e], list[j]
end
end
end
def shell_sort(list)
d = list.length
return -1 if d == 0
(0...list.length).each do |i|
d = d / 2
puts "d:#{d}"
exchange(d, list)
puts list.inspect
if d == 1
exchange(d, list)
break
end
end
list
end
arr = [10,9,8,7,6,5,4,3,2,1]
p shell_sort(arr)
Result:
#> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I am trying to create a ruby program where three numbers are entered and their sum is taken but if any numbers are the same they don't count toward the sum.
example (4,5,4) = 5
My problem is with my expressions. If i enter the same number I get multiple output for various combination. example enter 5,5,5 = 15,5,0
if a != b or c then
puts a+b+c
elsif b != a or c then
puts a+b+c
elsif c != a or b then
puts a+b+c
end
if a == b then
puts c
elsif a == c then
puts b
elsif b == c then
puts a
end
if a == b and c then
puts 0
elsif b == a and c then
puts 0
elsif c == a and b then
puts 0
end
Solving it with two beautiful self explanatory one-liners
array = [a,b,c]
array = array.keep_if {|item| array.count(item) == 1 }
array.inject(0){|sum,item| sum + item}
-The first line creates an array with your parameters.
-The second line only keep the items whose count equals to 1 (remove the ones that appear more than one time), and store that on the array.
-The third line sums all the remaining elements.
Voilà, the ruby way :)