38
\$\begingroup\$

Write a program or function that takes an array of non-negative integers as input and outputs a set of vectors/arrays with the elements of the input array in order, split so that each vector sums up to 15. If the sum of the first N elements doesn't "hit 15", then the number that made it pass 15 must be cut off, and the remainder will be the first element of the next vector. This goes on until you reach the end of the input array. If the sum of the final vector is less than 15, then a number must be added at the end to make the sum go up.

I think the rules are more easily understood by looking at the examples:

Input: 3 7 5 10
Output:
3 7 5           <- Sum is 15
10 5            <- 5 is added to make the sum 15

Input: 2 4 5 9 2 3 5 0 2 4 5 0 3
Output:
2 4 5 4          <- Sum 15. 9 is split in two. 
5 2 3 5          <- The first 5 is the remainder of 9
0 2 4 5 0 3 1    <- The last number is added to make the sum 15

Input: 1 1 1            
Output:
1 1 1 12         <- The number 12 is added to make the sum 15

Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Output:
1 2 3 4 5
6 7 2           <- 2 is the first part of 8
6 9             <- 6 is the remainder of 8
10 5            <- 5 is first part of 11
6 9             <- 6 is remainder of 11. 9 is first part of 12
3 12            <- 3 is remainder of 12. 12 is first part of 13
1 14            <- 1 is remainder of 13. 14 is 14
15
15              <- 15 is first part of 16
1 14            <- 1 is remainder of 16. 14 is first part of 17
3 12            <- 3 is remainder of 17. 12 is added to make the sum 15

Input: 20 20
Output:
15
5 10           <- 5 is remainder from the first 20
10 5           <- 10 is remainder from second 20. 5 is added to make the sum = 15.

Input: 100
Output
15
15
15
15
15
15
10 5

Both the input and the output format is optional. Whatever is best in your language.

The shortest code in bytes wins.


Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=65577,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
8
  • \$\begingroup\$ when i hit exactly 15 my programm puts a 0 like Input 15 Output 15 0 is that ok? \$\endgroup\$
    – Eumel
    Commented Dec 3, 2015 at 16:10
  • \$\begingroup\$ @Eumel, it has to be only 15. Sorry... \$\endgroup\$ Commented Dec 3, 2015 at 16:13
  • \$\begingroup\$ is kicking out 0s from input allowed? \$\endgroup\$
    – Eumel
    Commented Dec 3, 2015 at 16:16
  • \$\begingroup\$ No, the zeros must be included. See the second example. \$\endgroup\$ Commented Dec 3, 2015 at 16:28
  • 3
    \$\begingroup\$ This should definitely replace the FizzBuzz test \$\endgroup\$
    – CSᵠ
    Commented Dec 4, 2015 at 0:44

14 Answers 14

16
\$\begingroup\$

Java - 229 200 192 181 172 170 168 bytes

Had already begun, not for the win but for the fun :)
Any suggestion is welcome.

Saved 8 bytes thanks to @ThomasKwa
Saved 20 bytes thanks to @corsiKa
Saved 2 bytes thanks to @Ypnypn
Saved 2 bytes thanks to @user902383

String p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j-->0;)if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+" ";}return s+(15-c);}

170 bytes

String p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j-->0;){if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}}s+=i+" ";}return s+(15-c);}

172 bytes

String p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j>0;){j--;if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}}s+=i+" ";}return s+(15-c);}

181 bytes

void p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j>0;){j--;if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}}s+=i+" ";}System.out.print(s+(15-c));}

192 bytes

