Advertisement
Guest User

Untitled

a guest
Apr 28th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. implicit class RichInt(n: Int) { def ! : Int = (1 to n).product }
  2. def sum(x: Int) = x * (x + 1) / 2
  3.  
  4. def combination[T](set: Set[T], size: Int): Set[Set[T]] = {
  5. def solve[T](list: List[T], size: Int): Set[Set[T]] = {
  6. if(list.size < size) {
  7. Set.empty[Set[T]]
  8. } else {
  9. if(size == 0) {
  10. Set(Set.empty[T])
  11. } else if(size == 1) {
  12. list.map(item => Set(item)).toSet
  13. } else {
  14. def loop(remain: List[T], set: Set[Set[T]] = Set.empty[Set[T]]): Set[Set[T]] = {
  15. remain match {
  16. case Nil => set
  17. case item :: remain if remain.size < size - 1 => set
  18. case item :: remain =>
  19. loop(remain, set ++ solve(remain, size - 1).map(set => set + item))
  20. }
  21. }
  22. loop(list)
  23. }
  24. }
  25. }
  26. solve(set.toList, size)
  27. }
  28.  
  29. def coefficient(n: Int, order: Int): Int = {
  30. val numbers = (1 to n).toSet
  31. combination(numbers, n - order).toList.map(set => set.product).sum
  32. }
  33.  
  34. def toFormula(cs: List[Int]): String = cs.zipWithIndex.reverse.map {
  35. case (c, 0) => s"$c"
  36. case (1, o) => s"x ^ $o"
  37. case (c, o) => s"$c * x^$o"
  38. }.mkString(" + ")
  39.  
  40. def toFormula(cs: List[Double]): String = cs.zipWithIndex.reverse.map {
  41. case (c, 0.0) => s"$c"
  42. case (1.0, o) => s"x ^ $o"
  43. case (c, o) => s"$c * x^$o"
  44. }.mkString(" + ")
  45.  
  46. def coefficients(n: Int): (List[Int], Int) = {
  47. val product = n !
  48.  
  49. val cs = (product :: (1 to n).toList.map {
  50. o => coefficient(n, o)
  51. })
  52.  
  53. (cs.toList, product)
  54. }
  55.  
  56. (1 to 10).map { n =>
  57. val cs = coefficients(n) match {
  58. case (cs, p) => cs.map{ c => c.doubleValue / p }
  59. }
  60. toFormula(cs)
  61. } .foreach(println)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement