Ruby Pascal's triangle generator with memoization - ruby

I am attempting to memoize my implementation of a Pascal's triangle generator, as a Ruby learning experiment. I have the following working code:
module PascalMemo
#cache = {}
def PascalMemo::get(r,c)
if #cache[[r,c]].nil? then
if c == 0 || c == r then
#cache[[r,c]] = 1
else
#cache[[r,c]] = PascalMemo::get(r - 1, c) + PascalMemo::get(r - 1, c - 1)
end
end
#cache[[r,c]]
end
end
def pascal_memo (r,c)
PascalMemo::get(r,c)
end
Can this be made more concise? Specifically, can I create a globally-scoped function with a local closure more simply than this?

def pascal_memo
cache = [[1]]
get = lambda { |r, c|
( cache[r] or cache[r] = [1] + [nil] * (r - 1) + [1] )[c] or
cache[r][c] = get.(r - 1, c) + get.(r - 1, c - 1)
}
end
p = pascal_memo
p.( 10, 7 ) #=> 120
Please note that the above construct does achieve memoization, it is not just a simple recursive method.

Can this be made more concise?
It seems pretty clear, IMO, and moduleing is usually a good instinct.
can I create a globally-scoped function with a local closure more simply than this?
Another option would be a recursive lambda:
memo = {}
pascal_memo = lambda do |r, c|
if memo[[r,c]].nil?
if c == 0 || c == r
memo[[r,c]] = 1
else
memo[[r,c]] = pascal_memo[r - 1, c] + pascal_memo[r - 1, c - 1]
end
end
memo[[r,c]]
end
pascal_memo[10, 2]
# => 45

I have found a way to accomplish what I want that is slightly more satisfactory, since it produces a function rather than a lambda:
class << self
cache = {}
define_method :pascal_memo do |r,c|
cache[[r,c]] or
(if c == 0 or c == r then cache[[r,c]] = 1 else nil end) or
cache[[r,c]] = pascal_memo(r-1,c) + pascal_memo(r-1,c-1)
end
end
This opens up the metaclass/singleton class for the main object, then uses define_method to add a new method that closes over the cache variable, which then falls out of scope for everything except the pascal_memo method.

Related

How to optimize code - it works, but I know I'm missing much learning

The exercise I'm working on asks "Write a method, coprime?(num_1, num_2), that accepts two numbers as args. The method should return true if the only common divisor between the two numbers is 1."
I've written a method to complete the task, first by finding all the factors then sorting them and looking for duplicates. But I'm looking for suggestions on areas I should consider to optimize it.
The code works, but it is just not clean.
def factors(num)
return (1..num).select { |n| num % n == 0}
end
def coprime?(num_1, num_2)
num_1_factors = factors(num_1)
num_2_factors = factors(num_2)
all_factors = num_1_factors + num_2_factors
new = all_factors.sort
dups = 0
new.each_index do |i|
dups += 1 if new[i] == new[i+1]
end
if dups > 1
false
else
true
end
end
p coprime?(25, 12) # => true
p coprime?(7, 11) # => true
p coprime?(30, 9) # => false
p coprime?(6, 24) # => false
You could use Euclid's algorithm to find the GCD, then check whether it's 1.
def gcd a, b
while a % b != 0
a, b = b, a % b
end
return b
end
def coprime? a, b
gcd(a, b) == 1
end
p coprime?(25, 12) # => true
p coprime?(7, 11) # => true
p coprime?(30, 9) # => false
p coprime?(6, 24) # => false```
You can just use Integer#gcd:
def coprime?(num_1, num_2)
num_1.gcd(num_2) == 1
end
You don't need to compare all the factors, just the prime ones. Ruby does come with a Prime class
require 'prime'
def prime_numbers(num_1, num_2)
Prime.each([num_1, num_2].max / 2).map(&:itself)
end
def factors(num, prime_numbers)
prime_numbers.select {|n| num % n == 0}
end
def coprime?(num_1, num_2)
prime_numbers = prime_numbers(num_1, num_2)
# & returns the intersection of 2 arrays (https://stackoverflow.com/a/5678143)
(factors(num_1, prime_numbers) & factors(num_2, prime_numbers)).length == 0
end