void p(int[]a){int c=0,j;String s="";f:for(int i:a){for(j=i;j>0;){j--;c++;if(c==15){s+=(i-j)+"\n";c=0;if(j>=15)continue;if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+" ";}System.out.print(s+(15-c));}

200 bytes

void p(int[]a){int c=0,j;String s="";f:for(int i:a){j=i;while(j>0){j--;c++;if(c==15){s+=(i-j)+"\n";c=0;if(j>=15)continue;else{if(j!=0)s+=j+" ";c+=j;continue f;}}}s+=i+" ";}System.out.print(s+(15-c));}

229 bytes

void p(int[]a){int c=0,j;f:for(int i:a){j=i;while(j>0){j--;c++;if(c==15){System.out.print(i-j+"\n");c=0;if(j>=15){continue;}else{if(j!=0)System.out.print(j+" ");c+=j;continue f;}}}System.out.print(i+" ");}System.out.print(15-c);}

String p(int[] a) {
    int c = 0, j;
    String s = "";
    f: for (int i: a) {
        for (j = i; j-- > 0;)
            if (++c > 14) {
                s += (i - j) + "\n";
                c = 0;
                if (j < 15) {
                    if (j > 0) s += j + " ";
                    c += j;
                    continue f;
                }
            }
        s += i + " ";
    }
    return s + (15 - c);
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Wow, hadn't seen continue actually used in a Java program until now. \$\endgroup\$ Commented Nov 4, 2016 at 16:54
8
\$\begingroup\$

Pyth, 37 bytes

K15VQ=+ZNIgZK=-ZK-NZbIZZ)).?N;I>KZ-KZ

Explained

This is an implementation of Noah's equation in Pyth

K15              Store 15 in K (the max) (K is Autoinitializing, no = needed here)
VQ              For N in the evaluated input
  =+ZN           Set Z(Which in pyth defaults to 0) to Z+N
  IgZK           If Z(row total) is greater than or equal to K (row max)
    =-ZK         Set Z to Z-K (How much the max was exceeded)
    -NZ          Implicitly print N-Z
    b            Implicitly print b (in pyth defaults to a newline)
    IZ         If Z > 0 (There was excess to carry to the next row)
      Z          Implicitly print Z (the excess)
  .?N            Else(the current row count is < the max(15)) output the current number
;                Use infinite )'s in place of )) (to save 1 character)
I>KZ             If K > Z (The max is greater than the current row count)
  -KZ           Implicitly print K-Z (The amount needed for the row to equal 15)

This was my first pyth, so feel free to suggest improvements.

Example:

Input

[1, 3, 4, 5, 9, 8]

Output

1
3
4
5
2


7
8

Note: Much thanks to Isaacg for several bytes of size reduction advice and creating pyth in the first place! Please upvote his comments below :)

\$\endgroup\$
10
  • 2
    \$\begingroup\$ Else was recently changed to be .? instead of E, but I forgot to update the docs. Sorry about that. \$\endgroup\$
    – isaacg
    Commented Dec 3, 2015 at 7:07
  • \$\begingroup\$ @isaacg Thanks isaacg! I should have that working now. Though it only saves 1 byte since the else is 2 characters now. \$\endgroup\$
    – csga5000
    Commented Dec 3, 2015 at 19:04
  • 1
    \$\begingroup\$ Fixing it as we speak. \$\endgroup\$
    – isaacg
    Commented Dec 3, 2015 at 19:08
  • 3
    \$\begingroup\$ A couple of other suggestions: =Z+ZN and =+ZN are the same. It's a bit like Python's +=. Likewiese, =Z-ZK -> =-ZK. Also, you don't need the ) at the end - it's filled in automatically. Finally, FNQ and VQ are the same. \$\endgroup\$
    – isaacg
    Commented Dec 3, 2015 at 19:10
  • 1
    \$\begingroup\$ You can save another 2 byte by replacing I>Z0 with IZ - Z can't be negative, so you're really just checking if Z is not zero, and zero is falsy, while all other numbers are truthy. \$\endgroup\$
    – isaacg
    Commented Dec 4, 2015 at 22:49
7
\$\begingroup\$

Python 3 - 1̶7̶7̶ 1̶3̶8̶ 1̶6̶6̶ 1̶3̶3̶ 113

s=0
i=15
p=print
for e in eval(input()):
 if s>=i:p()
 s=s%i+e
 if s>i:s-=i;p(e-s);p();e=s
 p(e)
if s!=i:p(i-s%i)

Edit 5 Truly golfed thanks to @poke *removed line breaks etc

Edit 4 Aliased print, and replaced a = with a -= to save a byte. Thanks to @poke and @elzell. Also moved input eval into for loop to save 2 bytes from assignment

