title: The sum is always 15

text:
# Question
Title: The sum is always 15
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>
```

# Answer
## 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 :)
> 8 votes

# Answer
## 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);
}

```
> 16 votes

# Answer
## 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!
> 7 votes

# Answer
## 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.
> 7 votes

# Answer
# Python2<sub>*powered by RegEx*</sub>: ~~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 `x`es 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
> 4 votes

# Answer
## 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.
> 4 votes

# Answer
# 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.
> 3 votes

# Answer
## 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.

```
> 3 votes

# Answer
### 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

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# 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]

```
> 2 votes

# Answer
## 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...
> 1 votes

# Answer
# 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}));

```
> 0 votes

---
Tags: code-golf, math, arithmetic, array
---


title: Is it a Bumpy Word?

text:
# Question
Title: Is it a Bumpy Word?
*(inspired by this challenge over on Puzzling -- **SPOILERS** for that puzzle are below, so stop reading here if you want to solve that puzzle on your own!)*

If a letter in a word occurs alphabetically later than the previous letter in the word, we call that a *rise* between the two letters. Otherwise, **including if it's the same letter**, it's called a *fall*.

For example, the word `ACE` has two rises (`A` to `C` and `C` to `E`) and no falls, while `THE` has two falls (`T` to `H` and `H` to `E`) and no rises.

We call a word *Bumpy* if the sequence of rises and falls alternates. For example, `BUMP` goes rise (`B` to `U`), fall (`U` to `M`), rise (`M` to `P`). Note that the first sequence need not be a rise -- `BALD` goes fall-rise-fall and is also Bumpy.

### The challenge

Given a word, output whether or not it's Bumpy.

### Input

* A word (not necessarily a dictionary word) consisting of ASCII alphabet (`[A-Z]` or `[a-z]`) letters only, in any suitable format.
* Your choice if the input is all uppercase or all lowercase, but it must be consistent.
* The word will be at least 3 characters in length.

### Output

A truthy/falsey value for whether the input word is Bumpy (truthy) or not Bumpy (falsey).

### The Rules

* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

Truthy:

```
ABA
ABB
BAB
BUMP
BALD
BALDY
UPWARD
EXAMINATION
AZBYCXDWEVFUGTHSIRJQKPLOMN

```

Falsey:

```
AAA
BBA
ACE
THE
BUMPY
BALDING
ABCDEFGHIJKLMNOPQRSTUVWXYZ

```

---

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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 leaderboard snippet:

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

```

```
var QUESTION_ID=93005,OVERRIDE_USER=42963;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>
```

# Answer
> 31 votes
# MATL, 4 bytes

```
d0>d

```

Explanation:

```
d     % Implicitly take input. Take difference between each element
 0>   % Check whether diff's are positive. Should result in [0 1 0 1 ...] pattern.
   d  % Again take the difference. Any consecutive rises or falls results in a
      % difference of 0, which is a falsy value in MATL

```

This is my first MATL entry, so I wonder how much improvement there can be from this naive port from my MATLAB/Octave attempt (which would be `@(a)all(diff(diff(a)>0))`). Note that the `all` is not necessary because any zero makes an array false, so there's no `A` in the MATL port.

# Answer
> 24 votes
## JavaScript (ES6), ~~75~~ ~~69~~ ~~63~~ ~~46~~ 43 bytes

Saved 3 bytes thanks to Neil:

```
f=([c,...s])=>s[1]?c<s[0]^s[0]<s[1]&&f(s):1

```

Destructuring the string parameter instead of `s.slice(1)`.

---

Previous solution:
Saved 17 bytes thanks to ETHproductions:
```
f=s=>s[2]?s[0]<s[1]^s[1]<s[2]&&f(s.slice(1)):1

```

What happened from the previous solution step by step:

```
f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b // (63) Original
f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(s[i]<s[i+1]))?f(s,i):b   // (61) No point in reassigning `a`, it's not used again
f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^s[i]<s[i+1])?f(s,i):b     // (59) Remove unnecessary parentheses
f=(s,i=0)=>s[i+2]&&(b=s[i++]<s[i]^s[i]<s[i+1])?f(s,i):b         // (55) `a` is now just a waste of bytes
f=(s,i=0)=>s[i+2]?(b=s[i++]<s[i]^s[i]<s[i+1])?f(s,i):b:1        // (56) Rearrange conditional expressions to allow for more golfing
f=(s,i=0)=>s[i+2]?(b=s[i++]<s[i]^s[i]<s[i+1])&&f(s,i):1         // (55) Rearrange conditional expression
f=(s,i=0)=>s[i+2]?(s[i++]<s[i]^s[i]<s[i+1])&&f(s,i):1           // (53) `b` is now also a waste of bytes
f=(s,i=0)=>s[i+2]?s[i++]<s[i]^s[i]<s[i+1]&&f(s,i):1             // (51) Remove unnecessary parentheses
f=s=>s[2]?s[0]<s[1]^s[1]<s[2]&&f(s.slice(1)):1                  // (46) Use `s.slice(1)` instead of `i`

```

---

Previous solutions:
63 bytes thanks to ETHproductions:
```
f=(s,i=0,a=s[i++]<s[i])=>s[i+1]&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b

```

69 bytes:

```
f=(s,i=0,a=s[i++]<s[i])=>i+1<s.length&&(b=a^(a=s[i]<s[i+1]))?f(s,i):b

```

75 bytes:

```
f=(s,a=s[0]<s[1])=>{for(i=1;i+1<s.length&&(b=a^(a=s[i++]<s[i])););return b}

```

All letters in a word must have the same case.

# Answer
> 13 votes
# LabVIEW, 36 equivalent bytes

Golfed down using logical equivalences:

Ungolfed:

First we convert to lowercase, then to byte array. Trim off the first element of the byte array as it has no precedent. Then, for each element in the array, check if it's greater than the previous one (U8 char maps to ASCII as you expect) and store the result for the next iteration, as well as in an array for viewing overall bumpiness. If the current and prior boolean check are equal, we terminate the loop and it's not bumpy. Else, it's bumpy!

# Answer
> 8 votes
# Python, 56 bytes

```
lambda s:all((x<y)^(y<z)for x,y,z in zip(s,s[1:],s[2:]))

```

All test cases are at **ideone**

Zips through triples of characters in s and tests that all such triples have left and right pairs with different rise/fall properties.
Works for either all uppercase or all lowercase.

# Answer
> 6 votes
# C 59 Bytes

```
r;f(s)char*s;{for(r=0;r=*s?~r&1<<(*s>=*++s):0;);return!*s;}

```

# Answer
> 6 votes
# Ruby, ~~57~~ 48 bytes

Expects input to be all uppercase.

```
->s{!s.gsub(/.(?=(.)(.))/){($&<$1)^($1<$2)}[?f]}

```

See it on repl.it: https://repl.it/D7SB

## Explanation

The regular expression `/.(?=(.)(.))/` matches each character that's followed by two more characters. `(?=...)` is a positive lookahead, meaning we match the subsequent two characters but don't "consume" them as part of the match. Inside the curly braces, `$&` is the matched text—the first character of the three—and `$1` and `$2` are the captured characters inside the lookahead. In other words, if the string is `"BUMPY"`, it will first match `"B"` (and put it in `$&`) and capture `"U"` and `"M"` (and put them in `$1` and `$2`). Next it will match `"U"` and capture `"M"` and `"P"`, and so on.

Inside the block we check if the first pair of characters (`$&` and `$1`) is a rise and the second (`$1` and `$2`) is a fall or vice versa, much like most of the other answers. This `^` expression returns `true` or `false`, which gets converted to a string and inserted in place of the match. As a result, our example `"BUMPY"` becomes this:

```
"truetruefalsePY"

```

Since we know the input is all uppercase, we know `"f"` will only occur as part of `"false"` and `!result[?f]` gives us our answer.

# Answer
> 6 votes
# C#, ~~64~~ ~~63~~ 55 bytes

```
unsafe bool B(char*s)=>1>s[2]||*s<s[1]!=*++s<s[1]&B(s);

```

*-8 bytes from Scepheo's suggestions*

This is a port of Hedi's solution to C#. I also came up with a recursive solution, but the recursion wasn't as good. My original solution is below.

### My Original C#, ~~96~~ ~~94~~ 91 bytes

```
unsafe bool B(char*s,bool f=1>0,int i=0)=>1>s[1]||(s[0]<s[1]?f:1>i?!(f=!f):!f)&B(s+1,!f,1);

```

*-2 bytes by using `1>0` instead of `true`.*

*-3 bytes from Scepheo's suggestions for the port solution above*

Calls itself recursively checking that the rising/falling alternates each time.

Ungolfed:

```
// unsafe in order to golf some bytes from string operations.
// f alternates with each recursive call
// i is 0 for the first call, 1 for all subsequent calls
unsafe bool B(char* s, bool f = 1 > 0, int i = 0) =>
    1 > s[1] ? 1 > 0// (instead of 1 == s.Length) check if s[1] = NULL, and return true.
    : (
        s[0] < s[1] ? f // Rising, so use f...
        : // Else falling
            1 > i ? !(f=!f) // But this is the first call, so use true (but flip f)...
            : !f // Not first call, so use !f...
    )
    & B(s+1, !f, 1) // ...AND the previous value with a recursive call
                    // s+1 instead of s.Substring(1)
;

```

# Answer
> 5 votes
# JavaScript (ES6), 65 bytes

```
s=>[...s].map(C=>(c?(R=c<C,i++?t&=r^R:0,r=R):t=1,c=C),c=r=i="")|t

```

