text:
Buy the most appropriate items
A store is having a big sale.
If your price reaches $199 or more, you can reduce it by $100.
You can buy each product only once.
Here's an example list of products: (in order to simplify, the names of the products are represented by letters)
+------+-------+
| name | price |
+------+-------+
| A    | 26.9  |
| B    | 24.9  |
| C    | 49.9  |
| D    | 28.9  |
| E    | 14.9  |
| F    | 16.9  |
| G    | 19.9  |
| H    | 19    |
| I    | 14.9  |
| J    | 14.9  |
| K    | 26.9  |
+------+-------+

Input

A list of product price, such as the above example.
N the item list size    10 <= N <= 100
X a price

Output
The best shopping strategy to save money. Find out the least expensive purchase list with a total price of more than X,
and output:

The most appropriate total price (before deduction), for the data above, X = $199, and the most appropriate total price is 199.2

Notes

Your code can be a function (method) or a full working program.
Make your algorithm as fast as possible (less time complexity)!
If codes have the same time complexity, the one which uses less space wins.

Welcome to PPCG! You'll have to specify what is the winning criterion for this challenge (the most common one is code-golf but many others exist). I'd also recommend to include the solution for the given example and add a few other test cases. Also, can a product be purchased more than once? Is the total price supposed to be displayed before or after discount?

@Arnauld I've modified the question but I have no idea whether it fits the rules now.

Yes, I think it does. Voted to reopen.

Please note however that fastest-algorithm (the tag you've chosen) doesn't mean fastest-code (like your description suggests). I personally think that fastest-algorithm is indeed a better option here, so you'd rather edit the description than update the tag.

@Arnauld OK, I've changed the description. If there is still something inappropriate can you help me correct it? I'm not very good at English ^ ^

If two submissions have the same complexity, perhaps you should add a tiebreaker, such as shortest code.

Could we get a few more test cases please?

The Input section of your challenge says "All the prices above". This might look like we can simply hardcode the output, as the input is constant, but I guess you don't want that. I suggest writing something like "A list of products and their prices, such as the above example.". Also, the line above the code block reads "Here are the products:"; I suggest changing that to "Here's an example list of products:". More test cases will be appreciated too. Finally, I suggest allowing the solutions to identify the products in a different way than the uppercase letters, e.g. 0- or 1-based indices.

Clarification of the above comment (comments have a character limit): I'd also suggest not having the solutions unnecessarily take IDs of the products (they might not use them and it may cost to clean the input of them, although that will most probably be an O(number of products) operation), they can be based on the order they're given.

This would be simple knapsack if not for doubles... darn

@Erik the Outgolfer I've changed the question. Now you can only output the total price, not products.

Since the subset sum problem could be reduced to this question. This question is NP-Hard. And this question may be reduced to knapsack problem by making weight = price, max_weight = sum(price) - discount_price. Knapsack problem had been will well learnt, so I won't expect there will be any interesting answers here.

@tsh 3Q very much .i Know how to do it now.

Here the problem seems to me exponential... The clue of a good algo could be only have less operations on a random array... (but this is difficult to prove) so remain only the code golf tag

Python 2, \$O(2^{n/2})\$
import sys
def subsetsum(nums, target):
#    totalsum = sum(nums)
#    if(totalsum == target):
#        return target
#    if(totalsum < target):
#        return -1

    sumsA = {}
    sumsB = {}
    for n in nums[::2]:
        for k,v in sumsA.items() + [(0,[])]:
            newsum = k + n
            if newsum not in sumsA:
                sumsA[newsum] = v + [n]
                if newsum == target:
                    print "target found in sumsA loop: "
                    return target
    minsum = sys.maxsize
    for n in nums[1::2]:
        for k,v in sumsB.items() + [(0,[])]:
            newsum = k + n
            if newsum not in sumsB:
                sumsB[newsum] = v + [n]
                if newsum == target:
                    print "target found in sumsB loop: "
                    return target
                for a in sumsA:
                    combsum = a + newsum
                    if combsum == target:
                        print "target found in combined sumsA and sumsB loop: "
                        return target
                    if combsum > target and combsum < minsum:
                        minsum = combsum
    print "target",target,"not found, so return the closest alternative: "
    return minsum

# Test cases:
print subsetsum([26.9, 24.9, 49.9, 28.9, 14.9, 16.9, 19.9, 19, 14.9, 14.9, 26.9], 199)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
                 21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
                 21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
                 40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
                 49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 1000)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
                 21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
                 21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
                 40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
                 49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 555.5)

Try it online.
My Python skills are a bit rusty, so if you see any issues, let me know. Also, I think this can be improved in code for sure with some binary searches or something along those lines.
The program uses the Knapsack Meet-in-the-middle approach. It first uses all even-indexed items to get a set of all possible sums for the powerset of these even-indexed items. Then it does the same for all odd-indexed items, and simultaneously determines the minimum sum using the sums of these two sets.

Just curious - why did you pick python?

@Quintec Multiple reasons actually. When I was searching for an appropriate algorithm I came across a solution in Python for subsets which sum to a target exactly, which I modified to a meet-in-the-middle approach first, and then to a knapsack approach. The other two reasons are that Python's performance is pretty good overall (although Java is too tbh), and I want to try some languages I don't use very often once in a while (like I did yesterday with an Elixir answer).

Jelly, 10 bytes, Score \$O(2^n)\$
ŒPS€>Ƈ199Ṃ

Try it online!
Input is a list of prices for items. Output is the minimum possible price greater than 199. Note this outputs 199.20000000000002 due to floating point rounding. Also note as it stands that it will about the least total price greater than 199 (rather than greater than or equal to).
Time used scales exponentially and is approximately proportional to 2^n where n is the number of items. On TIO, 19 items takes approx. 14.5 seconds.

@Arnauld sorry missed that. I've added info about both absolute time and scaling of time to list length. The provided example is very quick (~0.2 seconds), but it approximately doubles for each added item.

@NickKennedy Score is complexity, not bytes, so you need to change the header. Also 2^n isn't particularly good :P

@ASCII-only Yes, realised that. I saw the first comment from Arnauld about the choice of scoring metric (such as code-golf) and misread that as being what the OP had chosen.

btw score as "\$O(2^n)\$" is fine (or maybe even preferable)


text:
Make me a metasequence
Background
For this challenge, a 'metasequence' will be defined as a sequence of numbers where not only the numbers themselves will increase, but also the increment, and the increment will increase by an increasing value, etc.
For instance, the tier 3 metasequence would start as:
1 2 4 8 15 26 42 64 93 130 176
because:
    1 2 3  4  5  6  7  8   9       >-|
      ↓+↑ = 7                        | Increases by the amount above each time
  1 2 4 7  11 16 22 29 37  46  >-| <-|
                                 | Increases by the amount above each time
1 2 4 8 15 26 42 64 93 130 176 <-|

Challenge
Given a positive integer, output the first twenty terms of the metasequence of that tier.
Test cases
Input: 3 Output: [ 1, 2, 4, 8, 15, 26, 42, 64, 93, 130, 176, 232, 299, 378, 470, 576, 697, 834, 988, 1160 ]
Input: 1 Output: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
Input: 5 Output: [ 1, 2, 4, 8, 16, 32, 63, 120, 219, 382, 638, 1024, 1586, 2380, 3473, 4944, 6885, 9402, 12616, 16664 ]
Input: 13 Output: [ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16383, 32752, 65399, 130238, 258096, 507624 ]
As you may realise, the first \$t+1\$ items of each sequence of tier \$t\$ are the first \$t+1\$ powers of 2...
Rules

Standard loopholes apply
This is code-golf, so shortest answer in bytes wins

I assume you mean 20 terms, not digits?

What do you mean by "tier"?

By the way, the tier three metasequence is OEIS A000125

Quintec - correct, fixed. @DavidC - A 'tier' is the amount of levels of addition: on tier 1, the numbers increase by one each time. On tier 2, the amount the numbers increase by increases by one each time. On tier 3, the amount the increase value increases by is increases by 1 each time; etc. I will add an example in un-golfed JS to demonstrate how the algorithm could work.

You may want to clarify if solutions have to work for input 20 or greater.

Can we choose to 0-index (so, output tier 1 for input 0, tier 2 for input 1, etc.)?

@Lynn if you must; as long as the answers are correct.

I found this in diagonals along Pascal's triangle, if that may help anybody

@MilkyWay90, it's not very clear what you mean: 219 (from level 5) only occurs in Pascal's triangle as $\binom{219}{1}$ and $\binom{219}{218}$.

@PeterTaylor Oh, oops, sorry about that

Jelly, 8 7 bytes
20ḶcþŻS

Try it online!
   cþ       Table of binom(x,y) where:
20Ḷ           x = [0..19]
     Ż        y = [0..n]    e.g.  n=3 → [[1, 1, 1, 1, 1, 1,  …]
                                         [0, 1, 2, 3, 4, 5,  …]
                                         [0, 0, 1, 3, 6, 10, …]
                                         [0, 0, 0, 1, 4, 10, …]]

      S     Columnwise sum.           →  [1, 2, 4, 8, 15, 26, …]

This uses @alephalpha’s insight that $$\text{meta-sequence}_n(i) = \sum_{k=0}^n \binom ik.$$

That is brutally succint. Just awesome.

Wolfram Language (Mathematica), 34 bytes
0~Range~19~Binomial~i~Sum~{i,0,#}&

Try it online!
The tier \$n\$ metasequence is the sum of the first \$n+1\$ elements of each row of the Pascal triangle.

There's almost a built-in for that, but unfortunately it's longer.

I don't know enough WL to do anything useful in it, but it seems to me that it might benefit from the identity $$T(n,k) = \begin{cases}1 & \textrm{if }k=0 \ 2T(n,k-1) - \binom{k-1}{n} & \textrm{otherwise}\end{cases}$$

Haskell, 34 bytes
(iterate(init.scanl(+)1)[1..20]!!)

Uses 0-indexed inputs (f 4 returns tier 5.)
Haskell, 36 bytes
f 1=[1..20]
f n=init$scanl(+)1$f$n-1

Try it online! Uses 1-indexed inputs (f 5 returns tier 5.)
Explanation
scanl (+) 1 is a function that takes partial sums of a list, starting from (and prepending) 1.

For example: scanl (+) 1 [20,300,4000] equals [1,21,321,4321].

It turns out that tier \$n\$ is just this function applied \$ (n-1) \$ times to the list \$[1,2,3,\dots]\$.
(Or equivalently: \$n\$ times to a list of all ones.)
We use either init or [1..20-n] to account for the list getting longer by \$1\$ every application.

[1..20-n] isn't going to work for $n > 20$

take 20.(iterate(scanl(+)1)[1..]!!) would only cost a byte more to fix that

Your pointfree answer can be back to 34 bytes using your other answer: (iterate(init.scanl(+)1)[1..20]!!).

Brain-Flak, 84 82 bytes
<>((()()()()()){}){({}[((()))])}{}<>{({}[(())]<<>{({}<>({}))<>}<>{}{({}<>)<>}>)}<>

Try it online!
Annotated
<>               Switch to the off stack
((()()()()()){}) Push 10
{({}[((()))])}{} Make twice that many 1s
<>               Switch back
{                While ...
({}[(())]<       Subtract one from the input and push 1
<>               Switch
{                For every x on the stack
({}<>({}))<>     Remove x and add it to a copy of the other TOS
}                End loop
<>{}             Remove 1 element to keep it 20
{({}<>)<>}       Copy everything back to the other stack
>)}<>            End scopes and loops

Try it online!

you know its funny how this is shorter than Rust

R, 36 bytes
rowSums(outer(0:19,0:scan(),choose))

Try it online!
Thanks to @Giuseppe for suggesting outer.
This is based on the approach @alephalpha described

you might be able to use Map instead of outer?

@JDL I can’t see how that would work. I need every possible combination, not just pairs of combinations.

dzaima/APL REPL, 14 bytes
(+\1,19↑)⍣⎕⍳20

Try it online!
(+\1,19↑)⍣⎕⍳20
(       )⍣⎕     repeat the function below input times:
 +\               cumulative sum of
   1,             1 prepended to
     19↑          the first 19 items of the previous iteration
           ⍳20  starting with the first 20 integers

-1 byte using dzaima/APL: 1∘, → 1,

@Adám oh duh.. right

Full program at 17: (≢↑(+\1∘,)⍣⎕)20⍴1

14 bytes by using the REPL (add the -s flag).

If you use the flag, language becomes -s btw (unless -s is repl flag?)

@ASCII-only the -s flag indicates to read stdin as a REPL, which being mentioned in the title is IMO sufficient (as it's the way to start a REPL)

Python 2, 69 58 55 bytes
Saved bytes thanks to ovs and Jo King; also, it works in Python 3 now as well.
m=lambda t:[1+sum(m(t-1)[:n])for n in range(~t and 20)]

Try it online!
The math
Let \$a(t,n)\$ be the \$n^{th}\$ term (0-indexed) of the sequence at tier \$t\$. A little analysis leads to the following recurrence formula:
$$
a(t,n) = 1+\sum_{i=0}^{n-1}a(t-1,i)
$$
Working backwards, we define \$a(0,n) = 1\$ and \$a(-1,n) = 0\$ for all \$n\$. These definitions will simplify our base case.
The code
We define a function m(t) that returns the first 20 elements of the sequence at tier t. If t is nonnegative, we use the recursive formula above; if t is -1, we return an empty list. The empty list works as a base case because the result of each recursive call is sliced ([:n]) and then summed. Slicing an empty list gives an empty list, and summing an empty list gives 0. That's exactly the result we want, since tier \$-1\$ should behave like a constant sequence of all \$0\$'s.
m=lambda t:                     # Define a function m(t):
 [          ]                   # List comprehension
     for n in range(         )  # for each n from 0 up to but not including...
                    ~n and 20   # 0 if n is -1, else 20:
  1+sum(          )             # a(t,n) = 1 + sum of
              [:n]              # the first n elements of
        m(t-1)                  # the previous tier (calculated recursively)

61 bytes as a recursive lambda function (Significantly more inefficient).

@ovs Thanks! I found a couple more bytes by using a different base case, too.

:( the nice way is too long

or a combinations builtin, yeah

closer (with stolen combinations function)

:P

(t>=0)*range(20) saves a byte, though there's probably a yet shorter expression.

if~t saves two more over @xnor

Pari/GP, 36 bytes
n->vector(20,i,i<n+2)*matpascal(19)~

Try it online!
A port of my Mathematica answer.

Pari/GP, 39 bytes
n->Vec(sum(i=1,n+1,(1/x-1)^-i)+O(x^21))

Try it online!

Pari/GP, 40 bytes
n->Vec((1-(1/x-1)^-n++)/(1-2*x)+O(x^20))

Try it online!

The generating function of the tier \$n\$ metasequence is:
$$\sum_{i=0}^n\frac{x^i}{(1-x)^{i+1}}=\frac{1-\left(\frac{x}{1-x}\right)^{1+n}}{1-2x}$$

Perl 6, 34 32 bytes
-2 bytes thanks to Jo King
{(@,{[\+] 1,|.[^19]}...*)[$_+1]}

Try it online!
Explanation
{                              }  # Anonymous block
   ,                ...*  # Construct infinite sequence of sequences
  @  # Start with empty array
    {              }  # Compute next element as
     [\+]     # cumulative sum of
          1,  # one followed by
            |.[^19]  # first 19 elements of previous sequence
 (                      )[$_+1]  # Take (n+1)th element

29 bytes (the $^a instead of $_ is necessary)

@JoKing Nice, but this assumes that $_ is undefined when calling the function. I prefer solutions that don't depend on the state of global variables.

Python 3.8 (pre-release), 62 bytes
f=lambda n:[t:=1]+[t:=t+n for n in(n and f(n-1)[:-1]or[0]*19)]

Try it online!

Explanation
f=lambda n:     # funtion takes a single argument
     [t:=1]     # This evaluates to [1] and assigns 1 to t
                # assignment expressions are a new feature of Python 3.8
       +        # concatenated to
     [  ....  ] # list comprehension

# The list comprehesion works together with the
# assignment expression as a scan function:
[t := t+n for n in it]
# This calculates all partial sums of it
# (plus the initial value of t, which is 1 here)

# The list comprehension iterates
# over the first 19 entries of f(n-1)
# or over a list of zeros for n=0
 for n in (n and f(n-1)[:-1] or [0]*19)

R (63 47 bytes)
function(n,k=0:19)2^k*pbeta(.5,pmax(k-n,0),n+1)

Online demo. This uses the regularised incomplete beta function, which gives the cumulative distribution function of a binomial, and hence just needs a bit of scaling to give partial sums of rows of Pascal's triangle.
Octave (66 46 bytes)
@(n,k=0:19)2.^k.*betainc(.5,max(k-n,1E-9),n+1)

Online demo. Exactly the same concept, but slightly uglier because betainc, unlike R's pbeta, requires the second and third arguments to be greater than zero.
Many thanks to Giuseppe for helping me to vectorise these, with significant savings.

R, 59 49 bytes
f=function(n)`if`(n,Reduce(`+`,f(n-1),1,,T),1:20)

Try it online!
Recursively Reduce with +, init=1 and accumulation=TRUE to avoid having to subset. Thanks to Criminally Vulgar for suggesting the recursive approach!

tio this is only 39 bytes (using binomial approach)

@NickKennedy that's a separate approach, so I'd recommend posting it yourself, and it's golfier to use outer than sapply for 36 bytes

Converting this approach to a recursive function gives 53 bytes (I think in recursives we need to include the assignment? If not, 51) TIO

@CriminallyVulgar we can get to 49 bytes :-)

@Giuseppe Haha I knew it was golfable, just couldn't see it! I messed with cumsum for a while to try and make it work, but that Reduce is so slick.
Nice to be able to drop the index by 1 as well, didn't see that in the comments.

Wolfram Language (Mathematica), 42 bytes
Nest[FoldList[Plus,1,#]&,Range[21-#],#-1]&

Try it online!

Retina, 59 bytes
.+
19*$(_,

Replace the input with 19 1s (in unary). (The 20th value is 0 because it always gets deleted by the first pass through the loop.)
"$+"{`
)`

Repeat the loop the original input number of times.
(.+),_*
_,$1

Remove the last element and prefix a 1.
_+(?<=((_)|,)+)
$#2*

Calculate the cumulative sum.
_+
$.&

Convert to decimal.
Try it online!

JavaScript (Node.js), 58 bytes
t=>Array(20).fill(t).map(g=(t,i)=>i--*t?g(t,i)+g(t-1,i):1)

Try it online!
It is trivial to write down following recursive formula based on the description in question
$$ g(t,i)=\begin{cases}
g(t,i-1)+g(t-1,i-1) & \text{if} \quad i\cdot t>0 \\
1 & \text{if} \quad i\cdot t=0 \\
\end{cases} $$
And you just need to generate an Array of 20 elements with \$[g(t,0)\dots g(t,19)]\$

57?

05AB1E, 11 9 8 bytes
19ÝIÝδcO

1-indexed
-1 byte by porting @alephalpha's Mathematica answer, so make sure to upvote him!!
Try it online or verify all test cases.
Explanation:
19Ý       # Push a list in the range [0, 19]
   IÝ     # Push a list in the range [0, input-integer]
     δ    # Apply on the two lists double-vectorized (as a table):
      c   #  The binomial coefficient
       O  # And then sum each inner list
          # (after which the resulting list is output implicitly)

Old 11 9 bytes answer:
20LIF.¥>¨

0-indexed
Try it online or verify all test cases.
Explanation:
20L        # Create a list in the range [1,20]
   IF      # Loop the input amount of times:
     .¥    #  Get the cumulative sum of the current list with 0 prepended automatically
       >   #  Increase each value in this list by 1
        ¨  #  Remove the trailing 21th item from the list
           # (after the loop, the result-list is output implicitly)

Nice use of .¥!

Rust, 135 bytes
fn t(m:u64)->Vec<u64>{let f=|y|(1..=y).fold(1,|a,n|a*n);(0..20).map(|i| (0..=u64::min(i,m)).fold(0,|a,x|a+f(i)/f(x)/f(i-x))).collect()}

used @alephalpha 's idea, like several others. there is no builtin factorial so that takes up at least 36 bytes, (plus dealing with negatives). no builtin choose, another 16 bytes. iterator->declared vector type, 20 bytes.. etc etc.
Ungolfed at play.rust-lang.org

There's a better way to calculate binomial coefficients for the same cost but which allows removing the min: fn t(m:i64)->Vec<i64>{let b=|n,k|(1..=k).fold(1,|a,j|a*(n-j+1)/j);(0..20).map(|i|(0..=m).fold(0,|a,x|a+b(i,x))).collect()} (122 bytes)

In fact, the binomial can be inlined: fn t(m:i64)->Vec<i64>{(0..20).map(|i|(0..=m).fold(0,|a,x|a+(1..=x).fold(1,|a,j|a*(i-j+1)/j))).collect()} (104 bytes). What would be nice is to combine the two folds, but I'm not sure how succinct tuples are.

Succinct enough: fn t(m:i64)->Vec<i64>{(0..20).map(|i|(0..=m).fold((0,1),|a,b|(a.0+a.1,a.1*(b-i)/!b)).0).collect()} (98 bytes)

thats amazing... i struggle to even understand how it works but its amazing.

It just uses one algebraic trick: $$\frac{n!}{k!(n-k)!} = \frac{n!}{(k-1)!(n-(k-1))!} \times \frac{n-k+1}{k}$$

JavaScript (ES6),  68  67 bytes
f=(n,a=[...f+f])=>n--?f(n,[s=1,...a.map(x=>s-=~--x)]):a.slice(0,20)

Try it online!

JavaScript (ES6), 63 bytes
NB: this version works for \$n\le20\$.
f=(n,a=[...Array(20-n)])=>n--?f(n,[s=1,...a.map(x=>s+=x||1)]):a

Try it online!

Ruby, 74 bytes
a=->b{c=[1];d=0;b==1?c=(1..20).to_a: 19.times{c<<c[d]+(a[b-1])[d];d+=1};c}
Ungolfed version:
def seq num
    ary = [1]
    index = 0
    if num == 1
        ary = (1..20).to_a
    else
        19.times{ary << ary[index]+seq(num-1)[index]; index+=1}
    end
    return ary
end

Quite resource-intensive--the online version can't calculate the 13th metasequence.
Try it online

Ruby, 49 bytes
f=->n{n<1?[1]*20:[o=1]+f[n-1][0,19].map{|x|o+=x}}

Recursive definition: Tier 0 is 1,1,1,1... and each subsequent tier is 1 followed by a sequence whose first differences are the previous tier. Annoyingly this would give me 21 values if I didn't explicitly slice out the first 20; seems like there should be a way to shorten this by avoiding that.

https://tio.run/#ruby pls

also 49

46

J, 24 bytes
<:(1+/\@,])^:[(1+i.20)"_

Try it online!
NOTE: Turns out this is a translation of dzaima's APL answer, though I actually didn't notice it before writing this.
explanation
<: (1 +/\@, ])^:[ (1+i.20)"_
<:                           NB. input minus 1 (left input)
                  (1+i.20)"_ NB. 1..20 (right input)
   (         )^:[            NB. apply verb in parens
                             NB. "left input" times
   (1     , ])               NB. prepend 1 to right input
   (  +/\@   )               NB. and take scan sum

C# (Visual C# Interactive Compiler), 120 bytes
n=>{for(long i=-1,h=0,m=0;++i<20;Print(i<1?1:h))for(m=h=0;m<=n;)h+=f(i)/(f(m)*f(i-m++));long f(long a)=>a>1?a*f(a-1):1;}

Try it online!
Based off of alephalpha's formula.

K (oK), 17 bytes
-1 byte thanks to ngn (switching from 0-indexed to 1-indexed)
{x(+\1,19#)/20#1}

Try it online!
1-indexed
K (oK), 18 bytes
{x(+\1,19#)/1+!20}

Try it online!
0-indexed

make it 1-indexed and save a byte: 1+!20 -> 20#1

@ngn Thanks, as always there's something I've missed :)

Perl 5, 48 bytes
$x=1,@A=(1,map$x+=$_,@A[0..18])for 0..$_;$_="@A"

TIO

R (60 59 bytes)
function(n)Reduce(function(p,q)2*p-choose(q-1,n),1:19,1,,1)

Online demo
Straightforward implementation of the observation

T(n,k) = 2 T(n-1,k) - binomial(n-1,k). - M. F. Hasler, May 30 2010

from OEIS A008949. The arguments to Reduce are the function (obviously), the array over which to map, the starting value, a falsy value (to fold from the left rather than the right), and a truthy value to accumulate the intermediate results in an array.

Jelly, 10 bytes
20RṖ1;ÄƲ⁸¡

Try it online!
0-indexed.

CJam (20 bytes)
1aK*{1\{1$+}/;]}q~*p

Online demo. This is a program which takes input from stdin and prints to stdout; for the same score an anonymous block (function) can be obtained as
{1aK*{1\{1$+}/;]}@*}

Dissection
This applies the definition literally:
1aK*      e# Start with an array of 20 1s
{         e# Loop:
  1\      e#   Push a 1 before the current list
  {1$+}/  e#   Form partial sums (including that bonus 1)
  ;]      e#   Ditch the last and gather in an array (of length 20)
}
q~*       e# Take input and repeat the loop that many times
p         e# Pretty print

Japt, 15 bytes
0-indexed; replace h with p for 1-indexed.
ÈîXi1 å+}gNh20õ

Try it

Vyxal R, 7 bytes
20⁰(ÞR›

Try it Online!
0-indexed.
How?
20⁰(ÞR›
20      # Push number 20
  ⁰(    # Loop input times
    ÞR  # Take the cumulative sum of list (20, R flag makes this a [1, 20] range), remove last item, and prepend 0. Short for ¦Ṫ0p
      › # Increment (implicit vectorization)

Vyxal RM, 7 bytes
19ƛ⁰ʀƈ∑

Try it Online!
1-indexed.
How?
19ƛ⁰ʀƈ∑
19      # Push the number 19
  ƛ     # Map, R and M flags make this be a [0, 19] range
   ⁰ʀ   # Inclusive zero range of input
     ƈ  # Binomial coefficient, implicit vectorization
      ∑ # Sum these binomimal coefficients

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Find how "smooth" a number is based on binary
I haven't been on PP&CG for a while, so I thought I would post something!
Your task is to find how "smooth" a natural number is. Your method is to:
1: Convert the number to binary
2: Find the number of changes / switches
3: Find the length of the string (in binary)
4: Divide length by changes
So, an example. 5.
Starting at step one, we wind up with 101 for binary.
Step two is where we count the "switches". This is how many times a digit changes, so 100001 would count 2 switches. 101 counts 2, too.
Step three has a length of three in binary.
Step four gives us 3/2, or 1.5.
Doing this for 10 is also simple: Step one results with 1010, two with three, three with four, and a final result has 1.33333333... repeating.
If the inputs output infinity (examples: 1, 3, and 7), you need to output something that tells you infinity, like \$\infty\$ or Infinity.
Now, you might ask, "what about scoring?" or something like that: You are scored in characters, so feel free to use a lot of code golfing languages. (I'm looking at you, Jelly)
If you round the output "smoothness factor" to 3 decimal places (4/3 is now 1.333, 5/3 is 1.667) your score is now x0.95, and being able to not only return a smoothness factor but also be able to compare two numbers (etc: putting in 5 and 10 returns > because 5's smoothness factor is greater than 10's) multiplies your value by x0.7. Command-line flags don't count for anything.
Have fun!
This challenge ends the 19th of March.
Current placeholders: The functional language holder, with 45 chars, Nahuel Fouilleul, and the code golf language holder, with 7 chars, Luis Mendo.

It would be a bit clearer if both examples were given separately. Also, I don't think the bonuses add much to the challenge.

welcome to PPCG! You've been around for a month or so, but I would suggest using The Sandbox to get feedback on your challenges before posting them.

Inputs 1, 3, 7 etc give infinity. Should we really output infinity for those?

No. If you put in 5 10, you will get >, but 10 5 gives <.

? I don't quite clearly understand what you're trying to say.

What is the reason for the complexity around scoring?

Hi, I downvoted this challenge due to the complexity around the scoring and the ambiguous-ness related to it.

I would suggest that if you are going to select an accepted answer at least wait 1 week

And if you do accept an answer, it should be the best one according to your own cumbersome scoring system.

I don't really see the point of scoring in characters. Almost all golfing languages, e.g. Jelly, have the same amount of bytes as characters anyway, so your reasoning isn't valid.

Perl 5 (-p -Mbignum), 45 bytes
$_=sprintf"%b",$_;$_=y///c/(s/(.)(?!\1)//g-1)

TIO

MATL, 7 characters
Btnwdz/

Try it online!
Explanation
B    % Convert to binary
t    % Duplicate
n    % Number of elements
w    % Swap
d    % Consecutive differences
z    % Number of nonzeros
/    % Divide

Honestly, how it it possible to incorporate 7 ASCII characters to make a complicated program like the one I described. I don't understand code golf anymore.

@Ethan Wait for the 4-byte Jelly or 05AB1E answers...

Note that in my original post I said you would be counted by chars, not bytes. Still stands.

@EthanSlota MATL is at least pretty easy to understand, since for the most part, each command is a MATLAB or Octave command and there's a parser built in Octave / MATLAB. This would translate to something like @(x,b=dec2bin(x))numel(b)/nnz(diff(b)) but it uses Luis' much terser language to achieve the same result.

@EthanSlota: Counting by chars instead of bytes can only make the scores even lower.

@LuisMendo I doubt I will find any 4-byters in 05AB1E. ;) Currently sitting at 8 tbh.. >.>

Honestly, I don't know how this hasn't been passed yet. And in ASCII!

Japt, 8 bytes
NULL for infinity
¤Ê/¢ä¦ x

Try it online!

Jelly, 8 bytes, score 8
Maybe there is a terser way... edit: I don't think there is.
BL÷BITLƲ

Infinity is given as inf.
Try it online!
...other 8's are possible too, for example BµITL÷@L or BL÷BnƝSƊ.

Here’s a version to get the bonuses: Try it online! score 16 x 0.95 x 0.7 = 10.64

Shouldn't inf be greater than all other values? If we can identify inf as less than all others we could accept a list of either one or two numbers and have BL÷BITLƲ),M for 11 * 0.7 = 7.7. (Maybe this comparison should be fixed...)

...BTW that isn't doing what you think IṠ$ is acting on the input list itself so it's just telling you that 10 is greater than 5 rather than comparing the smoothness of the two numbers.

Thanks - still getting my head around Jelly. This seems better: tio but is two bytes longer

JavaScript (ES6),  46 44  40 bytes / characters
Returns Infinity if there's no bit flip.
n=>(g=s=>n&&1+g(x=s-(n^(n>>=1))%2))``/~x

Try it online!
Commented
n => (                  // n = input integer
  g = s =>              // g = recursive function taking the number s of bit switches
    n &&                //   stop if n is equal to 0
    1 +                 //   otherwise, add 1 to the final returned value
    g(                  //   and do a recursive call to g:
      x =               //     update s and save the result in x:
        s -             //       subtract 1 from s if ...
        (n ^ (n >>= 1)) //       ... there is a bit switch; and shift n to the right
        % 2             //       NB: an extra bit switch is counted on the last bit
    )                   //   end of recursive call
)``                     // initial call to g with s = [''], which is coerced to 0
                        // as soon as something is subtracted from it
/ ~x                    // divide the result of g by -(x + 1), which compensates for
                        // the extra switch

05AB1E, 8 bytes/characters
bgIbγg</

Try it online or verify all test cases.
Or alternatively:
b©g®¥ÄO/

Try it online or verify all test cases.
Outputs 0.0 for the INF cases.

With both bonuses score: 11.97 (18 bytes/characters * 0.95 * 0.7):
εbgybγg</3.ò}DÆ.±)

Outputs 1 if the first input is larger than the second; -1 if vice-versa; 0 if they are equal.
NOTE: Because I output 0.0 for the INF cases, they are considered lower than non-infinity test cases. Let me know if this has to be fixed..
Try it online.
Explanation:
ε       # Map both values of the (implicit) input-list:
 b      #  Get the binary-string of the current value
  g     #  And get the length of this string
 yb     #  Get the binary-string of the current value again
   γ    #  Split it into chunks of equal adjacent digits
    g<  #  Get the amount of chunks, and subtract 1
 /      #  Divide both numbers
 3.ò    #  Round the number to 3 decimal values
}D      # After the map: duplicate the resulting list
  Æ     # Reduce the duplicated list by subtraction
   .±   # And get the sign of that result
     )  # Then wrap it into a list with the mapped values
        # (and output the result implicitly)

For clarification, ∞ ≠ 0.

@LuisMendo Yes, but 05AB1E doesn't have an infinite value (unless you count the infinite list). And since regular cases which divide x by y can never result in 0 anyway, I use that to indicate infinity (the challenge description states "you need to output something that tells you infinity", which is 0.0 in my answer). If the infinite list or an empty string or something has to be output instead of 0 it's 3 bytes more, although I don't really see the point..

I'll accept this answer as valid as there are no fractions that naturally result in zero. You would need to define something (like 5/1 = 0 = Infinity) to get 0.

@KevinCruijssen Ah, I see. Thanks for clarifying

Ruby, 42 bytes
->n{1.0*(w=(n^n/2).digits 2).size/~-w.sum}

Try it online!
How?
First step: bitwise XOR of x and x/2. The result will have a bit set to 1 for every switch in the input number plus 1, and so we just need to get the number of digits in base 2, and their sum. Then add some parentheses, and make it a float.

Kotlin, 83 82 bytes
{s->s.toString(2).run{length.toFloat()/(0..length-2).count{this[it]!=this[it+1]}}}

Try it online!

Welcome to PPCG! :)

1. Python 3, 131 bytes (154 with file header)
Hi. I know that my code is way longer than others, but I will try it ;) Indentation by tabs.
Script takes sequence of numbers in aguments and prints "smoothness" for each argument on own line. If number of changes is 0, prints "inf".
$ ./script.py 12
4.0

$ ./script.py 12 5 6
4.0
1.5
3.0

$ ./script.py `seq 5`
None
2.0
None
3.0
1.5

file header
#!/usr/bin/env python3

code
import sys
for n in sys.argv[1:]:
    b=bin(int(n))[2:];c=0;l=b[0]
    for o in b:
        if o!=l:c+=1
        l=o
    print(len(b)/c if c>0 else"inf")

Input single number from STDIN: 102+23 bytes (code + file header)
n=input();b=bin(int(n))[2:];c=0;l=b[0]
for o in b:
    if o!=l:c+=1
    l=o
print(len(b)/c if c>0 else"inf")

R, 56 bytes
length(y<-(x=scan())%/%2^(0:log2(x))%%2)/sum(diff(y)!=0)

Try it online!

Charcoal, 24 characters
≔⍘Ｎ²θ≔⁺№θ10№θ01η¿ηＩ∕Ｌθη∞

Try it online! Link is to verbose version of code. Explanation:
≔⍘Ｎ²θ

Input the number and convert it to base 2 as a string.
≔⁺№θ10№θ01η

Calculate the number of of switches by counting the occurrences of 10 or 01 in the string.
¿ηＩ∕Ｌθη∞

If the total is nonzero then output the smoothness otherwise print Infinity.

Python 3.8 (pre-release), 60 bytes
Port of G B's Ruby answer.
lambda l:(c:=(b:=bin(l^l>>1)).count('1'))>1and(len(b)-2)/~-c

Try it online!

Python 2, 68 bytes
Returns false if the value is infinite.
k=input()
n=s=0
while k:l=k%2;n+=1.;k/=2;s+=l^k%2
print s>1and n/~-s

Try it online!

Python 3, 105 chars
def s(n):b=bin(n)[2:];l=len(b);c=sum([0if b[i]==b[i+1]else 1for i in range(l-1)]);return l/c if c>0else-1

Returns -1 in the case of an infinity.

J-uby, 42 bytes
~:digits&2|:/%[:+@|Q,:chunk+I|A|:+@|:pred]

Attempt This Online!

q, 30 bytes
Outputs infinity 0w for 1, 3, 7 etc.
{count[b]%-1+/differ b:2 vs x}

k, 21 bytes
{(#x)%-1+/~~':x:2\:x}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Is it possible to make a clamp function shorter than a ternary in JS?
Imagine this short function to clamp a number between 0 and 255:
c = n => n > 0 ? n < 255 ? n : 255 : 0

Is this the shortest possible version of a clamp function with JavaScript (without ES.Next features)?
P.S: Not sure if it's relevant but, the 0 and 255 are not random, the idea is to clamp a number as an 8-bit unsigned integer.

Hi and welcome to PPCG! Just to be clear, any answer you receive here will not necessarily be a good idea to use in anything except for code golfing. Aside from that, if you care about what version / environment it has to work in you might want to specify it.

Oh, I'm well aware. I've updated the question a bit. Thank you :)

Shouldn't you at least remove all the spaces?

I don't know JS, but one way to clamp is to sort [0,n,255] and take the middle element -- might that be shorter?

@xnor Unfortunately, the JS sort() method uses a lexicographical comparison by default, so that would require an explicit callback. (Something like that.)

@Arnauld Wow, that's pretty silly. But it looks like it would be longer even if the sort was numerical.

I can't imagine a case where a length 1 array would be golfier than the approaches suggested, but just out of interest, JavaScript has built in support for clamped 8 bit unsigned ints: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray

20 bytes
For reference, this is the original version without whitespace and without naming the function:
n=>n>0?n<255?n:255:0

Try it online!

19 bytes
We can save a byte by inverting the logic of the ternary tests and using n>>8 to test whether \$n\$ is greater than \$255\$. Because of the bitwise operation, this will however fail for \$n\ge 2^{32}\$.
n=>n<0?0:n>>8?255:n

Try it online!

19 bytes
This one returns \$false\$ instead of \$0\$ but works for \$n\ge 2^{32}\$.
n=>n>255?255:n>0&&n

Try it online!

18 bytes
By combining both versions above, we end up with a function that works for \$256-2^{32}\le n<2^{32}\$ and returns \$false\$ for \$n<0\$.
n=>n>>8?n>0&&255:n

Try it online!
Commented
n =>          // n = input number
  n >> 8 ?    // if n is greater than 255 or n is negative:
    n > 0 &&  //   return false if n is negative
    255       //   or 255 otherwise
  :           // else:
    n         //   return n unchanged

(This is a fixed revision of the code proposed by @ValueInk in the comments.)

17 bytes
We can go a step further by limiting the valid input range to \$-2^{24}< n\le 2^{24}\$:
n=>n>>8?-n>>>24:n

Try it online!
Commented
n =>          // n = input number
  n >> 8 ?    // if n is greater than 255 or n is negative:
    -n >>> 24 //   non-arithmetic right-shift of -n by 24 positions
  :           // else:
    n         //   return n unchanged

Why stop there? If you're extremely liberal with what counts as a 0 (as JavaScript tends to do) you can always go for n=>n>>8?255:n>0&&n for 18 bytes, since false can be coerced to 0 and this will make all negative numbers evaluate to false

@ValueInk If you don't test $n<0$ beforhand, n>>8 will be truthy for any negative input.


text:
Create chunks from an array
Your task is to write a program which given an array and a number, you need to split the array into chunks with size is number.
Rules
Your program will receive an array A , as well as  a positive integer n. The array should then be split into chunks of length n, if the length of the string isn't divisible by n any leftover at the end should be considered its own chunk.

If n is greater than length of array A, you will need to return array A, for example: if n = 4 and array A = [1,2,3], you should return [1,2,3]

The array can contain any type rather than number.

You should not change order (or direction) of any item from left to right. For example if n = 2 and A= [1,2,3]. Any result rather than [[1,2],[3]] will be invalid.

Test Cases
n   A               Output

2   [1,2,3,4,5,6]   [[1,2],[3,4],[5,6]]
3   [1,2,3,4,5,6]   [[1,2,3],[4,5,6]]
4   [1,2,3,4,5,6]   [[1,2,3,4],[5,6]]

This is code-golf, so you the shortest bytes of each language will be the winner.

What type of numbers can the array contain? Only positive integers as in your example? Real numbers? Complex numbers?

Hi @Adám, Arnauld, Luis Mendo, could you please take a look again in the Rules section, I answered all your questions. Thanks!

If n is greater than the length of A we need to return A‽ Are you sure you don't mean [A]?

@Adám, sorry if I make my answers not clearly, I just updated it, could you please take a quick look.

@chaugiang I still think a too large n should return [A], e.g [[1,2,3]]. What if n is exactly the length of A?

@chaugiang Adam is correct imo.  The return value should be consistent.

@chaugiang Can n ever equal 1?

In a strongly typed language, it's simply impossible to return A rather than [A] , which would exclude an awful lot of languages.

This challenge inspire me to create this one Deal the cards to the players. Thank you for the idea :)

Tests are insufficient

Would it be OK if esolangs without arrays participated? Can we, say, take a list of numbers on input and print n numbers per line on output?

@snail_, yes, it should be okay!

05AB1E, 1 byte
ô

Try it online or verify all test cases.
Builtins ftw. :)

Python 3, 61 bytes
lambda A,n:[A,[A[x:x+n]for x in range(0,len(A),n)]][n<len(A)]

Try it online!
Modifies Henry T's existing Python 3 solution to produce valid output for n >= len(A).
Posting as its own answer due to lack of commenting privileges.

JavaScript (ES6), 36 bytes
Takes input as (n)(array).
n=>g=a=>a+a&&[a.splice(0,n),...g(a)]

Try it online!
Commented
n =>                  // n = chunk size
  g = a =>            // g = recursive function taking the array a[]
    a + a             // if a[] is empty, stop recursion and return an empty string
    &&                // otherwise, return an array made of:
    [ a.splice(0, n), //   the next chunk
      ...g(a)         //   followed by the result of a recursive call
    ]                 //   (the last call leads to ...'', which adds nothing)

Now that is a neat and clean solution, and I learned about recursive anonymous functions too!

APL (Dyalog Unicode), 12 bytesSBCS
⊢⊂⍨(⍴⊢)⍴1↑⍨⊣

Big thanks to Adám for basically doing basically all the golfing (and for basically all the APL knowledge I have currently >_>).
Explanation
 ⊂⍨           Partitioned enclose (commuted, i.e. left and right switched) - for each ⍵ in left, ⍺ in right, if ⍺ = 0, create a new sub-array, push ⍵ to latest sub-array
⊢             Right argument of entire expression
       ⍴      Reshape - Change size of right into dimensions specified by left
   (⍴ )       Shape of (here, there is only one dimension - length)
     ⊢        Right argument of entire expression
         ↑⍨   Take (commuted) - takes ⍺ elements from left where ⍺ is right. Extra elements (zeroes here) are automatically added
        1     1
           ⊣  Left argument of entire expression

Execution
Arguments 2, 1 2 3 4 5 6 7. Note that APL arrays are of the form a b c, with optional surrounding parentheses.
           ⊣  2
        1     1
         ↑⍨   1↑2 = 1 0
     ⊢        1 2 3 4 5 6 7
   (⍴ )       ⍴1 2 3 4 5 6 7 = 7
       ⍴      7⍴1 0 = 1 0 1 0 1 0 1
⊢             1 2 3 4 5 6 7
 ⊂⍨           1 0 1 0 1 0 1⊂1 2 3 4 5 6 7 = (1 2)(3 4)(5 6)(7)

Try it online!

Congratulations on your first APL answer. And nicely explained too! Here, have an APL pie:

Prolog (SWI), 90 84 61 bytes
Code:
[]*_*[].
L*N*[P|R]:-length(P,N),append(P,T,L),T*N*R;P=L,R=[].

The input format might be a bit weird, but it is:
A * n * Result.

For example, for the input: n = 2
A = [1, 2, 3, 4, 5, 6]
You would need to use [1, 2, 3, 4, 5, 6] * 2 * Result..
Try it online!

Ungolfed version:
divide([], _, []).
divide(List, N, [Prefix | Result]) :-
    length(Prefix, N), append(Prefix, Remaining, List), divide(Remaining, N, Result)
  ; Prefix = List, Result = [].

Try it online!.

PHP, 15 bytes
$f=array_chunk;

requires PHP 7. Call with $f(ARRAY, N).

I don't think you're required to give another name to a builtin, so this just scores 11, doesn't it?

@Neil I thought that might be a forbidden loophole; but you may be right.

Perl 6, 13 bytes
{*.batch($_)}

Try it online!
Curried function wrapping the batch built-in.

Did they fix that bug where you had to have a ; after the Whatever code?

@JoKing No. You only need a ; when passing arguments with $^a or @_.

Python 2, 39 bytes
i,j=input()
while j:print j[:i];j=j[i:]

Try it online!
Assumes that 1 chunk per line is acceptable output.

36 bytes as a recursive lambda function

@ovs - Very nice and also different enough for you to post as your own answer if you wish.

Brainfuck, 71 bytes
,[>+>+<<-]>>>,[<[>.,<-]>>>++++[<++++++++>-]<.[-]<<<[<+>>+<-]<[->+<]>>>]

Dunno if this counts or not... input format:
<character whose ascii is n>AAAAAAAAAAAAA
For example, in the input:
 1234567890123492034
n is 32 since the ASCII value of space is 32

Takes the input and puts in a space every time n characters pass
Explanation (no commas because that would break the program):
, take n
[>+>+<<-] copy into next two cells (destroys original)
>>>, take first of A into next cell
[ while that input exists
<[>.,<-] if n is nonzero output take next of A subtract one from n
>>>++++[<++++++++>-]<.[-]< n is zero so put a space
<<[<+>>+<-] copy the old n into surrounding cells
<[->+<] move from first cell to second
>>>] take input, do again

Remove the spaces for 71 characters

lol, I thought I removed all of them but I didn't notice those, thanks!

Try reorganizing the cells such that the cells you use more are more accessible (for example, if the input cell (the one where you use , more) is used more it could be put an a cell which is easier to access than if it was placed in other cells) or use a bruteforcer. I am not skilled in golfing in BF so these suggestions may not be helpful.

So far I have n n n A space as my cell setup, if you can think of a better way...

Could A space n n n ... work (or space A n n n...)?

With the first one, it might make it worse (because I'd have to skip over two cells to get to n and back) and the third one might also increase it (because I'd have to jump forward at the beginning to take n first, and it would be the same but backwards otherwise)

Yes, correct. You may look at the question "Tips for golfing in brainf***" for more ways to golf

Clean, 54 bytes
import StdEnv
$n l=[l%(i,i+n-1)\\i<-[0,n..length l-1]]

Try it online!

Python 3, 46 chars
lambda A,n:[A[:n],*(f(A[n:],n)if A[n:]else[])]

-1 thanks to @Collin Phillips.
Try it online!

I was able to get it to 46 characters with recursion

C# (Visual C# Interactive Compiler), 78 77 43 bytes
a=>b=>{int i=0;return a.GroupBy(_=>i++/b);}

Try it online!
I think we should be able to just write int i; because 0 is the default of int. I let it to avoid the error: error CS0165: Use of unassigned local variable 'i'.

F# (.NET Core), 15 bytes
Seq.chunkBySize

Try it online!
Well F# has a builtin...

J, 4 bytes
<\~-

Try it online!
Takes the array as left arg and chunk size as right arg.
Uses a dyadic hook and the infix adverb with a negative argument, which does what we want by definition.
Note: The return type must be boxed because J only allows tables of equal sized items.

CJam, 3 bytes
{/}

This is an anonymous block that takes an array of numbers and a number from the stack, and replaces them by an array of arrays.
Try it online!

Brachylog, 2 bytes
ġ₎

Try it online!

I read the statement, This came to mind immediately =). #builtinsFTW