What is the correct way to write this in Ruby?

I am needing to write few methods: value(x), zero(a,b,e), area(a,b), derivative(x)
class Funkcja
def initialize(funkcja)
#funkcja = funkcja
end
def value(x)
#funkcja.call(x)
end
end
This class will have to work over block which is an object from Proc
This is how I create that new object
f = Funkcja.new (Proc.new{|x| x*x*Math.sin(x)})
What is the correct way and in Ruby style (if not please show me that i
newbie in Ruby) to do this right Funkcja.new (Proc.new x) and
initialize #funkcja = funkcja
def zero(a, b, eps)
x = (a+b)/2.0
val = value(x)
if val >= -eps and val <= eps
x
else
left = value(a)
rigth = value(b)
if left < 0 and val > 0
zero(a,x,eps)
elsif left > 0 and val < 0
zero(a,x,eps)
elsif rigth > 0 and val < 0
zero(x,b,eps)
elsif rigth < 0 and val > 0
zero(x,b,eps)
elsif value == 0
x
else
nil
end
end
end
def area(a,b)
pole = 0
while a < b
if (self.value(a) > self.value( a + 0.00001))
pole = pole + (self.value( a) * 0.00001)
else
pole = pole + (self.value( a + 0.00001) * 0.00001 )
end
a += 0.00001
end
pole
end
def derivative(x)
eps = 0.00000001
return (self.value(x) - self.value(x - eps))/eps
end
Area is calculated area between a and b and OX, zero is find where
F (x)=0 derivative is calculated as derivative in point.
The main thing that's non-idiomatic is this:
f = Funkcja.new (Proc.new{|x| x*x*Math.sin(x)})
What would be more normal is to do this:
f = Funkcja.new { |x| x*x*Math.sin(x) }
This is a normal block, and you could split it up among multiple lines as usual:
f = Funkcja.new do |x|
x*x*Math.sin(x)
end
However, this wouldn't work with your initialize definition and that's because of one minor detail. You'd just need to change def initialize(funkcja) to def initialize(&funkja) - this converts the passed block into a proc that you can assign to a variable, use call with, etc:
def initialize(&funjka)
#funkja = funkja
end
Another way to do the same thing would be this:
def initialize
#funkja = yield
end
Other than that, your code seems fine with one other glaring non-idiomatic thing, which that you use self.value. The self is unnecessary unless you're using a setter method (i.e. self.value =), which you're not here.
Here's an idea of adapting one of your methods to a more Ruby style:
def area(a,b)
pole = 0
while a < b
if (yield(a) > yield(a + 0.00001))
pole = pole + (yield(a) * 0.00001)
else
pole = pole + (yield(a + 0.00001) * 0.00001)
end
a += 0.00001
end
pole
end
You'd use it like this:
area(a, b) do |a|
a ** 2
end
Now it's one thing to be handling Proc objects, that's fine, the do ... end method of appending blocks to method calls generates those by default. It's very not Ruby to put extra methods on Proc itself. I can't see anything here that can't be covered by defining these inside a simple module:
module CalculationModule
def area(a, b)
# ... Implementation
end
extend self
end
That way you can use those methods like CalculationModule.area or you can always include it into another class or module and use them like area.

Ruby parallel sorting

I am trying to create a multithreaded version of a sorting algorithm. I do not understand why this algorithm always returns just Array[1] instead of the full array.
class Array
def quick_sort
return self if self.length <= 1
pivot = self[0]
if block_given?
less, greater_equals = self[1..-1].partition { yield(x, pivot) }
else
less, greater_equals = self[1..-1].partition { |x| x < pivot }
end
l = []
g = []
Process.fork {l = less.quick_sort }
Process.fork {g = greater_equals.quick_sort}
Process.waitall
return l + [pivot] + g
end
end
The local variables l and g are not passed beyond Process.fork. They are only valid within that block. For example,
Process.fork{a = 2}
Process.wait
a #=> NameError: undefined local variable or method `a' for main:Object
In your code, the l and g assignments done before Process.fork are still valid when you call return l + [pivot] + g.
By the way, if you had intended l and g to be passed from Process.fork, then your initialization of these variables prior to Process.fork is meaningless.
From you examples it looks like you are trying to use Process where you actually want to use a thread.
Process: no shared resources with itś caller (Parent)
Thread: shares memory with its Parent
Your example would work if you replaced the Process.fork with Threads:
l = []
g = []
left_thread = Thread.new {l = less.quick_sort }
right_thread = Thread.new {g = greater_equals.quick_sort}
left_thread.join
right_thread.join
return l. + [pivot] + g