`.map` is definitely not the best solution.

# Answer
> 5 votes
# Python 2, 88 bytes

Simple solution.

```
s=input()
m=map(lambda x,y:y>x,s[:-1],s[1:])
print all(x-y for x,y in zip(m[:-1],m[1:]))

```

**Try it online**

If same letters in a row were neither a rise nor a fall, the solution would be 79 bytes:

```
s=input()
m=map(cmp,s[:-1],s[1:])
print all(x-y for x,y in zip(m[:-1],m[1:]))

```

# Answer
> 5 votes
# Jelly, 6 bytes

```
OI>0IẠ

```

Based on @sanchises' answer.

Try it online! or Verify all.

## Explanation

```
OI>0IẠ  Input: string S
O       Convert each char in S to an ordinal
 I      Get the increments between each pair
  >0    Test if each is positive, 1 if true else 0
    I   Get the increments between each pair
     Ạ  Test if the list doesn't contain a zero, 1 if true else 0

```

# Answer
> 5 votes
# Perl, 34 bytes

Includes +3 for `-p` (code contains `'` so `-e` can't be used)

Give uppercase input on STDIN:

```
bump.pl <<< AAA

```

`bump.pl`

```
#!/usr/bin/perl -p
s%.%$&.z lt$'|0%eg;$_=!/(.)\1./

```

# Answer
> 5 votes
# Jelly, ~~6~~ 5 bytes

-1 byte thanks to @Dennis (use a cumulative reduction)

```
<2\IẠ

```

All test cases are at **TryItOnline**

How?

```
<2\IẠ - main link takes an argument, s,    e.g. "BUMP"    or "BUMPY"
<    - less than comparison (a dyad)
 2   - literal 2 (a nilad)
  \  - n-wise overlapping reduction when preceded by a dyad-nilad chain
       (i.e. reduce the list by pairs with less than)
                                           e.g. [1,0,1]   or [1,0,1,1]
   I  - consecutive differences,           e.g. [-1,1]    or [-1,1,0]
    Ạ - All, 0 if any values are 0 else 1, e.g. 1         or 0

```

Works for either all uppercase or all lowercase.

# Answer
> 5 votes
## Python, 51 bytes

```
g=lambda a,b,c,*s:((a<b)^(b<c))*(s==()or g(b,c,*s))

```

Takes input like `g('B','U','M','P')` and outputs `1` or `0`.

Uses argument unpacking to take the first three letters and check if the first two compare differently from the second two. Then, recurses on the remainder, using multiplication for `and`.

# Answer
> 4 votes
# Java 7, ~~157~~ ~~153~~ ~~150~~ ~~125~~ 117 bytes

```
int c(char[]z){for(int i=2,a,b,c;i<z.length;i++)if(((a=z[i-1])<(c=z[i])&(b=z[i-2])<a)|(a>=c&b>=a))return 0;return 1;}

```

**Ungolfed & test cases:**

Try it here.

```
class M{
  static int c(char[] z){
    for(int i = 2, a, b, c; i < z.length; i++){
      if(((a = z[i-1]) < (c = z[i]) & (b = z[i-2]) < a) | (a >= c & b >= a)){
        return 0; //false
      }
    }
    return 1; //true
  }

  public static void main(String[] a){
    System.out.print(c("ABA".toCharArray()) + ", ");
    System.out.print(c("ABB".toCharArray()) + ", ");
    System.out.print(c("BAB".toCharArray()) + ", ");
    System.out.print(c("BUMP".toCharArray()) + ", ");
    System.out.print(c("BALD".toCharArray()) + ", ");
    System.out.print(c("BALDY".toCharArray()) + ", ");
    System.out.print(c("UPWARD".toCharArray()) + ", ");
    System.out.print(c("EXAMINATION".toCharArray()) + ", ");
    System.out.print(c("AZBYCXDWEVFUGTHSIRJQKPLOMN".toCharArray()) + ", ");

    System.out.print(c("AAA".toCharArray()) + ", ");
    System.out.print(c("ACE".toCharArray()) + ", ");
    System.out.print(c("THE".toCharArray()) + ", ");
    System.out.print(c("BUMPY".toCharArray()) + ", ");
    System.out.print(c("BALDING".toCharArray()) + ", ");
    System.out.print(c("ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()) + ", ");
  }
}

```

**Output:**

```
1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0

```

# Answer
> 4 votes
# Japt, 8 bytes

```
Uä> ä- e

```

Test it online!

### How it works

```
Uä> ä- e  // Implicit: U = input string
Uä>       // Map each pair of chars X, Y in U to X > Y.
    ä-    // Map each pair of items in the result to X - Y.
          // If there are two consecutive rises or falls, the result contains a zero.
       e  // Check that every item is truthy (non-zero).
          // Implicit: output last expression

```

# Answer
> 4 votes
# C# 105 104 Bytes

```
bool f(char[]x){int t=1;for(int i=2,p=x[1],f=x[0]-p>>7;i<x.Length;)f^=t&=p<(p=x[i++])?1-f:f;return t>0;}

```

105 bytes Solution:

```
bool f(char[]x){bool t=1>0,f=x[0]<x[1];for(int i=2,p=x[1];i<x.Length;)f^=t&=p<(p=x[i++])?!f:f;return t;}

```

Try it online

Using an array of chars saved one byte since the space can be omitted after the brackets. `f(string x)` vs `f(char[]x)`

It is 101 bytes if I can return an int 1/0 instead of bool true/false

```
int f(char[]x){int t=1;for(int i=2,p=x[1],f=x[0]-p>>7;i<x.Length;)f^=t&=p<(p=x[i++])?1-f:f;return t;}

```

# Answer
> 4 votes
# Haskell, 52 bytes

```
f x=and$g(/=)$g(>)x
  where g h y=zipWith h(tail y)y

```

I suspect I could get this a chunk smaller if I managed to get rid of the "where" construct, but I'm probably stuck with zipWith.

This works by making a list of the rises (True) and falls (False), then making a list of if the ajacent entries in this list are different

---

This is my first attempt at one of these, so I'll go through my thought process in case I've gone horribly wrong somewhere.

### Ungolfed Version (168 bytes)

```
isBumpy :: [Char] -> Bool
isBumpy input = and $ areBumps $ riseFall input
  where
    riseFall ax@(x:xs) = zipWith (>) xs ax
    areBumps ax@(x:xs) = zipWith (/=) xs ax

```

### Shorten names, remove type information (100 bytes)

```
f x = and $ g $ h x
  where
    h ax@(x:xs) = zipWith (>) xs ax
    g ax@(x:xs) = zipWith (/=) xs ax

```

### Move h into the main function as it is only used once (86 bytes)

```
f ax@(x:xs) = and $ g $ zipWith (>) xs ax
  where
    g ax@(x:xs) = zipWith (/=) xs ax

```

### Realise that areBumps and riseFall are similar enough to abstract (73 bytes)

```
f x  = and $ g (/=) $ g (>) x
  where
    g h ya@(y:ys) = zipWith h ys ya

```

### Note that (tail y) is shorter than ya@(y:ys) (70 bytes)

```
f x  = and $ g (/=) $ g (>) x
  where
    g h y = zipWith h (tail y) y

```

### Tidy up; remove unneeded spaces (52 bytes)

```
f x=and$g(/=)$g(>)x
  where g h y=zipWith h(tail y)y

```

# Answer
> 3 votes
## PowerShell v2+, 83 bytes

```
param($n)($a=-join(1..($n.Length-1)|%{+($n[$_-1]-lt$n[$_])}))-eq($a-replace'00|11')

```

A little bit of a different approach. This loops through the input `$n`, each iteration seeing whether the previous character `$n[$_-1]` is `-l`ess`t`han the current character `$n[$_]`, then casting the result of that Boolean operator to an int with `+`. Those are `-join`ed together into a string, stored into `$a`. We then check whether `$a` is `-eq`ual to `$a` with any substrings of `00` or `11` removed.

# Answer
> 3 votes
# Python 2.7, 84 bytes

```
s=input()
b=s[0]<s[1]
o=1
for i in range(len(s)-1):o&=(s[i]<s[i+1])==b;b^=1
print o

```

Returns 1 for bumpy, 0 for otherwise

Learned some cool stuff with bitwise & and ^.
Starts with boolean b defining first pair as up/down, then tests and flips b for each following pair.
o flips to false if test fails and sticks.
Requires quotes around input (+4 bytes for raw\_input() if that breaks some rule)

Test It

# Answer
> 3 votes
## Python 2.7 (again, ~~84~~ 83 bytes)

```
def a(s):x=s[1:];return[cmp(s[0],x)]+a(x) if x else []
print len(set(a(input())))>1

```

Or, ~~78~~ 77 bytes without the print.

~~By the way, the above 56 byte Python 2.7 example breaks on, for example, `"abbab"` or any other input with repeated characters.~~ Never mind, didn't read instructions. Revising.

Okay, down to 83. The triples one is nicer though.

# Answer
> 3 votes
# 05AB1E, 9 bytes

```
SÇ¥0›¥_O_

```

**Explanation**

```
SÇ          # convert to list of ascii values
  ¥         # take delta's
   0›       # check if positive, giving a list of 1's and 0's
            # if they alternate, the word is bumpy
     ¥      # take delta's again, if we have any 0's in the list the word is not bumpy
      _     # logical negation, turning 0 into 1 and everything else to 0
       O    # sum, producing 0 for a bumpy word and 1 for a non-bumpy word
        _   # logical negation, inverting the previous 1 into 0 and vice versa

```

Try it online!

# Answer
> 2 votes
# PHP, 80 bytes

```
$s=$argv[1];for($c=$s[0];$n=$s[++$i];$c=$n,$d=$e)if($d===$e=$n>$c)break;echo!$n;

```

or

```
for($c=$argv[1][0];$n=$argv[1][++$i];$c=$n,$d=$e)if($d===$e=$n>$c)break;echo!$n;

```

empty output for false, `1` for true

or Hedi´s recursive approach ported and a little golfed for 70 bytes:

```
function f($s){return!$s[2]|$s[0]<$s[1]^$s[1]<$s[2]&&f(substr($s,1));}

```

Actually, this should recurse infinitely for bumpy words, but it does not!

# Answer
> 2 votes
## CJam, 15 bytes

```
l2ew::<2ew::^:*

```

Try it online! (As a linefeed-separated test-suite.)

### Explanation

```
l    e# Read input.
2ew  e# Get all (overlapping) pairs.
::<  e# Check whether each pair is strictly ascending (1) or not (0).
2ew  e# Get all (overlapping) pairs.
::^  e# Take the bitwise XOR of each pair, giving 1 if a rise and a fall alternate,
     e# and zero if there are two rises or two falls in succession.
:*   e# Product. Gives 1 only if the previous step yielded a list of 1s, meaning
     e# that any two consecutive rises/falls will turn this into a zero.

```

# Answer
> 2 votes
# Haskell, ~~30~~ 37 bytes

```
q f=tail>>=zipWith f;k=and.q(/=).q(>)

```

Usage:

```
Prelude> k <$> words "ABA ABB BAB BUMP BALD BALDY UPWARD EXAMINATION AZBYCXDWEVFUGTHSIRJQKPLOMN"
[True,True,True,True,True,True,True,True,True]

Prelude> k <$> words "AAA BBA ACE THE BUMPY BALDING ABCDEFGHIJKLMNOPQRSTUVWXYZ"
[False,False,False,False,False,False,False]

```

# Answer
> 2 votes
# PHP 7, ~~137~~ 118 bytes

```
for($i=0;$i<strlen($argv[1])-2;$i++)if(((($s[$i]<=>$s[$i+1])<0)?1:0)==((($s[$i+1]<=>$s[$i+2])<0)?1:0)){echo"0";break;}

```

Empty output for Bumpy, `0` for Not Bumpy.

This is my first attempt at code golfing and I have to improve a lot, but it was a wonderful method to learn new things for me. I also wanted to challenge myself on that task by using the new PHP 7 Spaceship Operator which seems very interesting.

~~Anyway I'm not satisfied about it, first of all for the fact that I had to add an extra `if(isset($s[$i+2]))` to check if the variable exist because I did not find another workaround to the problem, but this is it for now.~~ (Note: I fixed that simply by changing `strlen($s)-1` to `strlen($s)-2`, I couldn't really see that before...).