Edit 3 Found savings in different OO inside second if

Edit 2 Fixed bug

Edit 1 Changed the input to be in the form '[1,2,3,4,5...]', and implemented first two comments, big thanks to @Morgan Thrapp

First time poster here. Input is command line with entries separated by spaces, output is entry per line, with a newline between groupings.

\$\endgroup\$
17
  • 3
    \$\begingroup\$ You can get it down to 122 by assigning 15 to a variable and only using one space for indentation. \$\endgroup\$ Commented Dec 2, 2015 at 21:57
  • \$\begingroup\$ Also, you fail the second test case, I get 2 3 5, but it should be 5 2 3 5. \$\endgroup\$ Commented Dec 2, 2015 at 22:01
  • 1
    \$\begingroup\$ @AdamMartin You may be interested in my Pyth version of your code \$\endgroup\$
    – csga5000
    Commented Dec 3, 2015 at 1:59
  • 1
    \$\begingroup\$ Since you’re using print so often, you should save it as a variable: p=print. Saves you another 14 characters. \$\endgroup\$
    – poke
    Commented Dec 3, 2015 at 12:05
  • 2
    \$\begingroup\$ Current count is 132, but you can get it down to 113 if you remove some of the line breaks. You can combine every if into a single line, e.g. if s>i:s-=i;p(e-s);p();e=s for the second one. That saves you line breaks and indentation characters. \$\endgroup\$
    – poke
    Commented Dec 3, 2015 at 22:04
7
\$\begingroup\$

Haskell, 126 107 102 100 bytes

