mirror of
https://github.com/RGBCube/nu_scripts
synced 2025-07-31 14:17:45 +00:00
add ways-to-add-up-to
to "math" module (#874)
at my job, i studied very quickly something that involved computing all the ways one can build a positive integer from the addition of other positive integers. enters the `ways-to-add-up-to` command i've written and added to the `math` module in this PR. ## example `ways-to-add-up-to 4` will be `[[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]]]` because $4$ can be obtained as follows: $$ 1 + 1 + 1 + 1 $$ $$ 1 + 1 + 2 = 1 + 2 + 1 = 2 + 1 + 1 $$ $$ 1 + 3 = 3 + 1 $$ $$ 2 + 2 $$ $$ 4 $$ > **Note** > $1 + 1 + 2$ and $1 + 2 + 1$ are considered the same because addition is _commutative_ and thus only `[1, 1, 2]` will be returned
This commit is contained in:
parent
8d8a865b38
commit
6aa2700730
1 changed files with 49 additions and 0 deletions
|
@ -238,3 +238,52 @@ def cartesian_product [] {
|
|||
[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6]
|
||||
]
|
||||
}
|
||||
|
||||
# `ways-to-add-up-to $n` is a list of all possible strictly-positive-integer sums that add up to `$n`
|
||||
#
|
||||
# # Example
|
||||
# `ways-to-add-up-to 4` will be `[[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]]]` because $4$
|
||||
# can be obtained as follows:
|
||||
# $$
|
||||
# 4 = 1 + 1 + 1 + 1
|
||||
# = 1 + 1 + 2
|
||||
# = 1 + 3
|
||||
# = 2 + 2
|
||||
# = 4
|
||||
# $$
|
||||
export def ways-to-add-up-to [n: int]: [ nothing -> list<list<int>> ] {
|
||||
if $n == 0 {
|
||||
return []
|
||||
} else if $n == 1 {
|
||||
return [[1]]
|
||||
}
|
||||
|
||||
ways-to-add-up-to ($n - 1)
|
||||
| each { |it|
|
||||
let a = $it | append [1]
|
||||
let b = seq 0 ($it | length | $in - 1) | each { |i| $it | update $i { $in + 1 } }
|
||||
[$a] ++ $b
|
||||
}
|
||||
| flatten
|
||||
| each { sort }
|
||||
| uniq
|
||||
}
|
||||
|
||||
#[test]
|
||||
def test [] {
|
||||
use std assert
|
||||
for it in [
|
||||
[n, expected];
|
||||
|
||||
[0, []],
|
||||
[1, [[1]]],
|
||||
[2, [[1, 1], [2]]],
|
||||
[2, [[1, 1], [2]]],
|
||||
[3, [[1, 1, 1], [1, 2], [3]]],
|
||||
[4, [[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]]],
|
||||
[5, [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 4], [2, 3], [5]]],
|
||||
] {
|
||||
assert equal (ways-to-add-up-to $it.n | sort) ($it.expected | sort)
|
||||
}
|
||||
print "tests passed"
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue