Menu

#93 contribute : subtuple()

open
nobody
None
5
2020-01-18
2019-12-31
No

subtuple() - subset of Sander Huisman's SelectTuples[].
see more info: https://resources.wolframcloud.com/FunctionRepository/resources/SelectTuples

licence: CC BY 4.0(same as original(Mathematica) version(maybe))
https://creativecommons.org/licenses/by/4.0/

:::Maxima
/* subtuple() - subset of Sander Huisman's SelectTuples[].
   see more info: https://resources.wolframcloud.com/FunctionRepository/resources/SelectTuples

   usage : subtuple(list, n, p)
             ex. subtuple([1,2], 3, lambda([x], evenp(first(x))))
           subtuple([list1, list2,...], p)
             ex. subtuple([[1,2], [3,4]], lambda([x], evenp(first(x))))
           subtuple(..., p, m)
             ex. subtuple([1,2], 3, lambda([x], evenp(first(x))), 3)
                 subtuple([[1,2], [3,4]], lambda([x], evenp(first(x))), 1)
*/
subtuple(list, [u]):=block([l, p, count:0, m:inf, stack:[]],
  local(subtuplesub),

  subtuplesub(head, tail):=block(
    if head = [] then block([r:reverse(tail)],
      if p(r) then (
        push(r, stack),
        if (count:count + 1) >= m then throw(stack)))
    else block([f],
      for f in pop(head) do subtuplesub(head, cons(f, tail))
    )
  ),

  if list = [] then return([[]]),

/*
  length(u) = 1 : subtuple([list1, list2,...], p)
            = 2 : subtuple(list, n, p) or subtuple([list1, list2,...], p, m)
            = 3 : subtuple(list, n, p, m)
*/
  l:length(u),
  if l = 1 then p:first(u)                                   /* subtuple([list1, list2,...], p) */
  elseif l = 2 then block([f:pop(u)],
    if integerp(f) then (list:makelist(list, f), p:first(u)) /* subtuple(list, n, p) */
    else (p:f, m:first(u))                                   /* subtuple([list1, list2,...], p, m) */
  ) else ( /* maybe l = 3 */
    list:makelist(list, pop(u)), p:pop(u), m:first(u)        /* subtuple(list, n, p, m) */
  ),
  if m <= 0 then return([]),

  reverse(catch(subtuplesub(list, []), stack))
);

Discussion

  • Takayuki Homma

    Takayuki Homma - 2020-01-18

    Sorry, p() should be local().

    19c19
    <   local(subtuplesub),
    ---
    >   local(p, subtuplesub),
    
     
    • Takayuki Homma

      Takayuki Homma - 2020-01-18

      "13c13" is correct. Sorry.

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.