Elixir, 16 bytes
Enum.chunk_every

Try it online!

Charcoal, 1 byte
⪪

Try it online! Charcoal's default I/O makes it difficult to demonstrate using anything except strings. If you want a full program that takes numeric lists and outputs formatted lists then this can be done as follows:
Ｅ⪪ＡＮ⪫ι,

Try it online! Link is to verbose version of code. Explanation:
  Ａ      Input array
 ⪪       Split into chunks of
   Ｎ     Input number
Ｅ       Map over chunks
     ι  Current chunk
    ⪫   Joined with
      , Literal `,`
        Implicitly print each chunk on its own line

Coconut, 8 bytes
groupsof

Try it online!

PowerShell, 67 65 bytes
-2 bytes thanks AdmBorkBork
param($n,$a)$a|%{$b+=,$_
if($b.Count-ge$n){,$b;rv b}}
if($b){,$b}

Try it online!

You should be able to rv b (alias for Remove-Variable) instead of $b=@() to save two bytes.

V, 6 bytes
òÀf,r

Try it online!
Hexdump:
00000000: f2c0 662c 720a                           ..f,r.

Explanation:
ò           " Until an error happens:
  f         "   (f)ind the...
 À          "     n'th...
   ,        "     ","
            "   (If there are less than n commas after the cursor, throw an error)
    r       "   Replace the char under the cursor with...
     <cr>   "     A newline

Clojure, 14 bytes
#(partition %)

builtins I guess

Hi, welcome. The function should take two arguments: the array to be partitioned and the length of the chunk. Also what happens if the last chunk isn't "full" when using partition?

Haskell, 26 bytes
import Data.Lists
chunksOf

Here's a more interesting version, with just a few more bytes (thanks to nimi for five bytes in each solution):
Haskell, 31 bytes
n![]=[]
n!x=take n x:n!drop n x

Try it online!

I think you can

n!x=take n x:n!drop n x.  Data.Lists provides also chunksOf.

R, 49 36 bytes
function(A,n)split(A,(seq(A)-1)%/%n)

Try it online!
Thanks to Kirill L. for the golf.

How about this, for 36

@KirillL. of course. Thanks!

Japt, 2 bytes
òV

Try it online!

Java 10, 106 80 bytes
L->n->{for(int l=L.size(),i=0;i<l;)System.out.print(L.subList(i,(i+=n)<l?i:l));}

Prints the chunks without delimiter.
Try it online.
106 bytes:
L->n->{var r=new java.util.Stack();for(int l=L.size(),i=0;i<l;)r.add(L.subList(i,(i+=n)<l?i:l));return r;}

Actually returns a list of lists.
Try it online.
Explanation:
L->n->{                       // Method with List and integer parameters and List return-type
  var r=new java.util.Stack();//  Create an empty List
  for(int l=L.size(),         //  Determine the size of the input-List
      i=0;i<l;)               //  Loop `i` in the range [0, size):
    r.add(                    //   Add to the result-List:
      L.subList(i,            //    A sublist of the input-list in the range from `i`
        Math.min(i+=n,l)));   //    to the minimum of: `i` + input-integer or the size
                              //    (and increase `i` by the input-integer at the same)
  return r;}                  //  Return the List of Lists of integers as result