[]#c=[]
(h:t)#c|s<0=t#u|s<1=u:t#[]|1<2=(c++[h-s]):(s:t)#[]where s=sum c+h-15;u=c++[h]
(#[]).(++[14])

Usage example: (#[]).(++[14]) $ [1..17] -> [[1,2,3,4,5],[6,7,2],[6,9],[10,5],[6,9],[3,12],[1,14],[15],[15],[1,14],[3,12]]

Edit: @Stewie Griffin helped me saving 19 bytes. Thanks!

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

CJam, 39 bytes

q~0af*Sf*N*30/{S-N/:,F1$:+-+0+e`W<e~p}/

Test it here.

This feels very suboptimal, but so far all my attempts at a shorter solution have been foiled by the presence of zeros in the input.

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

Python2powered by RegEx: 158 155 bytes

Made in python with love and almost no math.
Or Regex Math if you will, unary math.
'Real' math used only to 'fix' the last requirement:

If the sum of the final vector is less than 15, then a number must be added at the end to make the sum go up.

Codegolfed:

import re
def f(i):o=[map(len,p.split())for p in re.findall('((?:x *){15}|.+)',' '.join(['x'*c for c in i]))];l=sum(o[-1]);o[-1]+=([],[15-l])[l<15];print o

The way this works is by converting each number N into a string of length N (x chosen as the char to fill up the string) and joining them all into a space separated string. Resulting string is split via RegEx BLACK MAGIC into something like:

['x xx xxx xxxx xxxxx ', 'xxxxxx xxxxxxx xx', 'xxxxxx xxxxxxxxx', 'x']

for an input like: f([1, 2, 3, 4, 5, 6, 7, 8, 10])
That's then split again, and the length of consecutive xes is used to create the numbers again, everything packed nicely in a list comprehension.

Ungolfed:

import re
o = [map(len, p.split()) for p in re.findall('((?:x *){15}|.+)', ' '.join(['x'*c for c in i]))]
l = sum(o[-1])
o[-1] += ([], [15-l])[l<15]
print o

Output:

>>> f([30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16])
[[15], [15], [1, 2, 3, 4, 5], [6, 7, 2], [6, 9], [15], [1, 14]]

Note: there wasn't enough magic for the 0s so this entry disqualifies

zeros must be included. See the second example

\$\endgroup\$
1
  • \$\begingroup\$ All those function names are rather expensive. Makes using something like regex nearly impossible in code golf. Still, your byte size isn't bad considering \$\endgroup\$
    – csga5000
    Commented Dec 9, 2015 at 6:27
3
\$\begingroup\$

Seriously, 88 bytes

,`'!*'0`M' j0╗`;;;'|ε35*('!=╜+;╗%(' =|('0=|I)`Mεj'|@s`ôl`╝`ö'0@s╛M`Md;Σ35*-;`X``@q`Iƒ@q.

Try it online

It's my first Seriously answer! Now I'm intimately familiar with all the language's shortcomings!

Hex Dump:

2c6027212a2730604d27206a30bb603b3b3b277cee33352a2827213dbd2b3bbb252827203d7c2827303d7c49
29604dee6a277c407360936c60bc609427304073be4d604d643be433352a2d3b60586060407160499f40712e

Explanation:

,`'!*'0`M' j         Replace all the numbers by "0"+"!"*n, separated by " "
0╗                   Initialize an accumulator in register 0
` ... `M             Map the string with the following function:
   ;;;'|ε                Put three extra copies of the character, a pipe, an empty string
   35*                   and a 15 on the stack.
   ('!=                  Move one copy of the character to the top and push 1 if it's a !
   ╜+                    Load the accumulator, add the 1 or 0 from the preceding test
   ;╗                    Make a copy, and save it back to register 0
   %                     Modulo the sum by 15
   (' =|                 Or the result with whether the dug-up character is " "
   ('0=|                 Or the result with whether the dug-up character is "0"
   I                     If we're at " " or "0" or the current sum is not divisible by 15,
                         push empty string, else push "|"
   )                     Bury the new character under the original character.
εj                   Join the list that resulted from the map into a single string.
'|@s                 Resplit the string on occurrences of "|" (after every 15 "!"s)
`ôl`╝                Store a function in register 1 which trims whitespace
                     and returns the length of the remaining string
` ... `M             Map the list with the following function:
   ö                     Trim leading spaces.
   '0@s                  Split the string on occurrence of "0"
   ╛M                    Map the resulting list with the function stored in register 1
d;                   Push the last sublist from the resulting list and make a copy.
Σ                    Find the sum of the list.
35*-                 Subtract it from 15
;`X``@q`Iƒ           Duplicate it, drop it if it's zero, put it in the list otherwise.
@q.                  Put the list back in the big list and print it.
\$\endgroup\$
5
  • \$\begingroup\$ If Unicode code points are used, then do those characters count as 2 bytes each? :P \$\endgroup\$
    – Dan
    Commented Dec 4, 2015 at 13:39
  • \$\begingroup\$ I'm using the unicode in the depicted source so that it can be read the way it is meant to look. Otherwise it would look like random garbage full of unprintables. The official source is the hex dump. \$\endgroup\$
    – quintopia
    Commented Dec 4, 2015 at 18:36
  • \$\begingroup\$ It was meant to be a humorous question \$\endgroup\$
    – Dan
    Commented Dec 4, 2015 at 18:41
  • 1
    \$\begingroup\$ It was also a reasonable question another reader might wonder about, so I answered it humorlessly. \$\endgroup\$
    – quintopia
    Commented Dec 5, 2015 at 0:57
  • \$\begingroup\$ @quintopia +1 For trying a new golfing language! New languages are fun ;) I tried pyth for my first time on this question as well. \$\endgroup\$
    – csga5000
    Commented Dec 11, 2015 at 9:34
3
\$\begingroup\$

Javascript, 138 128 bytes

i=>eval("for(o=z=n='',m=15,t=q=0;q<i.length;q++)(t+=c=+i[q])>=m?(t-=m,z+=c-t,o+=z+`\n`,z=t>0?t+' ':n):z+=c+' ';t<m?o+z+(m-t):o")

With whitespace:

i => eval("
  for(o=z=n='', m=15, t=q=0; q < i.length; q++)
    (t+=c=+i[q])>=m
      ?(
        t-=m,
        z+=c-t,
        o+=z+`\n`,
        z=t>0?t+' ':n)
      :
        z+=c+' '
    ;
  t<m ? o+z+(m-t) : o
")

Example:

Assign the function to a variable

sumFifteen=i=>eval("for(o=z=n='',m=15,t=q=0;q<i.length;q++)(t+=c=+i[q])>=m?(t-=m,z+=c-t,o+=z+`\n`,z=t>0?t+' ':n):z+=c+' ';t<m?o+z+(m-t):o")

Then evaluate like so:

console.log(sumFifteen([1,4,11,4,5]))

1 4 10
1 4 5 5

Revision history:

12/3/2015 00:02 - Thanks to user81655(+1 him in the comments) for 10 byte improvement

12/2/2015 21:44 - Switched to use functional style in-order to reduce size.

\$\endgroup\$
5
  • 3
    \$\begingroup\$ You could improve this with these: f= is not needed according to site rules, remove the parentheses from (i), surround with eval so you don't need return or the brackets and replace the if with a ternary so that o is returned and change '\n' to `\n`, merge t+=... with t>=m to remove for loop brackets. Here's your solution in 127 bytes with all these improvements: i=>eval("for(o=z=n='',m=15,t=q=0;q<i.length;q++)(t+=c=+i[q])>=m?(t-=m,z+=c-t,o+=z+`\n`,z=t>0?t+' ':n):z+=c+' ';t<m?o+z+(m-t):o") \$\endgroup\$
    – user81655
    Commented Dec 3, 2015 at 5:30
  • \$\begingroup\$ @user81655 I'll implement some of those changes! When I try yours I get a SytaxError: Unexpected token ILLEGAL(...). Note, in order to test function I added f= \$\endgroup\$
    – csga5000
    Commented Dec 3, 2015 at 5:39
  • 1
    \$\begingroup\$ SO adds some symbols after o+ at the end of the line. Delete o+=z and write it again and it will work. :P \$\endgroup\$
    – user81655
    Commented Dec 3, 2015 at 5:44
  • \$\begingroup\$ @user81655 I don't see how \n makes any difference \$\endgroup\$
    – csga5000
    Commented Dec 3, 2015 at 5:45
  • 1
    \$\begingroup\$ You mean the `\n`? It won't work without it because the code is inside "..." because of the eval. \$\endgroup\$
    – user81655
    Commented Dec 3, 2015 at 5:46
2
\$\begingroup\$

Python 3: 139 bytes

Slightly different approach than the other answer. Produces the actual output from the question because I initially assumed that was a requirement.

def f(l):
 m=15;r,s=sum(l)%m,0
 if r:l+=[m-r]
 while l:
  x=l.pop(0)
  if s+x>m:y=m-s;l[0:0]=[x-y];x=y
  s+=x;print(x,end=' \n'[s==m]);s%=m

Example usage:

>>> f([2, 4, 5, 9, 2, 3, 5, 0, 2, 4, 5, 0, 3])
2 4 5 4
5 2 3 5
0 2 4 5 0 3 1
\$\endgroup\$
2
\$\begingroup\$

Perl, 86 bytes

#!perl -p
s|\d+( ?)|($i+=$&)<15?$&:($a=$&-($i%=15)).$/.($&>$a&&$&-$a.$1)|ge;$\=$".(15-$i)if$i

Counting the shebang as three, input is taken from stdin, space separated.


Sample Usage

$ echo -n 2 4 5 9 2 3 5 0 2 4 5 0 3 | perl sum15.pl
2 4 5 4
5 2 3 5
0 2 4 5 0 3 1
\$\endgroup\$
0
2
\$\begingroup\$

R, 155 bytes

n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}}

With indents and linebreaks:

n=scan()
while(S<-sum(n)){
     C=cumsum(n)
     if(S>14){
         w=which(C>14)[1]
         N=n[1:w]
         n=n[-(1:w)]
         r=C[w]-15
         N[w]=N[w]-r
         if(r) n=c(r,n)
         cat(N,"\n")
         }else{
            cat(n,15-S)
             n=0
             }
      }

Usage:

> n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}}
1: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18: 
Read 17 items
1 2 3 4 5 
6 7 2 
6 9 
10 5 
6 9 
3 12 
1 14 
15 
15 
1 14 
3 12
> n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}}
1: 20 20
3: 
Read 2 items
15 
5 10 
10 5
> n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}}
1: 10 5
3: 
Read 2 items
10 5 
> n=scan();while(S<-sum(n)){C=cumsum(n);if(S>14){w=which(C>14)[1];N=n[1:w];n=n[-(1:w)];r=C[w]-15;N[w]=N[w]-r;if(r)n=c(r,n);cat(N,"\n")}else{cat(n,15-S);n=0}}
1: 2 4 5 9 2 3 5 0 2 4 5 0 3
14: 
Read 13 items
2 4 5 4 
5 2 3 5 
0 2 4 5 0 3 1
\$\endgroup\$
2
\$\begingroup\$

