Ruby and a Math Problem - ruby

Let's say I have to have a cart with a subtotal of 1836.36. I must achieve this exact amount by adding up several products from a list with a range of prices.
Say, I have a few products at 9.99, 29.99, 59.99 and I can add several of each to meet the desired subtotal. How would one approach this problem using Ruby?
I've thought of feeding the list of prices into a script and somehow getting the script to add until it reaches the subtotal and then spit out the prices required to reach the subtotal... just not sure how to approach it.
Any suggestions are welcome and thanks in advance. Looking forward to ideas.

9.99*x + 29.99*y + 59.99*z = 1836.36
brute force iterate through all the permutations of x,y,z within a range of integers
For example:
(0..9).each do |x|
(0..9).each do |y|
(0..9).each do |z|
puts "x #{x} y #{y} z #{z}" if (x * 9.99 + y * 29.99 + z * 59.99 == 1836.36)
end
end
end
discard any answer whose sum is not 1835.36.
Something like that... haven't tested it. You could probably tweak and optimize it to ignore cases that would certainly fail to pass.

Related

How could I DRY this while loop?

I need to DRY this code but I don't know how.
I tried to dry the if condition but I don't know how to put the while in this.
def sum_with_while(min, max)
# CONSTRAINT: you should use a while..end structure
array = (min..max).to_a
sum = 0
count = 0
if min > max
return -1
else
while count < array.length
sum += array[count]
count += 1
end
end
return sum
end
Welcome to stack overflow!
Firstly, I should point out that "DRY" stands for "Don't Repeat Yourself". Since there's no repetition here, that's not really the problem with this code.
The biggest issue here is it's unrubyish. The ruby community has certain things it approves of, and certain things it avoids. That said, while loops are themselves considered bad ruby, so if you've been told to write it with a while loop, I'm guessing you're trying to get us to do your homework for you.
So I'm going to give you a couple of things to do a web search for that will help start you off:
ruby guard clauses - this will reduce your if-else-end into a simple if
ruby array pop - you can do while item = array.pop - since pop returns nil once the array is empty, you don't need a count. Again, bad ruby to do this... but maybe consider while array.any?
ruby implicit method return - generally we avoid commands we don't need
It's worth noting that using the techniques above, you can get the content of the method down to 7 reasonably readable lines. If you're allowed to use .inject or .sum instead of while, this whole method becomes 2 lines.
(as HP_hovercraft points out, the ternary operator reduces this down to 1 line. On production code, I'd be tempted to leave it as 2 lines for readability - but that's just personal preference)
You can put the whole thing in one line with a ternary:
def sum_with_while(min, max)
min > max ? -1 : [*(min..max)].inject(0){|sum,x| sum + x }
end
This is one option, cleaning up your code, see comments:
def sum_with_while(range) # pass a range
array = range.to_a
sum, count = 0, 0 # parallel assignment
while count < array.length
sum += array[count]
count += 1
end
sum # no need to return
end
sum_with_while(10..20)
#=> 165
More Rubyish:
(min..max).sum
Rule 1: Choose the right algorithm.
You wish to compute an arithmetic series.1
def sum_with_while(min, max)
max >= min ? (max-min+1)*(min+max)/2 : -1
end
sum_with_while(4, 4)
#=> 4
sum_with_while(4, 6)
#=> 15
sum_with_while(101, 9999999999999)
#=> 49999999999994999999994950
1. An arithmetic series is the sum of the elements of an arithmetic sequence. Each term of the latter is computed from the previous one by adding a fixed constant n (possibly negative). Heremax-min+1 is the number of terms in the sequence and (min+max)/2, if (min+max) is even, is the average of the values in the sequence. As (max-min+1)*(min+max) is even, this works when (min+max) is odd as well.

how does this checks surrounding cells in a 2D array

I am attempting to write a battleship game in ruby. I came across a code snippet that I think I grasp, but was hoping you all could maybe offer some clarification. The [-1,0,1] is what is throwing me. This is to check a 2D array. Thank you for your help as always.
def neighbors
#neighbors ||= [-1, 0, 1].repeated_permutation(2).map do |dx, dy|
#grid[x + dx, y + dy] unless dx.zero? && dy.zero?
end.compact
end
I think I may have figured it out finally. The repeated_permutation(2) takes to of the values in the [-1,0,1] to search around the "cell" in question.
What ||= means is if #neighbors responds to a nil (NilClass) object type or false (FalseClass) object value, it will take the value which you're assigning in the right side, that's to say the result of:
[-1, 0, 1].repeated_permutation(2).map do |dx, dy|
#grid[x + dx, y + dy] unless dx.zero? && dy.zero?
end.compact
To use ||= is like to use x || x = a or maybe x = a unless x, but in the Ruby way to be simple to read, simple to understand, simple to work with.
And what the [-1, 0, 1].repeated_permutation(2).map is trying to do is to map the result of a repeated_permutation over the [-1, 0, 1] array and to take the first and second value within the permutation, and to set your #grid variable probably (because I can't say what's #grid) as a range starting in the sum of dx plus x and then dy plus y unless the value of dx and dy are 0 at the same time (&&). Then compact the "mapped" result.
You might want to see Array#repeated_permutation and Array#permutation
Quick & dirty permutations are like minor changes to a series of numbers ([link to more indepth])1. What you're looking at is the array with being altered by the .repeated_permutations to find all options for each value & the results then being added to the original x & y coords...
The ||= & the unless parts are just checks to ensure the code doesn't run on 0's ...

