g | x | w | all
Bytes Lang Time Link
071Python 3241211T012134ZCrSb0001
008Husk250210T143421ZGlory2Uk
099Zsh250204T102203Zroblogic
007Jalapeño250204T045910ZATaco
009Nekomata250123T015734Zalephalp
037Wolfram Language Mathematica250106T083107ZIntroduc
009Jelly250106T200814Zlolad
057Maple241220T001829Zdharr
051Arturo241217T225904Zchunes
021Haskell + hgl241217T033638ZWheat Wi
036Scala 3241213T145913Zcorvus_1
063APL241212T180224ZAaron
052R241211T202440Zpajonk
091JavaScript V8241211T004627Zl4m2
091JavaScript V8241211T081747ZArnauld
012Japt241210T214951ZShaggy
00805AB1E241211T084042ZKevin Cr
095Python 3241211T055650Ztsh
057Charcoal241211T012919ZNeil
011Uiua241210T232939Znyxbird
008Vyxal241210T222948Zlyxal
020Vyxal241210T220058ZATaco

Python 3, 755 674 576 573 376 88 85 77 71 bytes

-81 bytes thanks to @corvus_192
-98 bytes
-3 bytes
-197 bytes
-288 bytes thanks to @roblogic
-3 bytes
-8 bytes
-6 bytes

Changelog

Date         Time        Size        Byte save   User Credit  (OG-csize)/OG
-----------+-----------+-----------+------------+------------+-------------+
2024-12-11 | 01:21:34Z | 755 bytes | -000 bytes | CrSb0001   | 00.00%      |
-----------+-----------+-----------+------------+------------+-------------+
2024-12-13 | 15:32:42Z | 674 bytes | -081 bytes | corvus_192 | 10.73%      |
-----------+-----------+-----------+------------+------------+-------------+
2025-01-06 | 21:34:44Z | 576 bytes | -098 bytes | CrSb0001   | 23.71%      |
-----------+-----------+-----------+------------+------------+-------------+
2025-01-22 | 19:02:07Z | 573 bytes | -003 bytes | CrSb0001   | 24.11%      |
-----------+-----------+-----------+------------+------------+-------------+
2025-03-19 | 23:33:17Z | 376 bytes | -197 bytes | CrSb0001   | 50.20%      |
-----------+-----------+-----------+------------+------------+-------------+
2025-03-20 | 00:34:46Z | 088 bytes | -288 bytes | roblogic   | 88.34%      |
           |           |           |            | CrSb0001   |             |
-----------+-----------+-----------+------------+------------+-------------+
2025-03-20 | 00:49:56Z | 085 bytes | -003 bytes | CrSb0001   | 88.70%      |
-----------+-----------+-----------+------------+------------+-------------+
2025-03-20 | 14:52:00Z | 077 bytes | -008 bytes | CrSb0001   | 89.80%      |
-----------+-----------+-----------+------------+------------+-------------+
2025-03-21 | 16:07:30Z | 071 bytes | -006 bytes | CrSb0001   | 90.60%      |
-----------+-----------+-----------+------------+------------+-------------+

@corvus_192's comment from 2024-12-13
@roblogic's comment from 2025-02-06


from itertools import*
lambda:{c for c in combinations(n,5)if sum(c)==t}

(returns a list set of sorted lists tuples, or set() if there are none/array len is less than 5.)

Note that this is still a valid solution as 1) it's still a lambda function, just anonymous and 2) we can simply define n and t below before doing the unittests.


I've been trying to figure out how I can use itertools to help, but I'm admittedly unable to come up with anything. @roblogic, I am SO sorry for not taking the time to look into itertools.combinations, it ended up saving me a total of 667 670 684 bytes compared to my original solution!




Old 755:

def fiveSum (nums,target):
    nums.sort()
    s=[]
    for i in range(len(nums)-4):
        if i>0 and nums[i]==nums[i-1]:
            continue
        for j in range(i+1,len(nums)-3):
            for k in range(j+1,len(nums)-2):
                l,m=k+1,len(nums)-1
                while l<m:
                    a=nums[i]+nums[j]+nums[k]+nums[l]+nums[m]
                    if a<target:
                        l+=1
                    elif a>target:
                        m-=1
                    else:
                        s.append((nums[i],nums[j],nums[k],nums[l],nums[m]))
                        l+=1
                        while nums[l]==nums[l-1] and l<m:
                            l+=1
    k=[]
    for b in list(set(s)):
        k.append(list(b))
    return k