Python 2, 117 bytes

i=input()
while i:
 s=15;r=[]
 while s>0:n=i.pop(0)if i else s;s-=n;r+=[n]if s>=0 else[n+s]
 if s<0:i=[-s]+i
 print r

Takes input as list:

>>[2,4,5,9,2,3,5,0,2,4,5,0,3]
[2, 4, 5, 4]
[5, 2, 3, 5]
[0, 2, 4, 5, 0, 3, 1]
\$\endgroup\$
1
\$\begingroup\$

Perl, 76 bytes

Includes +3 for -p (normally +1, but +3 to play fair with the other perl solution)

Run with the input on STDIN (final newline on input is optional, but MUST be absent for the empty input)

sum15.pl <<< "1 2 3"

sum15.pl:

#!/usr/bin/perl -p
s/$/ 15/;s/\d+/1x$&/eg;s/( *1){15}\K ?/
/g;s/
1*
*$//;s/1+|\B/length$&/eg

Look ma, no calculations whatsoever...

\$\endgroup\$
3
  • \$\begingroup\$ Better late than never! Very nice solution though :) \$\endgroup\$
    – Dada
    Commented Sep 15, 2016 at 18:31
  • \$\begingroup\$ 0s are rather tricky in this solution (represented by extra spaces) and I have to be very careful to properly handle spaces to keep the number of 0s correct. In particular consider inputs where a partial sum is exactly 15, like 1 14 2 13. Try them without the ` ?` and see what happens \$\endgroup\$
    – Ton Hospel
    Commented Sep 15, 2016 at 18:45
  • \$\begingroup\$ Yes, I tried it and saw that 0's where added at the begining of some lines like you say (that's why I deleted my comment 30 seconds after posting it). Thanks \$\endgroup\$
    – Dada
    Commented Sep 15, 2016 at 19:00
