title: Decompose a number into triangles

text:
# Question
Title: Decompose a number into triangles
Given an integer **n**, decompose it into a sum of maximal triangular numbers (where **Tm** represents the **m**th triangular number, or the sum of the integers from 1 to **m**) as follows:

* while **n \> 0**,

+ find the largest possible triangular number **Tm** such that **Tm ≤ n**.
    + append **m** to the triangular-decomposition representation of **n**.
    + subtract **Tm** from **n**.

For example, an input of **44** would yield an output of **8311**, because:

* 1+2+3+4+5+6+7+8 = 36 \< 44, but 1+2+3+4+5+6+7+8+9 = 45 \> 44.

+ the first digit is **8**; subtract 36 from 44 to get **8** left over.
* 1+2+3 = 6 \< 8, but 1+2+3+4 = 10 \> 8.

+ the second digit is **3**; subtract 6 from 8 to get **2** left over.
* 1 \< 2, but 1+2 = 3 \> 2.

+ the third and fourth digits must be **1** and **1**.

Use the digits 1 through 9 to represent the first 9 triangular numbers, then use the letters a through z (can be capitalized or lowercase) to represent the 10th through 35th triangular number. You will never be given an input that will necessitate the use of a larger "digit".

The bounds on the input are **1 ≤ n \< 666**, and it will always be an integer.

All possible inputs and outputs, and some selected test cases (listed as input, then output):

```
1 1
2 11
3 2
4 21
5 211
6 3
100 d32
230 k5211
435 t
665 z731

```

An output of  for an input of **-1/12** is not required. :)

# Answer
## JavaScript (ES6), 52 bytes

```
f=(n,t=0)=>t<n?f(n-++t,t):t.toString(36)+(n?f(n):'')

```

### How?

Rather than explicitly computing ***Ti = 1 + 2 + 3 + … + i***, we start with ***t = 0*** and iteratively subtract ***t + 1*** from ***n*** while ***t \< n***, incrementing ***t*** at each iteration. When the condition is not fulfilled anymore, a total of ***Tt*** has been subtracted from ***n*** and the output is updated accordingly. We repeat the process until ***n = 0***.

Below is a summary of all operations for ***n = 100***.

```
 n  |  t | t < n | output
----+----+-------+--------
100 |  0 | yes   | ""
 99 |  1 | yes   | ""
 97 |  2 | yes   | ""
 94 |  3 | yes   | ""
 90 |  4 | yes   | ""
 85 |  5 | yes   | ""
 79 |  6 | yes   | ""
 72 |  7 | yes   | ""
 64 |  8 | yes   | ""
 55 |  9 | yes   | ""
 45 | 10 | yes   | ""
 34 | 11 | yes   | ""
 22 | 12 | yes   | ""
  9 | 13 | no    | "d"
----+----+-------+--------
  9 |  0 | yes   | "d"
  8 |  1 | yes   | "d"
  6 |  2 | yes   | "d"
  3 |  3 | no    | "d3"
----+----+-------+--------
  3 |  0 | yes   | "d3"
  2 |  1 | yes   | "d3"
  0 |  2 | no    | "d32"

```

### Test cases

```
f=(n,t=0)=>t<n?f(n-++t,t):t.toString(36)+(n?f(n):'')

console.log(f(1))   // 1
console.log(f(2))   // 11
console.log(f(3))   // 2
console.log(f(4))   // 21
console.log(f(5))   // 211
console.log(f(6))   // 3
console.log(f(100)) // d32
console.log(f(230)) // k5211
console.log(f(435)) // t
console.log(f(665)) // z731
```
> 8 votes

# Answer
# Jelly, ~~18~~ 17 bytes

```
Ḥ‘½+.Ḟ©ịØB2®cạµ¹¿

```

This is a monadic link that prints to STDOUT. It's return value is **0** and should be ignored.

Try it online!
> 5 votes

# Answer
# dc, 74 bytes

```
?sa[2k_1K/1 4/la2*+v+0k1/dlardd*+2/-sadd10<t9>ula0<s]ss[87+P]st[48+P]sulsx

```

This is awful.

```
?sa             stores the input
[2k             sets precision to 2 so dc doesn't truncate 1/4
_1K/1 4/la2*+v+ uses the quadratic formula to find k, the next value to print
0k1/d           truncates k to an integer
lardd*+2/-sa    subtracts kth triangular number from the input
dd10<t9>u       determines whether to print k as a letter or a digit
la0<s]ss        loops when a is greater than 0
[87+P]st        prints k as a letter
[48+P]su        prints k as a digit (not p, as that leaves a trailing newline)
lsx             starts the main loop

```
> 4 votes

# Answer
## JavaScript (ES6), ~~61~~ 57 bytes

*Saved 4 bytes thanks to @Arnauld*

```
f=(n,p=q=0)=>n?p-~q>n?q.toString(36)+f(n-p):f(n,++q+p):''

```
> 3 votes

# Answer
# Retina, ~~115~~ ~~108~~ ~~38~~ 34 bytes

```
.+
$*¶
(\G¶|¶\1)+
0$1
+T`_w¶`w_`.¶

```

\[Try it online!\] (Includes test suite) Uses uppercase letters. Edit: Saved ~~70~~ 74 bytes by shamelessly adapting @MartinEnder's answer to Is this number triangular? Explanation: The number is converted into unary, then the largest possible triangular number is repeatedly matched until the number is exhausted. Each match is then converted into base 36.
> 2 votes

# Answer
# Java 7, 81 bytes

```
int i=0;String c(int n){return i<n?c(n-++i):Long.toString(i,36)+(n>(i=0)?c(n):"");}

```

Port from *@Arnauld*'s amazing JavaScript (ES6) answer.
My own approach was almost 2x as long..

Try it here.

**Explanation:**

```
int i=0;                  // Temp integer `i` (on class level)
String c(int n){          // Method with integer parameter and String return-type
  return i<n?             //  If `i` is smaller than the input integer
    c(n-++i)              //   Return a recursive call with input minus `i+1` (and raise `i` by 1 in the process)
   :                      //  Else:
    Long.toString(i,36)+  //   Return `i` as Base-36 +
     (n>(i=0)?            //   (If the input integer is larger than 0 (and reset `i` to 0 in the process)
      c(n)                //    Recursive call with the input integer
     :                    //   Else:
      "");                //    an empty String)
}                         // End of method

```
> 2 votes

# Answer
# PHP, 74 Bytes

```
for(;$n=&$argn;$t.=$i>10?chr($i+86):$i-1)for($i=0;$n>=++$i;)$n-=$i;echo$t;

```

Online Version
> 1 votes

# Answer
# R, 87 bytes

Originally, I tried to preset the possible Triangular numbers. This led to this code with 105 bytes:

```
pryr::f(n,{l=cumsum(1:35)
k=''
while(n){y=tail(which(l<=n),1)
n=n-l[y]
k=paste0(k,c(1:9,letters)[y])}
k})

```

This required more indexing so I tried the methodology from @Arnauld to reduce the bytes down to 87.

```
pryr::f(n,{k='';while(n){t=0;while(t<n){t=t+1;n=n-t};k=paste0(k,c(1:9,letters)[t])};k})

```

Both codes made use of the preset letters, since their I couldn't find a short way to convert to base 36.
> 0 votes

---
Tags: code-golf, number, integer
---


title: XKCD Password Generator

text:
# Question
Title: XKCD Password Generator
# Introduction

Apparently, this question has been asked here and it unfortunately closed. I thought it was a good idea to try again with it, but done right.

XKCD looks at the how we are trained to use "hard to remember passwords", thinking it's secure, but instead, would take a computer 3 days to crack. On the flip side, remembering 4-5 words brings Kuan's Password Intropy up, and is easy to remember. Crazy how that works, huh?

# Challenge

The job today is to create 5 passwords using words. 4 words per password and a minimum of 4 letters per word, but no maximum. Kuan's Password Intropy will need to be calculated for every password, but a forced minimum will not be set.

# What is Kuan's Password Intropy?

Kuan's Password Intropy is a measurement of how unpredictable a password is, according to Kuan. There is a simple calculation: **E = log2(R) * L**. E being Kuan's Password Intropy, R being range of available characters and L for password length.

Range of available characters is self explanatory. It's the range of characters that a password can have, in this case is Upper and lower case. Since there is 26 characters in the alphabet, 26 x 2 = 52 characters in the whole range of the password.

Password Length is also self explanatory. It's the total length of the password after creation.

# Constraints

* No input.
* A word **cannot reappear** in the same password.
* No symbols or numbers allowed in a password.
* 4 words per password, but a forced minimum of 4 letters per word.
* No spaces between words.
* You cannot generate the same password over and over again.
* Each word has to be capitalized in a password.
* Output has to be human-readable, must be spaced out. Must also include Kuan's Password Intropy of the password with it using Kuan's Password Intropy equation above.
* Dictionary. You must use this, download it as a text file and integrate accordingly. This will be the list from which you grab words from. Your code should assume its available.
* This is , shortest bytes win.

# Output

```
TriedScarProgressPopulation 153.9
TryingPastOnesPutting 119.7
YearnGasesDeerGiven 108.3
DoubtFeetSomebodyCreature 142.5
LiquidSureDreamCatch 114.0

```

# Answer
> 12 votes
# Python 2, ~~102~~ ~~101~~ ~~97~~ 91 bytes

```
from random import*
exec"x=''.join(x.title()for x in sample(f,4));print(x,57*len(x)/10);"*5

```

Assumes the dictionary as a list named `f`.

Can be tested by saving the file as `dict.txt` and calling

```
f = open('dict.txt').readlines()

```

# Answer
> 10 votes
# PowerShell (3.0+), 77 bytes

```
1..5|%{($p=-join($d|random -c 4|%{culture|% te*|% tot* $_}));57*$p.Length/10}

```

Try it online!

Using Jonathan Allan's `57*len/10` trick.

`$d` contains the dictionary as an array of words. If you're playing at home and want to fill `$d`:

```
$d=-split(irm pastebin.com/raw/eMRSQ4u2)

```

Using a golfed version of `(Get-Culture).TextInfo.ToTitleCase()` to capitalize the first letter; I don't think there's a shorter way to do that in PowerShell.

The rest is pretty straightforward I think.

The TIO link has the whole dictionary; disable the cache and go nuts!

# Answer
> 7 votes
# Jelly, 22 bytes

```
Ẋḣ4ŒtFµL×57÷⁵⁸,K
çÐ€5Y

```

A monadic link taking a list of list of characters, the parsed dictionary (as allowed in chat).

**Try it online!** (Click "Arguments" to hide the dictionary and reduce the need to scroll.)

### How?

Since the dictionary only contains valid words (`4`characters or more, only `[a-z]`), there is no need to check this condition.

Since all the words in the dictionary have lengths in `[4-8]` the possible password lengths are in `[16,32]`, and the possible entropies will never round differently to one decimal place than by replacing `log(52,2)` with `5.7`. The only problem is that using a floating point value of `5.7` will give floating point rounding errors for lengths `18`, `26`, and `31`. However multiplying by `57` and *then* dividing by `10` using `×57÷⁵` avoids this (while still being a byte shorter than printing the full floating point precision value using `×52l2¤`).

```
çÐ€5Y - Main link: list of list of characters (the parsed dictionary)
   5  - literal 5
 Ð€   - map across the implicit range [1,2,3,4,5]:
ç     -   last link (1) as a dyad
    Y - join with newlines
      - implicit print

Ẋḣ4ŒtFµL×57÷⁵⁸,K - Link 1, get password and entropy: list of lists of characters, number
Ẋ                - shuffle the list of lists (shuffle all the words)
 ḣ4              - head to 4 (the first four words)
   Œt            - title case (make the first letter of each uppercase)
     F           - flatten into one list of characters
      µ          - monadic chain separation, call that p
       L         - length of p
         57      - 57
        ×        - multiply
            ⁵    - 10
           ÷     - divide -> entropy to 1 decimal place
             ⁸   - link's left argument, p
              ,  - pair -> [p, entropy]
               K - join with (a) space(s)

```

# Answer
> 5 votes
# Ruby, ~~89~~ 83 bytes

```
d.select!{|w|w[3]}
5.times{p w=d.sample(4).map(&:capitalize)*'',5.700439718*w.size}

