Skip to content

Instantly share code, notes, and snippets.

@jamessouth
Created February 14, 2022 04:05
Show Gist options
  • Save jamessouth/4198642afdf24bd26613660497bcef6e to your computer and use it in GitHub Desktop.
Save jamessouth/4198642afdf24bd26613660497bcef6e to your computer and use it in GitHub Desktop.
2nd coin problem solutions - OCaml and Go
// How many different ways can we make change of $1.00, given half-dollars,
// quarters, dimes, nickels, and pennies?
// -- from SICP 1.2.2
package main
import "fmt"
func coin2() int {
cnt := 0
for h := 0; h <= 2; h++ {
for q := 0; q <= 4; q++ {
for d := 0; d <= 10; d++ {
for n := 0; n <= 20; n++ {
for p := 0; p <= 100; p++ {
if (p*1)+(n*5)+(d*10)+(q*25)+(h*50) == 100 {
cnt++
}
}
}
}
}
}
return cnt
}
func main() {
fmt.Println(coin2())
}
// 292
(* How many different ways can we make change of $1.00, given half-dollars,
quarters, dimes, nickels, and pennies?
-- from SICP 1.2.2 *)
let rec count_change amt = function
| [] -> 0
| h::t -> if amt < 0 then 0 else if amt = 0 then 1 else count_change amt t
+ count_change (amt - h) (h::t);;
print_int (count_change 100 [50;25;10;5;1]) |> print_newline
(* 292 *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment