Skip to content

Commit

Permalink
redo coinchange and equal
Browse files Browse the repository at this point in the history
  • Loading branch information
jonnymacs committed Aug 8, 2017
1 parent 6588c41 commit ddf76f9
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
16 changes: 16 additions & 0 deletions coinchange/prog1.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
n,m = gets.split(" ").map{|el| el.to_i }
c = gets.split(" ").map{|el| el.to_i }

# coin change forumula
# ways = ways to n with m-1 coins + ways to n - (c-1) with m coins

def ways(n, m, c, memo = {})
return 1 if n == 0
return 0 if n < 1 || m == 0
memo[n] ||= {}
return memo[n][m] if memo[n][m]
memo[n][m] = ways(n, m-1, c, memo) + ways(n - c[m-1], m, c, memo)
return memo[n][m]
end

puts ways(n, m, c)
17 changes: 17 additions & 0 deletions coinchange/prog1.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import Foundation
let line = readLine()!.components(separatedBy: " ").map{ Int($0)! }
let n = line[0]
let m = line[1]
let c = readLine()!.components(separatedBy: " ").map{ Int($0)! }

func ways(_ n: Int, _ m: Int, _ c: [Int], _ w: inout [Int:[Int:Int]]) -> Int {
if n == 0 { return 1 }
if n < 1 || m == 0 { return 0 }
if w[n] != nil && w[n]![m] != nil { return w[n]![m]! }
w[n] = w[n] ?? [Int:Int]()
w[n]![m] = ways(n, m-1, c, &w) + ways(n-c[m-1], m, c, &w)
return w[n]![m]!
}

var w = [Int:[Int:Int]]()
print("\(String(describing: ways(n,m,c,&w)))")
22 changes: 21 additions & 1 deletion equal/prog.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,32 @@
t.times do
@counter = nil
q = gets.to_i
# build a matrix of all the people and the number they have
folks = Matrix[gets.split(" ").map(&:to_i).sort]

# our target is the person(s) with the least number
# but we also have to check as many targets as we can give
# at one time (5 in this case)
targets = folks.first.downto(folks.first-4)

# for each target
targets.each do |target|
# build a matrix of length (num people)
# initialize to the target
#
least = Matrix[Array.new(q, target)]

# matrix subtraction - this gives us the number
# each person needs to get to be done
#
diff = folks - least
min = diff.map { |folk| folk/5 + (folk%5)/2 + (folk%5)%2 }.inject(&:+)

# count the min number of gives for each person
# and sum those
# we give 5 as many times as we can, then we give 2, then 1
min = diff.map { |need| need/5 + (need%5)/2 + (need%5)%2 }.inject(&:+)

# each target has a min. the target with the lowest min is the answer
@counter ||= min
@counter = @counter < min ? @counter : min
end
Expand Down

0 comments on commit ddf76f9

Please sign in to comment.