**Testing code:**

```
$as = array("ABA", "ABB", "BAB", "BUMP", "BALD", "BALDY", "UPWARD",
            "EXAMINATION", "AZBYCXDWEVFUGTHSIRJQKPLOMN", "AAA", "BBA",
            "ACE", "THE", "BUMPY", "BALDING", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");

foreach ($as as $s) {
    for($i=0;$i<strlen($s)-2;$i++)if(((($s[$i]<=>$s[$i+1])<0)?1:0)==((($s[$i+1]<=>$s[$i+2])<0)?1:0)){echo"0";break;}
}

```

**Test online**

# Answer
> 1 votes
# Javascript ES6, 100 bytes

```
d="charCodeAt";a=b=>{f=r=0;for(i=1;i<b.length;i++){if(b[d](i)<=b[d](i-1)){f=1}else{r=1}}return f&&r}

```

Try it here:

```
d="charCodeAt";a=b=>{f=r=0;for(i=1;i<b.length;i++){if(b[d](i)<=b[d](i-1)){f=1}else{r=1}}return f&&r}
alert(a(prompt()));
```

Oh come on two people already beat me to it by 40 bytes... whatever

# Answer
> 1 votes
# Python 3, ~~148 139~~ 127 bytes

```
def _(w):*r,=map(lambda a,b:0>ord(a)-ord(b)and-1or 1,w,w[1:]);s=len(r)%2==0and r+[r[0]]or r;return sum(s)in(-1,1)and s==s[::-1]

```

testing code

```
positives = ('ABA', 'ABB', 'BAB', 'BUMP', 'BALD', 'BALDY', 'UPWARD', 'EXAMINATION', 'AZBYCXDWEVFUGTHSIRJQKPLOMN')
negatives = ('AAA', 'BBA', 'ACE', 'THE', 'BUMPY', 'BALDING', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')

for w in positives:
    print(_(w), w)
    assert _(w)

for w in negatives:
    print(_(w), w)
    assert not _(w)

```

# Answer
> 1 votes
**C, ~~65~~ ~~57~~ 60 bytes**

```
 r;f(char*s){for(r=0;*++s&&(r=~r&1<<(*s>*(s-1))););return r;}

```

is fix of

```
r;f(char*s){for(;*++s&&(r=~r&1<<(*s>*(s-1))););return r;}

```

that works correctly with any data only at single function call (when the global variable `r` is initialized to zero).

But in any case this is shorter than previous solution (65 bytes) due to use of `for` instead of `while`. But previous (the following) is a little easier to understand:

```
r;f(char*s){while(*++s)if(!(r=~r&1<<(*s>*(s-1))))break;return r;}

```

My solution is based on bitwise `&` with inverted previous and current direction code, where direction code can be `2` (`1<<1`) for character code increase (`*s > *(s-1)`) or `1` (`1<<0`) otherwise. Result of this operation became 0 if we use the same direction code as previous and current, i.e. when word is not Bumpy.

**UPDATE:**

Code for testing:

```
#include <stdio.h>
#include <string.h>

r;f(char*s){for(;*++s&&(r=~r&1<<(*s>*(s-1))););return r;}

int main(void)
{
    char * Truthy[] = { "ABA",
                        "ABB",
                        "BAB",
                        "BUMP",
                        "BALD",
                        "BALDY",
                        "UPWARD",
                        "EXAMINATION",
                        "AZBYCXDWEVFUGTHSIRJQKPLOMN" };
    char * Falsey[] = { "AAA",
                        "BBA",
                        "ACE",
                        "THE",
                        "BUMPY",
                        "BALDING",
                        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    int posTestNum = sizeof(Truthy) / sizeof(char *);
    int negTestNum = sizeof(Falsey) / sizeof(char *);
    int i;
    int rate = 0;
    int tests = 0;
    int res = 0;
    printf("Truthy (%d tests):\n", posTestNum);
    for (i = 0; i < posTestNum; i++)
    {
        tests++;
        printf("%s - %s\n", Truthy[i], f(Truthy[i]) ? (rate++, "OK") : "Fail");
        r = 0;
    }
    printf("\nFalsey (%d tests):\n", negTestNum);
    for (i = 0; i < negTestNum; i++)
    {
        tests++;
        printf("%s - %s\n", Falsey[i], f(Falsey[i]) ? "Fail" : (rate++, "OK"));
        r = 0;
    }
    printf("\n%d of %d tests passed\n", rate, tests);
    return 0;
}

```

# Answer
> 1 votes
# PHP, 100 bytes

```
for($s=$argv[1];$i<strlen($s)-1;$i++)$s[$i]=$s[$i+1]>$s[$i]?r:f;echo str_replace([rr,ff],'',$s)==$s;

```

Replaces every char of the string (except the last one obviously) with an `r` for rise or an `f` for fall and then checks whether `rr` or `ff` occur in the string. To avoid that the last remaining character interfers with that, input must be all uppercase.

I'm very unsatisfied with the loop, for example I have a feeling that there must be a way to combine the `$i++` into one of the several `$i`s used in the loop, but I failed to find that way. Maybe someone else sees it.

(That's also why I posted my code, despite it being 20 (!) bytes longer than Titus' nice solution.)

# Answer
> 0 votes
# Java 8, ~~114~~ 90 bytes

```
(c,b)->{b=c[0]<c[1];for(int i=2;i<c.length;i++)if(c[i]>c[i-1]!=(b=!b))return 0;return 1;};

```

# Ungolfed test program

```
public static void main(String[] args) {
    BiFunction<char[], Boolean, Integer> func = (c, b) -> {
        b = c[0] < c[1];
        for (int i = 2; i < c.length; i++) {
            if (c[i] > c[i - 1] != (b = !b)) {
                return 0;
            }
        }
        return 1;
    };

    System.out.println(func.apply("ABCDEFG".toCharArray(), false));
    System.out.println(func.apply("AZBYCXDGEF".toCharArray(), false));
    System.out.println(func.apply("ZXZXZX".toCharArray(), false));
    System.out.println(func.apply("ZXCYZ".toCharArray(), false));
    System.out.println(func.apply("AAA".toCharArray(), false));
}

```

---
Tags: code-golf, string, decision-problem
---


title: Lord of the Golfs

text:
# Question
Title: Lord of the Golfs
# Intro

In J. R. R. Tolkien's Lord of the Rings, this phrase is on the cover of each book.

```
Three Rings for the Elven-kings under the sky,
Seven for the Dwarf-lords in their halls of stone,
Nine for Mortal Men doomed to die,
One for the Dark Lord on his dark throne
In the Land of Mordor where the Shadows lie.
One Ring to rule them all, One Ring to find them,
One Ring to bring them all, and in the darkness bind them,
In the Land of Mordor where the Shadows lie

```

However, this isn't that interesting. It's just . Let's change this to .