Explanation:

def fiveSum (nums,target):
    nums.sort()                                                             # does NOT return all 4 solutions for the last case if removed, unsure why
    s=[]                                                                    # ^ (only returns two/four arrays)
    for i in range(len(nums)-4):                                            # i < j < k < l < m
        if i>0 and nums[i]==nums[i-1]:                                      # later loops will cover all of the
            continue                                                        # other cases, so no need to recurse through them again
        for j in range(i+1,len(nums)-3):                                    # for j in range
            for k in range(j+1,len(nums)-2):                                # for k in range
                l,m=k+1,len(nums)-1                                         # No more "_ in range" needed anymore
                while l<m:                                                  # i < j < k < l < m
                    a=nums[i]+nums[j]+nums[k]+nums[l]+nums[m]               # The sum
                    if a<target:                                            # check if nums[0]+nums[1]+...+nums[4] == target
                        l+=1                                                # it probably doesn't, so increment l by 1
                    elif a>target:                                          # if overshoot
                        m-=1                                                # if it does, decrement m by 1
                    else:
                        s.append((nums[i],nums[j],nums[k],nums[l],nums[m])) # append to list
                        l+=1
                        while nums[l]==nums[l-1] and l<m:                   # More incrementation! (Yay?)
                            l+=1
    k=[]                                                                    # The final list
    for b in list(set(s)):
        k.append(list(b))
    return k                                                                # return List[List[str]]

Husk, 8 bytes

ufo=⁰ΣṖ5

Try it online!

Inputs target and array as separate arguments. Outputs [] if there is no valid solution.

Commented:

      Ṗ5  -- make a list of all possible quintuplets
 f        -- filter the quintuplets...
  o=⁰Σ    -- | that sum to the target 
u         -- deduplicate

Zsh, 99 bytes

Non-deterministic, but repeated calls to shuf is a good-enough solution for picking 5 numbers from a list.

