15
\$\begingroup\$

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.

\$\endgroup\$
9
  • \$\begingroup\$ I'm assuming zero is not positive? \$\endgroup\$ Jul 12, 2017 at 12:27
  • \$\begingroup\$ Indeed it is: en.wikipedia.org/wiki/Integer#Order-theoretic_properties \$\endgroup\$ Jul 12, 2017 at 12:28
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Jul 12, 2017 at 12:31
  • 1
    \$\begingroup\$ @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! \$\endgroup\$ Jul 12, 2017 at 12:35
  • 1
    \$\begingroup\$ @SocraticPhoenix softwareengineering.stackexchange.com/q/280648/92517 \$\endgroup\$
    – jpmc26
    Jul 12, 2017 at 23:32

23 Answers 23

8
\$\begingroup\$

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!

\$\endgroup\$
6
\$\begingroup\$

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]
\$\endgroup\$
5
\$\begingroup\$

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

\$\endgroup\$
5
\$\begingroup\$

Haskell, 30 bytes

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

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Charcoal, 15 bytes after applying NDD1

¿÷NNIEIη÷⁺IθιIη

Try it online!

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

1NDD = Neil-Driven Development.

My previous answer:

Charcoal, 32 27 24 20 bytes

NμNν¿÷μνIEν⁺÷μν‹ι﹪μν

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.

\$\endgroup\$
11
  • \$\begingroup\$ Removing the Cast operator works for some reason, but this isn't an ideal algorithm... I have a 16-byte solution. \$\endgroup\$
    – Neil
    Jul 12, 2017 at 13:24
  • \$\begingroup\$ @Neil Challenge accepted! \$\endgroup\$
    – Charlie
    Jul 12, 2017 at 20:15
  • \$\begingroup\$ I like the predefined variable, but now knowing that Cast works on lists I'm down to 11 bytes... \$\endgroup\$
    – Neil
    Jul 12, 2017 at 21:03
  • \$\begingroup\$ @Neil And I'm still unable to use Map, how on Earth does it work?? \$\endgroup\$
    – Charlie
    Jul 12, 2017 at 21:07
  • \$\begingroup\$ 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. \$\endgroup\$
    – Neil
    Jul 12, 2017 at 21:17
3
\$\begingroup\$

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!

previous answer, 63 bytes:

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!

\$\endgroup\$
1
  • \$\begingroup\$ pryr::f(diff(trunc(0:n*m/n))) works and is shorter! \$\endgroup\$
    – JAD
    Jul 12, 2017 at 21:52
2
\$\begingroup\$

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.
\$\endgroup\$
1
  • \$\begingroup\$ 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! \$\endgroup\$ Jul 14, 2017 at 6:04
2
\$\begingroup\$

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].
\$\endgroup\$
2
\$\begingroup\$

TI-Basic, 23 bytes

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

Returns ERR:DIVIDE BY 0 on error

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$ Jul 12, 2017 at 14:27
  • \$\begingroup\$ @ChristiaanWesterbeek Thanks! It does sound strange if you come from other languages, but that's how it is in MATLAB/Octave \$\endgroup\$
    – Luis Mendo
    Jul 12, 2017 at 14:30
2
\$\begingroup\$

Haskell, 93 89 88 87 86 71 bytes

m!n|n<=m=e$m:(0<$[2..n])
e(a:b:x)|b<a=e$a-1:e(b+1:x)
e(a:x)=a:e x
e x=x

Try it online!

Explanation

The main function here is e. e will take a list and essentially run a rolling pin along it from left to right. While there is an element in the list that is greater than its neighbor to the right we will move one from it to the right.

Now all we have to do is feed this function a sufficiently lopsided list and allow it to do the magic. The list we will choose is just m followed by n-1 zeros. Since that is easy to make.

The last thing we need to do is make sure that the error case is handled. For this we just throw a Non-exhaustive patterns in function error as long as m>n.

\$\endgroup\$
2
  • \$\begingroup\$ I think you can get rid of error[] by failing with a non-exhaustive pattern instead: m!n|m>n=e$m:replicate(n-1)0. \$\endgroup\$
    – Laikoni
    Jul 13, 2017 at 7:26
  • \$\begingroup\$ Also (0<$[1..n-1]) is shorter than replicate(n-1)0. \$\endgroup\$
    – Laikoni
    Jul 13, 2017 at 7:29
2
\$\begingroup\$

C# (.NET Core), 86 82 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

\$\endgroup\$
8
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Jul 12, 2017 at 16:04
  • \$\begingroup\$ @TheLethalCoder Hmm are you sure? Don't I need to add the using System.Collections.Generic if I return an IEnumerable<int>? \$\endgroup\$
    – LiefdeWen
    Jul 12, 2017 at 16:10
  • \$\begingroup\$ 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. \$\endgroup\$ Jul 12, 2017 at 16:14
  • \$\begingroup\$ No, Your tip is still good since the code without .ToArray() still compiles. \$\endgroup\$
    – LiefdeWen
    Jul 12, 2017 at 16:18
  • 1
    \$\begingroup\$ @OlivierGrégoire You are right, sorry and thank you. \$\endgroup\$
    – LiefdeWen
    Jul 13, 2017 at 13:20
2
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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.).

\$\endgroup\$
1
\$\begingroup\$

PHP>=7.1, 62 bytes

for([,$s,$n]=$argv;$n;)$s-=$r[]=$s/$n--^0;$r[0]?print_r($r):0;

PHP Sandbox Online

\$\endgroup\$
4
  • \$\begingroup\$ Clicked your link to the Sandbox, clicked Execute code and I got a Parse error. \$\endgroup\$ Jul 12, 2017 at 14:32
  • \$\begingroup\$ @ChristiaanWesterbeek The sandbox defaults to PHP 7.0.3. \$\endgroup\$
    – Neil
    Jul 12, 2017 at 14:37
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Jul 12, 2017 at 14:44
  • 1
    \$\begingroup\$ @ChristiaanWesterbeek fixed \$\endgroup\$ Jul 12, 2017 at 15:16
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ have never thought of using NameError to exit via error \$\endgroup\$ Jul 12, 2017 at 18:05
1
\$\begingroup\$

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) // [7]
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))
\$\endgroup\$
1
  • 1
    \$\begingroup\$ _=>m++/n|0 saves a bunch of bytes. \$\endgroup\$
    – Neil
    Jul 12, 2017 at 13:21
1
\$\begingroup\$

Java (OpenJDK 8), 80 73 63 61 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.

\$\endgroup\$
1
\$\begingroup\$

Pyth, 11 bytes

efqlTeQ./hQ

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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] [9]]
 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:,}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.