Guest User

Untitled

a guest
Jul 18th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. def f(ms: List[Int], n: Int): Int = ms match {
  2. case h :: t =>
  3. if (h > n) 0 else if (n == h) 1 else f(ms, n - h) + f(t, n)
  4. case _ => 0
  5. }
  6. val r = f(List(1, 2, 5, 10, 20, 50, 100, 200), 200)
  7.  
  8. final static int TOTAL = 200;
  9.  
  10. public static void main(String[] args) {
  11. int[] coins = {1, 2, 5, 10, 20, 50, 100, 200};
  12. int[] ways = new int[TOTAL + 1];
  13. ways[0] = 1;
  14.  
  15. for (int coin : coins) {
  16. for (int j = coin; j <= TOTAL; j++) {
  17. ways[j] += ways[j - coin];
  18. }
  19. }
  20.  
  21. System.out.println("Result: " + ways[TOTAL]);
  22. }
  23.  
  24. class IterationForCoin(stream: Stream[Int], coin: Int) {
  25. val (lower, higher) = stream splitAt coin
  26. val next: Stream[Int] = lower #::: (higher zip next map { case (a, b) => a + b })
  27. }
  28. val coins = List(1, 2, 5, 10, 20, 50, 100, 200)
  29. val result = coins.foldLeft(1 #:: Stream.fill(200)(0)) { (stream, coin) =>
  30. new IterationForCoin(stream, coin).next
  31. } last
  32.  
  33. import scalaz._
  34. import Scalaz._
  35.  
  36. val memo = immutableHashMapMemo[(List[Int], Int), Int]
  37. def f(ms: List[Int], n: Int): Int = ms match {
  38. case h :: t =>
  39. if (h > n) 0 else if (n == h) 1 else memo((f _).tupled)(ms, n - h) + memo((f _).tupled)(t, n)
  40. case _ => 0
  41. }
  42. val r = f(List(1, 2, 5, 10, 20, 50, 100, 200), 200)
Add Comment
Please, Sign In to add comment