# Distribute a number into a list of values as equal as possible whose sum is equal to that number

Probably a simple code-golf challenge. Given 2 positive integers m and n, make a list of n values that are positive integers whose sum is equal to the number m. Either all values in the output are the same value or the difference is exactly 1.

Examples

For example

• m=6 and n=3 would become 2, 2, 2
• m=7 and n=3 would become 2, 2, 3 or 2, 3, 2 or 3, 2, 2
• m=7 and n=2 would become 3, 4 or 4, 3
• m=7 and n=1 would become 7
• m=7 and n=8 would generate an error because the sum of 8 positive integers cannot be 7.
• m=10 and n=4 would become 3, 3, 2, 2 or any other permutation

Rules

• Both input and output is only about positive integers.
• Either all values in the output are the same value or the difference is exactly 1.
• The order of the values in the list is not important.
• The sum of the values in the list is equal to m.
• When it's not solvable, generate an error or a false value (in case of m=7 and n=8 for example).
• As a result of the other rules m=8 and n=3 would generate any of the permutations of 3, 3, 2 (not 2, 2, 4)

The winner

This is code-golf, so the shortest valid answer – measured in bytes – wins.

• I'm assuming zero is not positive? Jul 12, 2017 at 12:27
• Jul 12, 2017 at 12:28
• @aras I'm no mathematician but from what I've read up it usually depends on context. Some say it is unsigned, some both positive and negative, some positive etc. Jul 12, 2017 at 12:31
• @TheLethalCoder meanwhile, in java (and floating point in general), float a = -0f, b = 0f; System.out.println(a == b); System.out.println(a + "," + b);... produces true and -0.0,0.0. See, positive 0 and negative 0 are clearly two distinct number... the implementation says so! Jul 12, 2017 at 12:35
• @SocraticPhoenix softwareengineering.stackexchange.com/q/280648/92517 Jul 12, 2017 at 23:32

# Python 2, 48 43 bytes

Returns 0 on error.

lambda m,n:m/n and[m/n]*(n-m%n)+m%n*[m/n+1]


Try it online!

### 41 bytes (with @xnor's trick)

Throws NameError on error.

lambda m,n:[m/n or _]*(n-m%n)+m%n*[m/n+1]


Try it online!

# MATL, 7 bytes

:gie!Xs


When there is no solution the output is an array containing at least one zero, which is falsy in MATL.

Try it online!

### Explanation

Consider inputs m = 10 and n = 4.

:      % Implicitly input m. Push [1 2 ... m]
% STACK: [1 2 3 4 5 6 7 8 9 10]
g      % Logical: convert nonzeros to 1
% STACK: [1 1 1 1 1 1 1 1 1 1]
i      % Input n
% STACK: [1 1 1 1 1 1 1 1 1 1], 4
e      % Reshape into matrix with n rows, padding with zeros
% STACK: [1 1 1;
1 1 1;
1 1 0;
1 1 0]
!      % Transpose
% STACK: [1 1 1 1;
1 1 1 1;
1 1 0 0]
Xs     % Sum of each column. Implicitly display
% STACK: [3 3 2 2]


# Mathematica, 33 bytes

#>#2&&Last@IntegerPartitions@##1&


input

[63, 11]

output

{6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5}

outputs False when it's not solvable

m%n|m>=n=map(divn)[m..m+n-1]


Try it online!

# Charcoal, 15 bytes after applying NDD1

¿÷ＮＮＩＥＩη÷⁺ＩθιＩη


Try it online!

Outputs nothing if there is no solution. Link to the verbose version.

1NDD = Neil-Driven Development.

# Charcoal, 32 27 24 20 bytes

ＮμＮν¿÷μνＩＥν⁺÷μν‹ι﹪μν


Try it online!

Outputs nothing if there is no solution. Link to the verbose version.

Of course, I couldn't have golfed it down without Neil's help.

• Removing the Cast operator works for some reason, but this isn't an ideal algorithm... I have a 16-byte solution.
– Neil
Jul 12, 2017 at 13:24
• @Neil Challenge accepted! Jul 12, 2017 at 20:15
• I like the predefined variable, but now knowing that Cast works on lists I'm down to 11 bytes...
– Neil
Jul 12, 2017 at 21:03
• @Neil And I'm still unable to use Map, how on Earth does it work?? Jul 12, 2017 at 21:07
• Map is like the expression version of for, down to using the same loop variable. So in your example, rather than pushing an expression to a list each time, Map automatically collects them up and evaluates to the list of results.
– Neil
Jul 12, 2017 at 21:17

# R, 33 bytes

function(m,n)diff(trunc(0:n*m/n))


A port of Luis Mendo's Octave answer. Pretty sad that this is almost 50% shorter than my previous answer.

Try it online!

function(m,n,o=rep(m%/%n,n),d=m-sum(o))o+c(rep(0,n-d),rep(1,d))


An anonymous function that takes two (mandatory) arguments m and n, and two optional ones which are for golfing purposes. Returns a vector in increasing order. For failure, the first value will be 0, which is falsey in R, since if only uses the first value of the vector (with a warning).

It is essentially equivalent to the following function:

function(m,n){o=rep(m%/%n,n)
d=m-sum(o)
o+c(rep(0,n-d),rep(1,d))}


Try it online!

• pryr::f(diff(trunc(0:n*m/n))) works and is shorter!
Jul 12, 2017 at 21:52

# Gaia, 4 bytes

…÷l¦


There's almost just a built-in for this...

### Explanation

…     Get the range [0 .. m-1].
÷    Split into n roughly even length chunks. Throws an error if the number of chunks if
more than the list's length.
l¦  Get the length of each chunk.

• I thought there was a 4 byte solution too with 05AB1E. Now that it's gone, it makes it easier for me to decide. Congratulations and thanks! Jul 14, 2017 at 6:04

# Jelly, 7 6 bytes

:ȧœsL€


Try it online! Outputs nothing for falsy.

### How it works

:ȧœsL€    Main link. Arguments: m (integer), n (integer)
:         Integer division. Yields 0 if m < n; a positive integer otherwise.
ȧ        Logical AND. Yields 0 if m < n; m otherwise.
œs      Split into n roughly equal groups. Since the left argument is an integer,
this implicitly converts it to [1..m] (or [] for 0) before splitting.
L€    Length of €ach. If the inputs were 7 and 3, the previous result would be
[[1,2,3],[4,5],[6,7]], so this would give [3,2,2].


## TI-Basic, 23 bytes