# What you have to do

Use the Stack Exchange API (or `codegolf.stackexchange.com/users`, or the Stack Exchange Data Explorer) and find the two users with the highest scores in , the newest user, and highest-reputation user with only negatively scored post.

Then, you must insert these usernames into the following text:

```
Three Golfs for the <highest-scored code-golf user>-king under the sky,
Seven for the <second-highest-scored code-golf user>-lord in their halls of stone,
Nine for the Mortal <newest user> doomed to die,
One for the Dark Lord <highest reuptation user with only negative scored code-golf posts>
In the land of Golfdor, where the Golfers lie
One Golf to rule them all, One Golf to find them,
One Golf to bring them all, and in the darkness bind them,
In the Land of Golfdor, where the Golfers lie

```

You must insert the four usernames you found into the text in the angle-brackets.

# Other Rules

* This is so the shortest code wins.
* No URL Shorteners (including `ppcg.(ga|lol)`)

# Answer
# PHP, 577 bytes

not tested; I currently have no system available with `allow_url_fopen=On`
and I didn´t take the time to copy&paste the page sources.

```
function g($s){return join(file("http://codegolf.stackexchange.com/$s"));}$m=preg_match_all;$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g($u="$u&filter=all"),$b);$h=$b[2];$m("#>(.+)</a.+\s1 i#",g("users?tab=NewUsers&sort=creationdate"),$c);while($a){foreach($b[1]as$i=>$n)if($m("#st \"><strong>(-?)\d+#",$e=g("search?tab=votes&q=user:$n+[code-golf]"),$d)&&$d[1][0])break 2;if($a=strstr($a,"l=\"n"))$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g("$u&page=".$p+=!$p++),$b);}$m("#<code>(.+)</code>#U",g("q/93545"),$t);echo join([1=>$h[0],3=>$h[1],5=>$c[1][0],7=>$b[2][$i];]+split("#&[lg]t;#",$t[1][2]));

```

**breakdown**

```
// function to get page content from ppcg
function g($s){return join(file("http://codegolf.stackexchange.com/$s"));}

$m=preg_match_all;

// A,B: highest scores: find user names
$m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g($u="users?filter=all"),$b);
$h=$b[2];   // remember the names

// C: new users: find username after "1 in one day"
$m("#>(.+)</a.+\s1 i#",g("$u&tab=NewUsers&sort=creationdate"),$c);

// D: loop through users from first query
while($a)
{
    foreach($b[1]as$i=>$n)
        // find "vote-count-post" in code-golf votes for that user
        if($m("#st \"><strong>(-?)\d+#",$e=g("search?tab=votes&q=user:$n+[code-golf]"),$d)
        &&$d[1][0])             // test if highest vote is negative
            break 2;
    // none found yet?
    if($a=strstr($a,"l=\"n"))   // if there is a "next" link, get next page
        $m("#r-de.+/(\d+)/.+>(.+)<#U",$a=g("$u&page=".$p+=!$p++),$b);
}

$m("#<code>(.+)</code>#U",g("q/93545"),$t); // get code blocks from question page

echo join([         // 4. join and print
    1=>$h[0],           // first two results from first preg_match
    3=>$h[1],
    5=>$c[1][0],        // first result from second preg_match
    7=>$b[2][$i];       // $i-th username from (latest) reputation list
]+                  // 3. and replace indexes 1,3,5,7 with above array
split("#&[lg]t;#",  // 2. split by "<" and ">"
    $t[1][2]        // 1. output template is the 3rd code block
));

```
> 2 votes

---
Tags: code-golf, stack-exchange-api
---


# Question
Title: Recreate the Windows ME screensaver as ASCII
> This challenge is inspired from this answer at the Ask Ubuntu Stack Exchange.

# Intro

Remember the Windows ME screensaver with the pipes? Time to bring the nostalgia back!

# Challenge

You should write a program or function which will output an ASCII representation of the screensaver. In the screensaver there should be a single pipe which will grow in semi-random directions.
The start of the pipe will be randomly placed at any of the borders of the screen and the pipe piece should be perpendicular to the border (corner first-pipes can either be horizontal or vertical). Each tick the pipe will grow in the direction it is facing (horizontal/vertical) at an `80%` chance or take a corner at a `20%` chance.

# Pipe representation

To create the pipe, 6 unicode characters will be used

```
─    \u2500    horizontal pipe
│    \u2502    vertical pipe
┌    \u250C    upper left corner pipe
┐    \u2510    upper right corner pipe
└    \u2514    lower left corner pipe
┘    \u2518    lower right corner pipe

```

# Input

The program / function will take 3 values of input, which can be gathered through function parameters or prompted to the user.

* Amount of ticks
* Screen width
* Screen height

### Amount of ticks

For every tick, a piece of pipe will be added to the screen. Pipes will overwrite old pipe pieces if they spawn at the same position.

For example, take a screen of size 3x3

```
ticks == 3
─┐
 ┘

ticks == 4
─┐
└┘

ticks == 5
│┐
└┘

```

Whenever a pipe exits the screen, as in the last example at 5 ticks, then a new pipe will spawn at a random border. For example:

```
ticks == 6
│┐
└┘
  ─

```

The new pipe should have a 50% chance of being horizontal or vertical.

### Screen width/height

The screen width and height can be combined into a single value if that's preferrable in your language of choice. The screen width and height will always have a minimum value of 1 and a maximum value of 255. If your language of choice supports a console or output screen which is smaller than a 255x255 grid of characters then you may assume that the width and height will never exceed the boundaries of your console. (Example: Windows 80x25 cmd window)

# Output

The output of your program/function should be printed to the screen, or returned from a function. For every run of your program, a different set of pipes should be generated.

# Test cases

The following test cases are all random examples of valid outputs

```
f(4, 3, 3)
 │
─┘
  │

f(5, 3, 3)
 │
─┘┌
  │

f(6, 3, 3)
─│
─┘┌
  │

f(7, 3, 3)
──
─┘┌
  │

```

Obviously, the more ticks that have occured, the harder it becomes to prove the validity of your program. Hence, posting a gif of your output running will be preferred. If this is not possible, please post a version of your code which includes printing the output. Obviously, this will not count towards your score.

# Rules

* This is , shortest amount of bytes wins
* Standard loopholes apply
* If you use the unicode pipe characters in your source code, you may count them as a single byte

This is quite a hard challenge that can possibly be solved in many creative ways, you are encouraged to write an answer in a more verbose language even though there are already answers in short esolangs. This will create a catalog of shortest answers per language. Bonus upvotes for fancy coloured gifs ;)

Happy golfing!

Disclaimer: I am aware that Unicode characters aren't ASCII, but in lack of a better name I just call it ASCII art. Suggestions are welcome :)

# Answer
> 9 votes
# JavaScript (ES6), 264 ~~266 274 281~~

```
(t,w,h,r=n=>Math.random()*n|0,g=[...Array(h)].map(x=>Array(w).fill` `))=>((y=>{for(x=y;t--;d&1?y+=d-2:x+=d-1)x<w&y<h&&~x*~y?0:(d=r(4))&1?x=r(w,y=d&2?0:h-1):y=r(h,x=d?0:w-1),e=d,d=r(5)?d:2*r(2)-~d&3,g[y][x]="─└ ┌┐│┌  ┘─┐┘ └│"[e*4|d]})(w),g.map(x=>x.join``).join`
`)

```

Counting unicode drawing characters as 1 byte each. (As specified by OP)

*Less golfed*

```
(t,w,h)=>{
  r=n=>Math.random()*n|0; // integer range random function
  g=[...Array(h)].map(x=>Array(w).fill(' ')); // display grid
  for (x=y=w;t--;)
    x<w & y<h && ~x*~y||( // if passed boundary
      d = r(4), // select random direction
      d & 1? (x=r(w), y=d&2?0:h-1) : (y=r(h), x=d?0:w-1) // choose start position
    ),
    e=d, d=r(5)?d:2*r(2)-~d&3, // change direction 20% of times
    g[y][x]="─└ ┌┐│┌  ┘─┐┘ └│"[e*4|d], // use char based on current+prev direction
    d&1 ? y+=d-2 : x+=d-1 // change x,y position based on direction
  return g.map(x=>x.join``).join`\n`
}

```

**Animated test**

Note: trying to keep the animation time under 30 sec,more thicks make animation pace faster

```
f=(t,w,h,r=n=>Math.random()*n|0,g=[...Array(h)].map(x=>Array(w).fill` `))=>
{
  z=[]
  for(x=y=w;t--;d&1?y+=d-2:x+=d-1)
    x<w&y<h&&~x*~y?0:(d=r(4))&1?x=r(w,y=d&2?0:h-1):y=r(h,x=d?0:w-1),
    e=d,d=r(5)?d:2*r(2)-~d&3,g[y][x]="─└ ┌┐│┌  ┘─┐┘ └│"[e*4|d],
    z.push(g.map(x=>x.join``).join`\n`)
  return z
}

function go() {
  B.disabled=true
  var [t,w,h]=I.value.match(/\d+/g)
  var r=f(+t,+w,+h)
  O.style.width = w+'ch';
  var step=0
  var animate =_=>{
    S.textContent = step
    var frame= r[step++]
    if (frame) O.textContent = frame,setTimeout(animate, 30000/t);
    else   B.disabled=false
  }

  animate()
}

go()
```

```
#O { border: 1px solid #000 }
```

```
Input - ticks,width,height
<input value='600,70,10' id=I><button id=B onclick='go()'>GO</button>
<span id=S></span>
<pre id=O></pre>
```

