Algorithm to calculate the number of combinations to form 100

前端 未结 5 446
说谎
说谎 2020-12-08 23:13

I am struck in a tricky situation where I need to calculate the number of combinations to form 100 based on different factors.

Those are

  • Number of combin
5条回答
  •  死守一世寂寞
    2020-12-08 23:55

    I hope it's not a homework problem!

        def combinations(n: Int, step: Int, distance: Int, sum: Int = 100): List[List[Int]] =
          if (n == 1) 
            List(List(sum))
          else 
            for {
              first <- (step until sum by step).toList
              rest <- combinations(n - 1, step, distance, sum - first)
              if rest forall (x => (first - x).abs <= distance)
            } yield first :: rest
    

提交回复
热议问题