recursion method inside ruby minesweeper game stack level too deep

I am triggering endless recursion when trying to make a method that pulls up tiles when they are a zero. I have been testing by entering the following in irb:
class Board
attr_accessor :size, :board
def initialize(size = gets.chomp.to_i)
#size = size
#board = (1..#size).map { |x| ["L"] * #size }
end
def print_board
#board.map { |row| puts row.join }
end
end
class Mine
attr_accessor :proxi, :row, :col
def initialize(proxi)
#proxi = proxi
#row = 0
#col = 0
#random = Random.new
check_position
end
def check_position
if #proxi.board[#row - 1][#col - 1] != "L"
#row = #random.rand(1..#proxi.board.length)
#col = #random.rand(1..#proxi.board[0].length)
check_position
else
map_position
end
end
def map_position
#proxi.board[#row - 1][#col - 1] = "*"
end
end
b = Board.new(20)
m = (1..b.size * 2).map { |i| i = Mine.new(b) }
class Detector
attr_accessor :board, :proxi, :row, :col, :value
def initialize(board, proxi)
#board = board
#proxi = proxi
#row = 0
#col = 0
#value = 0
end
def mine?
if #proxi.board[#row - 1][#col - 1] == "*"
true
else
false
end
end
def detect
(#row - 1..#row + 1).each do |r|
(#col - 1..#col + 1).each do |c|
unless (r - 1 < 0 || r - 1 > #proxi.size - 1) || (c - 1 < 0 || c - 1 > #proxi.size - 1)
#value += 1 if #proxi.board[r - 1][c - 1] == "*"
end
end
end
end
def map_position
#proxi.board[#row - 1][#col - 1] = #value
#board.board[#row - 1][#col - 1] = #value
end
def recursion
if #proxi.board[#row - 1][#col - 1] == 0
(#row - 1..#row + 1).each do |r|
(#col - 1..#col + 1).each do |c|
unless (r - 1 < 0 || r - 1 > #proxi.size - 1) || (c - 1 < 0 || c - 1 > #proxi.size - 1)
#row, #col = r, c
detect
map_position
recursion
end
end
end
end
end
def reset
#row, #col, #value = 0, 0, 0
end
end
d = Detector.new(b, b)
b.print_board
If the output has plenty of free space in the upper right corner proceed to pasting the next part, else repaste.
d.row = 1
d.col = 1
d.mine?
d.detect
d.map_position
d.recursion
b.print_board
It will error out with a stack level too deep error at the recursion method. I know this is because it is having issues ending the recursive pattern. I thought my two unless statements deterring it from searching off the board would limit it to the area in the board. Plus the mines would force it to be limited in zeros it can expose. Maybe it is somehow writing spaces off the board or overwriting things on the board?
You don’t need a recursion here. Simply check each position for mines around:
Please always use 0-based arrays to eliminate lots of #blah - 1.
In detect you need to return immediately if there is a mine and set the #value otherwise:
def detect
return if #proxi.board[#row][#col] == '*'
value = 0 # no need to be global anymore
(#row - 1..#row + 1).each do |r|
(#col - 1..#col + 1).each do |c|
unless r < 0 || r >= #proxi.size || c < 0 || c >= #proxi.size
value += 1 if #proxi.board[r][c] == "*"
end
end
end
#proxi.board[#row][#col] = value
end
Now you don’t need map_position method at all. Simply check all the cells:
def check
(0..#proxi.size - 1).each do |r|
(0..#proxi.size - 1).each do |c|
#row, #col = r, c
detect
end
end
end
Hope it helps.
Exceeding the stack size is usually an indication that your recursion does not have the correct terminating condition. In your case, what mechanism is in place to prevent recursion from being called multiple times with the same #row #col pair? Note that of the 9 pairs that (#row - 1..#row + 1) (#col - 1..#col + 1) produce, one of those pairs is #row #col itself. The function will call itself infinitely many times!
A simple way to solve this would be to have something like a revealed array that keeps track of visited cells. Then recursion would mark each cell it visits as visited and return immediately if it is called on an already visited cell.
Additionally, your use of instance variables is extremely fragile here. Recursion relies on the fact that each function call has its own scope, but every call of recursion shares the same instance variables - which you're using to pass arguments! You should be using method arguments to keep the scopes distinct.

more ruby way of doing project euler #2

I'm trying to learn Ruby, and am going through some of the Project Euler problems. I solved problem number two as such:
def fib(n)
return n if n < 2
vals = [0, 1]
n.times do
vals.push(vals[-1]+vals[-2])
end
return vals.last
end
i = 1
s = 0
while((v = fib(i)) < 4_000_000)
s+=v if v%2==0
i+=1
end
puts s
While that works, it seems not very ruby-ish—I couldn't come up with any good purely Ruby answer like I could with the first one ( puts (0..999).inject{ |sum, n| n%3==0||n%5==0 ? sum : sum+n }).
For a nice solution, why don't you create a Fibonacci number generator, like Prime or the Triangular example I gave here.
From this, you can use the nice Enumerable methods to handle the problem. You might want to wonder if there is any pattern to the even Fibonacci numbers too.
Edit your question to post your solution...
Note: there are more efficient ways than enumerating them, but they require more math, won't be as clear as this and would only shine if the 4 million was much higher.
As demas' has posted a solution, here's a cleaned up version:
class Fibo
class << self
include Enumerable
def each
return to_enum unless block_given?
a = 0; b = 1
loop do
a, b = b, a + b
yield a
end
end
end
end
puts Fibo.take_while { |i| i < 4000000 }.
select(&:even?).
inject(:+)
My version based on Marc-André Lafortune's answer:
class Some
#a = 1
#b = 2
class << self
include Enumerable
def each
1.upto(Float::INFINITY) do |i|
#a, #b = #b, #a + #b
yield #b
end
end
end
end
puts Some.take_while { |i| i < 4000000 }.select { |n| n%2 ==0 }
.inject(0) { |sum, item| sum + item } + 2
def fib
first, second, sum = 1,2,0
while second < 4000000
sum += second if second.even?
first, second = second, first + second
end
puts sum
end
You don't need return vals.last. You can just do vals.last, because Ruby will return the last expression (I think that's the correct term) by default.
fibs = [0,1]
begin
fibs.push(fibs[-1]+fibs[-2])
end while not fibs[-1]+fibs[-2]>4000000
puts fibs.inject{ |sum, n| n%2==0 ? sum+n : sum }
Here's what I got. I really don't see a need to wrap this in a class. You could in a larger program surely, but in a single small script I find that to just create additional instructions for the interpreter. You could select even, instead of rejecting odd but its pretty much the same thing.
fib = Enumerator.new do |y|
a = b = 1
loop do
y << a
a, b = b, a + b
end
end
puts fib.take_while{|i| i < 4000000}
.reject{|x| x.odd?}
.inject(:+)
That's my approach. I know it can be less lines of code, but maybe you can take something from it.
class Fib
def first
#p0 = 0
#p1 = 1
1
end
def next
r =
if #p1 == 1
2
else
#p0 + #p1
end
#p0 = #p1
#p1 = r
r
end
end
c = Fib.new
f = c.first
r = 0
while (f=c.next) < 4_000_000
r += f if f%2==0
end
puts r
I am new to Ruby, but here is the answer I came up with.
x=1
y=2
array = [1,2]
dar = []
begin
z = x + y
if z % 2 == 0
a = z
dar << a
end
x = y
y = z
array << z
end while z < 4000000
dar.inject {:+}
puts "#{dar.sum}"
def fib_nums(num)
array = [1, 2]
sum = 0
until array[-2] > num
array.push(array[-1] + array[-2])
end
array.each{|x| sum += x if x.even?}
sum
end

Resources