```

Assumes that the passwords are stored in the variable `d`. You can add this line before the code:

```
d=$<.map(&:chomp)

```

and call the script for instance like this:

```
$ ruby generate_passwords.rb < dictionary_file.txt

```

Sample output:

```
"MarginStarvedOnusInsulted"
142.51099295
"KitchenMiseryLurkJoints"
131.110113514
"InducesNotablePitfallsPrecede"
165.312751822
"FarmersAbortFutileWrapper"
142.51099295
"RoutesBishopGlowFaithful"
136.81055323200002

```

*KitchenMiseryLurkJoints*... wow.

---

-6 bytes from Ajedi32

# Answer
> 4 votes
## Mathematica, 178 bytes

```
t=1;l=Length;While[t<6,s=RandomChoice[Import["https://pastebin.com/raw/eMRSQ4u2"],4];c=Capitalize/@s;f=Flatten@Characters[c];Print[StringJoin[c]," ",Log[2,l@Union@f]*l@f//N];t++]

```

Try it online

copy and paste using ctrl-v and press shift+enter to run

---

## Mathematica, 136 bytes

assuming that m is the dictionary the code is

```
m=ImportString[Import["C:\a.txt"]]

```

.

```
t=1;l=Length;While[t<6,s=RandomChoice[m,4];c=Capitalize/@s;f=Flatten@Characters[c];Print[StringJoin[c]," ",Log[2,l@Union@f]*l@f//N];t++]

```

# Answer
> 4 votes
# Bash, ~~66~~ 65 bytes

```
for w in `shuf -n4 -`;{((l+=${#w}));printf ${w^};};bc<<<$l*5.7004

```

Try it online!

Dictionary is recived by STDIN. Shuffles all words in dictionary and outputs first 4.

For each word, adds up its length in var l, and echoes the word capitalized. In the end calls bc to do the math.

Awk solution, 112 bytes, four passwords:

```
shuf -n16 -|xargs -n4|awk '{for(i=1;i<5;i++)printf toupper(substr($i,1,1))substr($i,2);print(length($0)-3)*5.7}'

```

# Answer
> 3 votes
# JavaScript (ES6), 164 bytes

```
d=>{for(i=5;i--;)console.log(p="....".replace(/./g,_=>(w=d.splice(Math.random()*d.length|0,1)[0])[0].toUpperCase()+w.slice(1)),(Math.log2(52)*p.length).toFixed(1))}

```

Assumes the dictionary is passed to the function as an array.

## Test Snippet

# Answer
> 3 votes
# Japt, 30 bytes

```
5Ç[V=Uö4 ®g u +Zt1Ã¬Mm52 *Vl]¸

```

Try it online!

# Answer
> 3 votes
(This is an adaptation of Martmists' answer, but I don't have the rep to comment)

# Python, ~~88~~ 86 bytes

```
g={*f}
exec('x="".join(g.pop().title()for i in "a"*4);print(x,len(x)*5.700439718);'*5)

```

By exploiting how `set` is nondeterministic, you can avoid having to import any randomness libraries.

# Answer
> 2 votes
# tcl, 137

Not a winner for sure, but I think it can be a golfed a little more.

```
time {set p "";time {set p [string totitle [lindex $d [expr int(rand()*[llength $d])]]]$p} 4;puts $p\ [expr 5.7004*[string length $p]]} 5

```

demo — The line 1 purpose is only to put the dictionary contents into the variable `d`

# Answer
> 2 votes
## Mathematica, 71 Bytes

Assuming the dictionary is already loaded into an array called `d`.

```
Table[{#,Log[2,52]StringLength[#]}&[""<>Capitalize@d~RandomSample~4],5]

```

Explaination:

```
                                        Capitalize@d                    - Capitalize all the dictionary
                                                    ~RandomSample~4     - make an array with 4 values. By default values can not repeat.
                                    ""<>                                - Concatenate with empty string to turn array into single string.
      {#,Log[2,52]StringLength[#]}&[                               ]    - Put current string next to log(2,52) times length of current string
Table[                                                              ,5] - Repeat this 5 times.

```

# Answer
> 2 votes
# PHP, 136 129 bytes

-7 bytes, thanks Jörg

```
for(shuffle($a);$i++<5;){for($s='',$c=0;$c<4;)strlen($w=$a[$k++])<4?:$s.=ucfirst($w).!++$c;echo$s.' '.log(52, 2)*strlen($s)."
";}

```

Try it online!

# Answer
> 2 votes
# ColdFusion 216 bytes

```
p={};z=arrayLen(c);for(x=0;x<5;x++){pw="";r={};while(structCount(r)<4){n=RandRange(1,z);r.append({"#c[n]#":true});}for(w in structKeyList(r)){pw&=REReplace(w,"\b(\w)","\u\1","All");};p.append({"#pw#":57*len(pw)/10})}

```

This works in ColdFusion 11+ and Lucee 4.5+

To run it: https://trycf.com/gist/ff14e2b27d66f28ff69ab90365361b12/acf11?theme=monokai

The TryCF link has less-golf-ish but the same code.

I didn't really expect to have a competitive golfing answer; I just wanted to see what it would take to complete this challenge in ColdFusion. Especially since there isn't much CF in these answers. :-) After the setup, it was surprisingly shorter than I expected.

My first attempt was a little shorter until I remembered that the same word can't be used more than once. Even though it's highly unlikely that the randomizer would pick the same index more than once, I dump the indexes into the keys of a structure, which will prevent duplication. Then I use that list of keys to build my final password string. I also used the math trick to find entropy.

# Answer
> 2 votes
# Python 3, 252 bytes

This is my first ever code golf challenge I've done! I know there are other Python answers on here (that are probably better than mine) but this looked fun, and so I wanted to try it anyways. Here's the golfed version:

```
import random, math
with open("d") as f: d=f.read()
l=d.split()
for a in range(5):
 u=[]
 p=""
 for b in range(4):
  w=random.choice([w for w in l if not w in u and len(w)>=4])
  u.append(w)
  w=w.title()
  p+=w
 print("%s %s"%(p,math.log2(52)*len(p)))

```

I would post a Try it Online! link, but that doesn't support multiple files. So here's a repl.it link: https://repl.it/InIl/0

Also, here's the ungolfed version:

```
import random
import math
with open("d") as f:
    dictionary = f.read() #this is the dictionary text file, simply saved as "d" as to use as few bytes as possible
words = dictionary.split() #here we turn that dictionary string into a list
for a in range(5): #here we iterate through 5 passwords
    used_words = []
    password = ""
    for b in range(4): #here we iterate through the 4 words in each password
        word = ""
        word = random.choice([word for word in words if not word in used_words and len(word) >= 4]) #Thanks to blackadder1337 from #python on freenode IRC for helping me with this.
        used_words.append(word)
        word = word.title()
        password = password + word
    print("%s %s"%(password, math.log2(52) * len(password)))

```

Like I said, this is my first time code gofling, so I'm sure this could be improved a lot.

# Answer
> 0 votes
# q/kdb+, ~~76~~ ~~74~~ ~~65~~ 56 bytes

**Solution:**

```
{(x;5.70044*(#)x)}(,/)@[;0;upper]each -4?" "vs(*)(0:)`:w

```

**Example:**

```
q){(x;5.70044*(#)x)}(,/)@[;0;upper]each -4?" "vs(*)(0:)`:w
"RulingOverheadSaddensPriest"
153.9119

```

**Explanation:**

Read in the word list, break apart on " ", pick 4 random words from this list, uppercase first letter of each word, then join together. Feed this into a lambda function which returns the password and the calculated 'entropy':

```
                                                     `:w / the wordlist is a file called 'w'
                                                 (0:)    / read in the file list (\n separated list)
                                              (*)        / take first (and only) item in the list
                                         " "vs           / split this on " "
                                      -4?                / take 4 random items from this list, neg means 'dont put back'
                      @[; ;     ]                        / apply a function to variable at indices (variable is implicit)
                           upper                         / uppercase (the function being applied)
                         0                               / index 0, the first character
                                 each                    / each of the 4 random items
                  (,/)                                   / 'raze' (flatten lists)
{                }                                       / anonymous lambda function
 (x;            )                                        / a 2-item list, x is first item
            (#)x                                         / count x, return the length of the list
    5.70044*                                             / multiply by 5.70044

```

**Notes:**

I caved in and used 5.70044 instead of `2 xlog 52 xexp`...

# Answer
> 0 votes
# Vim, 87 keystrokes

```
qq:r!echo "$RANDOM"l<CR>D:w o|e w<CR>@"ev4bd:w|bp<CR>p0~wX~wX~wX~Y:.!wc -c<CR>A*5.7003<Esc>:.!bc<CR>PJq4@q

```

Assumes that the dictionary is in a file named `w`. Will always use 4 consecutive words
Explanation:

```
qq                       Start recording a macro named 'q'
:r!echo "$RANDOM"l<CR>   Append the result of the shell command `echo "$RANDOM"l`
D                        Delete what you just appended
:w o|                    Save the buffer to the file 'o' and ..
e w<CR>                  Open the file 'w'
@"                       Execute the text we deleted as a normal-mode command
                         This will move the cursor a random number of characters
                         to the right
e                        Go to the end of the next word
v4bd                     Delete 4 words backwards
:w|                      Save the file and ..
bp<CR>                   Open the last buffer (the 'o' file)
p                        Paste the 4 words we deleted
0                        Move the cursor to the beginning of the line
~wX~wX~wX~               Remove the spaces between the words and capitalize
Y                        Copy current line
:.!wc -c<CR>             Pipe the current line through 'wc -c'
A*5.7003<Esc>            Append "*5.7003" to the end of the line
:.!bc<CR>                Pipe the current line through 'bc'
P                        Paste the password above the current line
J                        Join with line bellow
q                        Stop recording the 'q' macro
4@q                      Run the 'q' macro 4 times

```

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


title: How Persistent am I?

text:
# Question
Title: How Persistent am I?
## Your Task:

Write a program or function that, when given a number, outputs its *persistence*. The persistence of a number is the number of times you can add its digits before arriving at a one-digit number. All one digit numbers have a persistence of 0. Note that this is different from questions about finding the digital root, as those questions ask for the end result of this process, whereas this question wants the number of steps required to get there.

## Input:

An integer.

## Output:

The persistence of the inputted integer.

## Examples:

```
1-->0 (1=1)
12-->1 (1+2=3)
99-->2  (9+9=18, 1+8=9)
9999-->2 (9+9+9+9=36, 3+6=9)

```

## Scoring:

This is , lowest score in bytes wins.

# Answer
> 4 votes
# Jelly, 7 bytes

```
DS$ÐĿL’

```

Try it online!

## How it works

```
DS$ÐĿL’
DS$      digital sum
   ÐĿ    apply until results not unique, collect all intermediate results
     L   length of the collection
      ’  minus 1

```

# Answer
> 6 votes
# Python 2, ~~50~~ 39 bytes

-10 thanks to @JonathanAllan

```
f=lambda x:x>9and-~f(sum(map(int,`x`)))

```

Try it online!

# Answer
> 5 votes
# Brachylog, 10 bytes

```
;.{ẹ+}ⁱ⁾Ḋ∧

```

Try it online!

### Explanation

```
;.{  }ⁱ⁾     Iterate Output times on the Input…
        Ḋ∧   …so that the result is a single digit:
   ẹ+          Sum the elements

```

# Answer
> 5 votes
# Prolog (SWI), ~~91~~ 90 bytes

```
s(A,B):-A=0,B=0;divmod(A,10,Q,R),s(Q,T),B is T+R.
p(A,B):-A<10,B=0;s(A,S),p(S,T),B is T+1.

```

Try it online!

# Answer
> 3 votes
# C (gcc), 58 bytes

1 byte thanks to Felipe Nardi Batista and Kritixi Lithos who discovered the same golf independently.

```
a,m;f(n){for(m=n,a=0;m;m/=10)a+=m%10;return n>9?1+f(a):0;}

```

Try it online!

# Answer
> 3 votes
# Mathematica, 48 bytes

```
(n=#;t=0;While[n>9,n=Tr@IntegerDigits@n;t++];t)&

```

but **alephalpha** golfed it down to...

# Mathematica, 41 bytes

```
(t=-1;#//.n_:>Tr[t++;IntegerDigits@n];t)&

```

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
[DgiNq}SO

```

Explanation:

```
[          Start infinite loop
 D         Duplicate
  g        Length
   i       If equal to one:
    N        Push iteration number
     q       Terminate program
      }    Else:
       S     Get the characters
        O    Sum

```

Try it online!

# Answer
> 2 votes
# Haskell, ~~46~~ 45 bytes

```
g n|m<-sum$read.pure<$>show n,m<n=1+g m|1<3=0

```

Try it online!

`read.pure<$>show n` converts an integer `n` to a list of digits, applying `sum` to this list yields the digital sum `m`. If `m` is smaller than `n` then `n` was not yet a single digit, so we recursively call `g m` and add one. Otherwise `0` is returned.

# Answer
> 2 votes
# Javascript, 47 bytes

```
f=x=>x>9?f([...x+""].reduce((a,b)=>+a+ +b))+1:0

```

```
f=x=>x>9?f([...x+""].reduce((a,b)=>+a+ +b))+1:0

console.log('1 -> ' + f(1));
console.log('12 -> ' + f(12));
console.log('99 -> ' + f(99));
console.log('9999 -> ' + f(9999));
```

# Answer
> 2 votes
# Java 8, 67 bytes

```
n->{int r=0,s;for(;n>9;n=s,r++)for(s=0;n>0;n/=10)s+=n%10;return r;}

```

**Explanation:**

Try it here.

```
n->{            // Method with integer parameter and integer return-type
  int r=0,      //  Result-count
      s;        //  Digit-sum
  for(;n>9      //  Loop as long as `n` contains more than 1 digit
      ;         //    After every iteration:
      n=s,      //     Replace the `n` with the sum of digits
      r++)      //     and increase the result-count
    for(s=0;    //   Reset the sum to 0
        n>0;    //    Inner loop (2) as long as n is larger than 0
        n/=10)  //     Divide n by 10 every iteration
      s+=n%10;  //    And increase the sum with the trailing digit
                //   End of inner loop (2) (implicit / single-line body)
                //  End of loop (1) (implicit / single-line body)
  return r;     //  Return the result-count
}               // End of method

```

# Answer
> 2 votes
## Lua 125

```
function r(n,c,t,m)n=tostring(n)t,c=0,c or 0;for m=1,#n do t=t+n:sub(m,m)end return #n==1 and(print(c)or true)or r(t, c+1)end

```

you call it simply using r({yourNumber})

# Answer
> 2 votes
# MATL, 13 bytes

```
t:"tFYAs]v9>s

```

Try it online!

### Explanation

```
t        % Implicit input. Duplicate
:"       % Do the following that many times
  t      %   Duplicate
  FYA    %   Convert to base 10: array of decimal digits
  s      %   Sum of array
]        % End
v        % Concatenate stack vertically
9>       % Greater than 9? element-wise
s        % Sum. Implicit display

```

# Answer
> 2 votes
# Perl 5, 32 bytes

31 bytes of code + `-p` flag.

```
$_=eval,$\++while 1<s/./+$&/g}{

```

Try it online!

Short explanations:
`s/./+$&/g` adds a `+` before each digit and returns the number of digits. While this number is greater than `1`, we set `$_` to the value of the `eval`uation of this string, and increment the number of set (`$\++`). At the end, `$\` is implicitly printed thanks to `-p` and `}{`.

# Answer
> 1 votes
# PHP, 58 bytes

```
for(;9<$a=&$argn;$a=array_sum(str_split($a)))$p++;echo+$p;

```

Try it online!

# Answer
> 1 votes
# Swift 4, 89 bytes

```
func p(i:Int)->Int{return"\(i)".count==1 ?i :p(i:"\(i)".map{Int("\($0)")!}.reduce(0,+))}

```

Swift 4 is still in beta, so you can't run it online. If you have Xcode 9 Beta, it will work.

Un-golfed:

```
func p(i: Int) -> Int {
    return "\(i)".count==1 ? i : p(i: "\(i)".map{Int("\($0)")!}.reduce(0,+))
}

```

Here we check to see how many digits are in the number. If it is only one, we return the number. If not, we turn it into a string, change each character back into an int, get the total sum of all the digits, and run that back through the original function.

# Answer
> 1 votes
## Clojure, 88 bytes

```
#(loop[v(str %)i 0](if(=(count v)1)i(recur(str(apply +(for[c v](-(int c)48))))(inc i))))

```

Oddly long...

# Answer
> 1 votes
# Dyalog APL, 27 bytes

```
{⍵≤9:0⋄1+∇+/⍵⊤⍨10⍴⍨⌈10⍟1+⍵}

```

# Answer
> 1 votes
# Lua, ~~82~~ 80 bytes

```
x=~~...c=0while x>9 do
c=c+1z=0while x>0 do
z=z+x%10x=x//10
end
x=z
end
print(c)

```

Try it online!

# Answer
> 1 votes
# Braingolf, 28 bytes

```
V0R1>[dl2-?<1+M&+vm1+R>:v_|]

```

Try it online!

## Explanation

```
V0R1>[dl2-?<1+M&+vm1+R>:v_|]  Implicit input of commandline args
V0R                           Create stack2, push 0, return to stack1
   1>                         Push 1 to bottom of stack1
     [.....................]  While loop, will run while bottom item on stack1 is not 0
      d                       Split top of stack into digits
       l2-?                   If length of stack <= 2..
           <1+                ..Move BoS to stop and increment
              M               ..Move item to stack2
               &+             ..Sum entire stack
                 vm           ..Move item back from stack2
                   1+         ..Increment top item on stack2
                     R>       ..Return to stack1 and move ToS to bottom
                       :      Else
                        v_    ..Switch to stack2 and print last item
                          |   Endif

```

# Answer
> 1 votes
# Retina, 26 bytes

```
1`\d.
#$&
\d
$*
}`1+
$.&
#

```

Try it online! Explanation: The first stage counts the persistence: if there are at least two digits, the persistence (represented here by `#` signs) is incremented. The second stage converts each digit individually to unary, effectively adding them, while the third stage converts back to decimal, looping until a single digit is obtained. It then remains to count the `#` signs.

---
Tags: code-golf, number, sequence
---


# Question
Title: ASCII Arc Length: How long is a piece of string?
Given an ASCII representation of a piece of string, determine its length.

# Input

An multi-line ASCII rendering of a piece of string, which runs from top to bottom, with one 'node' (corner) on each line of input. The delimiter may be assumed to be `CR`, `LF`, `CRLF`, or `LFCR`. Input may be accepted from STDIN, Command Line Argument, Function Parameter, or whatever daft method your language of choice necessitates if none of the prior are applicable.

```
  #
 #
 #
  ####
##
  ##
 #
  ##
  #

```

Each line in the context of the previous tells you the position of one of the nodes on the string. The first line always has exactly one hash `#`, so the position is trivially found. Each following line has a hash '#' on the node itself, and on all calls which must be included to make the string 'complete' (attached to itself). All positions will be between 0 and 9 inclusive, but the difference is what realy matters.

For example, the string defined by the sequence `1, 3, 6, 5, 1, 3, 4` has the following nodes:

```
 #
   #
      #
     #
 #
   #
 #
     #
    #

```

Which we must join up on a line by line basis starting from the top (nodes marked with `X` for clarity, they will be hashes in actual imputs). This means, the first line has no hashes, and each following line has exactly as many hashes as are rquired to 'connect' the previous node to the current with hashes. This can be thought of as putting a hash in every space between the two nodes (on the lower line) and then removing any that appear on the line above. Example:

```
 X
  #X
    ##X
     X
 X###
   X
 X#
   ##X
    X

```

There will be no fewer than 2 lines, and no more than 100. The input will be padded with spaces to form a rectangle of width 10 (excluding the line delimiters). You may require a trailing new-line be present or absent, but declare any such requirements in your answer.

# Computing the Arc Length

You must output the arc length of this string. You compute the arc length by taking the distances between each consequtive nodes. The distance between one node and the next is `sqrt(d^2 + 1)` where `d` is the difference in position (that is, the current position minus the previous). For example, the sequence `4, 8, 2, 3, 4, 4` has differences `4, -6, 1, 1, 0`, which gives distances (rounded to 2 dp) `4.12, 6.08, 1.41, 1.41, 1` by squaring, adding one, and square-rooting. The arc length is then the sum of these distances, `14.02`.

You *must* reduce the result of the square-root to 2 decimal places before summing (this is to allow sqrt tables and make answers consistent/comparable across systems; see below).

Using the input example at the top\`

```
  #    2 -1  1.41
 #     1 +0  1.00
 #     1 +4  4.12
  #### 5 -5  5.10
##     0 +3  3.16
  ##   3 -2  2.24
 #     1 +2  2.24
  ##   3 -1  1.41
  #    2

            20.68 (total)

```

# Output

You must output the arc length as exactly one number, or a decimal string represenation with 2 decimal places of precision. Numerical output must be rounded, but I'm not going to quibble about minute floating point inaccuracies.

# SQRT Table

This is a table of the rounded squareroots you must conform to. You can either use this table itself, or verify that your system conforms to the results.

```
1  1.00
2  1.41
5  2.24
10 3.16
17 4.12
26 5.10
37 6.08
50 7.07
65 8.06
82 9.06

```

Powershell to produce this table:

```
0..9 | % {"" + ($_ * $_ + 1) + " " + [System.Math]::Sqrt($_ * $_ +1).ToString("0.00")}

```

# Test Cases

Input:

```
  #
 #
 #
  ####
##
  ##
 #
  ##
  #

```

Output: `20.68`

Input:

```
   #
###
   ####
      #
   ###
    #
     ###
 ####
   #
  #
##
  ########
         #
      ###
######

```

Output: `49.24`

Input:

```
         #
       ##
 ######
 #
  ####
      #
######
#
 ########
     #
 ####
     ####

```

Output: `44.34`

# Test Code

A larger test case and a C# solver and example generator can be found as a Gist.

# Victory Criterion

This is code-golf, the shortest code will win.

# Answer
# JavaScript (ES6), 158 bytes

*-1 byte thanks to @VisualMelon*

```
s=>s.split`
`.map(s=>(s=s.replace(/./g,(m,i)=>m>" "?i:""),n=s[0]>n?s.slice(-1):s[0]),n=p=0).reduce((t,v,i)=>(r=i&&t+(((p-v)**2+1)**.5*100+.5|0)/100,p=v,r),0)

```

Output is sometimes not exact (`0.999` instead of `1`) due to floating-point imprecision, but rounding was done part-way through the steps in order to match the square root table.

## Test Snippet

Note that trailing spaces on each line are ignored, so they can be omitted from the input.

```
f=
s=>s.split`
`.map(s=>(s=s.replace(/./g,(m,i)=>m>" "?i:""),n=s[0]>n?s.slice(-1):s[0]),n=p=0).reduce((t,v,i)=>(r=i&&t+(((p-v)**2+1)**.5*100+.5|0)/100,p=v,r),0)
```

```
<textarea id=I rows=15 cols=12></textarea><br>
<button onclick="O.value=f(I.value)">Run</button> <input id=O disabled>
```
> 1 votes

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


title: Exact change in fewest bills and coins

text:
# Question
Title: Exact change in fewest bills and coins
## Overview

In the US, the common denominations are the penny ($0.01), the nickel ($0.05), the dime ($0.10), the quarter ($0.25), one dollar, two dollars (less common but lets pretend it's common), five dollars, ten dollars, twenty dollars, fifty dollars, and one hundred dollars. ($1 to $100 respectively).

Your goal is to take an arbitrary money value and output a list of the fewest bills and coins that add up to that amount.

## Rules

* The output must be minimal. You cannot output "4175 pennies" for $41.75.
* The inputs and outputs can be any format or type, as long as you can explain what it means.
* Values must be kept the same. For instance, your program cannot accept "6523" for $65.23. It must accept the decimal value "65.23"

## Examples

If the input is $185.24, the output should be something like
$100 + $50 + $20 + $10 + $5 + $0.10 + $0.10 + $0.01 + $0.01 + $0.01 + $0.01

For the input $44.75, another acceptable output would be
\[0, 0, 2, 0, 0, 2, 0, 3, 0, 0, 0\]
Meaning 2 $20s, 2 $2s, 3 quarters, and 0 of the other denominations.

## Bonus

Accept another argument for the list of denominations so your program will work in other countries.

For example, if it's given this list of denominations.
\[15, 7, 2.5, 1, 0.88, 0.2, 0.01\]
and the money value "37.6", it should return something like
15 + 15 + 7 + 0.2 + 0.2 + 0.2

# Answer
# Mathematica, 54 bytes

```
#~NumberDecompose~{100,50,20,10,5,2,1,.25,.1,.05,.01}&

```

input

> \[44.75\]

output

> {0, 0, 2, 0, 0, 2, 0, 3, 0, 0, 0.}

# Mathematica, 82 bytes --WITH BONUS--

```
(s=#~NumberDecompose~#2;Row@Flatten@Table[Table[#2[[i]]"+",s[[i]]],{i,Length@s}])&

```

**Input**

> \[37.6, {15, 7, 2.5, 1, 0.88, 0.2, 0.01}\]

**output**

> 15 +15 +7 +0.2 +0.2 +0.2 +
> 4 votes

# Answer
# **Python 2**, ~~53~~ ~~94~~ ~~90~~ 78 bytes with bonus

```
def f(m,d=[100,50,20,10,5,2,1,.25,.1,.05,.01]):
 for i in d:
    print m//i
    m%=i

```

\*The indentation is a space for line 2, and tabs for the other lines

The function takes in the amount of money and a *sorted* list of the denominations (if not US).

Examples:

```
>>> f(44.75)
0.0
0.0
2.0
0.0
0.0
2.0
0.0
3.0
0.0
0.0
0.0
>>> f(37.6, [15, 7, 2.5, 1, 0.88, 0.2, 0.01])
2.0
1.0
0.0
0.0
0.0
3.0
0.0
>>> f(8, [5,4,1])
1
0
3

```
> 1 votes

# Answer
# Javascript(ES6), 97 bytes with bonus

```
f=(m,d=[100,50,20,10,5,2,1,0.25,0.1,0.05,0.01])=>{for(i of d){z=Math.round(m/i);alert(z);m-=z*i}}

```

# Java, 209 bytes

*so verbose...*

```
interface A{static void main(String[]a){int m=Integer.valueOf(a[0]);for(double i:new Double[]{100.0,50.0,20.0,10.0,5.0,2.0,1.0,0.25,0.1,0.05,0.01}){int z = (int)Math.round(m/i);System.out.println(z);m-=z*i;}}}

```

Both use same algorithm as jacoblaw's.
> 1 votes

# Answer
# PHP, 96 bytes

```
for(;$i<11;)$argn-=$c*$r[]=$argn/($c=[100,50,20,10,5,2,1,.25,.10,.05,.01][+$i++])^0;print_r($r);

```

Try it online!
> 1 votes

# Answer
# Python 2, 73 bytes

```
x=input()+1e-5
for c in 100,50,20,10,5,2,1,.25,.1,.05,.01:print x//c;x%=c

```

Try it online!

A greedy strategy works for these values. Going through currencies largest to smallest, we remove the greatest whole number of the currency, leaving the modulo as the remainder. This repeated divmod is effectively mixed based conversion.

The `+1e-5` is to ward off floating point errors where `$0.09999999999999998` is left but that's less than 1 cent.

I thought about compressing the list of values but didn't think of a good approach. There's not a uniform pattern for the values.
> 1 votes

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


title: Catch those sheep!

text:
# Question
Title: Catch those sheep!
You're a farmer and your flock of sheep has escaped! Oh no!

Round up those sheep by building fences to contain them. As a farmer on a budget you want to use the least amount of fence possible. Luckily for you though, they aren't the smartest sheep in the world and don't bother moving after having escaped.

# Task

Given a list of coordinates, output the least amount of fence segments necessary to contain the sheep.

# Rules

* Sheep are contained if they cannot wander off (no holes in the fence).
* You do not have to contain all the sheep in one block of fence - there could be multiple fenced-off areas independent from each other.
* Fence segments are oriented in cardinal directions.
* Each coordinate tuple represents a single sheep.
* Input must be positive integer pairs, `x>0` & `y>0`, but can be formatted appropriately for your language.
    + i.e.: `{{1,1},{2,1},{3,7}, .. }` or `[1,2],[2,1],[3,7], ..`
* Empty spaces inside a fenced-off area are okay.
* You cannot assume coordinates are input in any specific order.

For example, a single sheep requires `4` fence segments to be fully contained.

# Test cases

```
[1,1]
4

[1,1],[1,2],[2,2]
8

[2,1],[3,1],[2,3],[1,1],[1,3],[3,2],[1,2],[3,3]
12

[1,1],[1,2],[2,2],[3,7],[4,9],[4,10],[4,11],[5,10]
22

[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]
36

[1,1],[2,2],[3,3],[4,4],[6,6],[7,7],[8,8],[9,9]
32

[2,1],[8,3],[8,4]
10

```

**Notes**

* You can assume input coordinates are valid.
* Your algorithm should theoretically work for any reasonably large integer coordinate (up to your language's maximum supported value).
* Either full program or function answers are okay.

This is , so shortest answer in bytes wins!

# Answer
> 5 votes
## JavaScript (ES6), ~~251~~ ~~244~~ 275 bytes

```
a=>Math.min(...(P=(a,r=[[a]],c=a[0])=>(a[1]&&P(a.slice(1)).map(l=>(r.push([[c],...l]),l.map((_,i)=>r.push([[c,...l[i]],...((b=[...l]).splice(i,1),b)])))),r))(a).map(L=>L.reduce((p,l)=>l.map(([h,v])=>(x=h<x?h:x,X=h<X?X:h,y=v<y?v:y,Y=v<Y?Y:v),x=y=1/0,X=Y=0)&&p+X-x+Y-y+2,0)))*2

```

### How?

We use the recursive function ***P()*** to create a list of all possible partitions of the input list. This function is currently sub-optimal, in that it's returning some duplicated partitions -- which does not however alter the final result.

For each partition, we compute the number of fences required to surround all sheep in each group with a rectangle. The sum of these fences gives the score of the partition. We eventually return the lowest score.

### Test cases

```
let f =

a=>Math.min(...(P=(a,r=[[a]],c=a[0])=>(a[1]&&P(a.slice(1)).map(l=>(r.push([[c],...l]),l.map((_,i)=>r.push([[c,...l[i]],...((b=[...l]).splice(i,1),b)])))),r))(a).map(L=>L.reduce((p,l)=>l.map(([h,v])=>(x=h<x?h:x,X=h<X?X:h,y=v<y?v:y,Y=v<Y?Y:v),x=y=1/0,X=Y=0)&&p+X-x+Y-y+2,0)))*2

console.log(f([[1,1]]))
console.log(f([[1,1],[1,2],[2,2]]))
console.log(f([[2,1],[3,1],[2,3],[1,1],[1,3],[3,2],[1,2],[3,3]]))
console.log(f([[1,1],[1,2],[2,2],[3,7],[4,9],[4,10],[4,11],[5,10]]))
console.log(f([[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]]))
console.log(f([[1,1],[2,2],[3,3],[4,4],[6,6],[7,7],[8,8],[9,9]]))
console.log(f([[2,1],[8,3],[8,4]]))
```

# Answer
> 2 votes
# , ~~62 58 57~~ 55 bytes

```
{+//2*1+{(|/x)-&/x}'(x@?(&|/2>(|/'{x|-x}x-\:)')')/,:'x}

```

Try it online!

---
Tags: code-golf
---


title: Do you like Taekwondo?

text:
# Question
Title: Do you like Taekwondo?
Choi Hong Hi died on the 15th June 2002 at the honorable age of 83. He founded Taekwondo.

15 years after his death, I would like to be a Taekwondo master. This is my time to shine !

# Task

Given a string you should output a *Taekwondo* version.

# Rules

* You will receive a non-empty string/sentence by any valid input
* You must replace each titles (case insensitive) by the revised romanization equivalent.
* You must add `, *side kick*` at the end of the sentence because I like to do side kicks.
* You must output this changed sentence as a string.
* This is you should aim to minimize the byte count of your answer

# Examples

```
"I am a Student and I do Taekwondo twice a week"
  => "I am a Geup and I do Taekwondo twice a week, *side kick*"

"I am a Teacher willing to be a President"
  => "I am a Gyosa nim willing to be a Gwanjang nim, *side kick*"

```

# List of titles

```
English             =>  Revised Romanization
============================================
President           =>  Gwanjang nim
Founder             =>  Gwanjang nim
Master instructor   =>  Sabeom nim
Teacher             =>  Gyosa nim
Black Belt          =>  Dan
Student             =>  Geup
Color Belt          =>  Geup
Master level        =>  Godanja

```

# Answer
> 2 votes
# Retina, 154 bytes

```
i(`president|founder
Gwanjang_
master instructor
Sabeom_
teacher
Gyosa_
black belt
Dan
student|color belt
Geup
master level
Godanja
_
 nim
$
, *side kick*

```

Try it online!

# Answer
> 3 votes
# PHP, 241 bytes

```
<?=preg_replace(["#\b(President|Founder)\b#i","#\bMaster instructor\b#i","#\bTeacher\b#i","#\bBlack Belt\b#i","#\b(Studen|Color Bel)t\b#i","#\bMaster level\b#i"],[Gwanjang.$n=" nim",Sabeom.$n,Gyosa.$n,Dan,Geup,Godanja],"$argn, *side-kick*");

```

Try it online!

# Answer
> 2 votes
# C#, 262 bytes

```
s=>{for(int i=0;i<8;)s=s.ToUpper().Replace("PRESIDENT|FOUNDER|MASTER INSTRUCTOR|TEACHER|BLACK BELT|MASTER LEVEL|STUDENT|COLOR BELT".Split('|')[i],(i<2?"GWANJANG":i>3?"GEUP":"SABEOM|GYOSA|DAN|GODANJA".Split('|')[i-2])+(i++<4?" NIM":""));return s+", *SIDE KICK*";}

```

Full/Formatted version:

```
class Program
{
    static void Main(string[] args)
    {
        System.Func<string, string> f = s =>
        {
            for (int i = 0; i < 8;)
                s = s.ToUpper().Replace("PRESIDENT|FOUNDER|MASTER INSTRUCTOR|TEACHER|BLACK BELT|MASTER LEVEL|STUDENT|COLOR BELT".Split('|')[i],
                                        (i < 2 ? "GWANJANG"
                                               : i > 3 ? "GEUP"
                                                       : "SABEOM|GYOSA|DAN|GODANJA".Split('|')[i-2])
                                        + (i++ < 4 ? " NIM" : ""));

            return s + ", *SIDE KICK*";
        };

        System.Console.WriteLine(f("I am a Student and I do Taekwondo twice a week"));
        System.Console.WriteLine(f("I am a Teacher willing to be a President"));

        System.Console.ReadLine();
    }
}

```

# Answer
> 1 votes
# Retina, 163 bytes

```
i`President|Founder
Gwanjang¶
i`Master instructor
Sabeom¶
i`Teacher
Gyosa¶
i`Black Belt
Dan
i`Student|Color Belt
Geup
i`Master level
Godanja
¶
 nim
$
, *side kick*

```

Try it online!

# Answer
> 0 votes
# tcl, 212

```
puts "[string map -nocase {President Gwanjang\ nim Founder Gwanjang\ nim Master\ instructor Sabeom\ nim Teacher Gyosa\ nim Black\ Belt Dan Student Geup Color\ Belt Geup Master\ level Godanja} $argv], *side kick*"

```

## demo

# Answer
> 0 votes
# Python 3, 281 bytes

```
import re
x=input();a="Gwanjang";b=" nim";c="Geup";d="Master";e=" Belt"
for i in range(8):x=re.sub("(?i)"+["President","Founder",d+" instructor","Teacher","Black"+e,"Student","Color"+e,d+" level"][i],[a+b,a+b,"Sabeom"+b,"Gyosa"+b,"Dan",c,c,"Godanja"][i],x)
print(x+", *side kick*")

```

Try it online!

# Answer
> 0 votes
# JavaScript (ES6), 251 bytes

```
a=>a.replace(RegExp(b='president|founder|master instructor|teacher|black belt|student|color belt|master level','gi'),c=>((d='Gwanjang nim|')+d+'Sabeom nim|Gyosa nim|Dan|Geup|Geup|Godanja').split`|`[b.split`|`.indexOf(c.toLowerCase())])+', *side kick*'

```

Try it online!

This is not as compact as it could be since JavaScript is so verbose, but it's a great question. I recognized most of these terms as I am a 2nd Dan Black Belt in Taekwondo.

**Explanaion**

```
a=>
  a.replace(                                    // Replace on input string
    RegExp(                                     // Regex matching English phrases
      b='president|founder|master instructor|teacher|black belt|student|color belt|master level',
      'gi'                                      // Match all, case insensitive
    ),
    c=>
      ((d='Gwanjang nim|')+d+                   // Duplicate string portion
        'Sabeom nim|Gyosa nim|Dan|Geup|Geup|Godanja') // Add remaining phrases
      .split`|`                                 // Split into array by pipe
        [b.split`|`.indexOf(c.toLowerCase())])  // Access Korean phrase by corresponding index of matched English phrase
      +', *side kick*'                          // I like to do side kicks

```

# Answer
> 0 votes
# JavaScript (ES6), 233 bytes

```
s=>(btoa`>·¬×§·mÁ©ãjx4)µ§uêö§©àÒx¦ÔÆ¬µêô{-®ç-¢½i·¨IâTÞiÈ^¯a²¢Æ´)µV@^Ýj}R¶ç^Ýzêu
h¯@^Ýzêu1«-z½%z÷¥ØjjxÚ`.split(0).join` `.split`1`.map(d=>([a,b]=d.split(/2+/),s=s.replace(RegExp(a,'gi'),b))),s+', *side kick*"')

```

```
f=
s=>(btoa`>·¬×§·mÁ©ãjx4)µ§uêö§©àÒx¦ÔÆ¬µêô{-®ç-¢½i·¨IâTÞiÈ^¯a²¢Æ´)µV@^Ýj}R¶ç^Ýzêu
h¯@^Ýzêu1«-z½%z÷¥ØjjxÚ`.split(0).join` `.split`1`.map(d=>([a,b]=d.split(/2+/),s=s.replace(RegExp(a,'gi'),b))),s+', *side kick*"')

console.log(f('I am a Teacher willing to be a President'))
```

---

# JavaScript (ES6), 243 bytes

```
s=>(`President${A=':Gwanjang nim|'}Founder${A}Master instructor:Sabeom nim|Teacher:Gyosa nim|Black Belt:Dan|Student:Geup|Color Belt:Geup|Master level:Godanja`.split`|`.map(r=>([a,b]=r.split`:`,s=s.replace(RegExp(a,'gi'),b))),s+', *side kick*')

```

```
f=
s=>(`President${A=':Gwanjang nim|'}Founder${A}Master instructor:Sabeom nim|Teacher:Gyosa nim|Black Belt:Dan|Student:Geup|Color Belt:Geup|Master level:Godanja`.split`|`.map(r=>([a,b]=r.split`:`,s=s.replace(RegExp(a,'gi'),b))),s+', *side kick*')

console.log(f('I am a Teacher willing to be a President'))
```

---
Tags: code-golf, string
---


title: Decode my I2C Stream!

text:
# Question
Title: Decode my I2C Stream!
From the sandbox!

I2c or TWI, is a 2 way stream that uses 2 signal lines: `SDA` and `SCK`. This is used in sensors to communicate between a master and a slave. So, how does this work? Well, here's the boilerplate:

## Input:

1 I2c command represented by 2 strings where `-` is a high signal, and `_` is low. `SDA` is always the first string.

## Output:

The debug info for that command, including weather
it's a `READ` or `WRITE`,
which address it's to (in Hex), and
what memory the signal's addressing(in Hex).
if the transmission is invalid, print "Invalid"

## How does I2c work, then?

Image from Sparkfun!
An i2c request has 2 9-bit parts. the address and the payload. The address comes first.

A bit is only `READ` when the clock signal goes from `LOW` to `HIGH`. Going from `HIGH` to `LOW` is not a valid reading event.

The address is 7 bits, which come after both `SDA` and `SCL` are `LOW`. This is sent by the master.

After the 7th bit, the next is sent by the master, which is the `READ` Bit. If this bit is `HIGH`, then it's a `READ` operation, if the bit is `LOW`, then it's a `WRITE` operation.

After the 8 bits, the slave responds with an ACK bit, if the ACK bit is `HIGH`, then the entire transmission is invalid.

Then, the second transmission is sent.

The first 8 bits represent the data address that the master is `READ`ing or `WRITE`ing.

and the final bit is the 2nd ACK bit. If this bit is `HIGH`, then the entire transmission is invalid.

## Examples:

```
Raw IN: ["--____--__----__----__----__--__--__","___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"]
SDA: --____--__----__--__--__----__--__--__
SCK: ___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
Result: 0 0 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 0
Parse:  addr[22] op:[R] data:[181] success[yes]
out: address:0x16 op:Read data:0xB5

Raw IN: ["--____--__----__------__----__--__--__","___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"]
SDA: --____--__----__------__----__--__--__
SCK: ___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
Result: 0 0 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 0
Parse:  addr[22] op:[R] data:[181] success[No]
out: invalid
Note: (the ACK bit flipped high);

Raw IN: ["--_-_--__--_-__--_-_-__-_-_-_--__--__-","___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"]
SDA: --_-_--__--_-__--___-__-_-_-_--__--__-
SCK: ___-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
Result: 0 0 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 0
Parse:  addr[22] op:[R] data:[181] success[yes]
out: address:0x16 op:Read data:0xB5
Note: (the bit before the change is read.);

Raw IN: ["--_____--___-----___--___--___-----__---____--____","___--_-_--_--_-_--_-_--_-_--_-_--_-_--_-___-_--__-"]
SDA: --_____--___-----___--___--___-----__---____--____
SCK: ___--_-_--_--_-_--_-_--_-_--_-_--_-_--_-___-_--__-
Result: 0  0 1  0  1 1  0 1  0 1  0 1  1 0  1   0 1   0
Parse:  addr[22] op:[R] data:[181] success[yes]
out: address:0x16 op:Read data:0xB5
Note: (Clock signals Don't have to be perfect.);

Raw IN: ["--_____--___-----___--___--___-----__---____--____","___---_-_--_-___-_--__-"]
SDA: --_____--___-----___--___--___-----__---____--____
SCK: ___---_-_--_-___-_--__-
Result: 0   0 1  0   1 0   1
Parse:  Invalid
out: invalid
Note: (They do however, have to match the length of the data dignal.);

```

## Extra rules:

The `0x` prefix must be appended to all hex values in the output, as a formality. The input is strictly `-` for `HIGH` and `_` for `LOW`, and will always be 2 separate strings with a separator character. If both `SDA` and `SCL` change at the same time, then the previous bit is read.

This is a code golf, so whoever creates a running program in the least number of bytes wins! Good luck

# Answer
> 2 votes
# GNU sed, ~~427~~ ~~378~~ 364 + 1 = ~~428~~ ~~379~~ 365 bytes

+1 byte for `-r` flag. Takes colon-separated input. Output format is e.g. `a0x16oRd0xB5`, where `a` precedes the address, `o` precedes the operation (`R` or `W`), and `d` precedes the data.

Why do I do this to myself?

```
s/^/:/
:Q
s/:.+:$|::./E/
s/:(.).(.*):_-/\1:x\2:x/
s/:./:/g
tQ
s/(.{7})(.)(.)(.*)(.):/#\3\1%\2#\5\4:/
/#-|E/{z;iinvalid
q}
s/#./#/g
:R
s/[:%]/!u0;%0123456789ABCDEF,/
:A
s/((-)|_)!/!\2/
s/!-(u+)(.+);/!\1\2;\1/
:
/u%/!bZ
s/F;/;0/
t
s/(.);(.*%.*\1)(.)/\3\2\3/
s/u;/u1/
s/u(u*)%/;\1%/
b
:Z
s/!(u+)/!\1\1/
/#!/!bA
s/#!u+(.+);.+,/\1/
/:/bR
s/(..)(.)/a0x\1o\2d0x/
y/-_/RW/

```

Try it online!

## Explanation

The code works in two phases. In phase 1 we turn the two signals into a single binary string. This is the easy part.

```
# Prepend a `:`
s/^/:/
:Q
  # Check for length mismatch (one string exhausted before the other)
  s/:.+:$|::./E/

  # If the first two characters of SCK are `_-`, record first character of SDA
  # and discard second; replace each pair with `x` so we can unconditionally...
  s/:(.).(.*):_-/\1:x\2:x/

  # ...consume a character from each signal
  s/:./:/g

  # If we did a substitution, branch to :Q
  tQ

```

If this was our input:

> ```
> --_____--___-----___--___--___-----__---____--____:___--_-_--_--_-_--_-_--_-_--_-_--_-_--_-___-_--__-
>
> ```

...we now have this:

> ```
> __-_--_-_-_--_-_-_:
>
> ```

Before phase 2, we reformat this to make it a little easier to work with:

```
# Reformat `.......ma........b:` to `#a.......%m#b........:`
s/(.{7})(.)(.)(.*)(.):/#\3\1%\2#\5\4:/

# Check if ACK high or length mismatch; if either, print error and quit
/#-|E/{z;iinvalid
q}

# Delete ACK bits
s/#./#/g

```

Now we have:

> ```
> #__-_--_%-#-_--_-_-:
>
> ```

In phase 2, we convert each run of `_` and `-` (0 and 1) to a hexadecimal number. Because sed doesn't do math, this is almost half of the code. It actually takes each binary digit, converts it to unary, and then increments the hexadecimal number once for each unary digit.

```
:R
# Initialize: u = magnitude (unary 1); 0 = running sum (decimal); lookup table
s/[:%]/!u0;%0123456789ABCDEF,/

:A
  # Take the least-significant bit; if it's 0 drop it
  s/((-)|_)!/!\2/

  # If 1 (-), remove it and copy current magnitude (`u+`) after `;`
  s/!-(u+)(.+);/!\1\2;\1/

  # Increment number for each `u` after `;`
  # e.g. 12;uu -> 13uu -> 13;u -> 14u -> 14;
  :
    # No more `u`s, branch to :Z
    /u%/!bZ

    # Carry: 1F;u -> 1;0u -> 20u -> 20;
    s/F;/;0/
    t

    s/(.);(.*%.*\1)(.)/\3\2\3/
    s/u;/u1/

    # Drop a `u`; branch to `:`
    s/u(u*)%/;\1%/
    b

  :Z
    # Double magnitude: !uu3 -> !uuuu3
    s/!(u+)/!\1\1/
    # If there are binary digits left, branch to :A
    /#!/!bA

# Clean up
s/#!u+(.+);.+,/\1/

# Branch to :R for the second number
/:/bR

# Format output
s/(..)(.)/a0x\1o\2d0x/
y/-_/RW/

```

Before formatting, we have:

> ```
> 16-B5
>
> ```

All that remains is to add a prefix to each hexadecimal number change the operation (`-` or `_`) to read (`R`) or write (`W`), giving us:

> ```
> a0x16oRd0xB5
>
> ```

---
Tags: code-golf, string, data-structures, encoding
---


title: Am I a Special N-bonacci Number?

text:
# Question
Title: Am I a Special N-bonacci Number?
The N-bonacci sequence, originally invented by @DJMcMayhem in this question, is a sequence generated by starting with the integers 0 and 1, and then adding the previous N numbers to generate the next number. The special N-bonacci sequence is an N-bonacci sequence beginning with a pair of numbers other than 0 and 1, which will be named X and Y. If N is greater than the number of terms already in the sequence, simply add all available terms.

So for example the normal fibonacci sequence has an N of 2 (takes the previous two items), and an X and Y of 0 and 1, or 1 and 1, depending on who you ask.

## Your Task:

You are to write a program or function that checks whether an inputted integer (A) is part of the special N-bonacci sequence generated by the next three integers (using the second input as N, and the third and fourth as X and Y). Ensure that you handle the special case of N=1.

## Input:

Four non-negative integers, A, N, X, and Y.

## Output:

A truthy/falsy value that indicates whether A is part of the N-bonacci sequence generated by the N, X, and Y inputs.

## Test Cases:

```
Input:    Output:
13,2,0,1->truthy
12,3,1,4->falsy
4,5,0,1-->truthy
8,1,8,9-->truthy
9,1,8,9-->truthy

12,5,0,1->falsy  [0,1]>[0,1,1]>[0,1,1,2]>[0,1,1,2,4]>[0,1,1,2,4,8]>[0,1,1,2,4,8,16]>etc.

```

## Scoring:

This is , so the lowest score in bytes wins.

# Answer
# Jelly, 12 bytes

```
ḣ⁴S;µṀ<⁵µ¿⁵e

```

A full program taking `[X,Y]`, `N`, `A`.

**Try it online!**

### How?

```
ḣ⁴S;µṀ<⁵µ¿⁵e - Main link (monadic): [X,Y]
    µ   µ¿   - while:
     Ṁ       -   maximum value of the list
       ⁵     -   5th command line argument (3rd input) = A
      <      -   less than?
             - ...do:
 ⁴           -   4th command line argument (2nd input) = N
ḣ            -   head (get the first N (or less) items from the list)
  S          -   sum
   ;         -   concatenate (add the result to the front of the list)
          ⁵  - 5th command line argument (3rd input) = A
           e - exists in the resulting list?

```
> 5 votes

# Answer
# 05AB1E, 18 bytes

```
[DR²£O©‚˜³®>‹#]³QZ

```

Try it online!

---

Uses: `[X,Y], N, A`

---

I feel like some unintended functionality made that harder than it needed to be.

There's no greater-than-or-equal-to, never noticed that before.

And  didn't work, and required a `]`, for +1 bytes `#]³`.
> 5 votes

# Answer
# Python 2, ~~59~~ 56 bytes

```
a,n,l=input()
while l[0]<a:l=[sum(l[:n])]+l
print a in l

```

Try it online!

Takes input as `A,N,[X,Y]`
> 4 votes

# Answer
# Perl 6, 47 bytes

```
->\A,\N,\X,\Y{A∈(X,Y,{[+] @_.tail(N)}...*>A)}

```

test it

## Expanded:

```
->
  \A,
  \N,
  \X, \Y
{
    A          # is ｢A｣

  ∈            # an element of

    (          # this Sequence

      X, Y,        # seed values of sequence

      {            # generate the rest of the Seq using this code block

        [+]        # reduce by addition

          @_       # of all previously generated values
          .tail(N) # only use the last ｢N｣ of them
      }

      ...          # keep generating values until

      * > A        # it is greater than ｢A｣

    )
}

```
> 3 votes

# Answer
# Python 2, 50 bytes

```
a,n,l=input()
while[a]>l:l=[sum(l[:n])]+l
a in l>x

```

Takes input as `A,N,[Y,X]`. Outputs via exit code.

Try it online!
> 2 votes

# Answer
# , ~~69~~ 60 bytes

```
function(a,n,l){while(l<a)l=c(sum(l[1:n],na.rm=T),l)
a%in%l}

```

Try it online!

Returns an anonymous function, taking `a,n` and a vector `l=c(y,x)`. Constructs the N-bonacci sequence backwards (i.e., smaller index is further in the sequence), since `while(l<a)` only checks the first element of `l`.
> 1 votes

# Answer
# Common Lisp, 164 bytes

```
(defun f(a n x y &aux(l(list y x)))(if(= n 1)(or(= a x)(= a y))(loop(if(<= a(car l))(return(member a l))(setf l(cons(reduce'+ l)(if(<(length l)n)l(butlast l))))))))

```

This function returns `NIL` for false, non-NIL for true (according to the definition of *generalized boolean* of Common Lisp).

```
(defun f(a n x y &aux (l (list y x)))    ; initialize a list l for the N values
  (if (= n 1)                            ; special case for N = 1
      (or (= a x) (= a y))               ;    true only if A = X or A = Y
      (loop
        (if (<= a (car l))               ; when the last number generated is greater than A
            (return (member a l))        ; return true if A is in the list
            (setf l (cons (reduce '+ l)  ; otherwise compute the sum of l
                          (if (< (length l) n)   ; and push it to l (truncating the list at
                              l                  ; end if it has already size = N)
                              (butlast l))))))))

```
> 1 votes

# Answer
# k, 29 bytes

```
{x=*(*x>){(x=#y)_y,+/y}[y]/z}

```

Try it online! `1` is truthy, `0` is falsey. Input is `[A;N;X,Y]`.
> 0 votes

# Answer
# Mathematica, 94 bytes

```
(s={#3,#4};t=1;While[t<#2-1,s~AppendTo~Tr@s;t++];!LinearRecurrence[1~Table~#2,s,#^2]~FreeQ~#)&

```

input format

> \[A,N,X,Y\]
> 0 votes

# Answer
# PHP\>=7.1, 103 Bytes

```
for([,$n,$d,$s,$e]=$argv,$f=[$s,$e];$x<$n;)$x=$f[]=array_sum(array_slice($f,-$d));echo+in_array($n,$f);

```

Testcases
> 0 votes

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


title: Vacancy or no vacancy?

text:
# Question
Title: Vacancy or no vacancy?
We've all seen the signs on motels telling us if there's a vacancy or not:

Typically, these will permanently have the letters of **VACANCY** lit up, and have the letters of **NO** lit up if there isn't any room in the motel.

# The challenge

The average motel in the U.S. has 200 rooms.

You will write a program/function that takes an integer **T** (for taken rooms) as its only input.
Your program will then display the words `NO VACANCY`. The letters of `VACANCY` will be printed in red.
If **T** ≥ 200, the letters of `NO` will also be printed in red.

For example, assuming `a.out` is your program and "input" = command line argument:
(I typo'd and my system ignores case.)

# The rules

* Your program/function must **display** (or, if lambda, return) the exact string `NO VACANCY`, including case.
* Your program/function may only set the text foreground color to red and not the background.
* If you wish, you may use ANSI escape codes to print the red color - `\x1b[31m` will work.
* Your program/function may not change the text color of your shell after it finishes.
* Your program/function must terminate normally.
* Your program/function must print only to standard output.
* Your program/function must use your shell/terminal/IDE's default background color. (If you choose to have graphical output you may choose whatever color you like, except red.)
* If **T** ≤ 200, the letters of `NO` must be printed in your shell/terminal/IDE's default foreground color. (If you choose to have graphical output, once again you may choose whatever color you like)
* If for some reason your shell/terminal/IDE's default foreground/background color is red, you must print with a black background and a default white foreground.
* If you choose to use graphical output, red may only be used when specified in the program (e.g. your background color or default text color may not be red).

# The winner

As usual with , the shortest program wins! Brownie points for graphical output.
I'll accept the shortest answer in a week. Happy golfing!

# Leaderboard

```
var QUESTION_ID=123146,OVERRIDE_USER=61563;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
> 8 votes
# Jelly, ~~29~~ 26 bytes

```
<200o-“NO“ɓ31m”m“=ȤŻ»Œu“ɓm

```

This uses `<CSI>` (**0x9b**), which is shorter than `<ESC>[` (**0x1b 0x5b**).

It resets the foreground color with `<CSI>m` instead of `<CSI>0m`, as the **0** is implicit.

### Verification

Note that your terminal emulator (e.g., Konsole) must be set to ISO 8859-1 or similar.

### How it works

```
<200o-“NO“ɓ31m”m“=ȤŻ»Œu“ɓm  Main link. Argument: n (integer)

<200                        Compare with 200, yielding 1 if true, 0 if not.
    o-                      Logical OR -1; map 0 to -1 (and 1 to 1).
      “NO“ɓ31m”             Yield ["NO", "\x9b31m"].
               m            Take the list "modulo" 1 or -1, keeping it as is for 1,
                            reversing it for -1.
                “=ȤŻ»       Implicitly print the previous result and yield the
                            string " vacancy". This is achieved by indexing into
                            Jelly's in-built dictionary.
                     Œu     Convert to uppercase.
                       “ɓm  Implicitly print the previous result and yield the
                            string "\x9bm", which is printed on exit.

```

# Answer
> 11 votes
# Javascript (ES6), 60 bytes

(Open your browser's console while running the snippet to see the colored result.)

```
f=
n=>console.log((n>199?'%cNO':'NO%c')+' VACANCY','color:red')
```

```
<input oninput=f(this.value)>
```

# Answer
> 8 votes
# Ruby (\*nix style terminal), ~~54~~ ~~48~~ ~~45~~ ~~44~~ 43 bytes

*1 byte saved thanks to Value Ink*

*stands in for a literal esc byte (ASCII 27)*

```
->x{"#{x>199?"␛[31m":p}NO␛[31m VACANCY␛[m"}

```

A port of my python answer, that is ~~a byte~~ several bytes shorter. I'm new to ruby golf but eager to learn so feedback is appreciated.

# Answer
> 6 votes
# Python 3 (\*nix style terminal), ~~55~~ 54 bytes

```
lambda x:"\033[31m"*(x-199)+"NO\033[31m VACANCY\033[m"

```

---

This uses ANSI escape codes. `\033[31m` Makes the terminal red, if x is less than 200 we will start with one making `NO` red, otherwise we will have one after `NO` making it red anyway. When we are done `\033[m` clears the color from the terminal.

# Answer
> 6 votes
# HTML, ~~72~~ 71 bytes

```
<input min=200 type=number><x>NO <y>VACANCY<style>:valid+x,y{color:red}
```

# Answer
> 4 votes
# Java (OpenJDK 9), ~~102~~ ~~89~~ ~~88~~ 51 bytes

Yes, Java. :P This only works on \*nix terminals.

```
x->(x>199?"\033[31m":"")+"NO\033[31m VACANCY\033[m"

```

# Answer
> 3 votes
# Go, ~~82~~ 81 bytes

This only works on \*nix terminals. ~~I wonder how easy it would be to port this to Java...~~ Done.

```
func f(x int)string{v:="NO\033[31m VACANCY\033[m";if(x>199){v=v[2:7]+v};return v}

```

# Answer
> 3 votes
# Excel VBA, ~~76~~ ~~73~~ 72 Bytes

Anonymous VBE immediate window function that takes input of expected type `Integer` from cell `[A1]` and outputs a (NO) VACANCY sign across cells `A2:B2`

```
[A2]="NO":[B2]="VACANCY":Range([If(A1>199,"A2:B2","B2")]).Font.Color=255

```

-3 Bytes for changing `rgbRed` to `255`

# Answer
> 3 votes
## BASH / MKSH, ~~48 47~~ 46 bytes

```
(($1>199))&&a=^[[31m;echo $a^MNO ^[[31mVACANCY^[[m

```

Note: ^\[ means 1 byte wide ESC character: 0x1b or decimal 27.

^M means 1 byte wide CR character: 0x0d, decimal 13.

# Answer
> 3 votes
# bash, 41 bytes

```
echo ␛[$[($1>199)*31]mNO ␛[31mVACANCY␛[0m

```

where ␛ represents a literal ESC character (ASCII \033).

# Answer
> 2 votes
# Bash script, 60 bytes

```
c="\e[1;31m";((199<$1))&&printf $c;printf "NO$c VACANCY\e[m"

```

# Answer
> 2 votes
# Haskell, ~~54~~ 53 bytes

EDIT:

* -1 byte: From @Dennis's Jelly answer, the `0` argument in the final escape sequence can be dropped.

`f` takes an integer and returns a string. Use as `putStrLn$f 200`.

```
f t|t>199="\27[31m"++f 0|0<1="NO \27[31mVACANCY\27[m"

```

Try it online! Alas, the colors don't show up in TIO, but you can see that the ANSI codes are correctly placed.

Golfing seemed to peter out pretty quickly with this one - not even naming the escape strings seems to save anything. The cleverest bit is recursing with `f 0` to use the other branch as a substring. Three different attempts at using list comprehensions all turned up one byte longer. Perhaps the nicest I found:

```
f t=foldr drop"\27[31mNO \27[31mVACANCY\27[m"[5|t<200]

```

# Answer
> 2 votes
# HTML + CSS + JavaScript (ES6), ~~74~~ 59 bytes

Takes input as function argument of `f`, like `f(100)`.

### HTML

```
<x id=n>NO <j id=r>VACANCY

```

### CSS

```
#r{color:red

```

### JavaScript (ES6)

```
f=a=>a>199?n.id="r":0

```

## Test Snippet

```
f=a=>a>199?n.id="r":0

f(prompt("Enter a number"))
```

```
#r{color:red
```

```
<x id=n>NO <j id=r>VACANCY
```

# Answer
> 1 votes
# BASH, 100 bytes

```
if(($1<200));then
echo -n NO
else
echo -ne '\033[31mNO\033[0m'
fi
echo -e '\033[31m VACANCY\033[0m'

```

This can be probably be golfed, but I'm low on time. I'll come back to this later.

-5 bytes thanks to @R. Kap

# Answer
> 1 votes
# C (\*nix style terminal), ~~50~~ ~~55~~ ~~52~~ 51 bytes

-1 thanks to Wheat Wizard

```
f(t){printf("␛[%dmNO ␛[31mVACANCY␛[m",t>199?31:0);}

```

␛ stands for the literal ESC byte, ASCII 27.

Call with `f(200)`, 200 being the number. Prints `NO VACANCY` colored to the spec.

# Answer
> 1 votes
## Mathematica, 67 bytes

```
Print[s=Style[#,FontColor->Red]&;If[#>200,s,#&]@"NO",s@" VACANCY"]&

```

or (60 bytes, but may be considered cheating)
This is actually `Times["NO","VACANCY"]`, but appear to be correct.

```
(s=Style[#,FontColor->Red]&;If[#>200,s,#&]@"NO")s@"VACANCY"&

```

# Answer
> 1 votes
# Mathematica, 47 bytes

```
(If[#>199,Style[NO,Red],NO]Style[VACANCY,Red])&

```

# Answer
> 1 votes
# PHP, 41 bytes

```
␛[<?=$argn<200?31:''?>mNO␛[31m VACANCY␛[m

```

␛ represents the Escape character.

# Answer
> 0 votes
# shortC, 48 bytes

```
f(t){R"␛[%dmNO ␛[31mVACANCY␛[m",t>199?31:0

```

Where ␛ stands for ASCII 27, the ESCAPE byte.

# Answer
> 0 votes
# GW-BASIC, ~~78~~ ~~74~~ 65 bytes

-12 thanks to Orjan Johansen

```
1INPUT X:IF X>199THEN COLOR 4
2?"NO ";:COLOR 4:?"VACANCY":COLOR 7

```

Prompts user for an integer. Output:

# Answer
> 0 votes
# Tcl/Tk, 96 bytes

```
grid [label .n -text NO -fg [expr \$argv>199?"red":"tan"]]
grid [label .v -text VACANCY -fg red]

```

---
Tags: code-golf, color
---


# Question
Title: Calculate the last digits of Graham's Number
Graham's number ends in a 7. It is a massive number, in theory requiring more information to store than the size of the universe itself. However it is possible to calculate the last few digits of Graham's number.

The last few digits are:

```
02425950695064738395657479136519351798334535362521
43003540126026771622672160419810652263169355188780
38814483140652526168785095552646051071172000997092
91249544378887496062882911725063001303622934916080
25459461494578871427832350829242102091825896753560
43086993801689249889268099510169055919951195027887
17830837018340236474548882222161573228010132974509
27344594504343300901096928025352751833289884461508
94042482650181938515625357963996189939679054966380
03222348723967018485186439059104575627262464195387

```

Your program may not contain these (or similar numbers), but must calculate them. It must calculate 200 digits or more.

Output to stdout. Running time of a maximum of 2 minutes on decent hardware. Shortest program wins.

# Answer
> 9 votes
## dc - 21 chars

```
[3z202>xO200^|]dsxxrp

```

This takes about a minute on my computer, and would take lots longer for values larger than 200. It doesn't output leading zeroes.

Here's a slightly longer but faster version (26 chars):

```
[3rAz^|dz205>x]dsxxAz6-^%p
3[3rAz^|dz202>x]dsxxAz3-^%p # or an extra character for a few less iterations

```

# Answer
> 4 votes
## Haskell, 99

Performance not stellar, but it manages to compute 500 digits in a minute on my decade-old hardware.

```
f a b|b==0=1|odd b=mod(a*f a(b-1))m|0<1=f(mod(a^2)m)$div b 2
main=print$iterate(f 3)3!!500
m=10^500

```

(btw, I'd love to hear about its performance on more modern hardware)

# Answer
> 3 votes
# Python - 62 59 55 chars

```
x=3
for i in range(500):x=pow(3,x,10**500)
print"0%d"%x

```

Takes around 12 seconds on my PC.

```
sh-3.1$ time python cg_graham.py
02425950695064738395657479136519351798334535362521430035401260267716226721604198
10652263169355188780388144831406525261687850955526460510711720009970929124954437
88874960628829117250630013036229349160802545946149457887142783235082924210209182
58967535604308699380168924988926809951016905591995119502788717830837018340236474
54888222216157322801013297450927344594504343300901096928025352751833289884461508
94042482650181938515625357963996189939679054966380032223487239670184851864390591
04575627262464195387

real    0m11.807s
user    0m0.000s
sys     0m0.015s
sh-3.1$

```

# Answer
> 3 votes
# Python - 41 chars

499 digits

```
x=3;exec'x=pow(3,x,10**500);'*500;print x

```

500 digits

```
x=3;exec'x=pow(3,x,10**500);'*500;print'0'+`x`

```

# Answer
> 0 votes
# Axiom, 63 bytes

```
f()==(r:=3;d:=10^203;for i in 1..203 repeat r:=powmod(3,r,d);r)

```

ungolf and result

```
--This find the Graham's number follow the algo found in wiki
--http://en.wikipedia.org/wiki/Graham%27s_number
ff()==
   r:=3; d:=10^203
   for i in 1..203 repeat r:=powmod(3,r,d)
   r

(3) -> a:=f()::String
   (3)
  "8871783083701834023647454888222216157322801013297450927344594504343300901096
  92802535275183328988446150894042482650181938515625357963996189939679054966380
  03222348723967018485186439059104575627262464195387"
                                                             Type: String
(4) -> #a
   (4)  203
                                                    Type: PositiveInteger

```

#a=203 means the number len is \>200 it menas too that it not has some 0 first...

# Answer
> 0 votes
## Headsecks, 602 bytes

```
(h@HP0&Y+h8h (hx0RWc@4vYcx#@#PJ"B?[#CPx (h Lx$2(pl2YL;KD:T{9$2j<
 LSSh,ZT l2I<Pp,@4SX`,:xtc@T",($)<cKT\lbBAy44,dQl[yL"l+i,;9<*j0P
|)lD[+`\RBi!< LaD(LHPLyt{{@\iADRQdHTZQIT3[X`DB*`X$Cxh$*(T0$| ,[;
4:bit0DqAqi!lCYQ)<Ad(|1<$R4l+#tZrLPDatC[d*@0pDclJbh0|#S9<JRy!TP0
D+!|qiTXp<r$##Atj,B1ts;HLJ"Xp44I4cK4@|Q,4JI$|hp$Zyd+yl:y<s#\pD:9
4RDK,A!<X \cqLZ" h,kHp|qLRQIDh,+StZbL+{(|jqqL;9L"(xd"<s$8\:x,CY\
z0T[,(XdcxlbaD*D;+tDj\JIi4k[)LPDLBzP@DSc$jL $s4BjQ19|;!)|9t;TaQA
dLzit[0@l2!)I$,0P@$y<L4pLPLStQT"!a| $+8(DZ`00t ,RtX4C@$yQ11|KI\"
`|2<k3|R(Dyi<)LshTrzQ$sp D+DRbH|Q$CqT0D;AA\jdXd"ppdK3LzZl#\Bl`@t
k$*,11qTK+Xp|rqDZXp4{C!<Y4

```

Prints the last 200 digits.

Please remove the newlines before running.

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


# Question
Title: Find the missing integer (i) , The duplicated integer (j), the length or random integers (n). But only if "i" = "j", just tell me "Huh!?"
# The task

Your program will be given the following inputs: a number *n*, and an array of *n* positive integers. Your program only has to work when *n*=1000.

The program must do the following:

* If the input array is a permutation of the range \[1, 2, …, *n*\], output `Huh!?`
* Otherwise, return a three-element array \[*i*, *j*, *n*\], where *i* is a number from 1 to *n* inclusive that does not appear in the input array, and *j* is a number that appears more than once in the input array.

# Clarifications

* Because *n* will always have the same value, your program may get at it three different ways: hardcoding it as 1000, checking the length of the input array, or taking it from input.
* Per PPCG rules, you don't have to read an input at all if you don't need it to solve the question.
* The input will always be chosen so that there's a unique answer (in other words, the input array will contain no more than one duplicated element).

# Test case generator

The following test case generator, in the statistical programming language R, will generate an appropriate test case for this challenge. It takes the following inputs:

1. The value of *n*. In order to create an appropriate test case, this should be 1000.
2. The value of *i*.
3. The value of *j*.

Here's the generator itself:

```
#!/usr/bin/env Rscript
#Random_number_generator_1.R
getwd()

printf <- function(...) cat(sprintf(...))
print("Please set the range of random numbers from 1 to n \n")

this_range = scan(file = 'stdin', what = integer(), nmax = 1)

numbers = 1:this_range

#print("How many random numbers in this range")
# random_numbers = scan(file = "", what = integer(), n = 1)

#if(random_numbers > this_range)
#{
#  remove(random_numbers)
#  print("Sorry. When Replace = FALSE. It's not possible to have more unique random numbers than the given range")
#}

random_numbers = sample(numbers)
random_numbers = sample(random_numbers)

print("Now remove any random number in the available range")
number_taken = scan(file = 'stdin' , what = integer(), nmax = 1)
random_numbers = random_numbers[random_numbers != number_taken]

print("Now insert any random number within the range")
number_inserted = scan(file = 'stdin', what = integer(), nmax = 1)

random_numbers = append(random_numbers, number_inserted)

print(random_numbers)

write(random_numbers, file = "my_random_numbers.txt", sep = " ")

```

# Victory condition

This is , so the shortest code in bytes wins!

# Answer
# Jelly,  ~~27 26 21~~ 18 bytes

-8 bytes by applying a suggestion from Leaky Nun (use multi-set difference to `J` and a dequeue to replace a length-1 test)

```
ḲµVœ^J;LµḊȧȯ“Huh!?

```

A full program.

**Try it online!**

### How?

```
ḲµVœ^J;LµḊȧȯ“Huh!? - Main link: list of characters
Ḳ                  - split at spaces, call this x
 µ                 - start a new monadic chain with the result of that on the left
  V                - evaluate as Jelly code (vectorises) -> list of integers
     J             - range(length(x)) -> [1,2,3,...,n]
   œ^              - multi-set difference -> one of: []; [i,j]; or [j,i]
       L           - length of x -> n
      ;            - concatenate -> one of: [n]; or [i, j, n]; or [j, i, n]
        µ          - new monadic chain, call that r
         Ḋ         - dequeue r -> one of: []; [j, n]; or [i, n]
          ȧ        - logical and with r -> []; [i, j, n]; or [j, i, n]
            “Huh!? - list of characters "Huh!?" (end of a program so no close quote needed)
           ȯ       - logical or -> one of "Huh!?"; [i, j, n]; or [j, i, n]
                   - implicit print

```
> 1 votes

# Answer
# Mathematica, 70 bytes

```
{(a=(Range@1000~Complement~#)[[1]])+Tr@#-500500,a,1000}~Check~"Huh!?"&

```

Anonymous function. Takes a list of numbers as input and returns a list of numbers or a string as output. Ignore any messages generated. Works by finding *j* and then computing *i*.
> 0 votes

---
Tags: code-golf
---


title: Implement the "Lazy Sort"

text:
# Question
Title: Implement the "Lazy Sort"
I'm supposed to sort a list of numbers, but I'm super lazy. It's really hard to figure how to swap all the numbers around until all of them are in increasing order, so I came up with my own algorithm that will guarantee that the new list is sorted¹. Here's how it works:

For a list of size **N**, we'll need *N-1* iterations. On each iteration,

* Check if the N'th number is smaller than the *N+1'th* number. If it is, then these two numbers are already sorted, and we can skip this iteration.
* If they are not, then you need to continually decrement the first *N* numbers until these two numbers are in order.

Let's take a concrete example. Let's say the input was

```
10 5 7 6 1

```

On the first iteration, we'll compare 10 and 5. 10 is larger than 5, so we decrement it until it's smaller:

```
4 5 7 6 1

```

Now we compare 5 and 7. 5 is smaller than 7, so we don't need to do anything on this iteration. So we go to the next and compare 7 and 6. 7 is larger than 6, so we decrement the first three numbers until it's smaller than 6, and we get this:

```
2 3 5 6 1

```

Now we compare 6 and 1. Again, 6 is larger than 1, so we decrement the first four numbers until it's smaller than 1, and we get this:

```
-4 -3 -1 0 1

```

And we're done! Now our list is in perfect sorted order. And, to make things even better, we only had to iterate through the list **N-1** times, so this algorithm sorts lists in **O(N-1)** time, which I'm pretty sure is the fastest algorithm there is.²

Your challenge for today is to implement this Lazy Sort. Your program or function will be given an array of integers in whatever standard format you like, and you must perform this lazy sort and return the new *"sorted"* list. The array will never be empty or contain non-integers.

Here are some examples:

```
Input: 10 5 7 6 1
Output: -4 -3 -1 0 1

Input: 3 2 1
Output: -1 0 1

Input: 1 2 3
Output: 1 2 3

Input: 19
Output: 19

Input: 1 1 1 1 1 1 1 1 1
Output: -7 -6 -5 -4 -3 -2 -1 0 1

Input: 5 7 11 6 16 2 9 16 6 16
Output: -27 -25 -21 -20 -10 -9 -2 5 6 16

Input: -8 17 9 7
Output: -20 5 6 7

```

As always, this is , so write the shortest program you can!

---

¹ *This doesn't mean what it sounds like it means, but it is technically true*

² *I am completely kidding, please don't hate me*

# Answer
# Haskell, 40 bytes

```
f(a:r)|h:t<-f r=h-max(r!!0-a)1:h:t
f x=x

```

Try it online!
> 13 votes

# Answer
# Jelly,  ~~14 12 11~~  9 bytes

-2 bytes thanks to ETHproductions (use the minimum dyad, `«`)

```
I’«0Ṛ+\Ṛ+

```

A monadic link taking and returning lists of integers.

**Try it online!** or see the test suite.

I really don't think this is Lazy™ enough!

### How?

```
I’«0Ṛ+\Ṛ+ - Link: list of integers, a              e.g. [ 8, 3, 3, 4, 6, 2]
I         - increments between consecutive items of a   [-5, 0, 1, 2,-4 ]
 ’        - decrement (vectorises)                      [-6,-1, 0, 1,-5 ]
   0      - literal 0
  «       - minimum of decremented increments and zero  [-6,-1, 0, 0,-5 ]
    Ṛ     - reverse                                     [-5, 0, 0,-1,-6 ]
      \   - cumulative reduce with:
     +    -   addition                                  [-5,-5,-5,-6,-12]
       Ṛ  - reverse                                     [-12,-6,-5,-5,-5]
        + - addition (with a)                           [-4,-3,-2,-1, 1, 2]

```
> 12 votes

# Answer
## JavaScript (ES6), 61 bytes

```
a=>a.map((b,i)=>a=(b-=a[i+1])>0?a.map(c=>i--<0?c:c-b-1):a)&&a

```

### Test cases

```
let f =

a=>a.map((b,i)=>a=(b-=a[i+1])>0?a.map(c=>i--<0?c:c-b-1):a)&&a

console.log(JSON.stringify(f([10, 5, 7, 6, 1]))) // -4 -3 -1 0 1
console.log(JSON.stringify(f([3, 2, 1]))) // -1 0 1
console.log(JSON.stringify(f([1, 2, 3]))) // 1 2 3
console.log(JSON.stringify(f([19]))) // 19
console.log(JSON.stringify(f([1, 1, 1, 1, 1, 1, 1, 1, 1]))) // -7 -6 -5 -4 -3 -2 -1 0 1
console.log(JSON.stringify(f([5, 7, 11, 6, 16, 2, 9, 16, 6, 16]))) // 27 -25 -21 -20 -10 -9 -2 5 6 16
console.log(JSON.stringify(f([-8, 17, 9, 7]))) // -20 5 6 7
```
> 8 votes

# Answer
# Jelly, 12 bytes

```
I»1U
0ị;Ç_\U

```

Try it online!

### How it works

```
I»1U  Helper link. Argument: l (list of integers)
I     Compute the increments (difference between items) of l.
 »1   For each item n, take the maximum of n and 1.
   U  Reverse.

0ị;Ç_\U  Main link. Argument: l (list of integers)
   Ç     Call the helper link with argument l.
  ;      Concatenate this with
0ị       the 0th last item of the (1-indexed) l. (Can't use Ṫ because it modifies l)
    _\   Cumulatively reduce the result by subtraction.
      U  Reverse.

```

The basic idea at play is this: If you reverse the input and output arrays, the output is simply the input with each delta of 0 or greater replaced with -1. For example:

```
[10,  5,  7,  6,  1]   input
[ 1,  6,  7,  5, 10]   reverse
[   5,  1, -2,  5  ]   deltas
[  -1, -1, -2, -1  ]   min(deltas, -1)
[ 1, -1, -2, -1, -1]   reverse and concat the last item of the original
[ 1,  0, -2, -3, -4]   re-apply deltas
[-4, -3, -2,  0,  1]   reverse

```
> 7 votes

# Answer
# k, 20 bytes

```
{x-|+\0,1_0|1+-':|x}

```

Try it online.

Explanation:

```
{                  } /function, x is input
                 |x  /reverse x
              -':    /difference between every element
            1+       /add one to each difference
          0|         /make minimum difference be 0
      0,1_           /swap first difference with a 0
    +\               /cumulative sum
   |                 /reverse again
 x-                  /subtract from x

```
> 5 votes

# Answer
## Haskell, 56 bytes

```
a#(x:y:z)=map(+min(y-x-1)0)(a++[x])#(y:z)
a#x=a++x
([]#)

```

Try it online!

Keep the first part of the list in parameter `a`. At each step add the next element `x` to the end of `a` and increase all elements of a by the minimum of `(y-x-1)` and `0`.
> 4 votes

# Answer
# Python, 54 bytes

```
f=lambda a,*r:r and[f(*r)[0]-max(r[0]-a,1)]+f(*r)or[a]

```

Try it online!

Takes input splatted like `f(1,2,3)`. Outputs a list. Uses exponential time.
> 4 votes

# Answer
# Brain-Flak, 153 bytes

```
{(({})<>[({})])(({}({}))[({}[{}])])<>(([{}]({})))([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}({}<>{}())((<>))}{}{}}{}<>{}([]){{}({}<>)<>([])}<>

```

Try it online!

This includes `+1` for the `-r` flag.

```
#While True
{

    #Push the last value left in the array minus the counter onto the alternate stack
    (({})<>[({})])

    #Put the counter back on top of the alternate stack
    (({}({}))[({}[{}])])

    #Toggle
    <>

    #Find the difference between the last two inputs left on the array
    (([{}]({})))

    #Greater than or equal to 0?
    ([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

    #If So:
    {

      #Pop the truthy/falsy value
      {}

      #Increment the counter by the difference between elements +1
      ({}<>{}())

      #Push two falsys
      ((<>))

    #Endwhile
    }

    #Pop the two falsys
    {}{}

#Endwhile
}

#Pop the falsy

{}

#Toggle back
<>

#Pop the counter

#Reverse the stack
{}
([]){{}({}<>)<>([])}<>

```
> 3 votes

# Answer
## C#, 76 bytes

```
a=>{for(int d=0,i=a.Length-1;i>0;a[--i]-=d)d=a[i-1]-d<a[i]?d:a[i-1]-a[i]+1;}

```

This modifies the list in place. It goes through the list backwards and keep a running total of the delta to apply to each number.
> 3 votes

# Answer
## JavaScript (ES6), 59 bytes

```
f=([n,...a],p=a[0]-n)=>a+a?[(a=f(a))[0]-(p>1?p:1),...a]:[n]

```
> 2 votes

# Answer
# R, 56 bytes

`function(s){s-c(rev(cumsum(rev(pmax(0,-diff(s)+1)))),0)}`
> 2 votes

# Answer
# JavaScript (ES6), 68 bytes

```
a=>a.map((v,i)=>(d=v-o[i+1]+1)>1?o=o.map((v,j)=>j>i?v:v-d):0,o=a)&&o

```

Input and output is an array of integers.

## Test Snippet

```
f=
a=>a.map((v,i)=>(d=v-o[i+1]+1)>1?o=o.map((v,j)=>j>i?v:v-d):0,o=a)&&o
```

```
<input id=I oninput="O.value=f(this.value.split` `.map(x=>+x)).join` `">
<input id=O disabled>
```
> 1 votes

# Answer
# JavaScript (ES6), 50 bytes

```
f=a=>(b=[...a]).some((_,i)=>a[i]-->=a[i+1])?f(a):b

```

**Explanation:**

This is a recursive solution, which first clones the array, then decreases all values up until an element is greater or equal to the next element in the array.

The function calls itself as long as any elements are out of order. When the elements are finally sorted, the clone is returned. (We can't return the array itself, because the `some()` method would have decremented all its elements, making them all off by -1.)

**Test cases:**

```
f=a=>(b=[...a]).some((_,i)=>a[i]-->=a[i+1])?f(a):b

console.log(f([10,5,7,6,1])+'');
console.log(f([1,1,1,1,1,1,1,1,1])+'');
console.log(f([5,7,11,6,16,2,9,16,6,16])+'');
console.log(f([19])+'');
console.log(f([-8,17,9,7])+'');
console.log(f([1,2,3,4,5,6,7])+'');
```
> 1 votes

# Answer
## SWI-Prolog, 194 bytes

```
:-use_module(library(clpfd)).
f([],[],_,_).
f([A|B],[M|N],P,D):-A#=M-D-E,A#<P,abs(M,S),T#=S+1,E in 0..T,label([E]),f(B,N,A,D+E).
l([],[]).
l(A,B):-reverse(Z,B),f([X|Y],Z,X+1,0),reverse(A,[X|Y]).

```

Might be able to try it online here: http://swish.swi-prolog.org/p/LazySort.pl

You ask `l(L, [10,5,7,6,1]).` which says "solve for L, where L is the lazy sorted version of this list".

The two functions are:

* `l`azysorted(A,B) - states that A is the lazysorted version of B, if they're both empty lists, or if A can be obtained by reversing B, calling a helper function to walk the list and do a subtraction with an accumulator pushing each value lower than the previous one, and reversing the result of that back to the right way around.
* `f` helper matches two lists, the value of the previous number in the list, and a rolling difference accumulator, and solves for the new value of the current list position being the original value minus the difference accumulator, optionally minus a new value required to force this value below the previous number in the list, and `f` must solve for the tail of the list recursively with the now increased difference accumulator.

Screenshot of the test cases on Swish:
> 1 votes

# Answer
# C# (.NET Core), 89 88 86 79 bytes

* Saved just 1 byte with a slightly different approach.
* Saved another 2 bytes with a simplification of the `for`s.
* Saved 7 bytes thanks to the amazing golfing skills of VisualMelon.

```
a=>{for(int i=0,j,k;++i<a.Length;)for(k=a[i-1]-a[j=i]+1;--j>=0;)a[j]-=k>0?k:0;}

```

Try it online!

First `for` iterates through the array, then it calculates the decrement and finally the second `for` decrements the elements if necessary until the `i`th position.

Is it valid to just modify the original array instead of returning a new one (still getting used to the rules)?
> 0 votes

# Answer
## JavaScript (ES6), 61 bytes

```
a=>a.reduceRight((r,e)=>[e-(d=(c=e-r[0]+1)>d?c:d),...r],d=[])

```

Not the shortest solution but I couldn't pass over the opportunity to use `reduceRight`.
> 0 votes

---
Tags: code-golf, array, sorting
---