PHP, 45 bytes
function f($a,$b){return array_chunk($a,$b);}

Try it online!

Would just array_chunk be a valid answer?

@Arnauld I dont know. Never golfed in php before although I use it at work.

I'm not 100% sure either, but we can abuse the implicit conversion of undeclared variables to a string and do something like that.

(erratum: I meant undefined constants)

Jelly, 1 byte
s

Try it online!
While the printer makes it look like single-element splits are not wrapped into lists, they actually are.

This night give a better output as to showing that single element arrays are still actually arrays.

Er, is the downvote because I didn’t add @Nick Kennedy’s link?

certainly not from me

K (oK), 10 bytes
{(0N,x)#y}

Try it online!

Ruby, 25 bytes
->n,a{[*a.each_slice(n)]}

Try it online!
If we can return enumerators instead of arrays, then it becomes simply:
Ruby, 21 bytes
->n,a{a.each_slice n}

Try it online!

PicoLisp, 75 74 bytes
(de f(n l)(if(>= n(length l))(list l)(cons(head n l)(f n(tail(- 0 n)l)))))

Try it online!

Wolfram Language (Mathematica), 20 bytes
#2~Partition~UpTo@#&

Try it online!

Perl 5, 42 bytes
$p=<>-1;s/(,.*?){$p}\K,/],[/g&&($_="[$_]")

Try it online!

instead of &&(...) you can do ;... - this will save 3 bytes

also, you can embed expression in regexp using @{[...]}, so writing @{[<>-1]} instead of $p and calculating it will save another byte

hmm, I understand why you did this && (not to put extra brackets when n is at least the length of a), but even the accepted answer does not do that

Red, 46 bytes
func[n l][until[print take/part l n empty? l]]

Try it online!

Ahead, 38 bytes
Input is a series of numbers on stdin. The first number is n, and the rest of the numbers make up the array. Output consists of n comma-separated numbers per line, so each line is a chunk.
~Ilj~#l,'H!t<
vuj{ oN @j<c
>:&}>d2(nOl

Example
In: 2 1 2 3 4 5 6
Out:
1,2
3,4
5,6

In: 4 1 2 3 4 5 6
Out:
1,2,3,4
5,6,

Note there will be a trailing comma if the last chunk is not the right size. Hopefully this is ok.
Try it online!

Factor, 5 bytes
group

Try it online!

Vyxal, 1 byte
ẇ

Try it Online!

Ruby, 17 bytes
proc &:each_slice

Try it online!

APL(NARS), 55 char, 110 bytes
{⍺≤1:,¨⍵⋄z←¯1↓v←,/(k←1+⌊⍺÷⍨≢⍵)⍺⍴⍵⋄0=r←⍺∣≢⍵:z⋄z,⊂r↑↑k⌷v}

this appear to return the right results... test:
  f←{⍺≤1:,¨⍵⋄z←¯1↓v←,/(k←1+⌊⍺÷⍨≢⍵)⍺⍴⍵⋄0=r←⍺∣≢⍵:z⋄z,⊂r↑↑k⌷v}
  o 1 f 1 2 3 4 5 6
┌6────────────────────────────┐
│┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐│
││ 1│ │ 2│ │ 3│ │ 4│ │ 5│ │ 6││
│└~─┘ └~─┘ └~─┘ └~─┘ └~─┘ └~─┘2
└∊────────────────────────────┘
  2 f 1 2 3 4 5 6
 1 2  3 4  5 6
  3 f 1 2 3 4 5 6
 1 2 3  4 5 6
  4 f 1 2 3 4 5 6
 1 2 3 4  5 6
  5 f 1 2 3 4 5 6
 1 2 3 4 5  6
  6 f 1 2 3 4 5 6
 1 2 3 4 5 6
  7 f 1 2 3 4 5 6
 1 2 3 4 5 6

Python 3, 49 bytes
f=lambda x,n:[x[i:i+n]for i in range(0,len(x),n)]

Simple anonymous function implementation with a list comprehension.
47 bytes if you don't count the f= assignment.
Try it online!

Kotlin, 19 bytes
{a,n->a.chunked(n)}

o/ built-ins
Try it online!

GolfScript, 2 bytes
GS has a built-in. Unfortunately the implicit input got in the way.
~/

Try it online!

Thunno 2, 1 byte
ẇ

Try it online!
Yeah, another built-in :p
Polyglots with Vyxal apparently...


text:
Is it a valid penalty shoot-out prefix?
In association football (also known as soccer), a penalty shoot-out is the second tie-breaker measure that may be used in a match which can't end in a tie, after extra time (i.e. association football overtime).
In a penalty shoot-out, the main referee tosses a coin to determine at which goal the shoot-out happens, and then tosses another coin to determine which team starts first. However, the only thing relevant to this challenge is what happens then, described below.
Each team has 5 penalties available at start, and the penalty score is 0-0. If, at any point, a team's remaining penalties aren't enough to change the currently winning team, the shoot-out stops.
If there are no remaining penalties, but both teams' points are equal, an additional penalty is granted to both teams. This is repeated until the points aren't equal.
After the shoot-out stops, the team with the largest penalty score wins the game.
Challenge
Your challenge is, given two lists A and B representing which penalties team A and team B scored respectively, to determine if they represent a valid penalty shoot-out. A shoot-out is valid if the state represented by the input can be reached, regardless of whether the winning team can be determined. Note that you possibly have to test for both scenarios (Team A starting, Team B starting), since, if the state described in the input is reachable for at least one scenario, the input is valid. If the lists' lengths are different, the team represented by the longer one starts first (it can only have one more element than the other one, and the shorter list's team can't start, since then the longer list's team would shoot two penalties in a row, as the shorter list will be prematurely depleted).
Detailed examples
You can skip to the Rules section below, these are only to help solving the challenge.
Suppose you get this shoot-out as input, where - means no goal was scored and X means a goal was scored (it's invalid):
Team A: - X X X X
Team B: - - - - X

Assuming team A starts first:

Team A: - (0 - 0) (max possible score 4 - 5)
Team B: - (0 - 0) (max possible score 4 - 4)
Team A: X (1 - 0) (max possible score 4 - 4)
Team B: - (1 - 0) (max possible score 4 - 3)
Team A: X (2 - 0) (max possible score 4 - 3)
Team B: - (2 - 0) (max possible score 4 - 2)
Team A: X (3 - 0) (max possible score 4 - 2)
Team A already has a higher score than B could ever have, but the input hasn't
ended yet, so it's invalid if team A is first.

Assuming team B starts first:

Team B: - (0 - 0) (max possible score 5 - 4)
Team A: - (0 - 0) (max possible score 4 - 4)
Team B: - (0 - 0) (max possible score 4 - 3)
Team A: X (1 - 0) (max possible score 4 - 3)
Team B: - (1 - 0) (max possible score 4 - 2)
Team A: X (2 - 0) (max possible score 4 - 2)
Team B: - (2 - 0) (max possible score 4 - 1)
Team A already has a higher score than B could ever have, but the input hasn't
ended yet, so it's invalid if team B stars first.

The input is invalid no matter which team starts first, so it's considered
invalid.

On the contrary, here is a valid example:
Team A: X X X
Team B: - - -

Assuming team A starts first:

Team A: X (1 - 0) (max possible score 5 - 5)
Team B: - (1 - 0) (max possible score 5 - 4)
Team A: X (2 - 0) (max possible score 5 - 4)
Team B: - (2 - 0) (max possible score 5 - 3)
Team A: X (3 - 0) (max possible score 5 - 3)
Team B: - (3 - 0) (max possible score 5 - 2)
It can be determined that team A wins, however the input has ended, so it's
valid if team A starts first. Therefore, the input is valid.

Another example, this time with extra penalties:
Team A: X - X - - - X -
Team B: - X X - - - X X

Assuming team A starts first:

Team A: X (1 - 0) (max possible score 5 - 5)
Team B: - (1 - 0) (max possible score 5 - 4)
Team A: - (1 - 0) (max possible score 4 - 4)
Team B: X (1 - 1) (max possible score 4 - 4)
Team A: X (2 - 1) (max possible score 4 - 4)
Team B: X (2 - 2) (max possible score 4 - 4)
Team A: - (2 - 2) (max possible score 3 - 4)
Team B: - (2 - 2) (max possible score 3 - 3)
Team A: - (2 - 2) (max possible score 2 - 3)
Team B: - (2 - 2) (max possible score 2 - 2)
First 5 penalties result in a tie, so we move on to extra penalties.
Team A: -, Team B: - (2 - 2)
Team A: X, Team B: X (3 - 3)
Team A: -, Team B: X (3 - 4)
It can be determined that team B wins, however the input has ended, so it's
valid if team A starts first. Therefore, the input is valid.

Here is a valid input where it's too early to determine the winner:
Team A: X X - -
Team B: - X - X

Assuming team A starts first:

Team A: X (1 - 0) (max possible score 5 - 5)
Team B: - (1 - 0) (max possible score 5 - 4)
Team A: X (2 - 0) (max possible score 5 - 4)
Team B: X (2 - 1) (max possible score 5 - 4)
Team A: - (2 - 1) (max possible score 4 - 4)
Team B: - (2 - 1) (max possible score 4 - 3)
Team A: - (2 - 1) (max possible score 3 - 3)
Team B: X (2 - 2) (max possible score 3 - 3)
The input has ended before the winner can be determined, so it's valid if team A
starts first. Therefore, the input is valid.

Finally, here is an input where the lists' lengths differ:
Team A: - - -
Team B: X X - X

Since team B shot more penalties, it starts first:

Team B: X (0 - 1) (max possible score 5 - 5)
Team A: - (0 - 1) (max possible score 4 - 5)
Team B: X (0 - 2) (max possible score 4 - 5)
Team A: - (0 - 2) (max possible score 3 - 5)
Team B: - (0 - 2) (max possible score 3 - 4)
Team A: - (0 - 2) (max possible score 2 - 4)
Team B: X (0 - 3) (max possible score 2 - 4)
It can be determined that team B wins, however the input has ended, so it's
valid.

Rules

The team that shoots first can be either A or B, you can't assume one will always shoot first.
The lists will either have the same length, or their lengths will differ by one.
You may choose any two distinct and consistent values to represent scored/unscored penalties.
The lists can also be represented as integers converted from bijective base 2, strings or your language's native list format. If a bijective base 2 format is chosen, the input rules apply to the numbers converted to bijective base 2 (so digits 1 and 2 can either mean scored and unscored or unscored and scored respectively). Regular binary is not allowed, as one can't determine the presence of leading zeroes in the intended binary representation.
This is code-golf, so the shortest solution wins. However, please don't be discouraged from answering even if it seems like your language can't "beat the specialized ones".

Test cases
In these test cases, a 0 will represent a no-goal, and a 1 will represent a goal.
Format:
[Team A], [Team B]

Valid inputs:
[], []
[0], [0]
[0], [1]
[1], [1]
[0], []
[1, 1, 1, 1], [0, 0, 1, 1]
[0, 1, 1, 1, 1], [0, 1, 1, 0]
[0, 0, 0, 0, 1], [0, 0, 0, 1, 0]
[0, 0, 0, 0, 1], [0, 0, 0, 1]
[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]
[0, 1, 1, 1, 1], [0, 1, 1, 0, 1]
[1, 1, 1], [0, 0, 0]
[1, 1, 1, 1], [0, 0, 1]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Invalid inputs:
[0, 1, 1, 1, 1], [0, 1, 1, 0, 0]
[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1]
[1, 1, 1, 0], [0, 0, 0]
[1, 1, 1, 1], [0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1]
[0, 0, 0, 0, 1], [0, 1, 1, 1, 0]

Can I return 0 or false for for invalid, and return true for valid?

@EmbodimentofIgnorance "You may choose any two distinct and consistent values to represent scored/unscored penalties." The exact values don't matter, but there must only be two values.

I assume [[0,0],[1,1]] (or any test case where one of the two inner lists has 2 items) is truthy, since the game is still going on (just like the test cases with [[0],[1]] or [[0],[]] are still in progress)?

@KevinCruijssen Yes, because nobody can determine who will win, the outcome might be 3-2. ;-)

JavaScript (ES6),  117 112  109 bytes
Takes input as (a)(b), using \$1\$ for unscored and \$2\$ for scored. Returns \$0\$ or \$1\$.
a=>b=>!(g=(a,b,P=Q=i=5)=>(p=a[5-i])|(q=b[5-i])&&(--i<0?P-Q:P-Q>i|Q+q-P-p>i&p<2)|g(a,b,P+p,Q+=q))(a,b)|!g(b,a)

Try it online!
Commented
a => b =>                   // given a[] and b[]
  !(g = (                   // g is a recursive function taking:
      a,                    //   the results a[] of the team that plays first
      b,                    //   the results b[] of the team that plays second
      P =                   //   the cumulated goals P of the 1st team (relative value)
      Q =                   //   the cumulated goals Q of the 2nd team (relative value)
      i = 5                 //   a counter i
    ) =>                    // and returning a truthy value if something goes wrong
      (p = a[5 - i]) |      // if either the first team
      (q = b[5 - i]) && (   // or the second team is playing this round:
        --i < 0 ?           //   decrement i; if we've played more than 5 penalties:
          P - Q             //     do we already have a goal difference?
        :                   //   else:
          P - Q > i |       //     was the 1st team already guaranteed to win?
          Q + q - P - p > i //     or is the 2nd team now guaranteed to win
          & p < 2           //     while the 1st team failed its last attempt?
      ) |                   //
      g(                    //   do a recursive call:
        a, b,               //     pass a[] and b[] unchanged
        P + p,              //     update P
        Q += q              //     update Q
      )                     //   end of recursive call
  )(a, b) |                 // try g(a, b)
  !g(b, a)                  // try g(b, a); return 1 if at least one of them is falsy

Python 2, 176 169 171 169 bytes
-2 bytes thanks to @Kevin Cruijssen
exec"h=lambda a,b,m:m-%s/2>abs(sum(a)-sum(b));f=lambda a,b:a[5#==b[5#and h(a[:5],b[:5],6)if %s>10else h(a,b,7)and h(a[#,b[#,6)".replace("#",":~-%s/2]")%(("len(a+b)",)*6)

Try it online! (Including some extra test cases not listed above.)
Creates a function f that takes two arguments (the two lists of scored/unscored penalties) and returns True if the scores are possibly valid and False otherwise.
Partial explanation:
First of all, the exec construction is just a way to save a few bytes by not having to repeat the expression len(a+b) more than once. The above piece of code is equivalent to the following:
Update: the new and improved answer is the same byte count with or without exec trickery, so in the interests of simplicity I have removed it.
Update 2: The new bugfixed version includes even more string compression via substitution and exec. Yes, I use % formatting and a .replace on the same string. The code above is equivalent to:
h=lambda a,b,m:m-len(a+b)/2>abs(sum(a)-sum(b))
f=lambda a,b:a[5:(len(a+b)-1)/2]==b[5:~-len(a+b)/2]and h(a[:5],b[:5],6)if len(a+b)>10else h(a,b,7)and h(a[:(~-len(a+b)/2],b[:(len(a+b)-1)/2],6)

The main idea of this answer is to frame the question in terms of "half-points": each successful kick is a half-point and each failed one is a negative half-point. For a set of scores with length \$<=5\$ to be continuable (not len(a+b)>10), the total number of kicks left must have been greater than or equal to the half-point margin between the two teams. When one team has kicked an extra time, a half-point must be subtracted from the margin for various reasons, so this can be simplified by integer-dividing both sides of the equation by two. This is the function h in the code (with the argument m equal to 6).
However, to be a valid set of scores, an input need not be strictly continuable, but it must have been continuable before the last kick to have been made. This condition is equivalent to saying that it must 1) have been continuable the last time both sides had kicked the same number of times and 2) currently be within two half-points of being continuable — which is where the final argument to h comes in: h(a[:~-len(a+b)/2],b[:~-len(a+b)/2],6) tests condition 1) and h(a,b,7) (the 7 representing an extra two allowable half-points in the margin) tests condition 2).
The case where each team has kicked a maximum of five times has thus been settled. (Explanation to be continued for the other case.)
In terms of low-level golfing, I'm doubt there's too much to shave off, but algorithmically it could probably be done quite a bit more simply.