# Answer
> 13 votes
Nothing says nostalgia quite like...

## QBasic, 332 bytes

```
INPUT t,w,h
RANDOMIZE
CLS
1b=INT(RND*4)
d=b
IF b MOD 2THEN c=(b-1)/2*(w-1)+1:r=1+INT(RND*h)ELSE c=1+INT(RND*w):r=b/2*(h-1)+1
WHILE t
LOCATE r,c
m=(b+d)MOD 4
IF b=d THEN x=8.5*m ELSE x=13*m+(1<((b MOD m*3)+m)MOD 5)
?CHR$(179+x);
r=r-(d-1)MOD 2
c=c-(d-2)MOD 2
b=d
d=(4+d+INT(RND*1.25-.125))MOD 4
t=t-1
IF(r<=h)*(c<=w)*r*c=0GOTO 1
WEND

```

QBasic is the right language for the task because:

* Its encoding includes box drawing characters--no need for Unicode
* `LOCATE` allows you to print to any location on the screen, overwriting what was there previously
* Microsoft<sup>®</sup>

### Specifics

This is golfed QBasic, written and tested on QB64 with autoformatting turned off. If you type/paste it into the actual QBasic IDE, it will add a bunch of spaces and expand `?` into `PRINT`, but it should run exactly the same.