How to get the randrange equivalent of python in Ruby

I want to get a random value between 0 and 20 but skips by 3, like the python equivalent of:
random.randrange(0,20, 3)
Here's a one-liner:
(0...20).to_a.keep_if {|z| z % 3 == 0}.sample
And bjhaid's example will work if you make the top number the first number that is equal or greater that is divisible by 3, i.e.:
rand(21 / 3) * 3
But you would have to manually set that upper number depending on what your slice size and upper number are.
My one-liner is kind of ugly to me, if I were using it in just one place in an entire program I might use it. but if I was going to re-use it I'd make a method: edit I just noticed #cremno answer in the comments. I like their step version better than mine. I'd use that in a method:
def randrange(lower, upper, grouping)
(lower...upper).step(grouping).to_a.sample
end
my old method...
def randrange(lower, upper, grouping)
arr = (lower...upper).to_a.keep_if {|i| i % grouping == 0}
arr.sample
end

Iteration order

I'm working on Project Euler problem #4:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
My code as follows is wrong:
def ispalindrome?(number)
number.to_s == number.to_s.reverse
end
palindromes = []
(100..999).each { |x|
(100..999).each { |y|
palindromes.push (x * y) if ispalindrome?(x * y)
}
}
palindromes.last # => 580085
What's going on here?
This has nothing to do with ruby. Simple math :)
Replace palindromes.last with palindromes.max
As someone else said, replacing palindromes.last with palindromes.max will work.
The reason is that, as products of three-digit numbers, 580085 = 995 * 583 and 906609 = 993 * 913.
Think carefully about the order in which you consider pairs of x and y. If you consider (993, 913) and then later (995, 583) (as happens in the first and third examples), then the last palindrome found will be 580085.
You just forgot to sort your array before taking the value, I used your code from the first try just added
palindromes.sort
and it gave me 906609
The problem is that you are not returning the biggest number but the last number that was added , and it depends on the order you loop through the numbers.
you need to change your last command to:
puts palindromes.max

All possible products

I'm trying to find all possible product of two 3-digit numbers. When I work with small ranges, I'm able to get an output in short amount of time but when the ranges are big, it seems to take really long time. Is there any way to to shorten the time to get the result?
The problem I'm working on is:
"A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers."
a = []
for x in 100..999
for y in 100..999
num = (x * y)
unless a.include? num
a.push num
end
end
end
p a
This is going to compute 100 x 101 and 101 x 100 separately, even though they're not going to be pushed to the array since they're already in it.
I'm bad at math, but maybe every time x goes up, y's minimum range can go up since that one was just used? people who are better at math can tell me if this is going to start missing numbers.
z= 100
for x in 100..999
for y in z..999
num = (x * y)
unless a.include? num
a.push num
end
z = z+1
end
end
I think doing this might make the "unless a.include? num" line unnecessary, too.
Looking at your code a quick optimization you can make is to use a set rather than an array to store the already computed products.
Since a is an array, a.include?(num) will have to iterate through the entire list of elements before returning true / false.
If a were to be a set, a.include?(num) will return in sub linear time.
Example:
require 'set'
a = Set.new
for x in 100..999
for y in 100..999
num = (x * y)
unless a.include? num
a.add(num)
end
end
end
puts a.to_a.join(", ")
Moreover one of the nice properties of a set is that it only stores unique elements so the following would be equivalent:
require 'set'
a = Set.new
for x in 100..999
for y in 100..999
num = (x * y)
a.add(num)
end
end
puts a.to_a.join(", ")
What are you really trying to do, i.e. what is the original problem, and why do you need all of these products?
Are you printing every single one out? Is someone asking you for a concrete list of every single one?
If not, there is likely a better way to deal with this problem. For example, if all you wanted is to check if a number X will be an element in "that list of products", all you'd have to do is:
range = 100..999
range.any? { |i| range.include?(x / i) }

Resources