t=$1;shift;${5?};{repeat $[2**#]
S=(`shuf -n5<<<${(F)@}`)&&((${(j:+:)S}==t))&&echo ${(n)S}}|sort -u

Try it online!, or try the 160-byte deterministic solution 175b 189b 192b

Jalapeño, 7 bytes

cₓ5u↥{Σ=

Explained

cₓ5u↥{Σ=
cₓ5       # Choices of length 5 of implicit input
   u      # Unique only
    ↥{    # Where
       Σ= # Sum is equal to implicit second input

Hex-Dump of Bytecode

       0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
0000: e8 35 e4 d1 c4 e9 59                            

Try it Online!

Nekomata, 9 bytes

oS5Lũᵖ{∑=

Attempt This Online!

oS5Lũᵖ{∑=
o           Sort the first input
 S          Find a subset
  5L        Check that it has length 5
    ũ       Remove duplicate values of a non-deterministic object
     ᵖ{     Check that it satisfies the following condition:
       ∑    Its sum
        =   Is equal to the second input

Wolfram Language (Mathematica), 68 bytes 50 bytes 40 bytes 37 bytes

Union@Pick[a=#~Subsets~{5},Tr/@a,#2]&

Try it online!


Note

Returning "all possible permutations of one single array" is permitted eg test case 7:

Array: [1,0,9,6,5,0]
Target: 21
Output: [[1,0,9,6,5],[1,9,6,5,0]]

Saved 31 bytes by

  1. Switching to Cases from Select allowed me to use a pure function

  2. Union instead of DeleteDuplicates

  3. Using Infix ~ on Subset

  4. Using Tr instead of Total (thanks att!)

  5. Not pre-sorting (Sort/@) input as permutations of output is permitted

  6. Using Pick instead of Cases (thanks again att!)

Jelly, 9 bytes

Ṣœc5S=¥ƇQ

Try it online!

Loses to the Vyxal answer by 1 char as Jelly's combinations monad is 2 characters: œc.

Ṣœc5S=¥ƇQ    Main, dyadic link. Arguments: list, n
Ṣ            Sort (to help with dedup)
 œc5         Generate all 5-permutations
    S=¥      Dyadic link: is the sum of the list = n?
       Ƈ     Filter by
        Q    Deduplicate

Maple, 57 bytes

(n,t)->[{select(x->add(x)=t,combinat:-choose(n,5))[]}[]];

Explanation:

Input: n = nums (list), t = target.

combinat:-choose outputs combinations in lex order.

select filters for those that add to the target.

conversion from list to set {...[]} makes unique, then [...[]] converts back to a list.

Arturo, 51 bytes

$[a,t][a|sort|combine.by:5|select=>[t=∑&]|unique]

enter image description here

Haskell + hgl, 21 bytes

nB sr<<ss5><fl<eq^.sm

Attempt This Online!

Explanation

The order of operations is a bit strange here.

Reflection

We have some pretty good builtins here. The only 3-byte builtin is ss5 which definitely should not be a 2-byte function. It seems like we use a lot of glue, but it's not an area I can see much improvement. I really have all the glue I want. There's no parens and we don't even use any 3-byte composes.

It seems long but I don't really know how it could be shorter.

The only possible improvement is to make nB sr a builtin. I don't really know if this would be useful in the long term.

Scala 3, 36 bytes

t=>_ combinations 5 filter(_.sum==t)

Attempt This Online!

A function of type Int => Seq[Int] => Iterator[Seq[Int]].

APL, 63 chars

{⍺{⍵/⍨(⍺∘=+/∧5∘=∘≢)¨⍵}{0=≢⍵:1⍴⊂⍬⋄⊃,/(⊃⍵){(⊂⍵),⊂⍵,1⍴⍺}¨(∇1↓⍵)}⍵}

Takes the target on the left and the list of numbers on the right. Explanation, broken out slightly into a helper function:

combos←{0=≢⍵:1⍴⊂⍬⋄⊃,/(⊃⍵){(⊂⍵),⊂⍵,1⍴⍺}¨(∇1↓⍵)}    ⍝ Recursively generate all combinations of the input array
        0=≢⍵:                                    ⍝ If the input is empty
             1⍴⊂⍬                                ⍝    return a one-element array containing an empty array
                                      (∇1↓⍵)     ⍝ Otherwise recursively call with the tail of the list
                     (⊃⍵){           }¨          ⍝ And apply to each result with the head of the list as the left input
                               ⊂⍵,1⍴⍺            ⍝ Concat the right input with an array made from the left input
                          (⊂⍵),                  ⍝ And concat with the input itself
                ⊃,/                              ⍝ Join and disclose to not further nest the result

{⍺{⍵/⍨(⍺∘=+/∧5∘=∘≢)¨⍵} combos ⍵}
{                  ¨⍵}                           ⍝ Take all the possible combinations
   ⍵/⍨                                           ⍝ And replicate those that pass:
      (     ∧     )                              ⍝     the AND of
       ⍺∘=+/                                     ⍝         the left input matches their sum
             5∘=∘≢                               ⍝         the right input has 5 elements

R, 52 bytes

\(x,n)unique(t(combn(x,5,sort)[,combn(x,5,sum)==n]))

Attempt This Online!

Returns quintuplets as rows of a matrix.

JavaScript (V8), 91 bytes

f=([c,...x],s,n=R=[])=>1/n[4]?s||R[n.sort()]||print(R[n]=n):1/c&&f(x,s,n)^f(x,s-c,[...n,c])

Try it online!

JavaScript (Node.js), 97 bytes

f=([c,...x],s,n=R=[])=>1/n[4]?s||R[n.sort()]?[]:[R[n]=n]:1/c?[...f(x,s,n),...f(x,s-c,[...n,c])]:x

Try it online!

JavaScript (Node.js), 98 bytes

f=(x,s,i=R={},...n)=>1/n[4]?s||R[n.sort()]?[]:[R[n]=n]:x.flatMap((e,j)=>i<=j?[]:f(x,s-e,j,...n,e))

Try it online!

Dedup

JavaScript (V8), 91 bytes

f=([v,...a],n,o=q=[])=>o[4]?n||q[o.sort()]||print(q[o]=o):v+1&&f(a,n-v,[...o,[v]])|f(a,n,o)

Try it online!

Commented

f = (             // f is a recursive function taking:
  [v,             //   v = next value from the input array
      ...a],      //   a[] = remaining values
  n,              //   n = target sum
  o =             //   o[] = current output array
  q = []          //   q = object to keep track of output arrays
) =>              //
o[4] ?            // if o[4] is defined:
  n ||            //   unless n is not 0
  q[o.sort()] ||  //   or q[o] is defined (with o[] sorted),
  print(q[o] = o) //   print o[] and set q[o]
:                 // else:
  v + 1 &&        //   unless v is undefined,
  f(              //   do a 1st recursive call:
    a,            //     pass a[]
    n - v,        //     subtract v from n
    [...o, [v]]   //     append [v] to o[]
  ) |             //   end of recursive call
  f(a, n, o)      //   do a 2nd recursive call with everything unchanged

Japt, 12 bytes

Outputs an empty array if no solution is possible.

Íà5 â fÈx ¶V

Try it

Íà5 â fÈx ¶V     :Implicit input of array U & target integer V
Í                :Sort U
 à5              :Combinations of length 5
    â            :Deduplicate
      f          :Filter by
       È         :Passing through the following function
        x        :  Reduce by addition
          ¶V     :  Equal to V?

05AB1E, 8 bytes

{5.ÆÙʒOQ

Inputs in the order \$array,target\$. Outputs [] if there is no valid result.

Try it online or verify all test cases.

Explanation:

{         # Sort the first (implicit) input-list
 5.Æ      # Get all 5-element combinations of this list
    Ù     # Uniquify this list of quintuplets
     ʒ    # Filter it by:
      O   #  Where the sum of the quintuplet
       Q  #  Equals the second (implicit) input-integer
          # (after which the result is output implicitly)

Python 3, 95 bytes

f=lambda t,a,*p:[p][t*t:len(p)==5]or{i for v in[*a]for i in f(t-a.pop(0),[*a],*sorted([*p,v]))}

Try it online!

Input target value and the array of nums, output a set of tuples.

Charcoal, 57 bytes

W⁻θυF№θ⌊ι⊞υ⌊ι≔⟦⟧θFEX²LυE⌕A⮌⍘ι²1§υλF⁼⁵LιF⁼ηΣιF¬№θι⊞θιEθ⭆¹ι

Try it online! Link is to verbose version of code. Explanation:

W⁻θυF№θ⌊ι⊞υ⌊ι

Sort the input list.

≔⟦⟧θ

Start with no results.

FEX²LυE⌕A⮌⍘ι²1§υλ

Get all subsets of the sorted list.

F⁼⁵Lι

Filter on those that have length 5.

F⁼ηΣι

Filter on those with the desired total.

F¬№θι

Filter on those that are distinct.

⊞θι

Keep only the distinct subsets of 5 with the correct total.

Eθ⭆¹ι

Pretty-print the found subsets.

Uiua, 11 bytes

◴▽=⤚≡/+⧅<5⍆

Try it!

◴▽=⤚≡/+⧅<5⍆
           ⍆ # sort
        ⧅<5   # get quintuples
 ▽=⤚≡/+       # keep those for which the sum equals the target
◴             # and deduplicate

Vyxal, 8 bytes

s5ḋU'∑⁰=

Try it Online!

-2 from emanresu

Takes list then target.

Explained

s5ḋU'∑⁰=­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌­
s         # ‎⁡Sort the input. This helps with uniquification later
 5ḋ       # ‎⁢Get all combinations without replacement of length 5
   U      # ‎⁣Filter out duplicate instances of combinations
    '     # ‎⁤Keep combinations where:
     ∑ =  # ‎⁢⁡  The sum equals
      ⁰   # ‎⁢⁢  The target
💎

Created with the help of Luminespire.

Vyxal, 20 bytes

→tṖƛ5Þİ_;'∑←t=;λsS;ε

First Vyxal submission 🎉 Almost certainly golf-able.

Explained

→t                      # Assign the target to t
  Ṗ                     # Get all permutations of the input list
   ƛ5Þİ_;               # Taking the first 5 elements of each permutation
         '∑←t=;         # Where the sum is equal to t
               λsS;ε    # Uniqueify by the sorted string

Try it Online!