You can golf (%s-1)/2 to ~-%s/2 to save 2 bytes.

@KevinCruijssen Thanks!

Jelly, 62 54 49 bytes
ṫ⁵Ṗm2¬Ạ
N§ỤḢƊ¦LÞṚZFÄµ12R:2U_ṁḣ⁵ṫ-N<Ø.ẠaÇoL<3
ṚÇoÇ

Try it online!
ṫ⁵Ṗm2¬Ạ # helper function to determine whether
        # even indices at or beyond 10 are zero
ṫ⁵      # tail - take every item from 10
  Ṗ     # remove last item
   m2   # take every second item
     ¬  # logical not, will return 1 for an empty list
      Ạ # all
# function to create cumulative score
# difference and check values
N§ỤḢƊ¦    # negate scores for team with lower score
          # (or one of them if both same score)
  LÞṚ     # sort by length, longest first
  ZF      # transpose lists and flatten
  Ä       # cumulative sum
  µ       # this cumulative score difference (CSD)
          # now becomes left value
  12R:2U_ # subtract cumulative score difference from
          # 6,5,5,4,4,3,3,2,2,1
  ṁḣ⁵     # shorten to be no longer than 10 items
          # and no longer than CSD
  ṫ-N<Ø.Ạ # check last two values are greater than 0,-1
  aÇ      # check that helper function also TRUE
  oL<3    # handle very short scores
# main link that calls the above for scores in either order
ṚÇoÇ

Note the footer code at tio is just to handle multiple test cases and print outputs against inputs.
Thanks to @EriktheOutgolfer for golfing off 8 bytes

Nice try! This isn't a very trivial challenge. Some golfs.

Perl 6, 123 bytes
{all map {@^b>@^a||[R,](map {abs(($+=$_)-++$ %2/2)>(5-++$ /2 max++$ %2)},flat roundrobin @a,-<<@b).skip.any},@^a,@^b,@b,@a}

Try it online!
Returns falsey for valid shoot-outs, truthy for invalid ones.
Explanation
# Check whether block returns true (invalid shoot-out) for arguments (a, b) and (b, a)
{all map {...},@^a,@^b,@b,@a}
# Return true (invalid) if array b is longer than a
@^b>@^a||
# Return true (invalid) if any except the last value is true (shoot-out stopped)
[R,](...).skip.any
# Map values from a and negated b, interleaved
map {...},flat roundrobin @a,-<<@b
# Shoot out stopped?
abs(($+=$_)-++$ %2/2)>(5-++$ /2 max++$ %2)
    #     # Accumulator
           #        # Subtract 0.5 for first team
                      #                  # Sequence 4.5 4 3.5 3 2.5 2 1.5 1 1 0 1 0 1 0


text:
Deal the cards to the players
Tonight is card game night! You are the dealer and your task is to write a program to deal the cards to the players.
Given an array of cards and the number of players, you need to split the array of cards into a hand for each player.

Rules
Your program will receive an non-empty array A , as well as a non-zero positive integer n. The array should then be split into n hands. If the length of the string isn't divisible by n any leftover cards at the end should be distributed as evenly as possible.

If n==1, you will need to return an array of array with A as it's only element

If n is greater than the length of A, you will need to return every hand and an empty hand. if n = 4 and array A = [1,2,3], you should return [[1],[2],[3]] or  [[1],[2],[3],[]]. You are free to handle the empty hand with empty, undefined or null.

The array can contain any type rather than a number.

You should not change the order of the array while dealing. For example if n = 2 and A= [1,2,3], any result rather than [[1,3],[2]] will be invalid.

Test Cases
n   A               Output

1   [1,2,3,4,5,6]   [[1,2,3,4,5,6]]
2   [1,2,3,4,5,6]   [[1,3,5],[2,4,6]]
3   [1,2,3,4,5,6]   [[1,4],[2,5],[3,6]]
4   [1,2,3,4,5,6]   [[1,5],[2,6],[3],[4]]
7   [1,2,3,4,5,6]   [[1],[2],[3],[4],[5],[6]] // or [[1],[2],[3],[4],[5],[6],[]]

Demo Program
def deal(cards, n):
	i = 0
	players = [[] for _ in range(n)]
	for card in cards:
		players[i % n].append(card)
		i += 1
	return players

hands = deal([1,2,3,4,5,6], 2)

print(hands)

Try it online!
This is code-golf, so you the shortest bytes of each language will be the winner.
Inspired from Create chunks from array by chau giang

you will need to return every hands and an empty hand contradicts the last test case's first result possibility.

In the future I'd recommend using the Sandbox to iron out problems and gauge community feedback before posting your question to main

@JoKing I fully agree. I didnt think I would have so much edit to do. It is like pushing to prod without deploying on beta first. Thank you for the help.