The program inputs three comma-separated values: ticks, width, and height. It then asks for a random-number seed. (If this behavior isn't acceptable, change the second line to `RANDOMIZE TIMER` for +6 bytes.) Finally, it draws the pipes to the screen.

The maximum dimensions that can be entered are 80 (width) by 25 (height). Giving a height of 25 will result in the bottom row getting cut off when QBasic says "Press any key to continue."

### How?

TL;DR: A lot of math.

The current row and column are `r` and `c`; the current direction is `d` and the previous direction is `b`. Direction values 0-3 are down, right, up, left. Arithmetic translates those into the correct step values for `r` and `c`, as well as the correct edge coordinates to start on.

The box drawing characters `│┐└─┘┌` are code points 179, 191, 192, 196, 217, and 218 in QBasic. Those appear pretty random, but it still used fewer characters to generate the numbers with some (pretty convoluted, I'm-not-sure-even-I-understand-it) math than to do a bunch of conditional statements.

The code for changing direction generates a random number between -0.125 and 1.125 and takes its floor. This gives `-1` 10% of the time, `0` 80% of the time, and `1` 10% of the time. We then add this to the current value of `d`, mod 4. Adding 0 keeps the current direction; adding +/-1 makes a turn.

As for control flow, the `WHILE t ... WEND` is the main loop; the section before it, starting with line number `1` (`1b=INT(RND*4)`), restarts the pipe at a random edge. Whenever `r` and `c` are outside the window, we `GOTO 1`.

### Show me the GIF!

Here you go:

This was generated by a somewhat ungolfed version with animation, color, and an automatic random seed:

```
INPUT t, w, h
RANDOMIZE TIMER
CLS

restart:
' Calculate an edge to start from

b = INT(RND * 4)
'0: top edge (moving down)
'1: left edge (moving right)
'2: bottom edge (moving up)
'3: right edge (moving left)
d = b

' Calculate column and row for a random point on that edge
IF b MOD 2 THEN
    c = (b - 1) / 2 * (w - 1) + 1
    r = 1 + INT(RND * h)
ELSE
    c = 1 + INT(RND * w)
    r = b / 2 * (h - 1) + 1
END IF
COLOR INT(RND * 15) + 1

WHILE t
    ' Mathemagic to generate the correct box-drawing character
    m = (b + d) MOD 4
    IF b = d THEN
        x = 17 * m / 2
    ELSE
        x = 13 * m + (1 < ((b MOD m * 3) + m) MOD 5)
    END IF
    LOCATE r, c
    PRINT CHR$(179 + x);

    ' Update row and column
    r = r - (d - 1) MOD 2
    c = c - (d - 2) MOD 2
    ' Generate new direction (10% turn one way, 10% turn the other way,
    ' 80% go straight)
    b = d
    d = (4 + d + INT(RND * 1.25 - .125)) MOD 4

    ' Pause
    z = TIMER
    WHILE TIMER < z + 0.01
        IF z > TIMER THEN z = z - 86400
    WEND

    t = t - 1
    IF r > h OR c > w OR r = 0 OR c = 0 THEN GOTO restart
WEND

```

# Answer
> 9 votes
### Python 2.7, ~~624~~ ~~616~~ ~~569~~ ~~548~~ 552 bytes

```
from random import*
from time import*
i=randint
z=lambda a,b:dict(zip(a,b))
c={'u':z('lur',u'┐│┌'),'d':z('ldr',u'┘│└'),'l':z('uld',u'└─┌'),'r':z('urd',u'┘─┐')}
m=z('udlr',[[0,-1],[0,1],[-1,0],[1,0]])
def f(e,t,w,h):
 seed(e);s=[w*[' ',]for _ in' '*h]
 while t>0:
  _=i(0,1);x,y=((i(0,w-1),i(0,1)*(h-1)),(i(0,1)*(w-1),i(0,h-1)))[_];o=('du'[y>0],'rl'[x>0])[_]
  while t>0:
   d=c[o].keys()[i(7,16)//8];s[y][x]=c[o][d];x+=m[d][0];y+=m[d][1];t-=1;sleep(.5);print'\n'.join([''.join(k)for k in s]);o=d
   if(x*y<0)+(x>=w)+(y>=h):break

```

The first parameter is a seed, same seeds will generate the same output, printing each step with a 500 ms delay.

* **-10 bytes** thanks to @TuukkaX

repl it

Example run

```
f(5,6,3,3)

```

will output

```

 ─┐

```

```

──┐

```

```

┘─┐

```

```

┐
┘─┐

```

verbose version

```
import random as r
from time import *
char={
'u':{'u':'│','l':'┐','r':'┌'},
'd':{'d':'│','l':'┘','r':'└'},
'l':{'u':'└','d':'┌','l':'─'},
'r':{'u':'┘','d':'┐','r':'─'}
}
move={'u':[0,-1],'d':[0,1],'l':[-1,0],'r':[1,0]}
def f(seed,steps,w,h):
 r.seed(seed)
 screen=[[' ',]*w for _ in ' '*h]
 while steps > 0:
  if r.randint(0,1):
   x,y=r.randint(0,w-1),r.randint(0,1)*(h-1)
   origin='du'[y>0]
  else:
   x,y=r.randint(0,1)*(w-1),r.randint(0,h-1)
   origin = 'rl'[x>0]
  while steps > 0:
   direction = char[origin].keys()[r.randint(0,2)]
   screen[y][x]=char[origin][direction]
   x+=move[direction][0]
   y+=move[direction][1]
   steps-=1
   sleep(0.5)
   print '\n'.join([''.join(k) for k in screen]),''
   if x<0 or y<0 or x>=w or y>=h:
    break
   origin=direction

```

# Answer
> 7 votes
# C (GCC/linux), 402 353 352 302 300 298 296 288 bytes

```
#define R rand()%
x,y,w,h,r;main(c){srand(time(0));scanf(
"%d%d",&w,&h);for(printf("\e[2J");x%~w*
(y%~h)||(c=R 8,(r=R 4)&1?x=1+R w,y=r&2
?1:h:(y=1+R h,x=r&2?1:w));usleep('??'))
printf("\e[%dm\e[%d;%dH\342\224%c\e[H\n",
30+c,y,x,2*"@J_FHAF__L@HL_JA"[r*4|(r^=R 5
?0:1|R 4)]),x+=--r%2,y+=~-r++%2;}

```

Credit to edc65 for storing the direction in a single 4-bit number.

Reads a width/height on stdin before looping the screensaver forever. E.g.:

```
gcc -w golf.c && echo "25 25" | ./a.out

```

Or for a full-screen screensaver:

```
gcc -w golf.c && resize | sed 's/[^0-9]*//g' | ./a.out

```

For readability I added newlines. Requires a linux machine with a terminal respecting ANSI codes. Has colors! If you remove color support it costs 17 bytes less.

# Answer
> 5 votes
# Ruby, ~~413~~ ~~403~~ 396 bytes

A function that takes a number of ticks and a width as input and returns the final screen as a string. Could no doubt be golfed more.

```
->t,w{k=[-1,0,1,0,-1]
b=(" "*w+$/)*w
f=->t,a=[[0,m=rand(w),2],[w-1,m,0],[m,0,1],[m,w-1,3]].sample{n,m,i=a
d=k[i,2]
q=->n,m,i{_,g,j=rand>0.2?[[1,0],[3,0],[0,1],[2,1]].assoc(i):"021322033132243140251350".chars.map(&:to_i).each_slice(3).select{|c,|c==i}.sample
v,u=k[j||=i,2]
y=n+v
x=m+u
[g,y,x,j]}
g,y,x,j=q[n,m,i]
b[n*w+n+m]="─│┌┐┘└"[g]
y>=0&&y<w&&x>=0&&x<w ?t>1?f[t-1,[y,x,j]]:b:f[t]}
f[t]}

```

See it on repl.it: https://repl.it/Db5h/4

In order to see it in action, insert the following after the line that begins `b[n*w+n+m]=`:

```
puts b; sleep 0.2

```

...then assign the lambda to a variable e.g. `pipes=->...` and call it like `pipes[100,20]` (for 100 ticks and a 20x20 screen).

## Ungolfed & explanation

```
# Anonymous function
# t - Number of ticks
# w - Screen width
->t,w{
  # The cardinal directions ([y,x] vectors)
  # Up = k[0..1], Right = k[1..2] etc.
  k = [-1, 0, 1, 0, -1]

  # An empty screen as a string
  b = (" " * w + $/) * w

  # Main tick function (recursive)
  # t - The number of ticks remaining
  # a - The current position and vector index; if not given is generated randomly
  f = ->t,a=[[0,m=rand(w),2], [w-1,m,0], [m,0,1], [m,w-1,3]].sample{
    # Current row, column, and vector index
    n, m, i = a
    d = k[i,2] # Get vector by index

    # Function to get the next move based on the previous position (n,m) and direction (d)
    q = ->n,m,i{
      # Choose the next pipe (`g` for glyph) and get the subsequent vector index (j)
      _, g, j = (
        rand > 0.2 ?
          [[1,0], [3,0], [0,1], [2,1]].assoc(i) : # 80% of the time go straight
          "021322033132243140251350".chars.map(&:to_i).each_slice(3)
            .select{|c,|c==i}.sample
      )

      # Next vector (`v` for vertical, `u` for horizontal)
      # If straight, `j` will be nil so previous index `i` is used
      v, u = k[j||=i, 2]

      # Calculate next position
      y = n + v
      x = m + u

      # Return next glyph, position and vector index
      [g, y, x, j]
    }

    # Get next glyph, and subsequent position and vector index
    g, y, x, j = q[n, m, i]

    # Draw the glyph
    b[n * w + n + m] = "─│┌┐┘└"[g]

    # Check for out-of-bounds
    y >= 0 && y < w && x >=0 && x < w ?
      # In bounds; check number of ticks remaining
      t > 1 ?
        f[t-1, [y,x,j]] : # Ticks remain; start next iteration
        b : # No more ticks; return final screen

      # Out of bounds; repeat tick with new random start position
      f[t]
  }
  f[t]
}

```

---
Tags: code-golf, ascii-art
---


title: The House of Santa Claus

text:
# Question
Title: The House of Santa Claus
# The House of Santa Claus

**Note:** This is the first challenge that I have attempted to set. It has been through the Sandbox however if you find something wrong with it please do not just downvote but leave a comment so that I can improve it.

**Background**

There is a old childrens puzzle where the challenge is to draw a box with a roof and a cross through the middle without lifting your pen from the paper or going over any line twice.

In Germany it is known as "das Haus des Nikolaus" or "The House of Santa Claus". I honestly can't remember what we used to call it. For anyone who is not familiar with the puzzle, full details are available here.

Here is an ASCII art representation of the house.

```
 /\
/__\
|\/|
|/\|
----

```

**Challenge**

Write a program or function to draw the House of Santa Claus in any language of your choice.

Sounds too easy? Well here's the catch. It must also output each stage of the drawing and comply with the rules of the puzzle. Your program is not required to take any input. The finished house must look exactly as shown above.

According to the site above there are 44 possible solutions. You may use any one of them. This is an ASCII art challenge so you are not required to calculate the solution but only to draw it.

**Output**

An example of the required output from one of the 44 solutions is shown below:

```
----

 \
  \
----

 __
 \
  \
----

  \
 __\
 \
  \
----

 /\
/__\
 \
  \
----

 /\
/__\
|\
| \
----

 /\
/__\
|\/
|/\
----

 /\
/__\
|\/|
|/\|
----

```

**Rules**

* I have added 1 extra newline between each expected output to try to make the requirements clearer. This is optional. Any number of blank lines between each output is allowed.
* Your output must consist only of the characters /,\\,-,\_, and space as shown above. Trailing spaces are allowed.
* Each line in your drawing must continue from the end of the previous line and you may not repeat any line.
* Standard loopholes prohibited.
* You are not required to output the rhyme mentioned in the above link.
* This is code golf so the shortest answer in bytes will be the winner.

**Result**

Some great answers and thanks and respect to all who posted. I did say lowest byte count but I have marked as top answer not just for that but also for the great explanation of the code. Nice one @Dennis.

# Answer
> 10 votes
# Jelly, ~~40~~ ~~39~~ 36 bytes

```
“ḥ%DtƊVḍI’ḃ9W;“|_/-\/\|‘Ė¤y@\FỌ»⁶s4Y

```

Try it online!

### How it works

```
“ḥ%DtƊVḍI’

```

is a bijective base-250 literal; each character corresponds to its code point in Jelly's code page. The result is the integer **13192938935880491074**.

```
          ḃ9

```

converts the generated integer to bijective base 9, yielding the integer array
**\[9, 6, 7, 9, 6, 2, 2, 7, 1, 5, 3, 8, 1, 3, 5, 8, 4, 4, 4, 4\]**. The integers correspond to the order of the stroke, with the exception of **9**, which indicates a space.

```
            W

```

wraps the generated array into a singleton array, which will be required to prepend it to the array we'll generate now.

```
              “|_/-\/\|‘Ė¤

```

works as follows. `¤` combines the two links to the left into a niladic chain. The first one, `“|_/-\/\|‘` yields the code points of the specified characters, yielding **\[124, 95, 47, 45, 92, 47, 92, 124\]**. Then, `Ė` enumerates the code points, yielding
**\[\[1, 124\], \[2, 95\], \[3, 47\], \[4, 45\], \[5, 92\], \[6, 47\], \[7, 92\], \[8, 124\]\]**. The pair **\[n, c\]** means that the **n**th stroke will be the ASCII character with code point **c**.

```
             ;

```

concatenates the generated arrays. The result is the array
**\[\[9,6,7,9,6,2,2,7,1,5,3,8,1,3,5,8,4,4,4,4\],\[1,124\],\[2,95\],\[3,47\],\[4,45\],\[5,92\],\[6,47\],\[7,92\],\[8,124\]\]**.

```
                          y@\

```

performs a cumulative (i. e., showing all intermediate steps) reduce, using transliteration (`y`) with swapped arguments (`@`). In the first step, e.g., we replace each **1** in the original array with **124**, which is the code point of the character **|**.

```
                             FỌ

```

flattens the result and replaces all code points with the corresponding ASCII characters. In all steps, this will generate some unprintable characters with code points **1** to **9**.

```
                               »⁶

```

takes the character-wise maximum with the space character, replacing all unprintable characters with spaces.

```
                                 s4Y

```

splits the generated string into chunks of length four and joins them with a linefeed as separator.

# Answer
> 13 votes
## Javascript (ES6), ~~119~~ ~~116~~ ~~96~~ ~~92~~ 91 bytes

```
for(i=8;i--;)console.log(`834
3554
2610
2160
7777`.replace(/./g,c=>'|/|/\\_\\- '[c<i?8:c]))
```

# Answer
> 9 votes
## Batch, ~~356~~ ~~344~~ ~~341~~ 337 bytes

```
@set s=@set "
%s%g=@goto 1
%s%r=
%s%c=
%s%u=|
%s%l=|
%s%f=
@for /l %%i in (1,1,7)do @call:%%i
%s%u=|\/|
%s%l=|/\|
%g%
:7
%s%u=|\/
%s%l=|/\
%g%
:6
%s%f=----
%g%
:5
%s%u=|\
%s%l=| \
%g%
:4
%s%c=/__\
%g%
:3
%s%r= /\
%s%c=/  \
%g%
:2
%s%r= /
%s%c=/
:1
@for %%l in ("%r%" "%c%" "%u%" "%l%" "%f%")do @echo(%%~l

```

~~Stupid Batch `|` quoting rules... if you want a `|` in a variable, you need to quote it with three `^`s, so it's cheaper to use `@` instead and substitute it on output, although to achieve this I have to start with the left wall. Line one has a trailing space.~~ `echo(` is used because the `r`, `c`, and `f` variables could be empty and we don't want `ECHO is off.` printed.

Edit: Saved 12 bytes by using fallthrough for the last part. Saved 3 bytes by using a `for` loop to print each part, this means that I now use `|`s in my variables which makes the code slightly easier to read. Saved 4 bytes by using explicit `@` characters instead of `@echo off`. I think starting with the left wall still requires the fewest bytes.

# Answer
> 7 votes
# C, 118 bytes

```
main(){char *p,n;for(n='B';n++<'J';)for(p="ZFEAFDDEAGCHIAGHCIABBBBAA";*p;p++)putchar(" \n-\\_\\/|/|"[(*p<n)**p&15]);}

```

# Answer
> 6 votes
# ///, 112 bytes

```
/!/\/\///*/----
 !@/\\\\!$/ @@!^/
*@\/@@
@\/__@@
/*@
 $
*__
$
 $
*$
 __@
$
 $^$
 $^|@
|$^|@\/
|\/@^|@\/|
|\/@|
*

```

Try it online!

# Answer
> 2 votes
# PHP, ~~98~~ 95 bytes

inspired by Arnauld´s solution

```
for($i=8;$i--;)for($p=24;$p--;)echo"|/|/\\_\\-
"[($c="977779061290162945539438"[$p])<$i?8:$c];

```

Note: The first code line has a trailing space.

# Answer
> 1 votes
# PHP with GD, ~~348~~ 338 bytes (not competing)

not exactly what was being asked for, but ...

```
function f($v,$w){global$x,$y,$i;imageline($i,$x,$y,$x=$v,$y=$w,1);ob_start();imagepng($i);$s=ob_get_clean();ob_end_clean();echo'<img src="data:image/png;base64,',base64_encode($s),'" > ';}$i=imagecreate($w=9,$h=$w+$z=$w/2);imagecolorallocate($i,255,255,255);f(--$w,$y=--$h);f(0,$z);f($w,$z);f($w/2,0);f(0,$z);f(0,$h);f($w,$z);f($w,$h);

```

save to file, call in a browser

**breakdown**

```
function f($v,$w)
{
    global$x,$y,$i;
    imageline($i,$x,$y,$x=$v,$y=$w,1);      // draw line, set end coords as new start coords
    ob_start();imagepng($i);$s=ob_get_clean();ob_end_clean();           // get image output
    echo'<img src="data:image/png;base64,',base64_encode($s),'" > ';    // print <img> tag
}
// calculate dimensions, create image, allocate background color (foreground implicitly black)
$i=imagecreate($w=9,$h=$w+$z=$w/2);imagecolorallocate($i,255,255,255);
// paint lines: implicit `$x=0`
f(--$w,$y=--$h);f(0,$z);f($w,$z);f($w/2,0);f(0,$z);f(0,$h);f($w,$z);f($w,$h);

```

To draw a larger house, change `$w=9` to your desired width.

---
Tags: code-golf, ascii-art
---


title: Interpret Repetition!

text:
# Question
Title: Interpret Repetition!
*This challenge is the first in a two-challenge series about Repetition. The second will be up soon.*

In a language called Repetition (something I just made up), there consists an infinite string of `12345678901234567890...`, with `1234567890` repeating forever.

The following syntax is available to output numbers:

* `+-*/`: This inserts the operator into the string of repeating digits.
    + Examples:
        - `+` -\> `1+2` = `3` (The `+` inserts a `+` between `1` and `2`)
        - `+*` -\> `1+2*3` = `1+6` = `7` (Same as above, except two operators are used now)
        - `/` -\> `1/2` = `0` (Repetition uses integer division)
        - `//` -\> `1/2/3` = `0/3` = `0` (Repetition uses "left association" with multiple subtractions and divisions)
    + Each operator is inserted so that it has one digit to its left, unless there are `c`'s (see below).
* `c`: Concatenates with the next digit in the string.
    + Examples:
        - `c+` -\> `12+3` = `15` (The `c` "continues" the `1` and concatenates it with the next digit, `2`, to form `12`)
        - `+c` -\> `1+23` = `24`
        - `ccc` -\> `1234`
* `()`: Brackets for processing numbers.
    + Examples:
        - `(c+)*` -\> `(12+3)*4` = `15*4` = `60` (Repetition uses the order of operations)
        - `(c+)/c` -\> `(12+3)/45` = `15/45` = `0`
        - `(cc+c)/` -\> `(123+45)/6` = `168/6` = `28`
* `s`: Skip a number (removes the number from the infinite string).
    + `s+` -\> `2+3` = `5` (`s` skips `1`)
    + `csc` -\> `124` (The first `c` concats `1` and `2`, the `s` skips `3`, and the final `c` concats `12` to `4`)
    + `+s+` -\> `7` (The first `+` adds `1` and `2` to make `3`, `s` skips `3`, and the final `+` adds `3` to `4` to make `7`)
    + `cs*(++)` -\> `12*(4+5+6)` = `12*15` = `180`

In the examples above, only a finite amount of digits in the infinite string are used. The number of digits used is equivalent to `number of operators, concats and skips + 1`.

Your task is, when given a string of Repetition code, output the result.

Examples of input and output are:

```
++ -> 6
- -> -1
(-)* -> -3
cscc -> 1245
(cc+c)/ -> 28
cc+c/ -> 130
cs*(++) -> 180

```

This is code golf, so shortest code in bytes wins!

## Specs:

* You are guaranteed that the result will never go above `2^31-1`.
* You are also guaranteed that the input will only consist of the symbols `+-*/cs()`.
* An empty program will output `1`.

# Answer
# JavaScript (ES6), 110 bytes

```
s=>eval((" "+s)[R='replace'](/[^\)](?!\()/g,x=>x+i++%10,i=1)[R](/c| (\ds)+|s\d/g,"")[R](/\d+\/\d+/g,"($&|0)"))

```

Very simple, but integer division adds 25 bytes. For some reason a regex in JS can't match both the beginning of a string and the first character, so that adds a few bytes as well.

### How it works

1. Prepend a space to the input.
2. Append the next digit to each character (except `)`) that isn't immediately before a `(`.
3. Remove each `c`, a digit + `s` at the beginning (`1s2` -\> `2`), and each `s` \+ a digit (`3s4` -\> `3`).
4. Turn each division operation into int-division (`1/2` -\> `(1/2|0)`).
5. Evaluate and return.
> 4 votes

# Answer
## Batch, 332 bytes

```
@echo off
set s=
set e=
set d=
set r=
set/ps=
:d
set/ad=-~d%%10
:l
if "%s%"=="" goto g
set c=%s:~0,1%
set s=%s:~1%
if %c%==( set e=%e%(&goto l
if %c%==) set r=%r%)&goto l
if %c%==s goto d
if %c%==c set c=
if "%r%"=="" set/ar=d,d=-~d%%10
set e=%e%%r%%c%
set/ar=d
goto d
:g
if "%r%"=="" set/ar=d
cmd/cset/a%e%%r%

```

The behaviour of `s` makes this very awkward. (Maybe `cs` should evaluate to `13` and `-s` to `-2`?) Variables:

* `s` input string (explicitly blanked out because set/p doesn't change the variable if you don't input anything)
* `e` partial expression in normal integer arithmetic (which we can pass to `set/a` as a form of `eval`)
* `d` next digit from the infinite string of digits
* `r` right hand side of latest operator. We can't concatenate this immediately because `(` needs to come first, but we need to store it so that `s` won't increment it. Fortunately it does end up making the handling of `)` slightly easier.
* `c` current character.
> 0 votes

---
Tags: code-golf, math
---


title: Misconstrued Monomials

text:
# Question
Title: Misconstrued Monomials
There exists an equation, assuming `n` and `x` are positive,

that expresses the relationship between two monomials, one being a common misrepresentation of the other. Many people make the simple mistake of equating these (i.e. `3x^2` and `(3x)^2`).

### Challenge

Given a positive integer, `i`, determine and return the solution `n` and `x` with the smallest sum as an array `[n, x]`. In the case of a tie, any solution set is acceptable.

### Test Cases

```
62658722541234765
[15, 11]

202500
[4, 15]

524288
[8, 4]

33044255768277
[13, 9]

```

# Answer
> 5 votes
# Mathematica, 61 bytes

*Thanks to miles for saving 2 bytes, plus a whole bunch of bytes I counted for no reason!*

```
Last@Select[{n,(#/n)^(1/n)}~Table~{n,2Log@#},IntegerQ@*Last]&

```

Computes a table of pairs {n,x}, where x = (i/n)^(1/n), using all possible values of n; keeps only those for which the corresponding x is an integer; then returns the pair with the largest value of n.

Here, "all possible values of n" ranges from 1 to 2\*ln(i). This ignores the solution {n,x} = {i,1}, but that's okay since the solution {n,x} = {1,i} will suffice if it's the best choice. So x never needs to get smaller than 2, which means that n\*2^n ≤ i, and all such n are less than 2\*ln(i).

One can show using calculus that the pair {n,x} that minimizes their sum in this context is the same as the pair {n,x} with largest n (not counting {i,1}). That's why the initial `Last` is good enough to find the optimal pair.

# Answer
> 5 votes
# Brachylog, 35 bytes

```
,[N:X]#>>==L(.rMtT;Lr.rMtT),M^:T*?,

```

Try it online!

### Explanation

We construct a list `[N, X]`, where `N >= X`, then after assigning values to it, we try both `[N, X]` and `[X, N]` as possible output. For example, if `N` gets assigned to `3`, we will test through backtracking `[3, 1]`, `[1, 3]`, `[3, 2]`, `[2, 3]`, `[3, 3]` and `[3, 3]`. After that the next backtracking step will occur on the value of `N`, which will go to `4`, etc.

```
,[N:X]     The list [N, X]
#>         Both N and X are strictly positive
>=         N >= X
=L         Assign values to N and X, and L = [N, X]
(          Either...
    .          Output = L
    rM         M is the reverse of the Output
    tT         T is the second element of M
;          ...or...
    Lr.        Output is the reverse of L
    rM         M = L
    tT         T is the last element of M
),
M^         First element of M to the power of the second element of L (T)...
:T*?,      ... times T is equal to the Input

```

# Answer
> 3 votes
# MATL, 22 bytes

```
`T@XK:"@K@-@^*G=?3Mb~.

```

Outputs are `x`, `n` in that order.

Input is limited by MATL's default `double` data type, which can accurately represent integers up to `2^53` only. This excludes the first test (still, it gives the correct result, but that can't be guaranteed in general for inputs so large).

Try it online!

### Explanation

The code uses two nested loops:

* The outer `do...while` loop goes through all possible sums `n+x` in increasing order. The loop will be stopped as soon as a solution is found. This guarantees that we output the solution with minimum sum.
* The inner `for each` loop tests all `n` and `x` with that sum. When the sum coincides with the input, the inner loop is exited and the loop condition of the outer loop is set to `false` so that one is exited too.

Commented code:

```
`         % Do...while
  T       %   Push "true". Will be used as loop condition (possibly negated to exit loop)
  @       %   Push iteration index, say K, which represents n+x
  XK      %   Copy that into clipboard K
  :       %   Range [1 2 ... K]
  "       %   For each
    @     %     Push loop variable (1, 2, ... K), which represents n
    K@-   %     Compute x as K minus n
    @     %     Push n again
    ^*    %     Power, multiply. This gives n*x^n
    G=    %     Does this equal the input?
    ?     %     If so
      3M  %       Push the inputs of the third-last function, that is, x and n
      b   %       Bubble up the "true" that is at the bottom of the stack
      ~   %       Transform it into "false". This will exit the do...while loop
      .   %       Break the for loop
          %     Implicitly end if
          %   Implicitly end for
          % Implicitly end do...while
          % Implicitly display

```

# Answer
> 2 votes
# Jelly, ~~23~~ 16 bytes

```
×*@¥/=³
ṗ2ÇÐfSÞḢ

```

Given `i`, this generates all integer pairs with replacement in `[1, i]`. It then performs the same filtering and sorting as in the previous solution shown below. Since there is no time constraint, brute force will work given enough time.

Try it online!, but don't try large values online.

On my pc, it takes about 6 minutes to compute the result for `i = 2048` using the inefficient version.

### Efficient version

This is the previous solution for 23 bytes that is able to solve the large values quickly.

```
×*@¥/=³
ÆDµṚ*İ⁸żḞÇÐfSÞḢ

```

Given `i`, computes the divisors of `i` to generate pairs of `[n, x]` where `n` is a divisor and `x = floor( (i/n)^(1/n) )`. Then filters it for values where `n * x^n == i`, sort the remaining pairs by their sum, and returns the first pair.

Try it online! or Verify all test cases.

## Explanation

```
×*@¥/=³  Helper link. Input: list [n, x]
    /    Reduce using
   ¥       A dyadic chain
 *@        Compute x^n
×          Multiply by n
      ³  The initial value i
     =   Test if n * x^n == i

ṗ2ÇÐfSÞḢ  Main link (16 byte version). Input: integer i
ṗ2        Generate all pairs of integers in [1, i]
  ÇÐf     Filter for where the helper link is true
     SÞ   Sort them by their sum
       Ḣ  Return the first result

ÆDµṚ*İ⁸żḞÇÐfSÞḢ  Main link (23 byte version). Input: integer i
ÆD               Compute the divisors of i
  µ              Begin a new monadic chain operating on the divisors
   Ṛ             Reverse the divisors
     İ           Reciprocal of each divisors
    *            Raise each in the reversed divisors to the reciprocal of a divisor
      ⁸          Get the divisors
       ż         Interleave the divisors with the previous powers
        Ḟ        Floor each
         ÇÐf     Filter for where the helper link is true
            SÞ   Sort them by their sum
              Ḣ  Return the first result

```

# Answer
> 1 votes
# PHP, 104 Bytes

```
for(;1<$x=(($i=$argv[1])/++$n)**(1/$n);)!($x==ceil($x))?:$a[$x+$n]="[$x, $n]";ksort($a);echo$a[key($a)];

```

This outputs all possible solutions not in the proposed format 73 Bytes

```
for(;1<=$x=(($i=$argv[1])/++$n)**(1/$n);)!($x==ceil($x))?:print"$x,$n\n";

```

# Answer
> 1 votes
# Perl, 52 bytes

Includes +2 for `-ap`

Give input on STDIN

```
mono.pl <<< 33044255768277

```

`mono.pl`:

```
#!/usr/bin/perl -ap
$_=("@F"/++$.)**(1/$.)while!/\./?$\="$. $_":$_>2}{

```

Took some effort to make it work for `1` too. I have no idea if floating point errors can make this return the wrong answer for some inputs.

---
Tags: code-golf, number-theory
---


title: Round to n Sig Figs

text:
# Question
Title: Round to n Sig Figs
## Challenge

Given a number `x` and a number `n`, round number `x` to `n` significant figures and output the result.

## Significant figures

The significant figures of a number are digits that carry meaning contributing to its measurement resolution. This includes all numbers *except* leading zeroes.

Bear in mind that leading zeroes after a decimal point are still *insignificant* figures.

When rounding a digit, you must round away from zero if the following digit is greater or equal than five.

All trailing zeroes after a decimal point are counted as significant.

## Input

The first number will be `x`, the number to be rounded. The second number will be `n`, the number of significant figures you should round `x` to.

`x` will be a number (your code should handle both integers and floating points) between -1,000,000,000 and 1,000, 000,000 inclusive. `n` will be a positive integer between 1 and 50 inclusive. `n` will never be greater than the nunber of digits in `x`.

The input will never be `0` or any form of `0`, e.g. `0.000` or `000`.

## Examples

```
Inputs: 2.6754, 2
Output: 2.7

```

An output of `2.7000` would be invalid because the trailing zeroes after the decimal point are counted as significant figures.

---

```
Inputs: 0.00034551, 4
Output: 0.0003455

```

---

```
Inputs: 50237.1238, 3
Output: 50200

```

Note that this must not have a decimal point.

---

```
Inputs: 2374905, 1
Output: 2000000

```

---

```
Inputs: 543.0489, 4
Output: 543.0

```

---

```
Inputs: 15, 1
Output: 20

```

---

```
Inputs: 520.3, 3
Output: 520

```

If you wish, you can output `520.` instead but not `520.0`.

---

```
Inputs: -53.87, 2
Output: -54

```

---

```
Inputs: 0.0999, 2
Output: 0.10

```

## Rules

Built-in functions and libraries which allow you to round a number to `n` significant figures are disallowed.

## Winning

The shortest code in bytes wins.

# Answer
## Python 3, 83 bytes

(similar to the PHP answer)

```
from math import *
def s(x,n):
 y=10**(ceil(log10(abs(x)))-n)
 return y*round(x/y)

```

Test cases:

```
tests = [(2.6754,2), (0.00034551, 4), (50237.1238, 3),
        (2374905, 1), (543.0489, 4), (15, 1), (520.3, 3), (-53.87, 2)]

print ([s(x,n) for x,n in tests])

```

Output:

```
[2.7, 0.0003455, 50200, 2000000, 543.0, 20, 520, -54]

```

Apart from being slightly longer, another approach that I considered:

```
from math import *
def s(x,n):
 z=ceil(log10(abs(x)))
 return "%.*f"%(n-z,10**z*round(x/10**z,n))

```

... produces an incorrect output for the input of (15, 1):

```
['2.7', '0.0003455', '50200', '2000000', '543.0', '10', '520', '-54']

```

... due to floating point imprecision in the `round()` function. It seems likely to me that I could find test cases that would break the "round to zero decimal places" method also if I looked hard enough.

Thus, it seems to me that my solution probably isn't 100% correct for all cases and wouldn't be unless it was computed in decimal. This issue may therefore affect solutions in any language that use FP arithmetic.
> 3 votes

# Answer
# PHP, 130 Bytes

```
<?=number_format($r=round($i=$argv[1],($n=$argv[2])-ceil(log(abs($i),10))),($d=(1+floor(log(abs($r),10))-$n))<0?abs($d):0,".","");

```

PHP, 133 Bytes works with values \<1 for the significant figures

```
<?=number_format($r=round($i=$argv[1],($n=$argv[2])-floor(log(abs($i),10))-1),($d=(1+floor(log(abs($r),10))-$n))<0?abs($d):0,".","");

```

PHP, 56 Bytes works but skip unneccessary Zeros

```
<?=round($i=$argv[1],$argv[2]-floor(log(abs($i),10))-1);

```

Someone has stolen or deleted the round function in PHP! To make the challenge more interesting. 127 Bytes

```
<?=ceil($x=($i=$argv[1])*10**(($r=$argv[2])-($l=floor(log(abs($i),10))+1)))-$x<=0.5?ceil($x)*10**($l-$r):floor($x)*10**($l-$r);

```
> 5 votes

# Answer
## Batch, ~~660~~ 652 bytes

```
@echo off
set m=%1.
set s=
if %m:~,1%==- set s=-&set m=%m:~1%
:m
if %m:~,1%==0 set m=%m:~1%&goto m
set d=%m:.=%
:d
if %d:~,1%==0 set d=%d:~1%&goto d
for /l %%i in (1,1,%2) do call set d=%%d%%0
call set r=%%d:~%2,1%%
call set d=%%d:~,%2%%
if %r% leq 4 goto r
set r=
:i
set/ai=1+%d:~-1%
set r=%i:~-1%%r%
set d=%d:~,-1%
if %i% leq 9 set d=%d%%r%&goto r
if not "%d%"=="" goto i
set d=1%r:~1%
set m=1%m%
set m=%m:1.0=.%
:r
if %m:~,2%==.0 set m=%m:.0=.%&set d=0%d%&goto r
set i=0
set p=.
:l
if %m:~,1%==. echo %s%%i%%p%%d%&exit/b
if %i%==0 set i=
if "%d%"=="" set d=0&set p=
set i=%i%%d:~,1%
set d=%d:~1%
set m=%m:~1%
goto l

```

Explanation: Starts by suffixing a `.` to the parameter in case it doesn't have one already, then trims off the sign (which is saved) and any leading zeros. The resulting variable `m` is saved for later because it will tell us the desired magnitude of the result. Any `.`s are then removed, which could result in further leading zeros, so they are removed too. `n` zeros are suffixed to ensure that there are enough digits to round, then the `n`th and first `n` digits are extracted. If the `n`th digit is not 4 or less then we tediously add `1` to the string. If the string overflows then we increase the magnitude by prefixing a `1`, but if it was originally less than `0.1` we do that by removing the `1` we just added and also a `0` after the decimal point. If the magnitude is still less than `1` then we copy the zeros after the decimal point to the result, however if it is `1` or more then we extract the integer portion of the answer, adding extra zeros if necessary to reach the decimal point (which is then deleted as it would show incorrect precision). Finally the sign, integer portion, decimal point and decimal portion are concatenated.
> 3 votes

---
Tags: code-golf, math
---