0
\$\begingroup\$

Java - 158 155 bytes

Lambda version of https://codegolf.stackexchange.com/a/65590/46866 by yassin-hajaj, Not sure if a valid submission, but dont have enough rep to add a comment on the linked answer. Counted using http://meta.codegolf.stackexchange.com/questions/4944/byte-counter-snippet

a->{int c=0,j;String s="";f:for(int i:a){for(j=i;j-->0;)if(++c>14){s+=(i-j)+"\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+" ";}return s+(15-c);}

158 Bytes

a->{int c=0,j;String s="";f:for(int i:a){for (j=i;j-->0;)if(++c>14){s+=(i-j)+ "\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+ " ";}return s+(15-c);}

Ungolfed

a ->
    {
        int c=0, j;
        String s = "";
        f:
        for (int i : a) {
            for (j = i; j-- > 0; )
                if (++c > 14) {
                    s += (i - j) + "\n";
                    c = 0;
                    if (j < 15) {
                        if (j > 0) s += j + " ";
                        c += j;
                        continue f;
                    }
                }
            s += i + " ";
        }
        return s + (15 - c);
    }

can be used like

Function<int[], String> func =a->{int c=0,j;String s="";f:for(int i:a){for (j=i;j-->0;)if(++c>14){s+=(i-j)+ "\n";c=0;if(j<15){if(j>0)s+=j+" ";c+=j;continue f;}}s+=i+ " ";}return s+(15-c);};
System.out.println(func.apply(new int[]{2, 4, 5, 9, 2, 3, 5, 0, 2, 4, 5 ,0 ,3}));
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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