@aloisdg I can't parse your suggested alternate rule. If the idea is like people often deal to a circle, then all the players that end up with most cards are at the beginning, and players that are at the end may get no cards.

@Adám in the case of the empty hand? You are free to use any value suited in your language.

Can we use zero to indicate a missing card or empty hand e.g. n = 4   A = [1,2,3,4,5,6]      [[1,5],[2,6],[3,0],[4,0]]   or n = 4  A = [1,2,3]    [[1],[2],[3],[0]]

@Graham Yes zero is fine

What if the input array contains a 0?

@Shaggy indeed it would be a problem. I dont know if there is a language without empty or null array where [0] would be the correct way to write it. I would like to avoid [0] but I dont want to block a lang where [0] is the only way to have an empty array.

@Shaggy with n=2 and A=["1","2","3","4","5","6"] the output should be [["1","3","5"],["2","4","6"]] and with n=4 and A=["1","2","3"] I could allow an output with [["1"],["2"],["3"],[0]] if the language cannot to [], null etc.

Given that "the card can be any kind of value (number, object, string, etc.)" then A=[0,1,2] and n=4 would give an output of [[0],[1],[2],[0]].

05AB1E, 3 1 byte
Saved 2 bytes thanks to Adnan
ι

Try it online!
or as a Test Suite
Explanation
ι  # uninterleave

Does exactly what the challenge asks for

I think this should work as well: ι

@Adnan: Yeah thanks :) Only difference is the empty list for n=7, but that is an acceptable output format. I've totally missed that built-in :/

So there is a language with a built-in for this! :D

R, 46 25 bytes
function(A,n)split(A,1:n)

Try it online!
splits A into groups defined by 1:n, recycling 1:n until it matches length with A.

Perl 6, 33 24 bytes
->\b{*.classify:{$++%b}}

Try it online!
Anonymous curried code block that takes a number and returns a Whatever lambda that takes a list and returns a list of lists. This takes the second option when given a number larger than the length of lists, e.g. f(4)([1,2,3]) returns [[1],[2],[3]]
Explanation:
->\b{                  }  # Anonymous code block that takes a number
     *                    # And returns a Whatever lambda
      .classify           # That groups by
               :{$++%b}   # The index modulo the number