:Prompt M,N
:N(M≥N
:int(Ans⁻¹randIntNoRep(M,M+N-1


Returns ERR:DIVIDE BY 0 on error

# Octave, 24 bytes

@(m,n)diff(fix(0:m/n:m))


The code defines an anonymous function. The output is a numeric array (row vector). When there is no this array contains at least one zero, which is falsy in Octave.

Try it online!

### Explanation

0:m/n:m produces an array of n+1 values from 0 to m with step m/n. fix rounds each entry towards 0, and diff computes consecutive differences.

As an example, here are all intermediate results for m = 7, n = 3:

>> 0:m/n:m
ans =
0    2.3333    4.6667    7.0000

>> fix(0:m/n:m)
ans =
0     2     4     7

>> diff(fix(0:m/n:m))
ans =
2     2     3

• An array containing a zero is falsy. That seems like a stretch, but I'm don't know Octave either. Coming from Javascript with its coercions, I'd say why the hell not. +1 from me. Jul 12, 2017 at 14:27
• @ChristiaanWesterbeek Thanks! It does sound strange if you come from other languages, but that's how it is in MATLAB/Octave Jul 12, 2017 at 14:30

m!n|n<=m=e$m:(0<$[2..n])
• Also (0<$[1..n-1]) is shorter than replicate(n-1)0. Jul 13, 2017 at 7:29 # C# (.NET Core), 8682 71 bytes using System.Linq;a=>b=>new int[b].Select((x,i)=>(i<a%b?1:0/(a/b))+a/b)  throws an error for invalid inputs. Try it online! -4 bytes thanks to TheLethalCoder -11 bytes thanks to OlivierGrégoire • This is only a code snippet at the moment; you just need to wrap it in an anonymous function or a=>b=> at the start. Jul 12, 2017 at 16:04 • @TheLethalCoder Hmm are you sure? Don't I need to add the using System.Collections.Generic if I return an IEnumerable<int>? Jul 12, 2017 at 16:10 • I got that wrong anyway because you're returning an array (I misread the first part of the ternary). But only if that shows in your code and seeing as the IEnumerable<int> would be in the function definition you won't need to include the using. Jul 12, 2017 at 16:14 • No, Your tip is still good since the code without .ToArray() still compiles. Jul 12, 2017 at 16:18 • @OlivierGrégoire You are right, sorry and thank you. Jul 13, 2017 at 13:20 ## Haskell, 48 bytes m#n|m>=n=iterate(\(a:b)->b++[a+1])(0<$[1..n])!!m


Start with a list of n zeros. Repeat m times: take the first element, add one and put it at the end of the list.

Fails with a pattern match error if n < m.

Try it online!

# Braingolf, 30 bytes

.M>.M/v.mR>[.]$_v%!?[R1+>v]|R=  Try it online! Takes inputs in reverse order (n is first input, m is second) Divides m by n, duplicates the result n times, then loops through and increments one by one m % n times ## Batch, 71 bytes @if %1 geq %2 for /l %%i in (1,1,%2)do @cmd/cset/an=(%1+%%i-1)/%2&echo(  cmd/cset/a doesn't output any separator, so I have to use echo( (( avoids printing ECHO is on.). # PHP>=7.1, 62 bytes for([,$s,$n]=$argv;$n;)$s-=$r[]=$s/$n--^0;$r?print_r($r):0;  PHP Sandbox Online • Clicked your link to the Sandbox, clicked Execute code and I got a Parse error. Jul 12, 2017 at 14:32 • @ChristiaanWesterbeek The sandbox defaults to PHP 7.0.3. – Neil Jul 12, 2017 at 14:37 • With other languages like Octave and MATL a zero in an array is considered falsy, but I don't believe this to be the case with php. I suppose the output has to be falsy within the rules of the language the program is written in. Jul 12, 2017 at 14:44 • @ChristiaanWesterbeek fixed Jul 12, 2017 at 15:16 # Python 2, 41 bytes lambda m,n:(m%n*[m/n+1]+[m/n or _]*n)[:n]  Try it online! NameError when impossible. Python 2, 43 bytes lambda m,n:[c/n for c in range(m,m+n,m>=n)]  Try it online! ValueError when impossible. • have never thought of using NameError to exit via error Jul 12, 2017 at 18:05 # Javascript (ES6), 57 56 53 41 bytes m=>n=>m>=n&&[...Array(n)].map(_=>m++/n|0)  Answer now includes smarter way of creating the values. Thanks @Neil Usage f=m=>n=>m>=n&&[...Array(n)].map(_=>m++/n|0) f(6)(3) // [2, 2, 2] f(7)(3) // [3, 2, 2] f(7)(2) // [4, 3] f(7)(1) //  f(7)(8) // false f(8)(3) // [3, 3, 2]  History First mine (m,n)=>m>=n&&Array(n).fill(~~(m/n)).map((v,i)=>v+(i<m%n)) (m,n)=>m>=n&&Array(n).fill().map((v,i)=>~~(m/n)+(i<m%n))  Then added the spread operator and currying syntax tipped by @Arnauld m=>n=>m>=n&&[...Array(n)].map((v,i)=>~~(m/n)+(i<m%n))  • _=>m++/n|0 saves a bunch of bytes. – Neil Jul 12, 2017 at 13:21 # Java (OpenJDK 8), 80736361 59 bytes n->m->{for(int i=n;i-->0/(m/n);)System.out.println(m++/n);}  Try it online! Note, for currying purpose, m and n are reversed. # Pyth, 11 bytes efqlTeQ./hQ  Try it online! # Husk, 15 bytes S?ø▼Ẋ-mo÷³*⁰Θḣ  Try it online! A port of Luis Mendo's answer. Takes n followed by m as arguments. Outputs an empty list when no solution is possible. # Pyth, 13 bytes KE?>KQ0lMcK*d  Try it online! Output 0 on error. Cheating, 6 bytes lMcE*d  Try it online! The array contains a 0 on error. Sadly this isn't falsy in Pyth. Explanation KE?>KQ0lMcK*dQ # Implicit input Q for m KE # Store n in K *d # Generate a string of length Q containing only spaces cK # Chop this string in K pieces of equal sizes, initial piece longer if necessary lM # For each string, compute the length. Here we already have our result. However if the array contain a zero, we must output a falsy value ?>KQ # If K > Q... 0 # Then display zero, otherwise display the array  # CJam, 13 12 bytes {_2$>/,/z:,}


Try it online!

This is an anonymous block that takes the input as n m on the stack. It would have been a good answer, but the error handling requirement completely killed it.

Errors with a divide-by-zero when it's not possible to solve.

## Explanation

{   e# Stack:                | 3 10
_  e# Duplicate:            | 3 10 10
2\$ e# Copy from back:       | 3 10 10 3
>  e# Greater than:         | 3 10 1 (true)
/  e# Divide:               | 3 10
e# This will cause an error on invalid input.
,  e# Range:                | 3 [0 1 2 3 4 5 6 7 8 9]
/  e# Split on nth element: | [[0 1 2] [3 4 5] [6 7 8] ]
z  e# Transpose array:      | [[0 3 4 9] [1 4 7] [2 5 8]]
:, e# Length of each:       | [4 3 3]
}


If the error-handling requirement is lifted, this can be shortened to 7 bytes, which is a decrease of over 40%:

{,/z:,}
`