Am 10.06.21 um 10:57 schrieb Riccardo (Jack) Lucchetti:
Folks,
while revising some old code I stumbled into a function that I'd written
a while back, and I realised this could go into the extra package. Note:
for large input vectors (n > 5) the recursion approach really is much
slower than direct calculation, so there is quite a lot of room for
optimisation.
Opinions?
Hi guys,
I did not really get the conclusion of this discussion: Do all agree
that your choose() function is supposed to become part of the extra package?
If so, I have the following comments on it:
1) Nice function. Actually, I just need this for another package I am
working on ;-)
2) The name: Why not call it nchoosek() or combinations()? The first
suggestion is familiar for people coming from Matlab -- which are not
too few. Simply "choose" sounds _too_ general I would say (choose what
from which source?).
3) I suggest to change the signature to
function matrix choose (matrix from "Set of all choices",
int h[1::] "Number of selected choices")
First, h must be an integer, right? Second, we have another check that
only positive integers are passed.
Here is a slightly modified version.
<>
function matrix choose (matrix from "Set of all choices",
int h[1::] "Number of selected choices")
/* If "from" is a vector with n elements, this function
returns a matrix whose rows are all the possible subsets
with h elements; a recursive algorithm is used.
# For example: choose({1,2,3}, 2) returns
#
# 1 2
# 1 3
# 2 3
return: matrix with n! / (h! * (n-h)!) rows if succesful,
otherwise 1x1 matrix with an NA value. */
if rows(from) > 1 && cols(from) > 1
s = argname(from)
printf "\nError: %s is not a vector\n", strlen(s) ? s :
"argument 1"
return {NA}
endif
if h == 1
matrix ret = vec(from)
else
matrix ret = {}
n = nelem(from)
loop i=1..(n-h+1)
x = from[i]
matrix c = from[i+1:]
if rows(c) > 0
matrix ret |= x ~ choose(c, h-1)
endif
endloop
endif
return ret
end function
eval choose({1,2,3}, 2)
matrix v = seq(1, 10)
matrix r = choose(v, 5)
eval rows(r)
</>
If we agree that this shall become part of the extra package, I add 2-3
tests to our test suit for extra.
Artur