Wolfram Language (Mathematica), 28 bytes
(s=#;GatherBy[#2,#~Mod~s&])&

Try it online!

Very cleverly done!

"The array can contain any type rather than a number."

Japt, 2 bytes
Takes the array as the first input.
óV

Try it

Jelly, 6 2 bytes
sZ

Try it online!
Thanks to @JonathanAllan for saving 4 bytes

Does sZ not work?

@JonathanAllan yes, somehow missed that. Do you want to post as separate answer or shall I edit mine?

No you're welcome to edit :)

Python 2, 37 bytes
Code:
lambda x,n:[x[i::n]for i in range(n)]

Try it online!

Haskell, 39 bytes
import Data.Lists
(transpose.).chunksOf

Note: Data.Lists is from the third-party library lists, which is not on Stackage and hence will not appear on Hoogle.

Data.Lists doesn't seem to exist. I would assume that you meant Data.List, but it doesn't contain chunksOf.

chunksOf only seems to appear with the signature Int -> Text -> [Text].1

@JosephSible, it's in the lists package.

@SriotchilismO'Zaic, lots of things don't show up in Hoogle. It's in the split package and re-exported by the lists package. There are versions of chunksOf for lists, text, sequences, and probably other things.

J, 13, 11, 10, 9 bytes
(|#\)</.]

Try it online!
how (previous explanation, fundamentally the same)
] </.~ (| #\)
  </.~          NB. box results of grouping
]               NB. the right arg by...
         |      NB. the remainders of dividing...
       [        NB. the left arg into...
           #\   NB. the length of each prefix of...
              ] NB. the right arg,
                NB. aka, the integers 1 thru
                NB. the length of the right arg

Charcoal, 9 bytes
ＩＥθ✂ηιＬηθ

Try it online! Link is to verbose version of code. Takes input in the order [n, A] and outputs each value on its own line and each hand double-spaced from the previous. Explanation:
  θ         First input `n`
 Ｅ          Map over implicit range
    η       Second input `A`
   ✂        Sliced
     ι      Starting at current index
      Ｌη    Ending at length of `A`
        θ   Taking every `n`th element
Ｉ           Cast to string
            Implicitly print

+1 for making the symbol of "slice" a scissors!

Kotlin, 53 51 49 bytes
{a,n->(0..n-1).map{a.slice(it..a.size-1 step n)}}

The old, incorrect solution only worked for divisors of the array length. I'm certain this can be golfed down.
Try it online!

invalid

Doesn't work when n is not a divisor of the length of the list

I see, thanks. Fixing it now

I believe this is fixed @ASCII-only

sadly this is longer

rip. i got it down to 51 but still trying

looks like you can remove the extra pair ot parens

awesome, how did I miss that!

close

ah man, filterIndexed really kills you

Let us continue this discussion in chat.

Wolfram Language (Mathematica), 25 bytes
#2[[i;;;;#]]~Table~{i,#}&

Try it online!

O_o explanation pls

@ASCII-only ;; ;; is just a slice, roughly equivalent to python's : :; this gets slices of every $n$th element for offsets 1...n

oh yeah, forgot it was ;; not ; lol. was looking at this going "wth is i ; ; ; ; #"

JavaScript (Node.js), 51 bytes
A=>n=>A.map((x,i)=>e[i%=n]=[...e[i]||[],x],e=[])&&e

Try it online!
JavaScript (Node.js), 53 bytes
A=>n=>g=(i=n)=>i?[...g(--i),A.filter(_=>i--%n==0)]:[]

Try it online!

TSQL, 44 bytes
-- @       : table containing the input
-- column c: value of the card,
-- column a: position on the card in the deck
-- @n      : number of players

DECLARE @ table(a int identity(0,1), c varchar(9))
DECLARE @n int = 4

INSERT @ values('1a'),('2c'),('3e'),('4g'),('5i'),('6k')

SELECT string_agg(c,',')FROM @ GROUP BY a%@n

Try it out

Every time I'm on this website I see something new and go "Wow that's impressive, but why?"

@MindSwipe I have answered a lot of questions on StackOverflow, but many of those questions are the same or almost the same - also it feels like I am working for free. The code-golf questions are different every time and I enjoy it more because I get to use methods I rarely otherwise encounter.

Ruby, 81 bytes
def s a,n;a.each_with_index.inject(([[]]*n).map(&:dup)){|b,(c,d)|b[d%n]<<c;b};end

Try It Online

Could you possibly add a link to an online testing environment for ease of verification?

@JonathanFrech There you go.

Welcome to PPCG! There's a lot of optimizations you can do for length; for example, each_with_index is pretty expensive compared to an incrementing counter, map{[]} basically does the same thing as your map(&:dup) trick, anonymous Proc, etc. that can reduce your code down to 59 bytes. Try it online! Also check out the Ruby tips page

APL+WIN 26 or 31 bytes
If individual hands can be represented as columns of a 2D matrix then 26 bytes if an array of arrays then add 5 bytes.
(l,n)⍴((l←⌈(⍴a)÷n)×n←⎕)↑a←⎕

Try it online! ourtesy of Dyalog Classic
or
⊂[1](l,n)⍴((l←⌈(⍴a)÷n)×n←⎕)↑a←⎕

Try it online! Courtesy of Dyalog Classic
Explanation:
a←⎕ prompt for array of cards
((l←⌈(⍴a)÷n)×n←⎕)↑ prompt for integer, pad a with zeros to given even hands
(l,n)⍴ create 2D matrix with each column representing each hand
⊂[1] if required convert to nested vector - APL array of arrays

MathGolf, 9 bytes
\ô_í\%q╞;

Try it online!
Explanation
\           swap top elements (pops both input onto stack)
 ô          start block of length 6
  _         duplicate TOS (will duplicate the list)
   í        get total number of iterations of for loop (the other input)
    \       swap top elements
     %      modulo (picks every n:th item of the list
      q     print without newline
       ╞    discard from left of string/array (makes the next player pick cards starting with the next in the deck)
        ;   discard TOS (removes some junk in the end)

PHP, 85 83 82 bytes
function($a,$n){while($x<$n)$c[]=array_column(array_chunk($a,$n),+$x++);return$c;}

Try it online!
This will not be the shortest entry, but I thought it'd be fun to try and do it using PHP array function built-ins.  Result: long.
Output
1   [1,2,3,4,5,6]   [[1,2,3,4,5,6]]
2   [1,2,3,4,5,6]   [[1,3,5],[2,4,6]]
3   [1,2,3,4,5,6]   [[1,4],[2,5],[3,6]]
4   [1,2,3,4,5,6]   [[1,5],[2,6],[3],[4]]
7   [1,2,3,4,5,6]   [[1],[2],[3],[4],[5],[6],[]]
5   ["9C","QD","2S","4H","6D","AS","9D","TH","5C"]  [["9C","AS"],["QD","9D"],["2S","TH"],["4H","5C"],["6D"]]

Just FYI, instead of print_flat you can just do json_encode sandbox  - dosn't really change the answer any, just thought I would mention it, cheers!

@ArtisticPhoenix well, of course! (facepalm) Thanks! :)

Java (JDK), 90 bytes
A->n->{var o="";for(int h=0,i;h<n;o+="\n")for(i=h++;i<A.length;i+=n)o+=" "+A[i];return o;}

Try it online!
Thanks Olivier Grégoire for the lambda and better incrementing while iterating.

And here, I golfed it down to 90 bytes.

@OlivierGrégoire thanks! Somewhat new to this and was working on the lambda bit but struggling.

Perl 5 -la, 66 56 bytes
$,=<>;map{push@$_,shift@F}1..$,while@F;say"@$_"for 1..$,

Try it online!

C# (Visual C# Interactive Compiler), 43 bytes
a=>b=>{int i=0;return a.GroupBy(_=>i++%b);}

Try it online!

@JoKing [1,2,3], 4 should output [[1],[2],[3]]. You are dealing 3 cards to 4 players. I will update the main question.

It's generally discouraged to post solutions to your own challenges immediately.

@Shaggy ok I will take it into account for the next time. It is fine on so and rpg but I guess the competitive aspect of codegolf made it a bit unfair to self post directly. Make sense.

@Joe king you are right! I made a typo :/

C (gcc), 5 bytes
The compiler flag -Df= (req. leading space) fulfills specification. f(n_cards,n_hands,card_ptr) evaluates to a pointer to a list of hands.
Explanation
In C, it is common practice to implement lists of lists as a single interleaved array, when the number of lists remains constant but all lists can be extended. For example, in this case of dealing cards, it is more common for more cards to get added to each hand than more hands to be added, so it would be reasonable to implement a list of hands as an interleaved list. Coincidentally, the "deck" is such a list, and thus we return the parameter unmodified.
This challenge probably should've been sandboxed.

I think we all agree for the sandbox


text:
Sum integers in a string
Input
A string.
Output
The sum of all integers in the line.
Constraints
1≤Length of line≤500
Sample test Case
Input
the 5is 108 seCONd4 a

Output
117

Explanation
Sum is: 5+108+4=117

Hi there, welcome to PPCG. Challenges for a single language are usually frowned upon here at PPCG. Maybe you could change it to a general challenge: given a string, output the sum of all numbers in the string, ignoring everything else (i.e. "the 5is 108 seCONd4 a" will result in 117 because 5+108+4=117). Also, every 'question' here should have a winning condition tag. In this case I assume it's [code-golf] (being the shortest possible solution)?

It appears that you've posted a similar question on SO, which tends to confirm that it was not designed to be a PPCG challenge and you are looking for 'usable' code rather than golfed code. I'd recommend to improve your original question on SO instead, so that it better fits the rules of the site.

I've overhauled your post to fit our standards. Feel free to edit if the result doesn't suit you.

It would be best if the winning criterion was mentioned in the question directly it can be easy for new users to not realize that there is one when it is relegated to a tag.  Also you should explicitly say how to handle digits placed next to each other, from your example it seems that you treat them as a single number 108, but specification should not be inferred from examples.  You also mention integer does this mean we have to support negative integers?  It would be nice to see how exactly that is supposed to happen.

@Adám https://codegolf.meta.stackexchange.com/a/14840/34718

@mbomb007 Noted.

What about this case string x='-12hello3'; are you counting negative integers (i.e., -12+3 === -9)?

Possible duplicate of  Sum of integers in string, separated by non-numericals such as 'a' and 'Y'

05AB1E (legacy), 5 bytes
.œþOà

Try it online or verify a few more test cases. (Times out for the larger test cases due to the .œ builtin.)
05AB1E, 11 6 bytes
þмS¡þO

Try it online or verify a few more test cases.
Explanation:
.œ      # Get all partitions of the (implicit) input-string,
        # which are all possible ways of dividing the input-strings into substrings
  þ     # Only leave the items consisting of digits for each partition
        # (in the new version of 05AB1E, an explicit `€` is required)
   O    # Sum each inner list
    à   # Pop and push its maximum
        # (after which the result is output implicitly)

þм      # Only leave the non-digits of the (implicit) input-string
        #  i.e. "the 5is 108 seCONd4 a" → "the is  seCONd a"
  S     # Split it into a list of characters
        #  → ["t","h","e"," ","i","s"," "," ","s","e","C","O","N","d"," ","a"]
   ¡    # Split the (implicit) input-string by each of these characters
        #  → ["","","","","5","","","108","","","","","","","4","",""]
    þ   # Remove the empty strings by only leaving the digits
        #  → ["5","108","4"]
     O  # And sum these numbers (which is output implicitly)
        #  → 117

Oh hey, clever usage of ¡!

Javascript, 34 32 bytes
s=>eval(s.match(/\d+/g).join`+`)
Match all digits and join them by a + turning it into 5+108+4, eval the result.
Only works on positive integers.
Saved 2 bytes thanks to Arnauld

f=
    s=>eval(s.match(/\d+/g).join`+`)

g=()=>b.innerHTML = f(a.value)
g()
<input id=a value="the 5is 108 seCONd4 a" onkeyup="g()">
<pre id=b>

I guess using string.length in the console to count characters isn't a good idea when it contains escape characters... Whoops, fixed it. Thx again

A slightly better option would be console.log(f.toString().length), but it's not 100% reliable either.

Or just using TIO...

Perl 6, 14 bytes
{sum m:g/\d+/}

Try it online!
Anonymous code block that returns the sum of all series of digits

R, 64 48 45 bytes
After seeing the PowerShell entry I was able to golf this further.
function(s)eval(parse(,,gsub('\\D+','+0',s)))

Try it online!

t= is sufficient here rather than text

Thanks, I always forget about partial matching, (and the string of ,,, til you get to the option you want).

Retina 0.8.2, 8 bytes
\d+
$*
1

Try it online!

The first line matches all numbers
The second line replaces these by 1s, repeated said number of times
The last line is a match, and counts the total number of 1s in the string

APL (Dyalog Unicode), 11 bytes
Anonymous tacit prefic function
+/#⍎¨∊∘⎕D⊆⊢

Try it online!
⊢ the argument
⊆ partitioned (runs of True become pieces, run of False are separators) by
∊ membership
∘ of
⎕D the set of digits
#⍎¨ evaluate each in the root namespace
+/ sum

Bash, 43 bytes
for n in ${1//[!0-9]/ };{((s+=n));};echo $s

Replaces every non-number with a space, and then sums them together.
-5 bytes thanks to GammaFunction

You can use { } instead of do done.

thank you! I have edited my post

Zsh, 21 bytes
<<<$[${1//[^0-9]/+0}]

Try it online!
  ${1           }  # the 5is 108 seCONd4 a
  ${1//[^0-9]/+0}  # +0+0+0+05+0+0+0108+0+0+0+0+0+0+04+0+0
$[${1//[^0-9]/+0}] # 117

Unfortunately, bash complains because it interprets 0108 as octal. Zsh does not (unless setopt octalzeroes)

PowerShell, 29 bytes
($args-replace'\D+','+0')|iex

Try it online!

I was able to improve my R answer due to the +0 part.

Charcoal, 5 bytes
ＩΣ⁺ψＳ

Try it online! Link is to verbose version of code. Explanation: Charcoal's Sum operator automatically extracts numbers from a string, however if the string contains no non-digit characters then instead it takes the digital sum, so I concatenate a null byte to avoid this. The result is then cast back to string for implicit output.

Haskell, 50 bytes
sum.map read.words.map f
f x|'/'<x,x<':'=x
f _=' '

Try it online!
There's probably a better way, but this is the most obvious one.

Ruby, 32 27 characters
->s{eval s.scan(/\d+/)*?+}

Acknowledgments

-5 bytes thanks to Conor O' Brien

Welcome to PPCG! You could use *?+ instead of .join ?+ for -7 bytes. See ary * str

Java 10, 66 bytes
This is a lambda from String to int.
s->{var r=0;for(var n:s.split("\\D"))r+=new Long("0"+n);return r;}

Negative integers aren't supported. Presumably that's okay.
Try It Online
Acknowledgments

-3 bytes thanks to Embodiment of Ignorance

You can switch [^0-9] for \D for a few bytes, also you can switch long and String for var (though you will have to change the return type to int

Python 3, 63 59 56 bytes
Why not. Obligatory regex answer. Could probably dock off 6 by using Python 2, but whatever. Doesn't apply anymore since I'm using an eval approach instead of using map.

import re;x=lambda y:eval('+'.join(re.findall('\d+',y)))

Explanation:
import re; # Import regex module
x=lambda y: eval(                                 ) # Run as Python code
                  '+'.join(                     ) # Joined by '+'
                            re.findall('\d+',y) # A list of all matches of regex \d+ in string y

Try it online!

Nice! In your TIO you should use z == l[1] instead of z is l[1] though. The current code can give false negatives if the numbers get high enough.

PHP, 40 39 bytes
<?=array_sum(preg_split('(\D)',$argn));

Try it online!
Run with php -nF input is from STDIN. Example:
$ echo the 5is 108 seCONd4 a | php -nF sumint.php
117

Cubix, 17 bytes
?|i.I!/s+q;;>p.O@

Try it online!
    ? |
    i .
I ! / s + q ; ;
> p . O @ . . .
    . .
    . .

Watch it run
A fairly simple one.  I in cubix will take the first integer in the input and push it to the stack.  This has the effect of skipping all the characters.  The rest of it is dealing with the additional and detecting the end of the input.

I! Input an integer and test it for 0
s+q;; If not zero, swap TOS (forces and initial 0) and add.  Push result to the bottom of stack and clean out the top.  Return to beginning.
/i? If zero, redirect and do a character input to check
|?;/ If positive (character) turn right into a reflect, this then pushes it back through the checker ? and turns right onto the pop from stack, leaving 0 on TOS.  The IP then gets redirected back into the main loop.
I>p.O@ if negative (end of input) turn left, do integer input, bring the bottom of stack to top, output and halt.

Haskell, 43 bytes
f s|[(n,r)]<-reads s=n+f r|h:t<-s=f t|1>0=0

Try it online!
Makes use of reads.

Ahead, 13 bytes
This works because I simply scans the input stream for the next token that looks like a number, ignoring anything else.
~Ilj~#
 >K+O@

Try it online!

QuadR, 9 bytes
+/⍎⍵
\D

Try it online!
+/ sum of
⍎ evaluation as APL of
⍵ the result of
\D replacing each non-digit with
  a space

Japt -x, 5 bytes
f/\d+

Try it online!

3 bytes

Attache, 23 bytes
Sum##N=>MatchAll&"\\d+"

Try it online!
A more interesting, but indirect, answer (37  bytes): {Sum!Reap[ReplaceF[_,/"\\d+",Sow@N]]}
Explanation
Sum##N=>MatchAll&"\\d+"

This has the form:
f##g=>h&x

which, when expanded and parenthesized, becomes:
f ## (g => (h&x))

## composes two functions together, => creates a function mapping the left function over the result of the right function, and & binds an argument to a side of a function. For input _, this is equivalent to:
{ f[Map[g, h[_, x]]] }

First, then, we MatchAll runs of digit characters (\\d+). After, we convert each run to an actual integer using the N function. Finally, we take the sum of these numbers using Sum.

APL(NARS), chars 13, bytes 26
{+/⍎¨⍵⊂⍨⍵∊⎕D}

test:
  f←{+/⍎¨⍵⊂⍨⍵∊⎕D}
  f 'the 5is 108 seCONd4 a'
117

C# (Visual C# Interactive Compiler), 117 111 bytes
a=>System.Text.RegularExpressions.Regex.Replace(a,@"\D+"," ").Split(' ').Select(x=>x==""?0:int.Parse(x)).Sum();

Try it online.

Java 8, 53 130 bytes
105 bytes + 25 bytes for regex import
s->{long c=0;for(Matcher m=Pattern.compile("\\d+").matcher(s);m.find();c+=new Long(m.group()));return c;}

Try it online!
Explanation
s->{                                                    // Lambda function
    long c=0;                                           // Sum is zero
    for(Matcher m=Pattern.compile("\\d+").matcher(s);   // Prepare regex matcher
        m.find();                                       // While the string contains unused matches...
        c+=new Long(m.group()));                        // Add those matches to the output
    return c;                                           // Return the output
   }

I don't think this is correct: the (only) example by the OP suggests that consecutive digits should form a single integer, so "123" should produce 123, not 6 like your code does.

That's unfortunate, I'll revise when I can

@Michail revised

Perl 5 -p, 17 bytes
s/\d+/$\+=$&/eg}{

Try it online!

Japt v2.0a0 -x, 3 bytes
Another test drive for my (very-WIP) interpreter.
q\D

Try it
q\D     :Implicit input of string
q       :Split on
 \D     :  Non-digit characters (/[^0-9]/)
        :Implicitly reduce by addition and output

Java (JDK), 98 94 93 bytes
s->java.util.Arrays.stream(s.split("\\D")).filter(t->!t.isEmpty()).mapToLong(Long::new).sum()

Try it online!
-4 bytes by using Long::new instead of Long::valueOf.
-1 byte by shortening the regex - if we're already removing empty strings later, making some extras when splitting is fine.
Explained
s->                            // Lambda (target type is ToLongFunction<String>)
    java.util.Arrays.stream(   // Stream the result of
        s.split("\\D")        // splitting on non-digits
    )
    .filter(t->!t.isEmpty())   // Discard any empty strings
    .mapToLong(Long::new)      // Convert to long
    .sum()                     // Add up the stream's values.

SNOBOL4 (CSNOBOL4), 81 bytes
	S =INPUT
D	S SPAN('0123456789') . N REM . S	:F(O)
	O =O + N	:(D)
O	OUTPUT =O
END

Try it online!

Swift, 109 bytes
func s(a:String){var d=0,t=0;a.forEach{(c) in if let e=Int(String(c)){d=d*10+e}else{t+=d;d=0}};t+=d;print(t)}

Try it online!

Pip, 6 bytes
$+a@XI

Treats -123 as a negative integer. Try it online!
  a     Command-line input
   @XI  Regex find all integers (XI is a variable predefined as the regex `-?\d+`)
$+      Fold on +

If hyphens should be ignored rather than treated as minus signs, then the following works for 7 bytes:
$+a@+XD

XD is a preset variable for `\d`; +XD adds the regex + modifier to it, making it match 1 or more digits.

LiveScript, 38 33 bytes
(.match(/\d+/g)reduce ->+&0+ +&1)

Explanation:
(.match(/\d+/g)reduce ->+&0+ +&1)
(.match                         ) # BIOP, implicit function clause
       (/\d+/g)                   # The regex
               reduce             # After a `)`, the `.` is implicit
                      ->          # Pass a function
                        +&0+ +&1  # & refers to `arguments`, &0 is `arguments[0]` etc.
                                  # `++` is the concat operator hence the space

LiveScript with eval, 27 bytes
->eval it.match(/\d+/g)*'+' # A function using the implicit argument `it` and `ary*str`
eval . (.match(/\d+/g)*'+') # Same, but using function composition