n (たとえば 3 人) と s (たとえば 100$ ) が与えられた場合、s を n 人に分割したいと思います。
したがって、合計が s になるすべての可能な n タプルが必要です。
以下の私のScalaコード:
def weights(n:Int,s:Int):List[List[Int]] = {
List.concat( (0 to s).toList.map(List.fill(n)(_)).flatten, (0 to s).toList).
combinations(n).filter(_.sum==s).map(_.permutations.toList).toList.flatten
}
println(weights(3,100))
これは n の値が小さい場合に機能します。( n=1、2、3 または 4)。
n=4 を超えると、非常に時間がかかり、実質的に使用できなくなります。
遅延評価/ストリームを使用してコードを作り直す方法を探しています。
私の要件:nから10まで動作する必要があります。
警告 : 問題は非常に急速に大きくなります。Matlab からの私の結果 -
---For s =100, n = 1 thru 5 results are ---
n=1 :1 combinations
n=2 :101 combinations
n=3 :5151 combinations
n=4 :176851 combinations
n=5: 4598126 combinations
---