text
stringlengths 180
608k
|
---|
[Question]
[
Draw the parabolic trajectory of a thrown ball.
The input is the ball's initial upward velocity, a positive integer `v`. Every second, the ball moves `1` space right and `v` spaces vertically, and then `v` decreases by `1` to due to gravity. So, the upward velocity eventually steps down from `v` to `0` and down to `-v`, finally falling back down to its initial height.
The ball's positions trace a parabola. At horizontal position `x`, its height is `y=x*(2*v+1-x)/2`, with `(0,0)` the ball's initial position at the bottom left.
Output ASCII art of the ball's trajectory with `O`'s on the coordinates it ever occupies. The output should be a single multi-line piece of text, not an animation of the path over time.
The output should have no leading newlines and at most one trailing newline. The bottom line should be flush with the left edge of the screen, i.e. have no extra leading spaces. Trailing spaces are OK. You may assume the output line width fits in the output terminal.
v=1
```
OO
O O
```
v=2
```
OO
O O
O O
```
v=3
```
OO
O O
O O
O O
```
v=4
```
OO
O O
O O
O O
O O
```
v=10
```
OO
O O
O O
O O
O O
O O
O O
O O
O O
O O
O O
```
Related: [Bouncing ball simulation](https://codegolf.stackexchange.com/q/10520/20260)
---
**Leaderboard:**
```
var QUESTION_ID=111861,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/111861/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]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~18~~ ~~16~~ 13 bytes
-3 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!
```
F⊕N«←OM⊕ι↓»‖C
```
## Explanation
```
F⊕N« » For ι (implicitly from 0) to (1 + input as number)
←O Print O, with print direction rotated 180 degrees
M⊕ι↓ Move 1+ ι units down
‖C Reflect (in the default direction, right), leaving original intact
```
[Try it online!](https://tio.run/nexus/charcoal#ASwA0///77ym4oCmwrfCueKBuu@8rsK5wqtP77ytzrnihpPCu@KAlu@8o@KGkP//NQ "Charcoal – Try It Online") Link is to verbose code.
[Answer]
# C, ~~93~~ 92
(Note, someone got to 87 in the comments)
```
y,n;f(s){for(y=0;y<=s;){printf("%*c%*c",s-y+1,79,y*2+1,79);for(n=++y;s+1-n&&n--;)puts("");}}
```
[Try it online!](https://tio.run/nexus/c-gcc#HYyxCsMgFAD3fIUIDb6oYLqU8OrHBIk0Q1@CmkHEz@5sbeGGW@5aVoReRCj@CCJbg/lpI0I5w07JC36bXIerqLOc1WNRebr/BfBXkJUyY5SzpnEkrRHOK0XBOWCtrS/Ye91JQBkY82I2gF3Clq5AzOBQ24cO7Vb32r4)
---
Readable:
```
y,n;f(s){
for(y=0;y<=s;){
printf("%*c%*c",s-y+1,79,y*2+1,79);
for(n=++y;s+1-n&&n--;)puts("");
}
}
```
---
[Answer]
# [Python 2](https://docs.python.org/2/), 65 bytes
```
f=lambda n,x=0:(n and f(n-1,x+1)or'')+'\n'*n+' '*x+'O'+' '*n+'O'
```
[Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnU2FrYKWRp5CYl6KQppGna6hToW2omV@krq6prR6Tp66Vp62uoK5Voa3urw5kKYAF/NX/FxRl5pUAdRgaaP43NAAA "Python 2 – TIO Nexus")
[Answer]
# GNU sed, 41
* Score includes +1 from `-r` flags to sed.
```
s/$/OO/
:
s/(\s*) O( *)O$/&\n\1O \2 O/
t
```
Input is in unary, as a string of spaces - the length of string is the input.
[Try it online](https://tio.run/nexus/bash#HclBDsIgEEbhPaf4FygtiUFqVzaeYS4wO6Gxm8EwDSvvjk3f7stbS0XDJoiY8MCMeF@QisFRfn8K2su2U9@6yb7CXbyyONiGHzQn3Cpc12ADUTBPo2Fg9SNogB/JhisLRwJPOPbenUlFcv8D).
[Answer]
# Python 2, 76 bytes
```
x=input()
for i in range(x):print' '*(x-i),'O'+' '*i*2+'O'+'\n'*(i-x+1and i)
```
Pretty simple. The `i-x+1and i` is to prevent a bunch of trailing newlines.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 14 bytes
Saved 4 bytes thanks to *Adnan*
```
ƒ¶N×'ONúRÂJ}.c
```
[Try it online!](https://tio.run/nexus/05ab1e#@39s0qFtfoenq/v7Hd4VdLjJq1Yv@f9/QwMA "05AB1E – TIO Nexus")
**Explanation**
```
ƒ # for N in [0 ... input]
¶N× # push N newlines
'O # push "O"
Nú # pad with N spaces in front
RÂ # reverese and create a reversed copy
J # join everything to a string
} # end loop
.c # pad lines until centered
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 76 bytes
```
for((n=$1+1;--n;));{
yes ''|head -$n
r=$r›${n}AO
t=›${n}BO$t
}
echo O${r}O$t
```
Only works in a terminal since it uses [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code). `›` represents the CSI byte (**0x9b**).
### Test run
```
$ # The terminal's encoding must be set to ISO-8859-1.
$
$ xxd -g 1 arc.sh
0000000: 66 6f 72 28 28 6e 3d 24 31 2b 31 3b 2d 2d 6e 3b for((n=$1+1;--n;
0000010: 29 29 3b 7b 0a 79 65 73 20 27 27 7c 68 65 61 64 ));{.yes ''|head
0000020: 20 2d 24 6e 0a 72 3d 24 72 9b 24 7b 6e 7d 41 4f -$n.r=$r.${n}AO
0000030: 0a 74 3d 9b 24 7b 6e 7d 42 4f 24 74 0a 7d 0a 65 .t=.${n}BO$t.}.e
0000040: 63 68 6f 20 4f 24 7b 72 7d 4f 24 74 cho O${r}O$t
$
$ bash arc.sh 1
OO
O O
$ bash arc.sh 2
OO
O O
O O
$ bash arc.sh 3
OO
O O
O O
O O
$ bash arc.sh 4
OO
O O
O O
O O
O O
```
[Answer]
# JavaScript (ES6), ~~98~~ ~~92~~ ~~89~~ ~~84~~ 78 bytes
*(-20 bytes thanks to Arnauld!)*
```
f=(v,i=0)=>i>v?"":" "[r="repeat"](v-i)+0+" "[r](2*i)+0+`
`[r](i++<v&&i)+f(v,i)
```
A recursive solution. This is also my first *ever* answer in JavaScript, so please be gentle! I am still learning all this neat language has to offer, so golfing tips are very much appreciated. :)
## Test Snippet
You may need to scroll to see the entire output.
```
f=(v,i=0)=>i>v?"":" "[r="repeat"](v-i)+0+" "[r](2*i)+0+`
`[r](i++<v&&i)+f(v,i)
```
```
<input id=i min=1 type=number><button onclick=alert(f(document.getElementById("i").value))>Submit</button>
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~19~~ 17 bytes
```
Q:tqYsQ79Z?PtPv!c
```
Try it at [MATL Online!](https://matl.io/?code=Q%3AtqYsQ79Z%3FPtPv%21c&inputs=4&version=19.8.0) Or [verify all test cases](https://tio.run/nexus/matl#S/gfaFVSGFkcaG4ZZR9QElCmmPzfJeS/IZcRlzGXCZehAQA).
### Explanation
```
Q % Implicitly input v. Add 1
: % Push [1 2 ... v+1]
tq % Duplicate and subtract 1: pushes [0 1 ... v]]
Ys % Cumulative sum: gives [0 1 3 6 ...]
Q % Add 1: gives [1 2 4 7 ...]
79 % Push 79 (ASCII for 'O')
Z? % Create sparse matrix from column indices [1 2 3 4 ...],
% row indices [1 2 4 7 ...], and data 79
P % Flip vertically
tP % Duplicate, flip vertically
v % Concatenate the two matrices vertically
! % Transpose
c % Convert to char. Implicitly display. Char 0 is shown as space
```
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 37 bytes
```
x=0xR{y@xy-` *`o` y2**`o...2y{[` };};
```
Getting in with my kind-of-golfy language before the proper golfy langauges jump in.
## Explained
```
x= # Set 'x' to the input
0xR{ # For everything between the input and 0
y@ # Set the iteration value to y, for this function only.
xy-` * # Subtract y from x, repeat the string " " that many times.
`o # Push an "o" to the stack.
` y2** # Push 2*y " "'s to the stack
`o # Push another "o" to the stack
... # Concatenate the parts of this string together, giving us the two balls.
2y{[` }; # For all numbers between 2 and y, add a newline.
}; #
```
[Try it online!](https://tio.run/nexus/rprogn-2#@19ha1ARVF3pUFGpm6CglZCfoFBppAWk9fT0jCqroxMUaq1rrf///28OAA "RProgN 2 – TIO Nexus")
[Answer]
## Retina, ~~29~~ 19 bytes
```
?
$.`$*¶$&$'O$`$`O
```
[Try it online!](https://tio.run/nexus/retina#@69gz6Wil6CidWibipqKur9KgkqC////CiAAAA "Retina – TIO Nexus")
Takes input in unary as a run of spaces. Port of my JavaScript answer. Edit: Saved 10 bytes thanks to @MartinEnder♦.
[Answer]
# Retina, 35
* 2 bytes saved thanks to @MartinEnder
Port of [my sed answer](https://codegolf.stackexchange.com/a/111866/11259):
```
.+
$* OO
+`(\s*) (O *)O$
$&¶$1O $2 O
```
[Try it online](https://tio.run/nexus/retina#U9VwT/ivp82loqXg78@lnaARU6ylqaDhr6Cl6a/CpaJ2aJuKoYqRgoL//@AElf@GXEZcxlwmXIYGAA).
[Answer]
# R, 89 bytes
```
a=2*v+3
x=matrix(" ",a,v^2+1)
for(k in 0:v)x[c(1-k,k+2)+v,k^2+1]="o"
x[a,]="\n"
cat(x,sep="")
```
* Create a matrix of spaces (the variable a is the width of this matrix, saving a couple of bytes)
* Fill in "o"s at the required locations, working from the top of the arc downwards and outwards
* Add a newline at the end of each matrix row
* Collapse the matrix down to a single string and print
This is my first attempt at golfing, comments welcome...
[Answer]
# [Röda](http://github.com/fergusq/roda), ~~53~~ 52 bytes
```
f n{seq 0,n|{|i|["
"*i," "*(n-i),"O"," "*i*2,"O"]}_}
```
[Try it online!](https://tio.run/nexus/roda#@5@mkFddnFqoYKCTV1Ndk1kTrcSlpJWpo6SgpKWRp5upqaPkrwTmZWoZgdixtfG1/3MTM/MUqrk40zRMNblq/wMA "Röda – TIO Nexus")
Usage: `main { f(5) }`
Ungolfed version:
```
function f(n) {
seq(0, n) | for i do
push("\n"*i, " "*(n-i), "O", " "*i*2, "O")
done
}
```
[Answer]
# Befunge, ~~75~~ 73 bytes
```
<vp00:&
1<-1_:v#\+55:g01\-g01g00" O"1\*2g01" O"1p0
#@_\:v>$$:!
1\,:\_^#:-
```
[Try it online!](http://befunge.tryitonline.net/#code=PHZwMDA6JgoxPC0xXzp2I1wrNTU6ZzAxXC1nMDFnMDAiIE8iMVwqMmcwMSIgTyIxcDAKI0BfXDp2PiQkOiEKMVwsOlxfXiM6LQ&input=NA)
The first line reads in the velocity, *v*, and saves a copy in memory. The second line then counts down from *v* to zero, with the index *i*, and on each iteration pushes a sequence of character/length pairs onto the stack.
```
Length Character
-----------------
1 'O'
i*2 ' '
1 'O'
v-i ' '
i LINEFEED
```
This sequence represents a kind of run-length encoding of the required output in reverse. The last two lines then simply pop these character/length pairs off the stack, outputting *length* occurrences of each *character*, until the stack is empty.
[Answer]
# Java 8, ~~129~~ ~~124~~ 109 bytes
Golfed:
```
v->{String s="",t="";for(int j,y=0;y<=v;++y){for(j=0;j<v;++j)s+=j<y?"\n":" ";s+="o"+t+"o";t+=" ";}return s;}
```
[Try it online!](https://tio.run/nexus/java-openjdk#jZFBT4QwEIXv/IqXniCsRC8ehF2zxph48rDe1ENFupZ0C2lLDTH89nVgAdF4sJdp@r6@N5k51s2rkjlyxa3FreEfj@/F1uQPYnvDlcJnEAAjYx13VHwl33DgUoc7Z6TeP72Am72NiAUdURmEUjtIrHGRUslwmSKO5UQAu9a64pBUjUtqsnBKhyL0ONvMBDGDOSy5MLaCG2o6y3NMuUJL2nlKJVvD91FttDAa2fIEldTOwJQ/GVBSvO6xjIyuwZ41wxUYWJQusC749YFVDDF1F/e3JekGFVg8fn82hWuMhp20DivIaE76Yz7/0Hr7btiXkZ67YlrYOEkRltzzpHFSJaLRuZOVTu61uxvv2YnbQFAvNFg/DWhsViS8rlUb@iGuC7rgePwC)
Ungolfed:
```
public class DrawTheArcOfABall {
public static void main(String[] args) {
for (int i = 1; i < 6; ++i) {
System.out.println(f(v -> {
String s = "", t = "";
for (int j, y = 0; y <= v; ++y) {
for (j = 0; j < v; ++j) {
s += (j < y ? "\n" : " ");
}
s += "o" + t + "o";
t += " ";
}
return s;
} , i));
System.out.println();
System.out.println();
}
}
private static String f(java.util.function.IntFunction<String> f, int v) {
return f.apply(v);
}
}
```
[Answer]
## Haskell, 69 bytes
```
r=replicate
f n=[0..n]>>= \a->r a '\n'++r(n-a)' '++'O':r(2*a)' '++"O"
```
Usage example: `f 3` -> `" OO\n O O\n\n O O\n\n\nO O"`. [Try it online!](https://tio.run/nexus/haskell#@19kW5RakJOZnFiSypWmkGcbbaCnlxdrZ2erEJOoa1ekkKigHpOnrq1dpJGnm6iprgBkqvurWxVpGGlBuUr@Sv9zEzPzFGwVCkpLgkuKfPIUVBTSFEz@AwA "Haskell – TIO Nexus").
[Answer]
# VBA, ~~124~~ ~~112~~ ~~85~~ ~~88~~ ~~66~~ ~~63~~ 59 bytes
```
For i=0To[A1]:?Space([A1]-i)"O"Space(2*i)"O"String(i,vbCr):Next
```
Saved 29 bytes in total thanks to Taylor Scott
This must be run the in VBA Immediate window and print the result in the same.
Expanded / Formatted, it becomes:
```
For i=0 To [A1]
Debug.Print Space([A1]-i) & "O" & Space(2*i) & "O" & String(i,vbCr)
Next
```
(It turns out that concatenation in a print command is automatic without an operator.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 13 bytes
```
ÝηRO«ð×'O«ζ»
```
[Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//8OdzrdST8OCwqvDsMOXJ0/Cq862wrv//zI "05AB1E – Try It Online")
```
Ý # [0..n]
€LRO # [0.sum(), 0..1.sum(), ..., 0..n-1.sum(), 0..n.sum()]
« # Mirror image the array [0, 0..n.sum(), 0]
ð×'O« # Push that many spaces with an O appended to it.
.B # Pad small elements with spaces to equal largest element length.
ø» # Transpose and print.
```
[Answer]
# MATLAB, 114 Bytes
```
function p(v),for i=0:v,fprintf([repmat(' ',1,v-i),'o',repmat(' ',1,2*i),'o',repmat('\n',1,(i*(i~=v)+1))]);end,end
```
ungolfed:
```
function p(v)
for i=0:v
fprintf([repmat(' ',1,v-i),'o',repmat(' ',1,2*i),'o',repmat('\n',1,(i*(i~=v)+1))]);
end
end
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘Ḷ+\Ṛ⁶ẋ;€”Om0z⁶Y
```
**[Try it online!](https://tio.run/nexus/jelly#@/@oYcbDHdu0Yx7unPWocdvDXd3Wj5rWPGqY659rUAUUiPz//78pAA)**
### How?
```
‘Ḷ+\Ṛ⁶ẋ;€”Om0z⁶Y - Main link: v e.g. 3
‘ - increment: v+1 4
Ḷ - lowered range [0,1,2,3]
+\ - reduce with addition [0,1,3,6]
Ṛ - reverse [6,3,1,0]
⁶ - a space ' '
ẋ - repeat (vectorises) [' ',' ',' ','']
;€ - concatenate each with
”O - an 'O' [' O',' O',' O','O']
m0 - concatenate reflection [' O',' O',' O','O','O','O ','O ','O ']
z⁶ - transpose with space fill [' OO ',' O O ',' ',' O O ',' ',' ','O O']
Y - join with line feeds [' OO \n O O \n \n O O \n \n \nO O']
- implicit print
```
[Answer]
# PHP, 76 bytes
```
for(;$argn>=0;$s.=" ")echo($r=str_repeat)("
",$i++),$r(" ",$argn--),o,$s,o;
```
Run with `echo <v> | php -nR '<code>'` or [test it online](http://sandbox.onlinephpfunctions.com/code/308cb432f2f510679934cd7370608ca05c5656bf).
loops `$argn` down from input to `0` and `$i` up from 0;
prints - in that order - in each iteration
* `$i` newlines (none in the first iteration)
* left padding: `$argn` spaces
* left ball: `o`
* inner padding: `2*$i` spaces
* right ball: `o`
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~23~~ 19 bytes
```
2éoÀñYço/^2á O
HPJ>
```
[Try it online!](https://tio.run/nexus/v#@290eGX@4YbDGyMPL8/XjzM6vFDBn8sjwMvu////xgA "V – TIO Nexus")
Explain
```
2éo " Insert two 'o's
Àñ " <Arg> times repeat
Y " Yank the current (top) line. This is always '\s*oo'
ço/ " On every line that matches 'o'
^ " Go to the first non-whitespace character (the 'o')
2á " Append two spaces (between the two 'o's
O " Add a blank line on top of the current one
H " Go to the first line
P " Paste in front ('\s*oo')
J " Join this line with the blank line immediately after it
> " Indent once
```
[Answer]
## JavaScript (ES6), 87 bytes
```
f=
n=>' '.repeat(n+1).replace(/./g,"$`#$'O$`$`O").replace(/ *#/g,s=>[...s].fill``.join`
`)
```
```
<input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o>
```
Nonrecursive solution. Indexing requirement was annoying, both in the above and the following 62-byte (I don't know whether it would result in a shorter Retina port) recursive solution:
```
f=n=>~n?` `.repeat(n)+`OO`+f(n-1).replace(/^ *O/gm,`
$& `):``
```
[Answer]
## [Perl 5](https://www.perl.org/), 48 bytes
**47 bytes code + 1 for `-n`.**
```
$_++;print$/x$-,$"x$_,O,$"x($-++*2),O while$_--
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXlvbuqAoM69ERb9CRVdHRalCJV7HH0RrqOhqa2sZaer4K5RnZOakqsTr6v7/b/ovv6AkMz@v@L9uHgA "Perl 5 – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 17 bytes
```
r{n*íï- *'oï *+_x
```
[Try it online!](https://tio.run/##y00syUjPz0n7/7@oOk/r8NrD63UVtNTzD69X0NKOr/j/3/Q/AA "MathGolf – Try It Online")
## Explanation
```
r range(0, n)
{ start block or arbitrary length
n newline char, or map array with newlines
* pop a, b : push(a*b)
í get total number of iterations of for loop
ï index of current loop, or length of last loop
- pop a, b : push(a-b)
space character
* pop a, b : push(a*b)
' push single character
o print TOS without popping
ï index of current loop, or length of last loop
space character
* pop a, b : push(a*b)
+ pop a, b : push(a+b)
_ duplicate TOS
x reverse int/array/string
```
[Answer]
# [J](http://jsoftware.com/), 29 bytes
```
[:|:@(,~|.)' O'#~1,.~i.+/\@,]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61qrBw0dOpq9DTVFfzVlesMdfTqMvW09WMcdGL/a3KlJmfkK6QpGEIY6uowASN0AeP/AA "J – Try It Online")
Turned out very similar to Razetime's APL answer, though solved independently. I tried about 3 other approaches before realizing this one would be shortest.
[Answer]
# Stacked, ~~67~~ 63 bytes
```
args 0#1+:@x:>{!n x\-1-' '*'O'+n 2*' '*+'O'+x 1-n!=n*LF*+out}"!
```
Initial attempt, 67 bytes
```
args 0# :@v 1+2*:>[:v:+1+\-2/*' '*'O'+''split]"!fixshape tr rev out
```
Full program. Generates something like:
```
('O'
' ' 'O'
' ' 'O'
'O')
```
Which is the padded, transposed, reversed, and outputted.
[Answer]
## Batch, 163 bytes
```
@set l=@for /l %%i in (1,1,%1)do @call
@set s=
%l% set s= %%s%%
@set t=
%l%:c&for /l %%j in (2,1,%%i)do @echo(
:c
@echo %s%O%t%O
@set s=%s:~1%
@set t= %t%
```
[Answer]
## Ruby, 52 bytes
```
->x{(0..x).map{|a|$><<$/*a+' '*(x-a)+?O+' '*a*2+?O}}
```
No trailing newline (allowed by the rules: "*at most one trailing newline*")
] |
[Question]
[
Create a program that prints all whole numbers inclusively between an interval `(a, b)`, and replaces multiples of 8 in the sequence with random (uniformly distributed, independent of other characters), non-numeric, non-whitespace, printable ASCII characters.
Assume 0 < a < b in all cases.
If the number has more than 1 digit, make sure the amount of characters in the replacement matches!
Examples:
```
(1, 16) -> 1 2 3 4 5 6 7 $ 9 10 11 12 13 14 15 n@
(115, 123) -> 115, 116, 117, 118, 119, :F<, 121, 122, 123
(1, 3) -> 1 2 3
```
Non-Examples:
```
(1, 16) -> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
(115, 123) -> 115 116 117 118 119 $ 121 122 123
```
This is code golf, so the shortest code in bytes wins!
**Current Winner:**
[Pyke (21 bytes) by muddyfish](https://codegolf.stackexchange.com/questions/104356/crazy-8s-code-golf/104439#104439)
**Most Popular:**
[Python 2 (119 bytes) by Dennis](https://codegolf.stackexchange.com/questions/104356/crazy-8s-code-golf/104437#104437)
[Answer]
# [Python 2](https://docs.python.org/2/), 119 bytes
```
import random,string
def f(a,b):print`[random.choice(string.printable[10:95])for _ in`a`]`[2+a%8*b::5]or a;a<b<f(a+1,b)
```
[Try it online!](https://tio.run/nexus/python2#JY1BDoIwFETX9BR/Y0KlIRaC0cpNSGN/gWoTaUnt/fELu5eZl5nNL2tMGRKGKS7im5MPLzbNDlyJwnK1UpDNcPT1@I5@nMtDq/cO7Wce5EXdO81dTPAEHwwabYamwtPtbJXqNOX4wN72tFpJ2t3@Kj2A5eRDKQXIKxcEsiNs2p0FtFyxwh0iK/bD7Qc "Python 2 – TIO Nexus")
[Answer]
# Python 2, 126 bytes
[Try it online!](https://repl.it/EwR4/5)
```
import random,string
def f(a,b):
while b/a:print[a,eval('random.choice(string.printable[10:-6])+'*len(`a`)+"''")][a%8<1];a+=1
```
Many thanks to Flp.Tkc and EasterlyIrk for all of their help!
[Answer]
## zsh, ~~100~~ 98 bytes
```
for i in {$1..$2};{((i%8))&&<<<$i||<<<`yes 'shuf -e {!..~}|grep "[^0-9]"|head -c1'|head -$#i|zsh`}
```
The two input arguments are passed as command line arguments, and the numbers are output on separate lines.
```
for i in {$1..$2};{ # loop through the range
((i%8))&& # if the number is not divisible by 8 (i % 8 != 0),
<<<$i|| # output it
<<<` # otherwise, output the following:
yes ' # using `yes' as a golfy loop
shuf -e {\!..\~} # shuffle the range of printable ASCII (minus space)
|grep "[^0-9]" # get rid of numbers
|head -c1' # take the first character
|head -$#i # obtain a string with that code repeated len(i) times...
|zsh # ... and eval it
`}
```
[Answer]
## Pyke, ~~22~~ 21 bytes
```
h1:Fi8%!I`lV~Kl7T>Hs0
```
[Try it here!](http://pyke.catbus.co.uk/?code=h1%3AFi8%25%21I%60lV%7EKl7T%3EHs0&input=16%0A4)
Takes input in the form: `higher`, `lower`
```
h1: - range(lower, higher+1, 1)
F - for i in ^:
i8% - i % 8
! - not ^
I - if ^:
`l - len(str(i))
V - repeat V ^ times
~K - printable_ascii
l7 - ^.strip()
T> - ^[10:]
H - random.choice(^)
s0 - sum(^)
```
[Answer]
# Mathematica, 96 bytes
```
Range@##/.a_?(8∣#&):>Join[33~(c=CharacterRange)~47,58~c~127]~RandomChoice~⌊Log10@a+1⌋<>""&
```
**Explanation**
For inputs `m` and `n`:
```
Range@##
```
Generate `{m, m + 1, m + 2, ... , n}`
```
/.a_?(8∣#&):>
```
For all numbers that are divisible by 8 (call that `a`), apply this replacement rule:
```
Join[33~(c=CharacterRange)~47,58~c~127]
```
Get a list of all printable ASCII characters, except digits.
```
... ~RandomChoice~⌊Log10@a+1⌋
```
Pseudo-randomly choose `Floor[Log10[a] + 1]` characters from the list, allowing duplicates.
```
<>""
```
Join the characters.
[Answer]
## R, 73 bytes
```
i=scan();x=i[1]:i[2];x[!x%%8]=sample(sapply(c(32:46,58:126),intToUtf8));x
```
Reads input from stdin and replaces replaces numbers divisible by `8` with a uniformly chosen sample of ascii characters in the range `32...47, 58...126`. To draw the random sample we need a vector of characters, unfortunately `intToUtf8()` returns one string rather than a vector so we also have to vectorize it over the range using `sapply`.
[Answer]
# Python 2, 126 bytes
[*(one does not simply outgolf Dennis)*](https://codegolf.stackexchange.com/a/104437/60919)
Seeing as I did a lot of work on heather's answer, I thought I'd post my own solutions too.
```
import random,string
def f(a,b):
while b/a:print[a,eval('random.choice(string.printable[10:-6])+'*len(`a`)+"''")][a%8<1];a+=1
```
This is a function which takes two arguments and prints directly to `STDOUT`.
# 127 bytes
```
import random,string
lambda a,b:[[x,eval('random.choice(string.printable[10:-6])+'*len(`x`)+`''`)][x%8<1]for x in range(a,b+1)]
```
This is an unnamed anonymous function - to use, assign to a variable (such as `f`), and then call with `f(a, b)`. This returns the output as a list.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 28 bytes
```
Fia,b+1Pi%8?i{RC@>PA@`\D`}Mi
```
Takes the numbers as command-line arguments and prints a newline-separated list of results. [Try it online!](https://tio.run/nexus/pip#@@@WmaiTpG0YkKlqYZ9ZHeTsYBfg6JAQ45JQ65v5//9/0/9GpgA "Pip – TIO Nexus")
Explanation:
```
a,b are cmdline args; PA is string of all printable ASCII
Fia,b+1 For i in range(a, b+1):
P Print this:
i%8?i If i%8 is truthy (nonzero), i; otherwise:
{ }Mi Map this function to the digits of i:
@>PA All but the first character of PA (removes space)
@`\D` Find all regex matches of \D (nondigits)
RC Random choice from that list of characters
The map operation returns a list, which is concatenated
before printing
```
[Answer]
# JavaScript (ES6), 114 bytes
```
f=(x,y)=>(x+"").replace(/./g,d=>x%8?d:String.fromCharCode((q=Math.random()*84)+(q>15?43:33)))+(x<y?[,f(x+1,y)]:"")
O.textContent = f(1,200)
```
```
<pre id=O>
```
Those darn built-ins with 23-byte names....
[Answer]
# Bash + [apg](https://linux.die.net/man/1/apg), ~~64~~, ~~76~~, 73 bytes
EDITS:
* Fixed the "8 8" issue, exclude numeric characters from a set of random chars, +12 bytes
* **-3 bytes**, replaced `$1 $2` with `$@`, thx @pxeger
**Golfed**
```
seq $@|sed "$[(7&(8-$1%8))+1]~8s/.*/a=&;apg -a1 -n1 -Mcsl -m\${#a} -x0/e"
```
**Test**
```
>./crazy8 8 8
$
>./crazy8 115 123
115
116
117
118
119
As_
121
122
123
>./crazy8 1 16
1
2
3
4
5
6
7
"
9
10
11
12
13
14
15
x!
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 26 bytes
```
&:"@8\?@}6Y24Y2X-Xz@VnT&Zr
```
[Try it online!](https://tio.run/nexus/matl#@69mpeRgEWPvUGsWaWQSaRShG1HlEJYXohZV9P@/OZehOQA "MATL – TIO Nexus")
### Explanation
```
&: % Input a and b (implicit). Push range [a a+1 ... b]
" % For each k in that range
@ % Push k
8\ % Modulo 8
? % If non-zero
@ % Push k
} % Else
6Y2 % Push string of all printable ASCII chars
4Y2 % Push string '0123456789'
X- % Set difference
Xz % Remove space. Gives string of possible random chars
@Vn % Push number of digits of k
T&Zr % Random sample with replacement of that many chars from the string
% End if, end for each, display (implicit)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
jm?%d8dsmO-r\~\ jkUT`d}F
```
[Try it online!](https://tio.run/nexus/pyth#@5@Va6@aYpFSnOuvWxRTF6OQlR0akpBS6/b/v6GOgqEZAA "Pyth – TIO Nexus")
### Explanation:
```
jm?%d8dsmO-r\~\ jkUT`d}FQ # Auto-fill variables
}FQ # Splat inclusive range on the input
m?%d8d # Map over each number, if it isn't divisible by 8 return it
smO `d # for each other number, select a character at random for
each of it's digits and then flatten into one string
r\~\ # Printable ASCII excluding space
- jkUT # Setwise difference with numeric values (remove numbers)
j # Join with newlines
```
[Answer]
# [Perl 6](http://perl6.org/), 60 bytes
```
{map {$_%8??$_!!S:g/./{grep(/\D/,"!".."~").pick}/},$^a..$^b}
```
Explanation:
* `{ map { }, $^a .. $^b }`: A lambda that takes two arguments, generates the list of integers in that range, and returns it with the following transformation applied to each element:
* `$_ % 8 ?? $_ !!`: If the element is not divisible by 8, pass it on unchanged. Otherwise...
* `S:g/./{ }/`: ...replace each character of its string representation with the value generated by this expression:
* `grep(/\D/, "!" .. "~").pick`: Generate the range of characters between `!` and `~` (in Unicode order), filter out digits, and randomly pick one of the remaining characters.
[Answer]
## Perl, 66 bytes
```
map{$_%8||s%.%do{$_=chr rand 126}until/[!-\/:-~]/;$_%ge;say}<>..<>
```
Run with `-E` flag:
```
perl -E 'map{$_%8||s%.%do{$_=chr rand 126}until/[!-\/:-~]/;$_%ge;say}<>..<>' <<< "8
16"
```
This is pretty straight forward:
-`<>..<>` creates a list of the numbers between the 2 inputs number. And then `map` iterates over it:
-`$_%8||...` : the `...` are executed only if `$_` is a multiple of 8.
-`s%.%xxx%ge` : replace every character with `xxx`.
- `do{$_=chr rand 126}until/[!-\/:-~]/` pick a random character (from codes 0 to 126) until we get one that satisfies `/[!-\/:-~]/`, ie. one that is printable and is not a digit.
- `say`: print it.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~129~~ 119 bytes
```
s(a,r){a&&s(!isdigit(r=rand()%94+33)?putchar(r),a/10:a,0);}f(a,b){b>a&&f(a,b-1);b%8?printf("%d",b):s(b,0);printf(" ");}
```
[Try it online!](https://tio.run/##ZY7LCsIwEEX3fkWsVGYwakMFH9X6LXm0OlBjSeJCit9e04KIuLsczmFGLy9a9zOyunmYih11eLbV6lpOvsgH05D6Y3T/RYFuQ9h7kNxhJ@dzD1Pyhi4UwJ2ctAYw3W8WeY7n9hH0VTpwyOVaZAfJMyxedUwVdqqM8biXAguV7s6tIxtqSFKTROHgQQ3@h7Iktn3c7CbJMkDW@fHc8BJkiEUNgovtYL0B "C (gcc) – Try It Online")
129 → 119 Use the `%94+33` trick from [O.O.Balance](https://codegolf.stackexchange.com/a/161452/31443)
### Ungolfed:
```
s(a,r){
a&& // Loop recursively on a!=0
s(!isdigit(r=rand()%94+33) // Test random selection
?putchar(r),a/10 // Print and reduce a
:a // Retry random selection
,0); // Second arg, recurse
}
f(a,b){
b>a&& // Loop recursively on b>a
f(a,b-1); // Reduce b, recurse
b%8?printf("%d",b) // Print non 8's
:s(b,0); // Call s() for 8's
printf(" "); // Space separator
}
```
[Answer]
# C, ~~157~~ 115 bytes
```
f(a,b){b-a&&f(a,b-1);if(b%8)printf("%d",b);else for(;b;b/=10){while(isdigit(a=rand()%94+33));putchar(a);}puts("");}
```
Try it online [here](https://tio.run/##HYzNCoMwEITvfYoQUHapUsUKleDD5FcXrEqStgfx2dPgnL4ZZkbXk9YpOZCVwkPVsiwvrlsU5EAVL9w9rdEBLwzPHWGXYJnbPAgl1GNsGzx@My0WKBiaKIIcvVwNYDE8712HKPZP1LP0IFGcmQNwninlV/aWtMJ3I4PsuLGscG0jvS00eXplDoa@aps@2zP9AQ). Thanks to [jxh](https://codegolf.stackexchange.com/users/31443/jxh) for golfing 42 bytes.
Ungolfed version:
```
f(a, b) { // recursive function, parameters are implicitly int
b-a && f(a, b-1); // recurse until a = b
if(b % 8) // if the number is a multiple of 8
printf("%d", b); // simply print it
else for(; b; b /= 10) { // while b > 0, lop off the last digit
while(isdigit(a = rand() % 94 + 33)); // generate random characters in ASCII range [33, 127] until one is non-numeric
putchar(a); // print the character
}
puts(""); // print a newline
}
```
[Answer]
# Java 10, ~~149~~ 147 bytes (lambda function)
```
b->a->{var r="";for(;a<=b;r+=" ",a++)for(var c:(a+"").split("")){char t=0;for(;t<33|t>126|t>47&t<59;t*=Math.random())t=127;r+=a%8<1?t:c;}return r;}
```
[Try it online.](https://tio.run/##lZDNbsIwEITvPMUqUiu7AYuQ8lMcp7dKPXDiWPWwmACmwYmcDRKiefbUEdBrqWRZI8@3a83s8YiD/fqr1TlWFSzQ2HMPoCIko2HvXVGTycWmtppMYcXbVSTvlrJt5vr3QUtyxm7TFDQoaFeDFAfp@YgOnAoCuSkck5iolXShCiDoYxjy7rEj9JxhGARcVGVuiHnFz3rnDVLDyyQlcfxNaTSa@Pt5@kjJ@EXSk1og7YRDuy4OjHNS0WjafYAPsyR6pbmWjcuodhacbFrpY/tT1qvcJ78WcCzMGg6@FHYJ8PGJvOsHYHmqKDuIoiZReodyy7TAssxPLJrwm@Jc/kmP4l88Gt8xEP9v@/CGzy5402vaHw)
# Java 10, ~~227~~ 225 bytes (full program)
```
interface M{static void main(String[]A){var r="";for(var a=new Long(A[0]);a<=new Long(A[1]);r+=" ",a++)for(var c:(a+"").split("")){char t=0;for(;t<33|t>126|t>47&t<59;t*=Math.random())t=127;r+=a%8<1?t:c;}System.out.print(r);}}
```
[Try it online.](https://tio.run/##TU7LbsIwEPwVyxLIJhDFoTwdt@JeThwRh5UTwNDYyNmmqtJ8uzFISL2M5qHZnQu0MLmU1xCMxcofQVdk2zUIaDRpnSlJDcayHXpjT/vDhncteOIVpfLoPHsIULb6IZ/Onthmnx24hOK/I6LjE0UJHUOS8FdLrxkklPK0uX0ZZJHxTp9jgCp7npZYTKd/@C7yecS3xRCL2UriSG0Bz6kHW7qacY5K5IvHAxgsC/GBay373W@DVZ26b0xvcTcyz2XfhxCWWRD57A4)
**Explanation:**
```
b->a->{ // Method with two integer parameters and String return-type
var r=""; // Result-String, starting empty
for(;a<=b // Loop as long as `a` is smaller than or equal to `b`
; // After every iteration:
r+=" ", // Append a space to the result-String
a++) // And increase `a` by 1
for(var c:(a+"").split("")){
// Inner loop over the characters of the current number
char t=0; // Random-char, starting at 0
for(;t<33|t>126|t>47&t<59;
// Loop until `t` is a non-digit printable ASCII char
t*=Math.random())t=127;
// Set `t` to a random character with a unicode in the range [0,127)
r+=a%8<1? // If the current `a` is divisible by 8:
t // Append the random character
: // Else:
c;} // Append the digit instead
return r;} // Return the result
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 32 bytes
```
{(?84¨⍕⍵)⊇⎕D~⍨'!'…'~'}¨@{0=8|⍵}…
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6s17C1MDq141Dv1Ue9WzUdd7UApl7pHvSvUFdUfNSxTr1OvPbTCodrA1qIGqKAWKPQ/DajxUW8fxIyu5kPrjR@1TQTygoOcgWSIh2fwf0OFNAVDMy5DQ1MQw8iYCyRgDAA "APL (Dyalog Extended) – Try It Online")
Huge thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) and [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima) for their help. First time using Dyalog Extended!
Explanation:
```
{(?84¨⍕⍵)⊇⎕D~⍨'!'…'~'}¨@{0=8|⍵}… ⍝ Dyadic 2-train
… ⍝ Tacit range: list of numbers from left arg
⍝ to right arg inclusive
{(?84¨⍕⍵)⊇⎕D~⍨'!'…'~'}¨@{0=8|⍵} ⍝ Monadic function applied to above
{ } ⍝ Function definition
8|⍵ ⍝ 8 modulo every item in our range
0= ⍝ Transform list into a boolean vector, with
⍝ 1 where item was equal to zero, 0 otherwise
¨@ ⍝ Applies left function to each item selected
⍝ by above
{ } ⍝ Function definition
'!'…'~' ⍝ Range of all printable ASCII chars
⎕D~⍨ ⍝ Remove numeric characters from above
( ⍕⍵) ⍝ Convert function argument to string
⍝ (e.g., 123 -> "123")
84¨ ⍝ For each character, replace with number 84
⍝ (number of non-numeric printable ASCII chars)
? ⍝ Generate random number from 1-84 for each
⍝ 84 in list
⊇ ⍝ Index the ASCII char list with above random
⍝ numbers
```
[Answer]
# Inlined version
# [Scala](http://www.scala-lang.org/), 132 bytes
```
def S(a:Int,b:Int)= a to b map(x=>if(x%8==0)Random.nextInt(((33 to 47)++(58 to 126)).length).toChar.toString else String.valueOf(x))
```
[Try it online!](https://tio.run/##VY/dSsQwEIXv8xRzI0zYJXStP4tQQb0SFME@wbSd7kbSJDRTKYjPXhP2ypuZc4ZzPpjUk6PNTjHMAqkY0wfnuBcbvJkWoc6xebNJnpdx5Fn9iy5infkkP4RJKRW6r9yDd7IeeBX2Q4KnGH8UwDbwCC3Sw6uXfVemboBAAnQwUcS1ebQjrlfHpqn0BWh8ZuQgItZ1Sd7c690Ob49FH67vtDaO/UnO2kh4OdOcVyuz9Sdglxgu2nyTW/gjs7XeAGK@CbZ4qPZ1VYrlM61@tz8 "Scala – Try It Online")
# [Scala](http://www.scala-lang.org/), 198 bytes
### An improved functional version with immutable state (03-04-2018)
```
def S(a: Int, b: Int)={
val c=(33 to 47)++(58 to 126)
val r = (a to b).toStream.map {case x if x%8==0=>c(Random.nextInt(c.length)).toChar.toString
case x => String.valueOf(x)}
r}
```
[Try it online!](https://tio.run/##VVDRSsQwEHzPV8yLkHBH6Fn1DiEH6pOgCN4XpGl6F0mTkqZSOPrtNWlF8Gl3Z2dndrdX0srZtJ0PEX0uuPLWahWNd7wdoqys5m@mj89D0@hA/lGHaCz/lK72LSHEV19pDu/SOOgxalf3eOq6KwFmoNYNTlQ@4tXFLaolMpGbwLe0UIKWJaLH3Z5tNvT@kPPd7QP7YwQIUJnhivHoTzFo2fJWdrgq2WuMMA3Gm4MQhTgquu7FXVolWVHFrXbneGF59uUiwyph3HkxAH41xBErzJPnoD8aOrJpoYQpndGlVqQnuiu2ZZGl8m8YmeYf "Scala – Try It Online")
**A functional style solution in Scala (350 bytes)
for the fun of it.**
```
def r(a:Int, b:Int)={
var l=(33 to 47).toList:::(58 to 126).toList
l=Random.shuffle(l)
var x=ListBuffer[String]()
var k=0
(a to b).toList.foreach{e=>{
if(k==l.length){k=0
l=Random.shuffle(l)}
if (e.toInt%8==0){x+=l(k).toChar.toString
k+=1}
else{x+=e.toString
k+=1}}}
x}
```
*Suggestions for improvements are welcomed.*
[Answer]
# PHP, 163 bytes
```
$n=range(48,57);$c=array_diff(range(32,126),$n);
foreach(range($a,$b) as $v){if($v%8!=0){echo $v;}
else{for($i=0;$i<strlen($v);$i++){echo chr($c[array_rand($c)]);}}}
```
### Explanation:
* `$n = range(48,57)` These are the ASCII codes for numbers, which are in the middle of special characters (32-47) and other characters (58-126).
* `$c = array_diff(range(32,126), $n)` Using the `$n` array, exclude numeric characters and build an array of acceptable ASCII characters.
* `foreach(range($a,$b) as $v)` Loop over the range of values from `$a` to `$b` (inclusive), as $v inside the loop.
* `if($v % 8 != 0) { echo $v; }` Test for $v being evenly divisible by 8 using the mod operator `%`.
* `else { for($i = 0; $i < strlen($v); $i++) { ... }}` If not evenly divisible by 8, loop enough times for the number of digits in the number and print the characters (in the next step).
* `echo chr($c[array_rand($c)])` Print a single character from the acceptable array of ASCII values in `$c`. `array_rand` returns an index in the array, so we have to get the actual value at that index using `$c[random_key]`.
I could probably make this smaller by creating `$c` differently, and the loop to print the ASCII characters feels clunky so I'll continue to ponder how to shorten that.
[Answer]
## postgresql9.6 251 chars
very long code but postgresql also does it.
```
do language plpgsql $$ begin for n in a..bloop raise info'%',case when 0=n%8then(select array_to_string(array(select*from(select chr(generate_series(33,126)))t where chr!~'\d'order by random()limit floor(log(n))+1),''))else n::text end;end loop;end;$$
```
formatted sql is here:
```
do language plpgsql $$
begin
for n in a..b loop
raise info '%',
case when 0 = n % 8 then (
select array_to_string(array(select * from (
select chr(generate_series(33, 126))
) t where chr !~ '\d' order by random() limit floor(log(n)) + 1), '')
) else n::text
end;
end loop;
end;
$$
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 79 bytes
```
::[a,b|~c%8=0|[_l!c$||_R33,116|~e>47 and e<58|e=e+z]Z=Z+chr$(e)]\Z=Z+!c$]Z=Z+@
```
Skipping the numbers is a costly affair, here's a version that might also randomly select `0-9` for 20 bytes less:
```
::[a,b|~c%8=0|[len(!c$)|Z=Z+chr$(_r33,126|)]\Z=Z+!c$]Z=Z+@
```
Sample output for `1, 89`
```
1 2 3 4 5 6 7 U 9 10 11 12 13 14 15 M9 17 18 19 20 21 22 23 ^L 25 26 27 28 29 30
31 <U 33 34 35 36 37 38 39 gH 41 42 43 44 45 46 47 aJ 49 50 51 52 53 54 55 1b 57 58 59 60
61 62 63 ,C 65 66 67 68 69 70 71 ]; 73 74 75 76 77 78 79 [B 81 82 83 84 85 86 87 Ix 89
```
Explanation:
```
:: Get inputs 'a' and 'b' from the command line
[a,b| FOR(c=a; c<=b; c++)
~c%8=0| IF c is cleanly divisible by 8 THEN
_l!c$| Take the length (_l) of the string representation (! ... $) of c
[ | FOR (d = 1; d<= length(c); d++)
_R33,116| Set e to a random value in the range 33 - 116 (all the printable ascii's - 10)
~e>47 IF e falls between 47
and e<58| and 58 (ASCII code for 0-9) THEN
e=e+z e = e + 10 (z == 10 in QBIC)
] END IF
Z=Z+ Add to Z$
chr$(e)] ASCII character e
\ ELSE if c is not cleanly divisible by 8
Z=Z+!c$ Add to Z the string representation of c
] NEXT
Z=Z+@ Add a space to Z$ (@ is an implicitly delimited string literal with 1 significant space)
( Z$ is implicitly printed at end of program )
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŸεD8ÖižQžhK¦.rsg£
```
Takes the input as `highest\nlowest`, and outputs a list.
[Try it online](https://tio.run/##ASkA1v9vc2FiaWX//8W4zrVEOMOWacW@UcW@aEvCpi5yc2fCo///MTIzCjExNQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/6M7zm11sTg8LfPovsCj@zK8Dy3TKypOP7T4f22tzv/oaEMdQ7NYHThlaKpjaGSMytIBkRY6hoZGsbEA).
**Explanation:**
```
Ÿ # Create a list in the range [low (implicit) input, high (implicit) input]
ε # Map each value to:
D # Duplicate the value
8Öi # If it's divisible by 8:
žQ # Push all printable ASCII characters (" " through "~")
žhK # Remove all digits
¦ # Remove the first character (the space)
.r # Randomly shuffle the remaining characters
s # Swap to take the map value again
g # Get its length
£ # And leave that many characters from the string
# (and implicitly output the resulting list after we're done mapping)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 bytes
```
;òV ®%8?Z:EÅk9ò)öZìl
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=O/JWIK4lOD9aOkXFaznyKfZa7Gw=&input=MQoyMAotUw==)
```
;òV ®%8?Z:EÅk9ò)öZìl :Implicit input of integers U & V
òV :Range [U,V]
® :Map each Z
%8 : Modulo 8
?Z: : If truthy, return Z, else
; E : Printable ASCII
Å : Slice off first character
k : Remove
9ò : Range [0,9]
) : End remove
Zì : Digit array of Z
l : Length
ö : Get that many random characters from the string
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 128 bytes
```
include random.fs
: f 1+ swap do i 8 mod if i . else i 0 <# #s #> 0 do 83 random 33 + dup 47 > 10 * - emit loop ." "then loop ;
```
[Try it online!](https://tio.run/##LYxBa8IwHEfvfoo3exAUS0vFiYonC9tJcB53Kcs/GkiT0ERk@/Jdhjv93g8eT/sh3ZZX/TfjaNyXvSth6JzyfanjZIumXhAfXUB5DBt6rzA6Y4nYKBkq9gVFpDhkzNam@S/QNCxQ98DqlQN1xZwl0puE9T5QTmGabuKedze@teeWj7Y98sInl/dTzkl0s4RxJpnOmh8hiijC4IMM9ntSU68r9PgL "Forth (gforth) – Try It Online")
### Explanation
Loop from start to end, print number if not multiple of 8, otherwise get the number of digits in the number and print that many random characters followed by a space
### Code Explanation
```
include random.fs \ include/import the random module
: f \ start new word definition
1+ swap \ add 1 to end number, because forth loops are [start, end), and swap order
do \ start counted loop form start to end
i 8 mod \ get the remainder of dividing i (loop index) by 8
if \ if true (not 0, therefore not multiple of 8)
i . \ print the index
else \ otherwise
i 0 \ convert index to double-length number
<# #s #> \ use formatted numeric output to convert number to a string
0 do \ loop from 0 to (string-length - 1)
84 random \ get random number between 0 and 83
33 + \ add 33
dup 47 > \ check if result is larger than 47
10 * - \ if it is add 10 to result (results in number in range: 33-47,58-126)
emit \ output ascii char corresponding with number
loop \ end inner loop
." "then \ output a space and then close the if/else
loop \ end the outer loop
; \ end the word definition
```
### UnGolfed
I don't usually ungolf my solutions, but this one is long/complicated enough that I think it's needed
```
include random.fs
\ get the length (in digits) of a number
: num-length 0 <# #s #> nip ;
\ check if a number is a multiple of another
: is-multiple mod 0= ;
\ get a random printable non-digit ascii char
: random-char 84 random 33 + dup 47 > 10 * - ;
\ get a "random" string of printable ascii chars the same length as a number
: rand-str num-length 0 do random-char emit loop space ;
\ print numbers from a to b, replacing multiple of 8 with a random ascii string of the same length
: crazy-eights 1+ swap do i 8 is-multiple if i rand-str else i . then loop ;
```
[Answer]
# [PHP](https://php.net/), 130 bytes
```
function($a,$b){for(;$a<=$b;$a++)echo$a%8?$a:(function($l){while($l--)echo chr(($x=rand(44,128))-($x>58?:11));})(strlen($a))," ";}
```
[Try it online!](https://tio.run/##bY3NCsIwEITvfYpQVtjFFEz9K8baFxEk1tQUShLWioL47LWK4MXTDPMNM9HFYVtFF4VlDnxgGwP3rT/jjLSARpRDc/V13waPYCQc6dEERg1mW8JxlOmUbO0CmElRgdngr93R4@bazo4uyz4lUTtGhHvJxp9wsZAqL4iyMdkti2qjFJF@El567uz7jkimItXPQScJNKikUCvSyWcq3fu9T79ALUeUz/8yKf7maynymSI9vAA "PHP – Try It Online")
Ungolfed:
```
function c8( $a, $b ) {
for( ; $a<=$b; $a++ ) { // loop between a -> b
echo $a % 8 ? $a : // every 8, call anon func instead of value
(function($l) {
while( $l-- ) { // repeat length of value
$x = rand( 44, 128 ); // range size is printable chars [33,47][58,127]
$x-= $x > 58 ?: 11; // Subtract one from x. If x was less than or
// equal to 58, subtract a further ten from it
// so that it now falls within the 33-47 range
echo chr( $x ); // echo ASCII value
}
})( strlen( $a ) )," ";
}
}
```
[Answer]
# [Kotlin](https://kotlinlang.org), 136 bytes
```
{r:IntRange->var s=""
for(i in r){for(c in "$i"){var n=java.util.Random().nextInt(83)
if(n>14)n+=10
s+=if(i%8>0)c
else '!'+n}
s+=" "}
s}
```
[Try it online!](https://tio.run/##jVbbbts4EH33V0yMtJUQV4niJHWNONhsty0CdLdA27dFH2iZtrmRSJek4qaB/2W/ZX8se4aUZBVbYJsHhyLncmY4Z4a3xpdKPx4f0ysrhZcLWhpLfq0cFWYhaWXKJRVrUZZSr@R0AMG19xs3PT7mcz7OnBfFrfwKKYhkhamOvxznJ2fj84tBsCu@3dPE0Su29xYKg84bCdpYs7Kigkvh8aG0dwRvtF2bUpKuq7m0jpQuytqpO1ne01z6rZSahMa2l/ZOlP/8nYgRzdMRNhdk5aYUhXRU1aVXmxIrs6QJpOFFkpNfaqkLSVvl12ShYSpKaq0QeQX7C@W8VfMayRhBZyE3Ej/asxEDA5bzYUUB1w4etdHPAVNaVcSP7Vp56TZAMIoBiTkiuf746uamp5kNOA3XzkGVTugSqbikOWPk6AvhZCNyswyoYyZoLRCWsZLzpSkH2JXyI6rELQKrwz6yWpk64t37a6NvklNxQJXwxVq6g@Dn9VdRca6m4SvJR5RfpPT8Ck5OaUxndE4X9IIO6SXlJ5TnlJ9SPqb8jPJz0r9EpfwcaqfjqBc@8gv@ecE/E/55OaLpm0uWYg@np0G@9TjeOwwo/kA6fxLX5Ie48osf4mJYjIpBMSZEBTwMJ6BhnU9MgT4LRuRMrJ@1sbhgH4@Q1vk9PlFNusvkBkUFKpWimi8ELWtdeGV0LDjwg5Pv4pdgBcvEIW@YDKhbh0vyNSpnFf35sOTqq/2m9tkABlvRJOhO6Ub7D7xKp/Qxyj8MBkQw/ptcCvCgb4pJwjSXolgHDq1QWbE@ok4E1KJRcEl0J2yrP6PhEDtsIumpB600Og5m3rQ@ujLkKBhIqxUjGrUKznNpK5SuBR8aahotsyAQ/O1NwePwsDE07NwGO2@lljb2l8ZIQ5/Y3CTVjkm5V9jztMdQph6woAhE5Blg7VW2Cjydw8Xc3EXaBRmHOrlVG8JmcFVljQrnr0Exo7/Enchqr8rsQ8CXpJmWXz1uMZmM00ZDLSlpNFC1Z@02tWaOZqj4XtQfQ/ZM3WtQWds@umtye3ltPCJrm2TokaPmCljFWMSjRTnaa4T2t1VO9uWaDHc@9@JLtKEF6BHElso630v0Bg2dwe7Fv7uqNm1NyR3NuuhjYpqAnkyQm5O0d0j/QcJ/snTyO6FnB8@OoqewvYt4bVe7MZmCQiPvZs6@E7sIsINHQ2JO9O1g9YGJHNVWTU0uGh3Wt/E4bgx2sRIj6UIn@V2gyLv2YXqTODaBCueJsCs3pWtrxf1l5P5V2rH/XWxBvd7SXNlKRlKXtKFZlM3HF7GXPT7YadtQnl8F4s/AeISVqED09IHXRUPBYfoQinv2P1Wtlom@Qh3roxnq1h3NsKGeTK5O0mLA9xPvZMcnSCb@7x4Drk/2HpkSi7Yhdu0SkxrD7J6W1lQNrWPhxLG55caNxrdF8MYpj@dDy4Om@8bnQGH0IiqtwqvExuHaFe2olzs8UmLy0HGjDo/r5lnAQ5ufIITHkNw0LT92Cb@2ZqsZm0c0D4PYEUpaCC/QDzi8d0rLJD04yBCU8glSkGaV2DTCoe595g1nM6XdoCUCW8ic@iZpNsNEfPo0vCZ498@Tz/jstNut5jD/nHamGUkYabNWKssaoUYi8LbUyfAwyGGMHj5sEl6nu2HaUKhHshAv3aBYV6K8tquaZ97rNi3J8FexwF2g9x9AOybyfS9vIx6TuFt@DqGFtPl3Bo@lRRxogYA7JB1vmERaa@wUQxteubu0oXWwO38ORcKF1Fo5aNCH4RJig88ST8D3yyTPsvh8OcfidMyrsOSXRPqziQmsxqVHejNjH/8F "Kotlin – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 67 bytes
```
for i ({$1..$2})((i%8))||i=`tr -dc !-/:-~</*/ur*|head -c$#i`&&<<<$i
```
[Try it online!](https://tio.run/##BcHRCkAwFADQX7ky2tSsS0q6/oW2afdJDS@MX59z7iPkw5@AOAB2fd72CAzyEdi2onuVlFyNSqXE83JG0M5Coc2kPzKNuWKTgl8daCtKXuqaiATn/AM "Zsh – Try It Online")
Feels pretty long, but so are most answers to this one.
[Answer]
# Python 2, 180 Bytes
```
from random import*
def f(a,b):
for i in range(a,b+1):
if i%8<1:
k,i=str(i),''
for _ in k:i+=choice([chr(j)for j in range(33,48)]+[chr(j)for j in range(57,126)])
print i
```
EDIT:
Thanks @Flp.Tkc for realising I hadn't read the task properly.
Thanks @Caleb for pointing out I could use a few to reduce the byte count.
Thanks @Dennis for pointing out about the fact that numbers can't be included.
EDIT 2:
The current version could probably be simplified more than it is.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~82~~ 89 bytes
```
$a,$b=$args;$a..$b|%{($_,(-join[char[]](33..47+58..127|random -c "$_".Length)))[!($_%8)]}
```
[Try it online!](https://tio.run/nexus/powershell#@6@SqKOSZKuSWJRebK2SqKenklSjWq2hEq@joZuVn5kXnZyRWBQdG6thbKynZ2KubWqhp2doZF5TlJiXkp@roJusoKQSr6Tnk5qXXpKhqakZrQjUq2qhGVv7//9/Q0PT/4ZGxgA "PowerShell – TIO Nexus")
] |
[Question]
[
## Objective
Create a function to reverse string concatenation
## Input
Two strings (alphanumeric + spaces), where one should be subtracted for the other.
* You can assume that the string to be subtracted will never be larger than the other one.
## Output
The result from the subtraction
## Subtraction
You should remove one string from the start or the end of another string.
If the string is present in the start and in the end, you can only remove one, which one will be removed is up to you.
If the string isn't in the start or in the end, or isn't an exact match, it is an invalid subtraction and you should output the original string.
## Test Cases
### Valid Subtraction
```
'abcde','ab' -> 'cde'
'abcde','cde' -> 'ab'
'abab','ab' -> 'ab'
'abcab','ab' -> 'abc' or 'cab'
'ababcde','ab' -> 'abcde'
'acdbcd','cd' -> 'acdb'
'abcde','abcde' -> ''
'abcde','' -> 'abcde'
'','' -> ''
```
### Invalid Subtraction (returns original string)
```
'abcde','ae' -> 'abcde'
'abcde','aa' -> 'abcde'
'abcde','bcd' -> 'abcde'
'abcde','xab' -> 'abcde'
'abcde','yde' -> 'abcde'
```
### Invalid Input (don't need to be handled)
```
'','a' -> ''
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# Java 8, ~~46~~ ~~45~~ ~~44~~ 40 bytes
-1 byte thanks to TheLethalCoder
-1 byte because I'm dumb (thanks Rod!)
-4 bytes thanks to Kevin Cruijssen
```
a->b->a.replaceFirst("^"+b+"|"+b+"$","")
```
[Try it online!](https://tio.run/nexus/java-openjdk#dVNNb8IwDL33V1jRDu1aKti1Awkm7bbTjoxJThtYpn4pSdEQ47cz94M2jJJDEtvvvcSxc5ZZWSgD37jHsDIyDR8jJ05Ra3hDmcPRARplxVMZgzZoaNkXMoGMou67UTLfrTeAaqe9DlyPFaSY8QRhDjhZ8MkCQyXKFGPxKpU2LvtkPvfZbzM/sIAxL3J6di9rhDYvqIUmnSMw5HEiWFBvWNCjB3ez2P4ad4u@JxMnFGh1RuW7zUjEdv63B/o4F3HUze9c4udO7ofrqzXKrLdP1utuC@XK3ICkR51GIP0ZPA8vHaYi35kv8oM/hye7qE1pDtqILCwqE5ZUJJPmLvtgDHyrVmu5IZvcAdyG/FkXhMmiC6sqd9t2CQYoiVxZxPNaYt0qfV7OMF83adtDjfYKeHCxqVGntjGzE1TCVCoHHnK3xnkhug0ksk6hnIXaUiNTjw/MJfDuMwC/A19a8Mv5Fw72nNP5/Ac "Java (OpenJDK 8) – TIO Nexus") (includes all test cases)
A Java answer actually beats a few other practical languages. *Smiles. (and now it beats JS!)*
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (Try It Online!), 12 bytes
```
~cpĊh.∧Ċtw|w
```
[Try it online!](https://tio.run/nexus/brachylog2#@1@XXHCkK0PvUcfyI10l5TXl//8rJSYlp6Qq/VdKTlECAA "Brachylog – TIO Nexus")
Takes the string to subtract from from standard input, and the string to subtract as a command line argument.
## Explanation
```
~cpĊh.∧Ċtw|w
~c Split {the input} into pieces
p and (possibly) rearrange those pieces
Ċ such that there are two pieces
h and the first
. matches the command line argument
∧ then
w print
t the last
Ċ piece.
| If all else fails,
w print {the input}.
```
[Answer]
# JavaScript (ES6), 41 bytes
```
s=>t=>s.replace(eval(`/^${t}|${t}$/`),'')
```
Takes input via currying syntax, i.e. `f("abab")("ab")`.
[Answer]
# [Retina](https://github.com/m-ender/retina), 21 bytes
1 byte thanks to Martin Ender.
```
(.*);(\1|(.*)\1$|)
$3
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/ivoaelaa0RY1gDYsQYqtRocqkY//@fmGSdmJScksoFxFAWWCgxCUInwxgwOYQ6GMWVCNeZCGUACSirAm5BJUwjAA "Retina – TIO Nexus")
[Answer]
# JavaScript (ES6), ~~76~~ ~~70~~ ~~45~~ 41 bytes
```
s=>t=>s.replace(RegExp(`^${t}|${t}$`),"")
```
---
## Try It
```
f=
s=>t=>s.replace(RegExp(`^${t}|${t}$`),"")
o.innerText=f(i.value="abcde")(j.value="ab")
i.oninput=j.oninput=_=>o.innerText=f(i.value)(j.value)
```
```
<input id=i><input id=j><pre id=o>
```
[Answer]
# [Perl 6](https://perl6.org), 21 bytes
```
->$_,$b {S/^$b|$b$//}
```
[Try it](https://tio.run/nexus/perl6#bY5dToNAFIXfZxU3DXVAB9AXY0pL3IO@WTUw3BoS/sLQpk3FxeijSzB96Ya6BDoDFKH6MnfmO@eeM0uBsLq1uEPiDVzwNECYVaarvTLNh@2D/aL575qv2XZZKcd9gaKAGURhgkI3rNjLJlsC8LH/jidvYMNh90kPuy@Y6jA1n@izewmG21GblGQpGx9likOyyEvgqo50yCLN23TTBX0eJmHB5jnG6QrZHNcZ8gIDA1RZKEB9VK89jcVgcPIwEFkeJsUCRuOba8FgfCdAhco5YtDfYl3u/sfKMI9IWVHP5wFSJidVW1S9SEfVWWMpKyrHr7VlfAB55xzmNm@p8EDe6uhWkKDX2Mxa6dFhRgf6e3jWc@Le/9zv@s@E9Z8ft8ImGFQcAQ "Perl 6 – TIO Nexus")
## Expanded:
```
-> $_, $b { # pointy block lambda
S/ # Str replace and return (implicitly against 「$_」)
| ^ $b # starting with the second argument
| $b $ # or ending with the second argument
// # replace with nothing.
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ 9 bytes
```
k"^|$"¬qV
```
[Try it online!](https://tio.run/nexus/japt#@5@tFFejonRoTWHY//9KiUnJKalpSjoKSiAKAA "Japt – TIO Nexus")
[Answer]
# TI-Basic (TI-84 Plus CE), 63 bytes
```
Prompt Str0,Str2
inString(Str0,Str2
If Ans
sub(Str0,1,Ans-1)+sub(Str0,Ans+length(Str2),length(Str0)-Ans+1-length(Str2→Str0
Str0
```
[Answer]
## Mathematica, 162 bytes
```
(c=Characters;a=c@#;b=c@#2;l=Length;t={};If[l@Intersection[a,b]==l@b,If[MemberQ[Partition[a,l@b,1],b],t=a;Table[t=DeleteCases[t,b[[i]],1,1],{i,l@b}]],t=a];""<>t)&
```
test input style ["abcde","ab"]
[Answer]
# Python, ~~69~~ ~~68~~ ~~64~~ ~~57~~ ~~51~~ 45 bytes
This ended up being a completely different solution with Regex.
*Thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194) for -2 bytes!*
*and [Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/) for the massive -6 bytes!*
```
import re
lambda s,c:re.sub(c+'$|^'+c,'',s,1)
```
[Try it online!](https://tio.run/nexus/python3#hZHLCsIwEEX3fsUIwiQaBLdCF/6HCHkVArWGTgQF/71OH1KtrW4yyb1nJpckz451oc/GaSBl95Xf0tUIu8HV44QbqxAVqZ1chHO8VAkqX2siz7tcoDbWeVRcUUKWATbHxbffrB3A5IfP57f2sWsHO5TQKqj4lkYZjRkF6YR3xjqW2iwvhJWpsF3tmCl/7obBmpzqZ5O9CP2PMEP2OeT24wV65O5GUWIVyiTwUBSQPCWwmjxBbDrdkh@6B3KxDmW8JiG3FIvAHfwVUspaG89zFHB9Ag "Python 3 – TIO Nexus")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~66~~ ~~61~~ 49 bytes
```
case $1 in *$2)echo ${1%$2};;*)echo ${1#$2};;esac
```
[Try it online!](https://tio.run/nexus/bash#@5@cWJyqoGKokJmnoKVipJmanJGvoFJtqKpiVGttrQXnK4P5qcWJyf///09MSk5JBZIA "Bash – TIO Nexus")
less golfed:
```
a=$1;
case $1 in
*$2) c=${a%$2};;
$2*) c=${a#$2};;
*) c=$1;;
esac;
echo $c
```
Uses case to test begining or end, and array prefix/suffix (% / #) substraction
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~31~~ 30 bytes
-1 thanks to [Zacharý](https://codegolf.stackexchange.com/users/55550/zachar%c3%bd).
This actually uses reverse (i.e. the inverse of) concatenation! Takes original string as left argument, and what to subtract as right argument.
```
{0::⍺{0::⍺⋄,∘⍵⍣¯1⊢⍺}⍵⋄⍵,⍣¯1⊢⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P7g0qaQoMbnkUduEagMrq0e9u6DUo@4WnUcdMx71bn3Uu/jQesNHXYuAorUgfncLkNRBEf7/X11ZWTksMSczRQFmZGZ@npU6l3piUnJKqjpMEMjFFANxQIJAOQx1WMSwmpicAhRFNhKb1TCLUISBIigcoEc888qI8QoWwxITMcWSsDmmAltAVILdh@QAz7yC0hIrdQA "APL (Dyalog Unicode) – TIO Nexus")
Ungolfed:
```
{
0::⍺{ ⍝ if an error happens, apply the following function on the arguments
0::⍺ ⍝ if an error happens, return the left argument unmodified
,∘⍵⍣¯1⊢⍺ ⍝ inverse-append right argument on left argument
}⍵
⍵,⍣¯1⊢⍺ ⍝ inverse-prepend the right argument on the left argument
}
```
Legend:
`{`…`}` anonymous function
`⍺` left argument of the current function
`⍵` right argument of the current function
`0::`… if any error happens, execute this, else…
`⍣¯1⊢` inverse
`,∘⍵` concatenate *⍵* on the right
`⍵,` concatenate *⍵* on the left
[Answer]
# PHP, 54 Bytes
```
[,$x,$y]=$argv;echo preg_replace("#^$y|$y$#","",$x,1);
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/34d575ef526f172bb1b56d3f9b88dd5a6cab580f)
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
```
def f(s,c):v=len(c);print[s[v:],s[:-v],s][[s[:v],s[-v:],c].index(c)]
```
**[Try it online!](https://tio.run/nexus/python2#fZFNCsMgEIXXySmGQFBh0gNY2ouIi2Q0ECi2xCLp6VNNoe0iGReOvM/50bc6P8IoI5LS6XLzQZI6P@YpPE00SVuMRncpB2uyoMvJdEUne5qC80u@b9fxPkNEIJgCSCn6gZwXmKNQWMP/@sGy79GcdJzJQb4ruYy3tsxMn3jMd9C@@i3IVet7Bg7soAv7ta/yCKXrajMSmjZ708am3WxGEN1VYF0V14HU@gY "Python 2 – TIO Nexus")**
[Answer]
# [Haskell](https://www.haskell.org/), 49 bytes
```
f s a b|s==b=a|a/=b,h:t<-a=f(s++[h])t b|1<3=s
f""
```
[Try it online!](https://tio.run/nexus/haskell#bY3LCoMwEEX3fsWYVUKSPuhOnP5Bv8BmMdH6gCpiFGzx3632gbZ0M1zOPdzRmrRFHvVDH2oXU9XwQESGlJWyRyQj5dJd@ZnA6iNN0Jqn1ktpZ034/s7T@l7U/K/JyMbJhQm@/PigMQUHkz04RIs00BatyoM21IQpd9NCbkQ79fvwgM7LMGVsLKmoAKGk@gS8boqqhQ10Vdw1zQ0yARF/zadMzYEJBSsy328SJz/gHYRaMSbM@AA "Haskell – TIO Nexus") Usage: `f"" "abcdef" "ab"`. Alternatively, define `(-)=f""`and use like `"abcdef" - "ab"`.
This regex-free solution works by recursively splitting the string in all its pre- and postfixes and checking whether the string to be substracted matches one of them.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~72~~ 65 bytes
```
a,b=input()
l=len(b)
print[[a,a[:-l]][b==a[-l:]],a[l:]][b==a[:l]]
```
[Try it online!](https://tio.run/nexus/python2#@5@ok2SbmVdQWqKhyZVjm5Oap5GkyVVQlJlXEh2dqJMYbaWbExsbnWRrmxitm2MVGwsUAlEQESug3P//6onJScnqOuqJSeoA "Python 2 – TIO Nexus")
-7 bytes thanks to @FelipeNardiBatista
[Answer]
# C#, 88 bytes
```
s=>r=>s.StartsWith(r)?s.Substring(r.Length):s.EndsWith(r)?s.Substring(0,s.IndexOf(r)):s;
```
Compiles to a `Func<string, Func<string, string>>`.
[Answer]
### Ruby (lambda expression), 29 bytes
```
->a,b{a.sub /^#{b}|#{b}$/,""}
```
Yay for regex interpolation! Requires regex-safe subtrahends, but that's okay as per the challenge.
[Answer]
# [Tcl](http://www.tcl.tk/), 37 bytes
```
proc s {a b} {regsub "^$b|$b$" $a {}}
```
[Try it online!](https://tio.run/nexus/tcl#ZZB9bsMgDMX/zymeIg6wC/QkVSfxYVKkNImASJsYZ88caEuySQjMz89@lrfFzxoBSUJlJE9DWBX6T6F@hBI9hETKuesCRUQKkZUdWK20IUgFfnIDFT4BZ8t55etfH/LPHiWoUBuOuQ32KB@d9nuf5I1SPhTypxyetNXQsXNF8h/a/f6yr/NQhX2bdzs2sbMnqe9lJRBtMaMMwQ1TRXi4aaXJgFcavbzvoXHWkqdJE6udRbqG6N00QM@PRXrCNUC86kQrvEG00hsuF3zk4ggsK5v3CzuTqcY98wwaA50kVrrxJOnytv0C) (now running all tests)
Tcl is straightforward. `proc s {a b}` defines a function named `s` which takes parameters `a` and `b`. `regsub` substitutes `{}`, which is an empty string, for the value of `b` when it's at the start or end of `a`. The return is implicit.
[Answer]
# C, 96 bytes
It's common knowledge that string manipulation in C is cumbersome, as an extension golfing would be borderline masochistic. Sounds alright to me.
```
f(a,b,t,l)char**a,*b,*t;{t=*a;l=strlen(b);bcmp(t,b,l)?bcmp(t+=strlen(t)-l,b,l)||(*t=0):(*a+=l);}
```
One of the less readable programs I've written. Takes two inputs (despite how the function looks), a `char**` pointing to the string to deconcatenate and a `char*` which is the string to remove. The input pointer is edited in place and becomes the output (who cases about memory leaks anyway).
Example usage:
```
char *a = malloc(6);
strcpy(a, "abcde");
char *b = malloc(4);
strcpy(b, "abc");
f(&a,b);
printf("%s\n", a); // "de"
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~21~~ 32 bytes
```
{sub("^"$2"|"$2"$",z,$1);$0=$1}1
```
[Try it online!](https://tio.run/nexus/awk#@19dXJqkoRSnpGKkVAMiVJR0qnRUDDWtVQxsVQxrDf//T0xKTklVSEzigjCAGMhKTIKKwBgIVckpQCZQGRdMCKIDxFYAAA "AWK – TIO Nexus")
Original submission naively replaced text within first string, not just at beginning or end.
```
{sub($2,z,$1);$0=$1}1
```
[Try it online !](https://tio.run/nexus/awk#@19dXJqkoWKkU6WjYqhprWJgq2JYa/j/f2JSckqqQmISF4QBxEBWYhJUBMZAqEpOATKByrhgQhAdILYCAA "AWK – TIO Nexus")
Originally tried without the braces, but it required tricks to print out empty lines and or no-matches which ended up adding more bytes than this version.
[Answer]
# R, ~~20~~ ~~42~~ 41 bytes
```
pryr::f(sub(sprintf('^%s|%s$',b,b),'',a))
```
*-1 byte thanks to MickyT!*
Returns an anonymous function (which has arguments in the order `b,a`). Computes the string difference `a-b`. `sub` is a simple substitution that swaps the first occurrence of the pattern with, in this case, the empty string `''`. Constructs the regex with `sprintf` to match only at the beginning and end of string. Requires the `pryr` package to be installed.
On the TIO link, uses the more verbose `function(a,b)` definition for the function for four more bytes.
[Try it online!](https://tio.run/nexus/r#DcnBCcAwCAXQZRq@git0lYIKgVxsqcmtu9tc3@tn9RU@xx2kYpzLKJ93xOyEq@XX8oDYHgFEuTaruRoEruD6AQ)
[Answer]
# Common Lisp, 121 bytes
```
(lambda(x y)(cond((equal(#1=subseq x 0 #3=(length y))y)(#1#x #3#))((equal(#1#x #2=(-(length x)#3#))y)(#1#x 0 #2#))(t x)))
```
[Try it online!](https://tio.run/##ZZDLDoIwEEXX8hU3bQwziSY@1vgvhdZHglQFE9jw6zotPhBZzNDT0zvJFOWpvjyo9P6Cvb@BWnSMU4WUSJm8sE5BugIj@YJYXyRc/hhT8J9SWEExRkgynjMOHthgfH4@qpucze85n2a3cfwIdKHOmJMZhs96kKzgbBo0UGlv0kUoWO4Qej9XkOWAZFvmnFsTV0WFryyRu95NSXqd1fe8dlcRV9DbjEpXHZqjeCyqXutWqGb@Pghkk9HybbYchbctKZvgN3LB/AgTpT0B)
The usual wordy Common Lisp!
Ungolfed version:
```
(defun f(x y)
(cond ((equal (subseq x 0 (length y)) y) ; if x starts with y
(subseq x (length y))) ; return rest of x
((equal (subseq x (- (length x) (length y))) y) ; if x ends with x
(subseq x 0 (- (length x) (length y)))) ; return first part of x
(t x))) ; else return x
```
[Answer]
# [Kotlin](https://kotlinlang.org), 91 bytes
```
{a,b->val v=b.length
if(a.startsWith(b))a.drop(v)else if(a.endsWith(b))a.dropLast(v)else a}
```
[Try it online!](https://tio.run/##dY@xDoIwEIb3PsWFqU2AByCCcXNgc3C@pgUaayFtwRjCs9cK4mDiDXd/8v3Dd7fea2VCMxq4ozIUbesKOFmLz8PFW2XaisFMIM6EGtzIC6AbSGG7DLLqE6EMM6Y8q97dqeS5lqb1HVENxdx5tN5dle8oZwxzYfuBTkxqJ2EtSCN@cI3O7xVcwm6BUIKVKGplJGVwLCBJvor8HxyioafxAxoVGSNLOEute3j0Vguy7hc "Kotlin – Try It Online")
[Answer]
# Powershell, ~~34~~ 40 bytes
*+6 bytes when `Invalid Subtraction` test cases added*
```
param($s,$t)$s-replace"^$t(?!.*$t$)|$t$"
```
Comment:
The regexp expression `^$t|$t$` does not work as expected: it replaces both matches instead one (flag `g` always on). So, we are forced to use the negative lookahead group.
Test script:
```
$f = {
param($s,$t)$s-replace"^$t(?!.*$t$)|$t$"
}
@(
,('abcde','ab', 'cde')
,('abcde','cde', 'ab')
,('abab','ab', 'ab')
,('abcab','ab', 'abc', 'cab')
,('ababcde','ab', 'abcde')
,('acdbcd','cd', 'acdb')
,('abcde','abcde', '')
,('abcde','', 'abcde')
,('','', '')
,('abcde','ae', 'abcde')
,('abcde','aa', 'abcde')
,('abcde','bcd', 'abcde')
,('abcde','xab', 'abcde')
,('abcde','yde', 'abcde')
,('','a', '')
) | % {
$s,$t,$e = $_
$r = &$f $s $t
"$($r-in$e): $r"
}
```
Output:
```
True: cde
True: ab
True: ab
True: abc
True: abcde
True: acdb
True:
True: abcde
True:
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 57 bytes
Whegh, this is a mess in QBIC/QBasic...
```
B=@ `+B┘x=instr(;,;)~x|?_t_sB,x-1|+_sB,x+_lC|,_lB|||\?B
B=@ `+B Prepend a string to B$. Thisis a hack to avoid errors with
removing substrings stating at index 1
┘ Line-break in QBasic output
(;,;) Read the string (B$) and the to-be-removed substring (C$)
x=instr And make x to be the starting index of the first C$ in B$
~x| IF X <> 0 (ie C$ is present in B$)
? PRINT
_t trimmed version (drops the prepended space)
_sB,x-1|+ of a substring from 1 to x (the start of C$) -1
_sB,x+_lC|,_lB and the rest of the string, starting after C$
_l takes the length of a string
||| End TRIM, end Substring, end Length
\?B When missing C$, just print B$
```
[Answer]
# [Lua](https://www.lua.org), ~~71~~ 65 bytes
Accepting suggestions
```
a,b=...p='(.*)'print(a:match('^'..b..p)or a:match(p..b..'$')or a)
```
[Try it online!](https://tio.run/nexus/lua#@5@ok2Srp6dXYKuuoaelqV5QlJlXopFolZtYkpyhoR6nrqeXBJTVzC9SgAkWgIXUVdTBgpr///9PTEpOTAKSAA "Lua – TIO Nexus")
[Answer]
I initially misread the instructions. Thanks, [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen) for pointing out my mistake!
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 46 51 bytes
```
Function F($o,$a){([regex]"^$a").replace($o,'',1);}
```
[Try it online!](https://tio.run/nexus/powershell#@@9Wmpdckpmfp@CmoZKvo5KoWa0RXZSanloRqxSnkqikqVeUWpCTmJwKklVX1zHUtK79/x8A "PowerShell – TIO Nexus")
[Answer]
# Excel, 129 bytes
```
=IFERROR(IF(FIND(B1,A1)=1,SUBSTITUTE(A1,B1,"",1),IF(FIND(B1,A1,LEN(A1)-LEN(B1))>LEN(A1)-LEN(B1),LEFT(A1,LEN(A1)-LEN(B1)),A1)),A1)
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~56~~ 53 bytes
```
s/^(.*),(.*)\1$/\2/
s/^(.*),\1(.*)$/\2/
s/.*,(.*)/\1/
```
[Try it online!](https://tio.run/##K05N0U3PK/3/v1g/TkNPS1MHRMQYqujHGOlzwcRiDEEUTExPC6xIP8ZQ////xCSdxKTklNR/@QUlmfl5xf91iwA "sed – Try It Online")
] |
[Question]
[
In your grandparents' day, dialing a phone number was done with a [rotary dial](https://en.wikipedia.org/wiki/Rotary_dial) like this:
![](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Rotarydial.JPG/220px-Rotarydial.JPG)
To dial each digit, put your finger in the corresponding hole, pull it over to the finger stop, and release it. A mechanism will cause the dial to spin back to its resting position, and the phone will disconnect and reconnect a circuit a specified number of times, making audible clicks.
Dialing the digit *N* requires *N* such “pulses”, except for N=0 which is ten pulses.
Rotary phones have the property that large digits (8, 9, 0) take longer to dial than small digits (1, 2, 3). This was an important consideration in drawing up early area code maps, and why New York City with its heavy population (and phone line) density got [212](https://en.wikipedia.org/wiki/Area_codes_212,_646,_and_332) (only 5 pulses), while while [907](https://en.wikipedia.org/wiki/Area_code_907) (26 pulses) went to sparsely-inhabited Alaska. Of course, this all became irrelevant when touch-tone dialing became popular.
# The challenge
Write, in as few bytes as possible, a program or function that takes as input a string (or sequence of characters) containing a telephone number, and outputs its number of rotary dial pulses. These are to be counted as follows:
## Digits
* Digits 1-9 count as that number of pulses.
* Digit 0 counts as 10 pulses.
## Letters
Note that digits 2-9 on the dial have letters of the Latin alphabet associated with them. These were originally intended for [named exchanges](https://en.wikipedia.org/wiki/Telephone_exchange_names), but were latter re-appropriated for [phonewords](https://en.wikipedia.org/wiki/Phoneword), and for text message input systems.
You must support having letters in your phone numbers, using the [E.161](https://en.wikipedia.org/wiki/E.161) assignment of letters to digits:
* A, B, C = 2
* D, E, F = 3
* G, H, I = 4
* J, K, L = 5
* M, N, O = 6
* P, Q, R, S = 7
* T, U, V = 8
* W, X, Y, Z = 9
You may assume that the input has already been case-folded, to either upper or lower case.
## Other characters
You **must** allow arbitrary use of the characters `()+-./` and space as formatting separators. You **may** chose to allow *any* non-alphanumeric character for this purpose, if it's easier to implement.
These characters do not contribute to the pulse count.
# Example code
A non-golfed lookup table and function in Python:
```
PULSES = {
'1': 1,
'2': 2, 'A': 2, 'B': 2, 'C': 2,
'3': 3, 'D': 3, 'E': 3, 'F': 3,
'4': 4, 'G': 4, 'H': 4, 'I': 4,
'5': 5, 'J': 5, 'K': 5, 'L': 5,
'6': 6, 'M': 6, 'N': 6, 'O': 6,
'7': 7, 'P': 7, 'Q': 7, 'R': 7, 'S': 7,
'8': 8, 'T': 8, 'U': 8, 'V': 8,
'9': 9, 'W': 9, 'X': 9, 'Y': 9, 'Z': 9,
'0': 10
}
def pulse_count(phone_num):
return sum(PULSES.get(digit, 0) for digit in phone_num)
```
# Example input and output
* `911` → 11
* `867-5309` → 48
* `713 555 0123` → 42
* `+1 (212) PE6-5000` → 57
* `1-800-FLOWERS` → 69
* `PUZZLES` → 48
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ ~~18~~ ~~17~~ 15 bytes
```
AÁ0ªā6+žq÷9š‡þO
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f8XCjwaFVRxrNtI/uKzy83fLowkcNCw/v8///P1pJW0lHQckQRCiACA0QYQQXA7M04bIFICIVRJiBCF0QYQoiDJCIWAA "05AB1E – Try It Online")
This is the first answer to use π. Why use π, you might ask? Well, the letters are associated with 22233344455566677778889999, in order. Notice how most digits repeat 3 times, but 7 repeats 4 times. You could say that each digit repeats (3+1/7) times, on average. I wonder if there’s any number that’s approximately 3+1/7 and takes fewer bytes than 22/7…
This only gives 4 7s, not 4 9s, so we still need to handle Z as a special case.
```
A # alphabet (abcdefghijklmnopqrstuvwxyz)
Á # rotate right (zabcdefghijklmnopqrstuvwxy)
0ª # append 0 (zabcdefghijklmnopqrstuvwxy0)
ā6+ # range [7..33]
žq÷ # divide by π (22233344455566677778889991010)
9š # prepend 9 (922233344455566677778889991010)
‡ # transliterate the implicit input with the two lists above
# this replaces z → 9, a → 2, … y → 9, 0 → 10
þ # remove all non-digits
O # sum
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 51 bytes
```
n=>n.Sum(x=>x>64?(x-59-x/83-x/90)/3:x>47?1-~x%~9:0)
```
Saved 1 byte thanks to @recursive
Saved 10 bytes thanks to @ExpiredData's observation that only `() +-/.` will be in the input
[Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrpOZV2KXZvs/z9YuTy@4NFejwtauws7MxF6jQtfUUrdC38IYSFgaaOobW1XYmZjbG@rWVajWWVoZaP635govyixJ9cnMS9VI01Ay1LUwMNB18/EPdw0KVtLURJO2NDQECf4HAA "C# (Visual C# Interactive Compiler) – Try It Online")
```
n => // Function taking input as string
n.Sum(x => // Map each value 'x' through the following
x>64 ? // If 'x' is an uppercase letter
(x-59-x/83-x/90)/3 // Take each char's ASCII value subtracted by 59, and subtract
// one if the char is 'S' and one if the char is 'Z'
: x>47 ? // Else if the char is a digit
1-~x%~9 // Take 1 - (-x - 1) % -10 (Maps 0 to 10, and 1-9 to themselves
: 0 // Else, 0
) // And sum it all up, then return it
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function.
```
+/'@ADGJMPTW'∘⍸+11|(1⌽⎕D)∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1tf3cHRxd3LNyAkXP1Rx4xHvTu0DQ1rNAwf9ex91DfVRRMstvl/2qO2CY96@4BCnv6PupoPrTd@1DYRyAsOcgaSIR6ewf/TFNQtDQ3VuYC0hZm5rqmxgSWYY25orGBqaqpgYGhkDBbQNlTQMDI00lQIcDXTNTUwMACLGupaGBjouvn4h7sGBasDAA "APL (Dyalog Unicode) – Try It Online")
`(`…`)∘⍳` find the **ɩ**ndex\* of each character in the following string:
\* elements that are not found, get the index 1+the maximum index, i.e. 11
`⎕D` the digits: `"0123456789"`
`1⌽` cyclically rotate one step left; `"1234567890"`
`11|` division remainder when divided by 11\*
\* this gives 0 for all non-digits
…`+` add that to the following:
`'@ADGJMPTW'∘⍸` the **ɩ**nterval **ɩ**ndex\* for each character
\* So [−∞,"@") gives 0, ["@","A") gives 1, ["A","D") gives 2, etc.
`+/` sum that
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
```
lambda s:sum([(n-59-n/83-n/90)/3,1-~n%~9][n<58]for n in map(ord,s)if n>47)
```
[Try it online!](https://tio.run/##FYhPC4IwHEDvfYofQrBBw801dVLd7BQUdYgwD4YNB/pz@Ifo4lc3uzzee@47VC0Gs9k/57poXmUBfdKPDckIMqUZ@rFcoDn15UawCdeTzjPcqTg3bQcIFqEpHGm7ctNTawAP24jOn8rWbxCJ6ywOYIhFNw6E0tnTQngrLw4jpiTXi0ZCglIKuAjkkgJIIAIKlzRkinP@XyzmnB1P53t6vS398H4 "Python 2 – Try It Online")
Does some arithmetic on the ASCII value for each character. The first option checks for letters and the second options checks for numbers. The clarification that all punctuation characters allowed in the input are ones with ASCII values less than 48 let me simplify the logic, but a new method altogether might now be better.
# [Python 2](https://docs.python.org/2/), 84 bytes
```
lambda s:sum(1+'1xxxx2ABCx3DEFx4GHIx5JKLx6MNOx7PQRS8TUVx9WXYZ0'.find(c)/5for c in s)
```
[Try it online!](https://tio.run/##FYjJDoIwFADvfsULF9sYtK9YFhMPLrgrCu7x4kZsopUIxvr1iHOameSb3Z6K53HzkN@Pj9PlCGkjfT8IVsqoC3ir3dFW1@/pen8w1GI0nmh7Ogu0M1@EkbtcrbW32e72rFyNpbqQM62J@PmCM0gFKc0/N3m/AjaSl1QZxESq5J0RSnPDQzRKhms7prCYV6iDFgghgCG3ikQgHDmFuW@bgjH2X6bLmNmbBBs/jIwf "Python 2 – Try It Online")
Uses a hardcoded lookup string, with each block of 5 characters corresponding to the characters giving each value starting with 1. Blank spaces are filled with `x`, which can't be in the input which is capitalized. Fortuitously, characters not appearing in the string produce `-1` for the `.find` which gives a summand of zero.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ... ~~76~~ 69 bytes
```
s=>s.replace(/\w/g,q=>w+=1/q?+q||10:parseInt(q,35)*.32-1|0||9,w=0)&&w
```
[Try it online!](https://tio.run/##dY1LSwMxFIX3/orQRUnMZPIymURJRbAWQdqiiA/cDGNalGFeKc4m/306bnXK5ZzF@T643/lPHoruqzmQqv70w84NwS1C2vmmzAsP6UdP90nrFj12nLbXuI2Rs8sm74K/rw6wTaRC56kUhEcWo016x9B83g9XRV2FuvRpWe/hDs4s5zOEzv7ORmdESWanWMYlUEoBxoWc4pgDKLhAYLvURDHGpiRODGPk7mHzsnx8Oi28vr3/wv8/jAYw0xaB2816RVbP6c2ajiagFBiscTbGYjm2xhfjGSywdpkajg "JavaScript (Node.js) – Try It Online")
-7 thanks @Arnauld!
### Explanation
```
q | 1/q | +q | parseInt(q,35)*.32 | parseInt(q,35)*.32-1|0 | Output
---+-------------+------+--------------------+------------------------+--------
0 | Infinity(T) | 0(F) | N/A | N/A | 10
1 | 1.0000(T) | 1(T) | N/A | N/A | 1
2 | 0.5000(T) | 2(T) | N/A | N/A | 2
3 | 0.3333(T) | 3(T) | N/A | N/A | 3
4 | 0.2500(T) | 4(T) | N/A | N/A | 4
5 | 0.2000(T) | 5(T) | N/A | N/A | 5
6 | 0.1666(T) | 6(T) | N/A | N/A | 6
7 | 0.1428(T) | 7(T) | N/A | N/A | 7
8 | 0.1250(T) | 8(T) | N/A | N/A | 8
9 | 0.1111(T) | 9(T) | N/A | N/A | 9
A | NaN(F) | N/A | 3.20 | 2(T) | 2
B | NaN(F) | N/A | 3.52 | 2(T) | 2
C | NaN(F) | N/A | 3.84 | 2(T) | 2
D | NaN(F) | N/A | 4.16 | 3(T) | 3
E | NaN(F) | N/A | 4.48 | 3(T) | 3
F | NaN(F) | N/A | 4.80 | 3(T) | 3
G | NaN(F) | N/A | 5.12 | 4(T) | 4
H | NaN(F) | N/A | 5.44 | 4(T) | 4
I | NaN(F) | N/A | 5.76 | 4(T) | 4
J | NaN(F) | N/A | 6.08 | 5(T) | 5
K | NaN(F) | N/A | 6.40 | 5(T) | 5
L | NaN(F) | N/A | 6.72 | 5(T) | 5
M | NaN(F) | N/A | 7.04 | 6(T) | 6
N | NaN(F) | N/A | 7.36 | 6(T) | 6
O | NaN(F) | N/A | 7.68 | 6(T) | 6
P | NaN(F) | N/A | 8.00 | 7(T) | 7
Q | NaN(F) | N/A | 8.32 | 7(T) | 7
R | NaN(F) | N/A | 8.64 | 7(T) | 7
S | NaN(F) | N/A | 8.96 | 7(T) | 7
T | NaN(F) | N/A | 9.28 | 8(T) | 8
U | NaN(F) | N/A | 9.60 | 8(T) | 8
V | NaN(F) | N/A | 9.92 | 8(T) | 8
W | NaN(F) | N/A | 10.24 | 9(T) | 9
X | NaN(F) | N/A | 10.56 | 9(T) | 9
Y | NaN(F) | N/A | 10.88 | 9(T) | 9
Z | NaN(F) | N/A | NaN | 0(F) | 9
```
All of `[space]().+-/` are not captured by `/\w/g`, so they won't affect the total.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~52~~ 51 bytes
*@Grimy gets credit for -1*
```
y/A-Z/22233344455566677778889/;map$\+=$_||10,/./g}{
```
[Try it online!](https://tio.run/##K0gtyjH9/79S31E3St/IyMjY2NjExMTU1NTMzMwcCCwsLCz1rXMTC1RitG1V4mtqDA109PX002ur//@PMtQ1NPiXX1CSmZ9X/F/X11TPwNDgv24BAA "Perl 5 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 39 bytes
```
1#.'?@CFILOSVZ'&I.+11|1+'1234567890'i.]
```
[Try it online!](https://tio.run/##RYxBC4JAFAbv/oqPgl5iu7yn7boKUhAKgmAkFASdoqW6dPBav33rlMeZgXkGP1YajBIcZK5ps901bdcPxzMtWp2IvCUhSbO1sbkrmB76EuJopkG@0oQVPiX8GEW36/0FDypE6A/O5spkXEwmlwzGGPBvOdlEsEwljbGvrTLMPCVRjlk1XX@qDwOFLw "J – Try It Online")
A port of [Adám's APL solution](https://codegolf.stackexchange.com/a/185999/75681)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes
```
T`WTPMJGDA`Rd
}T`L`2L
0
55
\d
$*
1
```
[Try it online!](https://tio.run/##K0otycxL/K@qoeGe8D8kITwkwNfL3cUxISiFqzYkwSfByIfLgMvUlCsmhUtFi8vw/39LQ0MuCzNzXVNjA0suc0NjBVNTUwUDQyNjLm1DBQ0jQyNNhQBXM11TAwMDLkNdCwMDXTcf/3DXoGAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`WTPMJGDA`Rd
```
Convert the letters `WTPMJGDA` to the digits `9..0`.
```
}T`L`2L
```
Shuffle all the remaining letters down by 1 and repeat until all of the letters have been converted to digits.
```
0
55
```
Replace `0` with `55` as they take the same number of pulses to dial.
```
\d
$*
1
```
Take the digital sum.
[Answer]
# [K4](https://kx.com/download), 44 bytes
**Solution:**
```
+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?
```
**Examples:**
```
q)k)+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?"911"
11
q)k)+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?"867-5309"
48
q)k)+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?"+1 (212) PE6-5000"
57
q)k)+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")?"1-800-FLOWERS"
69
```
**Explanation:**
Naive approach, likely pretty golfable. Lookup index of character, lookup score, sum.
```
+/(1+(1+&(5#3),4 3 4),!10)(.Q.A,1_.Q.n,"0")? / the solution
? / lookup
( ) / do this together
"0" / string "0"
, / join with
.Q.n / string "0123456789"
1_ / drop first
, / join with
.Q.A / "A..Z"
( ) / do this together
!10 / range 0..9
, / join with
( ) / do this together
4 3 4 / list (4;3;4)
, / join with
(5#3) / list (3;3;3;3;3)
& / where, creates list 0 0 0 1 1 1 2 2 etc
1+ / add 1
1+ / add 1
+/ / sum up
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 53 bytes
```
{sum +<<m:g/\d/X||10}o{S:g[<:L>]=$/.ord*.313-28+|0+9}
```
[Try it online!](https://tio.run/##HcxNC4JAFIXhvb/iItJo0@i9DmNqFrSolVDUougDCcw2iWG0CPW3T0y7857F87q3z0jXXxhVMNfd@1MDz7I6fQSXMjj2PeHQdPv0cc7SfHGdO4HftOXYlyRFGPMeeTLo9@0LlesUHlRNa7GEiE0sFkdToSQmZk9JglIKkEJpmhO4IYUebFeRUIhoThIxoljnm8Nqt2czy7C2U0D3twfb6MCWzPfZic30Dw "Perl 6 – Try It Online")
Multiplies the ASCII code with 0.313 instead of 1/3 and uses bitwise OR which rounds to zero to get [the correct bias](https://tio.run/##K0gtyjH7/784sVJBKVlBQSEPiLX0jA2NFUBA18hCQbvGQEHbUsmaC6xGFw8AqknLL1JQd1TX01OPUleo5uIsKMrMK0nTUFItVlBQNUoBEmZ6xmkICixkmBKTp6SjoBKvw8XJqZdflKKjACLBzkBiAh2DygO6DENA21LTmqv2/38A).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 94 89 86 80 bytes
Thanks to ceilingcat, nwellnhof and Rogem for the suggestions.
```
c;f(char*s){c=*s-48;s=*s?(c<10U?c?c:10:c-17<26U?(c-11-c/35-c/42)/3:0)+f(s+1):0;}
```
[Try it online!](https://tio.run/##bc/PS8MwFAfw@/6KR2GQNA3La9cfa1qHh3kSFGV4mDuUB60BrdLIPIz@68ZkePDgJe@bvPB5CcmByDnSPaOXbootP1MbW7mutPV1y6hBtd/SlmpUNUksm7TY@2OJKGmV5X5Zp3yV1YqLnlmBvFZ6dmb8hLfOjCyEbhoogeBDHPvNicN5ARBaRi986t8nZlqlQQjThNuaw8fk@z2LlhbaK1ia5zFKgnQ6mGMCPfuNnF@EC24PR2ghuo70X9MI4d8cbP@7y2D4H7eBtQEEmBezcxtEVxWlzDO1cSVmkOc5KEwzJxBYiimH@10hc6WUQ1kpJW9u7552D4/f1L92g3Xy6wc "C (gcc) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 256 bytes
You can replace the `(( … ))` constructs with `let` for identical byte count. There may be a good algorithm to reduce the case statements but not found it so far. With a bit of rework you could make it a function also (but not in same or less bytes unless you can discount the `function fname { … }` top and tail).
```
read p;while ((${#p}>0));do case ${p:0:1} in ([1-9]) ((d+=${p:0:1}));; ([0]) ((d+=10));; ([ABC) ((d+=2));; ([P-S]) ((d+=7));; ([W-Z]) ((d+=9));;([DEF]) ((d+=3));; ([GHI]) ((d+=4));; ([JKL]) ((d+=5));; ([MNO]) ((d+=6));; (?) d=$d; esac;p=${p#?};done;echo $d
```
[Try it online!](https://tio.run/##Nc9LC4JAFIbhfb/igC5mkIEzVnYZSrrYvZRaBEkLcwYMoiQXLcTfbkYz2@d7F@fckiKr67dKJOTik90fCgixSyuvxkipkC9Ik0KBXeZDHPIK7k8gMWeDK2066YzM0LSiWdA4Ry2T6UyTqyViJ1P1NJ3ZxdDgRySeBwsjbR0tV2tDHU2b7c5QV9P@EBry/uRTkCNbClBFkor8d7LlV81rTyVUmr3AlnXtcCAudylEgce6iNjirI/IFrvwHBxPXw "Bash – Try It Online")
A better solution using the map character technique makes use of the `tr` tool:
# [Bash with tr], 173 bytes
```
read p;p=$(echo $p|tr A-Z 22233344455566677778889999);while ((${#p}>0));do case ${p:0:1} in ([1-9]) ((d+=${p:0:1}));; ([0]) ((d+=10));; (?) d=$d; esac;p=${p#?}; done;echo $d
```
[Try it online!](https://tio.run/##NY69CsIwFEZ3n@KCGRJK4Cb9sW2oxUEnQdFBUBxqE6ggNrSCQ@2zx0jxG885w3er@sa5zlQarLIFoaZuWiD28@pgxc8gpQzDMIqiOI6TJFn4pWma@TH1bu4PA5SSYW7HJTKmdAt11Rsgg80xFyPcn0AvgmdX5jsdFH/hW@UN/rnAiZQMdEG0AtNX9e/PYOflqEC3T6Oma9q5QACVQjLYrxMeI@JM8BSRb7a70/pw/AI "Bash – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 24 bytes
```
7r32:ØP«9Ṿ€ØAżFyfØDV€o⁵S
```
[Try it online!](https://tio.run/##AUMAvP9qZWxsef//N3IzMjrDmFDCqznhub7igqzDmEHFvEZ5ZsOYRFbigqxv4oG1U//Dh8WS4bmY//8xLTgwMC1GTE9XRVJT "Jelly – Try It Online")
A monadic link taking a string as its argument and returning the number of pulses. Rewritten inspired by [@Grimy’s 05AB1E answer](https://codegolf.stackexchange.com/a/186035/42248) so be sure to upvote them!
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell),109 102 87 bytes
```
$(switch -r($args|% t*y){\d{$_}[A-Y]{("{0}"-f(.313*$_-18))[0]}[Z]{9}0{10}})-join'+'|iex
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0WjuDyzJDlDQbdIQyWxKL24RlWhRKtSszompVolvjbaUTcytlpDqdqgVkk3TUPP2NBYSyVe19BCUzPaILY2Oiq22rLWoNrQoLZWUzcrPzNPXVu9JjO14v///@qGuhYGBrpuPv7hrkHB6gA "PowerShell – Try It Online")
EDIT: Used @mazzy's idea for a regex switch with some string formatting to cast char -> int -> string and grab only the first 'digit'
**Original:**
```
[char[]]"$args"|%{$a+=(48,(('22233344455566677778889999')[$_-65],(58,$_)[$_-ne48])[$_-lt64])[$_-gt47]-=48};$a
```
I was hoping to get <100 bytes, so I'll keep looking at it to see if there is anything else I can do. There's probably a way to remove the number string
Sorry if this is confusing as I nested arrays with boolean indexing statements but -
**Explanation:**
`[char[]]"$args"|%{` reads the input casted as a string and then explodes it to a char array and begins a for-each loop with checking `()[$_-gt47]` to see if any `()+-./` was entered (all have ascii character values <48)
Note: Powershell accepts `$true` and `$false` as `1` and `0` respectively for array indices
Then we get either `48` for the symbols, or:
`('22233344455566677778889999'[$_-65],(58,$_)[$_-ne48])[$_-lt64]`
The `[$_-lt64]` checks for a number or a letter (all assumed capital here). If it's a letter, `'22233344455566677778889999'[$_-65]` changes it to 0-25 to index into the array and output the pulse value (as a char). If the character is a number, we instead look at: `(58,$_)[$_-ne48]` checking for `0` and outputting `58` or just the numeric char itself.
Around everything `$a+= ... -=48` initializes a numeric variable $a at `0` and then adds the output. The output is the ascii char value of a number, so subtract `48`.
Note: if the input was a symbol, we get `$a+=48-48`, effectively ignoring it. If it was `0`, we get `$a+=58-48` to obtain our +10
Lastly, `;$a` just outputs our final value post for-each loop
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~95~~ ~~85~~ 79 bytes
*inspired by [nwellnhof's answer](https://codegolf.stackexchange.com/a/186016/80745).*
*inspired by `[0]` from [Sinusoid's answer](https://codegolf.stackexchange.com/a/186776/80745).*
```
$(switch -r($args|% t*y){\d{$_}0{10}[A-Y]{"$(.313*$_-18)"[0]}Z{9}})-join'+'|iex
```
[Try it online!](https://tio.run/##TZFrT8IwFIa/71eckOJWupp2W3cxmog6vKEgiMiQEANTMERwmwEz9ttnHbrY99vzvL3kdLVch1E8CxeLHL3AEaQ50uL1PJnMgEYaeo5e420VktoXTp@mKRpnLOUsG9bpYJRWkLZvcrOGxpS7uDJkoyxIvSzD9G05f1eJup2HmzxTlGNNAbl0TfU4V3XgHP8B13aoMJknqeWW1OEmCCGAccP8MUZpCAfN4AaGtm9TwRiTWjil5tRljDaarb7f6Uple6Vq94Kg6Uv4756f8y1hO64H9ZPTM79xfnF5dd28uW217zrd@95D/3EQqLrGGeHEICaxiCA2cYhLPCBgEKOgZmGswoqiYRetXdwi3i4YKxi2UIW0eAOKdUDhZhVOknAqx4/GOxyF8ecikWBP/gqKCyjH/ctp@FFuwgdl@5DKakXJ8m8 "PowerShell – Try It Online")
Unrolled version:
```
$(
switch -r($args|% toCharArray){
\d {$_}
0 {10}
[A-Y] {"$(.313*$_-18)"[0]}
Z {9}
}
)-join '+'|Invoke-Expression
```
```
key .313*$_-18 "$(...)"[0]
--- ---------- -----------
A 2.345 2
B 2.658 2
C 2.971 2
D 3.284 3
E 3.597 3
F 3.910 3
G 4.223 4
H 4.536 4
I 4.849 4
J 5.162 5
K 5.475 5
L 5.788 5
M 6.101 6
N 6.414 6
O 6.727 6
P 7.040 7
Q 7.353 7
R 7.666 7
S 7.979 7
T 8.292 8
U 8.605 8
V 8.918 8
W 9.231 9
X 9.544 9
Y 9.857 9
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 21 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
éT6T&\²|└t5φ╛│█♪√┘↑▓^
```
[Run and debug it](https://staxlang.xyz/#p=82543654265cfd7cc07435edbeb3db0dfbd918b25e&i=%22911%22%0A%22867-5309%22%0A%22713+555+0123%22%0A%22%2B1+%28212%29+PE6-5000%22%0A%221-800-FLOWERS%22&a=1&m=2)
[Answer]
# [Kotlin](https://kotlinlang.org), 113 bytes
```
{s:String->var t=0
for(c in s){val v=c-'0'
t+=when(v){0->10
in 1..9->v
in 17..42->(v-11-v/35-v/42)/3
else->0}}
t}
```
[Try it online!](https://tio.run/##jVjtbhu3Ev3vp5gaRb1CVrJkWXZkXAdwU6dN68ZpPpomfwp6l5L2erVUSa4V3cBAH@Tel@uL5J4ZcldaBwWaH6HIPeQM5@PM0LfGl0X1@fCQnlqtvM5pZiz5ReEoW6iy1NVcn@3h88L7lTs7PMxMruemnA2cV9mt/ggUIIPMLA//OBw9nkynY4Y/NXXlyRqv7IbyQpW0qkunHRUVKVotTKWpqpc32jI6KaqsrPOimlOpvdfW9fZ4/XlFG1NbmltV5StldeXdAeVqk8qZjI@HMTqcR2vlKOfz14Vf4PuuEmVxK1C@4JmIeGPCF62yBX7NC59CVR/kziABJ0Jnv5B9mbFWu5WpRNeFKTWjy5IKT@YOUG8aaNzrvFmlBPXJ6lIrpwEd0AUtNVuucEvGrgsckakaX7E7KIST3AqSb2BmnhTeMRTiPcteGVf4wlThbN4VjMpHMS4vXGaqSmc@Cm9nlBU2q6GwYpxb6ayYFXB8NJ@ZkS@W2qW0VLdiYTjmpgzXL4vs1g3EcN9FBwSFYTd6ASl/1AU0xE9XZwuG/fXnf4Pn//rzfykhXvTKS4y9OB/SelHA6og1rysGB2Q4/1Vwm9zK0ULdBdusrFlp6zeYKE@lsnMdrgsNHCWPU5qmNOyRV7eaSiM@8NHH2CJi3BKR3W4ZpXSU0rg3oDcc9hw@AVYsV8Z6hTiG7VyRa6vY4hwOuVVrvny9QuDYcsNwhCdsi/SA4VYu@GW92NALvab3xt7S0wJqc1DK4RC90OoONzS4djg54T3Bj7Ct7snNNGRj49x4OhodUWKqckOTaKteykYM3pEfNB2eUnJ00nynNZImBJOyTpebvkivFuqm4HS/KJW7VQO6nkH3Gog0ZL8KYXSjM7VEzFqO3ju2xXqhkQ4G7u17VjQm4g44XMgGN76Bz1omkZV3FoJTIQJHMxjnZuPhYUwQ045DLQ2hCVcj8ZeEYJnVVSYWEq@zb2VDUXGqhjj2lh2SAOwQhbrKNIcyRFuVBUaR/K28KqpAHB5X2mWi4DJTexzqGh9ts@JLMuOI0chZeF5IxcACbMWKDcuXM2Vp1pFovpNwk5/4F2Y06k/DBobL3bbymmTY2UDDgJbLj4adfLkKxCm/Xxivw3ExyI8gR6wXyYXTiYGRbSXp8e0KYQi3lCtEh2adnMkKrgqBpECnQC2ba6@1hY0tJFTw7wbeQBrnAcwZXiEYcmpKBDLiBs6STQh3iAVdSDCqFSe1LdryI05ZG5vHLJKSpD96BoOZnJrr6Hq3cV4vowXem5qWtcNqveLM5VvulBSOOGZ1Ca0dt0NI7RomuxyMTkZ88WJeLZE5DIZxmiOESdiiZ40jL1L6NqWndE5HjadSukzpGVbGceX7lH5I6TlWjuPKjyn9lNIVViZx5eeUXqR0jZWTuPIypV9SepXSayyexsU3Kb1N6VesPI4r71L6LaX3KX3A4nRrCLXha9TLGAh8uWCzBRNcCbLKNyFpkc8ZClMf4QrvpXxJDV/DQbAjx6IFka5DpWZgsPa1ILb51XWB4shHYoBkLGcNl7YQZHJKu4uS3qP@4FDcDIZC0kre2CUiJLKK02Au5Y1FvjU3yxaGa6Vp5FRylcpUfQleOFbbItvKabuaUGUsmIYpaIYUP3CgcFeEMgHKLzX7vSUvp3e1zQ2ESD0A3SCc9U7Bl2QM@Rl2X35UfJzUBFm4EA25e0Kgl8bconx4BcILUd5wXCHV5@XGI0hDnL18e/X6ksPgU3Q6HYwOzmiUttMjTFHFDi7i@G0cn8rYwsaYjrH8XRwv4/hMxhZ2jOkxlr@P4w9xfC5jC5tgOsHyj3H8KY5XMrawE0xPsPxzHF/E8VrGFnaK6SmWX8bxlzi@iuNrGVv4Y0xR7Q/exPFtHH@VsYVNMUVHcPAujr/F8X0cP8jYwods1iFP7/FfqL@Rin8X1yZCHb8jwnpnzS6rfW0r0M4yCZ4azLVPYjOJXoSDL7RIoKDt/k6QxFLWFqCGX2g6GlH/CY1GzcLjk9P@ZDyc8upxwwJ0OhrTZDKh4ehoLF8aOqJHI/QDo6Mevbw86U@GwyF/njSEghL0eDjsP7u6fnf56jV/Opk2n16@/fDh6vJ1FMSrz9o6DI74uGpaz1Itb3IVKgReApxAkmmO21ZwRsWFsUZtsGiHTT7YQ6xzec9A5kmo3Gf0WsbeGbp@j0DfI@KqqWeqLgN9eRRg6Yv/o61pCwM37gG7zfbQsMeeIG0kcecN5J2y8ahzGmLOhySdvWFfLyghR1/k/2ZW8wvdkcIEVEndQ5vZYO9UWWu@OqNjiaGlcR4lsmljixY94@K5yx0pluY1V1aulqDu7rlozSqt8wcPtagRbNKgVZ6z7QM9hfsO5BuOiUedb3f2EfjyNRjm0blM@J@0e4lsaA0S/nErJ71g1yhOFthFaRcMbdr3ARqFtnnZgjgyd6bEmfhPBIL@yXA56oJjAu7KFbqXy3ShO@3Wdh2RMBoMpg@VCtv/mV5dlJRTrqCxn@BWm9sh9I/oFTrQpuEInQi8DUdyDMX2owtOTukbmobgOu5x6K25z7vDkwXN9cOj59bUq9jvoJcbYu@oKWzSF3bQbNtGmXCwq28835EpqQN1t8WqPZgFOzTM8lhF/3Ey6IL5XeDXpj0NpOKizjn2dsHjCZQ8PoJ6VV6Gd@AxqGbb2HXh/F1u2TxhRaEm9x4ozS@WkA8qhO7Y5m0ibWGLYhaugpfjophz79OIz826@uJ2cP@8uEPIoSQHYjyRWoaLoJJ10fL5aCzFLE6OQ@eLMkXfdMGoWBEzBauCBJq/GUR3P7AcoRS5QDl/E@KngwFM@yDIQ8b3R6O@/DgcT@KP46Pe4fifZiXoCT1cB6tL6bwQyEa76qDNTenhOsgvteW9DxUdtrN7MSVU2Yu/YZtYRV6FAt0pIqIvv0sti4glXL7uye5YNKTs/Yw347Y/C8S786wN9WwJUKLs3J3RhbVq869Q0J702mJ2FcokCie4yP3NUYGhV3Qe9oxQ1@WB/PmTOwsn9p9ICTsf7mF7kknF6n0SXj/PhMn9o3M2RHLX@zTsPwGLRirDzr3W5f0nyZ04WJwbHcsm7j8Z3t/v@fvPIZTRvfNjIbyZ4/N0Zs1SFEdfb2OW7X3BFy3fDej5jPmFw4H/wBKg6BLAfnhwhL98oZKGPw/BMIPwvFgXCJYA7tZwD6U@teUs9E7nouZVUemk99VXA2/esvinEJ/0BIp2PxHogE2NDDpHA9CL8eMXFg@J5/DCXJUXdl5zE3PZ6JPsxNz@tyoPIr/aD7vxdq18WSX7XwdNEPxff1oFWb17gMIVrncumHKftCo5ruRvPvF2/DwNFKadl8eWJMA9fvpsQYm21tgz0AuU5YdDL1qh1aDVLb5p89A/uUZVaXbkcEguC@evZ8k@Wsz9lPabxnJ/W7j3d9tKxnzRTO6CO60ko2MDud9rrLy1VNAhGIp/i51i4sK7IQc5pT7/Hw "Kotlin – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~134~~ 123 bytes
```
f=lambda n:sum(map(int,n.translate(n.maketrans('ADGJMPTWBEHKNQUXCFILORVYSZ','23456789'*3+'79','()+-./ '))))+10*n.count('0')
```
[Try it online!](https://tio.run/##VY1NT8JAFEX3/IrZvVfKlDcdpx8mLFSKKAUqiEB3o0I00qGBYeGvL4UFSe/unnOTW/7bn72RVbXt7XTx@a2ZuT@eCix0ib/GdoxnD9ocd9pu0HiF/ttcO8JD//l1nL0vH5PhaPK2WD0NXtLp7GM9z6EDvrxTQRjF0JYuhHFN0HG512Xg1HEFtY33tT8Zi0DgVOWhvsItQixEvWjdehSEXEmKGzAUkimlGAlfNoQrGPrCd1iWBFwRUcMKHhHxQTpdJrN5w2SLPE@TC6vO "Python 3 – Try It Online")
-11 bytes thanks to @dan04
] |
[Question]
[
This [impossible object](https://en.wikipedia.org/wiki/Impossible_object) is [Reutersvärd's triangle](https://commons.wikimedia.org/wiki/File:Reutersv%C3%A4rd%E2%80%99s_triangle.svg):
[![enter image description here](https://i.stack.imgur.com/Ec4du.png)](https://i.stack.imgur.com/Ec4du.png)
Draw your own version according to these rules:
* Exactly 9 cubes total
* Each side is made up of exactly 4 cubes
* The cubes appear to overlap such that the rendered object is in fact an impossible object
* 4 distinct colours are used - one for the background and 3 for each of the faces of the cubes
* In bitmap output, the full triangle should be at least 100 pixels tall and at least 100 pixels wide
* Aspect ratio: the width and height of the full triangle should not be off by more than a factor of 2
* The triangle may be rotated by any amount relative to the above image
* The triangle may or may not be reflected relative to the above image
[Answer]
# Mathematica, 237 bytes
```
n={-1,1}#&;c_~g~s_:=Polygon[c+s#&/@{k={12,9},m=n@k,t={0,-12}}];p={#,#2~g~1,#3~g~-1}&;a=p[Cyan,#-k,#+m]&;b=p[Blue,#-t,#+k]&;c=p[Red,#-m,#+t]&;Graphics@{{a@#,b@#,c@#}&/@{j=4k,s=4{4,9},n@s,4m,r={-32,8},q=-4{4,5},4t,n@q,n@r},a@j,b@s,c@j,c@s}
```
Easier-to-read version:
```
1 n = {-1, 1} # &;
2 c_~g~s_ := Polygon[c + s # & /@ {k = {12, 9}, m = n@k, t = {0, -12}}];
3 p = {#, #2~g~1, #3~g~-1} &;
4 a = p[Cyan, # - k, # + m] &;
5 b = p[Blue, # - t, # + k] &;
6 c = p[Red, # - m, # + t] &;
7 Graphics@{
8 {a@#, b@#, c@#} & /@
9 {j = 4 k, s = 4{4, 9}, n@s, 4 m, r = {-32, 8},
10 q = -4{4, 5}, 4 t, n@q, n@r},
11 a@j, b@s, c@j, c@s}
```
Line 1 defines a function `n` that negates the first coordinate of an ordered pair. Line 2 defines a function `g` that produces a (roughly) equilateral triangle centered at the point `c`, and pointing down or up depending on whether `s` is `1` or `-1`. Line 3 defines `p` to be a parallelogram template consisting of a color and two triangles, and lines 4–6 define `a`, `b`, and `c` to be the three different specific types of parallelograms that appear in the cubes.
Line 8 defines a function `{a@#, b@#, c@#}&` that draws an entire cube centered at the point `#`; lines 9 and 10 apply that to the nine points needed to make the larger triangle. This produces nine cubes, starting at the upper right and going counterclockwise, where the later ones cover up parts of the earlier ones. Finally, line 11 redraws four parallelograms (in the upper right of the picture) so that they end up covering the later cubes as they're supposed to. The output is below:
[![enter image description here](https://i.stack.imgur.com/3xOue.png)](https://i.stack.imgur.com/3xOue.png)
[Answer]
# Brain-Flak, ~~487810~~ ~~327722~~ 75564 + 1 = 75565 bytes
Unfortunately this is a tad big to fit in an answer.
[PasteBin](http://pastebin.com/WqRM1HNY)
[Try it Online](https://tio.run/nexus/brain-flak#7Z1rbhsxDISvs/rRGwQBeo4gJzF8djcvJ/ZaAbyudkQOvyQ/Cu@iAsfU6EFyeFo@ftr7bzscf/6ens8ffz1YDseXpb0@/Xz8@WB5e/Pz/dYeffbcjofjcvXG2yt3jdoeeXIeD/uwL7J9D4w30MozGUi@wwH/5YV5DazACqxmYfX9wJebPz7fZYQLm6xXNxAEwRIIXjL5XeOlxFGC5f3jZFuDwQ/8/PE7j7PYnmetmZDVBAzBEFZ8FEmNP4If@IFfUvyuX/CNWu33nU30RRAEwWoICjmROP6wvbY0sibyEixLOrMnxAXwESwraZlolZk1r1mx8f96lgk8v0pGBP7PyhYwB3pDbIQIfyD/Zz8Ca1We2azaWFZ2Zt@f8UqMgVUNy5jVv2cCjJjG@AKWcZbeUpcXeAY7r8HsL@CngZoAcey7c5@dds5hXwn7xOtozvMtvoJ9zPUK9QN4CvY5zfRGNApvwT5me/msEnwF@3zsE@d@s7YzH7CP@c7qzmzAPg/7Gqs7/pLiZJss0s5cn7Wyx4lqxMmLiIZf/EwqFLKVDCjNbJqhSmg5i2HBVLHxIZnuQdX8XFnRWZ9Qti@Mpx2cjROlCLpzopvas5QZ1RrW93JUzr0izOiH4DhuXEzv@GDGpMyo3DGGirMmZEUVI/pzop2GtpwXhZzoHUuFF73wG8eL5tFgOBFO3BbLbP87oCcDTlKSNt@1OXLU9Xi@veS0@VvrYwyIjkH0csKbKmmLVVome6o3qt@bMtuODmI13nUg3ZlXxWvVj6/iqfk91RbVaya33a1K68zXyyOIDmTVxDczAdV9l0pnADmqX5Ca9hVU69j671TliE67qxp8@TaNU0IrwKZl6jl3C@ZZk3isE7JTvVZXGyvfubXNI4JrlfNbcGwTn@Hw2hh8sKjXr7PP2jPtMi9WZs8HxCDw2mx8MAPXnNGdyLjW2neRQ4PXplPVEvbIjJYjWLfXbkQVp/UUKKDlZDn3xlZMVMi5G4iVobrbZF5Q6xlZcYJtZaRW78dT02ICe9jXcTsyiKcOj1IVB/7Iyx/a/Ycbc7hyh1Zt0JNB5NUjBVQH/fhDwyCuOw@4Iy93yHt3JdRacVWVt9Wn08ZOBvr0KqV5KdHvIjUn6POxnSyb0rFrj9laQO0kba@6cKpDncsm7@pYaWbqzpWj07KWel5jzTRSrtm5nmKaDs/N1ba7uskiZxtH23riDQV0MWRes1jadluQ6676oc3vU@5rhPWFt15jzjTanY2nbR2veR/Ql22Up42kOuZbPSe3mnJYXQ7tHXwE5imgNpBtzcJ7yumrtFnM0ziTp0d3Uo@4St5jrDcyM5eG2ENudMetknhPNQWOcbvXbb6j8pyeML8/8zSvO54pWT6FPFSvJ4Kiwe45iOG@ka48WQH9Dir1w@d0lvF/tU4FNeahYx/CCulu80F7lQUqpXOoBFSZAUr@dzyB@nm/Moe4To07vo/vx/F9eVzJscpQlxXQlxMyzYSec9u6Ko@mv/wO6HpXC7Wpnpu6tj9mvVJvkS5QfTIPW7okj2aGTxsTd4OKWSfyC770jgXhTL1OY6Ds3J3TZp0D4aJdD41OGWBctKec0R0PCJfrgtY/nLfjgU5XVvg6dgzq9fY9FsjyqYOtW5@JLqoFMtPqIJtXn7zfd7pQ5eRwhV3xPvXi54a4bz57/9fLbej/ddubq@uRLxA6iYen0@nP338)
With the `-A` flag this outputs an ASCII ppm file that looks as follows:
[![New output](https://i.stack.imgur.com/XoHnl.png)](https://i.stack.imgur.com/XoHnl.png)
# Explanation
You may have already guessed I did not write this by hand. So here's how I did it:
I first made the image you see above from the image provided by the challenge. It has the distinction of having no color channel that is at any value other than `255` or `0` this way we can wrap it up into a smaller file with the max color channel set to 1. I then wrote a python script to golf a Brain-Flak program that solves this using a module I wrote myself that can be found [here](http://pastebin.com/zbbn5vJ0). Its not very polished its just a hack I threw together for things like this. `push` is a function that returns efficient Brain-Flak code to push a number to the stack and `kolmo` is a very simple Kolmogorov complexity solving program that attempts to find an efficient way to push a particular string to the stack.
```
from value import push,kolmo
def group(a, n):
return zip(*[a[i::n]for i in range(n)])
f=open("R.ppm")
a=["".join(x)for x in group(f.read().split()[3:][::-1],3)]
f.close()
def hardcode(string):
result = push(ord("\n")).join("(<>({})<>"+{"0":"","1":"()"}[x]+")"for x in string)
return result
last = ""
acc = 0
result = push(ord("0"))+"<>"
for x in a+[""]:
if x != last:
string = ("" if not last else kolmo("\n")+hardcode(last))
result += min([push(acc)+"{({}[()]<%s>)}{}"%string,acc*string],key=len)
acc=1
else:
acc += 1
last = x
print result+kolmo("P3 100 100 ")
```
This was quite fun and I hope to improve my answer
[Answer]
# HTML + CSS 3D (855 ~~866~~ bytes)
HTML *117 bytes* + CSS *738 bytes*
To keep the `z-indexes` in order was a bit tricky. ;)
```
/* CSS */
p{position:absolute;left:110px;top:0;width:50px;height:50px;transform-style:preserve-3d;transform:rotateX(-45deg)rotateY(21deg)rotateZ(20deg)}
p+p{left:140px;top:50px}
p+p+p{left:170px;top:100px}
p+p+p+p{left:200px;top:150px}
p+p+p+p+p{left:140px;top:150px}
p+p+p+p+p+p{left:80px;top:150px}
p+p+p+p+p+p+p{left:20px;top:150px}
p:nth-child(8){z-index:1;left:50px;top:100px}
p:nth-child(9){z-index:-1;left:80px;top:50px}
p:nth-child(10){z-index:1;left:67px;top:59px;transform:rotateX(-45deg)rotateY(21deg)rotateZ(20deg)scale(0.6)}
a{position:absolute;width:50px;height:50px;background:red;transform:rotateY(0deg)translateZ(25px)}
a+a{background:tan;transform:rotateY(-90deg)translateZ(25px)}
a+a+a{background:navy;transform:rotateX(90deg)translateZ(25px
```
```
<!-- HTML -->
<p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a>
```
I've kept the new lines for better readability. Maybe somebody spots potential for more golfing. However, they are not included in the byte count.
## Result
[![enter image description here](https://i.stack.imgur.com/4UMFT.jpg)](https://i.stack.imgur.com/4UMFT.jpg)
## jsFiddle Demo
[Try it yourself](https://jsfiddle.net/eh2mgjfn/)
Use Goole Chrome. Other browsers may have [problems with the `z-indexes`](https://stackoverflow.com/q/5472802/1456376).
## Edit
* Saved **2 bytes** by removing the duplicate `a`-selector, thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions).
* Saved **9 bytes** by removing an unnecessary `margin:0` on the `a`-element.
[Answer]
# BBC BASIC, 147 bytes
tokenised filesize 129 bytes
```
t=PI/1.5x=500y=x:FORi=0TO28b=i MOD3GCOL0,b:b*=t:a=i DIV9*t:IFb=0x-=99*COSa:y-=99*SINa
MOVEx,y:VDU25;66*COSb;66*SINb;28953;66*COS(b-t);66*SIN(b-t);:NEXT
```
2 bytes saved by using an absolute coordinate specification (`MOVE`) and two relative specifications per parallelogram, instead of changing the origin in order to be able to use all absolute specifications. 1 byte of unnecessary whitespace eliminated.
# BBC BASIC, 150 bytes
tokenised filesize 127 bytes
Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html>
```
t=PI/1.5x=500y=x:F.i=0TO28b=i MOD3GCOL0,b:b*=t:a=i DIV9*t:IFb=0 x-=99*COSa:y-=99*SINa:ORIGINx,y
L.66*COSb,66*SINb,0,0PLOT117,66*COS(b-t),66*SIN(b-t)N.
```
**Explanation**
We start with the coordinates at top right and plot rhombuses in groups of 3. Before each group of 3 we move the origin (West, West, West, SE, SE SE, NE, NE NE.) That means that the group of 3 at top right is the last complete group to be plotted, bringing the origin back to its original location. We then continue and plot the black and red (but not the green) of the first group again, a total of 29 rhombuses.
**Ungolfed**
```
t=PI/1.5 :REM 120 deg
x=500 :REM coordinates of top right corner
y=x
FORi=0TO28
b=i MOD3:GCOL0,b :REM set colour 0=black,1=red,2=green
b*=t :REM convert b to a multiple of 120deg
a=i DIV9*t
IFb=0 x-=99*COSa:y-=99*SINa:ORIGINx,y :REM before each group of 3 rhombs move the graphics origin
LINE66*COSb,66*SINb,0,0 :REM define one side of a rhombus
PLOT117,66*COS(b-t),66*SIN(b-t) :REM define one further corner and plot the rhombus
NEXT
```
**Output**
[![enter image description here](https://i.stack.imgur.com/Wvy6z.png)](https://i.stack.imgur.com/Wvy6z.png)
[Answer]
# HTML + JavaScript (ES6), 351 ~~374 384~~
```
<canvas id=C></canvas><script>c=C.getContext("2d");`133124222162184253104213162164244191224182133191064104222093164253122224284151284`.match(/.../g).map((v,i)=>(c.fillStyle=['#fc0','#f04','#08a'][a=i%3],c.beginPath(),c[l='lineTo'](x=5*~~v/10,y=v%10*25),c[l](x-10,y+(--a+!a)*17),a&&c[l](x-30,y+a*17),c[l](x-20,y),!a&&c[l](x-10,y-17),c.fill()))</script>
```
*Less golfed*
```
<canvas id=C></canvas>
<script>
c=C.getContext("2d");
[133,124,222,162,184,253,104,213,162,164,244,191,224,182,133,191,64,104,222,93,164,253,122,224,284,151,284]
.map((v,i)=>(
a = i % 3,
x = 5 * ~~ v / 10,
y = v % 10 * 25,
c.fillStyle = ['#fc0','#f04','#0a8'][a],
c.beginPath(),
--a,
c[l='lineTo'](x, y),
c[l]( x -10, y + (a+!a) * 17),
a&&c[l](x - 30, y + a * 17),
c[l](x - 20, y),
!a&&c[l](x - 10, y - 17),
c.fill()
))
</script>
```
**Test**
```
<canvas id=C></canvas><script>c=C.getContext("2d");`133124222162184253104213162164244191224182133191064104222093164253122224284151284`.match(/.../g).map((v,i)=>(c.fillStyle=['#fc0','#f04','#08a'][a=i%3],c.beginPath(),c[l='lineTo'](x=5*~~v/10,y=v%10*25),c[l](x-10,y+(--a+!a)*17),a&&c[l](x-30,y+a*17),c[l](x-20,y),!a&&c[l](x-10,y-17),c.fill()))</script>
```
[Answer]
## JavaScript(ES6)/SVG(HTML5), ~~350~~ 312 bytes
```
document.write(`<svg width=390 height=338>`)
a=`195,52;240,130;285,208;330,286;240,286;150,286;60,286;105,208;150,130;`
a=(a+a).split`;`
for(i=9;i--;)document.write(`<path fill=#FD0 d=M${a[i]}h60l-30,-52h-60z /><path fill=#088 d=M${a[i+3]}h60l-30,52h-60z /><path fill=#F64 d=M${a[i+6]}l-30,-52l-30,52l30,52z />`)
```
[Answer]
# SVG, ~~562~~ ~~540~~ ~~520~~ ~~504~~ ~~487~~ 473 bytes
This is my first time golfing SVG (or any markup, in fact); be gentle!
The assumed viewing environment is an SVG-capable web browser with anything like a typical window size. I tested it in Firefox 50 and in Chrome 55.
The `viewBox` is necessary to meet the 100-pixel requirement; blowing up all measurements by a suitable factor would also work but would take more bytes. Incidentally, it is possible to save another byte by removing the space in `0 -5` in the `viewBox` value, but Firefox won't accept this as valid (whereas Chrome will).
The aspect ratio is 1:1 instead of the true 0.866:1. I'm not sure exactly how the "factor of 2" rule is meant to be interpreted (I think it means that exaggeration as extreme as 0.433:1 or 1.732:1 is acceptable), but I'm pretty sure this meets the requirement anyway.
## SVG
```
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:l="http://www.w3.org/1999/xlink"
viewBox="0 -5 26 26"><g
id="a"><path d="m7,9H3V5h6z"/><g
id="f"><path fill="red" d="m9,5H3V1h4z"/><path
fill="blue" d="m3,1l2,4L3,9l-2-4z"/></g></g><use
l:href="#a" x="3" y="6"/><use
l:href="#e" x="12"/><g
id="e"><use l:href="#a" x="-6" y="12"/><use l:href="#a" x="-12" y="12"/></g><use
l:href="#a" x="-9" y="6"/><use
l:href="#a" x="-6"/><use
l:href="#a" x="-3" y="-6"/><use
l:href="#f"/></svg>
```
## Result
[![A PNG rendering of the above SVG code for Reutersvärd's Triangle](https://i.stack.imgur.com/CxYA6.png)](https://i.stack.imgur.com/CxYA6.png)
[Answer]
# [Python 3](https://docs.python.org/3/) + Turtle, 389 bytes
```
from turtle import*
a='#2e6f6e','#FAD028','#E44834'
L=lt;F=fd;B=begin_fill;E=end_fill
Z=0,1,2
pu()
ht()
speed(0)
for m in Z:L(120);F(30);L(60);F(30);L(60);[[[[color(a[j-m]),B(),[F(20)==L((5-i%2)*60)for i in(1,)+Z],E(),L(120)]for j in Z],k%2and[L(180),F(30),L(180)]or[L(300),F(30),L(60)]]for k in Z]
L(120)
F(30)
L(60)
F(10)
for k in[2,1]:color(a[k]);B();[F(20)==L(240)for i in Z];E();L(60)
```
From Bubbler's golf of -131 bytes!
[Try it online!](https://tio.run/##XU/LboMwELz7K5CiCDt1JGMoQrF8aFQ48QUgq6LFNISHkUsO/Xq6mFap4sNqvLMzOzt9zxczhsvSWDN4883OvfbaYTJ2PqBK@juu4ybWPvV32csr48mK0ihKwshHuexnkcmmFmf5rj/b8a1p@16kUo@1g6iQjAaUo@mGCbrMUL4mrWvMCGqM9QavHb3ilOOAMyIyHELNcfyAS3gfpjcWV@X1OChCz5jQMsMgkjLH@PnY7jk5wOxq2oIpDih5KhRNYXBzVyt1dfsU7fa8GusSmIQR6nbR7aOMhXbI/rXBVjl1t6nRZogcjxwPOPg9aR0qOQ3U6S9yp4iAwOIemEf3pGAoIOV26rL8AA "Python 3 – Try It Online")
# [Python 3 + Turtle](https://docs.python.org/3/), 537 520 bytes
```
from turtle import*
a=['#2e6f6e','#FAD028','#E44834']
pu()
ht()
speed(0)
for m in range(3):
lt(120);fd(30);lt(60);fd(30);lt(60)
for k in range(3):
for j in range(3):
color(a[j]);begin_fill()
for i in range(4):fd(20);rt(120 if i%2==0 else 60)
end_fill();lt(120)
if k==1:rt(180);fd(30);lt(180)
else:rt(60);fd(30);lt(60)
a=a[2:]+a[:2]
lt(120)
fd(30)
lt(60)
fd(10)
a=[a[2],a[1]]
for k in range(2):
color(a[k]);begin_fill()
for i in range(3):fd(20);rt(120)
end_fill();lt(60)
turtle.Screen().exitonclick()
```
-17 bytes from Dion, after removing unnecessary whitespace.
[Try it online!](https://tio.run/##bVHLasMwEDxbXyEIxVIbgi2bEBx8KLT9gR6NKKqzThQrklEUaL/eXeVBiduLVrOa2d1ZDd9h52wxjp13BxpOPhig@jA4Hx6Jqpt0JmDZLSGdp7O355dMrOLttSxXRZlKMpwYJ7uAx3EA2LCMk855eqDaUq/sFljBK5KYwHKR8XW3YQUGhMspIkkU9hPhObmfJpPWGeeZavaSrz9hq@1Hp43BKZKLQv8qSl5hn9jcn4eguqP6QdR1RsEcgZ5bJwnYzbXG@josZpHa13VeReXqbuAIkRArxNd/3KhaNaKST6qphCS3mhcSuZIQ5RhwzciVc9XkUpLJGkR0fPPb//E7cVtM3CLj3llse/nlxXvrASzjC/jSwdnW6LZnfBx/AA "Python 3 – Try It Online")
[![enter image description here](https://i.stack.imgur.com/BaG9g.gif)](https://i.stack.imgur.com/BaG9g.gif)
gif made from [cdlane's instructions!](https://stackoverflow.com/a/41353016/4568534)
] |
[Question]
[
[Inspiration](https://puzzling.stackexchange.com/q/31247/74193)
[Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is a well known cellular automaton "played" on an infinite grid, filled with cells that are either alive or dead. Once given an initial state, the board evolves according to rules indefinitely. Those rules are:
* Any live cell with 2 or 3 living neighbours (the 8 cells immediately around it) lives to the next state
* Any dead cell with exactly 3 living neighbours becomes a living cell
* Any other cell becomes a dead cell
Game of Life is known for having simple rules yet structures can quickly become chaotic with minimal change.
Consider the following initial state:
[![enter image description here](https://i.stack.imgur.com/QRJpe.png)](https://i.stack.imgur.com/QRJpe.png)
In 5 generations, this reaches [this](https://i.stack.imgur.com/9spDV.png) configuration, which is a period 2 oscillator. However, by adding in 8 live cells next to it:
[![enter image description here](https://i.stack.imgur.com/9vuK4.png)](https://i.stack.imgur.com/9vuK4.png)
we end up with a completely empty board after 54 generations.
---
Now, consider instead the following initial state:
[![enter image description here](https://i.stack.imgur.com/c2aWk.png)](https://i.stack.imgur.com/c2aWk.png)
That is, `CGCC` made up of living cells. Each letter is in a \$4\times6\$ bounding box, with a single empty column of cells between boxes, for a total bounding box of \$19\times6\$. [This](https://i.stack.imgur.com/Z8m0j.png) is a zoomed-in version.
After 256 generations, the board looks like
[![enter image description here](https://i.stack.imgur.com/SgfJs.png)](https://i.stack.imgur.com/SgfJs.png)
From this point, no meaningful change will happen: there are 2 oscillators which do not interact with anything else, and the rest are still lifes.
Your task is to "destroy" this by adding in living cells around the initial configuration.
You will start with the `CGCC` initial state, as shown above. You will add \$n\$ living cells to the board. Those cells must be outside of the \$19\times6\$ bounding box of the `CGCC` (but may touch against the outside). When this new initial state (with your added cells) is run, it must eventually result in an empty board.
Note that the board is considered infinite, so if your configuration produces any spaceships, it is not a valid configuration.
Your score is equal to \$n\$. The lowest score wins, ties are broken by the fewest generations required to empty the board. Please provide either a testing environment to demonstrate your solution, or provide a video/gif of it running.
[Here](https://copy.sh/life/?gist=fc6c7fb852fee0d1c6a6a7508ebffa9d) is a pre-filled `CGCC` pattern in a GoL simulator
[Answer]
# Score 1, 35 generations
Sorry, but I guess I wrecked the challenge. I brute-forced all meaningful one-dot additions by hand, and found no other answer that wins against this.
## Raw ASCII format
```
OOO OOO OOO OOO
O O O O
O O O O
O O OO O O
O O O O O
OOO OO OOO OOO
X
```
## Image of initial state
[![Initial State](https://i.stack.imgur.com/rBppi.png)](https://i.stack.imgur.com/rBppi.png)
## Copy.sh export
```
#C Generated by copy.sh/life
x = 19, y = 8, rule = B3/S23
b3o2b3o2b3o2b3o$o4bo4bo4bo$o4bo4bo4bo$o4bob2obo4bo$o4bo2bobo4bo$b3o2b
2o3b3o2b3o$$15bo!
```
[Try this pattern on copy.sh!](https://copy.sh/life/?gist=f0a24cbfaf523f8dd222874dc00f8b11)
## Slow animated gif
[![Slow Animated GIF](https://i.stack.imgur.com/uGHob.gif)](https://i.stack.imgur.com/uGHob.gif)
[Answer]
# \$n=2\$, 41 generations
```
#C Generated by copy.sh/life
x = 19, y = 8, rule = B3/S23
11bo$b3o2b3o2b3o2b3o$o4bo4bo4bo$o4bo4bo4bo$o4bob2obo4bo$o4bo2bobo4bo$b
3o2b2o3b3o2b3o$10bo!
```
Run it online [here](https://copy.sh/life/?gist=026375df121d031861f13af06eae8c2c). Here's what the initial position looks like:
[![enter image description here](https://i.stack.imgur.com/QYzZ3.png)](https://i.stack.imgur.com/QYzZ3.png)
[Answer]
# Score 8, 69 generations
This is what I promised for in the comment, but it got already beaten by Dingus...
I can't upload images right now, so I include a text-based initial configuration and the copy.sh export format.
## Raw ASCII format
```
X X
OOO OOO OOO OOO
O O O O
O O O O
O O OO O O
O O O O O
OOO OO OOO OOO
X
X
XX
X X
```
## Copy.sh export
```
#C Generated by copy.sh/life
x = 28, y = 22, rule = B3/S23
o18bo$b3o2b3o2b3o2b3o$o4bo4bo4bo$o4bo4bo4bo$o4bob2obo4bo$o4bo2bobo4bo$
b3o2b2o3b3o2b3o$9bo$$$$$$$$$$$$26bo$25b2o$25bobo!
```
] |
[Question]
[
One of the most common voting systems for single-winner elections is the plurality voting method. Simply put, the candidate with the most votes wins. Plurality voting, however, is mathematically unsound and is liable to create situations in which voters are driven to vote for the "lesser of two evils" as opposed to the candidate they truly prefer.
In this game, you will write program that takes advantage of the plurality voting system. It will cast a vote for one of three candidates in an election. Each candidate is associated with a certain payoff for yourself, and your goal is to maximize your expected payoff.
The payoffs are "uniformly" randomly distributed, change with each election, and add to 100. Candidate *A* could have payoff 40, Candidate *B* could have payoff 27, and Candidate *C* could have payoff 33. Each player has a different set of payoffs.
When it is your turn to vote, you will have incomplete information. Listed below is the information that you will have available to you. Since you don't know what other player's individual payoffs are, it will be your challenge to predict how they would vote given the current poll results.
* The partial results of the election so far
* The number of entrants (excluding yourself), who haven't voted yet
* Your personal payoffs for each of the candidates
* The total group payoffs for each of the candidates
After each player has been given a chance to vote, the candidate with the most votes wins in accordance with plurality voting. Each player then receives the number of points that corresponds the their payoff from that candidate. If there is a tie in votes, then the number of points assigned will be the average of the tied candidates.
## Tournament Structure
When first instantiated, the entrant will be told the number of elections held in the tournament. I will attempt to run an extremely large number of elections. Then, each election will be carried out one-by-one.
After the entrants are shuffled, each is given a turn to vote. They are given the limited information listed above and return a number signifying their vote. After each election is over, each bot is given the final poll results and their score increase from that election.
The victorious entrant will be the one with the highest total score after some large number of elections have been held. The controller also computes a "normalized" score for each contestant by comparing its score to the score distribution predicted for a randomly-voting bot.
## Submission Details
**Submissions will take the form of Java 8 classes.** Each entrant must implement the following interface:
```
public interface Player
{
public String getName();
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs);
public void receiveResults(int[] voteCounts, double result);
}
```
* **Your constructor should take a single `int` as a parameter,** which will represent the number of elections that will be held.
* The `getName()` method returns the name to be used on the leaderboard. This allows you to have nicely-formatted names, just don't go crazy.
* The `getVote(...)` method returns `0`, `1`, or `2` to signify which candidate will receive the vote.
* The `receiveResults(...)` method is mainly to enable the existence of more complex strategies that use historical data.
* You are allowed to create pretty much any other methods / instance variables you wish to record and process the information given to you.
## Tournament Cycle, Expanded
1. The entrants are each instantiated with `new entrantName(int numElections)`.
2. For each election:
1. The controller randomly determines the payoffs for each player for this election. The code for this is given below. Then, it shuffles players and has them start voting.
2. The entrant's method `public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)` is invoked, and the entrant returns their vote of `0`, `1`, or `2` for the candidate of their choice.
3. Entrants whose `getVote(...)` method doesn't return a valid vote will be assigned a random vote.
4. After everyone has voted, the controller determines the election results by the plurality method.
5. The entrants are informed of the final vote counts and their payoff by calling their method `public void receiveResults(int[] voteCounts, double result)`.
3. After all elections have been held, the winner is the one with the highest score.
## The Random Distribution of Payoffs
The *exact* distribution will have a significant effect on gameplay. I have chosen a distribution with a large standard deviation (about 23.9235) and which is capable of creating both very high and very low payoffs. I have checked that each of the three payoffs has an identical distribution.
```
public int[] createPlayerPayoffs()
{
int cut1;
int cut2;
do{
cut1 = rnd.nextInt(101);
cut2 = rnd.nextInt(101);
} while (cut1 + cut2 > 100);
int rem = 100 - cut1 - cut2;
int[] set = new int[]{cut1,cut2,rem};
totalPayoffs[0] += set[0];
totalPayoffs[1] += set[1];
totalPayoffs[2] += set[2];
return set;
}
```
## More Rules
Here are some more generalized rules.
* Your program must not run/modify/instantiate any parts of the controller or other entrants or their memories.
* Since your program stays "live" for the whole tournament, don't create any files.
* Don't interact with, help, or target any other entrant programs.
* You *may* submit multiple entrants, as long as they are reasonably different, and as long as you follow the above rules.
* I haven't specified an exact time limit, but I would greatly appreciate runtimes that are *significantly* less than a second per call. I want to be able to run as many elections as feasible.
## The Controller
**The controller can be found [here](https://github.com/PhiNotPi/StrategicVoting).** The main program is `Tournament.java`. There are also two simple bots, which will be competing, titled `RandomBot` and `PersonalFavoriteBot`. I will post these two bots in an answer.
## Leaderboard
It looks like ExpectantBot is the current leader, followed by Monte Carlo and then StaBot.
```
Leaderboard - 20000000 elections:
767007688.17 ( 937.86) - ExpectantBot
766602158.17 ( 934.07) - Monte Carlo 47
766230646.17 ( 930.60) - StatBot
766054547.17 ( 928.95) - ExpectorBot
764671254.17 ( 916.02) - CircumspectBot
763618945.67 ( 906.19) - LockBot
763410502.67 ( 904.24) - PersonalFavoriteBot343
762929675.17 ( 899.75) - BasicBot
761986681.67 ( 890.93) - StrategicBot50
760322001.17 ( 875.37) - Priam
760057860.67 ( 872.90) - BestViableCandidate (2842200 from ratio, with 1422897 tie-breakers of 20000000 total runs)
759631608.17 ( 868.92) - Kelly's Favorite
759336650.67 ( 866.16) - Optimist
758564904.67 ( 858.95) - SometimesSecondBestBot
754421221.17 ( 820.22) - ABotDoNotForget
753610971.17 ( 812.65) - NoThirdPartyBot
753019290.17 ( 807.12) - NoClueBot
736394317.17 ( 651.73) - HateBot670
711344874.67 ( 417.60) - Follower
705393669.17 ( 361.97) - HipBot
691422086.17 ( 231.38) - CommunismBot0
691382708.17 ( 231.01) - SmashAttemptByEquality (on 20000000 elections)
691301072.67 ( 230.25) - RandomBot870
636705213.67 ( -280.04) - ExtremistBot
The tournament took 34573.365419071 seconds, or 576.2227569845166 minutes.
```
Here are some older tournament, but none of the bots have changed in functionality since these runs.
```
Leaderboard - 10000000 elections:
383350646.83 ( 661.14) - ExpectantBot
383263734.33 ( 659.99) - LearnBot
383261776.83 ( 659.97) - Monte Carlo 48
382984800.83 ( 656.31) - ExpectorBot
382530758.33 ( 650.31) - CircumspectBot
381950600.33 ( 642.64) - PersonalFavoriteBot663
381742600.33 ( 639.89) - LockBot
381336552.33 ( 634.52) - BasicBot
381078991.83 ( 631.12) - StrategicBot232
380048521.83 ( 617.50) - Priam
380022892.33 ( 617.16) - BestViableCandidate (1418072 from ratio, with 708882 tie-breakers of 10000000 total runs)
379788384.83 ( 614.06) - Kelly's Favorite
379656387.33 ( 612.31) - Optimist
379090198.33 ( 604.83) - SometimesSecondBestBot
377210328.33 ( 579.98) - ABotDoNotForget
376821747.83 ( 574.84) - NoThirdPartyBot
376496872.33 ( 570.55) - NoClueBot
368154977.33 ( 460.28) - HateBot155
355550516.33 ( 293.67) - Follower
352727498.83 ( 256.36) - HipBot
345702626.33 ( 163.50) - RandomBot561
345639854.33 ( 162.67) - SmashAttemptByEquality (on 10000000 elections)
345567936.33 ( 161.72) - CommunismBot404
318364543.33 ( -197.86) - ExtremistBot
The tournament took 15170.484259763 seconds, or 252.84140432938332 minutes.
```
I also ran a second 10m tournament, confirming ExpectantBot's lead.
```
Leaderboard - 10000000 elections:
383388921.83 ( 661.65) - ExpectantBot
383175701.83 ( 658.83) - Monte Carlo 46
383164037.33 ( 658.68) - LearnBot
383162018.33 ( 658.65) - ExpectorBot
382292706.83 ( 647.16) - CircumspectBot
381960530.83 ( 642.77) - LockBot
381786899.33 ( 640.47) - PersonalFavoriteBot644
381278314.83 ( 633.75) - BasicBot
381030871.83 ( 630.48) - StrategicBot372
380220471.33 ( 619.77) - BestViableCandidate (1419177 from ratio, with 711341 tie-breakers of 10000000 total runs)
380089578.33 ( 618.04) - Priam
379714345.33 ( 613.08) - Kelly's Favorite
379548799.83 ( 610.89) - Optimist
379289709.83 ( 607.46) - SometimesSecondBestBot
377082526.83 ( 578.29) - ABotDoNotForget
376886555.33 ( 575.70) - NoThirdPartyBot
376473476.33 ( 570.24) - NoClueBot
368124262.83 ( 459.88) - HateBot469
355642629.83 ( 294.89) - Follower
352691241.83 ( 255.88) - HipBot
345806934.83 ( 164.88) - CommunismBot152
345717541.33 ( 163.70) - SmashAttemptByEquality (on 10000000 elections)
345687786.83 ( 163.30) - RandomBot484
318549040.83 ( -195.42) - ExtremistBot
The tournament took 17115.327209018 seconds, or 285.25545348363335 minutes.
```
[Answer]
# NoThirdPartyBot
This bot tries to guess which candidate will be third, and votes the candidate he likes best of the two front runners.
```
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NoThirdPartyBot implements Player {
public NoThirdPartyBot(int e) {
}
@Override
public String getName() {
return "NoThirdPartyBot";
}
@Override
public int getVote(int[] voteCounts, int votersRemaining, int[] payoffs,
int[] totalPayoffs) {
List<Integer> order = order(totalPayoffs);
if (payoffs[order.get(0)] > payoffs[order.get(1)]) {
return order.get(0);
} else {
return order.get(1);
}
}
static List<Integer> order(int[] array) {
List<Integer> indexes = Arrays.asList(0, 1, 2);
Collections.sort(indexes, (i1, i2) -> array[i2] - array[i1]);
return indexes;
}
@Override
public void receiveResults(int[] voteCounts, double result) {
}
}
```
# CircumspectBot
This bot votes for his favorite that hasn't been mathematically eliminated.
```
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CircumspectBot implements Player {
public CircumspectBot(int elections) {
}
@Override
public String getName() {
return "CircumspectBot";
}
@Override
public int getVote(int[] voteCounts, int votersRemaining, int[] payoffs,
int[] totalPayoffs) {
List<Integer> indexes = new ArrayList<>();
int topVote = Arrays.stream(voteCounts).max().getAsInt();
for (int index = 0; index < 3; index++) {
if (voteCounts[index] + votersRemaining + 1 >= topVote) {
indexes.add(index);
}
}
Collections.sort(indexes, (i1, i2) -> payoffs[i2] - payoffs[i1]);
return indexes.get(0);
}
@Override
public void receiveResults(int[] voteCounts, double result) {
}
}
```
[Answer]
# ExpectantBot
This bot computes the expected value of each voting option assuming that all voters afterwards will vote randomly.
```
import java.util.Arrays;
public class ExpectantBot implements Player {
public ExpectantBot(int elections) {
}
@Override
public String getName() {
return "ExpectantBot";
}
static double choose(int x, int y) {
if (y < 0 || y > x) return 0;
if (y > x/2) {
// choose(n,k) == choose(n,n-k),
// so this could save a little effort
y = x - y;
}
double denominator = 1.0, numerator = 1.0;
for (int i = 1; i <= y; i++) {
denominator *= i;
numerator *= (x + 1 - i);
}
return numerator / denominator;
}
double expectedPayout(int[] voteCounts, int[] payoffs, int votersRemaining) {
double total = 0.0;
for (int firstPartyVoters = 0; firstPartyVoters <= votersRemaining; firstPartyVoters++) {
for (int secondPartyVoters = 0; secondPartyVoters <= votersRemaining - firstPartyVoters; secondPartyVoters++) {
int thirdPartyVoters = votersRemaining - firstPartyVoters - secondPartyVoters;
int [] newVoteCounts = voteCounts.clone();
newVoteCounts[0] += firstPartyVoters;
newVoteCounts[1] += secondPartyVoters;
newVoteCounts[2] += thirdPartyVoters;
int highest = Arrays.stream(newVoteCounts).max().getAsInt();
int payoff = 0;
int winCount = 0;
for (int index = 0; index < 3; index++) {
if (newVoteCounts[index] == highest) {
payoff += payoffs[index];
winCount++;
}
}
double v = (double)payoff / (double) winCount;
double value = choose(votersRemaining, firstPartyVoters)*choose(votersRemaining - firstPartyVoters, secondPartyVoters)*v*Math.pow(1/3.0, votersRemaining);
total += value;
}
}
return total;
}
@Override
public int getVote(int[] voteCounts, int votersRemaining, int[] payoffs,
int[] totalPayoffs) {
int bestVote = 0;
double bestScore = 0.0;
for (int vote = 0; vote < 3; vote++) {
voteCounts[vote]++;
double score = expectedPayout(voteCounts, payoffs, votersRemaining);
if (score > bestScore) {
bestVote = vote;
bestScore = score;
}
voteCounts[vote]--;
}
return bestVote;
}
@Override
public void receiveResults(int[] voteCounts, double result) {
}
}
```
[Answer]
# HipBot
HipBot doesn't care about payouts. Money is just a sedative that distracts from true art.
HipBot wants to vote for someone *real*, not just some corporate shill. He also wants to wear their campaign shirt after their (presumably) humiliating defeat, so he feels superior whenever the winner does something wrong.
Therefore, HipBot votes for the person with the lowest votes or, if there's a tie, whoever's got the better payout. Eating organic-only isn't free.
```
public class HipBot implements Player{
public HipBot(int rounds){ /*Rounds are a social construct*/ }
public String getName(){ return "HipBot"; }
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs){
int coolest = 0;
int lowest = 100000000;
int gains = 0;
for( int count = 0; count < voteCounts.length; count++ ){
if( voteCounts[count] < lowest || (voteCounts[count] == lowest && payoffs[count] > gains) ){
lowest = voteCounts[count];
coolest = count;
gains = payoffs[count];
}
}
return coolest;
}
public void receiveResults(int[] voteCounts, double result){ /*The past is dead*/ }
}
```
HipBot is also untested, so let me know if there's anything going on.
EDIT: added in more competitive tiebreaking, pithy comments.
[Answer]
# PersonalFavoriteBot
This bot simply votes for the candidate with the highest personal payoff, ignoring everything else. One of the main points of this challenge is to demonstrate how this is not the optimal strategy.
```
import java.lang.Math;
import java.util.Random;
/**
* This bot picks the candidate with the highest personal payoff, ignoring everyone else's actions.
*
* @author PhiNotPi
* @version 5/27/15
*/
public class PersonalFavoriteBot implements Player
{
Random rnd;
String name;
/**
* Constructor for objects of class PersonalFavoriteBot
*/
public PersonalFavoriteBot(int e)
{
rnd = new Random();
name = "PersonalFavoriteBot" + rnd.nextInt(1000);
}
public String getName()
{
return name;
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
//return rnd.nextInt(3);
int maxloc = 0;
for(int i = 1; i< 3; i++)
{
if(payoffs[i] > payoffs[maxloc])
{
maxloc = i;
}
}
return maxloc;
}
public void receiveResults(int[] voteCounts, double result)
{
}
}
```
# RandomBot
This bot votes randomly. Regardless of the number of elections carried out (as long as it's reasonably high, like over 100), this contestant's normalized score fluctuates between -2 and 2.
```
import java.lang.Math;
import java.util.Random;
/**
* This bot votes for a random candidate.
*
* @author PhiNotPi
* @version 5/27/15
*/
public class RandomBot implements Player
{
Random rnd;
String name;
/**
* Constructor for objects of class RandomBot
*/
public RandomBot(int e)
{
rnd = new Random();
name = "RandomBot" + rnd.nextInt(1000);
}
public String getName()
{
return name;
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
return rnd.nextInt(3);
}
public void receiveResults(int[] voteCounts, double result)
{
}
}
```
[Answer]
# Follower
Follower wants to fit in. It thinks the best way to accomplish that is by voting the same way as everyone else, or at least with the plurality so far. It'll break ties towards its own preference, to show a little independence. But not too much.
```
public class Follower implements Player
{
public Follower(int e) { }
public String getName()
{
return "Follower";
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
int mostPopular = 0;
int mostVotes = voteCounts[0];
for (int i = 1; i < voteCounts.length; i++) {
int votes = voteCounts[i];
if (votes > mostVotes || (votes == mostVotes && payoffs[i] > payoffs[mostPopular])) {
mostPopular = i;
mostVotes = votes;
}
}
return mostPopular;
}
public void receiveResults(int[] voteCounts, double result) { }
}
```
Note: I haven't tested this, so let me know if there are any errors.
[Answer]
# Monte Carlo
This simulates a large amount of random elections. It then chooses the choice that maximizes it's own profits.
```
import java.util.ArrayList;
import java.util.List;
public class MonteCarlo implements Player{
private static long runs = 0;
private static long elections = 0;
public MonteCarlo(int e) {
elections = e;
}
@Override
public String getName() {
return "Monte Carlo (difficulty " + (runs / elections) + ")";
}
@Override
public int getVote(int[] voteCounts, int votersRemaining, int[] payoffs, int[] totalPayoffs) {
elections++;
double[] predictedPayoffs = new double[3];
long startTime = System.nanoTime();
while (System.nanoTime() - startTime <= 200_000){ //Let's give us 200 micro-seconds.
runs++;
int[] simulatedVoteCounts = voteCounts.clone();
for (int j = 0; j < votersRemaining; j++){
simulatedVoteCounts[((int) Math.floor(Math.random() * 3))]++;
}
for (int j = 0; j < 3; j++) {
simulatedVoteCounts[j]++;
List<Integer> winners = new ArrayList<>();
winners.add(0);
for (int k = 1; k < 3; k++) {
if (simulatedVoteCounts[k] > simulatedVoteCounts[winners.get(0)]) {
winners.clear();
winners.add(k);
} else if (simulatedVoteCounts[k] == simulatedVoteCounts[winners.get(0)]) {
winners.add(k);
}
}
for (int winner : winners) {
predictedPayoffs[j] += payoffs[winner] / winners.size();
}
simulatedVoteCounts[j]--;
}
}
int best = 0;
for (int i = 1; i < 3; i++){
if (predictedPayoffs[i] > predictedPayoffs[best]){
best = i;
}
}
return best;
}
@Override
public void receiveResults(int[] voteCounts, double result) {
}
}
```
[Answer]
# StatBot
StatBot is based on ExpectantBot; however, instead of assuming that each vote is equally probable it collects stats on how people vote and uses that to estimate the probability.
```
import java.util.Arrays;
public class StatBot implements Player {
static private int[][][] data = new int[3][3][3];
private int[] voteCounts;
StatBot(int unused) {
}
@Override
public String getName() {
return "StatBot";
}
static double choose(int x, int y) {
if (y < 0 || y > x) return 0;
if (y > x/2) {
// choose(n,k) == choose(n,n-k),
// so this could save a little effort
y = x - y;
}
double denominator = 1.0, numerator = 1.0;
for (int i = 1; i <= y; i++) {
denominator *= i;
numerator *= (x + 1 - i);
}
return numerator / denominator;
}
double expectedPayout(int[] voteCounts, int[] payoffs, int votersRemaining) {
Integer[] indexes = {0, 1, 2};
Arrays.sort(indexes, (i0, i1) -> voteCounts[i1] - voteCounts[i0]);
int [] stats = data[indexes[0]][indexes[1]];
int total_stats = Arrays.stream(stats).sum();
double total = 0.0;
for (int firstPartyVoters = 0; firstPartyVoters <= votersRemaining; firstPartyVoters++) {
for (int secondPartyVoters = 0; secondPartyVoters <= votersRemaining - firstPartyVoters; secondPartyVoters++) {
int thirdPartyVoters = votersRemaining - firstPartyVoters - secondPartyVoters;
int [] newVoteCounts = voteCounts.clone();
newVoteCounts[0] += firstPartyVoters;
newVoteCounts[1] += secondPartyVoters;
newVoteCounts[2] += thirdPartyVoters;
int highest = 0;
for (int h : newVoteCounts) {
if (h > highest) highest = h;
}
int payoff = 0;
int winCount = 0;
for (int index = 0; index < 3; index++) {
if (newVoteCounts[index] == highest) {
payoff += payoffs[index];
winCount++;
}
}
double v = (double)payoff / (double) winCount;
double value = choose(votersRemaining, firstPartyVoters)*choose(votersRemaining - firstPartyVoters, secondPartyVoters)*v;
value *= Math.pow((double)stats[0]/(double)total_stats, firstPartyVoters);
value *= Math.pow((double)stats[1]/(double)total_stats, secondPartyVoters);
value *= Math.pow((double)stats[2]/(double)total_stats, thirdPartyVoters);
total += value;
}
}
return total;
}
@Override
public int getVote(int[] voteCounts, int votersRemaining, int[] payoffs,
int[] totalPayoffs) {
int bestVote = 0;
double bestScore = 0.0;
for (int vote = 0; vote < 3; vote++) {
voteCounts[vote]++;
double score = expectedPayout(voteCounts, payoffs, votersRemaining);
if (score > bestScore) {
bestVote = vote;
bestScore = score;
}
voteCounts[vote]--;
}
voteCounts[bestVote]++;
this.voteCounts = voteCounts;
return bestVote;
}
@Override
public void receiveResults(int[] endVoteCounts, double result) {
Integer[] indexes = {0, 1, 2};
Arrays.sort(indexes, (i0, i1) -> voteCounts[i1] - voteCounts[i0]);
for(int i = 0; i < 3; i++){
data[indexes[0]][indexes[1]][i] += endVoteCounts[i] - voteCounts[i];
}
}
}
```
[Answer]
# Best Viable Candidate
Pretty heavily revised version of my original submission. This one still eliminates any candidates that cannot win given the remaining votes to be cast, but then uses a strategy that tries to optimize the *relative payoff* rather than the absolute one. The first test is to take the ratio of my personal payoff to the overall payoff for each candidate, looking for the best value there. I then look for other ratios that are very close to the best and if there is one that has a lower overall payoff than the very best I pick that one instead. Hopefully this will tend to depress the payout of the other players while keeping mine reasonably high.
This bot does *almost* as well as the original on in my own testing, but not quite. We'll have to see how it does against the full field.
```
/**
* This bot picks the candidate with the highest relative payoff out of those
* candidates who are not already mathematically eliminated.
*
* @author Ralph Marshall
* @version 5/28/2015
*/
import java.util.List;
import java.util.ArrayList;
public class BestViableCandidate implements Player
{
private static int NUM_CANDIDATES = 3;
private int relativeCount = 0;
private int relativeCountLowerTotal = 0;
private int totalRuns;
public BestViableCandidate(int r) {
totalRuns = r;
}
public String getName() {
return "BestViableCandidate (" + relativeCount + " from ratio, with " + relativeCountLowerTotal + " tie-breakers of " + totalRuns + " total runs)";
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs) {
int i, maxVoteSoFar = 0;
// First we figure out the maximum possible number of votes each candidate would get
// if every remaining bot voted for it
int [] maxPossibleVotes = new int[NUM_CANDIDATES];
for (i = 0; i < NUM_CANDIDATES; i++) {
// The voters remaining does not include me, so we need to add one to it
maxPossibleVotes[i] = voteCounts[i] + votersRemaining + 1;
if (voteCounts[i] > maxVoteSoFar) {
maxVoteSoFar = voteCounts[i];
}
}
// Then we throw out anybody who cannot win even if they did get all remaining votes
List<Integer> viableCandidates = new ArrayList<Integer>();
for (i = 0; i < NUM_CANDIDATES; i++) {
if (maxPossibleVotes[i] >= maxVoteSoFar) {
viableCandidates.add(Integer.valueOf(i));
}
}
// And of the remaining candidates we pick the one that has the personal highest payoff
// relative to the payoff to the rest of the voters
int maxCandidate = -1;
double maxRelativePayoff = -1;
int maxPayoff = -1;
int minTotalPayoff = Integer.MAX_VALUE;
int originalMaxCandidate = -1;
double originalMaxPayoff = -1;
double DELTA = 0.01;
double tiebreakerCandidate = -1;
for (Integer candidateIndex : viableCandidates) {
double relativePayoff = (double) payoffs[candidateIndex] / (double) totalPayoffs[candidateIndex];
if (maxRelativePayoff < 0 || relativePayoff - DELTA > maxRelativePayoff) {
maxRelativePayoff = relativePayoff;
maxCandidate = candidateIndex;
maxPayoff = payoffs[candidateIndex];
minTotalPayoff = totalPayoffs[candidateIndex];
} else if (Math.abs(relativePayoff - maxRelativePayoff) < DELTA) {
if (totalPayoffs[candidateIndex] < minTotalPayoff) {
tiebreakerCandidate = candidateIndex;
maxRelativePayoff = relativePayoff;
maxCandidate = candidateIndex;
maxPayoff = payoffs[candidateIndex];
minTotalPayoff = totalPayoffs[candidateIndex];
}
}
if (payoffs[candidateIndex] > originalMaxPayoff) {
originalMaxPayoff = payoffs[candidateIndex];
originalMaxCandidate = candidateIndex;
}
}
if (tiebreakerCandidate == maxCandidate) {
relativeCountLowerTotal++;
}
if (originalMaxCandidate != maxCandidate) {
/* System.out.printf("%nSelecting candidate %d with relative payoff %f (%d/%d) instead of %d with relative payoff %f (%d/%d)%n",
maxCandidate, (double) payoffs[maxCandidate]/(double)totalPayoffs[maxCandidate], payoffs[maxCandidate], totalPayoffs[maxCandidate],
originalMaxCandidate, (double) payoffs[originalMaxCandidate]/(double)totalPayoffs[originalMaxCandidate], payoffs[originalMaxCandidate], totalPayoffs[originalMaxCandidate]);
*/
relativeCount++;
}
return maxCandidate;
}
}
```
[Answer]
# Optimist
The Optimist is very optimistic and assumes that half of the remaining voters will vote for the candidate that gives it the best payoff.
```
import java.lang.Integer;
import java.lang.String;
import java.util.Arrays;
import java.util.Comparator;
public class Optimist implements Player
{
public Optimist(int _) { }
public String getName() { return "Optimist"; }
public int getVote(int[] curVotes, int rem, final int[] payoffs, int[] _)
{
Integer[] opt = new Integer[] { 0, 1, 2 };
Arrays.sort(opt, new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { return payoffs[i1] > payoffs[i2] ? -1 : payoffs[i1] == payoffs[i2] ? 0 : 1; } });
int a = curVotes[opt[0]], b = curVotes[opt[1]], c = curVotes[opt[2]];
double rest = (double)rem / 4;
if (b <= a + rest && c <= a + rest)
return opt[0];
else if (c <= b)
return opt[1];
else
return opt[0];
}
public void receiveResults(int[] _, double __) { }
}
```
[Answer]
# ABotDoNotForget
His goal is simple : determining the overall tendencies using the total payoffs and counting the number of time the lower/medium/higher ones won. He will then vote for the one that is most likely to win.
```
import java.util.ArrayList;
public class ABotDoNotForget implements Player
{
private int nbElec;
private int countElec=0;
private int[] currPayoffs=new int[3];
private int[] lmh=new int[3];
private int[] wins=new int[3];
public ABotDoNotForget(int nbElec)
{
this.nbElec=nbElec;
}
public String getName() {return "ABotDoNotForget";}
public int getVote(int[] voteCounts,
int votersRemaining,
int[] payoffs,
int[] totalPayoffs)
{
countElec++;
System.arraycopy(totalPayoffs, 0, currPayoffs, 0, totalPayoffs.length);
if(countElec<=nbElec/20&&countElec<=20)
{
int best=0;
for(int i=1;i<payoffs.length;i++)
if(payoffs[i]>=payoffs[best])
best=i;
return best;
}
for(int i =1;i<totalPayoffs.length;i++)
{
if(totalPayoffs[i]<totalPayoffs[i-1])
{
int tmp= totalPayoffs[i];
totalPayoffs[i]=totalPayoffs[i-1];
totalPayoffs[i-1]=tmp;
if(i==2&&totalPayoffs[i-1]<totalPayoffs[i-2]){
tmp= totalPayoffs[i-1];
totalPayoffs[i-1]=totalPayoffs[i-2];
totalPayoffs[i-2]=tmp;
}
}
}
lmhDist(currPayoffs,totalPayoffs);
int best=0;
for(int i=1;i<wins.length;i++)
if(wins[i]>=wins[best]){
best=i;
}
int ownH=0;
for(int i=1;i<payoffs.length;i++)
if(payoffs[i]>=payoffs[ownH])
ownH=i;
int ownM=0;
for(int i=1;i<payoffs.length;i++)
if(payoffs[i]>=payoffs[ownM]&&i!=ownH)
ownM=i;
int persBest=(voteCounts[ownH]-voteCounts[ownM]+(votersRemaining/3)>=0
&&voteCounts[ownH]-voteCounts[best]<(votersRemaining/3))?ownH:ownM;
return persBest;
}
public void receiveResults(int[] voteCounts, double result)
{
int best=0,bestV=voteCounts[best];
for(int i=1;i<voteCounts.length;i++)
if(voteCounts[i]>=bestV){
best=i;
bestV=voteCounts[i];
}
wins[lmh[best]]++;
}
private void lmhDist(int[] a,int[] s)
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(a[0]);al.add(a[1]);al.add(a[2]);
lmh[0]=al.indexOf(s[0]);
lmh[1]=al.indexOf(s[1]);
lmh[2]=al.indexOf(s[2]);
}
}
```
### Edit :
Some change done in the decision algorythm, now takes into account his own best payoff. Should now be able to vote better when the current distribution was making him vote for his own Lower when others where voting for their Higher payoffs.
[Answer]
# Priam
Priam hates recursion. He estimates the probability of each remaining bot based on the total payoffs and then calculates the best way of maximising his payoff.
```
public class Priam implements Player {
private static double[] smallFactorials = {1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600,6227020800.,87178291200.,1307674368000.,20922789888000.,355687428096000.,6402373705728000.,121645100408832000.,2432902008176640000.};
@Override
public String getName() {
return "Priam";
}
@Override
public int getVote(int[] voteCounts, int votersRemaining, int[] payoffs,
int[] totalPayoffs) {
int totalPayoff = totalPayoffs[0] + totalPayoffs[1] + totalPayoffs[2];
double p0 = ((double)totalPayoffs[0])/totalPayoff;
double p1= ((double) totalPayoffs[1])/totalPayoff;
double p2 = ((double)totalPayoffs[2])/totalPayoff;
double[] expectedPayoffs = {0,0,0};
for(int myChoice=0;myChoice<3;myChoice++)
{
for(int x0 = 0; x0 <= votersRemaining; x0++)
{
for(int x1 = 0; x1 <= (votersRemaining-x0); x1++)
{
int x2 = votersRemaining - (x1 + x0);
double probability =
Math.pow(p0, x0)
* Math.pow(p1, x1)
* Math.pow(p2, x2)
* Choose(votersRemaining, x0)
* Choose(votersRemaining-x0, x1);
int votes0 = voteCounts[0];
int votes1 = voteCounts[1];
int votes2 = voteCounts[2];
if(myChoice == 0)
{
votes0++;
}
else if(myChoice==1)
{
votes1++;
}
else
{
votes2++;
}
votes0+=x0;
votes1+=x1;
votes2+=x2;
if(votes0>votes1 && votes0>votes2)
{
expectedPayoffs[myChoice]+=probability*payoffs[0];
}
else if(votes1>votes2)
{
expectedPayoffs[myChoice]+=probability*payoffs[1];
}
else
{
expectedPayoffs[myChoice]+=probability*payoffs[2];
}
}
}
}
if(expectedPayoffs[0]>expectedPayoffs[1] && expectedPayoffs[0]>expectedPayoffs[2])
{
return 0;
}
else if(expectedPayoffs[1]>expectedPayoffs[2])
{
return 1;
}
else
{
return 2;
}
}
private long Choose(int source, int team) {
return Factorial(source)/(Factorial(team)*Factorial(source-team));
}
private long Factorial(int n) {
if(n<=20)
{
return (long)smallFactorials[n];
}
double d=(double)n;
double part1 = Math.sqrt(2*Math.PI*d);
double part2 = Math.pow(d/Math.E, d);
return (long)Math.ceil(part1 * part2);
}
@Override
public void receiveResults(int[] voteCounts, double result) {
}
public Priam(int i)
{
}
}
```
Much much faster than Odysseus as there is no recursion (runs in time O(n^2)) and can do one million elections in about 15 seconds.
[Answer]
# NoClueBot
NoClue does not actually know Java or math very well, so he has no idea if this weighting-ratio-thingy will help him win. But he's trying.
```
import java.lang.Math;
import java.util.*;
/**
* Created by Admin on 5/27/2015.
*/
public class NoClueBot implements Player {
public NoClueBot(int e) { }
public String getName() {
return "NoClueBot";
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs) {
double x = 0;
int y = 0;
for (int i=0; i<3; i++) {
double t = (double) voteCounts[i] * ((double) payoffs[i]/(double) totalPayoffs[i]);
if (x<t) {
x = t;
y = i;
}
}
return y;
}
public void receiveResults(int[] voteCounts, double result) { }
}
```
---
# SomeClueBot
SomeClueBot has been decommissioned. ~~actually uses logic! used to use logic, which turned out to be inefficient, so instead he became mindful of the total payoff, not his own. uses logic again! But he doesn't do well with all these followers and optimists, and even people who don't care! :)~~
---
# SometimesSecondBestBot
Basically PersonalFavouriteBot, improved (in theory).
```
import java.lang.Math;
/**
* Created by Admin on 5/27/2015.
*/
public class SometimesSecondBestBot implements Player {
public SometimesSecondBestBot(int e) { }
public String getName() {
return "SometimesSecondBestBot";
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs) {
int m = 0;
int n = 0;
for(int i = 1; i< 3; i++) {
if(payoffs[i] > payoffs[m]) { n = m; m = i; }
}
return (voteCounts[n]>voteCounts[m]&&totalPayoffs[n]>totalPayoffs[m])||(voteCounts[m]+votersRemaining<voteCounts[n])||voteCounts[m]+votersRemaining<voteCounts[Math.min(3-n-m, 2)] ? n : m;
}
public void receiveResults(int[] voteCounts, double result) { }
}
```
[Answer]
# The extremist
Always vote for the candidate with the lowest payoff
```
public class ExtremistBot implements Player
{
public ExtremistBot(int e){}
public void receiveResults(int[] voteCounts, double result){}
public String getName(){
return "ExtremistBot";
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
int min = 0;
for(int i = 1; i<payoffs.length; i++){
if(payoffs[i] <payoffs[min]){
min = i;
}
}
return min;
}
}
```
[Answer]
# SmashAttemptByEquality
The goal is to equalize all the candidats, then SMASH! all the other bots on the last round.
This is a destructive algorith that tries to bug out all the others, to claim the win.
```
public class SmashAttemptByEquality implements Player {
static private int elections;
public SmashAttemptByEquality(int e) {
this.elections = e;
}
public String getName() {
return "SmashAttemptByEquality (on " + String.valueOf(this.elections) + " elections)";
}
public int getVote(int[] voteCounts, int votersRemaining, int[] payoffs, int[] totalPayoffs) {
//if there are no votes or it is a tie
if(voteCounts.length == 0 || (voteCounts[0] == voteCounts[1] && voteCounts[1] == voteCounts[2]))
{
//let the system handle the (distributed?) randomness
return 3;
}
//we want to win, so, lets not mess when there are no voters left
if( votersRemaining > 0 )
{
//lets bring some equality!
if( voteCounts[0] >= voteCounts[1] )
{
if(voteCounts[0] > voteCounts[2])
{
return 2;
}
else
{
return 0;
}
}
else if( voteCounts[1] >= voteCounts[2] )
{
if(voteCounts[1] > voteCounts[0])
{
return 0;
}
else
{
return 1;
}
}
else
{
return 0;
}
}
else
{
//just play for the winner!
if( voteCounts[0] >= voteCounts[1] )
{
if(voteCounts[0] > voteCounts[2])
{
return 0;
}
else
{
return 2;
}
}
else if( voteCounts[1] >= voteCounts[2] )
{
if(voteCounts[1] > voteCounts[0])
{
return 1;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
}
public void receiveResults(int[] voteCounts, double result) { }
}
```
Notice that this is **untested**!
[Answer]
# **Basic Bot**
Basic Bot just votes for the candidates that isn't eliminated and has the largest maximum payoff from those candidates.
```
public class BasicBot implements Player {
public BasicBot(int e) { }
public String getName()
{
return "BasicBot";
}
public static int getMax(int[] inputArray){
int maxValue = inputArray[0];
for(int i=1;i < inputArray.length;i++){
if(inputArray[i] > maxValue){
maxValue = inputArray[i];
}
}
return maxValue;
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
// Check for Eliminated Candidates
int eliminated0 = 0;
int eliminated1 = 0;
int eliminated2 = 0;
if( ((voteCounts[0] + votersRemaining) < voteCounts[1]) || ((voteCounts[0] + votersRemaining) < voteCounts[2]))
{
eliminated0 = 1;
}
if( ((voteCounts[1] + votersRemaining) < voteCounts[0]) || ((voteCounts[1] + votersRemaining) < voteCounts[2]))
{
eliminated1 = 1;
}
if( ((voteCounts[2] + votersRemaining) < voteCounts[0]) || ((voteCounts[2] + votersRemaining) < voteCounts[1]))
{
eliminated2 = 1;
}
// Choose the Candidates that is not elimated with the largest payoff
if ((payoffs[0] == getMax(payoffs)) && eliminated0 == 0)
return 0
else if ((payoffs[1] == getMax(payoffs)) && eliminated1 == 0)
return 1
else
return 2
}
public void receiveResults(int[] voteCounts, double result)
{
}
}
```
[Answer]
## Kelly's Favorite
I started with CircumspectBot, but not much is left. Makes a sort of boring guess at the probability distribution of the remaining votes, and then makes the choice that maximizes its own log-utility (Kelly Criterion). Not the speediest, but within the ball park of some of the others. Also, it's fairly competitive with the field (as it stood when I started working on this, and downloaded the other bots).
```
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class KellysFavorite implements Player {
private ArrayList<Double> cache = new ArrayList<Double>();
public KellysFavorite(int elections) {
cache.add(0.0);
double v = 0.0;
for(int i=1; i<1000; i++) {
v += Math.log(i);
cache.add(v);
}
}
@Override
public String getName() {
return "Kelly's Favorite";
}
private double factln(int n) {
return cache.get(n);
}
private double binll(int x, int n, double p)
{
double ll = 0.0;
ll += ((double)x)*Math.log(p);
ll += ((double)(n - x))*Math.log(1.0 - p);
ll += factln(n) - factln(x) - factln(n-x);
return ll;
}
public double logAdd(double logX, double logY) {
// 1. make X the max
if (logY > logX) {
double temp = logX;
logX = logY;
logY = temp;
}
// 2. now X is bigger
if (logX == Double.NEGATIVE_INFINITY) {
return logX;
}
// 3. how far "down" (think decibels) is logY from logX?
// if it's really small (20 orders of magnitude smaller), then ignore
double negDiff = logY - logX;
if (negDiff < -20) {
return logX;
}
// 4. otherwise use some nice algebra to stay in the log domain
// (except for negDiff)
return logX + java.lang.Math.log(1.0 + java.lang.Math.exp(negDiff));
}
@Override
public int getVote(int[] voteCounts,
int votersRemaining,
int[] payoffs,
int[] totalPayoffs) {
int totalviable = 0;
boolean[] viable = { false, false, false };
int topVote = Arrays.stream(voteCounts).max().getAsInt();
for (int index = 0; index < 3; index++) {
if (voteCounts[index] + votersRemaining + 1 >= topVote) {
viable[index] = true;
totalviable += 1;
}
}
// if only one candidate remains viable, vote for them
if(totalviable == 1) {
for(int index = 0; index < 3; index++)
if(viable[index])
return index;
} else {
double votelikelihoods[] = { 0.0, 0.0, 0.0 };
double totalweight = 0.0;
for(int index=0; index<3; index++) {
if(!viable[index])
votelikelihoods[index] -= 10.0;
else if(voteCounts[index] < topVote)
votelikelihoods[index] -= 0.1;
totalweight += Math.exp(votelikelihoods[index]);
}
double probs[] = new double[3];
for(int index=0; index<3; index++) {
probs[index] = Math.exp(votelikelihoods[index]) / totalweight;
}
double[] utilities = {0,0,0};
for(int mychoice=0; mychoice<3; mychoice++) {
boolean seen[] = { false, false, false };
double likelihoods[] = { Double.NEGATIVE_INFINITY,
Double.NEGATIVE_INFINITY,
Double.NEGATIVE_INFINITY };
int[] localVoteCounts = { voteCounts[0] + (mychoice==0?1:0),
voteCounts[1] + (mychoice==1?1:0),
voteCounts[2] + (mychoice==2?1:0) };
for(int iVotes=0; iVotes<=votersRemaining; iVotes++)
for(int jVotes=0; jVotes<=(votersRemaining-iVotes); jVotes++) {
int kVotes = votersRemaining - iVotes - jVotes;
int a = localVoteCounts[0] + iVotes;
int b = localVoteCounts[1] + jVotes;
int c = localVoteCounts[2] + kVotes;
int wincount = Math.max(a, Math.max(b, c));
int winners = 0;
if(a>=wincount) { winners += 1; }
if(b>=wincount) { winners += 1; }
if(c>=wincount) { winners += 1; }
double likelihood =
binll(iVotes, votersRemaining, probs[0])
+ binll(jVotes, votersRemaining-iVotes, probs[1] / (probs[1] + probs[2]));
likelihood += Math.log(1.0/winners);
if(a>=wincount) {
if(seen[0])
likelihoods[0] = logAdd(likelihoods[0],
likelihood);
else
likelihoods[0] = likelihood;
seen[0] = true;
}
if(b>=wincount) {
if(seen[1])
likelihoods[1] = logAdd(likelihoods[1],
likelihood);
else
likelihoods[1] = likelihood;
seen[1] = true;
}
if(c>=wincount) {
if(seen[2])
likelihoods[2] = logAdd(likelihoods[2],
likelihood);
else
likelihoods[2] = likelihood;
seen[2] = true;
}
}
for(int index=0; index<3; index++)
utilities[mychoice] += Math.exp(likelihoods[index]) * Math.log((double)payoffs[index]);
}
double maxutility = Math.max(utilities[0], Math.max(utilities[1], utilities[2]));
int choice = 0;
for(int index=0; index<3; index++)
if(utilities[index]>=maxutility)
choice = index;
return choice;
}
throw new InternalError();
}
@Override
public void receiveResults(int[] voteCounts, double result) {
}
}
```
Also available at <https://gist.github.com/jkominek/dae0b3158dcd253e09e5> in case that's simpler.
[Answer]
## CommunismBot
CommunismBot thinks we should all just get along and pick the candidate who is best for everyone.
```
public class CommunismBot implements Player
{
Random rnd;
String name;
public CommunismBot(int e) {
rnd = new Random();
name = "CommunismBot" + rnd.nextInt(1000);
}
public String getName()
{
return name;
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
int maxloc = 0;
for(int i = 1; i< 3; i++)
{
if(totalPayoffs[i] > totalPayoffs[maxloc])
{
maxloc = i;
}
}
return maxloc;
}
public void receiveResults(int[] voteCounts, double result) { }
}
```
## Hatebot
Hatebot always picks the best candidate. Unless they're a dirty-stinking-party 1. Those guys are awful.
```
import java.util.Random;
public class HateBot implements Player
{
Random rnd;
String name;
public HateBot(int e) {
rnd = new Random();
name = "HateBot" + rnd.nextInt(1000); }
public String getName()
{
return name;
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
if(payoffs[0]>payoffs[2])
return 0;
else
return 2;
}
public void receiveResults(int[] voteCounts, double result) { }
}
```
## StrategicBot
StrategicBot votes for the best candidate provided that they're within one standard deviation of the next best candidate, given the number of voters remaining.
```
import java.util.Random;
public class StrategicBot implements Player
{
Random rnd;
String name;
public StrategicBot(int e) {
rnd = new Random();
name = "StrategicBot" + rnd.nextInt(1000);
}
public String getName()
{
return name;
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
double margin = 9.0*votersRemaining/9;
int maxloc = 0;
boolean noLead=false;
for(int i = 1; i< 3; i++)
{
for(int j = 1; j < 3; j++)
{
if(payoffs[j] + margin > payoffs[i])
noLead=true;
}
if(payoffs[i] > payoffs[maxloc] && noLead)
{
maxloc = i;
}
noLead=false;
}
return maxloc;
}
public void receiveResults(int[] voteCounts, double result) { }
}
```
[Answer]
# ExpectorBot
Tries to predict how all other Bots will vote by calculating average Payout for the others. Default votes for best payoff, but will vote for second best, if it has more expected votes than the best, a better than average payout for me and the worst-payout has a chance of winning this thing.
```
import java.util.Arrays;
public class ExpectorBot implements Player
{
class Votee
{
int index;
int payoff;
float avgPayoff;
float expectedVotes;
}
public ExpectorBot( final int e )
{
}
@Override
public String getName()
{
return "ExpectorBot";
}
@Override
public int getVote( final int[] voteCounts, final int votersRemaining, final int[] payoffs, final int[] totalPayoffs )
{
final int otherVoters = Arrays.stream( voteCounts ).sum() + votersRemaining;
final Votee[] v = createVotees( voteCounts, otherVoters, votersRemaining, payoffs, totalPayoffs );
final Votee best = v[ 0 ]; // Most Payoff
final Votee second = v[ 1 ];
final Votee worst = v[ 2 ];
int voteFor = best.index;
if( ( second.expectedVotes >= best.expectedVotes + 1 ) // Second has more votes than Best even after I vote
&& ( second.payoff >= second.avgPayoff ) // Second payoff better than average for the others
&& ( worst.expectedVotes >= best.expectedVotes + 0.5f ) ) // Worst has a chance to win
{
voteFor = second.index;
}
return voteFor;
}
private Votee[] createVotees( final int[] voteCounts, final int otherVoters, final int votersRemaining, final int[] payoffs, final int[] totalPayoffs )
{
final Votee[] v = new Votee[ 3 ];
for( int i = 0; i < 3; ++i )
{
v[ i ] = new Votee();
v[ i ].index = i;
v[ i ].payoff = payoffs[ i ];
// This is the average payoff for other Players from this Votee
v[ i ].avgPayoff = (float)( totalPayoffs[ i ] - payoffs[ i ] ) / otherVoters;
// The expected number of Votes he will get if everyone votes for biggest payoff
v[ i ].expectedVotes = voteCounts[ i ] + ( votersRemaining * v[ i ].avgPayoff / 100.0f );
}
Arrays.sort( v, ( o1, o2 ) -> o2.payoff - o1.payoff );
return v;
}
@Override
public void receiveResults( final int[] voteCounts, final double result )
{
}
}
```
[Answer]
## LockBot
Just a lonely philosopher, looking for his "e"...
```
//He thinks he's the father of democracy, but something's missing....
public class LockBot implements Player {
public LockBot(int i) {
//One election, 10000000, what's the difference?
}
@Override
public String getName() {
return "LockBot";
}
@Override
public int getVote(int[] voteCounts, int votersRemaining, int[] payoffs,
int[] totalPayoffs) {
double totalPlayers = voteCounts.length + votersRemaining;
double totalPayoff = totalPlayers * 100;
//adjust total payoffs to ignore my own
for( int i = 0; i < totalPayoffs.length; i++){
totalPayoffs[i] -= payoffs[i];
}
//Votes are probably proportional to payoffs
//So lets just find the highest weight
double[] expectedOutcome = new double[3];
for(int i = 0; i< expectedOutcome.length; i++){
expectedOutcome[i] = (totalPayoffs[i] / totalPayoff) * payoffs[i];
}
//Find the highest
int choice = 0;
if(expectedOutcome[1] > expectedOutcome[choice]){
choice = 1;
}
if(expectedOutcome[2] > expectedOutcome[choice]){
choice = 2;
}
return choice;
}
@Override
public void receiveResults(int[] voteCounts, double result) {
// TODO Auto-generated method stub
}
}
```
[Answer]
# WinLose
If you win, I lose! That simple. So this bot votes for the one that he likes and everyone else dislikes.
```
public class WinLose implements Player
{
public WinLose(int e) { }
public String getName()
{
return "WinLose";
}
public int getVote(int [] voteCounts, int votersRemaining, int [] payoffs, int[] totalPayoffs)
{
int max = 0;
for(int i = 1; i< 3; i++)
{
if(10*payoffs[i]-totalPayoffs[i] > 10*payoffs[max]-totalPayoffs[max])
{
max = i;
}
}
return max;
}
public void receiveResults(int[] voteCounts, double result)
{
}
}
```
] |
[Question]
[
The number `113` is the first prime whose length `3` is prime, digital sum `5 = 1 + 1 + 3` is prime, and digital product `3 = 1 * 1 * 3` is prime.
A prime that has these 3 properties will be called *supremely prime*. The primes `11117` and `1111151` are other examples.
# Goal
Write a program that can find the largest *supremely prime* number possible in less than an hour on a decent modern personal computer (such as the preferred spec [here](http://oit.duke.edu/comp-print/recommendations/hardware_specs.php)).
You should not simply give us a large supreme prime. You need to show us your search process with code that actually works. You can build on your or other people's solutions but be sure to give them credit. We're kind of communally trying to find the largest supreme prime realizable on a normal computer in an hour.
# Scoring
The submission that finds the largest supreme prime wins. If it turns out that there are finitely many supreme primes then the first submission that generates the highest supreme prime wins.
(If you can mathematically prove that either there are or aren't infinitely many supreme primes I'll give you 200 bounty rep just because. :) )
# Details
* You may use any source to generate your primes (e.g. internet).
* You may use probabilistic prime testing methods.
* Everything is in base 10.
* Zero and one are NOT considered prime.
* Primes that contain `0` have a digital product of `0` so obviously they can't be supreme.
* To keep the page less cluttered put large (100+ digit) supreme primes in the form:
```
{[number of 1's before the prime digit]}[prime digit]{[number of 1's after the prime digit]}
```
So `1111151` could be expressed as `{5}5{1}`.
[Answer]
# Python 2.7 on PyPy, {2404}3{1596} (~10^4000)
```
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111113111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
```
Found this one about 50 minutes after starting from 4000. Therefore, I would estimate this is the upper limit of this code approach.
Change: I've noticed that some lengths seem to be more fruitful for generating this sort of prime than others, so I've decided to only check 50 random locations of the digit that isn't 1 instead of all possible locations, before moving on. I'm not completely sure this will improve performance, or that 50 is correct, but we'll see.
Possibilities list is generated based on the fact that for the products requirement to be fulfilled, the number must be all ones except for a prime. In addition, the prime can't be 2 because of the sum and length relationship, and the digital sum must not be divisible by three, giving the %3 requirements.
is\_prime taken from <http://codepad.org/KtXsydxK> , written by @primo
Note: this is\_prime function is actually a Baillie-PSW pseudoprime test, but there are no known counter-examples, so I'm not going to worry about the distinction.
```
#http://codepad.org/KtXsydxK
from my_math import is_prime
import time,random
LLIMIT=2748
time.clock()
start_time=time.time()
checked=0
while time.time()-start_time<3600:
small_primes = [a for a in range(LLIMIT,2*LLIMIT) if is_prime(a)]
leng,dig=(0,0)
for a in small_primes:
if a+2 in small_primes:
leng,dig=(a,3)
break
if a+4 in small_primes:
leng,dig=(a,5)
break
if a+6 in small_primes:
leng,dig=(a,7)
break
start=time.clock()
print leng,dig,time.clock(),checked
for loc in random.sample(range(leng),50):
checked+=1
if is_prime(int('1'*loc+str(dig)+'1'*(leng-loc-1))):
print leng-1,loc,dig,time.clock(),time.clock()-start, \
int('1'*loc+str(dig)+'1'*(leng-loc-1))
break
LLIMIT=leng+1
```
[Answer]
# PARI/GP, 4127 digits
(104127-1)/9 + 2\*10515
This is a fairly straightforward search: check only prime digit lengths, then compute the possible primes to use, then iterate through all possibilities. I special-cased the common cases where there are 0 or 1 suitable prime digits to use.
```
supreme(lim,startAt=3)={
forprime(d=startAt,lim,
my(N=10^d\9, P=select(p->isprime(d+p),[1,2,4,6]), D, n=1);
if(#P==0, next);
if(#P==1,
for(i=0,d-1,
if (ispseudoprime(D=N+n*P[1]), print(D));
n*=10
);
next
);
D=vector(#P-1,i,P[i+1]-P[i]);
for(i=0,d-1,
forstep(k=N+n*P[1],N+n*P[#P],n*D,
if (ispseudoprime(k), print(k))
);
n*=10
)
)
};
supreme(4200, 4100)
```
This took 36 minutes to compute on one core of a fairly old machine. It would have no trouble finding such a prime over 5000 digits in an hour, I'm sure, but I'm also impatient.
A better solution would be to use any reasonable language to do everything but the innermost loop, then construct an abc file for [primeform](http://openpfgw.sourceforge.net/) which is optimized for that particular sort of calculation. This should be able to push the calculation up to at least 10,000 digits.
**Edit**: I implemented the hybrid solution described above, but on my old machine I can't find the first term with >= 10,000 digits in less than an hour. Unless I run it on something faster I'll have to change to a less lofty target.
[Answer]
# Perl, 15101 digits, {83}7{15017}, 8 minutes. Max found: 72227 digits
Using my module [Math::Prime::Util](https://metacpan.org/pod/Math::Prime::Util) and its [GMP back end](https://metacpan.org/pod/Math::Prime::Util::GMP). It has a number of compositeness tests including [is\_prob\_prime()](https://metacpan.org/pod/Math::Prime::Util#is_prob_prime) with an ES BPSW test (slightly more stringent than Pari's ispseudoprime), [is\_prime()](https://metacpan.org/pod/Math::Prime::Util#is_prime) which adds one random-base M-R, and [is\_provable\_prime()](https://metacpan.org/pod/Math::Prime::Util#is_provable_prime) which will run BLS75 T5 or ECPP. At these sizes and types, doing a proof is going to take a long time. I threw in another M-R test in the pedantic verifier sub. Times on a Core2 E7500 which is definitely not my fastest computer (it takes 2.5 minutes on my i7-4770K).
As Tim S. points out, we could keep searching for larger values, up to the point where a single test takes an hour. At ~15000 digits on this E7500 it takes about 26s for an M-R test and 2 minutes for the full is\_prime (trial division plus base-2 M-R plus ES Lucas plus one random-base M-R). My i7-4770K is over 3x faster. I tried a few sizes, mainly seeing how it did on other people's results. I tried 8k, 20k, and 16k, killing each after ~5 minutes. I then tried 15k in progression for ~10m each and got lucky on the 4th one.
OpenPFGW's PRP tests are certainly faster once past 4000 or so digits, and much faster indeed in the 50k+ range. Its test has a fair amount of false positives however, which makes it a great pre-test but one would still like to verify the results with something else.
This could be parallelized with perl threads or using MCE similar to the parallel Fibonacci prime finder examples in the module.
Timing and results on an idle i7-4770K using single core:
* input 3000, 16 seconds, 3019 digits, {318}5{2700}
* input 4000, 47 seconds, 4001 digits, {393}7{3607}
* input 4100, 5 seconds, 4127 digits, {29}7{4097}
* input 6217, 5 seconds, 6217 digits, {23}5{6193}
* input 6500, 5 minutes, 6547 digits, {598}5{5948}
* input 7000, 15 minutes, 7013 digits, {2411}7{4601}
* input 9000, 11 minutes, 9001 digits, {952}7{8048}
* input 12000, 10 minutes, 12007 digits, {652}5{11354}
* input 15100, 2.5 minutes, 15101 digits, {83}7{15017}
* input 24600, 47 minutes, 24671 digits, {621}7{24049}
* input 32060, 18 minutes, 32063 digits, {83}7{31979}
* input 57000, 39 minutes, 57037 digits, {112}5{56924}
* input 72225, 42 minutes, 72227 digits, {16}3{72210}
For the 32k digit result, I started 6 scripts running at the same time each with successive arguments starting at 32000. After 26.5 minutes one finished with the 32063 digit result shown. For 57k I let successive scripts run 6 at a time for an hour in input increments of 500 until the 57k result returned in 57 minutes. The 72k digit result was found by doing successive primes from 70k up, so definitely not found in an hour (though once you know where to start, it is).
The script:
```
#!/usr/bin/env perl
use warnings;
use strict;
use Math::Prime::Util qw/:all/;
use Math::Prime::Util::GMP; # Just to ensure it is used.
my $l = shift || 1000; $l--;
while (1) {
$l = next_prime($l);
my @D = grep { is_prime($l-1 + $_) } (3,5,7);
next unless scalar @D > 0;
for my $s (0 .. $l-1) {
my $e = $l-$s-1;
warn " checking $l $s\n" unless $s % 100;
for my $d (@D) {
my $n = "1"x$s . $d . "1"x$e;
die unless length($n) == $l;
verify_supreme($n,$s,$d,$e) if is_prime($n); # ES BPSW + 1 rand-base M-R
}
}
}
sub verify_supreme { # Be pedantic and verify the result
my($n,$s,$d,$e) = @_;
die "Incorrect length" unless is_prime(length($n));
die "Incorrect sum" unless is_prime(vecsum(split(//,$n)));
my $prod = 1; $prod *= $_ for split(//,$n);
die "Incorrect product" unless is_prime($prod);
die "n is not a prime!" unless miller_rabin_random($n,1); # One more M-R test
die "{$s} $d {$e}\n";
}
```
[Answer]
# Mathematica 3181 digits
Update: There were some serious mistakes in my first submission.
I was able to devote some time to checking the results for this one.
The output is formatted as a list of digits. That makes for easy checking of each of the conditions.
```
f[primeDigitLength_]:=
Module[{id=ConstantArray[1,primeDigitLength-1]},
permutations=Reverse@Sort@Flatten[Table[Insert[id,#,pos],{pos,primeDigitLength}]&/@{3,5,7},1];
Flatten[Select[permutations,PrimeQ[FromDigits[#]]\[And]PrimeQ[Plus@@#]&,1],1]]
```
**Example**
This was my first test, a search for a solution with 3181 digits.
It found the first case in 26 seconds.
Let's go through the reasoning. Then we'll step into the program itself.
Let's start, as I did, "What is the 450th prime?" Can we find a solution with that many digits (3181)?
```
primeDigits = Prime[450]
```
>
> 3181
>
>
>
---
The number is found by joining the digits.
```
number = FromDigits[digits];
```
But rather than display it, we can ask instead what the digits are and where they lie.
```
DigitCount[number]
```
>
> {3180, 0, 0, 0, 0, 0, 1, 0, 0, 0}
>
>
>
This means that there were 3180 instances of the digit 1, and a single instance of the digit 7.
At what position is the digit 7?
```
Position[digits, 7][[1, 1]]
```
>
> 142
>
>
>
So the digit 7 is the 142nd digit. All the others are 1's.
---
Of course, the product of the digits must be a prime, namely 7.
```
digitProduct = Times @@ digits
```
>
> 7
>
>
>
---
And the sum of the digits is also a prime.
```
digitSum = Plus @@ digits
PrimeQ[digitSum]
```
>
> 3187
>
> True
>
>
>
---
And we know that the number of digits is a prime. Remember, we selected the 450th prime, namely 3118.
So all the conditions have been met.
[Answer]
# Python 2.7, 6217 digits: {23}5{6193} 6 mins 51 secs
I was working on my own version and was disappointed to see that @issacg had beaten me to the punch with a very similar approach, albeit with is\_(very\_probably)\_prime(). However, I see that I have some significant differences that result in a better answer in less time (when I also use is\_prime). To make this clear, when also starting from 4000, I arrive at a better 4001 digit answer ({393}7{3607}) in only 26 mins, 37 seconds using the *standard* Python interpreter (also at version 2.7), **not** the PyPy version. Also, I'm not 'spot' checking the numbers. All of the candidates are checked.
Here's the primary improvements:
1. Use a prime generator (<https://stackoverflow.com/questions/567222/simple-prime-generator-in-python/568618#568618>) to create a list of primes to check against and (his version of "small primes") and for generating eligible number lengths.
2. We want to spend our time looking for the largest supreme prime of a given length, not the smallest, so, I construct the largest possible numbers first for checking, not the smallest. Then, once one is found, we can immediately move on to the next length.
# EDIT: Now with multiprocessing
This is a significant change to previous versions. Before, I noticed that my 8-core machine was hardly working, so, I decided to try my hand at multiprocessing in Python (first time). The results are very nice!
In this version, 7 children processes are spawned, which grab a 'task' off a queue of potential possibilities (num\_length + eligible digits). They churn through trying different [7,5,3] positions until it finds one. If it does, informs the master process of the new longest length that has been found. If children are working on a num\_length that is shorter, they just bail, and go get the next length.
I started this run with 6000, and it is still running, but so far, I'm very pleased with the results.
The program doesn't yet stop correctly, but not a huge deal to me.
Now the code:
```
#!/usr/bin/env python
from __future__ import print_function
import sys
from multiprocessing import Pool, cpu_count, Value
from datetime import datetime, timedelta
# is_prime() et al from: http://codepad.org/KtXsydxK - omitted for brevity
# gen_primes() from: https://stackoverflow.com/questions/567222/simple-prime-generator-in-python/568618#568618 - ommitted for brevity
from external_sources import is_prime, gen_primes
def gen_tasks(start_length):
"""
A generator that produces a stream of eligible number lengths and digits
"""
for num_length in gen_primes():
if num_length < start_length:
continue
ns = [ n for n in [7,5,3] if num_length + n - 1 in prime_list ]
if ns:
yield (num_length, ns)
def hunt(num_length, ns):
"""
Given the num_length and list of eligible digits to try, build combinations
to try, and try them.
"""
if datetime.now() > end_time or num_length <= largest.value:
return
print('Tasked with: {0}, {1}'.format(num_length, ns))
sys.stdout.flush()
template = list('1' * num_length)
for offset in range(num_length):
for n in ns:
if datetime.now() > end_time or num_length <= largest.value:
return
num_list = template[:]
num_list[offset] = str(n)
num = int(''.join(num_list))
if is_prime(num):
elapsed = datetime.now() - start_time
largest.value = num_length
print('\n{0} - "{1}"\a'.format(elapsed, num))
if __name__ == '__main__':
start_time = datetime.now()
end_time = start_time + timedelta(seconds=3600)
print('Starting @ {0}, will stop @ {1}'.format(start_time, end_time))
start_length = int(sys.argv[1])
#
# Just create a list of primes for checking. Up to 20006 will cover the first
# 20,000 digits of solutions
#
prime_list = []
for prime in gen_primes():
prime_list.append(prime)
if prime > 20006:
break;
print('prime_list is primed.')
largest = Value('d', 0)
task_generator = gen_tasks(start_length)
cores = cpu_count()
print('Number of cores: {0}'.format(cores))
#
# We reduce the number of cores by 1 because __main__ is another process
#
pool = Pool(processes=cores - 1)
while datetime.now() < end_time:
pool.apply_async(hunt, next(task_generator))
```
[Answer]
## C, [GMP](https://gmplib.org/) - {7224}5{564} = 7789
Kudos to @issacg and all of you guys for the inspirations and tricks.
And also the masterful question asker @Calvin's Hobbies for this question.
Compile:
`gcc -I/usr/local/include -o p_out p.c -pthread -L/usr/local/lib -lgmp`
If you feel like donating your computation power or curious of the performance, feel free copy the code and compile. ;) You will need GMP installed.
```
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<gmp.h>
#include<pthread.h>
#define THREAD_COUNT 1
#define MAX_DIGITS 7800
#define MIN_DIGITS 1000
static void huntSupremePrime(int startIndex) {
char digits[MAX_DIGITS + 1];
for (int i = 0; i < MAX_DIGITS; digits[i++] = '1');
digits[MAX_DIGITS] = '\0';
mpz_t testPrime, digitSum, digitCount, increment;
for (int j = 0; j < MAX_DIGITS - startIndex; digits[j++] = '0');
int step = THREAD_COUNT * 2;
for (int i = startIndex, l = MAX_DIGITS - startIndex; i > MIN_DIGITS - 1;
i -= step, l += step) {
fprintf(stderr, "Testing for %d digits.\n", i);
mpz_init_set_ui(digitCount, i);
if (mpz_millerrabin(digitCount, 10)) {
for (int j = 3; j < 8; j += 2) {
mpz_init_set_ui(digitSum, i - 1 + j);
if (mpz_millerrabin(digitSum, 10)) {
gmp_printf("%Zd \n", digitSum);
digits[MAX_DIGITS - 1] = j + 48;
mpz_init_set_str(testPrime, digits, 10);
mpz_init_set_ui(increment, (j - 1) * 99);
for (int k = 0; k < i/20; ++k) {
if (mpz_millerrabin(testPrime, 25)) {
i = 0;
j = 9;
k = l;
gmp_printf("%Zd\n", testPrime);
break;
}
mpz_add(testPrime, testPrime, increment);
mpz_mul_ui(increment, increment, 100);
fprintf(stderr, "TICK %d\n", k);
}
}
}
}
for (int j = 0; j < step; digits[l + j++] = '0');
}
}
static void *huntSupremePrimeThread(void *p) {
int* startIndex = (int*) p;
huntSupremePrime(*startIndex);
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
int startIndexes[THREAD_COUNT];
pthread_t threads[THREAD_COUNT];
int startIndex = MAX_DIGITS;
for (int i = 0; i < THREAD_COUNT; ++i) {
for (;startIndex % 2 == 0; --startIndex);
startIndexes[i] = startIndex;
int rc = pthread_create(&threads[i], NULL, huntSupremePrimeThread, (void*)&startIndexes[i]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
--startIndex;
}
for (int i = 0; i < THREAD_COUNT; ++i) {
void * status;
int rc = pthread_join(threads[i], &status);
if (rc) {
printf("ERROR: return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
return 0;
}
```
[Answer]
## PFGW, 6067 digits, {5956}7{110}
Run [PFGW](http://sourceforge.net/projects/openpfgw/) with the following input file and `-f100` to prefactor the numbers. In about 2-3 CPU minutes on my computer (i5 Haswell), it finds the PRP (10^(6073-6)-1)/9+6\*10^110, or [{5956}7{110}](http://factordb.com/index.php?id=1100000000697101122). I chose 6000 digits as the starting point as a nothing-up-my-sleeve number that's a little higher than all previous submissions.
```
ABC2 $a-$b & (10^($a-$b)-1)/9+$b*10^$c
a: primes from 6000 to 6200
b: in { 2 4 6 }
c: from 0 to 5990
```
Based on how quickly I was able to find this one, I could easily bump up the number of digits and still find a PRP within an hour. With how the rules are written, I might even just find the size where my CPU, running on all 4 cores, can finish one PRP test in an hour, take a *long* time to find a PRP, and have my "search" consist solely of the one PRP.
P.S. In some senses, this isn't a "code" solution because I didn't write anything besides the input file...but then, many one-line Mathematica solutions to mathematical problems could be described in the same way, as could using a library that does the hard work for you. In reality, I think it's hard to draw a good line between the two. If you like, I could write a script that creates the PFGW input file and calls PFGW. The script could even search in parallel, to use all 4 cores and speed up the search by ~4 times (on my CPU).
P.P.S. I think [LLR](http://www.mersenneforum.org/showthread.php?t=19167) can do the PRP tests for these numbers, and I'd expect it to be [far faster than PFGW](http://mersenneforum.org/showthread.php?t=19425). A dedicated sieving program could also be better at factoring these numbers than PFGW's one-at-a-time. If you combined these, I'm sure you could push the bounds much higher than current solutions.
[Answer]
# Python 2.7, 17-19 digits
```
11111111171111111
```
Found 5111111111111 (13 digits) in 3 seconds and this 17 digit supreme prime in 3 minutes. I'll guess that the target machine could run this and get a 19 digit supreme prime in less than an hour. This approach does not scale well because it keeps primes up to half the number of target digits in memory. 17 digit search requires storing an array of 100M booleans. 19 digits would require a 1B element array, and memory would be exhausted before getting to 23 digits. Runtime probably would be, too.
Primality test approaches that don't involve a ridiculously large array of divisor primes will fare much better.
```
#!/usr/bin/env python
import math
import numpy as np
import sys
max_digits = int(sys.argv[1])
max_num = 10**max_digits
print "largest supreme prime of " + str(max_digits) + " or fewer digits"
def sum_product_digits(num):
add = 0
mul = 1
while num:
add, mul, num = add + num % 10, mul * (num % 10), num / 10
return add, mul
def primesfrom2to(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a array of primes, 2 <= p < n """
sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)/3) ::2*k] = False
sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False
return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]
def checkprime(n):
for divisor in primes:
if (divisor>math.sqrt(n)):
break
if n%divisor==0:
return False
return True
# make an array of all primes we need to check as divisors of our max_num
primes = primesfrom2to(math.sqrt(max_num))
# only consider digit counts that are prime
for num_digits in primes:
if num_digits > max_digits:
break
for ones_on_right in range(0,num_digits):
for mid_prime in ['3','5','7']:
# assemble a number of the form /1*[357]1*/
candidate = int('1'*(num_digits-ones_on_right-1)+mid_prime+'1'*ones_on_right)
# check for primeness of digit sum first digit product first
add, mul = sum_product_digits(candidate)
if add in primes and mul in primes:
# check for primality next
if checkprime(candidate):
# supreme prime!
print candidate
```
[Answer]
# Mathematica 4211 4259 digits
With the number: {1042}7{3168} {388}3{3870}
Which was generated by the following code:
```
TimeConstrained[
Do[
p = Prime[n];
curlargest = Catch[
If[PrimeQ[p + 6],
list = ConstantArray[1, p];
Do[
temp = FromDigits[ReplacePart[list, i -> 7]];
If[PrimeQ[temp],
Throw[temp]
], {i, p}]
];
If[PrimeQ[p + 4],
list = ConstantArray[1, p];
Do[
temp = FromDigits[ReplacePart[list, i -> 5]];
If[PrimeQ[temp],
Throw[temp]
], {i, p}]
];
If[PrimeQ[p + 2],
list = ConstantArray[1, p];
Do[
temp = FromDigits[ReplacePart[list, i -> 3]];
If[PrimeQ[temp],
Throw[temp]
], {i, p}]
];
Throw[curlargest];
]
, {n, 565, 10000}]
, 60*60]
```
The throws cause it to stop testing for other numbers with the same digits as the one currently found.
since it begins testing at the most significant digit this will mean that it always returns the largest number unless the number of digits is a member of a prime triplet.
Simply started testing just below the value of one of the preceding answers :)
Once it finishes, the number is stored in the variable curlargest
[Answer]
# JavaScript, 3019 digits, {2,273}5{745}
This uses the MillerRabin test included in BigInteger.js by Tom Wu.
Starting from **0 => 2,046 digits** = {1799}7{263} **in one hour**.
Starting from **3000 => 3,019 digits** = {2,273}5{745} **in one hour, less 3 seconds**.
When it started from 0, the program skipped ahead and began searching again at a length of 1.5X the length of the last s-prime found. Then when I saw how fast it was running I guessed it would find one starting at 3000 in one hour - which it did with only 3 seconds to spare.
You can try it here: <http://goo.gl/t3TmTk>
(Set to calculate all s-primes, or skip ahead.)
![enter image description here](https://i.stack.imgur.com/NHXYL.jpg)
![enter image description here](https://i.stack.imgur.com/60FMN.jpg)
![enter image description here](https://i.stack.imgur.com/OEJwY.jpg)
The program works by constructing strings of all "1"s, but with one "3", "5", or "7". I added a quick check in the IsStrPrime function to reject numbers ending in "5".
```
if (IsIntPrime(length)) {
var do3s = IsIntPrime(length + 2);
var do5s = IsIntPrime(length + 4);
var do7s = IsIntPrime(length + 6);
if (do3s || do5s || do7s) {
// loop through length of number
var before, digit, after;
for (var after = 0; after <= length - 1; after++) {
before = length - after - 1;
beforeStr = Ones(before);
afterStr = Ones(after);
if (do3s && IsStrPrime(beforeStr + (digit = "3") + afterStr)) { RecordAnswer(); if (brk) break; }
if (AreDone()) break;
if (do5s && IsStrPrime(beforeStr + (digit = "5") + afterStr)) { RecordAnswer(); if (brk) break; }
if (AreDone()) break;
if (do7s && IsStrPrime(beforeStr + (digit = "7") + afterStr)) { RecordAnswer(); if (brk) break; }
if (AreDone()) break;
if (after % 10 == 0) document.title = "b=" + bestLength + ", testing=" + length + "-" + after;
}
}
}
```
This was pretty fun. Reminds me of a puzzle I did many years back to calculate what's called a **digit removed prime**. This is a prime number that if you remove any digit, then the remaining number is still prime. For example 1037 is a digit removed prime because 1037, 037, 137, 107, and 103 are prime. I found one 84 digits long, and the longest I know of is 332 digits long. I'm sure we could find one much longer with the techniques used for this puzzle. (But choosing the trial numbers is a little bit trickier - maybe?)
[Answer]
# Python 3.9.2, with [sympy](https://docs.sympy.org/latest/index.html) and [gmpy2](https://gmpy2.readthedocs.io/en/latest/), 3019 digits
Completed the search **from 3000 digits to 3019 digits in approximately 10 minutes** on my laptop.
Port of [@Charles's Pari/GP answer](https://codegolf.stackexchange.com/a/35474/110802) in Python.
```
import sympy
import gmpy2
import time
def supreme(lim, startAt=3):
for d in sympy.primerange(startAt, lim + 1):
N = 10**d // 9
P = [p for p in [1,2,4,6] if sympy.isprime(d + p)]
if len(P) == 0:
continue
if len(P) == 1:
n = 1
for i in range(0, d):
if gmpy2.is_strong_bpsw_prp(N + n * P[0]):
print(N + n * P[0])
n *= 10
continue
D = [P[i+1] - P[i] for i in range(len(P) - 1)]
n = 1
for i in range(0, d):
for k in range(N + n * P[0], N + n * P[-1] + 1, n * D[0]):
if gmpy2.is_strong_bpsw_prp(k):
print(k)
n *= 10
start_time=time.time()
supreme(3019, 3000)
print(f"The search ends in {time.time()-start_time} seconds")
```
```
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111151111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111115111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
The search ends in 606.180704832077 seconds
```
[Answer]
# Axiom, 3019 digits {318}5{2700}
```
)time on
-- Return true if n is pseudo prime else return false
-- **Can Fail**
prime1(n:PI):Boolean==
n=1=>false
n<4=>true
i:=5;sq:=sqrt(1.*n)
repeat
if i>sq or i>50000 then break
if n rem i=0 then return false
i:=i+2
if i~=50001 then return true
--output("i")
if powmod(3,n,n)=3 then return true
--output("e")
false
-- input 'n': must be n>1 prime
-- output [0] if not find any number, else return
-- [n,a,b,c,z] 'n' digits of solution,
-- 'a' number of '1', 'b' central digit, 'b' number of final digit '1'
-- 'z' the number found
g(n:PI):List NNI==
x:=b:=z:=1
for i in 1..n-1 repeat
z:=z*10+1
b:=b*10
repeat
--output b
k:=0 -- 3 5 7 <-> 2 4 6
for i in [2,4,6] repeat
~prime?(n+i)=>0 --somma
k:=k+1
t:=z+b*i
if prime1(t) then return [n,x-1,i+1,n-x,t]
--if x=1 then output ["k=", k]
if k=0 then break
x:=x+1
b:=b quo 10
if b<=0 then break
[0]
-- start from number of digits n
-- and return g(i) with i prime i>=n
find(n:PI):List NNI==
i:=n
if i rem 2=0 then i:=i+1
repeat
if prime?(i) then --solo le lunghezze prime sono accettate
output i
a:=g(i)
if a~=[0] then return a
i:=i+2
```
result from the start value 3000 in 529 sec
```
(4) -> find(3000)
3001
3011
3019
(4)
[3019, 318, 5, 2700, Omissis]
Type: List NonNegativeInteger
Time: 0.02 (IN) + 525.50 (EV) + 0.02 (OT) + 3.53 (GC) = 529.07 sec
```
] |
[Question]
[
Your goal is to generate a [Fibonacci spiral](https://en.wikipedia.org/wiki/Fibonacci_number) with numbers.
![Sample](https://i.stack.imgur.com/eHWK9.png)
### Example Input / Output
```
1 -> 1
2 -> 1 1
3 -> 1 1
2 2
2 2
6 -> 8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 1 1 3 3 3
8 8 8 8 8 8 8 8 2 2 3 3 3
8 8 8 8 8 8 8 8 2 2 3 3 3
```
[Input of 9](http://pastebin.com/Gvagy4LQ)
**Input**
The input can be taken through STDIN or function argument. It will be a single number
**Output**
The output can be from STDOUT or a function's return value. It should be a single string.
Extra whitespace at the very end of the line is not allowed. The output can contain digits, linefeeds (newlines), and spaces.
Orientation does not matter, this means rotations and reflections. As long as it follows a valid Fibonacci spiral pattern.
Numbers with different amounts of digits (e.g. 1 and 13) should be right-aligned with each other. A space may need to be added to the very beginning of a line so everything can line up.
```
1 1 1 1
100 100 should actually be 100 100
```
You can see an example [here](http://pastebin.com/ysVyi4qY)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins!
[Answer]
## APL, 23
```
{a,⍴⍨2⍴⊃⍴a←⌽⍉⍵}⍣(⎕-1)⍪1
```
Explanation:
```
⍪1 this creates a 1x1 matrix containing just 1
{..}⍣(⎕-1) the power operator (⍣) repeats the function {} user input - 1 times
a,⍴⍨2⍴⊃⍴a←⌽⍉⍵ the function being iterated rotates the matrix and appends the next matrix to it.
```
Try it on [tryapl.org](http://www.tryapl.org/?a=%7Ba%2C%u2374%u23682%u2374%u2283%u2374a%u2190%u233D%u2349%u2375%7D%u2363%288-1%29%u236A1&run)
[Answer]
# Matlab, 84 bytes
A function is used. Output is in stdout.
```
function f(N)
s=0;t=1;y=1;for n=2:N
u=s+t;s=t;t=u;y=[rot90(y) t*ones(t)];end;disp(y)
```
Examples:
```
>> f(1)
1
>> f(2)
1 1
>> f(3)
1 2 2
1 2 2
>> f(6)
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
3 3 3 1 1 8 8 8 8 8 8 8 8
3 3 3 2 2 8 8 8 8 8 8 8 8
3 3 3 2 2 8 8 8 8 8 8 8 8
>> f(7)
8 8 8 8 8 8 8 8 13 13 13 13 13 13 13 13 13 13 13 13 13
8 8 8 8 8 8 8 8 13 13 13 13 13 13 13 13 13 13 13 13 13
8 8 8 8 8 8 8 8 13 13 13 13 13 13 13 13 13 13 13 13 13
8 8 8 8 8 8 8 8 13 13 13 13 13 13 13 13 13 13 13 13 13
8 8 8 8 8 8 8 8 13 13 13 13 13 13 13 13 13 13 13 13 13
8 8 8 8 8 8 8 8 13 13 13 13 13 13 13 13 13 13 13 13 13
8 8 8 8 8 8 8 8 13 13 13 13 13 13 13 13 13 13 13 13 13
8 8 8 8 8 8 8 8 13 13 13 13 13 13 13 13 13 13 13 13 13
5 5 5 5 5 1 2 2 13 13 13 13 13 13 13 13 13 13 13 13 13
5 5 5 5 5 1 2 2 13 13 13 13 13 13 13 13 13 13 13 13 13
5 5 5 5 5 3 3 3 13 13 13 13 13 13 13 13 13 13 13 13 13
5 5 5 5 5 3 3 3 13 13 13 13 13 13 13 13 13 13 13 13 13
5 5 5 5 5 3 3 3 13 13 13 13 13 13 13 13 13 13 13 13 13
```
## Matlab, 78 bytes
```
function y=f(N)
s=0;t=1;y=1;for n=2:N
u=s+t;s=t;t=u;y=[rot90(y) t*ones(t)];end
```
Same as above except a Matlab's feature is exploited, namely, it automatically displays function output (as a string) in stdout. This avoids the conversion to string in the above approach.
```
f(6)
ans =
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
3 3 3 1 1 8 8 8 8 8 8 8 8
3 3 3 2 2 8 8 8 8 8 8 8 8
3 3 3 2 2 8 8 8 8 8 8 8 8
```
[Answer]
# Python 2, 121 bytes
```
a,b=0,1;L=[]
exec"a,b=b,a+b;L=zip(*L[::-1])+[[a]*a]*a;"*input()
for r in L:print" ".join("%*d"%(len(str(a)),x)for x in r)
```
The relaxed rules on rotations makes this a lot simpler.
I haven't used backticks in place of `str(a)` here because I'm not sure whether we're allowed more leading spaces than necessary, if we ever reach longs. Although, even if we were, using `a` itself would be shorter anyway.
[Answer]
# Ruby, ~~243~~ ~~242~~ ~~236~~ ~~233~~ ~~222~~ ~~170~~ 130 bytes
```
s,l,r=0,1,[]
gets.to_i.times{s+=l
l=s-l
s.times{r<<[s]*s}
r=r.transpose.reverse}
r.map{|w|puts w.map{|c|"%#{s.to_s.size}s"%c}*" "}
```
[Answer]
# Python - ~~189~~ ~~179~~ 174
```
n=int(input())
f=[1,1]
while len(f)<n:f+=[f[-1]+f[-2]]
o=[[]]
for i in f:o=(list(zip(*o)))[::-1]+[[i]*i]*i
for x in o:print(' '.join(str(y).rjust(len(str(f[-1])))for y in x))
```
[Answer]
# J, 36 bytes
```
1&(($~,~)@(1{$@]),.|:@|.@])&(,.1)@<:
```
Usage:
```
(1&(($~,~)@(1{$@]),.|:@|.@])&(,.1)@<:) 6
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 1 1 3 3 3
8 8 8 8 8 8 8 8 2 2 3 3 3
8 8 8 8 8 8 8 8 2 2 3 3 3
```
Method:
The function rotates the current square and adds the new square to the current one `input-1` times. Square size and element values are gathered from the size of the previous rectangle.
Code explanation:
```
1&( loop
($~,~) new square with size and elements
@(1{$@]) with the size of the second dimension of the current rectangle
,. attached to
|:@|.@] rotated current rectangle
)&(,.1) starting the loop with matrix 1
@<: looping input-1 times
```
[Try it online here.](http://tryj.tk/)
[Answer]
## Haskell, 183 176 171 163 bytes
```
import Data.List
s t=map((t>>[l t])++)t
e 1=[[1]];e n=s.reverse.transpose$e$n-1
f=g.e
g m=unlines$map(>>=((show$l m)#).show)m
a#b|l a<l b=b;a#b=a#(' ':b)
l=length
```
The function is `f`, which takes a number and returns a single string:
```
λ: putStr $ f 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 5 5 5 5 5 8 8 8 8 8 8 8 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 5 5 5 5 5 8 8 8 8 8 8 8 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 5 5 5 5 5 8 8 8 8 8 8 8 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 5 5 5 5 5 8 8 8 8 8 8 8 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 5 5 5 5 5 8 8 8 8 8 8 8 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 3 3 3 1 1 8 8 8 8 8 8 8 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 3 3 3 2 2 8 8 8 8 8 8 8 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 3 3 3 2 2 8 8 8 8 8 8 8 8
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
```
[Answer]
# Pyth, 34 bytes
```
jbmsm.[hl`lhZ`k\ d=Zu+_CGmmlGGGQ]]
```
Surprisingly, more than half of the code is printing/padding, rather than generating the matrix.
The generation of the matrix is really simple however, it consists of a transpose and reversal, and adding N lines containing N copies of N, where N is the current number of lines.
Example output for 7:
```
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
5 5 5 5 5 8 8 8 8 8 8 8 8
3 3 3 1 1 8 8 8 8 8 8 8 8
3 3 3 2 2 8 8 8 8 8 8 8 8
3 3 3 2 2 8 8 8 8 8 8 8 8
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
```
[Answer]
## Perl, ~~289 277~~ 257 bytes
```
@f=(0,1);push@f,$f[-1]+$f[-2]while(@f<=$ARGV[0]);$d=1+length$f[-1];shift@f;map{$v=$f[$_];$t=sprintf("%${d}d",$v)x$v;$_%4||map{unshift@s,$t}1..$v;$_%4==3&&map{$_.=$t}@s;$_%4==2&&map{push@s,$t}1..$v;$_%4==1&&map{$_=$t.$_}@s;}0..$#f;$\=$/;for(@s){s/^ //;print}
```
[Answer]
# K, 48 bytes
```
{{`0:1_',/'(1+#$|//x)$x}(x-1){+|x,\:t#t:#x}/,,1}
```
And in action:
```
{{`0:1_',/'(1+#$|//x)$x}(x-1){+|x,\:t#t:#x}/,,1}7
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 1 1 3 3 3
8 8 8 8 8 8 8 8 2 2 3 3 3
8 8 8 8 8 8 8 8 2 2 3 3 3
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
```
May still be some good opportunities for golfing.
The program basically consists of two parts- generating the concatenated matrix and formatting it for output. The former is fairly simple:
```
{(x-1){+|x,\:t#t:#x}/,,1}5
(3 3 3 2 2
3 3 3 2 2
3 3 3 1 1
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5)
```
Beginning with a 1x1 matrix containing 1, build a T-length vector of T where T is the length of the starting matrix on the first dimension (`t#t:#x`) and attach that to each row of the original matrix (`x,\:`). Reversing and transposing the result (`+|`) rotates it 90 degrees. We do this N-1 times.
Formatting is pretty clunky, because K's natural approach to printing a matrix won't align number columns the way we need:
```
{`0:1_',/'(1+#$|//x)$x}
```
The basic idea is to take the maximum element of the matrix (`|//x`), convert it to a string (unary `$`), take its length plus one (`1+#`) and then format the elements of the matrix to right aligned strings of that size. Then to tidy up, join those strings (`,/'`) and drop the resulting leading space (`1_'`).
[Answer]
# CJam, 48 bytes
```
1saali({z{W%}%_0=,__sa*a*+}*_W=W=,):U;{USe[}f%N*
```
[Try it online](http://cjam.aditsu.net/#code=1saali(%7Bz%7BW%25%7D%25_0%3D%2C__sa*a*%2B%7D*_W%3DW%3D%2C)%3AU%3B%7BUSe%5B%7Df%25N*&input=7)
The core part of generating the pattern seems reasonably straightforward. Rotate the rectangle created so far, and add a square of values at the bottom.
The code for padding the result looks awful, though. I tried a bunch of combinations of `f` and `:` operators to apply the padding to the nested list, but nothing worked. If anybody has better suggestions, they are most welcome.
```
1s First value. Using string for values so that we can pad them in the end.
aa Wrap it twice. Data on stack will be a list of lists (list of lines).
li Get input.
( Decrement, since we seeded the list at n=1.
{ Loop over n.
z Transpose...
{W%}% ... and reverse all lines, resulting in a 90 degree rotation.
_0=, Get length of line, which is the size of square we need to add.
__ Create two copies of size.
sa Convert one size to string, and wrap it in array.
* Replicate it size times. This is one line.
a Wrap the line...
* ... and replicate it size times. The square of new values is done.
+ Add the list of lines to the previous list of lines.
}* End of loop over n.
_W=W= Get last value produced.
,) Take its length, and increment it. This is the output field width.
:U; Store the field width in variable, and pop it. This is ugly.
{ Start of block applied to all values.
U Field width stored in variable.
S Space.
e[ Pad left.
}f% End of block applied to all values.
N* Join lines with newline.
```
[Answer]
# Pyth, 29 bytes
```
Vu+C_GmmlGGGQ\]Yjdm.\[l`lN`d\ N
```
[Demonstration.](https://pyth.herokuapp.com/?code=Vu%2BC_GmmlGGGQ%5DYjdm.%5Bl%60lN%60d%5C%20N&input=7&debug=0)
If padding was free/implicit, like in APL, or matrix output was allowed, this would be 14 bytes:
```
u+C_GmmlGGGQ]Y
```
[Answer]
## Ruby, 129 bytes
I edited the other ruby answer a bunch, but my most recent change is not being accepted or something, so here it is:
```
s,r=0,[[1]]
gets.to_i.times{s+=r[0][0]
r=(r+[[s]*s]*s).transpose.reverse}
r.map{|w|puts w.map{|c|"%#{r[0][s].to_s.size}s"%c}*' '}
```
[Answer]
## ES6, 248 bytes
```
n=>(f=(n,o=n)=>Array(n).fill(o),g=n=>n<3?[f(n,1)]:(a=g(n-2)).reverse().concat(f(l=a[0].length,f(l))).map((e,i,a)=>f(a.length).concat(e.reverse())),a=g(n),s=' '.repeat(l=` ${a[0][0]}`.length),a.map(a=>a.map((e,i)=>(s+e).slice(!i-1)).join``).join`\n`)
```
Where `\n` represents a literal newline character.
Annoyingly the formatting takes up a large chunk of the code.
`f` is a helper function that makes a filled array. It's used mostly to create the filled squares but also handily doubles up to produce the base cases for the recursion.
`g` is the main gruntwork. It recursively generates the last but one solution, rotates it 180 degrees, then appends the next two squares.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/8629/edit).
Closed 3 years ago.
[Improve this question](/posts/8629/edit)
Write a program to factorize a semi-prime number in the shortest amount of time.
For testing purposes, use this:
\$38!+1\$ (\$523022617466601111760007224100074291200000001\$)
It is equal to:
\$14029308060317546154181 × 37280713718589679646221\$
[Answer]
## Python (w/ pypy2 v7.3.1) ~0.9s
Using a [Multiple Polynomial Quadratic Sieve](http://en.wikipedia.org/wiki/Quadratic_sieve#Multiple_polynomials). I took this to be a code challenge, so I opted not to use any external libraries (other than the standard `log` function, I suppose). When timing, the [PyPy JIT](http://pypy.org/) should be used, as it results in timings 4-5 times faster than that of [cPython](http://www.python.org/).
**Update (2013-07-29):**
Since originally posting, I've made several minor, but significant changes which increase the overall speed by a factor of about 2.5x.
**Update (2014-08-27):**
As this post is still receiving attention, I've updated `my_math.py` correcting two errors, for anyone who may be using it:
* `isqrt` was faulty, sometimes producing incorrect output for values very close to a perfect square. This has been corrected, and the performance increased by using a much better seed.
* `is_prime` has been updated. My previous attempt to remove perfect square 2-sprps was half-hearted, at best. I've added a 3-sprp check - a technique used by Mathmatica - to ensure that the tested value is square-free.
**Update (2014-11-24):**
If at the end of the calculation no non-trivial congruencies are found, the progam now sieves additional polynomials. This was previously marked in the code as `TODO`.
**Update (2020-08-29):**
A few improvements resulting in minor performance gains, including:
* Calculating the average contributation of the skipped primes, rather than roughly approximating.
* Actually sieving powers of the prime factor base. The modular square root of each power can be computed efficiently through use of [Hensel Lifting](https://en.wikipedia.org/wiki/Hensel%27s_lemma#Hensel_lifting).
* Reusing the sieve array in subsequent iterations, rather than creating a new one.
---
**mpqs.py**
```
import math
import my_math
import time
# Multiple Polynomial Quadratic Sieve
# assumes n is composite
def mpqs(n, verbose=False):
if verbose:
time1 = time.time()
root_n = my_math.isqrt(n)
root_2n = my_math.isqrt(n+n)
# formula chosen by experimentation
# seems to be close to optimal for n < 10^50
bound = int(7.5 * math.log(n, 10)**2)
prime = []
mod_root = []
log_p = []
num_prime = 0
# size of the sieve
x_max = bound * 5
x_max_2 = x_max+x_max
# maximum value on the sieved range
m_val = (x_max * root_2n) >> 1
# find a number of small primes for which n is a quadratic residue
pg = my_math.primes()
p = pg.next()
while p < bound or num_prime < 3:
# legendre (n|p) is only defined for odd p
if p > 2:
leg = my_math.legendre(n, p)
else:
leg = n & 1
if leg == 1:
prime += [p]
log_p += [math.log(p, 10)]
r = int(my_math.mod_sqrt(n, p))
roots = [r]
q = p
while q < x_max:
# find all square roots mod p^n via Hensel Lifting
r = int((r + (n - r*r)*my_math.mod_inv(r+r, q))%q)
#assert r*r%q == n%q
roots += [r]
q *= p
mod_root += [roots]
num_prime += 1
elif leg == 0:
if verbose:
print 'trial division found factors:'
print p, 'x', n/p
return p
p = pg.next()
# fudging the threshold down a bit makes it easier to find powers of partial-partial
# relationships, but it also makes the smoothness check slower. reducing by twice the log
# of the largest prime in the factor base results in cofactors less than that value squared
thresh = math.log(m_val, 10) - log_p[-1]*2
# skip small primes. they contribute very little to the log sum
# and add a lot of unnecessary entries to the table
# instead, fudge the threshold down a bit, according to expected number of factors
min_prime = int(thresh*2)
sp_idx = my_math.binary_search(prime, min_prime)
sieve_primes = prime[sp_idx:]
fudge = sum([log_p[i]/(prime[i]-1) for i in xrange(sp_idx)])
sums = [fudge]*x_max_2
if verbose:
print 'smoothness bound:', bound
print 'sieve size:', x_max
print 'log threshold:', thresh
print 'skipping primes less than:', min_prime
smooth = []
used_prime = set()
partial = {}
num_smooth = 0
prev_num_smooth = 0
num_used_prime = 0
num_partial = 0
num_poly = 0
root_A = my_math.isqrt(root_2n / x_max)
if verbose:
print 'sieving for smooths...'
while True:
# find an integer value A such that:
# A is =~ sqrt(2*n) / x_max
# A is a perfect square
# sqrt(A) is prime, and n is a quadratic residue mod sqrt(A)
while True:
root_A = my_math.next_prime(root_A)
leg = my_math.legendre(n, root_A)
if leg == 1:
break
elif leg == 0:
if verbose:
print 'dumb luck found factors:'
print root_A, 'x', n/root_A
return root_A
A = root_A * root_A
# solve for an adequate B
# B*B is a quadratic residue mod n, such that B*B-A*C = n
# this is unsolvable if n is not a quadratic residue mod sqrt(A)
b = my_math.mod_sqrt(n, root_A)
B = (b + (n - b*b) * my_math.mod_inv(b + b, root_A))%A
# B*B-A*C = n <=> C = (B*B-n)/A
C = (B*B - n) / A
num_poly += 1
# sieve for prime factors
i = sp_idx
for p in sieve_primes:
logp = log_p[i]
e = 0
q = p
while q < x_max:
inv_A = my_math.mod_inv(A, q)
# modular root of the quadratic
a = int(((mod_root[i][e] - B) * inv_A)%q)
b = int(((q - mod_root[i][e] - B) * inv_A)%q)
amx = a+x_max
bmx = b+x_max
apx = amx-q
bpx = bmx-q
k = q
while k < x_max:
sums[apx+k] += logp
sums[bpx+k] += logp
sums[amx-k] += logp
sums[bmx-k] += logp
k += q
q *= p
e += 1
i += 1
# check for smooths
x = -x_max
i = 0
while i < x_max_2:
v = sums[i]
if v > thresh:
vec = set()
sqr = []
# because B*B-n = A*C
# (A*x+B)^2 - n = A*A*x*x+2*A*B*x + B*B - n
# = A*(A*x*x+2*B*x+C)
# gives the congruency
# (A*x+B)^2 = A*(A*x*x+2*B*x+C) (mod n)
# because A is chosen to be square, it doesn't need to be sieved
sieve_val = (A*x + B+B)*x + C
if sieve_val < 0:
vec = {-1}
sieve_val = -sieve_val
for p in prime:
while sieve_val%p == 0:
if p in vec:
# keep track of perfect square factors
# to avoid taking the sqrt of a gigantic number at the end
sqr += [p]
vec ^= {p}
sieve_val = int(sieve_val / p)
if sieve_val == 1:
# smooth
smooth += [(vec, (sqr, (A*x+B), root_A))]
used_prime |= vec
elif sieve_val in partial:
# combine two partials to make a (xor) smooth
# that is, every prime factor with an odd power is in our factor base
pair_vec, pair_vals = partial[sieve_val]
sqr += list(vec & pair_vec) + [sieve_val]
vec ^= pair_vec
smooth += [(vec, (sqr + pair_vals[0], (A*x+B)*pair_vals[1], root_A*pair_vals[2]))]
used_prime |= vec
num_partial += 1
else:
# save partial for later pairing
partial[sieve_val] = (vec, (sqr, A*x+B, root_A))
x += 1
# reset the value for the next go
sums[i] = fudge
i += 1
prev_num_smooth = num_smooth
num_smooth = len(smooth)
num_used_prime = len(used_prime)
if verbose:
print 100 * num_smooth / num_prime, 'percent complete\r',
if num_smooth > num_used_prime and num_smooth > prev_num_smooth:
if verbose:
print '%d polynomials sieved (%d values)'%(num_poly, num_poly*x_max_2)
print 'found %d smooths (%d from partials) in %.3f seconds'%(num_smooth, num_partial, time.time()-time1)
print 'solving for non-trivial congruencies...'
# set up bit fields for gaussian elimination
masks = []
mask = 1
bit_fields = [0]*num_used_prime
for vec, vals in smooth:
masks += [mask]
i = 0
for p in used_prime:
if p in vec: bit_fields[i] |= mask
i += 1
mask += mask
# row echelon form
col_offset = 0
null_cols = []
for col in xrange(num_smooth):
pivot = col-col_offset == num_used_prime or bit_fields[col-col_offset] & masks[col] == 0
for row in xrange(col+1-col_offset, num_used_prime):
if bit_fields[row] & masks[col]:
if pivot:
bit_fields[col-col_offset], bit_fields[row] = bit_fields[row], bit_fields[col-col_offset]
pivot = False
else:
bit_fields[row] ^= bit_fields[col-col_offset]
if pivot:
null_cols += [col]
col_offset += 1
# reduced row echelon form
for row in xrange(num_used_prime):
# lowest set bit
mask = bit_fields[row] & -bit_fields[row]
for up_row in xrange(row):
if bit_fields[up_row] & mask:
bit_fields[up_row] ^= bit_fields[row]
# check for non-trivial congruencies
for col in null_cols:
all_vec, (lh, rh, rA) = smooth[col]
lhs = lh # sieved values (left hand side)
rhs = [rh] # sieved values - n (right hand side)
rAs = [rA] # root_As (cofactor of lhs)
i = 0
for field in bit_fields:
if field & masks[col]:
vec, (lh, rh, rA) = smooth[i]
lhs += list(all_vec & vec) + lh
all_vec ^= vec
rhs += [rh]
rAs += [rA]
i += 1
factor = my_math.gcd(my_math.list_prod(rAs)*my_math.list_prod(lhs) - my_math.list_prod(rhs), n)
if 1 < factor < n:
break
else:
if verbose:
print 'none found.'
continue
break
if verbose:
print 'factors found:'
print factor, 'x', n/factor
print 'time elapsed: %.3f seconds'%(time.time()-time1)
return factor
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Uses a MPQS to factor a composite number')
parser.add_argument('composite', metavar='number_to_factor', type=long, help='the composite number to factor')
parser.add_argument('--verbose', dest='verbose', action='store_true', help="enable verbose output")
args = parser.parse_args()
if args.verbose:
mpqs(args.composite, args.verbose)
else:
time1 = time.time()
print mpqs(args.composite)
print 'time elapsed: %.3f seconds'%(time.time()-time1)
```
**my\_math.py**
```
import math
import mpqs
# primes less than 212
small_primes = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97,101,103,107,109,113,127,131,137,139,149,151,
157,163,167,173,179,181,191,193,197,199,211]
# pre-calced sieve of eratosthenes for n = 2, 3, 5, 7
indices = [
1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,
107,109,113,121,127,131,137,139,143,149,151,157,
163,167,169,173,179,181,187,191,193,197,199,209]
# distances between sieve values
offsets = [
10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6,
6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4,
2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6,
4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2]
# tabulated, mod 105
dindices =[
0,10, 2, 0, 4, 0, 0, 0, 8, 0, 0, 2, 0, 4, 0,
0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 6, 0, 0, 2,
0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 2,
0, 6, 6, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 4, 2,
0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 6, 2,
0, 6, 0, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 8,
0, 0, 2, 0,10, 0, 0, 4, 0, 0, 0, 2, 0, 4, 2]
max_int = 2147483647
# returns the index of x in a sorted list a
# or the index of the next larger item if x is not present
# i.e. the proper insertion point for x in a
def binary_search(a, x):
s = 0
e = len(a)
m = e >> 1
while m != e:
if a[m] < x:
s = m
m = (s + e + 1) >> 1
else:
e = m
m = (s + e) >> 1
return m
# divide and conquer list product
def list_prod(a):
while len(a) > 1:
a = [m*n for m,n in zip(a[::2], a[1::2] + [1])]
return a[0]
# greatest common divisor of a and b
def gcd(a, b):
while b:
a, b = b, a%b
return a
# extended gcd
def ext_gcd(a, m):
a = int(a%m)
x, u = 0, 1
while a:
x, u = u, x - (m/a)*u
m, a = a, m%a
return (m, x, u)
# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
return pow(a, (m-1) >> 1, m)
# modular inverse of a mod m
def mod_inv(a, m):
return ext_gcd(a, m)[1]
# modular sqrt(n) mod p
# p must be prime
def mod_sqrt(n, p):
a = n%p
if p%4 == 3:
return pow(a, (p+1) >> 2, p)
elif p%8 == 5:
v = pow(a << 1, (p-5) >> 3, p)
i = ((a*v*v << 1) % p) - 1
return (a*v*i)%p
elif p%8 == 1:
# Shanks' method
q = p-1
e = 0
while q&1 == 0:
e += 1
q >>= 1
n = 2
while legendre(n, p) != p-1:
n += 1
w = pow(a, q, p)
x = pow(a, (q+1) >> 1, p)
y = pow(n, q, p)
r = e
while True:
if w == 1:
return x
v = w
k = 0
while v != 1 and k+1 < r:
v = (v*v)%p
k += 1
if k == 0:
return x
d = pow(y, 1 << (r-k-1), p)
x = (x*d)%p
y = (d*d)%p
w = (w*y)%p
r = k
else: # p == 2
return a
#integer sqrt of n
def isqrt(n):
c = (n << 2)/3
d = c.bit_length()
a = d>>1
if d&1:
x = 1 << a
y = (x + (n >> a)) >> 1
else:
x = (3 << a) >> 2
y = (x + (c >> a)) >> 1
if x != y:
x = y
y = (x + n/x) >> 1
while y < x:
x = y
y = (x + n/x) >> 1
return x
# integer cbrt of n
def icbrt(n):
d = n.bit_length()
if d%3 == 2:
x = 3 << d/3-1
else:
x = 1 << d/3
y = (2*x + n/(x*x))/3
if x != y:
x = y
y = (2*x + n/(x*x))/3
while y < x:
x = y
y = (2*x + n/(x*x))/3
return x
# strong probable prime
def is_sprp(n, b=2):
if n < 2: return False
d = n-1
s = 0
while d&1 == 0:
s += 1
d >>= 1
x = pow(b, d, n)
if x == 1 or x == n-1:
return True
for r in xrange(1, s):
x = (x * x)%n
if x == 1:
return False
elif x == n-1:
return True
return False
# lucas probable prime
# assumes D = 1 (mod 4), (D|n) = -1
def is_lucas_prp(n, D):
P = 1
Q = (1-D) >> 2
# n+1 = 2**r*s where s is odd
s = n+1
r = 0
while s&1 == 0:
r += 1
s >>= 1
# calculate the bit reversal of (odd) s
# e.g. 19 (10011) <=> 25 (11001)
t = 0
while s:
if s&1:
t += 1
s -= 1
else:
t <<= 1
s >>= 1
# use the same bit reversal process to calculate the sth Lucas number
# keep track of q = Q**n as we go
U = 0
V = 2
q = 1
# mod_inv(2, n)
inv_2 = (n+1) >> 1
while t:
if t&1:
# U, V of n+1
U, V = ((U + V) * inv_2)%n, ((D*U + V) * inv_2)%n
q = (q * Q)%n
t -= 1
else:
# U, V of n*2
U, V = (U * V)%n, (V * V - 2 * q)%n
q = (q * q)%n
t >>= 1
# double s until we have the 2**r*sth Lucas number
while r:
U, V = (U * V)%n, (V * V - 2 * q)%n
q = (q * q)%n
r -= 1
# primality check
# if n is prime, n divides the n+1st Lucas number, given the assumptions
return U == 0
## Baillie-PSW ##
# this is technically a probabalistic test, but there are no known pseudoprimes
def is_bpsw(n):
if not is_sprp(n, 2): return False
# idea shamelessly stolen from Mathmatica's PrimeQ
# if n is a 2-sprp and a 3-sprp, n is necessarily square-free
if not is_sprp(n, 3): return False
a = 5
s = 2
# if n is a perfect square, this will never terminate
while legendre(a, n) != n-1:
s = -s
a = s-a
return is_lucas_prp(n, a)
# an 'almost certain' primality check
def is_prime(n):
if n < 212:
m = binary_search(small_primes, n)
return n == small_primes[m]
for p in small_primes:
if n%p == 0:
return False
# if n is a 32-bit integer, perform full trial division
if n <= max_int:
p = 211
while p*p < n:
for o in offsets:
p += o
if n%p == 0:
return False
return True
return is_bpsw(n)
# next prime strictly larger than n
def next_prime(n):
if n < 2:
return 2
n += 1
if n < 212:
m = binary_search(small_primes, n)
return small_primes[m]
# find our position in the sieve rotation via binary search
x = int(n%210)
m = binary_search(indices, x)
i = int(n + (indices[m] - x))
# adjust offsets
offs = offsets[m:] + offsets[:m]
while True:
for o in offs:
if is_prime(i):
return i
i += o
# an infinite prime number generator
def primes(start = 0):
for n in small_primes[start:]: yield n
pg = primes(6)
p = pg.next()
q = p*p
sieve = {221: 13, 253: 11}
n = 211
while True:
for o in offsets:
n += o
stp = sieve.pop(n, 0)
if stp:
nxt = n/stp
nxt += dindices[nxt%105]
while nxt*stp in sieve:
nxt += dindices[nxt%105]
sieve[nxt*stp] = stp
elif n < q:
yield n
else:
sieve[q + dindices[p%105]*p] = p
p = pg.next()
q = p*p
# true if n is a prime power > 0
def is_prime_power(n):
if n > 1:
for p in small_primes:
if n%p == 0:
n /= p
while n%p == 0: n /= p
return n == 1
r = isqrt(n)
if r*r == n:
return is_prime_power(r)
s = icbrt(n)
if s*s*s == n:
return is_prime_power(s)
p = 211
while p*p < r:
for o in offsets:
p += o
if n%p == 0:
n /= p
while n%p == 0: n /= p
return n == 1
if n <= max_int:
while p*p < n:
for o in offsets:
p += o
if n%p == 0:
return False
return True
return is_bpsw(n)
return False
max_trial = 1e10
max_pollard = 1e22
def factor(n):
if n < max_trial:
return factor_trial(n)
for p in small_primes:
if n%p == 0:
return [p] + factor(n/p)
if is_prime(n):
return [n]
if n < max_pollard:
p = pollard_rho(n)
else:
p = lenstra_ecf(n) or mpqs.mpqs(n)
return factor(p) + factor(n/p)
def factor_trial(n):
a = []
for p in small_primes:
while n%p == 0:
a += [p]
n /= p
i = 211
while i*i < n:
for o in offsets:
i += o
while n%i == 0:
a += [i]
n /= i
if n > 1:
a += [n]
return a
def pollard_rho(n):
# Brent's variant
y, r, q = 0, 1, 1
c, m = 9, 40
g = 1
while g == 1:
x = y
for i in range(r):
y = (y*y + c) % n
k = 0
while k < r and g == 1:
ys = y
for j in range(min(m, r-k)):
y = (y*y + c) % n
q = q*abs(x-y) % n
g = gcd(q, n)
k += m
r *= 2
if g == n:
ys = (ys*ys + c) % n
g = gcd(n, abs(x-ys))
while g == 1:
ys = (ys*ys + c) % n
g = gcd(n, abs(x-ys))
return g
def ec_add((x1, z1), (x2, z2), (x0, z0), n):
t1, t2 = (x1-z1)*(x2+z2), (x1+z1)*(x2-z2)
x, z = t1+t2, t1-t2
return (z0*x*x % n, x0*z*z % n)
def ec_double((x, z), (a, b), n):
t1 = x+z; t1 *= t1
t2 = x-z; t2 *= t2
t3 = t1 - t2
t4 = 4*b*t2
return (t1*t4 % n, t3*(t4 + a*t3) % n)
def ec_multiply(k, p, C, n):
# Montgomery ladder algorithm
p0 = p
q, p = p, ec_double(p, C, n)
b = k >> 1
while b > (b & -b):
b ^= b & -b
while b:
if k&b:
q, p = ec_add(p, q, p0, n), ec_double(p, C, n)
else:
q, p = ec_double(q, C, n), ec_add(p, q, p0, n),
b >>= 1
return q
def lenstra_ecf(n, m = 5):
# Montgomery curves w/ Suyama parameterization.
# Based on pseudocode found in:
# "Implementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware"
# Gaj, Kris et. al
# http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
# Phase 2 is not implemented.
B1, B2 = 8, 13
for i in range(m):
pg = primes()
p = pg.next()
k = 1
while p < B1:
k *= p**int(math.log(B1, p))
p = pg.next()
for s in range(B1, B2):
u, v = s*s-5, 4*s
x = u*u*u
z = v*v*v
t = pow(v-u, 3, n)
P = (x, z)
C = (t*(3*u+v) % n, 4*x*v % n)
Q = ec_multiply(k, P, C, n)
g = gcd(Q[1], n)
if 1 < g < n: return g
B1, B2 = B2, B1 + B2
if __name__ == "__main__":
import argparse
import time
parser = argparse.ArgumentParser(description='Uses a various methods to factor a composite number')
parser.add_argument('composite', metavar='number_to_factor', type=long, help='the composite number to factor')
args = parser.parse_args()
time1 = time.time()
print factor(args.composite)
print 'time elapsed: %.3f seconds'%(time.time()-time1)
```
---
**Sample I/O:**
```
$ pypy mpqs.py --verbose 523022617466601111760007224100074291200000001
smoothness bound: 14998
sieve size: 74990
log threshold: 18.7325510316
skipping primes less than: 37
sieving for smooths...
230 polynomials sieved (34495400 values)
found 849 smooths (242 from partials) in 0.786 seconds
solving for non-trivial congruencies...
factors found:
37280713718589679646221 x 14029308060317546154181
time elapsed: 1.011 seconds
```
Note: not using the `--verbose` option will give slightly better timings:
```
$ pypy mpqs.py 523022617466601111760007224100074291200000001
37280713718589679646221
time elapsed: 0.902 seconds
```
---
### Basic Concepts
In general, a quadratic sieve is based on the following observation: any odd composite \$n\$ may be represented as:
\$n=(x+d)(x-d)=x^2-d^2\Rightarrow d^2=x^2-n\$
This is not very difficult to confirm. Since \$n\$ is odd, the distance between any two cofactors of \$n\$ must be even \$2d\$, where \$x\$ is the mid point between them. Moreover, the same relation holds for any multiple of \$n\$
\$abn=(ax+ad)(bx-bd)=abx^2-abd^2\Rightarrow abd^2=abx^2-abn\$
Note that if any such \$x\$ and \$d\$ can be found, it will immediately result in a (not necessarily prime) factor of \$n\$, since \$x+d\$ and \$x-d\$ both divide \$n\$ by definition. This relation can be further weakened - at the consequence of allowing potential trivial congruencies - to the following form:
\$d^2\equiv x^2\mod n\$
So in general, if we can find two perfect squares which are equivalent mod \$n\$, then it's fairly likely that we can directly produce a factor of \$n\$ a la \$\gcd(x±d,n)\$. Seems pretty simple, right?
Except it's not. If we intended to conduct an exhaustive search over all possible \$x\$, we would need to search the entire range from \$\sqrt{n}\$ to \$\sqrt{2n}\$, which is marginally smaller than full trial division, but also requires an expensive `is_square` operation each iteration to confirm the value of \$d\$. Unless it is known beforehand that \$n\$ has factors very near \$\sqrt{n}\$, trial division is likely to be faster.
Perhaps we can weaken this relation even more. Suppose we chose an \$x\$, such that for
\$y\equiv x^2\mod n\$
a full prime factorization of \$y\$ is readily known. If we had enough such relations, we should be able to *construct* an adequate \$d\$, if we choose a number of \$y\$ such that their product is a perfect square; that is, all prime factors are used an even number of times. In fact, if we have more such \$y\$ than the total number of unique prime factors they contain, a solution is guaranteed to exist; It becomes a system of linear equations. The question now becomes, how do we chose such \$x\$? That's where sieving comes into play.
### The Sieve
Consider the polynomial:
\$y(x)=x^2-n\$
Then for any prime \$p\$ and integer \$k\$, the following is true:
\$y(x+kp)=(x+kp)^2-n\\y(x+kp)=x^2+2xkp+(kp)^2-n\\y(x+kp)=y(x)+2xkp+(kp)^2\equiv y(x)\mod p\$
This means that after solving for the roots of the polynomial mod \$p\$ - that is, you've found an \$x\$ such that \$y(x)\equiv 0\mod p\$, ergo \$y\$ is divisible by \$p\$ - then you have found an infinite number of such \$x\$. In this way, you can sieve over a range of \$x\$, identifying small prime factors of \$y\$, hopefully finding some for which all prime factors are small. Such numbers known as \$k-smooth\$, where \$k\$ is the largest prime factor used.
There's a few problems with this approach, though. Not all values of \$x\$ are adequate, in fact, there's only very few of them, centered around \$\sqrt{n}\$. Smaller values will become largely negative (due to the \$-n\$ term), and larger values will become too large, such that it is unlikely that their prime factorization consists only of small primes. There will be a number of such \$x\$, but unless the composite you're factoring is very small, it's highly unlikely that you'll find enough smooths to result in a factorization. And so, for larger \$n\$, it becomes necessary to sieve over *multiple* polynomials of a given form.
### Multiple Polynomials
So we need more polynomials to sieve? How about this:
\$y(x)=(Ax+B)^2-n\$
That'll work. Note that \$A\$ and \$B\$ could literally be any integer value, and the math still holds. All we need to do is choose a few random values, solve for the root of the polynomial, and sieve the values close to zero. At this point we could just call it good enough: if you throw enough stones in random directions, you're bound to break a window sooner or later.
Except, there's a problem with that too. If the slope of the polynomial is large at the x-intercept, there'll only be a few suitable values to sieve per polynomial. It'll work, but you'll end up sieving a whole lot of polynomials before you get what you need. Can we do better?
We can do better. An observation, as a result of [Montgomery](http://en.wikipedia.org/wiki/Peter_Montgomery_(mathematician)) is as follows: if \$A\$ and \$B\$ are chosen such that there exists some \$C\$ satisfying
\$B^2-n=AC\$
then the entire polynomial can be rewritten as
\$y(x)=(Ax+B)^2-n=(Ax)^2+2ABx+B^2-n=A(Ax^2+2Bx+C)\$
Furthermore, if \$A\$ is chosen to be a perfect square, the leading \$A\$ term can be neglected while sieving, resulting in much smaller values, and a much flatter curve. For such a solution to exist, \$n\$ must be a [quadratic residue](http://en.wikipedia.org/wiki/Quadratic_residue) mod \$\sqrt{A}\$, which can be known immediately by computing the [Legendre symbol](http://en.wikipedia.org/wiki/Legendre_symbol):
\$(n|\sqrt{A})=1\$. Note that in order to solve for \$B\$, a complete prime factorization of \$\sqrt{A}\$ needs to be known (in order to take the modular square root \$\sqrt{n}\mod\sqrt{A}\$), which is why \$\sqrt{A}\$ is typically chosen to be prime.
It can then be shown that if \$A\approx\frac{\sqrt{2n}}{M}\$, then for all values of \$x\in[-M,M]\$:
\$|y(x)|\le\frac{M\sqrt{2n}}{2}\$
And now, finally, we have all the components necessary to implement our sieve. Or do we?
### Powers of Primes as Factors
Our sieve, as described above, has one major flaw. It can identify which values of \$x\$ will result in a \$y\$ divisible by \$p\$, but it cannot identify whether or not this \$y\$ is divisible by a *power* of \$p\$. In order to determine that, we would need to perform trial division on the value to be sieved, until it is no longer divisible by \$p\$.
>
> **Edit:** This is incorrect. The roots of \$n\$ mod \$p^k\$ can be computed directly from the roots mod \$p\$ through the use of [Hensel Lifting](https://en.wikipedia.org/wiki/Hensel%27s_lemma#Hensel_lifting). This current implementation does precisely this.
>
>
>
We seemed to have reached an impasse: the whole point of the sieve was so that we *didn't* have to do that. Time to check the playbook.
\$\ln(a\cdot b\cdot c\cdot d\cdot\ldots)=\ln(a)+\ln(b)+\ln(c)+\ln(d)+\ln(\ldots)\$
That looks pretty useful. If the sum of the \$\ln\$ of all of the small prime factors of \$y\$ is close to the expected value of \$\ln(y)\$, then it's almost a given that \$y\$ has no other factors. In addition, if we adjust the expected value down a little bit, we can also identify values as smooth which have several powers of primes as factors. In this way, we can use the sieve as a 'pre-screening' process, and only factor those values which are likely to be smooth.
This has a few other advantages as well. Note that small primes contribute very little to the \$\ln\$ sum, but yet they require the most sieve time. Sieving the value 3 requires more time than 11, 13, 17, 19, and 23 *combined*. Instead, we can just skip the first few primes, and adjust the threshold down accordingly, assuming a certain percentage of them would have passed.
Another result, is that a number of values will be allowed to 'slip through', which are mostly smooth, but contain a single large cofactor. We could just discard these values, but suppose we found another mostly smooth value, with exactly the same cofactor. We can then use these two values to construct a usable \$y\$; since their product will contain this large cofactor squared, it no longer needs to be considered.
### Putting it all together
The last thing we need to do is to use these values of \$y\$ construct an adequate \$x\$ and \$d\$. Suppose we only consider the non-square factors of \$y\$, that is, the prime factors of an odd power. Then, each \$y\$ can be expressed in the following manner:
\$y\_0=p\_0^0\cdot p\_1^1\cdot p\_2^1\cdots p\_n^0\\y\_1=p\_0^1\cdot p\_1^0\cdot p\_2^1\cdots p\_n^1\\y\_2=p\_0^0\cdot p\_1^0\cdot p\_2^0\cdots p\_n^1\\y\_3=p\_0^1\cdot p\_1^1\cdot p\_2^0\cdots p\_n^0\\\vdots\$
which can be expressed in the matrix form:
\$M=\begin{bmatrix}0&1&1&\cdots&0\\1&0&1&\cdots&1\\0&0&0&\cdots&1\\1&1&0&\cdots&0\\\vdots\end{bmatrix}\$
The problem then becomes to find a vector \$v\$ such that \$vM=\vec{0}\mod 2\$, where \$\vec{0}\$ is the null vector. That is, to solve for the left null space of \$M\$. This can be done in a number of ways, the simplest of which is to perform Gaussian Elimination on \$M^T\$, replacing the row addition operation with a row `xor`. This will result in a number of null space basis vectors, any combination of which will produce a valid solution.
The construction of \$x\$ is fairly straight-forward. It is simply the product of \$Ax+B\$ for each of the \$y\$ used. The construction of \$d\$ is slightly more complicated. If we were to take the product of all \$y\$, we will end up with a value with 10s of thousands, if not 100s of thousands of digits, for which we need to find the square root. This calcuation is impractically expensive. Instead, we can keep track of the even powers of primes during the sieving process, and then use `and` and `xor` operations on the vectors of non-square factors to reconstruct the square root.
~~I seem to have reached the 30000 character limit. Ahh well, I suppose that's good enough.~~ Saved a bunch of bytes by switching to \$MathJax\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 0.34 sec
```
FactorInteger
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y0xuSS/yDOvJDU9teh/QFFmXolCdHq0sYWitmGsgr6@Y1Jxfk5pSWpIZm5mXnrs//8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
Well, your 38!+1 broke my php script, not sure why. In fact, any semi-prime over 16 digits long breaks my script.
However, using 8980935344490257 ( 86028157 \* 104395301 ) my script managed a time of **25.963 seconds** on my home computer (2.61GHz AMD Phenom 9950). A lot faster than my work computer which was nearly 31 seconds @ 2.93GHz Core 2 Duo.
**php - 757 chars** incl. new lines
```
<?php
function getTime() {
$t = explode( ' ', microtime() );
$t = $t[1] + $t[0];
return $t;
}
function isDecimal($val){ return is_numeric($val) && floor($val) != $val;}
$start = getTime();
$semi_prime = 8980935344490257;
$slice = round(strlen($semi_prime)/2);
$max = (pow(10, ($slice))-1);
$i = 3;
echo "\nFactoring the semi-prime:\n$semi_prime\n\n";
while ($i < $max) {
$sec_factor = ($semi_prime/$i);
if (isDecimal($sec_factor) != 1) {
$mod_f = bcmod($i, 1);
$mod_s = bcmod($sec_factor, 1);
if ($mod_f == 0 && $mod_s == 0) {
echo "First factor = $i\n";
echo "Second factor = $sec_factor\n";
$end=getTime();
$xtime=round($end-$start,4).' seconds';
echo "\n$xtime\n";
exit();
}
}
$i += 2;
}
?>
```
I'd be interested to see this same algorithm in c or some other compiled language.
[Answer]
# Pari/GP, 0.21s
```
factor(input())
```
Pari/GP seems to be slightly more performant in this task than Mathmatica.
[Try it online!](https://tio.run/##JccxCoAwDEDR3ZOkg5DEmuLgYUqh0qWGUifx7NHiWz5fYyvzoZbB7bflmPrZoFS9Ojhnz6St1A55zMoLMgsFLyJInyCIGJg9jXreiPFH9gI "Pari/GP – Try It Online")
] |
[Question]
[
Consider a regular grid, where each cell has integer coordinates. We can group the cells into (square-shaped) "rings" where the cells in each ring have the same [Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance) (or chessboard distance) from the origin. Your task is to take such a cell coordinate and rotate that cell by one position counter-clockwise within its ring. This implements the following mapping:
[![enter image description here](https://i.stack.imgur.com/skFsp.png)](https://i.stack.imgur.com/skFsp.png)
So for example if the input is `(3, -2)` you should output `(3, -1)`. Note that `(0, 0)` is the only input that should map to itself.
## Rules
The I/O format is fairly flexible. You can use two individual numbers, a pair/list/array/tuple of numbers, a single complex number, a string containing two numbers, etc.
You may assume that `-128 < x,y < 128`.
You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the our [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output.
You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins.
## Test Cases
```
(0, 0) => (0, 0)
(1, 0) => (1, 1)
(1, 1) => (0, 1)
(0, 1) => (-1, 1)
(-1, 1) => (-1, 0)
(-1, 0) => (-1, -1)
(-1, -1) => (0, -1)
(0, -1) => (1, -1)
(1, -1) => (1, 0)
(95, -12) => (95, -11)
(127, 127) => (126, 127)
(-2, 101) => (-3, 101)
(-65, 65) => (-65, 64)
(-127, 42) => (-127, 41)
(-9, -9) => (-8, -9)
(126, -127) => (127, -127)
(105, -105) => (105, -104)
```
[Answer]
## JavaScript (ES6), ~~60~~ 59 bytes
Takes input with currying syntax `(x)(y)` and returns an array `[new_x, new_y]`.
```
x=>y=>(x|y&&((z=x+(y<0))>-y?z>y?y++:x--:z>y?x++:y--),[x,y])
```
### How it works
Our main task is to determine in which quadrant we are, so that we know in which direction to move.
We can use this formula as a first approximation:
```
x > -y ? (x > y ? 0 : 1) : (x > y ? 2 : 3)
```
Here is what we get:
```
3 1 1 1 1 1 1 1 1
3 3 1 1 1 1 1 1 0
3 3 3 1 1 1 1 0 0
3 3 3 3 1 1 0 0 0
3 3 3 3 3 0 0 0 0
3 3 3 3 2 2 0 0 0
3 3 3 2 2 2 2 0 0
3 3 2 2 2 2 2 2 0
3 2 2 2 2 2 2 2 2
```
Almost there. But the bottom left and bottom right corners of the rings are invalid. We need to shift the lower half of the matrix by one position to the left, so we define `z` as:
```
z = y < 0 ? x + 1 : x
```
And we replace `x` with `z` in our formula:
```
z > -y ? (z > y ? 0 : 1) : (z > y ? 2 : 3)
```
Which leads to:
```
3 1 1 1 1 1 1 1 1
3 3 1 1 1 1 1 1 0
3 3 3 1 1 1 1 0 0
3 3 3 3 1 1 0 0 0
3 3 3 3 3 0 0 0 0
3 3 3 2 2 0 0 0 0
3 3 2 2 2 2 0 0 0
3 2 2 2 2 2 2 0 0
2 2 2 2 2 2 2 2 0
```
The whole matrix is now correct, except for the special case `[0, 0]` (no move at all) which must be addressed separately.
### Test cases
```
let f =
x=>y=>(x|y&&((z=x+(y<0))>-y?z>y?y++:x--:z>y?x++:y--),[x,y])
console.log(f(0)(0)); // => (0, 0)
console.log(f(1)(0)); // => (1, 1)
console.log(f(1)(1)); // => (0, 1)
console.log(f(0)(1)); // => (-1, 1)
console.log(f(-1)(1)); // => (-1, 0)
console.log(f(-1)(0)); // => (-1, -1)
console.log(f(-1)(-1)); // => (0, -1)
console.log(f(0)(-1)); // => (1, -1)
console.log(f(1)(-1)); // => (1, 0)
console.log(f(95)(-12)); // => (95, -11)
console.log(f(127)(127)); // => (126, 127)
console.log(f(-2)(101)); // => (-3, 101)
console.log(f(-65)(65)); // => (-65, 64)
console.log(f(-127)(42)); // => (-127, 41)
console.log(f(-9)(-9)); // => (-8, -9)
console.log(f(126)(-127)); // => (127, -127)
console.log(f(105)(-105)); // => (105, -104)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~14~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
S;IṠN0n/¦Ạ¡+
```
Input and output are in form of arrays. [Try it online!](http://jelly.tryitonline.net/#code=UztJ4bmgTjBuL8Km4bqgwqEr&input=&args=Wzk1LCAtMTJd) or [verify all test cases](http://jelly.tryitonline.net/#code=UztJ4bmgTjBuL8Km4bqgwqErCsOH4oKsRw&input=&args=WzAsIDBdLCBbMSwgMF0sIFsxLCAxXSwgWzAsIDFdLCBbLTEsIDFdLCBbLTEsIDBdLCBbLTEsIC0xXSwgWzAsIC0xXSwgWzEsIC0xXSwgWzk1LCAtMTJdLCBbMTI3LCAxMjddLCBbLTIsIDEwMV0sIFstNjUsIDY1XSwgWy0xMjcsIDQyXSwgWy05LCAtOV0sIFsxMjYsIC0xMjddLCBbMTA1LCAtMTA1XQ).
### Background
To figure out in which direction we have to move, we can observe the relative position of the start point to the quadrant bisectors **x + y = 0** (blue) and **x - y = 0** (red).
![diagram](https://i.stack.imgur.com/n9THn.png)
* The origin is fixed. We advance by adding **[0, 0]** to the start point.
* Points in the topmost triangle – including the bisector of the first quadrant – have positive sum and non-negative delta (**y - x**). We advance by adding **[-1, 0]** to the start point.
* Points in the leftmost triangle – including the bisector of the second quadrant – have non-positive sum and positive delta. We advance by adding **[0, -1]** to the start point.
* Points in the bottommost triangle – including the bisector of the third quadrant – have negative sum and non-positive delta. We advance by adding **[1, 0]** to the start point.
* Points in the rightmost triangle – including the bisector of the fourth quadrant – have non-negative sum and negative delta. We advance by adding **[0, 1]** to the start point.
To figure out the correct direction, we compute **[-sign(x + y), -sign(y - x)]**, which has only nine possible outcomes.
The following table illustrates which outcomes have to get mapped to which directions.
```
sign(x+y) | sign(y-x) | -sign(x+y) | -sign(y-x) | Δx | Δy
------------+------------+------------+------------+------------+------------
0 | 0 | 0 | 0 | 0 | 0
1 | 0 | -1 | 0 | -1 | 0
1 | 1 | -1 | -1 | -1 | 0
0 | 1 | 0 | -1 | 0 | -1
-1 | 1 | 1 | -1 | 0 | -1
-1 | 0 | 1 | 0 | 1 | 0
-1 | -1 | 1 | 1 | 1 | 0
0 | -1 | 0 | 1 | 0 | 1
1 | -1 | -1 | 1 | 0 | 1
```
This leaves three cases.
* If at least one of the signs is **0**, **[Δx, Δy] = [-sign(x+y), -sign(y-x)]**.
* If the signs are equal and non-zero, **[Δx, Δy] = [-sign(x+y), 0]**.
* If the signs are different and non-zero, **[Δx, Δy] = [0, -sign(y-x)]**.
### How it works
```
S;IṠN0n/¦Ạ¡+ Main link. Argument: [x, y] (pair of integers)
S Sum; compute x + y.
I Increments; compute [y - x].
; Concatenate; yield [x + y, y - x].
Ṡ Sign; compute [sign(x + y), sign(y - x)].
N Negate; yield [-sign(x + y), -sign(y - x)].
¡ Do n times:
Ạ Set n to all([-sign(x + y), -sign(y - x)]), i.e., 1 if the signs
are both non-zero and 0 otherwise.
¦ Conditional application:
n/ Yield 1 if the signs are not equal, 0 if they are.
0 Replace the coordinate at 1 or 0 with a 0.
This returns [Δx, Δy].
+ Add; yield [Δx + x, Δy + y].
```
[Answer]
# [Pyth](http://github.com/isaacg1/pyth), 19 bytes
```
&Q+^.jZ1.RhycPQ.n0Z
```
[Try it online!](http://pyth.tryitonline.net/#code=JlErXi5qWjEuUmh5Y1BRLm4wWg&input=LTktOWo)
Translation of my [Julia answer](https://codegolf.stackexchange.com/a/96436/3852):
```
&Q If input is 0, then 0, else:
PQ Get phase of input
c .n0 Divide by π
y Double
h Add one
.R Z Round to integer
^.jZ1 Raise i to this power
+ Add to input
```
[Answer]
## Python, 55 bytes
```
lambda x,y:(x-(-y<x<=y)+(y<=x<-y),y+(~x<y<x)-(x<y<=-x))
```
Detects the four diagonal quadrants, and shifts the appropriate coordinate.
[Answer]
# Haskell, ~~77~~ ~~71~~ 69 bytes
```
x#y|y>=x,-x<y=(x-1,y)|y>x=(x,y-1)|y< -x=(x+1,y)|y<x=(x,y+1)|1>0=(0,0)
```
This is just checking each of those tilted quadrants, and modifying the input accordingly. Note that the spaces are necessary, otherwise e.g. `>-` would be understood as an operator (which is not defined).
Thank you @nimi for removing a few more bytes!
[Answer]
# Ruby, 68
Lambda function takes complex number as argument, returns complex number.
```
->z{k=1
4.times{z*=?i.to_c
x,y=z.rect
y*y>=x*x&&y<-x&&(z+=k;k=0)}
z}
```
We rotate the point through 90 degrees 4 times by multiplying by `i`. It therefore passes through all 4 quadrants, and would be returned unchanged - except for the fact we modify it when it is in a specific one of them. The fact it is always modified in the same quadrant simplifies the modification.
It is easiest to follow if we alter it `z` when it is in the righthand quadrant. in this case we need to increase the y coordinate by 1 (i.e add `i` to `z`.)
We check `x.abs>=y.abs` by comparing the squares of `x` and `y`. This tells us the point is in the righthand or lefthand quadrant, not top or bottom. To check it is in fact in the righthand quadrant we further check that `x>y` (strictly greater because we want to exclude the case `x=y` which belongs to the "top" quadrant.) Where this is true we add `i` to `z`.
For golfing reasons, adding `i` is not desirable. Instead we modifiy the number when it is in the bottom quadrant, in which case we have to add 1 to the `x` coordinate (add 1 to `z`.) In this case we test that `y*y>=x*x` to check it is in the top or bottom quadrant. To further ensure it is in the bottom quadrant we need to check `y<-x` (strictly excluding the case of the bottom right corner where `y=-x`.)
An advantage of this check is there is no special case for the coordinate 0,0. Unfortunately it was found that moving the point can shift it to a different quadrant and this means that a second movement must be suppressed should that quadrant be checked again, which probably negates the advantage.
**Example 1**
```
Input 95,-12
Rotate 90deg 12,95
Rotate 90deg -95,12
Rotate 90deg -12,-95
Rotate 90deg 95,-12
y.abs>=x.abs=TRUE, y<-x=TRUE, increase x 95,-11
The check and alteration of the coordinate is done AFTER the rotation.
Thus in this case it gets done in the 4th iteration of the loop, not the 1st.
If the code were rewritten to do the check and alteration BEFORE the rotation,
it would be done in the 1st iteration instead of the 4th.
```
**Example 2**
```
Input -1,0
Rotate 90deg 0,-1
y.abs>=x.abs=TRUE, y<-x=TRUE, increase x 1,-1
Rotate 90deg 1,1
Rotate 90deg 1,-1
Rotate 90deg -1,-1
y.abs>=x.abs?=TRUE, y<-x=TRUE but DO NOT CHANGE x!
This is an unusual situation due to the fact that the first move caused the
point to advance by one quadrant. We do NOT want to move it again, for this
reason we need to set k to 0 the first time it is moved.
```
**In test program**
```
f=->z{k=1 #amount to be added to coordinate
4.times{z*=?i.to_c #iterate 4 times, rotating point by 90deg till it reaches the original orientation
x,y=z.rect #separate out x and y for testing
y*y>=x*x&&y<-x&&(z+=k;k=0)} #if y.abs>=x.abs and y negative and not equal -x, move the point and zero k.
z} #return z
puts f[Complex(0, 0)] # (0, 0)
puts f[Complex(1, 0)] # (1, 1)
puts f[Complex(1, 1)] # (0, 1)
puts f[Complex(0, 1)] # (-1, 1)
puts f[Complex(-1, 1)] # (-1, 0)
puts
puts f[Complex(-1, 0)] # (-1, -1)
puts f[Complex(-1, -1)] # (0, -1)
puts f[Complex(0, -1)] # (1, -1)
puts f[Complex(1, -1)] # (1, 0)
puts f[Complex(95, -12)] # (95, -11)
puts f[Complex(127, 127)] # (126, 127)
puts
puts f[Complex(-2, 101)] # (-3, 101)
puts f[Complex(-65, 65)] # (-65, 64)
puts f[Complex(-127, 42)] # (-127, 41)
puts f[Complex(-9, -9)] # (-8, -9)
puts f[Complex(126, -127)] # (127, -127)
puts f[Complex(105, -105)] # (105, -104)
```
**Diagram**
The following image shows (blue) the area where `x*x>=y*y`, (yellow) the area where `y<-x` and (green) the intersection of these, which is the region where the correct transformation is the addition of 1 to `z`.
[![enter image description here](https://i.stack.imgur.com/ypl8b.png)](https://i.stack.imgur.com/ypl8b.png)
[Answer]
## Python, 52 bytes
```
h=lambda z:z and 1j*h(z/1j)if'-'in`z*1j-z-1`else z+1
```
Complex input and output. To test the point for being in the lower diagonal quadrant, first rotate it 135 counterclockwise to move that quadrant to the (x>0, y>0) standard quadrant, and test if the result has no minus symbol in the string representation. Subtracting 1 first takes care of the boundary condition.
If it's not in that quadrant, rotate the whole problem 90 degrees. The input is zero is specially handled to output itself.
Other attempts with complex numbers:
```
## 56 bytes
## Coordinate input, complex output
q=lambda x,y:(y<=x<-y)*(1j*y-~x)or x+1j*y and 1j*q(y,-x)
## 60 bytes
h=lambda z:(z+1)*(z.imag<=z.real<-z.imag)or z and 1j*h(z/1j)
## 63 bytes
from cmath import*
h=lambda z:z and 1j**(phase(z*1j-z)*2//pi)+z
```
[Answer]
## Mathematica, 34 bytes
```
±0=0
±z_:=z+I^Floor[2Arg@z/Pi+3/2]
```
This defines a unary operator `±` which takes and returns a complex number whose components represent `x` and `y`.
Now that Lynn has revealed the complex number solution and Dennis has beaten my score, I don't feel so bad for posting my golfed referenced implementation. :) (It turns out to be virtually identical to Lynn's answer.)
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~19~~ 17 bytes
```
t|?JGJq*X/EYP/k^+
```
This uses complex numbers as input and output.
[Try it online!](http://matl.tryitonline.net/#code=dHw_SkdKcSpYL0VZUC9rXis&input=LTEyNys0Mmo) Or [verify all test cases](http://matl.tryitonline.net/#code=IkAKdHw_SkBKcSpYL0VZUC9rXisKXVZAVicgLT4gJ2JoaEQ&input=WzArMGogMSswaiAxKzFqIDArMWogLTErMWogLTErMGogLTEtMWogMS0xaiA5NS0xMmogMTI3KzEyN2ogLTIrMTAxaiAtNjUrNjVqIC0xMjcrNDJqIC05LTlqIDEyNi0xMjdqIDEwNS0xMDVqXQ).
### Explanation
Let's take input `-127+42j` as an example.
```
t| % Implicit input. Duplicate and take absolute value
% STACK: -127+42j, 133.764718816286
? % If nonzero
% STACK: -127+42j
J % Push j (imaginary unit)
% STACK: -127+42j, j
GJq* % Push input multiplied by -1+j. This adds 3*pi/4 to the phase of the input
% STACK: -127+42j, j, 85-169i
X/ % Phase of complex number
% STACK: -127+42j, j, -1.10478465600433
EYP/ % Divide by pi/2
% STACK: -127+42j, j, -0.703327756220671
k % Round towards minus infinity
% STACK: -127+42j, j, -1
^ % Power
% STACK: -127+42j, -j
+ % Add
% STACK: -127+41j
% Implicit end
% Implicit display
```
[Answer]
# Ruby, 51 bytes
**Original form**
```
->x,y{d=x*x-y*y
[x+(d>0?0:-y<=>x),y+(d<0?0:x<=>y)]}
```
**Alternate form per Xnor's comment**
```
->x,y{[x+(x*x>y*y ?0:-y<=>x),y+(x*x<y*y ?0:x<=>y)]}
```
Uses the same type of inequalities as my other answer, but in a different way.
**In test program**
```
f=->x,y{d=x*x-y*y
[x+(d>0?0:-y<=>x), #if y.abs>=x.abs: x+=1 if -y>x, x-=1 if -y<x
y+(d<0?0:x<=>y)]} #if x.abs>=y.abs: y+=1 if x>y, y-=1 if x<y
p f[0, 0] # (0, 0)
p f[1, 0] # (1, 1)
p f[1, 1] # (0, 1)
p f[0, 1] # (-1, 1)
p f[-1, 1] # (-1, 0)
puts
p f[-1, 0] # (-1, -1)
p f[-1, -1] # (0, -1)
p f[0, -1] # (1, -1)
p f[1, -1] # (1, 0)
p f[95, -12] # (95, -11)
p f[127, 127] # (126, 127)
puts
p f[-2, 101] # (-3, 101)
p f[-65, 65] # (-65, 64)
p f[-127, 42] # (-127, 41)
p f[-9, -9] # (-8, -9)
p f[126, -12] # (127, -127)
p f[105, -105] # (105, -104)
```
[Answer]
# Julia, ~~38~~ 34 bytes
```
!z=z==0?0:z+im^int(2angle(z)/pi+1)
```
Dennis saved four bytes. Thanks!
[Try it online!](http://julia.tryitonline.net/#code=IXo9ej09MD8wOnoraW1eaW50KDJhbmdsZSh6KS9waSsxKQoKcHJpbnRsbighKDAraW0qIDApICAgICApCnByaW50bG4oISgxK2ltKiAwKSAgICAgKQpwcmludGxuKCEoMStpbSogMSkgICAgICkKcHJpbnRsbighKDAraW0qIDEpICAgICApCnByaW50bG4oISgtMStpbSogMSkgICAgKQpwcmludGxuKCEoLTEraW0qIDApICAgICkKcHJpbnRsbighKC0xK2ltKiAtMSkgICApCnByaW50bG4oISgwK2ltKiAtMSkgICAgKQpwcmludGxuKCEoMStpbSogLTEpICAgICkKcHJpbnRsbighKDk1K2ltKiAtMTIpICApCnByaW50bG4oISgxMjcraW0qIDEyNykgKQpwcmludGxuKCEoLTIraW0qIDEwMSkgICkKcHJpbnRsbighKC02NStpbSogNjUpICApCnByaW50bG4oISgtMTI3K2ltKiA0MikgKQpwcmludGxuKCEoLTkraW0qIC05KSAgICkKcHJpbnRsbighKDEyNitpbSogLTEyNykpCnByaW50bG4oISgxMDUraW0qIC0xMDUpKQo&input=)
[Answer]
# C++, 94 bytes
```
#define a(x) (x>0?x:-(x))
#define f(x,y) y>a(x-.5)?x--:-y>a(x+.5)?x++:x>a(y+.5)?y++:x|y?y--:x;
```
Ungolfed:
```
#define a(x) (x>0?x:-(x)) //shorter than std::abs from <cmath>
#define f(x,y)
y>a(x-.5)? // shift absolute value function by 0.5 to the right to get upper fourth
x--:
-y>a(x+.5)? //same for lower fourth
x++:
x>a(y+.5)? //same for right fourth
y++:
x|y? //only left fourth and 0 are left
y--:
x; //can't be empty, just does nothing
```
Usage:
```
#include <iostream>
void test(int x, int y, int rx, int ry){
std::cout << "(" << x << ", " << y << ")=>";
f(x,y);
std::cout << "(" << x << ", " << y << ") - " << ((x==rx&&y==ry)?"OK":"FAILURE") << std::endl;
}
//Using the test cases from the question
int main() {
test(0, 0, 0, 0);
test(1, 0, 1, 1);
test(1, 1, 0, 1);
test(0, 1, -1, 1);
test(-1, 1, -1, 0);
test(-1, 0, -1, -1);
test(-1, -1, 0, -1);
test(0, -1, 1, -1);
test(1, -1, 1, 0);
test(95, -12, 95, -11);
test(127, 127, 126, 127);
test(-2, 101, -3, 101);
test(-65, 65, -65, 64);
test(-127, 42, -127, 41);
test(-9, -9, -8, -9);
test(126, -127, 127, -127);
test(105, -105, 105, -104);
return 0;
}
```
[Try it online](http://ideone.com/XV93r8)
[Answer]
## R, 131 110 bytes
A function that takes the two integers, `x,y` as inputs and writes the output to stdout. The solution follows @Dennis' control flow scheme but could probably be golfed.
EDIT: Updated code based on @JDL's suggestions and saved a bunch of bytes.
```
function(x,y){X=sign(x+y);Y=sign(y-x);if(!X|!Y){x=x-X;y=y-Y}else if(X==Y&X&Y)x=x-X else if(X-Y&X)y=y-Y;c(x,y)}
```
**Ungolfed**
```
f=function(x,y){
X=sign(x+y) # calculate sign
Y=sign(y-x) # =||=
if(!X|!Y){x=x-X;y=y-Y} # if at least one is 0: subtract sign
else if(X==Y&X&Y)x=x-X # if signs are equal and non-zero: add sign to x
else if(X-Y&X)y=y-Y # if signs are not equal and non-zero: add sign to y
c(x,y) # print to stdout
}
```
[Answer]
# JavaScript (ES6), 57 bytes (55–63†)
Accepts an [x, y] array, modifies it in-place, and returns it.
```
c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y),c)
```
## How it works
```
c=>(
```
This is a single-parameter arrow function with a `return`-free concise body.
```
[x,y]=c
```
The parameter is immediately destructured into `x` and `y` variables.
```
,
```
The comma operator combines multiple expressions into one, using the result of the last.
```
i=x>y|x==y&x<0
```
`i` is used for differentiating increment and decrement cases. When `x` is greater than `y`, we are in either the bottom or right quadrant, and need to advance in one dimension (`i=1` by boolean-to-number coercion). Likewise when we are on the negative portion of the dividing **x = y** diagonal. In all other cases—including the origin—no increment is required (`i=0`).
```
c[i^x<-y|x==-y]
```
We use a somewhat similar expression for controlling which array index to adjust. When we are incrementing and not in the left or bottom quadrants (or when we are *not* incrementing and *in* the left or bottom), then the bitwise XOR will produce `1` and we will adjust the **y** value. Likewise for when we are on the dividing **x = -y** diagonal (including the origin). In all other cases, the index will be `0` (**x**).
```
-=-i|!!(x|y)
```
When `i` is `1`, we will add it to the specified value. When `i` is `0`, we will subtract 1 from the value *if and only if* we are not at the origin. The latter is detected by `x|y` yielding nonzero, clipped to {0, 1} by boolean coercion, and the negation of `i` allows us to use bitwise OR instead of logical (since `-1` has no zero bits, it is safe from modification).
```
c
```
The array is last, so it will be returned.
## Testing
```
let f =
c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y),c)
let cases = `
(0, 0) => (0, 0)
(1, 0) => (1, 1)
(1, 1) => (0, 1)
(0, 1) => (-1, 1)
(-1, 1) => (-1, 0)
(-1, 0) => (-1, -1)
(-1, -1) => (0, -1)
(0, -1) => (1, -1)
(1, -1) => (1, 0)
(95, -12) => (95, -11)
(127, 127) => (126, 127)
(-2, 101) => (-3, 101)
(-65, 65) => (-65, 64)
(-127, 42) => (-127, 41)
(-9, -9) => (-8, -9)
(126, -127) => (127, -127)
(105, -105) => (105, -104)
`;
let failures = cases.trim().split("\n").filter(l => {
const FAIL = true;
let m = /.*?(-?\d+).*?(-?\d+).*?(-?\d+).*?(-?\d+)/.exec(l);
if (!m) return FAIL;
let [_, x, y, X, Y] = m;
let [x2, y2] = f([+x, +y]);
if (x2==X && y2==Y) return !FAIL;
console.log("(%s) yielded (%s); expected (%s)", [x, y], [x2, y2], [X, Y]);
return FAIL;
});
console.log("failures: " + failures.length);
// => failures: 0
```
## †Variations
We can save two more bytes by skipping a meaningful return value and using *only* the input mutation:
```
c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y))
```
…or we can skip input mutation and make all variables local for a pure function, at the cost of six bytes:
```
([x,y],i=x>y|x==y&x<0,c=[x,y])=>(c[i^x<-y|x==-y]-=-i|!!(x|y),c)
```
[Answer]
## JavaScript (ES6), ~~80~~ 76 bytes
```
(x,y,s=Math.max(x,y,-x,-y))=>(s?x+s?y-s?x-s?x++:y++:x--:y+s?y--:x++:0,[x,y])
```
[Answer]
## Haskell, 53 bytes
```
0%0=(0,0)
x%y|y>=0-x,y<x=(x,y+1)|(p,q)<-(-y)%x=(q,-p)
```
Takes two numbers, outputs a tuple. If the point is in the east section `-x<=y<x`, increase the second coordinate by 1. Otherwise, cycle the quadrants by rotating the input point 90 degrees, calling the function on it, then rotating back.
[Answer]
## Racket 191 bytes
```
(cond[(= 0 x y)(list x y)][(= x y)(if(> x 0)(list(sub1 x)y)(list(add1 x)y))][(> x y)(if(>= x(abs y))
(list x(add1 y))(list(add1 x)y))][(< x y)(if(> y(abs x))(list(sub1 x)y)(list x(sub1 y)))])
```
Ungolfed (directly translating figure directions to code without using any intermediate formula):
```
(define(f x y)
(cond
[(= 0 x y) (list x y)]
[(= x y)
(if (> x 0)
(list (sub1 x) y) ; left
(list (add1 x) y))] ; right
[(> x y)
(if (>= x (abs y))
(list x (add1 y)) ; up
(list (add1 x) y))] ; right
[(< x y)
(if (> y (abs x))
(list (sub1 x) y) ; left
(list x (sub1 y)))] ; down
))
```
Testing:
```
(f 0 0)
(f 1 0)
(f 1 1)
(f 0 1)
(f -1 1)
(f -1 0)
(f -1 -1)
(f 0 -1)
(f 1 -1)
(f 95 -12)
(f 127 127)
(f -2 101)
(f -65 65)
(f -127 42)
(f -9 -9)
(f 126 -127)
(f 105 -105)
```
Output:
```
'(0 0)
'(1 1)
'(0 1)
'(-1 1)
'(-1 0)
'(-1 -1)
'(0 -1)
'(1 -1)
'(1 0)
'(95 -11)
'(126 127)
'(-3 101)
'(-65 64)
'(-127 41)
'(-8 -9)
'(127 -127)
'(105 -104)
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 16 bytes
This takes a complex number as input and outputs another complex number. Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=O2DigqfilaZAL8-EdUzDr-KBvyswYOKVrFg&input=Myswag)
```
;`₧╦@/τuLïⁿ+0`╬X
```
**Ungolfing**
```
Implicit input z.
; Duplicate z.
`...`╬ If z is non-zero (any a+bi except 0+0j), run the following function.
Stack: z, z
₧ Get phase(z).
╦@/ Divide phase(z) by pi.
τuL Push floor(2*phase(z)/pi + 1).
ïⁿ Push 1j ** floor(2*phase(z)/pi + 1).
+ And add it to z. This is our rotated z.
0 Push 0 to end the function.
X Discard either the duplicate (0+0j) or the 0 from the end of function.
Implicit return.
```
[Answer]
# Scala, 184 bytes
```
val s=math.signum _
(x:Int,y:Int)=>{val m=x.abs max y.abs
if(x.abs==y.abs)if(s(x)==s(y))(x-s(x),y)else(x,y-s(y))else
if(x.abs==m)(x,y+Seq(0,x).indexOf(m))else(x-Seq(0,y).indexOf(m),y)}
```
### Ungolfed:
```
import math._
(x: Int, y: Int) => {
val max = max(x.abs, y.abs)
if (x.abs == y.abs)
if (signum(x) == signum(y))
(x - signum(x), y)
else
(x, y - signum(y))
else
if (x.abs == max)
(x, y + Seq(0, x).indexOf(max))
else
(x - Seq(0, y).indexOf(max), y)
}
```
### Explanation:
```
val s=math.signum _ //define s as an alias to math.signum
(x:Int,y:Int)=>{ //define an anonymous function
val m=x.abs max y.abs //calculate the maximum of the absolute values,
//which is 1 for the innermost circle and so on.
if(x.abs==y.abs) //if we have a cell at a corner of a circle
if(s(x)==s(y)) //if it's at the top-left or bottom-right, we need to
//modify the x value
(x-s(x),y) //if x is positive (bottom-right),
//we need to return (x+1,y),
//(x-1,y) If it's at the top-left.
//This can be simplified to (x-s(x),y)
else //for top-right and bottom-left,
(x,y-s(y)) //modify y in the same way.
else //we don't have a corner piece
if(x.abs==m) //if we're at the left or right edge of the square
(x,y+Seq(0,x).indexOf(m)) //if it's a piece from the right edge, add one
//to y, else subtract 1
else //it's a piece from the top or bottm edge
(x-Seq(0,y).indexOf(m),y) //subtract 1 from x if it's from the top edge,
//else subtract -1
}
```
] |
[Question]
[
# Alternate Title: [Tally Your Prison Sentence on the Wall](https://s3.amazonaws.com/lowres.cartoonstock.com/law-order-jail-jail_cell-prisoner-prison_cell-prison-jcen999_low.jpg)
Given a number `n`, output tallies grouped into the traditional 5-per-group and 50 per row.
---
# Examples
1
```
|
|
|
|
```
4
```
||||
||||
||||
||||
```
5
```
|||/
||/|
|/||
/|||
```
6
```
|||/ |
||/| |
|/|| |
/||| |
```
50
```
|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /|||
```
51
```
|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /|||
|
|
|
|
```
256
```
|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /|||
|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /|||
|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /|||
|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /|||
|||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/ |||/
||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/| ||/|
|/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/|| |/||
/||| /||| /||| /||| /||| /||| /||| /||| /||| /|||
|||/ |
||/| |
|/|| |
/||| |
```
---
# Rules
* 5 tallies per group, 50 total tallies per row.
* The first 4 tallies are vertical, the 5th tally crosses all other tallies.
+ Each of the first four consist of 4 vertical `|` characters.
+ The final 5th tally spans all 4 of the first, with a `/` character, diagonally.
* Each group should be separated by a space, each row a blank newline.
* The constraints on `n` are: `0 <= n <= 1000` (for simplicity).
* Trailing spaces and newlines are fine, preceding are not.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")[ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'"), lowest byte-count wins.
---
Reviewed by ~4 people in the [sandbox](https://codegolf.meta.stackexchange.com/a/14215/59376).
---
P.S. *fun little tid-bit, the average number of tallies per row in prison was 50, hence the alt. title.*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~30~~ 25 bytes
```
FN«J﹪ι⁵⁰×⁵÷ι⁵⁰¿﹪⊕ι⁵↓⁴«←↙⁴
```
[Try it online!](https://tio.run/##TY29CsIwFIXn5Cky3kAEEeNQ1y4RKw59gdreYiA/JU3qIH322ICC63fO@U7/7ELvO5Pz6AMD5aYUb8k@MADn7E3JJdmp9dD4IRkPWjC554K12uIMUjDlYq0XPeA34vxMiR7Zb6BcH9CiiziA3oZys96DdhGq2r@cYEdOCZoZyxdp/IJQXXGMRUP@ioWV8oZXuuZ8kKe8W8wH "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input number
F « Loop over implicit range
ι ι Loop index
⁵⁰ ⁵⁰ Literal 50
﹪ Modulo
÷ Integer divide
⁵ Literal 5
× Multiply
J Jump to column, row
ι Loop index
⊕ Incremented
⁵ Literal 5
﹪ Modulo
¿ If
↓⁴ Print 4 `|`s downwards
« Implicit else
← Move left
↙⁴ Print 4 `/`s down and left
```
[Answer]
# [Funky](https://github.com/TehFlaminTaco/Funky), ~~156~~ ~~132~~ 133 bytes
```
n=>{k=n=>((l="|"::rep)(3-i)+"/"+l(i)+" ")::rep(n)p=print L=f=>fori=0i<4i++p(f())forc=0c<n//50c++{L@k(10);p()}L@k((m=n%50)//5)+l(m%5)}
```
[Try it online!](https://tio.run/##HYxbCoMwEEW3IgFhhqEkfeTHOtIFuIvQgaBOQ7Afxbr2NPbncrgHjrx1@hThojxsE9cFmNl8TdflZ0K4niKSsYZmOKAx@BegmDjlqGszsvAgrxzZxf4WiRIIINYnsAu9WutdINrGxwRnh/cEuB8MC2vrHVaPtb60Hvci4C9Yfg "Funky – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 117 bytes
```
f m|m<1=""|n<-min 50 m=unlines[[last$"| "!!(0^c%5):['/'|r+c%5==4,n-n%5>c]|c<-[1..n]]|r<-[0..3]]++'\n':f(m-50)
(%)=mod
```
[Try it online!](https://tio.run/##Dc1LDoIwEADQvacYGkgh2NpGGxNCvYTLWhOCEImd0fDZ9e6V3du9d7d8hhBSGgEjttoyFqkVOBEYBWg3ChMNi3OhW9acRWBZVqpnX5iqcfzE41zvtvZyJEGFufU@9q1wWkryPs47lZRn7@uaP4g3Y4nCqOpQFpXF7ytht0cWftt6X2fIYQStr@kP "Haskell – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 29 bytes
```
J;øṀṪṙŀ4C10§:oR"|||/"÷5oR'|%5
```
[Try it online!](https://tio.run/##ATMAzP9odXNr//9KO8O44bmA4bmq4bmZxYA0QzEwwqc6b1IifHx8LyLDtzVvUid8JTX///8yNTY "Husk – Try It Online")
I feel like the first `5` is redundant, but removing it gives a type error...
## Explanation
```
J;øṀṪṙŀ4C10§:oR"|||/"÷5oR'|%5 Implicit input, an integer n.
oR'| Repeat the character '|'
%5 n mod 5 times.
oR"|||/" Repeat the string "|||/"
÷5 n/5 times.
§: Tack the '|'-string to the end of that list.
C10 Cut the list of strings into pieces of length 10.
Ṁ For each piece,
Ṫ ŀ4 for each k in [0,1,2,3],
ṙ rotate each string k steps to the left
and collect the results into a list.
Now we have a list of lists of lists of strings.
J;ø Join them with the list [[]].
Implicitly join each list of strings by spaces,
then join the resulting list of strings by newlines,
and print the result.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes
```
:5[“|||/”]ẋ;”|ẋ⁸%5¤¤W¤ṙ€4Ḷ¤s⁵Z€G€j⁾¶¶
```
[Try it online!](https://tio.run/##y0rNyan8/9/KNPpRw5yamhr9Rw1zYx/u6rYG0jVA@lHjDlXTQ0sOLQk/tOThzpmPmtaYPNyx7dCS4keNW6OAPHcgznrUuO/QtkPb/v9HUWFogKHA0gIA "Jelly – Try It Online")
# Explanation
```
:5[“|||/”]ẋ;”|ẋ⁸%5¤¤W¤ṙ€4Ḷ¤s⁵Z€G€j⁾¶¶ Main Link
:5 Floordiv by 5
[“|||/”]ẋ Repeat ["|||/"] by this number
; Append
”|ẋ ¤ "|" repeated by
⁸%5¤ The argument modulo 5
W¤ Then wrapped to prevent weirdness
ṙ€ Rotate each tally segment by
4Ḷ¤ (each) [0, 1, 2, 3]
s⁵ Slice into pieces of length 10 (to get 50 per row)
Z€ Transpose each
G€ Convert each into a grid
j⁾¶¶ Join these grids by a double newline
```
wheee this is too long
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 33 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ā.{┐4∙F5\?X1w⁄3-14╚╬5@}┼FM»\?O¶oā
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/index.html?code=JXUwMTAxLiU3QiV1MjUxMDQldTIyMTlGNSU1QyUzRlgxdyV1MjA0NDMtMTQldTI1NUEldTI1NkM1QCU3RCV1MjUzQ0ZNJUJCJTVDJTNGTyVCNm8ldTAxMDE_,inputs=MjU2)
Golfing on a phone is hard..
Explanation:
```
ā push an empty array
.{ repeat input times
┐4∙ push a 4 tall line
F5\? } if the counter (1-indexed) divides by 5
X pop that vertical line
1w⁄ get the width of the main array
3- subtract 3 from that width - X position
1 push 1 - Y position
4╚ push a 4 long diagonal
╬5 place that in the main array at [width-3; 1]
@ push a space - for the below to add spacing
┼ append horizontally
FM»\? if the counter divides by 50
O output the main array
¶o output a newline
ā push a new array
(note that the outputting here doesn't disable
implicit outputting)
```
[Answer]
# JavaScript (ES6), ~~139~~ 137 bytes
```
n=>eval('s="";for(i=0;i++<=n/50;s+=N)for(j=5;--j;s+=N=`\n`)for(k=0;k<(x=(y=n-i*50)<0?50+y:50);)s+=++k%5?k%5-j|k>5*(x/5|0)?"|":"/":" ";s')
```
Returns a string with one trailing newline when `n` is not a multiple of 50 and one with several trailing newlines when `n` *is* a multiple of 50.
## Ungolfed
```
n=>{
s=""
for(i=0; i++ <= n/50; s+=N)
for(j=5; --j; s+=N=`\n`)
for(k=0; k < (x = (y = n-i*50) < 0 ? 50+y : 50);)
s += ++k%5 ?
k%5-j|k>5*(x/5|0) ?
"|"
: "/"
: " "
return s
}
```
## Test Snippet
```
f=
n=>eval('s="";for(i=0;i++<=n/50;s+=N)for(j=5;--j;s+=N=`\n`)for(k=0;k<(x=(y=n-i*50)<0?50+y:50);)s+=++k%5?k%5-j|k>5*(x/5|0)?"|":"/":" ";s')
;(I.oninput=_=>O.innerText=f(+I.value))(I.value=76)
```
```
<input id=I type=number>
<pre id=O style="border-bottom:1px solid black"></pre>
```
## Non-`eval` solution, 150 bytes
```
n=>(A=(v,m)=>j=>[...Array(v).keys()].map(m).join(j))(n/50+1|0,i=>A(4,j=>A(x=(y=n+~i*50)<0?50+y:50,k=>++k%5?k%5-4+j|k>5*(x/5|0)?"|":"/":" ")``)`
`)`
`
```
Possibly able to golf this one further but the `eval` method has been shorter so far.
[Answer]
# [J](http://jsoftware.com/), ~~50 48 45 35~~ 33 bytes
```
_50|:\'|/ '{~[{.(|.2,=i.4)$~]-5|]
```
[Try it online!](https://tio.run/##y/r/P81WTyHe1KDGKka9Rl9BvbouulpPo0bPSMc2U89EU6UuVte0JvZ/anJGvoONQ5pCZklqbrGCsYKJpYKpgYKRqdl/AA)
```
( =i.4) Identity matrix of size 4.
( 2, ) Prepend a row of 2s.
(|. ) Upside down.
$~ Take __ rows.
]-5|] Input rounded down to a multiple of 5.
[{. Pad with rows of zeroes to [input] rows.
'|/ '{~ Get the characters.
_50|:\ Transpose and fit to width.
```
[Answer]
# C (gcc), 170 bytes
```
char*s="|||/ \0||/| \0|/|| \0/||| \0";h;k;g(x){for(h=0;h<5;h++){for(k=x;k>4;k-=5)printf(s+6*h);for(;k&&h-4;k--)printf("|");putchar(10);}}f(x){for(;x>49;x-=50)g(50);g(x);}
```
[Try it online!](https://tio.run/##NY3BCoMwEETP7VeUHCSrBFMxQtnGL@lFAjESakUtBEy@3SYVL/OWGXZGsV6pfVemm/NFEu99eXvxqD6h9AlREwgatNhTB5v@zNRIjuYp0BTFYVjp0LY1WiYFTPMwrpouRZMbwBSjzTLDUszOlHgCOH3XtE7vHDAEfdaja@sHutjFoadR/ssY9vh5e3fDSGG7XjStABPEgUo08Qj7Dw "C (gcc) – Try It Online")
`f` is a function taking a nonnegative integer (`x`) and printing that many tallies, grouped as specified, to stdout
`g` is a helper function that prints `x` tallies, grouped by 5, without splitting lines.
`f` calls `g(50)` and decrements `x` by 50 until it is less than 50, then calls `g(x)` to print the remaining tallies on one line.
`s` is a `char*` such that, as strings, `s` is the first row of a bundle, `s+6` is the second, `s+12` is the third, and `s+18` is the fourth, and `s+24` is an empty string.
`g(x)` prints bundles and decrements x by 5 until x is less than 5, then prints `x` single tallies.
[Answer]
# Python, ~~129~~ ~~113~~ 112 bytes
```
f=lambda n:n>50and f(50)+"\n\n"+f(n-50)or"\n".join(("|||/|||"[k:k+4]+" ")*(n//5)+" "+"|"*(n%5)for k in range(4))
```
### Explanation
```
def p(n):
if n > 50:
return p(50) + "\n\n" + p(n-50) # Handle 50-groups recursively
else:
# For each of the 4 lines:
rows = []
for row in range(4):
# - Build the "|||/"-blocks by slicing the correct part of "|||/|||".
# - Do that n/5 times
# - Then add "|" n%5 times
rows += [("|||/|||"[row:row+4]+" ")*(n//5) + " " + "|"*(n%5)]
# Join the four rows together
return "\n".join(rows)
```
Works in Python 2 and 3.
[Try it online](https://tio.run/##FcdBCsIwEEbhqwwDwsSgKdq4KOhFrItIjcbUPyV0I@TuMS4evG/5rq@EY63@PLvPfXKEARfbOUzkxXZK84gRrL1g15hyM@/fKUCESymmxdc4RN3fNBOrrcAYq/6vuXDjxiqfMkUKoOzwfEivVF1ywCpeDvbU9AM)
[Answer]
# [Python 2](https://docs.python.org/2/), 142 bytes
```
n=input()
while n>0:print"\n".join("".join("|/ "[2*(j%5>3)+(n/(5*(j/5+1))and 3-i==j%5)]for j in range(min(50,n)))for i in range(4)),"\n";n-=50
```
[Try it online!](https://tio.run/##RY3RCoJAFETf@4plIbg3tV217aFYf6R6ELK8UrMiRgT9@6ZB9DQMhzPTv8Y2oIgRXtA/RuLFs5Vbo1DZXT8IRn2EXndBQPqXb6P0oVhRt3RVyQnBkJuacUnOXOOsyky8nyifLmFQnRKooca1ofukO5uCmWcif7JhTuerPTLvbMwN2e9eLNz2Aw "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 103 bytes
```
$a=<>;do{$_=$a<50?"|||/ "x($a/5).'|'x($a%5):"|||/ "x10;for$i(1..4){say;s%\|/%/|%g}say""}while($a-=50)>0
```
[Try it online!](https://tio.run/##NYtBCsIwEAC/ImFDm0OTDbgX09QX@ANBAlYNFFMaQaXbrxvrwdsMw4z9NFApEHzbuXOa4eQhtIR7wcxmI141BENKV1z9UJLa/YtFd0kTxNpqvVVzDm@X5ZGNNCyvy6pCLM9bHPr1azyh6rAUsp80PmK659IcSKPFLw "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 134 bytes
```
f#n=unlines$(concat.f.(<$[1..n`div`5]))<$>["|||/ ","||/| ","|/|| ","/||| "]
f n|n>50=id#50++'\n':f(n-50)|1>0=(++['|'<$[1..n`mod`5]])#n
```
[Try it online!](https://tio.run/##NY7NCoMwEITvfYolCknQxliaHor6Bj31aAOVamiobsWfnvLudin0MPPBMAzzbOZX1/fb5iIsV@w9dnMsHm98NItyShRxnSuF99Z/7sZKWcRVzUIIGbCUmIUfs/AjgWh3DjBgZXTp28joJOE35GcncG@0DHmlS5EkNQ/8Pz68Wxq3MsJtaDxCCUMzXkCM63JdJlBAfRBTN/aebnVgNPA9l0ApuyGT1HAS6jyFYwomhRO5JlFwMCe7fQE "Haskell – Try It Online")
asdfghjkl-- Yeah, I'm working on it.
[Answer]
# PHP, ~~138~~ 141+1 bytes
probably not the shortest possible solution
```
for(;0<$z=50+min($n=$x=$y=0,$argn-=50);print"
")while($n++<$z||!$x=+(3<$y+=$n=print"
"))echo"/| "[$n%5?($y+$x++)%4<3|$n%5+$y<4|$z-$z%5<$n:2];
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/9ee6ee191ed8f83b9b14ae4537d0179dc4929042).
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 188 bytes
```
i->{int j=0,l,k;String r="";for(;j<~-i/50+1;j++,r+="\n")for(l=0;l<4;l++,r+="\n")for(k=0;k<(j*50+50>i?i-j*50:50);k++)r+=k%5>3?" ":k%5==3-l?"/":"|";return r.replaceAll("/(?=(\\|*\n))","|");}
```
[Try it online!](https://tio.run/##XZAxa8MwFIT3/AohKEixrbhN3cGybLoUOhQKGesOqqMEyYosZDkQkvSvu3JjKPRNH/fuhjvFjzzprDBq247yYDvngQoaGbzUZDeYxsvOkCVd2OFLywY0mvc9eOPSgPOi99wH7WW2Fa/Gi71wMdh4J82@BJ5rfXoP7AEDo0zK84SKpbGOW3pzAccgpLvOIaqK70SusjS6pyqKYhcxWBuIp59mKdXFI9X/9DbobYHUMqSytJSVTCbOsxTTNopw8LZ3WbmuIIB5IMbWia7gCubwAqkTfnAGOOKE1bwRz1ojuEIVQ3V9WdYGYxgHH6bXkc4DzJ2PndyCQ5gB3Vp8fAKOwyRgvs2p9@JAusETO/VHf1MQbq0@oYfsCWP6G7hexx8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 100 bytes
```
->n{(n/-50*-4).times{|i|j=[n-i/4*50,50].min
$><<("|||/|||"[i%4,4]+" ")*(j/5)+?|*(j%5)+$/*(1+i%4/3)}}
```
**Commented**
```
->n{(n/-50*-4).times{|i| #Calculate rows of tallies (Ruby rounds division towards negative infinity. Multiply by 4 lines per tally and iterate through them.)
j=[n-i/4*50,50].min #Number of strokes printed in current row is either the number remaining, or 50, whichever is less
$><<("|||/|||"[i%4,4]+" ")*(j/5)+ #Send to stdout the correct 4 chars selected from "|||/|||" plus a space, j/5 times (rounded down, which eliminates odd strokes.)
?|*(j%5)+ #If there are any odd strokes, add them to the output
$/*(1+i%4/3) #followed by a newline (2 for the final line of each row of tallies.)
}
}
```
[Try it online!](https://tio.run/##NYyxCsMgFAD3fkWRBPQZ85QqdEjSDxGXQgMKcWibIeT57dalw8ENx73351HXuaolnzyjchqUFeM3bq/PSZHS7LOKaMHpwekwbjFfumWaOCMibDAfezvYINmVCeAJnZAPatI36RC4kS3Amyil3v/fRKtPYEwo9Qc "Ruby – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~47~~ 46 bytes
```
Wa-:yP('|X4.sRA3-_'/M,4)X(YMN[a50])/5.'|Xy%5.n
```
[Try it online!](https://tio.run/##K8gs@P8/PFHXqjJAQ70mwkSvOMjRWDdeXd9Xx0QzQiPS1y860dQgVlPfVA8oXalqqpf3//9/I1MzAA "Pip – Try It Online")
### Explanation
```
Implicit: a is 1st cmdline arg, y is "", s is space, n is newline
W While loop:
a-:y Each iteration, subtract y from a and check if a is still nonzero
(Since "" is 0 in numeric contexts, this does nothing the first time through)
P Print the following:
('|X4.sRA3-_'/M,4)X(YMN[a50])/5.'|Xy%5.n
M Map this function to each number in
,4 range(4):
'|X4 String of four pipe characters
.s Concatenate a space
RA Replace the character at index
3-_ (3 minus function argument)
'/ with forward slash
We now have a list of four strings representing
the rows of a group of 5 tally marks; the
following operations apply to the list
element-wise:
[a50] List of a (number of remaining tallies) and 50
MN Get the min (number of tallies on this row)
Y Yank it into y
( )/5 Divide by 5 (number of groups on this row)
( )X String-multiply by that amount
y%5 Number of leftover tallies on this row
'|X String-multiply that many pipes
. Concatenate
.n Concatenate a newline
```
The resulting list will be something like this:
```
["|||/ ||\n" "||/| ||\n" "|/|| ||\n" "/||| ||\n"]
```
By default, `P` concatenates the contents of the list together and outputs them with a trailing newline. Thus, we get
```
|||/ ||
||/| ||
|/|| ||
/||| ||
```
with *two* trailing newlines (one from the list contents and one added by `P`). If there is another row to be printed, this gives the requisite blank line in between.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 30 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
H╷‾#%╵¹‾#÷U╷5×¹5%?4|*];4-;4/}╋
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXUyNTc3JXUyMDNFJTIzJXVGRjA1JXUyNTc1JUI5JXUyMDNFJTIzJUY3JXVGRjM1JXUyNTc3JXVGRjE1JUQ3JUI5JXVGRjE1JXVGRjA1JXVGRjFGJXVGRjE0JTdDJXVGRjBBJXVGRjNEJXVGRjFCJXVGRjE0JXVGRjBEJXVGRjFCJXVGRjE0JXVGRjBGJXVGRjVEJXUyNTRC,i=MjU2,v=8)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
5‰"|||/"¬‚×J4ôTôεε3Ý._}ø»¶«,
```
[Try it online.](https://tio.run/##AUIAvf9vc2FiaWX//zXigLAifHx8LyLCrOKAmsOXSjTDtFTDtM61zrUzw50uX33DuMK7wrbCqyz//zExMf8tLW5vLWxhenk)
**Explanation:**
```
5‰ # Divmod the (implicit) input-integer by 5
# i.e. 111 → [22,1]
"|||/" # Push string "|||/"
¬ # Push its first character (without popping the string itself): "|"
‚ # Pair them together: ["|||/","|"]
× # Repeat it based on the divmod
# i.e. [22,1] → ["|||/|||/|||/...|||/|||/|||/","|"]
J # Join everything together to a single string
# → "|||/|||/|||/...|||/|||/|||/|"
4ô # Which is then split into block of size 4
# → ["|||/","|||/","|||/",...,"|||/","|||/","|||/","|"]
Tô # Then split this list into sublists of size 10
# → ["|||/","|||/","|||/",...],[...,"|||/"],["|||/","|||/","|"]]
ε # For-each over the sublists:
ε # Map over the strings in the sublist:
3Ý # Push list [0,1,2,3]
._ # For each: rotate the string that many times
# ("|||/" → ["|||/","||/|","|/||","/|||"])
}ø # After the map: zip/transpose; swapping rows/columns
» # Join each inner list by spaces, and then the strings by newlines
¶« # Append a newline to each string
, # And print with trailing newline
```
`¶«,` of course has a few possible equal-bytes alternatives, like `,¶?` or `,õ,`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
⌐å9☼,▄█┌`╕G╛ï╞▬Gpƒ\╜ª_N╬
```
[Run and debug it](https://staxlang.xyz/#p=a986390f2cdcdbda60b847be8bc61647709f5cbda65f4ece&i=1%0A4%0A5%0A6%0A50%0A51%0A256&a=1&m=2)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~107~~ 106 bytes
```
i,j;f(n){for(;n>50;f(50))n-=50;for(i=5;--i;)for(j=0;putchar(++j+~n?j%5?(j-i)%5|n-j<n%5?'|':47:32:10)%5;);}
```
[Try it online!](https://tio.run/##NY3RbsIwDEXf8xUIqSJWHJGyGlBNx4dsPKCwbo60gLruhVJ@vTPT9nbOtXVv9O8xTpNg4tZmGNpzZzk/U1ClAJB982BNpSH2XhgekprAl@8@fhw761xy97xPBe1t8gIF3bJPu6y@uC3qalM/reoyaM7A4/R5lGxhMJL7WR9fDs1QYoWEa6SAVOKK1mi2WFYjm99d/ROdk92XXN/Ore0jLP9Qb8DiHJjBXDq11s6L02ueozbLAbTB/tNoxukH "C (gcc) – Try It Online")
-1 thanks to [ceilingcat](https://codegolf.stackexchange.com/questions/147962/basic-ascii-tallies/189237?noredirect=1#comment453635_189237)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `L`, 169 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 21.125 bytes
```
4ẋ5ẇƛ\|*₅5=[ḢėṘƛ÷$\/Ȧ;ðwj
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJMPSIsIiIsIjThuos14bqHxptcXHwq4oKFNT1b4biixJfhuZjGm8O3JFxcL8imO8Owd2oiLCIiLCI2Il0=)
[Answer]
# Befunge, ~~125~~ 105 bytes
```
$&:!#@_:::"2"v>*\5%4\`+1g1-,1+:14g\`#v_55+,$:#v_55+,
!}0:+*`"2"\-\<^!-g01%5\!`g41+5*5/5:::<0p01:-1<<<4-p4
```
[Try it online!](http://befunge.tryitonline.net/#code=JCY6ISNAXzo6OiIyInY+Klw1JTRcYCsxZzEtLDErOjE0Z1xgI3ZfNTUrLCQ6I3ZfNTUrLAohfTA6KypgIjIiXC1cPF4hLWcwMSU1XCFgZzQxKzUqNS81Ojo6PDBwMDE6LTE8PDw0LXA0&input=MjU2)
] |
[Question]
[
A *1-up quine* is a program which is very similar to a quine. The one major difference is that instead of printing itself once, when **n** copies of the program are concatenated, the result prints the original program **n+1** times.
## Example
If your program is `Abc123`:
```
Abc123 -> Abc123Abc123
Abc123Abc123 -> Abc123Abc123Abc123
Abc123Abc123Abc123 -> Abc123Abc123Abc123Abc123
```
# Challenge
Your challenge is to create the shortest valid 1-up quine in any language. The usual quine rules apply, so you may not:
* Submit the empty program.
* Directly or indirectly read1 the source code.
* Use quining built-ins.
This is code-golf, so **shortest code in bytes wins.**
1This does not include using a hard-coded string or code block as part of your program.
[Answer]
# GolfScript, 12 bytes
```
{: ".~"][}.~
```
[Try it online!](http://golfscript.tryitonline.net/#code=ezogIi5-Il1bfS5-&input=)
### How the source code works
```
{: ".~"][}.~
{ } Define and push a code block.
.~ Push a copy and execute it.
: Save the code block in the space character.
Every subsequent space will now execute the code block.
".~" Push that string.
] Wrap everything up to the last [ in an array.
[ Set a new array marker.
```
If the above source code is executed once, the stack will end up as
```
["" {: ".~"]} ".~"]
```
where the empty string at the beginning corresponds to the initial state of the stack (empty input).
Two copies of the source code would leave a final state of
```
["" {: ".~"]} ".~"] [{: ".~"]} ".~"]
```
three copies a final state of
```
["" {: ".~"]} ".~"] [{: ".~"]} ".~"] [{: ".~"]} ".~"]
```
and so on.
### What happens next
After executing the source code, the interpreter does the following.
1. It wraps the entire stack in an array, and pushes that array on the stack.
For two copies of the source code, the stack now contains
```
["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [["" {: ".~"][} ".~"] [{: ".~"][} ".~"]]
```
2. It executed `puts` with the intention of printing the wrapped stack, followed by a linefeed.
`puts` is defined as `{print n print}`, so it does the following.
1. `print` prints the wrapped up copy of the stack without inspecting it (i.e., without converting it to its string representation). This sends
```
{: ".~"][}.~{: ".~"][}.~
```
(the source code) to STDOUT and pops the stack copy from the top of the stack.
The stack now contains
```
["" {: ".~"][} ".~"] [{: ".~"][} ".~"]
```
2. executes the code block we defined previously.
`:` begins by saving `[{: ".~"][} ".~"]` in the space character, then `".~"` pushes itself, `]` wraps the `".~"` in an array, and `[` sets a new array marker.
3. `n` pushes a string consisting of a single linefeed.
The stack now contains
```
["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [".~"] "\n"
```
4. is executed once more. However, it was redefined when we called it for the first time and now contains an array, not a code block.
In fact, it pushes `[{: ".~"][} ".~"]`, leaving the stack as
```
["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [".~"] "\n" [{: ".~"][} ".~"]
```
5. Finally, `print` prints the topmost stack item without inspecting it, sending
```
{: ".~"][}.~
```
to STDOUT, 1-upping the source code.
[Answer]
## GolfScript, 12 bytes
```
{`'.~'+:n}.~
```
[Try it online!](http://golfscript.tryitonline.net/#code=e2AnLn4nKzpufS5-&input=)
### Explanation
This combines ideas from the standard GolfScript quine:
```
{'.~'}.~
```
And my [recently discovered quine](https://codegolf.stackexchange.com/a/71488/8478):
```
":n`":n`
```
The main idea is again to use `n` which is printed implicitly at the end of the program in order to get the additional copy of the quine. Since assigning the variable doesn't change anything when it's done again in subsequent copies, this will only add one copy. Here's a breakdown of the code:
```
{ # Standard quine framework. This pushes the block, duplicates it and runs the
# second copy, such that it can process the first copy to create a quine.
` # Convert the block to its string representation.
'.~'+ # Append the string '.~' to make a complete quine. This is simply left on the
# stack to be printed at the end.
:n # Store the string in n such that one more copy is printed at the end.
}.~
```
[Answer]
# Javascript ES6 (REPL), 55 bytes
```
var a=-~a;$=_=>`var a=-~a;$=${$};$();`.repeat(a+1);$();
```
*Saved 2 bytes thanks to @user81655!*
# Explanation
Here's the standard quine framework:
```
$=_=>`$=${$};$()`;$()
```
You should be able to see this framework inside the submission. More explanation below.
---
```
var a=-~a;
```
This is the counter, defaulted to 1. Basically, it tells us how much to repeat the quine and increments at the same time.
```
$=_=>`var a=-~a;$=${$};$();`.repeat(a+1);$();
```
This is the quine part. We essentially repeat the quine string by the counter+1. Subsequent function calls will override the output.
[Answer]
# CJam, 14 bytes
```
{"_~"]-2>_o}_~
```
[Try it online!](http://cjam.tryitonline.net/#code=eyJffiJdLTI-X299X34&input=)
### How it works
```
{"_~"]-2>_o}_~
{ } Define a code block and push it on the stack.
_~ Push and execute a copy of it.
"_~" Push that string.
] Wrap the entire stack in an array.
-2> Discard all but the last two elements (block and string).
_o Push and print a copy of that array.
```
After the last copy of the program has been executed, the array that contains the block and the string is still on the stack, so it is printed implicitly.
[Answer]
# Groovy, 83 bytes
```
s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//
```
There is one embedded and no trailing newline. This prints:
```
s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//
```
The function `f()` prints one copy of the quine. The initial program calls it twice. The first line of the appended code becomes a comment and only the second call to `f()` is executed.
[Answer]
# Ruby, 43 bytes
```
1;s="1;s=%p;$><<s%%s*n=2-0";$><<s%s*n=2-0
```
By itself, this prints itself `2-0` or `2` times. When concatenated to another copy of itself, the final print statement looks like `$><<s%s*n=2-01`, meaning it outputs itself just once (`01` being octal 1). So only the final copy of the string prints twice, the others print once.
The inline assignment to `n` is just to get the order of operations working correctly; state isn't actually being passed from one copy to the next.
[Answer]
# NodeJS, ~~63~~ ~~61~~ ~~60~~ 55 bytes
*this will also work in JavaScript (ES6) if you consider multiple console messages to be separated by newlines (no REPL required)*
Saved 2 bytes thanks to @dev-null
```
(f=_=>(t=_=>console.log(`(f=${f})()`)||(_=>t))(t()))()
```
*note that there is a newline at the end of the code.*
This was an interesting one, definitely one of my favorites for this site so far.
I'm fairly confident this can't be golfed much more. *(maybe SpiderMonkey's `print` function...)*
## Explanation
```
//FIRST ITERATION
console.log(`(f=${f})()`) //logs to the console a quine of the source code using function f's toString()
|| //causes the expression to evaluate to the second part, since console.log's return value is falsy
(_=>t) //a function that returns function t when called
t=_=> //defines function t to be the code above. When called, t will log a quine and then return a function that returns t.
( )(t()) //call t twice. (one call is done via the t() as an ignored parameter) This will print the quine twice.
f=_=> //define f as the above code.
( )() //call function f with no arguments. this results in a function returning t. (the result of calling t once)
//this newline is to compensate for console.log's behavior of adding a newline to its output
//SECOND ITERATION
( ) //call the function that returns t that was returned from the first iteration. This expression will result in whatever that function returns, which is t.
f=_=>(t=_=>console.log(`(f=${f})()`)||(_=>t))(t()) //this part evaluates to a function, which is passed as a parameter to the function that returns t, that ignores its parameter.
() //call whatever the last expression returned, which is the function t, with no parameters. This will print the quine once.
//this call will result in a function returning t, just like from the first iteration, so we can add on more iterations at will.
```
[Answer]
## Ruby, 55 bytes
```
n||=2;s="n||=2;s=%p;$><<(s%%s)*n;n=1;";$><<(s%s)*n;n=1;
```
Nothing very interesting here, it is just a normal ruby quine with a counter.
[Answer]
# JavaScript (ES6), 164 bytes
```
console.log((`+String.fromCharCode(96)).repeat(window.a||(a=3,5)).slice(67,-14))
console.log((`+String.fromCharCode(96)).repeat(window.a||(a=3,5)).slice(67,-14))
```
Works in any JS testing page or console in Firefox, assuming that the space between two console messages counts as a newline.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~58~~ 53 bytes
*Thanks to Jo King for -5 bytes.*
```
<say "<$_>~~.EVAL for 0..!.++;">~~.EVAL for 0..!.++;
```
Based on [Jo King's quine](https://codegolf.stackexchange.com/a/176322/14109).
[Try it online!](https://tio.run/##K0gtyjH7/9@mOLFSQclGJd6urk7PNczRRyEtv0jBQE9PUU9b21oJqyjX//8A "Perl 6 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~65~~ ~~61~~ 55 bytes
```
a=2
exec(s:='print(end="a=2\\nexec(s:=%r)#"%s*a);a=1')#
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9HWiCu1IjVZo9jKVr2gKDOvRCM1L8VWCSgeE5MHk1Et0lRWUi3WStS0TrQ1VNdU/v8fAA "Python 3.8 (pre-release) – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 60 bytes
```
s='try:n\nexcept:n="s=%r;exec s"%s;print n\nprint n';exec s
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWvaSo0iovJi@1Ijm1oMQqz1ap2Fa1yDq1IjVZoVhJtdi6oCgzr0QBqALKUIfKcf3/DwA "Python 2 – Try It Online")
[Answer]
# Japt, 40 bytes
```
Oo("+Q ²pT°?1:2 é4;POo("+Q ²pT°?1:2 é4;P
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=T28oIitRILJwVLA/MToyIOk0O1BPbygiK1EgsnBUsD8xOjIg6TQ7UA==&input=) Explanation to come.
[Answer]
# [Y](https://github.com/ConorOBrien-Foxx/Y)
## Noncompeting, 6 bytes
```
UCn*px
```
Y is a headcannon that I've had for a while, and this inspired me to write it. It is made for challenges in which sequencing is key, such as this. The code is divided into links by "node" characters. In this case, our code is put into two chains (originally), with the node being `C`.
```
U C n* px
1 N 2
```
`U` records a transcendental string, i.e., one that spans links. It records until it meets another `U`. If a `U` is not met by the end of the string, it wraps around. Also, `U` is included in the string by default. After recording the string, we proceed to the node `C`, which just moves us to the next link.
`n` pushes the number of chains. For our base case, this 2. For a sequence of `K` chains, there are `K+2` chains, as there are `K` nodes. `*` is string repittion. `p` prints the entire stack (in this case, one string), and `x` terminates the program.
In a text:
```
UCn*px
U..... record that string
C next link
n* repeat that string twice.
px print and terminate
UCn*pxUCn*pxUCn*px
U.....U record string
C next link
n* repeat that string four times (three Cs)
px print and terminate
```
[Try it here!](http://conorobrien-foxx.github.io/Y/)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes
```
⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HX0kcdK5QgVF12elb5o6ZmIG5VQjD//wcA "Brachylog – Try It Online")
Modified from [this quine.](https://codegolf.stackexchange.com/a/183203/85334)
```
⊥ Fail,
∨ or
w print
"⊥∨~kgjw₃w₅" "⊥∨~kgjw₃w₅"
₃ formatted
gj with itself;
₃w₅ print it again at the end of the program if this route succeeds.
```
When this is concatenated with itself, every route except the last fails and the program moves on to the next one, executing each `w₃` and backtracking past every `w₅` except the very last one.
```
⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HX0kcdK5QgVF12elb5o6ZmIG5VQjCJUfP/PwA "Brachylog – Try It Online")
```
⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HX0kcdK5QgVF12elb5o6ZmIG5VQjCppeb/fwA "Brachylog – Try It Online")
```
⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HX0kcdK5QgVF12elb5o6ZmIG5VQjDpqeb/fwA "Brachylog – Try It Online")
] |
[Question]
[
There is a boy named Peter. Peter is a picky eater and doesn't like to eat the same kind of cookie again on the same day.
Peter gets a present, The present is a box of cookies! The box contains \$K\$ types of cookies. Also, it contains different amount of each type of cookie.
Peter, being the picky eater he is, Wants to eat \$n\$ cookies, on each \$n^{th}\$ day. Also, he does not want to eat more than 1 cookie of the same kind on any given day.
i.e. He eats \$1\$ cookie on the \$1^{st}\$ day, \$2\$ cookies on the \$2^{nd}\$ day and so on.
If there is no possible way for Peter to eat \$n\$ cookies at day \$n\$, he gives up and dumps the box. He also dumps the box if it becomes empty.
Find the maximum number of days that the box will last for Peter.
## Input
\$K\$ Positive Integers, specifying the number of cookies for each different kind.
## Output
An Integer corresponding to how many days Peter keeps the box.
## Test Cases
```
INPUT -> OUTPUT
1 2 -> 2
1 2 3 -> 3
1 2 3 4 4 -> 4
1 2 3 3 -> 3
2 2 2 -> 3
1 1 1 1 -> 2
11 22 33 44 55 66 77 88 99 -> 9
10 20 30 40 50 60 70 80 -> 8
3 3 3 3 3 3 3 3 3 3 3 -> 7
3 3 3 3 3 3 3 3 3 -> 6
9 5 6 8 7 -> 5
1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10 -> 35
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 -> 32
```
[Gist for test cases](https://gist.githubusercontent.com/EliteDaMyth/19479d4d3bc1f285dcfb8dc4d4ebfa3f/raw/132ca67a3e239b0a0e26ea0341e591493ec7dc22/testcases.txt)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
[Answer]
# [Perl 5](https://www.perl.org/), ~~79~~ ~~77~~ ~~76~~ ~~75~~ ~~69 (rip)~~ ~~68~~ ~~64~~ 62 bytes
Credit to **@Lynn** for improving my answer by 4 bytes (68 to 64) and the explanation about the comma operator in scalar context here <https://docstore.mik.ua/orelly/perl2/prog/ch03_18.htm>
Thanks **@Nahuel Fouilleul** for the tip using anonymous functions to save 2 bytes (64 to 62) but if it's not allowed I'll revert back
```
sub{$^=0;++$^while(@_=sort{$b-$a}@_),!grep--$_[$_]<0,0..$^;$^}
```
**Test Cases Here:** [Try it online!](https://tio.run/##1ZPLToNQEIb3PMVIZgHp33rkThHlAXRpYmJaYvWoJE1LgEYjYenOR9CX80XwQOslUeJavgNnzvxzSWDIZbF0Wz6P23KzqHkei2g04vn9XbaURpLG5bqoal6M@bJJUhN7t4XMx2NOLzidHQqIyYTnEc@bNtqUkk6ysppOT9eFPKuyZak/ZrmnR5qWVLKsSorJuDiANQN1G@xPAw6cr0Pvt5S5i@zpTaWrABXuwHXhefB9BAHCsFcFLAFbwBFwBTwBXyAQnWTjF34VOmcIVRsB/G/tf2ANYA/gDOAO4A3gDxAMEA6g3tZf6/vncfvWwS7xHztnZqQl8iGXV5W87ibSAtkgp3@qpY4hKAD5IA/kKmd3WypNu1kXZHQzbWwHGvRZyTSp1khdBncSiLeKqVoknEa9xper7ifg8/GRkfRx5lbIi2xV0Yh0rlVIE3O9zW5Ixy4r/qhIx6S/vTzpNFX767MO3o@0pm3fAQ)
### Expanded:
```
sub { # Declare subroutine
$^ = 0; # Set scalar caret variable to 0 (you can put this variable right next to if statements and for loops etc)
++$^ while # Pre increment caret while the condition below is true
( # Bracket used so that you can declare/reassign values in a conditional
@_ = sort { # Sort the default array and store result back to default array
$b - $a # Sort from greatest to least (scalar variables a and b are default variables that come with sort)
}@_ # Add the default array as a parameter for the sort
), # End of bracket (in scalar context like in this solution it will only grab the right most argument of the array so the while loop is entirely dependent on the condition below)
!grep # Only save values if the below statement is true for each item in default array then reverse the boolean (will return false if the size of the array after grep is greater than 0)
--$_[$_] < 0, # Check whether the pre decrement of item (default is $_) at the index of default array is less than 0. If the caret is out of range of the array, it will default to undef which is treated as 0 in math operations)
0 .. $^ # Add an array of range 0 to caret inclusive to the grep
; # End of the while loop statement modifier
$^ # Return caret variable
} # End of subroutine
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~96~~ ~~92~~ 91 bytes
```
f=lambda l,n=1:n<=len(l)and-~f([v-(e<n)for e,v in enumerate(sorted(l)[::-1])if(e<n)-v],n+1)
```
[Try it online!](https://tio.run/##1ZPLboMwEEX3fMXswOpF4v1S6I9QFpQYBZU4CJyobZT@OrWttI3UoK7LMTCPa0bCM@Ob3B1EuCxdOTT7521DA0TpF2JTDlw4A2vE1v3onOrkOnwjWHeYiONEvSAujns@NZI782GSfKvEVVG4fs36zmjdUw3x4LNF8lnOVJJT@QhqkH4h/DYQIfpxTDxQ5lVpMKbKK4GSR4hjJAnSFFmGPDdZD4GH0EPkIfaQeEg9ZJ5OhbjD3YQO5lDfRob0pvwvghXCFaIV4hWSFdIVshXyFdTf@mvdHk9sSmfXjf84WDOLv468Ve2q@zEAhaDIPNVSbg7KQCkoAcUqqO@AWe2Oty980nvsp2OQRq0NMpYf2szSUyHB9VS896Nj@h30VYkVFqlLT0DnSGacceqFdDr7LC/kPtJ5vhCdr1UqXpZzfbHZ8gk "Python 3 – Try It Online")
Simply "eats" \$1\$ each of the \$n\$ cookies with the largest amount each day, starting with \$n=1\$, until we don't have \$n\$ different cookies left. Returns the number of days this was successful.
### Explanation
```
f=lambda l,n=1: # function taking the list of
# cookies l and day n
n<=len(l) # if don't we have enough cookies for
# today return False (0)
and # if we do have enough cookies
-~ # return 1 plus
f([...],n+1) # our function called reclusively for
# day n+1 with updated list:
sorted(l)[::-1] # of cookies sorted from most to least
for e,v in enumerate(..) # over the position and number of the
# cookies
v-(e<n) # subtract 1 from the n largest
# amount of cookies
if(e<n)-v # discarding empty amounts
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~82~~ ~~77~~ 76 bytes
-5 bytes inspired by [x1Mike7x](https://codegolf.stackexchange.com/users/45323/x1mike7x)'s [answer](https://codegolf.stackexchange.com/a/225978/64121). (Adding a `0` to the cookie list at every iteration)
-1 byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!
```
l=input()
i=0
while l.sort()<l>[0]:i-=1;l[i:]=[x-1for x in[1]+l[i:]]
print~i
```
[Try it online!](https://tio.run/##1ZFPT8QgEMXvfIq5dY2zG0pLodV6W69evDUctGKW2LQNsrF78atX6K5/Epd4Nj8CL@8NMwmMB7cbeja3w5OGGpIkmbva9OPerS6IqSl525lOQ7d5Hay3rrubhqrKrOv0qmtMpepmWqfPg4UJTN@k6nJxFRmt6d27mX1Dcupxb/e6IgDOHsIBoCfdQhhMgm716GB7d7u1drDHgkerH17mJkWmSNgx@zwxx/xLB5d5daxaCMqHPvWlOXKORYFCoJRYliGkyChmFHOKnGJBUVCU1CcZnuGc770SfV@UKL4H/4JFyCLkEXiEIoKIICOUEfxL/bV@fApfJsvTvX9sqg8 "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 70 bytes
```
f=(a,c=d=0)=>c?d-1:f(a.sort((a,b)=>b-a).map(x=>c*x?x-!!c--:x,c=++d),c)
```
[Try it online!](https://tio.run/##1VFLbpxAEN1zimfLUnfHA@rhz1jMrJJlNl7Gkcw0jYOFYQI4IrLmBpGy8dK@R87jC/gIk@oZNJEio6yjh@iqeu9VFfRt9i3rVFtuertucr3bFSnPZirNUynSpVrl9nxR8MzpmrbnxKypurYz4dxlGz6Q4t2wGuyTE2Xbi4F85@e5mCmxa/XX@7LVnBUdE06rs/xDWenL77XiUjh9c9m3ZX3DhdNtqrLnp1f1qXCKpn2fqS@8Q7rEgwV8QlV2/Qx62GjV6xyfkaIbPQz2Ekxc7DVUN8eRYocNP97frXUrLqhXq6ktCm5k@4Jq6q6ptFM1N/z67IH4LfYH0vTPxBXY66@fL0@P9GZYgL08/2Dba@qwFbs5XLOEa5nAM6E3hj6BUn9MR86Fe3AY2QEHO6lIRjYfQYAwRBQhjpEkhk@suYQr4Un4EoFEKBFJxNKQseXhLRAVWW@WQysBzUCMyKTBcZW/4U7Am4A/gWAC4QSiCcQTSCZAf@2fj7mL4HhnwX56PHr/56L5Lvc3 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = list of cookies
c = // c = cookies that were not eaten the day before
d = 0 // d = day counter
) => //
c ? // if we failed to eat all the cookies the day before:
d - 1 // stop and return d - 1
: // else:
f( // do a recursive call:
a.sort((a, b) => // sort the list of cookies ...
b - a // ... from highest to lowest
) //
.map(x => // for each value x in the sorted list:
c * x ? // if both c and x are not equal to 0:
x - !!c-- // decrement x and c
: // else:
x, // leave x unchanged
c = ++d // start by incrementing d and setting c to d
), // end of map()
c // pass c
) // end of recursive call
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes
```
‘ɼ-€+NÞƲAƑ¿ṛ®’
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4yTe3QfNa3R9js879gmx2MTD@1/uHP2oXWPGmb@//8/2lDHSMdYx0THVMdMx1zHQsdSx9BAZygLxgIA "Jelly – Try It Online")
[All testcases](https://tio.run/##1ZExCsIwGIV3r@ITftOkSUYv4AVKRxfpBdyKi@DmpgieQBxcVCgILRR6jPYiMQ1FCzY4yxfIy/9e8pNkuUiSlTFNuq@ySbM@j@fFqbzOyl3@rB/H/NKkB1Pfb1Rlxabc2oAx0SiagsVwE4K3AAf/LFydWdklHU5a3wZsnEMIhCGkhFLQ2rkERggInCAIIUESFLVWgAEGjbaoYc@Gguy1/4J5CDxwD8JD6EF6UB60B/tav0b/e4RrrbqNf1y0l4pf "Jelly – Try It Online")
## Explanation
```
‘ɼ-€+NÞƲAƑ¿ṛ®’ Main monadic link
¿ While
Ƒ invariant under
A absolute value
(that is, no numbers are negative)
do
Ʋ (
ɼ Apply this to the register:
‘ Increment
€ Map [over the range 1..register]:
- -1
+ Add
the list
Þ sorted by
N negation
Ʋ )
ṛ Replace with
® the register
’ Decrement
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~88~~ ~~82~~ ~~81~~ 80 bytes
```
f=lambda a,n=-1:-1in(a:=sorted([0]+a))and-n-2or f([x-1for x in a[n:]]+a[:n],n-1)
```
[Try it online!](https://tio.run/##1VLbaoQwFHz3K6YPi0mrJcZbFOyPiJSUVSrsRtEUtl9vE3W3S2nocx0f5pyZyYkm46d@H1QsxmlZuuokz29HCRmoKozKMOoVkWU1D5Nuj6RmzZOkVKpjqEI@TOhIfQmjzrALegVZq7IxlrpUTaDCiC5W0u2srTqMrSKMlh7MY5uvvQo2MnxoVCt9nsdTr4mP8AU@/bZKNRuHmfd4liPplQ6uS@wJSpvNLue5nfRdqjLDNbnOoQGI35HDTPFQ4XD0ccAqBrcIpUsEbnfAPUtiS@OdJgamTPZy1zj4lrC2DVvcuIzNxBKkKbIMeQ4hUBRWL7yIgTPEDAlDypAx5AyCWVF4MX6DkXLv13bmFTAzIJDbMr1t5Se4A7EDiQOpA5kDuQPCgcIB89f@fO1ZpLczS9fpYs/@56b9Lu6tdy26u3Zf "Python 3.8 (pre-release) – Try It Online")
Unwrapped version:
```
def f(a, n=-1):
a = sorted([0] + a)
if -1 in a:
return -n - 2
p = [x - 1 for x in a[n:]]
q = a[:n]
return f(p + q, n - 1)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
v{āNÌ‹R-Wds}\O
```
[Try it online!](https://tio.run/##yy9OTMpM/f@/rPpIo9/hnkcNO4N0w1OKa2P8//@PNtQx0jHWMdExiQUA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/2v6z6SKPf4Z5HDTuDdMNTimtj/P8Dhbm4yjMyc1IVilITUxQy87hS8rkUFPTzC0r0IbqhFJqBNgoqYLV5qf@jDXWMYrlApI4xjNYx0TGBs0GiRkAWRBUYglhASaAsUKmJjqmpjpmZjrm5joWFjqUlSNJAx8hAx9hAx8RAx9RAx8xAx9xAx8IAKGOsgwViEweKWeoAzdWx0DFHWIwBjXBAYxzQBAc0xQHNcEBzHNACB7TEAYEhRQghRYop2GYLqL4hLBjLBQA)
**Commented:**
```
v } # for N in range(len(input))
{ # sort the current cookie list (initially the input)
ā # push the range [1..len(list)]
NÌ # push N+2
‹ # is each value in the range less than N+2?
# this yields a list with N+1 leading ones
R # reverse the list of 1's and 0's
- # subtract this from the current cookie list
Wds # push min(list) >= 0 under the current list
\ # after the loop: discard the final cookie list
O # sum the stack: this counts the number of times
# the cookie counts were non-negative
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 32 bytes
```
{#(|/'0>)_x{x[y#>x]-:1;x}\1+!#x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJzVkc8OgjAMxu97is9wEEKMZX/YgIQXQeKNJ/Awg7y7ddOIkcWz+TVZ169dt3Vq5yy/HffUF2c/++Ga9X48tFXnl1NV7jK/CHFp82moIEeBsEK9PWjo1S4qkv1XdiD6nMI5XKJhDOoa1sI5NE2UCZKgCJpgCDXBEhwFTWGDbSVEG/D5cLDrS3whE2x2i0/dxCSoE9gELkGTgH/sl30MyoTe7ln5x8GxEKLML11UHqORHOdxc46BYpPFHZYKhNk=)
* `x{...}\1+!#x` set up a scan, seeded with `x` (the number of cookies of each type), run over `1..(number of types of cookies + 1)` (variable `y`)
+ `y#>x` identify the `n` cookies to eat (i.e., the `y` indices containing the largest values)
+ `{x[...]-:1;x}` eat those cookies, feeding the result into the next iteration of the scan
* `(|/'0>)_...` remove scan iteration results where there was any negative value
* `#...` return the count of the filtered results
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ⁿ┘ª1µiZ&Xû¢♣◙2╜8æ≥/
```
[Run and debug it](https://staxlang.xyz/#p=fcd9a631e6695a2658969b050a32bd3891f22f&i=%5B1+2%5D%0A%0A%5B1+2+3%5D%0A%0A%5B1+2+3+4+4%5D%0A%0A%5B1+2+3+3%5D%0A%0A%5B2+2+2%5D%0A%0A%5B1+1+1+1%5D%0A%0A%5B11+22+33+44+55+66+77+88+99%5D%0A%0A%5B10+20+30+40+50+60+70+80%5D%0A%0A%5B3+3+3+3+3+3+3+3+3+3+3%5D%0A%0A%5B3+3+3+3+3+3+3+3+3%5D%0A%0A%5B9+5+6+8+7%5D%0A%0A%5B1+1+1+1+1+1+1+1+1+1+1+1+2+2+2+2+2+2+2+2+2+2+2+2+3+3+3+3+3+3+3+3+3+3+3+3+4+4+4+4+4+4+4+4+4+4+4+4+5+5+5+5+5+5+5+5+5+5+5+5+6+6+6+6+6+6+6+6+6+6+6+6+7+7+7+7+7+7+7+7+7+7+7+7+8+8+8+8+8+8+8+8+8+8+8+8+9+9+9+9+9+9+9+9+9+9+9+9+10+10+10+10+10+10+10+10+10+10+10+10%5D%0A%0A%5B1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10+1+2+3+4+5+6+7+8+9+10%5D%0A&m=1)
A direct implementation. Takes in golfscript arrays, but normal ones are supported as well.
## Explanation
```
{{No{i|i^<-mcc:@i^>wL%v
{ w do-while top of stack is true:
{No sort descending
{ m map each element to:
i|i^< iteration index <= outer loop iteration index?
- subtract that form the element
cc copy twice
:@ count of truthy elements
i^< < index+1?
L wrap all arrays in stack
%v length decremented
```
[Answer]
# [J](http://jsoftware.com/), 38 bytes
```
_1+1#.0*/"1@:<:[(-~\:~)/\.@|.@,(#$1:)\
```
[Try it online!](https://tio.run/##1ZHLCsIwEEX3fsVFhbY@4qRNmjQqFARXrtxacCE@cOMPiL9eo9iq1cG1nAlk5t5hwuRYtkWww9QhwAAE589QYLZczMu17MuOoN6oLXM3catweCncJRoVIj@LfBB2utJFRRm19lM33rW2m8MJe0jEL1ckbwkU1Huh1uMbT@1OnXqvN/t2Ba2RpjAG1iLLagchJiQERdCElGAIlio5@QYrVkIGPwsWpvGsD2KGhEExaIaUwTBYhozBb@9XNL9R38fbR/MfF8sr "J – Try It Online")
For `1 2 2`:
```
(#$1:)\
1 0 0
1 1 0
1 1 1
[ … |.@,
1 1 1
1 1 0
1 0 0
1 2 2
f /\. for each suffix, fold from bottom to top with f
( /:~) sort the remaining cookies (highest first),
-~ subtract the needed cookies for the day:
0 0 _1
1 0 1
1 2 1
1 2 2
0*/"1@:<: does the row only contain numbers >= 0?
0 1 1 1
1#. count the 1s
_1+ minus one (the initial cookie row)
-> 2
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 20 bytes
```
TvNgg:RSNg+:vRL UiDi
```
Takes inputs as command-line arguments. [Try it here!](https://replit.com/@dloscutoff/pip)
The equivalent program in Pip Classic is **22 bytes**:
```
TvNgg:RVSNg+:vRL++i--i
```
Verify all test cases: [Try it online!](https://tio.run/##1dG7CsIwGIbh/b@KF9dSSZukSTu4uohKFd2ETqVbRXARr73G41KDszw58eUESd/1w56mOnIR9nNhRcOUCemMibDmMmzPy7at6t1m2SbVuV4kSZem3cCVHc3hJNchI5dQ0c8Wg3mNtOShv88@SBbikIclBmspCpzDe8pSMkWu0AqjsIpC4RReieaLcSol4Tw87n3ZSB6hI0yEjSgiXISPKCPCC/0qnw@wj3v9a9cfhzc "Pip – Try It Online")
### Explanation
```
TvNgg:RSNg+:vRL UiDi
g is list of cmdline args; v is -1; i is 0 (implicit)
T Loop until
vNg there is a -1 in the cookie counts list:
R The reverse of
SNg the cookie counts list, sorted ascending
(in other words: the cookie counts list, sorted descending)
Ui Increment i and
vRL create a list of that many -1's
+: Add those two lists itemwise
g: Assign the result back to g
Di Decrement i and autoprint it
```
---
Here are two different approaches, also 20 bytes each:
```
Wi<#R:SN:FI:gDg@<Uii Filter 0's out of the list at each step instead of checking for -1
L#gI(g:RSNgi)Dg@<Uii Loop len(input) times; increment i only if there are enough cookies
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 62 bytes
```
f=(c,d=0)=>c.sort((x,y)=>y-x)[d]?f(c,++d,c.map(x=>--c[--d])):d
```
[Try it online!](https://tio.run/##1ZFLTuNAEIb3PsUvhORuEVuN3wY5rJjlbFiGSHjabcYjY2faBiVCuQESG5ZwD87DBThCpjqxgoSwWI8@y11Vf73s/pPf5Z3U1aJ3mrZQm02ZMTkpMsGzqXS7VveMLScr8lbOks@K@VlJ@tFRMZHuTb5gy2zqOHLmOMWc85Nio9Xf20orZpedzV2t8uJHVauLVSOZ4G7fXvS6aq4Zd7tFXfXs4LI54G7Z6vNc/mYdsinuLWCGuur6CdRyoWSvCsyRoRtqbDhT2Px0m0Nxc@wlGmrW@nl780tpfkq9tKK2KJlJ2wZk23Rtrdy6vWZXh/ekr7E9kGUfE89gv78@vj0/0dvGCey3lwd7fUUd1nxzDM8s4VnG8I3pD2ZAkBsM7qB58HYVJm3HrpyyKI3KAoQhoghxjCRBmho9tY4FPAFfIBAIBSKBWCARRkwsH19BUmx9GY6sFDQDCWLjhvtVPuON4I8QjBCOEI0Qj5CMkI5Af@3bx9xFuL@zcDs9GWr/56D5Lu8f "JavaScript (Node.js) – Try It Online")
The TIO setup is based on Arnauld's answer.
Seems greedy eating cookies with most copies works, though I don't know how to prove it (but that doesn't matter).
```
f = (
c, // cookies (array of integers)
d = 0 // day (integer)
) =>
c.sort((x, y) => y - x) // sort cookies (desc order)
[d] ? // Is there enough kinds of cookie for today?
f(c, ++d, // Next iteration (day + 1)
c.map(x => --c[--d]) // Eat 1 per each
// greedy eat kinds with most copies
): d
```
[Answer]
# [Haskell](https://www.haskell.org/), 71 bytes
```
(0?)
n?a=maximum$n:[(n+1)?b|b<-mapM(\x->x:[x-1|x>0])a,sum b+n+1==sum a]
```
[Try it online!](https://tio.run/##LY1NbsIwEIX3OcUskLBF3BLzU0rj5AKtegBgMSYJtYgdKw5qFpy9rg3R23xv5r2ZH3TXum19I46eLEuamBKFxlHpm56Z/YGYRUZLeZc502i/yHFkxbg/jCy7j8XyRDF1Nw1yEWJCRMST16iMqLoEiEo7mrMmNEnVdxY4fXEWDXkVczan@ay41MOnMnUCbT0Air7GKkx/u75yoD7kYwDhku2VGUgTIkKmmEqaQPziM@DACuBJhFXE1YTroGDXk512HPizEWNPPervsIEt7OAt2s3fuWnx4jw7W@vZN/8H "Haskell – Try It Online")
The relevant function is `(0?)`, which takes the list `a` of cookie quantities and returns the number of days.
Due to Haskell requiring `import Data.List` for sorting, I think bruteforce is the way to go.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~31~~ 29 bytes
```
.+
$*
m{O^`^1*
1_
_
}1`1$
_
_
```
[Try it online!](https://tio.run/##1dE7DsIwDAbg3ecoEiq/kPNOTsHA3paBgQEGxIZ69mBKYSkWM/qSOHIelpLr8Xa6HOpqvR9QtxtqWjrfd93QmZZMTz2NZjCNxL5WA0vS4V4jPPw8c2QlPlcnZCQtedniEQJiRErIGaWQYViGY3hGYERGYmQmhy@WWSqQ@5CR3sUWrMIpvCIooiIpsqIo5IV@tc8HhKlunk/9cfIB "Retina 0.8.2 – Try It Online") Takes a newline-separated list, but link is to test suite that converts from comma-separated list for convenience. Explanation: Performs a slightly different calculation with the same result: on day `m` he eats up to `m` cookies, then when all the cookies have run out the desired answer is the most cookies he ate in any given day.
```
.+
$*
```
Convert to unary.
```
m{`
}`
```
Repeat until all the cookies have been eaten, and also evaluate the script in multiline mode.
```
O^`^1*
```
Sort the cookies in descending order.
```
1_
_
```
Try to eat the same number of cookies that were eaten the previous day.
```
1`1$
1_
```
Try to eat a new different cookie each day.
```
_
```
Count the maximum number of cookies eaten on any given day.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
≔⁰ζW›Lθζ«≦⊕ζ≔⟦⟧ηW⌈⁻θηF№θκ⊞ηκ≔ΦEη⁻κ‹λζκθ»Iζ
```
[Try it online!](https://tio.run/##bY49C8IwEIbn9ldkvEIEwbGTFBShhe6lQ6hnE5qmNh8qir89JrbgIrfc3cP73HWc6W5i0vu9MaJXsKXkmeXpnQuJBI4amUUNJarecpizSDPySpOKXdfESXUaR1QWz0s2WUHTUsLjvMoq9hCjG6ESyhmYIwyuy6QJFJNTNq6GsKmd4cBj/3MdhIx/hKuRLIaBkhKNAfl9KosBSuYQeqe1FsFXMGMhoNz7ptnRP9W2fnOTHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰ζ
```
Start with `n=0`.
```
W›Lθζ«
```
While there are enough different cookies:
```
≦⊕ζ
```
Increment `n`.
```
≔⟦⟧ηW⌈⁻θηF№θκ⊞ηκ
```
Sort the cookies into descending order.
```
≔ΦEη⁻κ‹λζκθ
```
Decrement the first `n` cookies, removing entries that become zero.
```
»Iζ
```
Print the final value of `n`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~97 91 88 84 69~~ 63 bytes
```
f=(n,d=0)=>n.sort((a,b)=>b-a)[d]?f(n.map((e,i)=>e-=d>=i),d+1):d
```
[Try it online!](https://tio.run/##1VPBjpswEL3zFXOqbQVYB0Ig2TpRtcqhPWQP2UuVjbRObBYqFlLstFpV/fbUDk6kZhf1XD0EnnnzZsZ4/I3/4GrXlnsd1I2Qx2POcO0LRgmb1aFqWo0x97fG2gacrMVmnuM6fOF7jKVfGrcMmJixkvhiMCRTcfRubkAExUc6l1P7lfN1MZCB8AsmNmu6meJiwCT5QI2DerumVhq0VPqOK6mAwdMQIghmEHl2Edtl7JYjA2OOnOm4CKJOYcM6dHITZcKMbARJAuMxpClkGUwmlp94QwoRhZjCiEJCYUwhpZBRS2ZeDO/BUKn3rnvsTcDUgAxSayaXVq4R9SDuwagHSQ/GPUh7kPVg0gPz1/752LNILmeWnKpnTvs/O@2@oqdbN7RqX5VaS2Fm9jK/4cmJ0WONyK13jgjzpl3wXYFlBWwGv1yCqjQvBrI6q2wBq@vost4fLG/DzL25BCFyun6SzZaHl61ssSQXTSvVobIiR520w43jm0qGVfOM0cNi9XD3abWYomvms4IcI//L6n4ZKt2W9XOZv@JTK8RHBOT3A69AN8jvSvlobnLAX0nWaHmPfEBfFyu0WQ9w7vTAGHMdkrctFRL4TtvsbhM/uTJZzuKreGP@Jsc/ "JavaScript (Node.js) – Try It Online")
## How it works
### Arguments
* `n` [init: none] - the array of cookie types
* `d` [init: 0] - the day number
### Function body
First, we check if there are enough truthy entries to "pick" cookies. If not we simply return the day count.
If there are enough, then from each element of the sorted list (descending) we subtract 1 if the index is low enough and the element is strictly positive. If not, leave the element as it is. Call `f` with the obtained array and an incremented day number.
I also realized that since `0` is falsey, we do not need to filter. PLEASE don't make the 69 joke, it's getting boring.
*-2 bytes thanks to @A username*
*-6 bytes thanks to @tsh*
[Answer]
# [R](https://www.r-project.org/), 86 bytes
```
function(b){while({b=-sort(-b);b=c(b[1:T]-1,b[-1:-T],0);T<=sum(b|1)&b[T]+1})T=T+1
T-1}
```
[Try it online!](https://tio.run/##1ZJBasMwEEX3PoWhUCQyAkmWLDmpewrtjDGV49LQNg62Q1vSnN01ocqmmTjb8rQS/8@fkaYb109ffbVrhqarXptm11e@/czH5/22Hjbtlnh6@HjZvDXk4HPWt91AmKcrn9fEF2LpSibAF0wsmSuB05V7yPv9O/Hfgt77wpULcaQudwsROSaOF8NITQRISuO7mD3GMsI1kARVclUFClRQquvK@Ypy0skbck/MTzHFTrlTiwq0hjQFY8BayLJgzVArB8kh4aA4aA4pB8PB8uCzmC@BCwSXudkVHCnmyGCaByyYoNQzj/UHiZAgKASNkCIYBIuQIUw/NHfOi6TnNlifGrO/Zf/x5XlkGY0/ "R – Try It Online")
```
days_peter_keeps_box=
function(b){
while({ # Loop for each day peter has the box:
b=-sort(-b) # sort the cookies with most-abundant types first,
b=c(b[1:T]-1,b[-1:-T],0) # take out 1 cookie from each of the first T types (initially 1),
T<=length(b) # now check: if T is greater than the number of cookie types
&b[T]>-1 # or any of the types have less than zero cookies left
# then we've gone one day too many... stop the loop;
})T=T+1 # otherwise increment T.
T-1} # When the loop is finished, output T-1.
```
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 257 bytes
```
fmod P is pr SORTABLE-LIST{Nat<}*(sort List{Nat<}to L). var L : L . var X
N :[L]. op b : L -> Nat . op _,_ : L Nat -> Nat . eq b(L)= L,0 . eq L,N =
d(sort(L),s N),s N . eq X,s N = N[owise]. op d : L Nat ~> L . eq d(L,0)=
L . eq d(L s N,s X)= d(L,X)N . endfm
```
### Example Session
```
\||||||||||||||||||/
--- Welcome to Maude ---
/||||||||||||||||||\
Maude 3.1 built: Oct 12 2020 20:12:31
Copyright 1997-2020 SRI International
Tue May 18 23:37:06 2021
Maude> fmod P is pr SORTABLE-LIST{Nat<}*(sort List{Nat<}to L). var L : L . var X
> N :[L]. op b : L -> Nat . op _,_ : L Nat -> Nat . eq b(L)= L,0 . eq L,N =
> d(sort(L),s N),s N . eq X,s N = N[owise]. op d : L Nat ~> L . eq d(L,0)=
> L . eq d(L s N,s X)= d(L,X)N . endfm
Maude> red b(1 2) .
reduce in P : b(1 2) .
rewrites: 37 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 2
Maude> red b(1 2 3) .
reduce in P : b(1 2 3) .
rewrites: 99 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 3
Maude> red b(2 2 2) .
reduce in P : b(2 2 2) .
rewrites: 96 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 3
Maude> red b(11 22 33 44 55 66 77 88 99) .
reduce in P : b(11 22 33 44 55 66 77 88 99) .
rewrites: 1045 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 9
Maude> red b(1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10) .
reduce in P : b(1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6
6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10) .
rewrites: 82081 in 27ms cpu (27ms real) (2952129 rewrites/second)
result NzNat: 35
```
### Ungolfed
```
fmod P is
pr SORTABLE-LIST{Nat<} * (sort List{Nat<} to L) .
var L : L .
var X N : [L] .
op b : L -> Nat .
op _,_ : L Nat -> Nat .
eq b(L) = L, 0 .
eq L, N = d(sort(L), s N), s N .
eq X, s N = N [owise] .
op d : L Nat ~> L .
eq d(L, 0) = L .
eq d(L s N, s X) = d(L, X) N .
endfm
```
This program accepts input via a function `b` which takes a list of natural numbers. The function `d` will "eat" cookies for each step, and it the program runs until the list term is no longer a well-formed list of natural numbers, then returns the index of the previous step.
[Answer]
# [Haskell](https://www.haskell.org/), 114 bytes
```
import Data.List;p i k|i<length(filter(>0)k)=p(i+1).zipWith(-)(sort k)$replicate(length k-i-1)0++repeat 1|0<1=i---
```
[Try it online!](https://tio.run/##vVJNb5tAEL3zK0aWpbBi1lm@QQk59ZieemikaBURd12vwBgta1uu/N/dMU6U2C7NJQoPBPtm3psHy7zsKlXX@71etEtj4Vtpy8m97uxNCxqqnb6tVfPbzt2Zrq0y7p1gFStaV3s@m/zR7U9NNc7c7iCu2NiottbT0ir3qIOKa@4z4XlUUaUFfydu/UJzzvecA6zXa7Bz1Sl43lrVwUYZBdPlqrHqF5QNXbQmqaGWnnvewhWJr5wZFNCCcByHdBZqMLCDGd2Lgh4PxZX9Yc19A2MYTWAEngfdfLmhDnoaAb97xxkHXo8dLCmQ2WjKdGry8IGJS9PZkb8uTsydRakbcluU7fcncFfNdGXMFg7BGYz72Y/gPvoYSAxYv8bjGkOJ4RmDEUYSo3P2tDMgLjjT9jidQFLSkmWEcYxJgmmKWYZ5LjF/1yYwEBgKjATGAhOBqcBMSMzeekL8BySm/@mQmLxVc6T5mGEqMb4IfYFgAOEAogHEA0iO6GMkZ0gHkA0gHwB91Y9O2sD4cvfjPkT2YvFlZB/j033pFV9@SLn/Cw "Haskell – Try It Online")
---
Uses an algorithm of order \$\mathcal O(m\cdot n\ln n)\$ where \$m\$ is the maximum number of cookies of one kind and \$n\$ is the input list's size: On day \$d\$, sort all remaining cookies by their quantity and remove the \$d\$ cookies of whose kinds there are the most, if possible. Else, this day is the one sought after. If on the other hand the removal was successful, go on to day \$d+1\$.
] |
[Question]
[
### Introduction
In base 10, the Champernowne constant is defined by concatenating representations of successive integers. In base 10: `0.1234567891011121314151617...` and so on.
You can see that the first appearence of `15` starts at the `20th` decimal:
```
Position
0000000001111111111222222222233333333334444444444555555555566666666
1234567890123456789012345678901234567890123456789012345678901234567
^
0.1234567891011121314151617181920212223242526272829303132333435363738...
^^
15 = position 20
```
The first appearence of `45` starts at the `4th` decimal:
```
Position
0000000001111111111222222222233333333334444444444555555555566666666
1234567890123456789012345678901234567890123456789012345678901234567
^
0.1234567891011121314151617181920212223242526272829303132333435363738...
^^
45 = position 4
```
So, the task is easy. Given a non-negative integer, output the position of the integer in the Champernowne constant.
### Rules
* You may provide a function or a program
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
### Test cases
```
Input: 20
Output: 30
Input: 333
Output: 56
Input: 0
Output: 11 (note that the 0 before the decimal point is ignored)
Input: 2930
Output: 48
```
[Answer]
# LabVIEW, 29 [LabVIEW Primitives](https://codegolf.meta.stackexchange.com/a/7589/39490)
This uses strings for now. It matches the input as a pattern and outputs the offset - (input lenght -1).
[![](https://i.stack.imgur.com/wGdn4.gif)](https://i.stack.imgur.com/wGdn4.gif)
[Answer]
# Pyth, 10
```
hxjkS+QT`Q
```
Concatenates first `input + 10` numbers then finds the 0 based index plus one.. The extra ten are only needed for 0.
[Test Suite](http://pyth.herokuapp.com/?code=hxjkS%2BQT%60Q&input=2930&test_suite=1&test_suite_input=0%0A1%0A15%0A20%0A333%0A2930&debug=0)
[Answer]
# Javascript, 57 bytes
```
a=prompt();for(y=b=" ";y<a+11;)b+=++y;alert(b.indexOf(a))
```
Saved 1 byte thanks to Conor O'Brien.
[Answer]
## Haskell, 62 bytes
```
a#b|and$zipWith(==)a b=1|1<2=1+a#tail b
(#(show=<<[1..])).show
```
Usage example: `(#(show=<<[1..])).show $ 2930`-> `48`.
How it works: `a # b` finds the position of `a` within `b`: if `a` is prefix of `b` return `1`, else add `1`to a recursive call with `a # tail b`. The pointfree function `(#(show=<<[1..])).show` expects an (unnamed) argument `n` and calls `show n # show=<<[1..]`.
The function `subIndex` would also do the job of `#`, but the required `import Data.List.Utils` doesn't pay off.
[Answer]
# Ruby, 28
```
->n{[*0..n+10]*''=~/\B#{n}/}
```
Includes a 0 at the beginning so that matches are 1-indexed, but uses `\B` to require that the match not be at the beginning of the string.
[Answer]
# Japt, 11 bytes
This was originally beating Pyth, but apparently it didn't work for input `0`.
```
1+1oU+B ¬bU
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=MSsxb1UrQiCsYlU=&input=MTAx)
### How it works
```
1+1oU+B ¬ bU
1+1oU+B q bU // Implicit: U = input integer
1oU+B // Generate the range [0, U+11).
q bU // Join and take the index of U.
1+ // Add one to get the correct result.
// Implicit: output last expression
```
[Answer]
# Lua, 54 Bytes
```
s=""for i=1,1e4 do s=s..i end print(s:find(io.read()))
```
Note: ~~Currently this program prints both the first occurrence of the first char of the string, and the point where it ends. If this is not allowed, it will cost a few more bytes.~~ I would like to petition for a bonus because my program prints out both the first position and last position of the input number.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 22 bytes
```
it10+:Yst' '=~)wYsXf1)
```
Take the input (`i`), make the vector 1 to input+10 (`10+:`), converts the vector to a string (`Ys`), and remove the spaces, which is painful, (`t' '=~)`). Then, convert the input to a string (`Ys`), find where the input string is in the string of numbers (`Xf`) and take the first location (`1)`). The `t`'s and `w`'s are manipulating the stack (duplicate and swap, respectively).
[Answer]
# PowerShell, 39 44 bytes
[Edit: my assumption doesn't hold, building an array from 1-0 doesn't find 0 at place 11. Instead, build from 1-x+10 to handle 0 as well, now 44 bytes]
```
param($i)(1..($i+10)-join'').IndexOf("$i")+1
```
---
You will always find *x* when building a string of the Champernowne constant at the latest point when you add *x* onto the end, so an array from 1-x will always have the answer in it. The question becomes *"does it occur any sooner than that?"*. This code
```
param($i)(1..$i-join'').IndexOf("$i")+1
e.g.
PS C:\Temp> .\Champer.ps1 20
30
```
generates a range of numbers, casts it to a string, and searches for the parameter inside it. Because PowerShell is an object oriented shell, the parameter is actually an `[int]` type, so trying to save two characters with `.IndexOf($i)` would search the string for an integer and find nothing. That's why I use string interpolation `"$i"`.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL) (release 1.0.1), 22 bytes
```
iXK10+:"@Ys]N$hKYsXf1)
```
### Example
```
>> matl iXK10+:"@Ys]N$hKYsXf1)
> 333
56
```
### Explanation
```
i % Input
XK % Copy to clipboard K
10+ % Add 10. This is needed in case input is 0
: % Vector of equally spaced values, starting from 1
" % For each
@Ys % For loop variable as a string
] % End
N$h % Horizontal concatenation of all stack contents
KYs % Paste from clipboard K (input number) and convert to string
Xf % Find one string within another
1) % First value
```
# [MATL](https://github.com/lmendo/MATL) (release 20.8.0), 16 bytes (language postdates challenge)
*Credit to @Giuseppe for this version of the program (slightly modified)*
```
10+:"@V]&hGVXf1)
```
[Try it online!](https://tio.run/##y00syfn/39BA20rJISxWLcM9LCLNUPP/f2NjYwA)
### Explanation
```
10+ % Implicit Input. Add 10. This is needed in case input is 0
: % Vector of equally spaced values, starting from 1
" % For each
@V % For loop variable as a string
] % End
&h % Horizontal concatenation of all stack contents
GV % Paste from automatic clipboard G (input number) and convert to string
Xf % Find one string within another
1) % First value
```
[Answer]
## PowerShell, ~~54~~ 50 Bytes
```
for($c='';!($x=$c.IndexOf("$args")+1)){$c+=++$i}$x
```
Thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) for the idea of swapping the `while` loop for a `for` loop.
Executes via a `for` loop. As with other languages, the first statement in the loop can construct variables and assignments, so this starts with `$c` equal to just the empty string `''` so that we have zero-indexing of the string lining up with the decimal indexing of the challenge. We're then in a loop that checks whether `$c` has the input integer (`$args`) somewhere within it (i.e., since `.IndexOf()` returns `-1` if the string isn't found, we add one to that (`0`) and not it (`$TRUE`) to continue the loop). If it's not found, we add on our pre-incremented `$i` counter variable, then recheck the string. Once the string is found, `.IndexOf()` will return a positive value, the not of which will be `$FALSE`, breaking out of the loop. Finally, we output the index with `$x`.
[Answer]
# JavaScript (ES6), 40 bytes
```
x=>(f=n=>n?f(n-1)+n:" ")(x+11).search(x)
```
Uses the recursive function `f` to avoid loops. The [search](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) method works the same as `indexOf` except that it takes a RegExp as a parameter, which is irrelevant for this challenge.
Adding a `" "` for the `n=0` case (zero is falsy in JS) coerces the `+` to perform string concatenation instead of addition, and corrects for zero-based indexing.
[Answer]
# Python 3, 54.
```
print(''.join(map(str,range(1,9**7))).find(input())+1)
```
[Answer]
## CJam, 11 bytes
```
r_i),s\#Be|
```
[Test it here.](http://cjam.aditsu.net/#code=r_i)%2Cs%5C%23Be%7C&input=15)
I'm finding the position of `N` in the string `01234...N` to account for the 1-based indexing. Finally I fix `0` by applying logical OR with 11.
[Answer]
## Seriously, 13 bytes
```
;≈9u+R`$`MΣí
```
Takes input as an integer. Contains unprintables, so hexdump:
```
0c3bf739752b526024604de4a1
```
[Try it online](http://seriouslylang.herokuapp.com/link/code=0c3bf739752b526024604de4a1&input=5)
Explanation:
```
;≈9u+R`$`MΣí
<form feed> push str(input)
;≈9u+R dupe, push [1,...,input+10]
`$`MΣ string concatenation of list
í get index of input
```
[Answer]
# ùîºùïäùïÑùïöùïü, 13 chars / 22 bytes
```
1+⩥(1,ï+ḋ)⨝ÿï
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=20&code=1%2B%E2%A9%A5%281%2C%C3%AF%2B%E1%B8%8B%29%E2%A8%9D%C3%BF%C3%AF)`
[Answer]
## k4, 21 bytes
```
{*1+(,/$1+!10+x)ss$x}
```
Same algo as everyone else—concatenate `[1..10+x]` as strings, search for x as string, convert to one-based indexing, return first hit.
Checking the test cases:
```
&/20 4 30 56 11 48={*1+(,/$1+!10+x)ss$x}'15 45 20 333 0 2930
1b
```
[Answer]
# Mathematica, 101 bytes
```
(If[#==0,11,m=Min@SequencePosition[s=Flatten[(K=IntegerDigits)/@Range[0,#]],K@#];Length@s[[;;m-1]]])&
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~82~~ ~~73~~ 55 bytes
*Migrated from [the duplicate](https://codegolf.stackexchange.com/questions/137474/champernowne-up-to-me)*
```
x!b|or$zipWith(==)x b=0
x!(_:b)=1+x!b
(!(show=<<[1..]))
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0IxqSa/SKUqsyA8syRDw9ZWs0IhydaAq0JRI94qSdPWUBuogivdVkNRozgjv9zWxibaUE8vVlPzf25iZp5tQVFmXolKupKlodJ/AA "Haskell – Try It Online")
## Explanation
First we define `!`. `x!b` truncates `b` to the first appearance of `x`. It does this by checking if `b` starts with `x` (`or$zipWith(==)x b`) returning `x` if it does and moving one down the string otherwise. Then we define our main function. Our main function is a point-free function that takes the constant (`show=<<[1..]`) and truncates it to the first appearance of `x`. This takes `x` as a string.
[Answer]
# JavaScript (ES6), ~~50~~ ~~39~~ 38 bytes
```
x=s=``
f=n=>-~s.search(n)||f(n,s+=++x)
```
---
## Try it
```
x=s=``
f=n=>-~s.search(n)||f(n,s+=++x)
o.innerText=f(i.value=15);oninput=_=>o.innerText=f(+i.value)
```
```
<input id=i type=number><pre id=o></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
+⁵RVw
```
[Try it online!](https://tio.run/##y0rNyan8/1/7UePWoLDy////GwAA "Jelly – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
⌐╛∙#»▓
```
[Run and debug it](https://staxlang.xyz/#p=a9bef923afb2&i=20%0A333%0A0%0A2930&a=1&m=2)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 26 bytes
```
{[~](0..$_).index($_)||11}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq6LlbDQE9PJV5TLzMvJbVCA8iqqTE0rP2fll@kYGiqY2KqY2SgY2xsrGOgY2RpbKBQzaWgoFCcWKmgp5bGVfsfAA "Perl 6 – Try It Online")
Finds the index of the element in the concatenated range from 0 to that element, or `11` if the number is a zero
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 5 bytes
```
€ṁdNd
```
[Try it online!](https://tio.run/##yygtzv7//1HTmoc7G1P8Uv7//29hDgA "Husk – Try It Online")
*-1 thanks to Razetime*
```
€ The 1-based index, in
d decimal digits
ṁ concat-mapped over
N all natural numbers,
d of the decimal digits of the input.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
nLJsk>
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/z8erONvu/39jY2MA "05AB1E – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
₁+ɾṅḟ›
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwi4oKBK8m+4bmF4bif4oC6IiwiIiwiMjBcbjMzM1xuMCJd) `ɾṅḟ` would be enough if not for the zero edgecase.
```
₁+ɾṅḟ›
› # 1 +
ḟ # Index of input in
·πÖ # Concatenation of
…æ # 0...
‚ÇÅ+ # 100+n
```
[Answer]
# [Perl 6/Rakudo](https://perl6.org/) 29 bytes
```
{$_~=$++until /(.+)$^a/;$0.chars}
```
Defines a function with one input ($^a). Call thus:
```
say {$_~=$++until /(.+)$^a/;$0.chars}(333)
> 56
```
Appending `$`, an anonymous variable, incrementing `$++` until the input `$^a` is found, and then counting the number of chars before it. Requiring at least 1 char before it `.+` in the regex usefully excludes the 0->0 case
[Answer]
# J, 30 Bytes
```
{.I.(":E.[:}.' '-.~":@i.@+&11)
```
Could probably be golfed down a bit more, specifically in concatenating the first n+10 integers.
### Explanation:
```
{.I.(":E.[:}.' '-.~":@i.@+&11)
i.@+&11 | Integers 0 to n+10
":@ | Format list to string
' '-.~ | Strip spaces
}. | Behead (remove leading 0)
[: | Cap (previous verbs executed in order, not as a fork)
":E. | Find matches to the string n (returns a boolean vector)
I. | Indexes of 1s
{. | Take only the first
```
Note that this is 0-indexed. Examples:
```
{.I.(":E.[:}.' '-.~":@i.@+&11) 1
0
{.I.(":E.[:}.' '-.~":@i.@+&11) 0
10
{.I.(":E.[:}.' '-.~":@i.@+&11) 333
55
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~42~~ 31 + 1 (-p) = 32 bytes
```
(join'',0..$_+10)=~/$_/;$_="@-"
```
[Try it online!](https://tio.run/##K0gtyjH9/18jKz8zT11dx0BPTyVe29BA07ZOXyVe31ol3lbJQVfp/38jS2ODf/kFJZn5ecX/dX1N9QwMDf7rFgAA "Perl 5 – Try It Online")
**Explanation**
```
(join'',0..$_+10) # concatenate all of the numbers from 0 to 10 over the input
=~/$_/; # skip the first 0, then find the input
$_="@-" # @- holds the index of the start of the last match
```
] |
[Question]
[
Inspired by [Golf me an ASCII Alphabet](https://codegolf.stackexchange.com/questions/80940/golf-me-an-ascii-alphabet), of which this challenge is (almost) a direct inverse.
---
### Task:
Take a string of ASCII-art text and output the content of the text as regular ASCII text.
---
### Input:
String of ASCII-art text.
Input will only contain instances of ASCII character `#`, spaces and 4 or 5 newlines (a trailing newline is optional). All lines have the same length. (That is, the last ASCII-art letter is padded with trailing spaces.) You can use some other printable ASCII character instead of `#` in the input if you wish.
The input will contain ASCII-art letters `A-Z` and ASCII-art spaces (a 5x5 block of whitespace). No punctuation. There is only one line of ASCII-art text (5 actual lines). There will be no trailing or leading ASCII-art spaces, nor will there be adjacent ASCII-art spaces.
Letter size is 5x5 characters. There is a 1x5 space between each letter. Space between words is a 5x5 block of whitespace (+ 1x5 space on each side, because it is just another letter). There will be no 1x5 space at the end or at the beginning, only between ASCII-art letters.
---
### Output:
String containing the text as ASCII characters `A-Z` + spaces. The output can be in lowercase also, if that is somehow easier for your solution. Mixed case is also allowed.
---
### The ASCII-art letters:
```
### #### ### #### ##### ##### ### # # ##### ##### # # # # #
# # # # # # # # # # # # # # # # # # ## ##
##### #### # # # #### #### # ## ##### # # ### # # # #
# # # # # # # # # # # # # # # # # # # # # #
# # #### ### #### ##### # ### # # ##### ### # # ##### # #
# # ### #### ### #### ### ##### # # # # # # # # # # #####
## # # # # # # # # # # # # # # # # # # # # # #
# # # # # #### # # #### ### # # # # # # # # # # #
# ## # # # # # # # # # # # # # ## ## # # # #
# # ### # ## # # # ### # ### # # # # # # #####
```
The space:
```
|
| A 5x5 square of spaces.
| (Padded with |s to make it appear in this post.)
|
|
```
---
### Examples:
Input:
```
# # ##### # # ### # # ### #### # ####
# # # # # # # # # # # # # # # #
##### #### # # # # # # # # # #### # # #
# # # # # # # ## ## # # # # # # #
# # ##### ##### ##### ### # # ### # # ##### ####
```
Output: `HELLO WORLD`
Input:
```
### ### ### ##### #####
# # # # # # #
##### ### # # #
# # # # # # #
# # ### ### ##### #####
```
Output: `ASCII`
Input:
```
#### #### ### ###
# # # # # # #
#### #### # # ##
# # # # # #
# # ### ###
```
Output: `PPCG`
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~405~~ ~~335~~ ~~234~~ ~~182~~ 171 bytes
```
lambda s,j=''.join:j(' QPVXU_O__FBLK_JMD_CSYZWIENH_AG___TR'[int(j(`ord(y)%2`for y in j(s.split('\n')[x][i:i+5]for x in range(5))),2)%13836%37]for i in range(0,len(s)/5,6))
```
[Try it online!](https://tio.run/nexus/python2#jVLJboMwEL3zFSMshK2itAkirZBy6N6m@74Q5FAlVEbURJBD8vU0FKdMCKnqw8ieeW/m@dlhb5DHwdfHKIDMinqm2YoSId2ImnB3@/z6xG84Pzm4vOD9qyN@@PD2/nJ@fH3G908554/3pifklEZ0mKQjOmdGZxgmKcxBSIho1somsZhScyBN5s18T7hiy/ELxKxApIH8HFOHMWZ1mNG29@yuYe/@1EVV37HisaQZ23asLmP5JF1MhJDquq4RACBAigXFHlQsUqBWiSkzpIxLCIFlB8QlmIX29ajympqOOzd0IBW3hiT/00CA/KEB@4DiRh9qeFiY6bVdn2katlfRUUTN12QTLFzDArCRqopODVwkdW1us1SC3hcRtQ1vt4L/Hawutep/5XDtd2Hf8m8 "Python 2 – TIO Nexus")
---
Finally shorter than JS
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~50 44~~ 42 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ỴZ;6/UOḂḅ7‘ị“¥ŒƲVĊ⁾|W£⁼³ƭÇuʋụzḢĖ0ḢẆẠØsĠỌỊ»
```
**[Try it online!](https://tio.run/##y0rNyan8///h7i1R1mb6of4PdzQ93NFq/qhhxsPd3Y8a5hxaenTSsU1hR7oeNe6rCT@0@FHjnkObj6093F56qvvh7qVVD3csOjLNAEg@3NX2cNeCwzOKjyx4uLvn4e6uQ7v///@vrq7OpaygoKCsoAwCCiC2ApQECSlAAUQNREQZQsKUKCvATEDSq4ysC4mNTkLFuaC2I5uMxQRlhF40lcrEuUFZQRmPG5DDAYnEGQ5o6hWAgQkA "Jelly – Try It Online")** (note the argument does not require the leading newline, but since leading and trailing newlines have no effect I included one to make the multiline string more human-readable)
Results are mixed case (as allowed by the OP in [a comment](https://codegolf.stackexchange.com/questions/115696/read-ascii-art-text/115798#comment282640_115696)).
### How?
Splits on new lines, transposes, and joins together sub-slices of (up to) six together to get the character representations and reverses each (equating the later base conversion for the final character of length 25 to all the others of length 30). Then maps `'#'` and `' '` to one and zero respectively using the fact that `'#'` has an odd ordinal while `' '` has an even one. Reads each as if it were a base seven number. Effectively takes modulo 81 of each (to yield 27 unique values for the 27 possible cases), and finally indexes into a "magic string" with the correct chars at the correct indexes (modulo indexing is used with a magic string of length 81 to save 2 bytes).
Here is the "magic string" I created along with a (case-insensitive) regex pattern it needed to match (I added "ed" to make it length 81):
```
' affectedly Azerbaijan rewaxed naganas jiujitsudankly pase UVB freqHaarlemcoacted'
'^ ..f...e.....z......a..r.w.x...n.g......iuj....d..kly.p.s...vb....qh.....m.o.ct.*'
```
As such it may be compressed, looking up eleven sub-slices as words in Jelly's dictionary (most of which use the leading space default):
```
' affectedly Azerbaijan rewaxed naganas jiujitsudankly pase UVB freqHaarlemcoacted'
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
```
which results in the Jelly compressed string, `“¥ŒƲVĊ⁾|W£⁼³ƭÇuʋụzḢĖ0ḢẆẠØsĠỌỊ»`
The rest of the code works as follows:
```
ỴZ;6/UOḂḅ7‘ị“...» - Main link: multi-line string, s e.g. HI as the #s and spaces
Ỵ - split on new lines ["# # #####","# # # ","##### # ","# # # ","# # #####"] (each is actually a list)
Z - transpose ["#####"," # "," # "," # ","#####"," ","# #","# #","#####","# #","# #"] (each is actually a list)
6/ - six-wise reduce by
; - concatenation ["##### # # # ##### ","# ## ####### ## #"] (each is actually a list)
U - upend (reverse each) [" ##### # # # #####","# ## ####### ## #"] (each is actually a list)
- note: all except the last will be length 30 and like " ...", which will become [0,0,0,0,0,...], while the last will be length 25 without those five leading zeros.
O - cast to ordinals ('#' -> 35, ' '-> 32) [[32,32,...],[35,32,...]]
Ḃ - modulo 2 ('#' -> 1, ' ' -> 0) [000001111100100001000010011111, 1000110001111111000110001] (each is actually a list)
ḅ7 - convert from base 7 (vectorises) [223498370543967315553, 191672428080864454753] (these are now integers)
‘ - increment [223498370543967315554, 191672428080864454754]
- (modulo 81 these would be [68, 41])
ị - index into (modulo & 1-indexed):
“...» - the "magic string" described above ' affectedly Azerbaijan rewaxed naganas jiujitsudankly pase UVB freqHaarlemcoacted'
"Hi" 41^ 68^
```
[Answer]
## JavaScript (ES6), ~~204~~ ~~186~~ ~~184~~ 182 bytes
*Saved 18 bytes thanks to Neil*
*Saved 2 bytes thanks to ETHproductions*
*Saved 2 bytes thanks to YairRand*
Breakdown:
* 42-byte lookup table
* ~~162~~ ~~144~~ ~~142~~ 140 bytes of code
```
s=>(a=s.split`
`)[0].replace(/.{6}/g,(_,n)=>' H_JM__WDCSORLU___QKG_P_AFT_N_EI_XBV____YZ'[[0,1,2,4].reduce((p,r,i)=>p+='0b'+a[r].substr(n,5).replace(/./g,c=>1^1-c)<<i*6,0)%178%69%43])
```
### Demo
```
let f =
s=>(a=s.split`
`)[0].replace(/.{6}/g,(_,n)=>' H_JM__WDCSORLU___QKG_P_AFT_N_EI_XBV____YZ'[[0,1,2,4].reduce((p,r,i)=>p+='0b'+a[r].substr(n,5).replace(/./g,c=>1^1-c)<<i*6,0)%178%69%43])
console.log(f(
' ### ### ### ##### ##### \n'+
'# # # # # # # \n'+
'##### ### # # # \n'+
'# # # # # # # \n'+
'# # ### ### ##### ##### \n'
));
```
[Answer]
## [Bash](https://www.gnu.org/software/bash/) + [ImageMagick](https://www.imagemagick.org) + [Tesseract](https://github.com/tesseract-ocr), 161 bytes
I wanted to try the approach suggested by @stewie-griffin and went for bash + ImageMagick (to convert a string to an image) and Tesseract (to do the OCR). Here's my code, which works for the 'HELLO WORLD' testcase, but fails the other ones. Maybe some tweaking to the parameters (font, font size, kerning, spacing) helps.
```
convert -font Courier-Bold -pointsize 8 -interline-spacing -3 -kerning -3 label:"$(</dev/stdin)" -bordercolor White -border 5%x20% png:- | tesseract stdin stdout
```
Just copy-paste the ascii art into the commandline after running the command. Finish your input by pressing ^d.
Current output for the test cases:
* HELLO WORLD: HELLO WORLD
* ASCII: H5511
* PPCG: PPOG
[Answer]
# Scala, 184 181 bytes
A magic string + modulo solution based on `hashCode` :)
```
(a:String)=>a.split("\n").map(_.grouped(6)map(_.take(5))toArray).transpose.map(l=>"Q__WLUY_XOI_ZN_GEFR_P__JKBMV_S__ __C__D__H_T__A"(Math.abs(l.mkString.hashCode)%106%79%47))mkString
```
[Try online (Scalafiddle)](https://scalafiddle.io/sf/XORzpU8/0)
More readable :
```
(a:String) => a.split("\n")
.map(_.grouped(6)map(_.take(5))toArray)
.transpose
.map ( l =>
"Q__WLUY_XOI_ZN_GEFR_P__JKBMV_S__ __C__D__H_T__A"(
Math.abs(l.mkString.hashCode)%106%79%47
)
)mkString
```
## Explanations
* The initial String (ASCII art) is split into 5 lines (height of ASCII character)
* Each line is split in 6-characters elements (width of ASCII character + 1 space)
* Only the first 5 characters are kept (the space at the end is useless)
* The lines are transposed (each ASCII character is represented as a sequence of 25 characters (5x5), containing either `'#'` or `' '`)
* Each ASCII character representation (sequence) is converted to String and an absolute hashcode is computed for that String (absolute needed because of next modulus)
* 3 consecutive modulus (`% 106 % 79 % 47`) are applied to associate a number ∈ `[0; 47[` for each ASCII character (see explanations below)
* This number is used as an index of the magic string
**How to get the magic string ?**
First, I represented all letters like this :
```
case class Letter(letter: Char, ascii: Seq[Char])
```
Then, I created an alphabet containing ASCII representations of all characters :
*Example :*
```
###
# #
#####
# #
# #
```
becomes
```
Letter('A', " ### # ####### ## #") // 25 characters from top-left to bottom-right
```
For each letter, an absolute hashcode was computed (all hashcodes are distinct) :
```
val codes = alphabet.map { case Letter(l, a) => (l, Math.abs(a.mkString.hashCode)) }
// codes: Seq[(Char, Int)] = List(( ,253243360), (A,380997542), (B,1221679148), (C,1573119535), (D,307929190), (E,858088672), (F,857996320), (G,750155628), (H,897290147), (I,1518088099), (J,928547488), (K,1184149391), (L,519601059), (M,741735953), (N,2139154001), (O,1625960980), (P,1307658950), (Q,92382816), (R,1221771494), (S,1689301359), (T,1515228067), (U,1390718627), (V,386730851), (W,733134481), (X,628338619), (Y,23919695), (Z,2081560145))
```
Then I tried to decrease each code, but always respecting the fact that each code must be unique (the list grouped by the code must have 27 elements, 1 for each letter). So I tried the first 200 modulus :
```
val mod = (1 to 200).find(modulo => codes.map { case (a,b) => (a, b % modulo) }.groupBy(_._2).size==27).get
```
I found `106` as the first modulo to be applied :
```
val codes2 = codes.map { case (l, c) => (l, c%mod) }
val codes = codes2
// codes: Seq[(Char, Int)] = List(( ,32), (A,46), (B,104), (C,35), (D,38), (E,16), (F,96), (G,94), (H,41), (I,89), (J,102), (K,71), (L,83), (M,105), (N,13), (O,56), (P,20), (Q,0), (R,18), (S,29), (T,43), (U,5), (V,27), (W,3), (X,87), (Y,53), (Z,91))
```
I repeated the previous steps until the smallest modulo. I found :
* 79
* 47
* 44
* 42
*Note :* The last modulo I chose (`47`) is not the smallest here :
* I found 44, but if I had chosen 44, the magic string would have size 44 (instead of 47) **but** I would have to write `%106%79%47%44` (13 characters instead of `%106%79%47` = 10 characters). So in bytes, the code should have had the same size as the one I got
* There is also 42, but then the code should have had 1 byte more than the one I got
Next, I applied the consecutive modulus (`% 79 % 47`) to the last `codes`, to get the definitive codes associated to each letter :
```
codes: Seq[(Char, Int)] = List(( ,32), (A,46), (B,25), (C,35), (D,38), (E,16), (F,17), (G,15), (H,41), (I,10), (J,23), (K,24), (L,4), (M,26), (N,13), (O,9), (P,20), (Q,0), (R,18), (S,29), (T,43), (U,5), (V,27), (W,3), (X,8), (Y,6), (Z,12))
```
Finally, to construct the magic string :
```
val initialMap = (0 until 47).map(i => (i, '_')).toMap
val codesMap = codes.map(i => (i._2, i._1)).toMap
val magicString = (initialMap ++ codesMap).toSeq.sortBy(_._1).map(_._2).mkString
// magicString: String "Q__WLUY_XOI_ZN_GEFR_P__JKBMV_S__ __C__D__H_T__A"
```
*Example :* The letter `A` above is associated to 46 (`380997542 % 106 % 79 % 47`), and the 46th element of the magic string is A :)
## Test cases
```
// assign function to f
val f = (a:String)=>a.split("\n").map(_.grouped(6)map(_.take(5))toArray).transpose.map(l=>"Q__WLUY_XOI_ZN_GEFR_P__JKBMV_S__ __C__D__H_T__A"(Math.abs(l.mkString.hashCode)%106%79%47))mkString
```
**HELLO WORLD :**
```
val asciiArt = """|# # ##### # # ### # # ### #### # ####
|# # # # # # # # # # # # # # # #
|##### #### # # # # # # # # # #### # # #
|# # # # # # # ## ## # # # # # # #
|# # ##### ##### ##### ### # # ### # # ##### #### """.stripMargin
f(asciiArt) // HELLO WORLD
```
**ASCII :**
```
val asciiArt = """| ### ### ### ##### #####
|# # # # # # #
|##### ### # # #
|# # # # # # #
|# # ### ### ##### #####""".stripMargin
f(asciiArt) // ASCII
```
**PPCG :**
```
val asciiArt = """|#### #### ### ###
|# # # # # # #
|#### #### # # ##
|# # # # # #
|# # ### ### """.stripMargin
f(asciiArt) // PPCG
```
## Edits
* Saved 3 bytes by removing `.` before `map`, `toArray` and `mkString`
[Answer]
# PHP, 294 Bytes
```
<?$l=" 00000YE00G0000R000A0Q0000C0BW000K00000000000LT00000J00000000MU0000Z0000DI000000V0000000P00H0000ONF000S00X";preg_match_all("#(.{5})\s#s","$_GET[0] ",$t);for($i=0;$i<$c=count($a=$t[1])/5;$i++)$s.=$l[bindec(strtr($a[$i].$a[$i+$c].$a[$i+2*$c].$a[$i+3*$c].$a[$i+4*$c]," #","01"))%106];echo$s;
```
[Try it online!](https://tio.run/nexus/php#jVXbbtswDH3XVxCiBtiLkSnr5SU1hl267r51666OETiOtwTInCB2n4p@eyrZUiPJclAhoRiKlI4OSeXs2Wax2bEspggACCgHSB2UlCZQo/VpLdhK7YJA1A5GLJpRhu5KZSfqdHNnzw64j3U88WEYEPAABpMHQ/by4PgDHRPCZjFVAYY0tusARRMqMY80qVOrxi9PrAGuc24DLtfg0HECz409fPRxdiC30HdVQP3RmempAjQQqgtqnKYX2uQ8HJtNJXaxOdXh5c3oGIc3cCxSb5Ix163XlxJwDjgg28rCgz52CTurHXaIv91sCqy0ohbYTT1RabMTgJ6SsHdrGlaH3AvitqGqIKs9tb@L0zrnvjMKkYwO9eC8btYFCHZfQwDV4J76Ip63Vb8af9fbIssXQcKyiM0ilkdsHrEizSo2vTi/Snga3hBWxVQ4F/liDXRSTkq9NimbK6xEc3M5fp9zfiGVr@L7nF9K9SV/8VNM7/l@fLhqpnf698fvUv6R4tXb1vRDLX3h/I2cP396LeQ3zn@JEzfb4t/0f1bni2m2WgUUg@HNyW04qbCiEdXggEasDsfyigFbxnzMlmfiHcrX12UdiL8fViejNHxyIuyDQUgAWDWM2SqZLct5kQdVva1FYJawZTpspgHLtfb08V4/MvRjqUfiqRM4@IiG4aMRP01b6lgluCLklux2dw "PHP – TIO Nexus")
Expanded
```
$l=" 00000YE00G0000R000A0Q0000C0BW000K00000000000LT00000J00000000MU0000Z0000DI000000V0000000P00H0000ONF000S00X"; # search string mod 106
preg_match_all("#(.{5})\s#s","$_GET[0] ",$t); # Regex take each group of five chars followed by a whitespace
for($i=0;$i<$c=count($a=$t[1])/5;$i++)
$s.=$l[bindec(strtr($a[$i].$a[$i+$c].$a[$i+2*$c].$a[$i+3*$c].$a[$i+4*$c]," #","01"))%106]; # join each groups make a binaray make a decimal mod 106
echo$s; # Output
```
## Converting the Input to an image format
[@Stevie Griffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin) search a solution to get this from an image.
I think he want **not really** the image format I have use.
```
echo'<svg xmlns="http://www.w3.org/2000/svg" width="100%"><switch><foreignObject x="0" y="0" width="100%" height="300"><body xmlns="http://www.w3.org/1999/xhtml"><pre>'.$_GET[0].'</pre></body></foreignObject></switch></svg>';
```
SVG can contains HTML parts if then included in a foreignObject.
So I put a pre Element in a SVG.
## Image Output
```
<svg xmlns="http://www.w3.org/2000/svg" width="100%"><switch><foreignObject x="0" y="0" width="100%" height="300"><body xmlns="http://www.w3.org/1999/xhtml"><pre># # ##### # # ### # # ### #### # ####
# # # # # # # # # # # # # # # #
##### #### # # # # # # # # # #### # # #
# # # # # # # ## ## # # # # # # #
# # ##### ##### ##### ### # # ### # # ##### #### </pre></body></foreignObject></switch></svg>
```
## Solving from Image Changes
SVG is machine readable so after saving the SVG as "i.svg" you need
only replace `$_GET[0]` with `preg_replace("#(^.*e>)(.*)(</p.*$)#s","$2",join(file("i.svg")))` in the way with normal input + 55 Bytes
[Answer]
# Powershell, ~~152~~ 146 bytes
```
-join$(for($t=$args-split'
';$c-lt$t[0].Length;$c+=6){$s=0;$t|% s*g $c,5|% t*y|%{$s+=$s+$_}
'_ISRJ_BK_HFQPL_MYNCE _TXDAO_VWUZ__G'[$s%578%174%36]})
```
Test script:
```
$f = {
-join$(for($t=$args-split'
';$c-lt$t[0].Length;$c+=6){$s=0;$t|% s*g $c,5|% t*y|%{$s+=$s+$_}
'_ISRJ_BK_HFQPL_MYNCE _TXDAO_VWUZ__G'[$s%578%174%36]})
}
&$f @"
# # ##### # # ### # # ### #### # ####
# # # # # # # # # # # # # # # #
##### #### # # # # # # # # # #### # # #
# # # # # # # ## ## # # # # # # #
# # ##### ##### ##### ### # # ### # # ##### ####
"@
&$f @"
### ### ### ##### #####
# # # # # # #
##### ### # # #
# # # # # # #
# # ### ### ##### #####
"@
&$f @"
#### #### ### ###
# # # # # # #
#### #### # # ##
# # # # # #
# # ### ###
"@
&$f @"
### #### ### #### ##### ##### ### # # ##### ##### # # # # # # # ### #### ### #### ### ##### # # # # # # # # # # #####
# # # # # # # # # # # # # # # # # # ## ## ## # # # # # # # # # # # # # # # # # # # # # #
##### #### # # # #### #### # ## ##### # # ### # # # # # # # # # #### # # #### ### # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # # # # # ## ## # # # #
# # #### ### #### ##### # ### # # ##### ### # # ##### # # # # ### # ## # # # ### # ### # # # # # # #####
"@
```
Output:
```
HELLO WORLD
ASCII
PPCG
ABCDEFGHIJKLMNOPQRSTUVWXYZ
```
Note:
1. `$t|% s*g $c,5|% t*y|%{$s+=$s+$_}` is shortcut for `$t.substring($c,5).toCharArray()|%{$s+=$s+$_}`
2. `("abcd","efgh").substring(1,2)` returns the array `("bc","de")`
3. `("bc","de").toCharArray()` returns the array `('b','c','d','e')`
[Answer]
# C, ~~225~~ 209 bytes
*Thanks to @ceilingcat for saving 16 bytes!*
```
i,j,k,l,n,m;f(char*s){l=index(s,10)-s+1;for(i=0;i<l/6;++i){for(m=j=0;j<5;m+=n*(exp10(j++)+.1))for(n=k=0;k<5;)n+=(s[i*6+j+k*l]==35)<<k++;for(j=0;"Qi Y$>W);Xa%d^F4K-]7jcMAG="[j++]-32-m%77;);putchar(n?64+j:32);}}
```
[Try it online!](https://tio.run/##jZBBS8NAEIXv/RVL1sJOJtGmaVNws4oXPYgHTyq1QkiauptkW5oqhdK/3pg1EUNRcQ6P4fHmm2FidxHHVSUd5WRO7min4CmLX6O1XcIuF1In8y0rHW8AbokeT5drJsWAyzA/CziihJ2xCqFqU4VjXqDQNptvV96AKUTAUw/ARLTI6khWR0CjYOVU2gEqzOx8JoQ/hjDMED/5BmXdS/J0cvEA/DHqJy/Xo1t3NlHx3dWNsKY1d@b6Q7foTyYc@OptYw5m@jIYoTr3h8D3@0rqDSkiqdn7Uiaw66XMooQQSqgpYnrSqrFIW02mcWijXxFKnnWL6AzT7linP9bWrxHN/i77BwT9Hj5K0n9eQQn964ruLzr66y@O8sQC3ttXhzjNo0VZuXnxAQ)
] |
[Question]
[
# Guidelines
## Scenario
John has an important number, and he doesn't want others to see it.
He decided to encrypt the number, using the following steps:
His number is always a non-decreasing sequence (ie. `"1123"`)
He converted each digit into English words. (ie. `"123" -> "ONETWOTHREE"`)
And then, rearrange the letters randomly. (ie. `"ONETWOTHREE" -> "ENOWTOHEETR"`)
John felt that his number were safe in doing so. In fact, such encryption can be easily decrypted :(
---
## Task
Given the encrypted string s, your task is to decrypt it and return the original number.
---
## Rules
* This is code golf, so the shortest answer in bytes wins
* You can assume that the input string is always valid
* The input string only contains uppercase letters
* The original numbers are always arranged in ascending order
* You may return the number in string or integer format
* The letters will only be shuffled between one word, not between the whole string.
* The numbers will only be from 1 to 9 inclusive (`ONE` to `NINE`)
---
## Possible Unscrambled String
Here is a list of the strings just after they have been converted to strings from the numbers:
```
1 -> ONE
2 -> TWO
3 -> THREE
4 -> FOUR
5 -> FIVE
6 -> SIX
7 -> SEVEN
8 -> EIGHT
9 -> NINE
```
---
## Examples
`"NEO" -> 1`
`"ENOWOT" -> 12`
`"EONOTWHTERE" -> 123`
`"SNVEEGHEITNEIN" -> 789`
`"ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN" -> 123456789`
`"NOEWOTTOWHEERT" -> 1223`
[Answer]
# Python 2, ~~121~~ ~~117~~ 115 bytes
```
def g(s,a=0,f=''):
for c in s:
a+=34**ord(c)%43;r='P!\x83u\x8eI\x92|Z'.find(chr(a))+1
if r:f,a=f+`r`,0
return f
```
-4 bytes: After all that golfing I forgot to inline a single-use variable. Brain fart.
-2 bytes: Double-spaced indent → single tab indent (thanks to Coty Johnathan Saxman); note that this does not display correctly in the answer.
## Ungolfed (compatible with python 3):
```
nums = [80, 33, 131, 117, 142, 73, 146, 124, 90]
def decode(str):
acc = 0
final = ''
for c in str:
acc += (34**ord(c))%43
if acc in nums:
final += str(1+nums.index(acc))
acc=0
return final
```
## Magic number finder:
```
#!/usr/bin/env python3
from itertools import count, permutations
def cumul(x):
s = 0
for v in x:
s += v
yield s
all_words = 'ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split()
for modulo in range(1, 1000):
for power in range(1, 300):
combinations = []
for word in all_words:
my_combination = []
for perm in permutations(word):
my_combination += cumul(power**(ord(x)) % modulo for x in perm)
combinations.append(my_combination)
past_combinations = set(())
past_intermediates = set(())
collision = False
for combination in combinations:
final = combination[-1]
if final in past_intermediates or any(intermediate in past_combinations for intermediate in combination):
collision = True
break
past_combinations.add(final)
past_intermediates.update(combination)
if not collision:
print("Good params:", power, modulo)
print("Results:", ", ".join(str(x[-1]) for x in combinations))
```
## Explanation:
I had a feeling that I could smash the ASCII bits together and sum them up somehow to determine when I had a full word. Originally I tried messing with `3**ord(letter)` and comparing to expected results, but it resulted in some very large numbers. I though it would be appropriate to brute-force some parameters a little, namely modulus (to ensure the numbers are small) and a multiplier to disperse the numbers differently around the range of the modulus.
I ended up changing the multiplier variable into a variable affecting the power itself because (from trial and error) that somehow managed to give me a slightly shorter golfed answer.
And above you see the results of that brute-forcing and a little manual golfing.
The reason for choosing `3**x` originally is because I knew you could represent every number there. The most repeated digits any number had is two (thrEE, sEvEn, NiNe, etc), so I decided to think of every input as a base-3 number. That way I could (mentally) represent them as something like `10100000000010020000` (three; a 1 in the `t` slot, a 1 in the `r` slot, a 1 in the `h` slot, and a 2 in the `e` slot). Each number this way gets a unique representation which can be easily pieced together by iterating the string and summing some numbers, and it ends up independent of the actual order of the letters. Of course, this didn't turn out to be the ideal solution, but the current solution is still written with this idea in mind.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḟ“RGS”O“OX‘,“¢©“¢¢¤‘yF×4/%74ị⁽Gל?9¤Ḍ
```
A monadic link taking a list of characters (the string) and returning an integer.
**[Try it online!](https://tio.run/##y0rNyan8///hjvmPGuYEuQc/apjrD2T5RzxqmKEDZBxadGglhFp0aAlQrNLt8HQTfVVzk4e7ux817nU/PP3oZHvLQ0se7uj5//@/q5@/f3iIq2uQR0hQqL@ba5inW4RnsJ9rmGtwiIe7p6urn6cfAA "Jelly – Try It Online")**
Uses a **very different** method to [Pietu1998's Jelly answer](https://codegolf.stackexchange.com/a/131858/53748), ~~yet has the same byte count~~ (~~I really thought it might~~ *it did* end up as less)!
Does not rely on the monotonicity of the original number (so an input of `HTREEWTONOE` would work for example).
### How?
First note that the words themselves (and therefore any anagrams thereof) can all be changed to ones of length 4 by removing any Rs, Gs and Ss and replacing any Os with two characters (say "12") and any Xs with three characters (say "345").
```
letters -> -RGS -> O:12, X:345
ONE ONE 12NE
TWO TWO TW12
THREE THEE THEE
FOUR FOU F12U
FIVE FIVE FIVE
SIX IX I345
SEVEN EVEN EVEN
EIGHT EIHT EIHT
NINE NINE NINE
```
We may then map the product of the ordinals of those characters to the numbers 1 to 9 using modulo arithmetic, depending upon our choice (the "12345"), then look these up in a reordered list of the digits. The code actually casts to characters first and then replaces the ordinals, but it is also possible in 37 bytes with characters, e.g. "DIAAE" ([try it](https://tio.run/##y0rNyan8///hjvmPGuYEuQc/apgLZPhHAGkdIMPFE0g4OroCuZVu/oenm@irmps83N39qHGv@@HpRyfbWx5a8nBHz////139/P3DQ1xdgzxCgkL93VzDPN0iPIP9XMNcg0M83D1dXf08/QA)).
```
ḟ“RGS”O“OX‘,“¢©“¢¢¤‘yF×4/%74ị⁽Gל?9¤Ḍ - link: list of characters
“RGS” - literal ['R','G','S']
ḟ - filter discard
O - convert to ordinals
“OX‘ - code-page indices list = [79,88]
“¢©“¢¢¤‘ - code-page indices lists = [[1,6],[1,1,3]]
, - pair -> [[79,88],[[1,6],[1,1,3]]]
y - translate (replace 79s (Os) with [1,6]
and 88s (Xs) with [1,1,3])
F - flatten into a single list
4/ - 4-wise reduce by:
× - multiplication (product of each window of four)
%74 - modulo 74
¤ - nilad followed by link(s) as a nilad:
⁽G× - base 250 literal = 18768
œ?9 - permutation of [1,2,3,4,5,6,7,8,9] at that
- index in a lexicographically sorted list of
- all such permutations -> [1,5,8,2,4,9,7,6,3]
ị - index into
Ḍ - convert from decimal digits to an integer
```
---
### Another 37
```
42BĖZ“Øȧɲ“Pt’żḥ€⁸*/)⁸xO×⁵/%⁽R1%⁽©v%⁵Ḍ
```
[Try it online!](https://tio.run/##y0rNyan8/9/EyOnItKhHDXMOzzix/OQmICOg5FHDzKN7Hu5Y@qhpzaPGHVr6mkCywv/w9EeNW/VVHzXuDTIEkYdWlgGprQ939Pz//9/Vz98/PMTVNcgjJCjU3801zNMtwjPYzzXMNTjEw93T1dXP0w8A "Jelly – Try It Online")
This one repeats characters such that any\* shuffled number name becomes length ten:
| characters | repeat |
| --- | --- |
| G R S T U V | 1 |
| H N | 2 |
| E F I | 3 |
| W | 4 |
| O | 5 |
| X | 6 |
e.g:
```
ONE => OOOOONNEEE
TWO => TWWWWOOOOO
THREE => THHREEEEEE
OURF => OOOOOURFFF
EVIF => EEEVIIIFFF
IXS => IIIXXXXXXS
VENES => VEEENNEEES
GHIET => GHHIIIEEET
NINE => NNIIINNEEE
WOTISX => WWWWOOOOOTIIISXXXXXX
```
Then takes the products of the ordinals of length ten slices and performs a modulo chain to map these to \$[1,9]\$ appropriately.
\* The repetition part works for "ZERO" too -> "ZEEEROOOOO" as 'Z' will also repeat once.
[Answer]
# [Python 2](https://docs.python.org/2/),~~131~~ 127 bytes
```
s=input()
for y in'WXGURFSOIZ':vars()[y]=s.count(y)
while Z<9:s+=[O-U-W,W,R-U,U,F-U,X,S-X,G,I-X-G-F+U][Z]*str(Z+1);Z+=1
print s
```
[Try it online!](https://tio.run/##DcTNCoMgAADge0/hTZ06aLf9eKzWZUIlitFhjI2EYaG24dO7fYdvTXFe3CHnwK1bt4hw8Vo8SMA6qHQju7oXrYGnz90HhMc08bB/LJuLKOHiO9v3E5jL8RQIHwWTTFFFOyappPV/TXumaUNbplnDaiKn0Uy7ED0ypMRnQ3hZrN66CELO8CYqJYZBqGtVdQP8AQ "Python 2 – Try It Online")
Based on a corrected version of the JavaScript [Draco18s](https://codegolf.stackexchange.com/users/47990/draco18s) solution.
[Answer]
# [PHP](https://php.net/), 164 bytes
```
for($c=count_chars($argn);$i<9;)echo str_pad("",[$c[79]-$c[87]-$u=$c[85],$c[87],$c[72]-$g=$c[71],$u,$f=$c[70]-$u,$x=$c[88],$c[86]-$f,$g,$c[73]-$x-$f-$g][+$i],++$i);
```
[Try it online!](https://tio.run/##JVBNa@NADL33V5TgQ0JdaHfZTYsb9rBIHl0kkDVjQwghuPm6xMZNoKf@9VROL6PRG72n96Y/9Ne3f/2hv9sOQzesh23fDefjaT/9gjWL0X@YFXfZZtifFhOsgRDQag1JIIkIo1ICCIRUJX@KUSqIhokbkURMBMGEpQYBMFRjwlihQ7FiTQoWSKEJahYMGQBirGsB1sglSkBgFgUiDWQIRq4FJmFcI4GjamJpQrTEoIAQWQ1GZyCV2yTXK8UhCsDoBh1gISmBylgzKbmPGtBlEX1tBWyiWrtY2QSfbpDMlcTjCrthC@Bb0OfGRJXnaqqQlFUslEwM0TP7SzBzDxBiBZPiuuuGadYu2u5yOq/bw2b4mN5@dFZkx7fXYrZtD939x3lY95v36WSSL7N2OX9dPXp5mXu5LMbbn1X@A4xl/svx/YjPnx245Nnu1jyN43n2eWO8/DD@OrbLs/2N99ubT@@dvVo@ZMdV/uDnrLhevwE "PHP – Try It Online")
# [PHP](https://php.net/), 179 bytes
based on the previous approach check first the even numbers and then the odd numbers in increasing order
```
for($z=[$o=($c=count_chars($argn))[87],$f=$c[85],$x=$c[88],$g=$c[71],$c[79]-$o-$f,$c[72]-$g,$v=$c[70]-$f,$c[86]-$v,$c[73]-$x-$v-$g];$i<9;)echo str_repeat(++$i,$z[_405162738[$i]]);
```
[Try it online!](https://tio.run/##LY9LC8IwEITv/gqRPSRYQeujkRg8SAUvFkTxEEIooa9LE2It4sG/XtcgzLLfLDOHdbUbdntXu1HhvfXaF876rmkr8kn1ObueDinlI8h91YpJdk5R13uGOma3y28mfCitJ/AWEqwgYISxz7bTps79g4QipZIlKoJSgJFsjfQKxJCqHyULJFxbNQM7gzKYGE0VQR8Cc/U/sw1SHwJLpBcajCkOzW7LaWFqO3504Y0i78h0Ck0Eb6lX8/ViEydLJqFRivJh@AI "PHP – Try It Online")
# [PHP](https://php.net/), 201 bytes
```
for(;$o=ord(WUXGOHFVN[$i]);$i++)for(;$r[$o]<count_chars($argn)[$o];$t[]=$i>3?2*$i-7:2+2*$i,sort($t))for(++$r[$o],$n=0;$q=ord(([TO,ORF,IS,HEIT,EN,TREE,IVE,SEEN,NIE][+$i])[$n++]);)$r[$q]++;echo join($t);
```
[Try it online!](https://tio.run/##JY4xa8MwEIX3/IoSbpAqFUo6FKq4Gcol0SJD7LoFIUxwnFgdJOfirv3rruVs797B976@68f1pu/6RUsUqaa2jzT4cGF/WJu81B/I1QKOdAnZsjAV4m6PujSozVKN50hMQcwindjX5/cu328rY8E7rsALwe9/shDduom/Yaib7kg3NvN4qhUM1mXg3182q0fwT69vK5GCvE0aDAY@M4S4QySE7FnBdR5ktsxlfthKXcjkJNHI8oAodYWywOkyGp0VScdCEGKy4olzdUKotuniw0/0IY2ocfwH "PHP – Try It Online")
[Answer]
# Javascript (ES6), ~~288~~ ~~150~~ 144 bytes
```
q=s=>[u=(l=t=>s.split(t).length-1)`U`,l`O`-l`W`-u,l`W`,l`R`-w,u,f=l`F`-u,x=l`X`,l`S`-x,g=l`G`,l`I`-x-g-f].map((n,i)=>`${i}`.repeat(i&&n)).join``
const testCases = ['NEO', 'ENOWOT', 'EONOTWHTERE', 'SNVEEGHEITNEIN', 'ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN']
testCases.forEach(testCase => console.log(testCase, q(testCase)))
```
Longer than ~~the other two~~ one of the other JS entries, but I thought I'd drop an interesting approach that might work for someone in another language.
Essentially we can determine the following:
```
W -> 2
X -> 6
G -> 8
U -> 4
```
Any occurrence of these letters implies that that digit exists in the original number. From here we can deduce the rest of the digits:
```
R-U -> 3
F-U -> 5
S-X -> 7
```
Including the two complicated cases:
```
O-(U+W) -> 1
I-(X+G+(F-U)) -> 9
```
Both `1` and `9` area Hard comparatively. For ONE, `E` shows up more than once in some words (`SEVEN` has two) as does `N` (`NINE`), so we're stuck with checking for `O` which occurs in two other places, fortunately both are simple.
For NINE, nine is hard no matter how you slice it.
Thus we end up with this map:
```
[u=(l=t=>s.split(t).length-1)`U`, //unused 0; precompute 'U's
l`O`-l`W`-u, //1
l`W`, //2
l`R`-w, //3
u, //4
f=l`F`-u, //5
x=l`X`, //6
l`S`-x, //7
g=l`G`, //8
l`I`-x-g-f] //9
```
9 is able to back-reference siX, eiGht, and Five (with 5 back-referencing foUr) with the variable assignments, saving bytes. Thanks to Neil for this, it uses several features of JS I am very unfamiliar with (the back-ticks for stripping `('` in half, for instance) and actually comes much closer to the idea I'd doodled out on paper before attempting to code it (I'd left 9 as "what's left over", thinking about it as "if I see an `X` I can remove it and an `S` and `I` from the string, then..." so that after the four simple cases the next 3 would *become* simple).
The reason this entry is *interesting* is because it can handle *any shuffled string* as input. i.e. rather than the individual words being shuffled, we can shuffle the whole string, which is what I thought John was doing originally:
```
q=s=>[u=(l=t=>s.split(t).length-1)`U`,l`O`-l`W`-u,l`W`,l`R`-w,u,f=l`F`-u,x=l`X`,l`S`-x,g=l`G`,l`I`-x-g-f].map((n,i)=>`${i}`.repeat(i&&n)).join``
const testCases = ['XENSENINEVSI']
testCases.forEach(testCase => console.log(testCase, q(testCase)))
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 234 bytes
```
string q(string s){string[]n="ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".Split(',');var r="";int x=0,i=0,j;try{for(;;)for (j=x;;)if(n[i].IndexOf(s[j])>=0){if(++j==n[i].Length+x){r+=i+1;x=j;break;}}else{i++;break;}}catch{}return r;}
```
[Try it online!](https://tio.run/##hVGxTsMwFNz5CisLtmIqmC2zoNfGEthSYppKVYeQuuAQHLBdFBTl20uAio0yPL3T3b0b7tXhou68OeyDdY@o@AjRvLCzEKtoa1S3VQjoptuaRdfuzoYjfwjRf7nf8BEEMvyg9cbxREmgulRUZzkAnav7nM7FEmghVrSAJUgKYpFpKoWEZFa8tjbic3pO2HvlkedJwqyLqOeX1E7TsOg/hl3nMWNkWgg3vJ@g3WG3tpuZcFvTqx0O62ZDrvklGSYlTRvOv@Vb4x7jU9qTwafcples5w178KZ6ZuNo2mAGm6a/RF3F@mkYvYl775Bn4@F1/9BOTRwLee/sFt1V1mEytYGmalzoWjMrvY3m1jqD33AiQSWEsL9kkKpU@pRDKpAg5MkQJZUuMw05nLIVcgmwyEDofwOlUqUGyDOd36s5LMV8JQo5vavQ2UIAyOP9OB4@AQ "C# (.NET Core) – Try It Online")
Expanded version:
```
static string q(string s)
{
string[] n = "ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".Split(',');
var r = "";
int x = 0, i = 0, j = 0;
try
{
for(;;)
for (j = x; ;)
if (n[i].IndexOf(s[j]) >= 0)
{
if (++j == n[i].Length + x)
{
r += i + 1; x = j;
break;
}
}
else
{
i++;
break;
}
}
catch { }
return r;
}
```
Being my first entry, I'm uncertain about the rules... I'm only counting the size of the class used to de-crypt, not the code that tests it, right?
**Edit**
And for the fun of it - here's what I started doing, not reading the complete rules :S - [See it at IdeOne](http://ideone.com/upgxwt). It de-crypts even when characters from one digit can be scrambled to any place in the string.
**Edit 2**
Shortened according to tips by TheLethalCoder. Thanks!
**Edit 3**
And now Titus shaved of a few more bytes. Thanks!
**Edit 4** Six years later :D
As [Magic Octopus Urn](https://codegolf.stackexchange.com/users/59376/magic-octopus-urn) commented, this wasn't working in all cases. Had to add a few bytes to make it work :(
Using try/catch I can ignore boundary checks and save a few bytes :P
[Answer]
# Mathematica, 133 bytes
```
(s={};c=Characters;j=c@#;Table[If[FreeQ[j~Count~#&/@c[#[[i]]]&@ToUpperCase@IntegerName@Range@9,0],s~AppendTo~i],{i,9}];FromDigits@s)&
```
**input**
>
> "VENESGTHIEENNI"
>
>
>
**output**
>
> 789
>
>
>
[Answer]
# [Retina](https://github.com/m-ender/retina), 88 bytes
```
[EFIST]
^(ON|NO)*
$#1$*1
O
W
2
HR|RH
3
UR|RU
4
X
6
GH|HG
8
(NN)*$
$#1$*9
r`NV|VN
7
V
5
```
[Try it online!](https://tio.run/##JYy9bsJAEIT7eY04knEHJPw8wPj2ml3pbn1GQiBTpEhDgVL63c1Bmhlpvpl5/Pz93m/LZxum5cw@Zr8A19Z0Vlt1aD7WTbeGASM2kDQnwRZD9QFfOGGHILMEHNCqrrrmf3DEY9IyF8UeBd/LojRQbTQHTc1HcSYiayGDMLoy6qtho5NJPA3Ws8T@FLOyMLuESGotuSQy10zx1jdGJXx9aKx5b0NiDOJP "Retina – Try It Online")
**Explanation**
* First, drop a bunch of unnecessary characters not needed for distinctness
* Pick the 1s off the front (this lets us drop the rest of the Os immediately after and clears up some Ns before we get to the 5, 7, 9 mess)
* 2, 3, 4, 6, and 8 are now trivial
* 9s are a double NN, so grab those off the end before we deal with 5 and 7
* Replace 7s from the right (so we don't reduce VNV to 75 instead of 57)
* 5s are the remaining Vs
[Answer]
# JavaScript (ES6), ~~142~~ 139 Bytes
Saved 3 Bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil).
Doesn't currently take advantage of numbers are always arranged in ascending order
```
f=s=>s?'ENO|OTW|EEHRT|FORU|EFIV|ISX|EENSV|EGHIT|EINN'.split`|`.findIndex(w=>[...s.slice(0,y=w.length)].sort().join``==w)+1+f(s.slice(y)):''
```
```
f=s=>s?'ENO|OTW|EEHRT|FORU|EFIV|ISX|EENSV|EGHIT|EINN'.split`|`.findIndex(w=>[...s.slice(0,y=w.length)].sort().join``==w)+1+f(s.slice(y)):''
const testCases = ['NEO', 'ENOWOT', 'EONOTWHTERE', 'SNVEEGHEITNEIN', 'ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN']
testCases.forEach(testCase => console.log(testCase, f(testCase)))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes
```
Dị“©ȯ¿w¶&ÇhṆỌƘ#Ȯʋ~¢CNẓ_»Ḳ¤FṢŒu
L3*Ç€iṢ
```
[Try it online!](https://tio.run/##AVcAqP9qZWxsef//ROG7i@KAnMKpyK/Cv3fCtibDh2jhuYbhu4zGmCPIrsqLfsKiQ07hupNfwrvhuLLCpEbhuaLFknUKTDMqw4figqxp4bmi////Ik9ORVRXTyI "Jelly – Try It Online")
### Explanation
```
L3*Ç€iṢ Main link. Argument: s (string)
L Get length of s.
3* Raise 3 to that power. This will always be greater than n.
Ç€ Get the name of each of the numbers using the helper link.
iṢ Find the position of the sorted input.
Dị“©ȯ¿w¶&ÇhṆỌƘ#Ȯʋ~¢CNẓ_»Ḳ¤FṢŒu Helper link. Argument: n (number)
D Get digits of n.
“©ȯ¿w¶&ÇhṆỌƘ#Ȯʋ~¢CNẓ_» The string "one two (...) eight nine AA".
Ḳ Split that string at spaces.
ị Get name of each digit in the list.
F Flatten to a single string.
Ṣ Sort the characters.
Œu Make uppercase.
```
[Answer]
# Javascript (ES6), 221 bytes
```
s=>(m=btoa`8Ñ>Mc¾LtDáNQ!Q>HþHA7átþ4Ò`.split`+`.map(s=>RegExp(s.replace(/(.)\1*/g,c=>`(?=(.*${c[0]}){${c.length}})`))),t=0,r=0,[...s].map(c=>(t+=c,d=1,n=0,m.map((r,i)=>t.match(r)&&(d--,n=i)),d||(r=r*10+n+1,t=0))),r)
```
Example code snippet:
```
f=
s=>(m=btoa`8Ñ>Mc¾LtDáNQ
!Q>H
þHA7átþ4Ò`.split`+`.map(s=>RegExp(s.replace(/(.)\1*/g,c=>`(?=(.*${c[0]}){${c.length}})`))),t=0,r=0,[...s].map(c=>(t+=c,d=1,n=0,m.map((r,i)=>t.match(r)&&(d--,n=i)),d||(r=r*10+n+1,t=0))),r)
console.log(f("NEO"))
console.log(f("ENOWOT"))
console.log(f("EONOTWHTERE"))
console.log(f("SNVEEGHEITNEIN"))
console.log(f("ENOOWTEERHTRUOFEVIFXISNEVESTHGIEENIN"))
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 160 bytes
```
([ONE]{3})*([TWO]{3})*([THRE]{5})*([FOUR]{4})*([FIVE]{4})*([SIX]{3})*([SEVN]{5})*([EIGHT]{5})*([NIE]{4})*
$#1$*1$#2$*2$#3$*3$#4$*4$#5$*5$#6$*6$#7$*7$#8$*8$#9$*9
```
[Try it online!](https://tio.run/##Pcq7bsJAEIXh3q8xU8B0YJvLAxx7p5mRdoc1EqKgSJEmRZQO5dmdC5juP0ff59vX@8dtnlcXN1zv7fdaVpeY/JUp/979fw9@ytd792itWLroeeEF1RYOHVMsw/TJG6YNy4Zpy7Jlallapo6lY@pZeqYdy45pz7JnOrAcmI4sx3k2eAPzyaOBm8eUAhlNsQqMCRoGtT/hUwA5RT75gKrDWYuhokQaFTC1Hw "Retina – Try It Online") Loosely based on @TessellatingHeckler's PowerShell answer.
[Answer]
# [Perl 5](https://www.perl.org/), 102 + 1 (-n) = 103 bytes
```
for$i(map{"[$_]{".length.'}'}ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE){$,++;print$,while(s/^$i//)}
```
[Try it online!](https://tio.run/##Dcy7CoMwFADQf5GAitdHB6fOV83QBJL4gNKWDrYGbAwqdBB/vannA47t5zF37jXNRAefp928K3ncNi8Ze/Neh8Tf/Z0zBNVyUJVAhILXAgraIEjagcQGGSAtKwWMMgw3AlF0trM2K4HvoMc@WNI70Wka7s4h47xViKJSouYFNrToqGRHIlVVUsTj@E121ZNZXHzJk@yUudj8AQ "Perl 5 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 182 bytes
```
[regex]::Replace("$args",'(?<1>[ONE]{3z2>[TWO]{3z3>[THRE]{5z4>[FOUR]{4z5>[FIVE]{4z6>[SIX]{3z7>[SVEN]{5z8>[EIGHT]{5z9>[NIE]{4})'.replace('z','})|(?<'),{$args.groups.captures[1].name})
```
[Try it online!](https://tio.run/##Lc5PC4IwGMfx9yLBHIhgan8k1mnpLhPULBg7iAw7WMpMCs3Xvrbo9uHhC7@n715CDjfRtkoxKRrx5lGUib6tamFbq0o2g@UA@3jwEEsp5rM/rRErLqmRr5Vk@hhOAWKn9JzxOZhCTVJiww1iObmadKtVYmrSHWKYxElhvEeMEpMuELjyPwsm4IAFfvQqgM78e8JtZDf2g1tX/XOUYmAedx/VXSxQKZXTEuM4waSgmNAv "PowerShell – Try It Online")
Ungolfed but not working code:
```
[System.Text.RegularExpressions.Regex]::Replace("$args",
'(?<1>[ONE]{3})
|(?<2>[TWO]{3})
|(?<3>[THRE]{5})
|(?<4>[FOUR]{4})
|(?<5>[FIVE]{4})
|(?<6>[SIX]{3})
|(?<7>[SVEN]{5})
|(?<8>[EIGHT]{5})
|(?<9>[NIE]{4})'
,{$args.groups.captures[1].name}
)
```
e.g. `(?<3>[THRE]{5})` matches the character class `THRE`, so it can match them out of order, and has to match any of these characters five times next to each other, and the capture group is named '3' to map names with numbers.
Rudimentary compression by swapping the repeating text `})|(?<` for a `z`.
[Answer]
## C++, ~~296~~, 288 bytes
Short Version:
```
#define T string
using namespace std;T N[]={"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};T Q(T S){T R="";for(int i=0;i<9;i++){do{if(S.find(N[i])!=T::npos){S.erase(S.find(N[i]),N[i].size());R+=to_string(i+1);}}while(next_permutation(N[i].begin(),N[i].end()));}return R;}
```
Full Version:
```
#define T string
using namespace std;
T N[]={"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};
T Q(T S)
{
T R="";
for(int i=0;i<9;i++) //for all possible
//codewords (ONE,TWO...NINE)
{
do
{
if(S.find(N[i])!=T::npos) //if found in encrypted word
{
S.erase(S.find(N[i]),N[i].size()); //erase it from the word
R+=to_string(i+1); //save integer to the result string
}
//check next permuation of codeword
} while(next_permutation(N[i].begin(),N[i].end()));
}
return R;
}
```
[Try ONLINE!](https://tio.run/##VVFNb4MwDD0nvyJjFxBdtR1XoLds5QIaZO2kqaoYpF2kNkEhaB9Vf3tnw6StSvSMzcuTn1237c2urs/XStf7vpEsVqZzVlaHOf2rVfudscq9XxSBpvRufr5u5FZpyQQbK7TvAJmuDrJrq1pCuYmoYNnrOjl6eca9iSdWOeKi4Jg95M8FhnSJWZm@IPIlzyDy9HEhIGYpPDxFFISefMHKgB4pEaxIPC@iZGusr7RjKrmNVHwfqTAMKAEGaQzAkQAQtfXLKbTa@NmrWgdXiZjNdGu6AH8il5ByKm3VyQveBHHaqW/pB0E00IowcWYz2vVVeDeWTwCnj3e1l76Wn27TSnvoXeWU0YPS9E3ulPZ/BSXoB4MgvKPEStdbzYqIns7o5FAhFU2CNzaaYwm7jSDE7B7CYJF0xrpLdfZPHuZFxjZZx3Vtv1onG5DxMp7jROEA5rgAnD58LvlD@pKWcCER@UpwXiyGJfASN4KKtekdi2NYxJ9ogI3/AA)
**Edit:**
1) 200->296 bytes, for including namespace and definition of N in the count, as suggested by orlp
2) 296->288, for using macro, thanks to Zacharý
[Answer]
# Ruby, ~~138~~ ~~114~~ 110 bytes
```
gsub(/#{"3ONE3TWO5THRE4FOUR4FIVE3SIX5SEVN5EIGHT4NIE".gsub(/(.)(\D+)/,'([\2]{\1})|')}/){(1..9).find{|i|$~[i]}}
```
Byte count includes 1 byte for the `-p` option.
### What?
This:
```
/#{"3ONE3TWO5THRE4FOUR4FIVE3SIX5SEVN5EIGHT4NIE".gsub(/(.)(\D+)/,'([\2]{\1})|')}/
```
is a regex literal which, through string interpolation, evaluates to:
```
/([ONE]{3})|([TWO]{3})|([THRE]{5})|([FOUR]{4})|([FIVE]{4})|([SIX]{3})|([SEVN]{5})|([EIGHT]{5})|([NIE]{4})|/
```
If we assign that to `regex`, the rest of the code is somewhat easy to grasp: Each match in the input is substituted with the number of the capturing group, extracted from the magical variable `$~` which contains the current match data:
```
gsub(regex){(1..9).find{|i|$~[i]}}
```
[Try it online!](https://tio.run/##JcyxTsMwFEbhPY9RkGqr4KgkGdj7J/Zyr2TfxpWaLhUqytJWlA4oCY@OCWL/zvm4H79Ser/djyp/GBYFEwqJXIn1KGve@rJ2LYrgdlVASxVcY6Ukh4X5j5TRqtusdP60VPvu5TB060mPSz3lelBrY161OfXnt2Hsx8fvfX@YppQInIE4smRgYolW4JEFaoHGwgnB0Z/gKIC34rdco3X1zgVCiyC2cQDNiBjzRmYY2c5Wfi7Xz/5yvqXn6y8 "Ruby – Try It Online")
[Answer]
# Java 8, ~~198~~ 256 bytes
```
s->{String r="",x=r;for(String n:"ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE".split(" ")){for(char c:n.toCharArray())x+="(?=.*"+c+")";x+="["+n+"]{"+n.length()+"}x";}for(int i=0,q;i<9;)for(q=(s+" ").split(x.split("x")[i++]).length-1;q-->0;)r+=i;return r;}
```
+58 bytes.. due to regex of the previous version not working properly (it was also matching "EEE";"EEN";etc.)
**Explanation:**
[Try it here.](https://tio.run/##jZHBTuMwEIbvPMXIpxiTiD0uJqDVatrksLaUmAap6iGEAGZTp3VcCKry7MWB9EwlW54Zz/zj@fxavpVhu6nN6@P/Q9WUXQf/Sm32ZwDauNo@lVUNYnQBcme1eYYqmIyOch8f/PZLgIEYDl14s5@ubUzIRR9b/tTaY4m5IlIgqEKCSjJEmMm7DGbpAiFP7yHHBQrAdJ4oEKlAEnWbRruAAKF0P@pUL6WF6spErv3rzT/Wlh8BpT2LSXAbR@eEVYxQwsfAkjDDyGrvj6ipzbN7CSgjQ0/4MEr5@UDHlxdbrq9/czqGtnHQsbHZ1Lc/9u8JXWrGVnQSCn/xbRjeXHJqWay5rd3OGrB8OPBvHJvdQ6Mr6Fzp/PHW6kdYe64Th@UKSvoNdaQNa4/O1O9fTvBF1dP@6Fy9jtqdiza@xjUmWEcmqgIiUHocP2WhkIVUpyRKIVWRKMzwhOxcLBDnCaZKYCpOe4csFGKWqOxOznCRzu7TXPifzlUyTxHFSTJCoh9HySLxUsexhrPh8Ak)
```
s->{ // Method with String as parameter and return-type
String r="", // Result-String
x=r; // Regex-String
for(String n:"ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE".split(" ")){
// Loop (1) from "ONE" through "NINE":
for(char c:n.toCharArray())
// Inner loop (2) over the characters of this String
x+="(?=.*"+c+")"; // Append regex-group `(?=\w*c)` where `c` is the capital character
// End of inner loop (2) (implicit / single-line body)
x+="["+n+"]{"+n.length()+"}x";
// Append regex part `[s]{n}` where `s` is the String, and `n` is the length
} // End of loop (1)
// The regex now looks like this, which we can split on "x":
// (?=.*O)(?=.*N)(?=.*E)[ONE]{3}x(?=.*T)(?=.*W)(?=.*O)[TWO]{3}x(?=.*T)(?=.*H)(?=.*R)(?=.*E)(?=.*E)[THREE]{5}x(?=.*F)(?=.*O)(?=.*U)(?=.*R)[FOUR]{4}x(?=.*F)(?=.*I)(?=.*V)(?=.*E)[FIVE]{4}x(?=.*S)(?=.*I)(?=.*X)[SIX]{3}x(?=.*S)(?=.*E)(?=.*V)(?=.*E)(?=.*N)[SEVEN]{5}x(?=.*E)(?=.*I)(?=.*G)(?=.*H)(?=.*T)[EIGHT]{5}x(?=.*N)(?=.*I)(?=.*N)(?=.*E)[NINE]{4}x
for(int i=0,q;i<9;) // Loop (3) from 0 through 9 (exclusive)
for(q=(s+" ").split(x.split("x")[i++]).length-1;
// Split the input on the current regex-part,
// and save the length - 1 in `q`
q-->0; // Inner loop (4) over `q`
r+=i // And append the result-String with the current index (+1)
); // End of inner loop (4)
// End of loop (3) (implicit / single-line body)
return r; // Return the result-String
} // End of method
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 181 bytes
```
s->{String x="",r;for(int i=0,l;i<9;)for(r="ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".split(",")[i++],l=r.length();s.matches("["+r+"]{"+l+"}.*");s=s.substring(l))x+=i;return x;}
```
[Try it online!](https://tio.run/##jVHLbsMgELz3KxAnXBPUa@W6t03MoSDZJK4U5eC4bkqLSQQkTRX521Py6LmRWMHuDqOd2c9m14zWm85@vn0dW9N4j14abQ93CGkbOvfetB0SpxShKjhtV6gl14dPslgfYsQjkEU5OvrR8@Ha3ucYU5e9rx2JVEjnD9Rk@ukxS04ll2MpgKpaUlWUAHQspyUd8xnQir/SCmYgKPBJoajgAjDzG6MDwRQnc52mC2pyx0xnV@GDJJlnfRPaj84TPMepS/HigFOT4oHd49jNPfPbpT/PRUyS7NNcZ64LW2fRPhuO2UXDZrs0ukU@NCFeu7V@Q30046p3vkBNcnHiZBHqo17bfZ8TcrYiWvTjQ9ez9TawTfwTjCU9s6wlWIDEyb8oELKW6hagFFLVhYISbkBXYgYwKYArAVzcNoesFUBZqHIqxzDj41deibiUShUTDiBuohESohwl6yJS/cka7objLw "Java (OpenJDK 8) – Try It Online")
I took the liberty to reuse [Kevin Cruyssen's TIO template](https://codegolf.stackexchange.com/a/132077/16236). Hope you don't mind ;)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~36~~ 31 bytes
```
‘€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘#vyœN>UvyX:
```
[Try it online!](https://tio.run/##AVQAq/8wNWFiMWX//@KAmOKCrMK14oCa4oCi4oCew63igKDDrMuGw4jFksWhw6/Cv8W4wq/CpcWg4oCYI3Z5xZNOPlV2eVg6//9PRU5UT1dURUVSSEZPUlU "05AB1E – Try It Online")
---
View it ran with debug: [TIO With Debug](https://tio.run/##AVcAqP8wNWFiMWX//@KAmOKCrMK14oCa4oCi4oCew63igKDDrMuGw4jFksWhw6/Cv8W4wq/CpcWg4oCYI861xZN9dnlOPlV2eVg6//9PRU5UT1dURUVSSEZPUlU)
```
‘€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘# | Push ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE']
vyœ | For each list of permutations of that word...
N>U | Push index + 1 into register X.
vyX: | Replace each permutation with X.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~238~~ 236 bytes
```
def f(s):
e=''
while len(s):
for i in range(9):
for r in[''.join(p)for p in permutations('ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split()[i])]:
if s[:len(r)]==r:e+=str(i+1);s=s[len(r):]
return e
from itertools import*
```
[Try it online!](https://tio.run/##jc89a8MwEAbg3b/iyGKpKYHSqS4ez7YWCWzFCRgPgciNii0JSaH017uxEyh06nTw3Mt9uO94seZ1ns9qgIEEmiWg8jRN4OuiRwWjMneEwXrQoA34k/lQ5G3FVW9uujTdfVptiKMLuSXolJ@u8RS1NYGkgiPIgwBZ1YhQiH0NBWsRGnaEBlvkgKysJHDGMd0FN@pIaKd72mewbAI9QOiy5SBP@zz3mdrmIXqity/0PeShu7eyPgGv4tUbUMng7QQ6Kh@tHQPoyVkfn2bntYlkw1Fsnod7pTR5aMNbxLJCJjkyvgb@0G8WuRAHiVhXst6LAltWHFnDb@80sioZIn9M@FeQ0vkH "Python 3 – Try It Online")
---
Brute-force solution, doesn't take advantage non-decreasingness of digits.
---
Thanks to @Mr. Xcoder for saving 2 bytes!
[Answer]
# PHP, 141 bytes
```
for($a=count_chars($argn);$c=ord($s[++$p]?:$s=[OWU,W,HG,U,FU,X,SX,G,N17.$p=0][$i-print str_repeat($i++,$x)]);)$x=$a[$i+48]+=($p?-1:1)*$a[$c];
```
older version, **151 bytes**:
```
for($a=count_chars($argn,1);$s=[OWU,W,HG,U,FU,X,SX,G,N17][+$i++];print str_repeat($i,$a[$i+48]))for($p=0;$c=ord($s[$p]);)$a[$i+48]+=($p++?-1:1)*$a[$c];
```
loops through the digits from 1 to 9, counting unique characters in the word and subtracting non-unique characters´ counts, printing the digit on the go.
Although it is printing on the go, the digit counts must be stored for the `9` case to work.
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/d55e59c0dadd323e1abf1b87ee1beab3eda81d84).
It would save 4 more bytes to store the digit counts in `$a[$i]` instead of `$a[$i+48]` and use ASCII `1` and `7` (in quotes) instead of the digit characters themselves.
**breakdown**
```
for(
$a=count_chars($argn,1); # count character occurences in input
$s=[OWU,W,HG,U,FU,X,SX,G,N17][+$i++]; # loop through digit names
print str_repeat($i,$a[$i+48]) # print digit repeatedly
)
for($p=0;$c=ord($s[$p]);) # loop through name
$a[$i+48]+= # add to digit count
($p++?-1:1)* # (add first, subtract other)
$a[$c]; # character occurences
```
`ONE` is not the only word with an `O`, so it needs to subtract the counts for `W` (only appearing in `TWO`) and `U` (only appearing in `FOUR`) and so on.
`NINE` is special, because there is no way to just subtract if I used the letters (that would require `I-X-G-F+U` or `N-O-S+W+U+X`), so I use the digit counts instead.
# PHP, 160 bytes
```
$a=count_chars($argn);foreach([W2O,U4FOR,X6SI,G8I,F5I,O1,R3,S7,I9]as$s)for(${$s[$p=1]}+=$n=$a[ord($s)];$c=ord($s[++$p]);)$a[$c]-=$n;while($$i--?print$i:$i++<9);
```
assumes all upper case input; characters may be scrambled all over.
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/07454a4d490a2e124e2a9af361b5ba4bf9153e1f).
**explanation**
loops through the digit words, counting their unique characters´ occurences in the input and in the process reducing the count of other characters.
"Other characters" *could* mean all other characters in the word; but only considering those that will be needed later saved 19 bytes.
Transforming the `str_repeat` loop to a combined loop saved 5 bytes.
And using variable variables for the digit count saved another 8.
**breakdown**
```
$a=count_chars($argn); # count character occurences in input
foreach([W2O,U4FOR,X6SI,G8I,F5I,O1,R3,S7,I9]as$s) # loop through digit names
for(${$s[$p=1]}+= # 2. add to digits count
$n=$a[ord($s)]; # 1. get count of unique character
$c=ord($s[++$p]);) # 3. loop through other characters
$a[$c]-=$n; # reduce character count
while(
$$i--?print$i # print digit repeatedly
:$i++<9); # loop through digits
```
] |
[Question]
[
This is the inverse of [Let's do some "deciph4r4ng"](https://codegolf.stackexchange.com/q/115709/38183)
---
In this challenge, your task is to encipher a string. Luckily, the algorithm is pretty simple: reading from left to right, each typical writing character (ASCII range 32-126) must be replaced by a number ***N*** (0-9) to indicate that it is the same as the character ***N+1*** positions before it. The exception is when the character does not appear within the previous 10 positions in the original string. In that case, you should simply print the character again.
Effectively, you should be able to reverse the operation from the original challenge.
### Example
The input string `"Programming"` would be encoded this way:
[![Example1](https://i.stack.imgur.com/WWdbF.png)](https://i.stack.imgur.com/WWdbF.png)
Hence, the expected output is `"Prog2am0in6"`.
### Clarifications and rules
* The input string will contain ASCII characters in the range 32 - 126 exclusively. You can assume that it will never be empty.
* The original string is guaranteed not to contain any digit.
* Once a character has been encoded, it may in turn be referenced by a subsequent digit. For instance, `"alpaca"` should be encoded as `"alp2c1"`.
* References will never wrap around the string: only previous characters can be referenced.
* You can write either a full program or a function, which either prints or outputs the result.
* This is code golf, so the shortest answer in bytes wins.
* Standard loopholes are forbidden.
### Test cases
```
Input : abcd
Output: abcd
Input : aaaa
Output: a000
Input : banana
Output: ban111
Input : Hello World!
Output: Hel0o W2r5d!
Input : this is a test
Output: this 222a19e52
Input : golfing is good for you
Output: golfin5 3s24o0d4f3r3y3u
Input : Programming Puzzles & Code Golf
Output: Prog2am0in6 Puz0les7&1Cod74G4lf
Input : Replicants are like any other machine. They're either a benefit or a hazard.
Output: Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d.
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~24~~ 23 bytes
```
(.)(?<=\1(.{0,9}).)
$.2
```
[Try it online!](https://tio.run/nexus/retina#HUyxCsIwFNzfVzxBtAUJ6iYoDg46FhFcXF6b1yaY5kkah1b89pp6d8vdcTdmKs@O@8Njk6nPerX75iqHudqOI5WVBkqAknwiXNg5wbsEp2cQje0wiTByF6ERV1vfTEkjorGWgL28oQjSBGrbqSvew@C4wwWeRDOe0wSu/HK2Ih/TU2B09slIvkeJhgO2VBnrWeHNcL9MPdt/Tliy59pGlMkYGiho9QM "Retina – TIO Nexus")
A fairly simple regex substitution. We match each character and try to find a copy of it 0-9 characters before it. If we find it, we replace the character with the number of characters we had to match to get to the copy.
The results don't quite match the test cases, because this one uses the largest possible digit instead of the smallest possible one.
[Answer]
## JavaScript (ES6), ~~74~~ ~~57~~ 54 bytes
*Saved 3 bytes thanks to ETHproductions with the brilliant `p=/./g` instead of `p={}` (inspired by Neil)*
```
s=>s.replace(p=/./g,(c,i)=>(i=p[c]-(p[c]=i))>-11?~i:c)
```
### Test cases
```
let f =
s=>s.replace(p=/./g,(c,i)=>(i=p[c]-(p[c]=i))>-11?~i:c)
console.log(f("abcd"));
console.log(f("aaaa"));
console.log(f("banana"));
console.log(f("Hello World!"));
console.log(f("this is a test"));
console.log(f("golfing is good for you"));
console.log(f("Programming Puzzles & Code Golf"));
console.log(f("Replicants are like any other machine. They're either a benefit or a hazard."));
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~72~~ 66 bytes
*Thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) for golfing 6 bytes!*
```
(a:r)%s=last(a:[n|(n,b)<-zip['0'..'9']s,b==a]):r%(a:s)
e%s=e
(%"")
```
[Try it online!](https://tio.run/nexus/haskell#@6@RaFWkqVpsm5NYXAJkR@fVaOTpJGna6FZlFkSrG6jr6albqscW6yTZ2ibGaloVqQIVFWtypQK1pHKl2WqoKilp/s9NzMyzzcwrSS1KTC5RSPsfUJSfXpSYm5uZlw4A "Haskell – TIO Nexus")
The function `%` keeps the partially processed string in reverse in its second argument, so it's able to search the first 10 elements of this string for occurences of the character it's examinating. The submission consists of the unnamed function `(%"")` which calls the previous function with the empty string as its second argument.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20 19~~ 18 bytes
-2 Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)
```
õ¹vDyåiDykëy}?yìT£
```
[Try it online!](https://tio.run/nexus/05ab1e#@695aGeZS@XhpZkuldmHV1fW2lce2nF4Tcihxf//B6UW5GQmJ@aVFCskFqUq5GRmpyok5lUq5JdkpBYp5CYmZ2TmpeophGSkVqoD5VMzweKJCkmpealpmSUK@SBORmJVYlGKHgA "05AB1E – TIO Nexus")
```
õ # Push an empty string
¹v y # For each character in input
D # Duplicate the string on the stack (call this S)
åi # If this character is in S
Dyk # Push the index of that that character
ë } # Else
y # Push the character
? # Print without newline
yì # Prepend this character to S
T£ # Remove all but the first 10 elements from S
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
s=''
for c in input():d=s[:~10:-1].find(c);s+=-d*c or`d`
print s
```
[Try it online!](https://tio.run/nexus/python2#Lc07C4NAEATg3l@xEMjeRc2jvWiVIq1FOhE09xBBPdnVFBb@dXOFMM0U883OOWLkPIGGbgyZlllIZXIu1fa4q/RRXV03GqHlk@M8NRcNnmpTRxN14wy8n@BjeQ7LnyW2UeTyvhm@pgFSZM2irTg6J1pxLHSJN8x0hgpVFX653AIU/EomlCDKQ3aC5Y4F@ZaaYejGFoplXXvLcIaXNxbevnf4Bw "Python 2 – TIO Nexus")
[Answer]
# [Perl 5](https://www.perl.org/), 36 bytes
35 bytes of code + `-p` flag.
```
s/(\D)(.{0,9})\K\1/length$2/e&&redo
```
[Try it online!](https://tio.run/nexus/perl5#HYtBi8IwFITv@RVPVqqCturNswu74EVE8NLLazM2wdekpPFgxd9eozNz@WaYn0mHILTqxr6Yl7@Lef5cL3evRXkoN4XANdFMtwWyLED7ceSq1oqTVMUuWf1DxNPFB9ETFY3tKYUpoo/qGHwTuG2ta@h4HwZBTxntvQb9ebmqEzqxNbuYHgEk9gZi9yAfDQK1XBvrkNPZ4DFLO@y3Z6rgcLWR/AcMDxx0/gY "Perl 5 – TIO Nexus")
Some explanations:
The goal is to replace a non-digit character (`\D` but it correspond to the backreference `\1` in my regex) that is preceded by less than 10 characters (`.{0,9}`) and the same character (`(\D)`...`\1`) by the length of the `.{0,9}` group (`length$2`). And `redo` while characters get replaced.
[Answer]
# Python 2, ~~89~~ 84 bytes
```
m=input()[::-1];j=1;t=''
for i in m:s=m[j:].find(i);t=[i,`s`][0<s<10]+t;j+=1
print t
```
[Try it Online!](https://tio.run/nexus/python2#DcmxDoMgEADQ3a@4STTaRlbwJoeu7oTEGsUcETCAiz9P@9ZXHJK/7ty0SogX19IilxkZq0yIQEAenEjolBX6bchvDbX/V9QvadFqGNPIB91laTvk1RXJZ8ilsDmGI36dI3/AfD/PuSeoYQrbDp9wmnViPw)
Iterates throught the string in reverse, and builds a new string with the correct numbers inserted.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
```
£¯Y w bX s r"..+"X
```
[Try it online!](https://tio.run/nexus/japt#HclNDkAwFEXhrdx0YiDpYsSA4cOVvqCkmgjbsQB7sLH6GZ7vpPu8rxobmgorgrE2N1VKpuAyais@rpBAjDoQ4nfM0TFgktapp0XpuGfvp/4uaOjZa8T8hZNDQmfNAw "Japt – TIO Nexus")
### Explanation
```
£ ¯ Y w bX s r"..+"X
mXY{s0,Y w bX s r"..+"X}
// Implicit: U = input string
mXY{ } // Replace each char X and index Y in U by this function:
s0,Y // Take U.slice(0,Y), the part of U before this char.
w bX // Reverse, and find the first index of X in the result.
// This gives how far back this char last appeared, -1 if never.
s // Convert the result to a string.
r"..+"X // Replace all matches of /..+/ in the result with X.
// If the index is -1 or greater than 9, this will revert to X.
// Implicit: output result of last expression
```
[Answer]
# JavaScript, ~~100~~ 80 bytes
```
x=>x.split``.map((c,b,a)=>{for(i=0;i++<=9&&a[b-i]!=c;);return i>9?c:i-1}).join``
```
[Try it online!](https://tio.run/nexus/javascript-node#bY4xT8MwFIR3fsWjQ7CVYsFYgsPAwFohNoSUF/c5eeDY1XOK2iB@ewhMCHHb3ek@nbfz0dZHk/eBx6YxQu8kmZQ2A@6Vcut2jdrWHz6JYntVcVne2k1R4HNb8su5dZWuhMaDROB6c@du@PL6U//CvCaOTTO7FHMKZELqlFcrXLTS@uxP/EjLDYdxzIBCEPiNAOMJ0tiTwICu50gGnno6XSw98U@O0FIkzyOkb9PjhLIz/@C3kjrBYeDYwfYwTYEyFHCfdgQPKfhlMX8B "JavaScript (Node.js) – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
õIv¹N£RT£©yåi®ykëy}J
```
[Try it online!](https://tio.run/nexus/05ab1e#@394q2fZoZ1@hxYHhRxafGhl5eGlmYfWVWYfXl1Z6/X/f1BqQU5mcmJeSbFCYlGqQk5mdqpCYl6lQn5JRmqRQm5ickZmXqqeQkhGaqU6UD41EyyeqJCUmpeallmikA/iZCRWJRal6AEA "05AB1E – TIO Nexus")
**Explanation**
```
õ # push an empty string
Iv # for each [index,char] [N,y] in input
¹N£ # push the first N characters of input
R # reverse
T£ # take the first 10 characters of this string
© # save a copy in register
yåi # if y is in this string
®yk # push the index of y in the string in register
ë # else
y # push y
} # end if
J # join stack as one string
```
[Answer]
# Python 3, ~~125~~ 118 bytes
```
def p(x):print(x,end='')
l={}
for i,c in enumerate(input()):
if l.get(c,i+9)<i+9:
p(i-l[c]-1)
else:
p(c)
l[c]=i
```
[Try it online!](https://tio.run/nexus/python3#JczBCsIwEATQe75ib81iKvRoMV8iHkq6qQsxhmQLBfHb44owDMw7TF8pQrEHzqVyFns4yqsfBjTJvz8mviqwC8AZKO9PqouQ5Vx2sYizAY6QzhuJDY5PF7xqqeohj@kW7uOEBig1@mPQ9WPPvcuDG2gWEGryBQ)
[Answer]
# [C (tcc)](http://savannah.nongnu.org/projects/tinycc), 113 bytes
Since the function creates a copy of an input string, the maximum size of input is 98 characters (more than enough to fit the longest test input). Of course, this can be changed to any other value.
```
i,j;f(char*s){char n[99];strcpy(n,s);for(i=1;s[i];i++)for(j=i-1;j>-1&&i-j<11;j--)if(n[i]==n[j])s[i]=47+i-j;j=-1;}
```
[Try it online!](https://tio.run/nexus/c-tcc#bY1BS8QwEIXv/RVDwTWxzUJBWNYY754E8VZ7iN2ETFynJckKddnfXtOKeHEuM@/NN/NmrL20rHc63ER@XjpQu993MqbQjxOjOnJph8BQNTK22EmsKr4YXqFopH8QzWaDwt83WQjB0TLKmFLU@o4vF@p2V2VAepX5y4yU4EMjsc8BD7w4F5BrDc6RbafKZzMesdeUIuhg4IjvBjRNMCRnQj7tHZLZwosz03XeG1x9DW@GjMUEwyKc/tLhsC3l@n4MOdWy8pHGU4I7uIqvVNZLIP8BLPubf@GnU8r0P3Bxmb8B "C (tcc) – TIO Nexus")
**Edit**
-15 bytes. Thanks **Johan du Toit**.
[Answer]
# Java 7, ~~102~~ 101 bytes
```
void a(char[]a){for(int b=a.length,c;--b>0;)for(c=b;c-->0&c+11>b;)if(a[c]==a[b])a[b]=(char)(b-c+47);}
```
[Try it online!](https://tio.run/nexus/java-openjdk#nZLBbsMgDEDv@Qqvhy6oS9RJk3aIUinqYTtW66QdohwMcRI0AhUhndKq395B9gULIDA2fjZgoXAYoLjez0bWgLHo0JYVsmtjbCy1A55jqki3rnsSWZLw3TZjwSZynokk2W3XYvP8vOMZk02MpajyHEtesTDlM47FPBGbl1eW3e6nkSspYHDo/DLH7FHq@Ois1G1Zndk1ggIQctD0A0XMsgj@cuJe4vkKuahXqTN7ryysxWk@ginGPAjHaXDUp2Z06ckjndKzPgqevi3z5Kh9X@b7TkoZ@DJW1Q/LCK6TA/iB4GhwyxitUY1/4IBpjanB/yBMZlwGO1jTWuz7ADyMl4uiAdawNzXBm4@zDPpBJ18ZqJ2/qCVQ8psA9QTGdWR9kYhOakrhs6Pp0dtJznoETpoa6cCETYcXtHX6/wxu0e3@Cw "Java (OpenJDK 8) – TIO Nexus")
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). I always enjoy an excuse to use the goes-to operator.
[Answer]
# PHP, 104 Bytes
forward solution
```
for($i=0;$i<strlen($a=&$argn);$f[$l]=$i++)$a[$i]=is_int($f[$l=$a[$i]])&($c=$i-$f[$l]-1)<10?$c:$l;echo$a;
```
Backwards solutions
[Online Versions](http://sandbox.onlinephpfunctions.com/code/258a21bf9091c12366037b4297bc2bf275cab010)
## PHP, 111 Bytes
```
for(;++$i<$l=strlen($a=&$argn);)!is_int($t=strrpos($argn,$a[-$i],-$i-1))?:($p=$l-$i-$t-1)>9?:$a[-$i]=$p;echo$a;
```
## PHP, 112 Bytes
```
for(;++$i<$l=strlen($a=&$argn);)if(false!==$t=strrpos($argn,$a[-$i],-$i-1))($p=$l-$i-$t-1)>9?:$a[-$i]=$p;echo$a;
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/7a425f8f42d9ca94f451fa5f2f72b46971966a5d)
[Answer]
## REXX, ~~124~~ 125 bytes
```
a=arg(1)
b=a
do n=1 to length(a)
m=n-1
c=substr(a,n,1)
s=lastpos(c,left(a,m))
if s>0&m-s<=9 then b=overlay(m-s,b,n)
end
say b
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~117~~ ~~103~~ 93 bytes
```
i,j;f(char*s){for(i=strlen(s)-1;s[--i];)for(j=i-1;s[j]&&i-j--<10;)if(s[i]==s[j])s[i]=47+i-j;}
```
[Try it online!](https://tio.run/##bY7BTsMwDIbvfQqrEiNhy8SkSZMIeYCdkBC30kPInMWlpFWSIY1pz16SIjjhk/3/v/3ZiKMx00SrTlpmnA53kV/sEBipmEKPnkUuNjI2QlAreXE6RbPStYsFiU6Ix8295GRZbKhVqhh8bre7ZfbldSKf4EOTZ58DHXh1qSBXgUFmNK2qn3HsyWifIuiA0NM7gvZnGJLDkFeNI49reHF4vs0@0qxreEOPlhIMZXD6S4fDupbz@TFkqmX13o@nBA9wE199vSpA/hPI//71v@GnU8rpf8LVdfoG "C (gcc) – Try It Online")
No string.h import, works w/ warning. If this is against the rules, I'll pull it.
## Pretty Code:
```
i,j;
f(char *s) {
// Chomp backwards down the string
for(i=strlen(s)-1; s[--i];)
// for every char, try to match the previous 10
for(j=i-1; s[j] && i-j-- < 10;)
// If there's a match, encode it ('0' + (i-j))
if (s[i] == s[j])
s[i] = 47+i-j;
}
```
## Edits:
* Changed from LLVM to gcc to allow implicit i,j declaration, removed lib import.
* Added function wrapper for compliance
* Decrement in loop boundaries thanks to **ceilingcat**
* Removed `break` and braces from loop, first match modifies `s[i]
[Answer]
# MATL, ~~31~~ 30 bytes
```
&=R"X@@f-t10<)l_)t?qV}xGX@)]&h
```
Try it at [**MATL Online!**](https://matl.io/?code=%26%3DR%22X%40%40f-t10%3C%29l_%29t%3FqV%7DxGX%40%29%5D%26h&inputs=%27golfing+is+good+for+you%27&version=19.9.0)
**Explanation**
```
% Implicitly grab input as a string
&= % Perform element-wise comparison with automatic broadcasting.
R % Take the upper-triangular part of the matrix and set everything else to zero
" % For each column in this matrix
X@ % Push the index of the row to the stack
@f % Find the indices of the 1's in the row. The indices are always sorted in
% increasing order
- % Subtract the index of the row. This result in an array that is [..., 0] where
% there is always a 0 because each letter is equal to itself and then the ...
% indicates the index distances to the same letters
t10<) % Discard the index differences that are > 9
l_) % Grab the next to last index which is going to be the smallest value. If the index
% array only contains [0], then modular indexing will grab that zero
t? % See if this is non-zero...
qV % Subtract 1 and convert to a string
} % If there were no previous matching values
x % Delete the item from the stack
GX@) % Push the current character
] % End of if statement
&h % Horizontally concatenate the entire stack
% Implicit end of for loop and implicit display
```
] |
[Question]
[
>
> **Notice:** This [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge has completed. This means that the green checkmark, which has been awarded to C5H8NNaO4 for their entry The Observer will not be moved to any new answer.
>
>
> You may still submit new entries, but there may be delays in new tournaments running as I am not actively checking for new entries anymore.
>
>
>
## Introduction
In this challenge, you are playing an arcade game titled *The Ultimate Samurai Showdown Ultimate Edition Special Version 2.0 X Alpha Omega Turbo* (or just *Ultimate Samurai Showdown* for short). Your opponents? None other than the other members of Programming Puzzles & Code Golf!
As you might expect from a PPCG arcade game, you do not play *Ultimate Samurai Showdown* directly, but rather write a program that will play the game for you. This program will fight against programs submitted by other users in one on one duels. The most skilled program will be crowned the Ultimate Samurai of PPCG, and be granted the green tick of legend.
## Game Description
This section describes the mechanics behind the game.
### Victory Condition
A *match* consists of two *samurai* which are facing off against each other. Each samurai begins each match with 20 *hit points* and 1 *honour*. A samurai wins if his opponent is dead and he is still alive. There are two methods by which a samurai can die:
1. If a samurai's hit points are brought down to 0, he will die.
2. If a samurai brings their own honour *below* 0, he will be struck down by the gods for acting dishonourably in a duel.
Being struck down by the gods has higher priority over having hit points reduced to 0, so in a situation where one samurai is at 0 health points and the other is at -1 honour, the samurai with 0 health points will win. In a situation where both samurai are at -1 honour, they both get struck down by the gods and the game is a draw.
A match consists of up to 500 *turns*. If all 500 turns pass and the match has not been decided (neither samurai has died), the gods grow bored and strike down both of the samurai, thus resulting in a draw.
### Actions
On each turn, the samurai must perform exactly one of the following actions:
**`W`**
The samurai shall wait and perform no action. This makes him look cool but doesn't help him defeat his opponent. This is also the default action.
**`B`**
The samurai shall bow to his opponent in an honourable fashion. This pleases the gods and thus the samurai will gain 1 Honour. Honour is vital to your samurai's success because Honour is essentially the "resource" for this game -- all moves apart from `B` and `W` can decrease Honour. Also, if a samurai gains 7 Honour or more, he is granted use of the *Sword of the Gods*. The implications of this are described below.
However, bowing to your opponent leaves you open if your opponent decides to strike you with his sword, so be careful when you choose to bow.
**`G`**
The samurai shall enter a defensive position and guard against any sword strikes. This move will successfully block all sword strikes, even ones made with the *Sword of the Gods*.
However, the gods frown upon an overly defensive samurai, so this move will consume 1 Honour *if* the samurai's action on the immediately preceding turn was also guarding. It does not consume Honour otherwise.
**`I`**
The samurai shall attempt to strike his opponent with a quick draw of his sword from its scabbard. If the samurai has 7 Honour or more, he will use the *Sword of the Gods* instead of his regular sword. This move consumes 1 Honour.
The quick draw is a fast strike that will beat slower overhead attacks, however, it will lose against parries. If the strike connects successfully it will do 1 damage, or 2 damage with the *Sword of the Gods*.
**`P`**
The samurai shall attempt to parry any incoming attack, then launch his own attack. If the samurai has 7 Honour or more, he will use the *Sword of the Gods* instead of his regular sword. This move consumes 1 Honour.
The parry is a good manoeuvre against fast strikes, but it will be overpowered by slower overhead attacks. If the strike connects successfully it will do 1 damage, or 2 damage with the *Sword of the Gods*.
**`O`**
The samurai shall attempt to strike his opponent with a slower overhead attack. If the samurai has 7 Honour or above, he will use the *Sword of the Gods* instead of his regular sword. This move consumes 1 honour.
The overhead strike can overpower parries, but it will lose against fast strikes. If the strike connects successfully it will do 1 damage, or 2 damage with the *Sword of the Gods*.
### Sword of the Gods
A samurai with Honour that is 7 or more gains the ability to use the *Sword of the Gods*. If his Honour is reduced below 7, the ability to use the *Sword of the Gods* will be revoked from him. The *Sword of the Gods* deals 2 damage instead of 1.
The *Sword of the Gods* does not allow a strike to defeat a sword strike that it would not ordinarily defeat. For instance, a *Sword of the Gods* parry will still lose to an ordinary overhead strike, and a *Sword of the Gods* quick draw will not overpower an ordinary quick draw. Indeed, the so-called *Sword of the Gods* is actually not all that powerful -- perhaps it is a cosmic joke played by the gods...
### Interaction Table
The Stack Snippet below contains a table which explicitly lists all the possible results of the different combinations of actions the two samurai can take. To view it, click on "Show Code Snippet", then click "Run Code Snippet".
```
td,
th {
border: 1px solid #ccc;
text-align: center;
font-family: sans-serif;
}
```
```
<table>
<tr>
<th></th>
<th>W (Wait)</th>
<th>B (Bow)</th>
<th>G (Guard)</th>
<th>I (Quick Draw)</th>
<th>P (Parry)</th>
<th>O (Overhead Strike)</th>
</tr>
<tr>
<td>W (Wait)</td>
<td>Nothing occurs.</td>
<td>The player that bowed gains +1 Honour.</td>
<td>If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>The player that waited takes 1 damage (or 2 if the Sword of the Gods was used.) The player that struck loses 1 Honour.</td>
<td>The player that waited takes 1 damage (or 2 if the Sword of the Gods was used.) The player that struck loses 1 Honour.</td>
<td>The player that waited takes 1 damage (or 2 if the Sword of the Gods was used.) The player that struck loses 1 Honour.</td>
</tr>
<tr>
<td>B (Bow)</td>
<td>The player that bowed gains +1 Honour.</td>
<td>Both players gain +1 Honour.</td>
<td>The player that bowed gains +1 Honour. If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>The player that bowed gains +1 Honour and takes 1 damage (or 2 if the Sword of the Gods was used). The player that struck loses 1 Honour.</td>
<td>The player that bowed gains +1 Honour and takes 1 damage (or 2 if the Sword of the Gods was used). The player that struck loses 1 Honour.</td>
<td>The player that bowed gains +1 Honour and takes 1 damage (or 2 if the Sword of the Gods was used). The player that struck loses 1 Honour.</td>
</tr>
<tr>
<td>G (Guard)</td>
<td>If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>The player that bowed gains +1 Honour. If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>If a guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>The player that struck loses 1 Honour. If the guarding player guarded the previous turn, that player loses 1 Honour. </td>
<td>The player that struck loses 1 Honour. If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>The player that struck loses 1 Honour. If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
</tr>
<tr>
<td>I (Quick Draw)</td>
<td>The player that waited takes 1 damage (or 2 if the Sword of the Gods was used.) The player that struck loses 1 Honour.</td>
<td>The player that bowed gains +1 Honour and takes 1 damage (or 2 if the Sword of the Gods was used). The player that struck loses 1 Honour.</td>
<td>The player that struck loses 1 Honour. If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>Both players lose 1 Honour. </td>
<td>Both players lose 1 Honour. The player that quick drawed takes 1 damage (or 2 if the Sword of the Gods was used.).</td>
<td>Both players lose 1 Honour. The player that used an overhead strike takes 1 damage (or 2 if the Sword of the Gods was used.).</td>
</tr>
<tr>
<td>P (Parry)</td>
<td>The player that waited takes 1 damage (or 2 if the Sword of the Gods was used.) The player that struck loses 1 Honour.</td>
<td>The player that bowed gains +1 Honour and takes 1 damage (or 2 if the Sword of the Gods was used). The player that struck loses 1 Honour.</td>
<td>The player that struck loses 1 Honour. If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>Both players lose 1 Honour. The player that quick drawed takes 1 damage (or 2 if the Sword of the Gods was used.).</td>
<td>Both players lose 1 Honour. </td>
<td>Both players lose 1 Honour. The player that parried takes 1 damage (or 2 if the Sword of the Gods was used.).</td>
</tr>
<tr>
<td>O (Overhead Strike)</td>
<td>The player that waited takes 1 damage (or 2 if the Sword of the Gods was used.) The player that struck loses 1 Honour.</td>
<td>The player that bowed gains +1 Honour and takes 1 damage (or 2 if the Sword of the Gods was used). The player that struck loses 1 Honour.</td>
<td>The player that struck loses 1 Honour. If the guarding player guarded the previous turn, that player loses 1 Honour.</td>
<td>Both players lose 1 Honour. The player that used an overhead strike takes 1 damage (or 2 if the Sword of the Gods was used.).</td>
<td>Both players lose 1 Honour. The player that parried takes 1 damage (or 2 if the Sword of the Gods was used.).</td>
<td>Both players lose 1 Honour. </td>
</tr>
</table>
```
## Program Communication
To facilitate the running of the tournament, a controller program was written to play the role of the "gods" -- it keeps records of honour and health and smites samurai accordingly. This section describes how your program will communicate with the controller program.
### Input Description
The controller program will call your program from the command line like this:
```
<command> <history> <enemy_history> <your_health> <enemy_health> <your_honour> <enemy_honour>
```
where:
* `<command>` is the command required to run your program. For instance, if your program is in a file `super_sentai.pl`, the command is probably `perl super_sentai.pl`.
* `<history>` is a history of moves that you made. For instance, `WWBP` would mean you waited twice, bowed once, and parried once.
* `<enemy_history>` is a history of moves your enemy made. For instance, `BBBI` would mean your enemy bowed three times and performed one quick draw.
* `<your_health>` is your current health.
* `<enemy_health>` is the enemy's current health.
* `<your_honour>` is your current honour.
* `<enemy_honour>` is the enemy's current honour.
For the first turn, the `history` and `enemy_history` will be empty, so your program will just be called with the last four arguments like this:
```
<command> <your_health> <enemy_health> <your_honour> <enemy_honour>
```
Please be prepared for this!
Astute readers may notice that the four arguments providing the honour and health of both samurai are, to some extent, superfluous; since this is a perfect information game, the honour and health of the samurai can be determined using only the histories.
These values are provided for convenience purposes so that you do not have to parse the history arguments. This should prove useful for implementing simple strategies, such as not attacking when your Honour is 0.
### Output Description
To choose an action, your program should output one of `W`, `B`, `G`, `I`, `P`, or `O` to standard output, depending on what action you want to make. If your program doesn't output anything within 1000ms, it will be terminated and your program will be treated as if it outputted `W`.
If your program outputs more than one letter, only the first letter will be considered -- so outputting `Parry` will be the same as outputting `P`.
If the output of your program's first letter is not any of the options listed above, it will default to `W`.
### Submission Format
Submit a program as an answer to this post. You may submit multiple programs. If you are submitting multiple simple programs, I recommend submitting them as a single answer; if you are submitting multiple complex programs, I recommend submitting them as separate answers. Once I have successfully added your program/s to the tournament, I will make a commit to the git repository with your entry (linked below).
If I encounter problems that prevent your program from being added to the tournament, I will leave a comment on your entry indicating the problem.
Please include the following in your submission:
1. The human readable name of your program, for use in scoreboards. Spaces are allowed here; commas and Unicode characters are not.
2. The language your program is written in. Please avoid writing in strange, difficult to access languages like TinyMUSH.
3. A short synopsis of your program. This can be a description on how the program works, or just some flavour text about your program (if you want to be all secretive), or perhaps both.
4. The command/s required to run your program. For instance, if you were writing your submission in Java called `example.java`, you would provide compiling instructions `javac example.java` then running instructions `java example`.
5. The source code for the program.
To assist in submitting, I provide a submission template which can be found [here](https://raw.githubusercontent.com/katyaka/ultimate-samurai-showdown/master/template). The template makes submissions look nicer. I strongly encourage using it.
I also provide two example entries. Although the example entries will be participating in the round robin, their main purpose is to clarify the submission and input/output formats for the tournament, rather than being serious contenders for the title of Ultimate Samurai.
## Tournament Structure
This section describes how the tournament between the participants will be run.
### Control Program
The control program is written in Python 2 and can be found on the [Ultimate Samurai Showdown Github repository](https://github.com/katyaka/ultimate-samurai-showdown). If you'd like to run it yourself, instructions on how to run it are included in the README.md file in the link. However, only tournaments run on my computer will be official to avoid hardware differences affecting tournament results.
The control program will be ran on a laptop computer running Arch Linux. It has an Intel Core i7 processor and 8GB of RAM. I will endeavour to get all entries running on my computer, but I'd appreciate it immensely if you avoid languages that can't be accessed freely (as in no monetary cost).
### Scoring System
The scoring system is a round robin. Each program will play eight matches against every other program. A win grants the program 1 point, a loss no points, and a draw 0.5 points. The program with the highest score wins the game. If there is a draw, I will duel the top two programs against each other to determine the winner.
The number of times each program will play each other program may be decreased from 8 if there is an extremely large number of entrants. I will add a note here if this occurs.
I will be running the round robin many times as new submissions are posted, but it is only the most recent round robin that will count.
### Disqualifications
It is possible for your program to be disqualified from the tournament. Disqualification may occur if:
* Your program does not compile or run;
* Your program is a *strategic duplicate* of another program (that is, it implements the exact same strategy as another program);
* Your program attempts to sabotage other programs by modifying the controller code, other program's code, etc;
* Your program attempts to exploit a bug in the controller code. Instead of exploiting bugs you should instead open an issue in the git repository, make a comment here, or ping me in chat.
### Past Results
Detailed results of all tournaments are made available at the [wiki page](https://github.com/katyaka/ultimate-samurai-showdown/wiki/Past-Results).
The most recent tournament was completed on 2015-07-17 07:20. Here is a summary of the results:
```
The Observer: 209.0
Coward: 203.0
Monk: 173.0
Elephant Warrior: 157.0
Iniqy: 157.0
Agent 38: 144.0
Ninja: 138.0
Meiyo Senshi: 138.0
Kakashi: 136.0
Yoshimitsu: 131.0
Hermurai: 121.0
Warrior Princess: 120.0
Gargoyle: 119.5
The Honourable: 119.0
Hebi: 118.5
Predictor: 116.0
Whack-a-mole: 107.0
The Fool: 106.0
The Prophet: 105.0
Copy-san: 97.0
YAGMCSE: 80.0
The Waiter: 66.0
Swordsman: 43.0
Spork Holder: 32.5
Blessed Samurai: 27.5
Attacker: 27.0
The Terminator: 17.0
Master Yi: 16.0
```
[Answer]
# The Monk (Java)
The Monk values honour and praises the blessings of the Gods.
Being trained in patience he calmly sends his prayers to heaven until he feels being favoured by God.
Enjoying his life, he tries to protect it. When he's losing health over a certain rate, he defends himself as best as he can.
Hoping for the support of his Gods he randomly sends ejaculations[1] to heaven, otherwise he fights as best as he can.
If his opponent is worn out from the battle he finishes him using his remaining honour to grant him a fast and painless death.
Compile/Run
```
javac Monk.java
java Monk
```
---
```
public class Monk {
public static void main(String[] args){
char r = 'B';
double s = Math.random ();
int n = Math.max (args [0].length ()- 8, 1);
int p = args.length > 4 ? Integer.parseInt (args [4]):0;
int l = Integer.parseInt (args [3]);
int m = Integer.parseInt (args [2]);
double d = 1 + (20 - m) / n;
double e = 1 + (20 - l) / n;
if (((p>8&&s<.7)||l<11||m<2)&&p>0) {
r=(s<(.14)||d>=2||e/d<.618)?'G':"OPI".charAt((int)(Math.random()*3));
}
System.out.print (r);
}
}
```
# The Ninja (Java)
The Ninja is fast and attacks even faster. He attacks right away after a friendly formal greeting, further confusing his enemy by bowing before and after every attack.
Upon being blessed the ninja keeps up this behaviour, waiting for his opponent to make his first move(s). Using this opportunity he unleashs a series of blasts, blessed by the ninja Goddess until he's too worn out from the battle.
Using his remaining honor he hides under the leaves beneath, guarding himself from the next attack. He jumps out and attacks his foe from behind, being hidden as fast again.
If he receives a fatal wound he goes all out to take his opponent's live with him -- of course, keeping a miminum of honour.
```
javac Ninja.java
java Ninja
```
---
```
public class Ninja {
public static void main(String[] args){
char r = 'B';
int n = args [0].length ();
int p = args.length > 4 ? Integer.parseInt (args [4]):0;
int m = Integer.parseInt (args [2]);
int a = n % 3;
if (p>7) {
if (m>17) {
r = "BBI".charAt (a);
} else if (m>13) {
r = "BII".charAt (a);
} else {
r = "GIG".charAt (a);
}
} else if (p>0) {
if (m > 10) {
r = "BBI".charAt (a);
} else {
r="IGI".charAt (n%2);
}
}
System.out.print (r);
}
}
```
# Kakashi, The Copycat Ninja (Java)
Kakashi copies his opponents moves by randomly choosing between the last two moves the opponent made. If the opponent waits, he bows -- He keeps his honour as well.
```
javac Kakashi.java
java Kakashi
```
---
```
public class Kakashi {
public static void main(String[] args){
char r;
String h = args [1];
if (h=="W" || Integer.parseInt ( args.length > 4?args [4]:"0") < 1){
r = 'B';
} else if (Math.random ()<.1) {
r = 'I';
} else {
r = h.charAt ((int) (h.length()==1?0: h.length()-Math.random ()*2));
}
System.out.print (r);
}
}
```
*I wish Kakashi could be blessed with the sharingan..
I thought about reading the cast.txt. Simulate every round of his history against every opponent in there. Try to find out against which opponent he's fighting by comparing the simulated enemies history with the real enemies history. Then use that information to predict the next move the opponent would do and pick the best countermove from a predefined list.
But I feel this could take a bit as I have super slow Internet at the moment and about no Java skills*
# The Observer, (node.js)
The Observer bows before trying to predict the opponent's next move from its past 5 moves, choosing the best counterpart for the predicted move.
Edit: Thanks to @apsillers for sharing the node.js boilerplate!.
```
node observer.js
```
---
```
var argv = process.argv;
var history = argv.length>6?argv[2]:"";
var enemyHistory = argv.length>6?argv[3]:"";
var offset = 8 - argv.length;
var my = { health:+argv[4-offset], honor:+argv[6-offset], history:history };
var enemy = { health:+argv[5-offset], honor:+argv[7-offset], history:enemyHistory };
my.godSword = my.honor >= 7;
enemy.godSword = enemy.honor >= 7;
function decide() {
process.stdout.write(arguments[Math.floor(arguments.length*Math.random())]);
process.exit();
}
var m = {
m:{},
l:function (a,b) {
if (!this.m[a]) {
this.m [a] = [];
}
this.m[a].push (b);
},
p:function (a) {
for (var k=0;k<a.length;k++)
for (var j=1;j<a.length;j++)
for (var i=-1+k; i<a.length-j; i++)this.l (a.slice (i,i+j),a[i+j]);
},
a:function (a) {
if (!this.m[a])return;
return this.m[a][0|Math.random () * this.m[a].length-1]
}
}
var g={
B:"IPO",
G:"B",
I:"PG",
O:"IG",
P:"OG",
W:"I"
}
var c,i=0;
m.p(enemy.history);
while (!c && i++<enemy.history.length) {
c=m.a (enemy.history.slice (i));
}
decide.apply (0,my.honor < 7?["B"]:g[c].split (''))
```
---
Edit:
I had a major flaw in the observer, I actually don't know what I thought yesterday night. It seems he only looked at the past two moves of the enemy.
He did surprisingly well like this.
His memory now get's queried for the longest (end) part of the enemies history he already has seen. This contains an array with all the moves that followed the history of moves. One is randomly selected. So if one move followed more often, it is as well more likely to be picked. Kind of like markov chains.
The Observer, now guards as well.
---
[1]: *TIL: ejaculation has a religious meaning*
[Answer]
# Meiyo Senshi (Java)
Hailing from the Haijima area, not much is known about the Meiyo. They do not normally participate in games of sport, but have sent a warrior to this one in order to assess their rivals.
They are an honorable bunch, though, so you can be assured he will make his presence known to the gods in short order. Once he has seen enough of his foe to report, he will use the blessings received to strike down his opponent.
To compile run, it's the standard Java way:
```
> javac MeiyoSenshi.java
> java MeiyoSenshi
```
```
public class MeiyoSenshi {
public static void main(String[] args){
System.out.print(
Integer.valueOf(args[args.length<5?0:2])>12 ||
Integer.valueOf(args[args.length<5?2:4])<1 ?
"B":
"IPO".charAt((int)(Math.random()*3))
);
}
}
```
[Answer]
# Spork Holder (Ruby)
Spork Holder bows on the first turn, then acts randomly afterwards. It is one of the two example entries.
Command: `ruby spork-holder.rb`
```
if ARGV.length == 4
print "B"
else
print ["W", "B", "G", "I", "P", "O"].sample
end
```
---
# The Waiter (bash)
The Waiter only waits on every turn. It is one of the two example entries.
Command: `echo W`
There is no source code required.
[Answer]
# Coward (Node.js)
>
> [*I'm a coward / It's a miracle I dare breathe*](https://www.youtube.com/watch?v=BJ1aOACfYQE)
>
> [*Overpowered / By the gentlest summer breeze*](https://www.youtube.com/watch?v=BJ1aOACfYQE)
>
>
>
* Checks for `BXBXBX`/`BBB` patterns to bow (or hit you) when you're bowing.
* Checks for `GXGXGX` patterns to bow when you're guarding.
* If his random bravery roll overcomes his fear threshold for that round, he'll try for a hit.
+ Having a Sword of the Gods makes him braver.
+ An opponent with a Sword of the Gods makes him more fearful.
+ An opponent who leads by at least 5 Health or more also makes him a little scared.
* Otherwise, he takes turns guarding and bowing.
**If you want to write a Node.js submission**, please feel free to use my boilerplate code; everything up to an including the `decide` function is fully general and free to take.
---
```
node coward.js
```
---
```
var argv = process.argv;
var history = argv.length>6?argv[2]:"";
var enemyHistory = argv.length>6?argv[3]:"";
var offset = 8 - argv.length;
var my = { health:+argv[4-offset], honor:+argv[6-offset], history:history };
var enemy = { health:+argv[5-offset], honor:+argv[7-offset], history:enemyHistory };
my.godSword = my.honor >= 7;
enemy.godSword = enemy.honor >= 7;
function decide() {
process.stdout.write(arguments[Math.floor(arguments.length*Math.random())]);
process.exit();
}
var enemyGuards = !!enemy.history.match(/G.G.G.$/);
var enemyBows = !!enemy.history.match(/(B.B.B.$)|(BBB$)/);
// open with a bow
if(!my.history) { decide("B"); }
// enemy will likely bow? Hit them with your super sword! (or bow)
if((!enemy.honor || enemyBows)) {
if(my.godSword) { decide("P","I","O"); }
else { decide("B"); }
}
// no point in hitting them if they're going to guard
if(enemyGuards) { decide("B"); }
// calculate bravery level
var braveryLevel = 0.3;
braveryLevel += (my.godSword * 0.2) - (enemy.godSword * 0.2);
braveryLevel -= (enemy.health - my.health > 5) * 0.1;
// if we're feeling brave, hit them
if(Math.random() < braveryLevel && my.honor) { decide("P","I","O"); }
// if we didn't just guard, and we're not feeling brave, cower in fear
if(!my.history.match(/G$/)) {
decide("G");
}
// if we did just guard, and we're feeling cowardly,
// if we don't have sword of the gods, bow
// otherwise, do anything except guard
if(!my.godSword) {
decide("B");
} else {
decide("B","P","I","O");
}
```
[Answer]
# Whack-a-mole (R)
Strikes when enemy is likely to bow, else guards.
```
args <- commandArgs(TRUE)
L <- length(args)
my_health <- as.integer(args[L-3])
enemy_health <- as.integer(args[L-2])
my_honour <- as.integer(args[L-1])
enemy_honour <- as.integer(args[L])
if(L>4){enemy_history <- args[L-4]}else{enemy_history <- ""}
if(my_honour<1){
out <- "B"
}else if (enemy_honour<=1 | grepl("BB$",enemy_history)){
out <- sample(c("I","O"),1)
}else{
out <- "G"
}
cat(out)
```
Run using `Rscript Whack-a-mole.R`.
[Answer]
# Elephant Warrior (Java)
The Elephant Warrior is from an older, more natural time. He has seen much, and remembers all. He curries favor with the gods while he examines his opponent, and then once he takes them into his heart, he takes them apart.
Compile: `javac ElephantWarrior.java`
Command: `java ElephantWarrior`
```
import java.util.LinkedList;
//Elephants never forget
class ElephantWarrior
{
static LinkedList<Choice> analysis = new LinkedList<Choice>();
public static void main(String[] args){
if(args.length < 6){ respond("B");}
String myhis = args[0];
String enHis = args[1];
int health = Integer.parseInt(args[2]);
int enHealth = Integer.parseInt(args[3]);
int honour = Integer.parseInt(args[4]);
int enHonour = Integer.parseInt(args[5]);
//Bow a few times until I know how he operates
if(enHis.length() <= 5){
respond("B");
}
//Special cases
//If I'm at 0 honor, better bow
else if(honour <= 0){
respond("B");
}
else{
analyze(enHis);
//Narrow it down to applicable choices
char hisLast = enHis.toCharArray()[enHis.toCharArray().length - 1];
LinkedList<Choice> hisOptions = new LinkedList<Choice>();
for(Choice c: analysis){
if(c.pattern.toCharArray()[0] == hisLast){
hisOptions.add(c);
}
}
//Default to assuming they bow
char hisNext = 'B';
int mostLikely = 0;
//What will they do next?
for(Choice c : hisOptions){
if(c != null && c.probability > mostLikely){
//System.out.println("Option = " + c.pattern);
//System.out.println("Prob = " + c.probability);
mostLikely = c.probability;
hisNext = c.pattern.toCharArray()[1]; }
}
//Now go through potential case
switch(hisNext){
case 'W':
respond("I");
break;
case 'B':
respond("O");
break;
case 'G':
respond("B");
break;
case 'I':
if(enHonour > 0){
respond("P");
}
else{
respond("B");
}
break;
case 'P':
respond("O");
break;
case 'O':
respond("I");
break;
default:
respond("G");
}
}
}
static void analyze(String his){
//Keep track of his previous moves
char[] shortString = his.substring(1,his.length() - 1).toCharArray();
char[] longString = his.toCharArray();
for( int i = 0; i < shortString.length; i++) {
String pattern = "" + longString[i] + shortString[i];
boolean exists = false;
for(Choice c : analysis){
if(c.pattern.equals(pattern)){
exists = true;
c.probability++;
}
}
if(!exists){
analysis.add(new Choice(pattern, 1));
}
}
}
private static void respond(String s){
System.out.println(s);
System.exit(0);
}
}
class Choice{
String pattern;
int probability;
Choice(String p, int i){
pattern = p;
probability = i;
}
}
```
[Answer]
# Warrior Princess (Julia)
This is the first King of the Hill challenge I've competed in. Let's see how this goes.
The Warrior Princess prioritizes attack and honor, and resorts to self-preservation when needed. She's rather eager and never waits. In an effort to remain nimble, she also doesn't use an overhead attack.
---
Save as `warrior-princess.jl` and run from the command line like so:
```
julia warrior-princess.jl <arguments>
```
If you don't have Julia, you can download it [here](http://julialang.org/downloads). To avoid issues, the latest stable version is recommended (i.e. not the development version).
---
```
type Samurai
history::String
health::Int
honor::Int
end
A = length(ARGS) < 5 ? ["", "", ARGS] : ARGS
me = Samurai(A[1], int(A[3]), int(A[5]))
opponent = Samurai(A[2], int(A[4]), int(A[6]))
if length(me.history) == 0
# Always begin the match with an honorable bow
action = "B"
elseif (!ismatch(r"[OIP]", opponent.history) && me.history[end] != 'G') ||
(me.health < 2 && me.honor > 0)
# Guard if the enemy has not yet attacked and I did not previously
# guard, or if my health is low and my honor is sufficient
action = "G"
elseif me.honor < 2
# Bow if I'm low on honor
action = "B"
elseif opponent.honor >= 7 && opponent.history[end] ∈ ['B', 'W']
# Assume the enemy will attack with the Sword of the Gods if they
# most recently bowed or waited
action = "I"
else
action = "P"
end
println(action)
```
[Answer]
# Gargoyle (Java)
Tries to use the defensive move without consuming honor.
Since it's a java entry:
```
> javac Gargoyle.java
> java Gargoyle
```
```
public class Gargoyle {
public static void main(String args[]) {
if (args.length < 5 || Integer.valueOf(args[4]) > 0) {
System.out.println("IPO".charAt((int)(Math.random()*3)));
} else if (args[0].charAt(args[0].length()-1) != 'G') {
System.out.println('G');
} else {
System.out.println('B');
}
}
}
```
[Answer]
# Swordsman (C/Java)
Swordsman bows on the first turn and whenever he is running low on honor. He then checks if the opponent hadn't bowed or defended or waited in the previous turn. If the opponent hadn't, there is a big probability that he will do one of these in the current turn and swordsman thus randomly strikes on the opponent. If this isn't true, he defends if he hasn't defended the previous turn. If he had, he bows to gain honor.
**C version:**
```
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_and_exit(char* str)
{
puts(str);
exit(0);
}
int main(int argc, char** argv){
srand(time(NULL));
char* attack_moves[]={"I", "P", "O"};
int random_num = rand() % 3;
if(argc == 5 || atoi(argv[5]) == 0)
print_and_exit("B");
else if(argv[2][strlen(argv[2])-1] != 'B' && argv[2][strlen(argv[2])-1] != 'G' && argv[2][strlen(argv[2])-1] != 'W')
print_and_exit(attack_moves[random_num]);
else if(argv[1][strlen(argv[1])-1] != 'G')
print_and_exit("G");
print_and_exit("B");
}
```
Install GCC (compiler) and save the code into a file named "*Swordsman.c*" command for compiling:
```
gcc Swordsman.c -o Swordsman
```
Executable named "*Swordsman*" will be created. Run using
```
Swordsman
```
**Java version:**
```
public class Swordsman {
public static void print_and_exit(String str)
{
System.out.println(str);
System.exit(0);
}
public static void main(String[] argv) {
String attack_moves[]={"I", "P", "O"};
int random_num = (int)(Math.random()*3);
if(argv.length == 4 || Integer.valueOf(argv[5]) == 0)
print_and_exit("B");
else if(argv[2].charAt(argv[2].length()-1) != 'B' && argv[2].charAt(argv[2].length()-1) != 'G' && argv[2].charAt(argv[2].length()-1) != 'W')
print_and_exit(attack_moves[random_num]);
else if(argv[1].charAt(argv[1].length()-1) != 'G')
print_and_exit("G");
print_and_exit("B");
}
}
```
Install javac (compiler) and save the code into a file named "*Swordsman.java*" command for compiling:
```
javac Swordsman.java
```
Class file named "*Swordsman.class*" will be created. Run using
```
java Swordsman
```
---
---
# Attacker (Java)
Attacker doesn't care about anything except that he wants his opponent dead. He randomly strikes one of the attack moves and if has low honor, bows.
```
public class Attacker {
static int position = -1;
public static void print_and_exit(String str)
{
System.out.println(str);
System.exit(0);
}
public static void main(String[] argv) {
String attack_moves[]={"I", "P", "O"};
position = (position + 1) % 3;
if(argv.length != 5 && Integer.valueOf(argv[5]) == 0)
print_and_exit("B");
else
print_and_exit(attack_moves[position]);
}
}
```
Install javac (compiler) and save the code into a file named "*Attacker.java*" command for compiling:
```
javac Attacker.java
```
Class file named "*Attacker.class*" will be created. Run using
```
java Attacker
```
---
---
# Predictor (C/Java)
Predictor predicts the enemies moves. In the first turn, it uses a random move. Bows if his honor is low, strikes if the enemies honor is low or has bowed in the previous turn. If predictor hasn't guarded the previous turn, guards in the current turn. Else, does the same move as the enemy has done in the previous turn, provided that it isn't `'W'` in which case, Predictor bows.
**C version:**
```
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
void print_and_exit(char* str)
{
puts(str);
exit(0);
}
int main(int argc, char** argv){
srand(time(NULL));
int random = rand() % 5;
char* moves[] = {"B", "G", "I", "P", "O"};
if(argc == 5)
print_and_exit(moves[random]);
if(atoi(argv[5]) <= 0)
print_and_exit(moves[0]);
if(atoi(argv[6]) <= 0)
print_and_exit(moves[4]);
if(argv[2][strlen(argv[2])-1] == 'G')
print_and_exit(moves[4]);
if(argv[1][strlen(argv[1])-1] != 'G')
print_and_exit(moves[1]);
if(argv[2][strlen(argv[2])-1] != 'W'){
char buf[2]={0};
*buf = argv[2][strlen(argv[2])-1];
print_and_exit(buf);
}
print_and_exit(moves[0]);
}
```
Install GCC (compiler) and save the code into a file named "*Predictor.c*" command for compiling:
```
gcc Predictor.c -o Predictor
```
Executable named "*Predictor*" will be created. Run using
```
Predictor
```
**Java version:**
```
public class Predicator{
public static void print_and_exit(String str)
{
System.out.println(str);
System.exit(0);
}
public static void main(String[] argv){
int random = (int)(Math.random() * 5);
String moves[] = {"B", "G", "I", "P", "O"};
if(argv.length == 4)
print_and_exit(moves[random]);
else if(Integer.valueOf(argv[5]) <= 0)
print_and_exit(moves[0]);
else if(Integer.valueOf(argv[6]) <= 0)
print_and_exit(moves[4]);
else if(argv[2].charAt((argv[2].length())-1) == 'G')
print_and_exit(moves[4]);
else if(argv[1].charAt((argv[1].length())-1) != 'G')
print_and_exit(moves[1]);
else if(argv[2].charAt((argv[1].length())-1) != 'W'){
print_and_exit(""+argv[2].charAt((argv[2].length())-1));
}
else
print_and_exit(moves[0]);
}
}
```
Install javac (compiler) and save the code into a file named "*Predicator.java*" command for compiling:
```
javac Predicator.java
```
Class file named "*Predicator.class*" will be created. Run using
```
java Predicator
```
---
Not sure how effective these bots will be as I don't have the python2 interpreter to test it.
[Answer]
# Master Yi (Python)
The master assassin gains much favor in the early game, building it up until he's invincible. Tries to attack when they least expect it.
```
import sys, random
class MasterYi(object):
def __init__(self):
self.attack = lambda: random.choice(['I','P','O'])
self.bow = "B"
self.guard = "G"
self.wait = "W"
if len(sys.argv)>6:
self.hist = sys.argv[1]; self.ohist = sys.argv[2]
self.hp = sys.argv[3]; self.ohp = sys.argv[4]
self.hon = sys.argv[5]; self.ohon = sys.argv[6]
else:
self.hist = []; self.ohist = []
self.hp = sys.argv[1]; self.ohp = sys.argv[2]
self.hon = sys.argv[3]; self.ohon = sys.argv[4]
self.last = self.hist and self.hist[-1] or "W"
self.olast = self.ohist and self.ohist[-1] or "W"
self.oGuarder = len(self.ohist)>4 and self.ohist[-4]==self.ohist[-2]=="G"
def move(self):
if self.hon < 1: return self.bow
if self.olast == "G": return self.attack
if self.hon > 6:
if self.oGuarder: return self.bow
if self.ohon > 6: return self.guard
if self.ohon < 7: return self.attack
return self.attack
if self.ohon > 6: return self.guard
return self.bow
Yi = MasterYi()
print(Yi.move())
```
To run:
Save as `MasterYi.py`
```
python MasterYi.py <args>
```
[Answer]
# Copy-san (C)
Copies every move of his opponent. Pretty sure he's guaranteed to lose.
Compile: `gcc copy-san.c`
```
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc == 5) {
putchar('B');
} else {
char *enemy_hist = argv[2];
size_t len = strlen(enemy_hist);
putchar(enemy_hist[len - 1]);
}
putchar('\n');
return 0;
}
```
[Answer]
## Hebi (Java)
Hebi follow The Way Of The Snake.
The Snake has no need for the blessing of the gods.
The Snake slithers its strikes; like waves upon the beach, what comes in recedes back the way it came.
The Snake never waits.
The Snake has no sense of aptness, elsewise it would've been written in Python.
Running instructions:
```
> javac hebi.java
> java hebi
```
Code body:
```
public class hebi{
public static void main(String args[]){
if( (args.length < 5) || (args[0].length() % 18 == 0) ) System.out.println( "IPO".charAt((int)(Math.random()*3)) );
else{
int hist_size = args[0].length();
if (hist_size % 3 == 1) System.out.println("G");
else if (hist_size % 3 == 2) System.out.println("B");
else{
if (hist_size % 18 == 9) System.out.println(args[0].charAt(hist_size - 3));
else if(hist_size % 18 == 12) System.out.println(args[0].charAt(hist_size - 9));
else if(hist_size % 18 == 15) System.out.println(args[0].charAt(hist_size - 15));
else{
char move_head = args[0].charAt( (hist_size / 18) * 18 );
char move_mid;
if( hist_size % 18 == 3 ){
if ( move_head == 'I' ) move_mid = "PO".charAt((int)(Math.random()*2));
else if( move_head == 'O' ) move_mid = "IP".charAt((int)(Math.random()*2));
else move_mid = "OI".charAt((int)(Math.random()*2));
System.out.println(move_mid);
}
else{
move_mid = args[0].charAt( ((hist_size / 18) * 18) + 3 );
char move_tail;
if( move_head == 'I' ){
if( move_mid == 'P' ) move_tail = 'O';
else move_tail = 'P';
}else if( move_head == 'P' ){
if( move_mid == 'O' ) move_tail = 'I';
else move_tail = 'O';
}else{
if( move_mid == 'I' ) move_tail = 'P';
else move_tail = 'I';
}
System.out.println( move_tail );
}
}
}
}
}
}
```
[Answer]
# The Honourable (Java)
The Honourable values honor above all. That is, his honor above everyone else's. If the enemy samurai has greater or equal honor, he bows. None shall be more honorable than he. Otherwise, he does a random move. He never guards twice in a row - that would be dishonorable!
to compile:
```
> javac TheHonourable.java
> java TheHonourable
```
Source:
```
public class TheHonourable {
public static void main(String[] args) {
char move;
if (args.length < 5) {
move = 'B';
} else if (Integer.valueOf(args[5]) >= Integer.valueOf(args[4])){
move = 'B';
} else {
move = (args[0].endsWith("G")) ?
"IPO".charAt((int)(Math.random()*3)) :
"GIPO".charAt((int)(Math.random()*4));
}
System.out.print(move);
}
}
```
[Answer]
# Blessed Samurai (Python)
This Samurai tries to keep the gods' favor for a long as possible. He rushes to get the holy sword, then alternates between Guarding and Attacking with one of the strikes, restocking honour when needed. If it looks like either he or his opponent may soon fall, he rushes in for a kill. He will easily fall to an oponent that can track his pattern, but his strategy of always attacking at two damage should be pretty effective.
```
import sys
import random
class BlessedSamurai(object):
def __init__(self):
if len(sys.argv) < 7:
print("B")
else:
self.attack = ['O', 'I', 'P']
self.hp = sys.argv[3]
self.ohp = sys.argv[4]
self.hon = sys.argv[5]
self.last = sys.argv[1][-1]
print(self.move())
def move(self):
#check if I have low health or should rush the kill
if (self.hp < 5 or self.ohp < 5) and self.hon > 0:
return(random.choice(self.attack))
# charge honour to get SOTG
elif self.hon < 7:
return 'B'
#Alternate guarding and attacking
else:
if self.last == 'G':
return(random.choice(self.attack))
return 'G'
Sam = BlessedSamurai()
```
---
To run:
Save as BlessedSamurai.py
```
python BlessedSamurai.py <args>
```
[Answer]
# Hermurai (C++)
Admires his opponent, and is a little paranoid. Wants to know if he can do what other samurai can, because he still can't believe himself to be a samurai. His never-fading dream became reality before him knowing it. Which could cost his head...
```
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
char getLastAttack(string enemy_history)
{
size_t found = enemy_history.find_last_of("IPO");
if(found == string::npos)
{
return 'I';
}
return enemy_history[found];
}
int main(int argc, const char * argv[])
{
if(argc != 7){
printf("B");
return 0;
}
string enemy_history(argv[2]);
int ho;
string honour(argv[5]);
stringstream(honour) >> ho;
if(ho > 20){
char atk = getLastAttack(enemy_history);
printf("%c", atk);
return 0;
}
char lastMove = enemy_history[enemy_history.length()-1];
if(lastMove == 'W' || lastMove == 'G')
lastMove = 'B';
printf("%c", lastMove);
return 0;
}
```
---
# Iniqy (C++)
Strikes as hard as possible. Goes into unstoppable attack mode when he is in danger.
```
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
char getLastAttack(string enemy_history)
{
size_t found = enemy_history.find_last_of("IPO");
if(found == string::npos)
{
return 'I';
}
return enemy_history[found];
}
int main(int argc, const char * argv[])
{
if(argc != 7){
printf("B");
return 0;
}
string history(argv[1]);
string enemy_history(argv[2]);
string health(argv[3]);
string enemy_health(argv[4]);
string honour(argv[5]);
string enemy_honour(argv[6]);
int he, enemy_he, ho, enemy_ho;
stringstream(health) >> he;
stringstream(enemy_health) >> enemy_he;
stringstream(honour) >> ho;
stringstream(enemy_honour) >> enemy_ho;
if(ho > 6 || ((he < 6 || enemy_he < 6) && ho > 0))
{
char atk = getLastAttack(enemy_history);
printf("%c", atk);
return 0;
}
printf("B");
return 0;
}
```
---
Both are written in C++.
To compile:
```
g++ iniqy.cpp -o iniqy
```
To run on Linux:
`./iniqy`
To run on Windows:
`iniqy.exe`
[Answer]
# The Terminator (ruby)
The Terminator doesn't pay attention to his own health. The Terminator has no notion of honor. The Terminator is sent from the future and simply determined to terminate its opponent. It does so by watching its opponents moves, and nothing else. It samples the moves and calculates the appropriate response in such an intricate manner that no present-day technology can predict the Terminator's actions. In fact, to anyone living in 2015 the Terminator may seem somewhat random ...
```
responses = {
?W => %w(B I),
?B => %w(I O),
?G => %w(B B),
?I => %w(G P),
?P => %w(B O),
?O => %w(G I)
}
if ARGV.size > 4
pool = ARGV[1].chars.map{ |c| responses[c] }.flatten
puts pool.sample
else
puts %w(O I P B).sample
end
```
[Answer]
# Agent 38[1] (C)
As a product of extensive genetic manipulation, Agent 38 has the physique and mental acuity of a super[2]-samurai, and is definitely superior to all its helplessly[citation needed] flawed[citation needed] competitors.
---
```
//Agent 38
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifdef _WIN32
#include <Windows.h>
unsigned int tick_count(){
return GetTickCount();
}
#else
#include <sys/time.h>
unsigned int tick_count(){
struct timeval t;
gettimeofday(&t, NULL);
return 1000 * t.tv_sec + t.tv_usec / 1000;
}
#endif
float program[5][4][4][4][4]={
{{{{-1.192779,0.693321,-1.472931,-0.054087},{0.958562,0.557915,0.883166,-0.631304},{-0.333221,1.410731,0.496346,0.087134},{0.459846,0.629780,-0.479042,-0.025909}},{{0.547976,1.059051,-0.748062,-0.675350},{-0.607591,-0.152156,-0.400350,-0.685337},{1.686450,0.628706,0.312865,0.324119},{1.652558,0.403733,-0.456481,-0.081492}},{{0.371629,-0.036948,-0.982682,0.065115},{1.360809,0.681294,0.505074,0.782737},{-0.545192,0.954937,-0.727853,0.273542},{-0.575777,1.615253,-0.064885,-0.516893}},{{0.577015,-0.112664,0.456595,-0.007560},{-0.660930,-0.738453,0.668093,1.716388},{1.972322,0.108558,0.535114,-0.337916},{0.640208,-0.019680,-0.769389,0.873087}}},{{{-0.021140,-0.095956,-0.098309,-0.280295},{-0.926284,1.724028,0.278855,0.678060},{0.153006,-1.860947,-0.577699,-1.931683},{-0.187152,0.529719,-1.164157,0.125499}},{{0.582208,-0.835029,-0.329857,0.088176},{-0.030797,0.389396,0.584636,-0.025866},{-0.736538,1.624658,0.690493,0.387515},{0.973253,-0.530825,1.934379,-0.872921}},{{0.812884,0.138399,-1.452478,-1.504340},{-0.119595,0.986078,-0.993806,1.102894},{0.848321,-0.268764,0.876110,0.782469},{0.948619,-0.557342,0.749764,-0.712915}},{{-1.195538,0.783784,-1.973428,-0.873207},{0.085426,-0.241360,-0.534561,-0.372105},{0.029696,-0.906821,0.932227,-0.834607},{0.764903,-0.276117,-1.346102,-0.093012}}},{{{0.168113,0.855724,1.817381,-0.547482},{0.468312,0.923739,-0.723461,0.798782},{-0.875978,-0.942505,-0.684104,-0.046389},{0.893797,-0.071382,0.283264,0.811233}},{{0.391760,0.309392,-0.045396,-0.977564},{0.085694,0.257926,-0.775461,0.060361},{0.486737,-0.175236,0.806258,-0.196521},{0.691731,-0.070052,0.636548,0.464838}},{{0.532747,-1.436236,-0.900262,-0.697533},{0.566295,0.650852,0.871414,-0.566183},{-0.075736,-0.886402,0.245348,-0.438080},{-0.811976,0.022233,-0.685647,0.323351}},{{-1.864578,1.141054,1.636157,-0.455965},{0.592333,0.890900,-0.259255,0.702826},{0.404528,0.905776,0.917764,0.051214},{0.761990,0.766907,-0.595618,-0.558207}}},{{{0.209262,-1.126957,-0.517694,-0.875215},{0.264791,0.338225,0.551586,0.505277},{0.183185,0.782227,0.888956,0.687343},{0.271838,0.125254,1.071891,-0.849511}},{{0.261293,-0.445399,0.170976,-0.401571},{0.801811,0.045041,-0.990778,-0.013705},{-0.343000,-0.913162,0.840992,0.551525},{-0.526818,-0.231089,0.085968,0.861459}},{{0.540677,-0.844281,-0.888770,0.438555},{0.802355,-0.825937,0.472974,-0.719263},{-0.648519,1.281454,0.470129,-0.538160},{-0.851015,0.985721,-0.993719,0.558735}},{{1.164560,-0.302101,0.953803,0.277318},{0.886169,0.623929,1.274299,-0.559466},{-0.948670,0.807814,-1.586962,-0.502652},{-0.069760,1.387864,-0.423140,0.285045}}}},
{{{{0.747424,-0.044005,0.402212,-0.027484},{0.785297,0.169685,0.734339,-0.984272},{-0.656865,-1.397558,0.935961,-0.490159},{-0.099856,-0.293917,0.129296,-0.920536}},{{0.546529,-0.488280,-0.516120,-1.112775},{0.155881,-0.103160,0.187689,0.485805},{0.918357,0.829929,0.619437,0.877277},{0.389621,0.360045,0.434281,0.456462}},{{-0.803458,-0.525248,-0.467349,0.714159},{-0.648302,-0.005998,-0.812863,0.205664},{0.591453,0.653762,-0.227193,-0.946375},{0.080461,0.311794,0.802115,-1.115836}},{{-0.495051,-0.869153,-0.179932,0.925227},{-1.950445,1.908723,-0.378323,-0.472620},{-0.688403,-1.470251,1.991375,-1.698926},{-0.955808,-0.260230,0.319449,-1.368107}}},{{{-0.029073,-0.622921,-1.095426,-0.764465},{-0.362713,-0.123863,0.234856,-0.772613},{0.697097,0.103340,0.831709,0.529785},{0.103735,-0.526333,-0.084778,0.696831}},{{-0.670775,0.289993,-0.082204,-1.489529},{0.336070,0.322759,0.613241,0.743160},{0.298744,-1.193191,0.848769,-0.736213},{0.472611,-0.830342,0.437290,-0.467557}},{{-0.529196,-0.245683,0.809606,-0.956047},{-1.725613,0.187572,0.528054,-0.996271},{-0.330207,0.206237,0.218373,0.187079},{0.243388,0.625787,-0.388859,0.439888}},{{-0.802928,-0.811282,0.788538,0.948829},{0.966371,1.316717,0.004928,0.832735},{-0.226313,0.364653,0.724902,-0.579910},{-0.544782,-0.143865,0.069256,-0.020610}}},{{{-0.393249,0.671239,-0.481891,0.861149},{-0.662027,-0.693554,-0.564079,-0.477654},{0.070920,-0.052125,-0.059709,0.473953},{-0.280146,-0.418355,0.703337,0.981932}},{{-0.676855,0.102765,-0.832902,-0.590961},{1.717802,0.516057,-0.625379,-0.743204},{-0.170791,-0.813844,-0.269250,0.707447},{0.057623,0.472053,-0.211435,0.147894}},{{-0.298217,0.577550,1.845773,0.876933},{0.617987,0.502801,0.951405,0.122180},{0.924724,-0.166798,0.632685,-0.466165},{-0.834315,-0.864180,-0.274019,0.568493}},{{0.669850,-0.961671,0.790462,0.738113},{-0.534215,-0.556158,0.653896,0.031419},{0.065819,0.220394,0.153365,-0.373006},{0.886610,-0.742343,1.282099,0.198137}}},{{{0.092579,-0.026559,-1.121547,0.143613},{-0.289030,0.265226,-0.350741,-0.897469},{-0.918046,0.038521,-1.515900,0.488701},{-0.759326,-1.782885,-1.787784,0.249131}},{{-0.849816,-0.857074,-0.843467,-0.153686},{0.998653,0.356216,0.926775,0.300663},{-0.749890,-0.003425,-0.607109,0.317334},{-0.561644,0.446478,-0.898901,0.711265}},{{0.232020,-0.445016,0.618918,0.162098},{0.381030,-0.036170,0.084177,0.766972},{0.493139,0.189652,-0.511946,-0.273525},{0.863772,-0.586968,0.829531,-0.075552}},{{0.191787,-0.627198,0.975013,-0.448483},{-0.197885,0.151927,-0.558646,-1.308541},{-0.582967,1.207841,0.746132,0.245631},{0.314827,-0.702463,-0.301494,0.787569}}}},
{{{{0.670028,-1.825749,-0.739187,0.482428},{0.175521,-0.020120,-0.154805,0.187004},{0.971728,-0.160181,-0.164031,-0.868147},{-0.954732,-0.175713,0.791116,0.294173}},{{-0.958337,-0.843157,-0.472882,0.273517},{-0.999058,0.824762,-0.223130,-0.150628},{0.393747,-0.301297,0.095572,-0.798950},{-0.119787,0.746673,0.955094,0.259353}},{{0.951590,0.225539,0.503282,0.668746},{-0.384898,-0.979592,-0.005485,-0.191883},{-0.692369,-0.642401,-0.825598,0.171933},{-0.321919,-0.498635,0.449704,0.780842}},{{-0.387902,0.522435,0.565608,0.166193},{-0.799671,-0.295871,-0.702573,-0.151006},{0.040550,-0.468503,0.651076,0.636352},{-0.839299,-0.090651,0.428761,0.187043}}},{{{-0.369823,0.377011,0.422936,0.284752},{-0.181514,-0.701449,0.748768,0.540533},{0.734381,0.149410,-0.867043,-0.397142},{-0.770904,-0.581897,-1.578306,-0.402638}},{{0.859015,-0.540358,0.202715,-0.975354},{-0.773629,-0.382342,-0.022498,-0.129286},{-0.901210,-0.641866,1.219216,0.731525},{0.740457,0.858546,-0.408661,-0.364897}},{{-0.830865,-1.370657,-1.226303,-0.392147},{-0.810554,-0.975232,-0.717845,-0.825379},{-0.150096,-0.664533,0.347084,0.243443},{-0.447383,0.842164,1.491342,0.380295}},{{-0.383958,0.811219,0.160459,0.841601},{1.631515,0.371637,0.110000,0.467783},{-0.689356,-0.004289,-0.081057,-0.317243},{0.092451,-0.181268,-0.575747,-0.580061}}},{{{0.908549,-0.013975,-0.880165,-0.938937},{-0.225713,0.449478,0.372569,-0.229889},{0.255711,-0.264752,0.307982,0.260505},{0.314966,-0.540905,0.743032,-0.078475}},{{-0.307472,-1.268296,0.020383,1.798401},{-0.150954,0.909716,-0.407903,0.379046},{0.621853,-0.003629,-0.582697,0.614618},{-0.122843,-0.627133,-0.217968,0.608322}},{{0.071923,0.807315,0.538905,-0.630660},{0.495641,0.240202,-0.920822,-0.258533},{-1.760363,-0.448525,-0.351553,-0.551666},{0.152720,0.900531,0.061966,-0.544377}},{{0.648923,0.450945,-1.530020,1.570190},{0.536210,0.078454,0.577168,0.464872},{-0.888258,-0.950748,0.781474,0.958593},{0.463631,0.319614,-0.248374,-0.413144}}},{{{0.293463,0.236284,1.721511,0.107408},{-0.790508,-0.072027,-0.559467,-0.955839},{-0.777662,-0.169876,0.896220,0.776105},{0.003944,-0.745496,-0.236446,-0.824604}},{{-1.770746,-0.051266,-0.174258,0.003074},{-0.339553,-0.868807,-0.032754,-0.494847},{-0.896712,0.957339,-0.003444,-1.582125},{-0.699883,0.626691,0.799635,-0.542343}},{{-0.635123,-0.755960,0.576373,-0.899530},{-0.393745,0.718900,0.312400,0.511415},{-0.647565,0.368431,0.214726,0.892693},{-0.511960,-0.513262,0.885908,-0.536478}},{{-0.590074,0.623328,0.268674,-0.401391},{0.308868,-0.869862,0.233132,0.243337},{-0.242908,-0.557192,-0.728454,0.867029},{0.156435,-0.805308,-0.815392,-1.437798}}}},
{{{{0.613484,1.454566,-0.363858,0.634053},{0.535096,-0.641079,-0.607553,0.852559},{0.959100,-0.398621,0.375819,0.385756},{-0.601982,0.494128,0.809699,0.608804}},{{-1.390871,-0.943062,1.556671,0.966501},{-0.013242,0.152716,-0.089592,0.230793},{0.933785,0.119358,0.057387,0.502033},{-0.332925,0.537509,-0.081436,-0.701995}},{{-0.435117,0.996885,0.646630,-0.092342},{0.004343,-0.737514,-0.716187,-0.946819},{0.814258,-0.766971,-0.488162,-0.531619},{-0.923069,0.683915,-0.023809,-1.242992}},{{-0.909155,-0.166488,-0.159273,-0.908121},{-0.783871,-0.522598,0.691845,-0.164065},{1.255966,0.051373,-0.566025,0.820081},{0.186583,0.266032,-0.793747,-0.510092}}},{{{0.890639,0.970042,-0.507885,-0.029557},{-0.771142,-0.875802,0.400070,-1.264247},{-0.881146,0.570950,-0.051624,0.347612},{0.312110,-0.374885,0.600112,0.388460}},{{-0.417107,-0.309284,-0.128477,0.689671},{-0.695866,1.254585,-0.381883,-0.313415},{0.433565,0.919626,0.159180,-0.657310},{-1.396139,0.346053,0.108768,0.061238}},{{-0.776695,0.084491,0.045357,0.312823},{-0.379268,1.217006,-0.014838,-1.032272},{-1.251344,-0.366283,-0.124786,0.729754},{0.979936,0.669519,-0.900018,-0.596954}},{{-0.998834,0.593942,0.375639,-0.627459},{0.297281,0.400240,0.839707,0.960262},{-0.872143,0.574040,-0.559580,-1.965570},{-0.559218,-0.778780,-0.955526,-0.253380}}},{{{-1.919625,-1.911049,0.025035,0.754917},{-0.110993,0.535933,-0.572788,-0.856476},{-0.810836,-0.496261,1.128368,1.758826},{-0.564368,-1.849772,-0.251560,0.635528}},{{0.768196,-0.934122,0.207228,0.884610},{-0.356145,0.265792,-0.835582,0.377675},{-0.410745,0.613212,0.245560,-0.873826},{1.725191,-0.263344,-0.077167,-0.976379}},{{-0.736299,-0.109476,0.044512,-0.004005},{0.692230,0.316670,0.267247,-1.076821},{-0.903184,0.189762,-0.674111,0.219113},{0.639162,1.347521,0.428823,-0.765664}},{{-0.509165,0.458806,-0.851011,0.455027},{-0.218564,-0.063492,0.889320,-0.762062},{0.145950,0.985037,-0.489372,-0.879851},{0.352346,-0.127275,0.896496,-0.596037}}},{{{0.402678,1.479855,0.089187,0.967153},{-0.431225,0.402980,0.883584,-0.900324},{0.262233,-0.647278,0.637005,0.142678},{-0.003253,-0.671924,0.969458,-0.316752}},{{0.345185,-0.477503,-0.326822,-0.106251},{0.239521,1.617125,0.632651,0.969976},{-1.015183,-0.676629,0.955842,0.134925},{-0.319063,-0.493157,-0.488088,0.713008}},{{-0.468621,1.301292,-1.826501,1.138666},{0.170247,-0.661171,0.895204,-0.400700},{-0.077645,-0.978179,-0.245724,0.245282},{-0.258300,0.287261,-0.006274,0.549716}},{{-0.932247,-0.274950,0.920451,0.016237},{0.888865,-0.845248,1.661716,-0.108960},{0.712357,0.586609,-0.867356,0.355058},{-0.540912,0.892622,0.302627,0.247194}}}},
{{{{0.817578,0.719047,0.438903,0.637398},{0.750466,-0.911799,-0.609606,0.358541},{-1.782979,-0.851717,-0.802122,0.735913},{0.490604,-0.417822,-0.332074,0.836756}},{{-0.650232,-0.442026,0.874916,0.705671},{0.217602,-0.755841,0.573944,0.279365},{-0.713729,0.358880,-0.308992,0.778297},{0.832099,-0.916695,-0.887834,1.041483}},{{1.019467,1.099488,-0.130674,-0.241995},{0.792572,0.756977,0.518186,0.070411},{-0.815779,-0.790757,-1.027439,-0.163698},{0.721461,-0.403364,0.656609,-0.367364}},{{-0.279333,-0.742041,0.515832,-0.408114},{0.834577,0.736056,0.900594,0.276357},{0.726000,0.464991,-0.569281,0.098139},{-0.582324,0.875666,-0.681556,-0.903009}}},{{{1.300969,-0.798351,0.107230,1.611284},{0.239211,0.418231,-0.795764,-0.398818},{-0.939666,1.768175,-0.297023,-0.064087},{-0.239119,-0.365132,0.864138,0.595560}},{{1.898313,-0.343816,1.066256,0.876655},{-0.053636,0.544756,-0.937927,0.189233},{0.445371,-0.656790,-0.675091,0.753163},{-0.293330,-0.002717,0.341173,0.095493}},{{0.951658,0.513912,-0.678347,-0.981140},{-0.020791,0.571138,-0.890648,0.881789},{-1.783345,0.909598,-0.393155,0.240630},{-0.057908,-0.237435,-0.124993,-0.754091}},{{-0.014153,0.127172,0.097134,0.538952},{0.167943,0.786395,0.946153,-0.762513},{-0.562758,0.675657,-0.226395,0.979761},{0.850214,0.818309,0.397074,-0.372059}}},{{{0.803316,-0.659538,-1.987864,-0.186366},{-0.259213,0.315848,-0.427898,0.326521},{-0.168181,-0.620898,0.562309,0.722064},{-1.949690,0.307720,-0.147760,0.603492}},{{0.898339,0.986228,0.724530,0.105193},{0.066046,0.037689,-0.553543,0.597864},{0.296553,0.165199,0.500125,-0.395978},{0.790120,-1.873361,0.354841,-0.187812}},{{-0.559746,0.357012,0.373903,-0.113564},{-0.671918,-0.919720,0.258328,-0.283453},{0.008365,0.597272,0.355827,0.391287},{0.355297,-0.631888,0.221383,1.448221}},{{0.259199,-0.491776,0.721151,0.391427},{0.494000,0.652814,-0.153306,-0.615687},{0.142167,-0.601161,0.281702,0.563390},{0.904019,1.284241,0.901663,0.244620}}},{{{-0.664638,-0.564596,0.839897,0.153358},{-0.506883,0.822337,-0.974957,-0.098112},{-0.962870,-0.274566,0.418039,-0.020525},{-0.965969,0.954587,-0.250493,-0.031592}},{{-0.966475,0.455338,0.868491,0.723032},{-0.002141,0.021922,-0.131429,-0.601106},{-1.240003,1.483318,1.612920,-0.653210},{-0.505979,0.005588,-0.087506,-0.705789}},{{-0.203137,0.765652,-0.132974,-0.900534},{0.731132,0.133467,-1.086363,0.600763},{1.795911,-0.411613,-1.990494,0.405937},{0.729332,-0.119175,-0.979213,0.362346}},{{-0.049014,0.228577,-1.728796,-0.898348},{-0.540969,1.245881,-0.820859,0.285859},{0.430751,-0.373652,0.034535,0.434466},{0.365354,0.243261,0.910114,1.497873}}}}
};
float eval_polynomial(float variables[4],int program_index,int variable_index,int indices[4]){
if(variable_index==4)return program[program_index][indices[0]][indices[1]][indices[2]][indices[3]];
float result=0,base=1;
for(int power=0;power<4;++power){
indices[variable_index]=power;
result+=base*eval_polynomial(variables,program_index,variable_index+1,indices);
base*=variables[variable_index];
}
return result;
}
int main(int argc,char *argv[]){
srand(tick_count());
rand();
float variables[4],probability[5],total=0;
int i,indices[4],temp;
for(i=0;i<4;++i){
sscanf(argv[i-4+argc],"%d",&temp);
variables[i]=temp;
}
temp=variables[1];
variables[1]=variables[2];
variables[2]=temp;
if(variables[1]==0){ //bow if our honour is 0
putchar('B');
return 0;
}
variables[0]/=20;variables[2]/=20;
variables[1]=1/(variables[1]+1);variables[3]=1/(variables[3]+1);
for(i=0;i<5;++i){
probability[i]=eval_polynomial(variables,i,0,indices);
if(probability[i]<0)probability[i]=0;
total+=probability[i];
probability[i]=total;
}
total*=(float)rand()/RAND_MAX;
for(i=0;i<5;++i)if(total<probability[i]){
putchar("BGIPO"[i]);
return 0;
}
putchar('B');
return 0;
}
```
---
[1] Completely irrelevant number
[2] Guaranteed to be true 1% of the time
---
# YAGMCSE
Monte Carlo methods seem to exhibit decent play, so here's Yet Another Generic Monte Carlo Simulation Entry!
Unlike most of the other entries in this contest, this entry uses a large number of simulations of random games, and thus requires the use of the -O3 flag for optimal performance.
Compile the program with the command:
*gcc monte.c -o monte -O3 -std=c99*
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <Windows.h>
unsigned int tick_count(){
return GetTickCount();
}
#else
#include <sys/time.h>
unsigned int tick_count(){
struct timeval t;
gettimeofday(&t, NULL);
return 1000 * t.tv_sec + t.tv_usec / 1000;
}
#endif
const int turn_limit=500;
enum Move{
WAIT,BOW,GUARD,QUICK,PARRY,OVERHEAD
};
struct Player{
int health,honour;
enum Move lastMove;
};
typedef struct Player Player;
//<command> <history> <enemy_history> <your_health> <enemy_health> <your_honour> <enemy_honour>
//<command> <your_health> <enemy_health> <your_honour> <enemy_honour>
int damage_table[6][6][2]={
{{0,0},{0,0},{0,0},{1,0},{1,0},{1,0}}, //P1 is waiting
{{0,0},{0,0},{0,0},{1,0},{1,0},{1,0}}, //P1 is bowing
{{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}}, //P1 is guarding
{{0,1},{0,1},{0,0},{0,0},{1,0},{0,1}}, //P1 is using quick draw
{{0,1},{0,1},{0,0},{0,1},{0,0},{1,0}}, //P1 is parrying
{{0,1},{0,1},{0,0},{1,0},{0,1},{0,0}} //P1 is using overhead attack
};
enum Move decode_move(char x){
switch(x){
case 'W': return WAIT; break;
case 'B': return BOW; break;
case 'G': return GUARD; break;
case 'I': return QUICK; break;
case 'P': return PARRY; break;
case 'O': return OVERHEAD; break;
}
return WAIT;
}
struct SimulationStat{
enum Move first_me_move;
int win,draw,lose,compound;
};
int stat_compare(const void*a,const void*b){
return ((struct SimulationStat*)b)->compound-((struct SimulationStat*)a)->compound;
}
struct SimulationStat monte_carlo(int num_iters,enum Move first_me_move,Player original_me,Player original_opponent){
struct SimulationStat simulation_result={first_me_move,0,0,0};
for(int iter=0;iter<num_iters;++iter){
Player me=original_me,opponent=original_opponent;
int turn,game_result;
for(turn=0;turn<turn_limit;++turn){
enum Move me_move,opponent_move=rand()%(OVERHEAD-BOW+1)+BOW;
if(turn==0)me_move=first_me_move;
else me_move=rand()%(OVERHEAD-BOW+1)+BOW;
//update honour for guarding
if(me.lastMove==GUARD&&me_move==GUARD)--me.honour;
if(opponent.lastMove==GUARD&&opponent_move==GUARD)--opponent.honour;
int me_attacking=me_move==QUICK||me_move==PARRY||me_move==OVERHEAD,opponent_attacking=opponent_move==QUICK||opponent_move==PARRY||opponent_move==OVERHEAD;
//update health of players
me.health-=damage_table[me_move][opponent_move][0]*(1+(opponent.honour>=7));
opponent.health-=damage_table[me_move][opponent_move][1]*(1+(me.honour>=7));
//update honour for attacking (Sword of the Gods is revoked after the player attacks with an original honour value of 7)
if(me_attacking)--me.honour;
if(opponent_attacking)--opponent.honour;
//printf("%d %d\n",me.health,me.honour);
//printf("%d %d\n",opponent.health,opponent.honour);
//check if any of the terminating conditions are met
//c. both players fall off the graces of the gods (me.honour<0&&opponent.honour<0)
if(me.honour<0&&opponent.honour<0){
game_result=0; //draw
break;
}
//a. player 1 falls off the graces of the gods (me.honour<0)
else if(me.honour<0){
game_result=-1; //loss
break;
}
//b. player 2 falls off the graces of the gods (opponent.honour<0)
else if(opponent.honour<0){
game_result=1; //win
break;
}
//d. both players are dead (me.health<0&&opponent.health<0)
else if(me.health<0&&opponent.health<0){
game_result=0; //draw
break;
}
//e. player 1 is dead (me.health<0)
else if(me.health<0){
game_result=-1; //loss
break;
}
//f. player 2 is dead (opponent.health<0)
else if(opponent.health<0){
game_result=1; //win
break;
}
}
//both players get struck down by the guards for being boring
if(turn==turn_limit)game_result=0; //draw
if(game_result==1)++simulation_result.win;
else if(game_result==0)++simulation_result.draw;
else ++simulation_result.lose;
}
return simulation_result;
}
int main(int argc,char*argv[]){
//const int num_iters=200000,num_shortlist_iters=1000000;
const int num_iters=20000,num_shortlist_iters=55000;
srand(tick_count());
Player me,opponent;
if(argc==5){
sscanf(argv[1],"%d",&me.health);
sscanf(argv[2],"%d",&opponent.health);
sscanf(argv[3],"%d",&me.honour);
sscanf(argv[4],"%d",&opponent.honour);
me.lastMove=WAIT;
opponent.lastMove=WAIT;
}else{
sscanf(argv[3],"%d",&me.health);
sscanf(argv[4],"%d",&opponent.health);
sscanf(argv[5],"%d",&me.honour);
sscanf(argv[6],"%d",&opponent.honour);
me.lastMove=decode_move(argv[1][strlen(argv[1])-1]);
opponent.lastMove=decode_move(argv[2][strlen(argv[2])-1]);
}
struct SimulationStat results[6];
results[0].first_me_move=WAIT;
results[0].win=0;
results[0].draw=0;
results[0].lose=num_iters;
results[0].compound=-num_iters*2-1000; //waiting is worse than any other action
for(enum Move first_me_move=BOW;first_me_move<=OVERHEAD;++first_me_move){
results[first_me_move]=monte_carlo(num_iters,first_me_move,me,opponent);
struct SimulationStat *cur=&results[first_me_move];
cur->compound=cur->win*4+cur->draw*1-cur->lose*2;
}
qsort(results,OVERHEAD-WAIT+1,sizeof(*results),stat_compare);
for(int i=0;i<OVERHEAD-BOW+1;++i){
struct SimulationStat *cur=&results[i];
// fprintf(stderr,"%c: %f%% win, %f%% draw, %f%% lose => %d\n","WBGIPO"[cur->first_me_move],(double)cur->win/num_iters*100.,(double)cur->draw/num_iters*100.,(double)cur->lose/num_iters*100.,cur->compound);
}
for(int i=0;i<2;++i){
results[i]=monte_carlo(num_shortlist_iters,results[i].first_me_move,me,opponent);
struct SimulationStat *cur=&results[i];
cur->compound=cur->win*2+cur->draw*1;
}
qsort(results,2,sizeof(*results),stat_compare);
for(int i=0;i<2;++i){
struct SimulationStat *cur=&results[i];
// fprintf(stderr,"%c: %f%% win, %f%% draw, %f%% lose => %d\n","WBGIPO"[cur->first_me_move],(double)cur->win/num_shortlist_iters*100.,(double)cur->draw/num_shortlist_iters*100.,(double)cur->lose/num_shortlist_iters*100.,cur->compound);
}
putchar("WBGIPO"[results[0].first_me_move]);
return 0;
}
```
[Answer]
After my failed attempt to enter Target Dummy, I present to you my next bot...
# ScroogeBot - Python 2
This bot will bow if he has one honor. Otherwise he will flip a coin.
If it lands on heads, he will perform a random attack. If it lands on tails, he will either bow or guard.
Command: `python scroogebot.py`
```
import random, sys
# If he has more than one honor...
if int(sys.argv[5]) > 1:
#Flip a coin.
coin = random.choice(['heads','tails'])
#If the coin lands on heads...
if coin == 'heads':
#Attack!
print random.choice(['I','O','P'])
#If the coin lands on tails...
else:
#Don't attack!
print random.choice(['G','B'])
#If he has 1 honor...
else:
#Bow!
print "B"
```
[Answer]
## Yoshimitsu (JS)
Tries to not get guarded by checking the last two moves, will get bravery with higher honor. based off the template [apsillers](https://codegolf.stackexchange.com/a/52320) made
```
var attacks = ['I','P','O'];
var pasive = ['B','W'];
var argv = process.argv;
var playerHistory = argv.length>6?argv[2].split(''):[];
var enemyHistory = argv.length>6?argv[3].split(''):[];
var offset = 8 - argv.length;
var my = { health:+argv[4-offset], honor:+argv[6-offset], history:playerHistory };
var enemy = { health:+argv[5-offset], honor:+argv[7-offset], history:enemyHistory };
my.godSword = my.honor >= 7;
enemy.godSword = enemy.honor >= 7;
enemy.lastMove = enemyHistory.pop();
enemy.secondToLast = enemyHistory.pop();
enemy.didAttack = !!attacks.indexOf(enemy.lastMove);
my.lastMove = playerHistory.pop();
function decide() {
process.stdout.write(arguments[Math.floor(arguments.length*Math.random())]);
process.exit();
}
chooseAnAttack = function(){ decide.apply(this,attacks); };
if( ( pasive.indexOf( enemy.lastMove ) && my.honor < 15 ) || (my.honor < 7 && enemy.health > 10) || my.honor === 1 ){
if( Math.random * 15 < my.honor ){
chooseAnAttack();
} else {
decide('B');
}
} else if( enemy.honor < 2 ){
chooseAnAttack();
} else if( enemy.didAttack ){
if( attacks.indexOf( enemy.secondToLast ) ){
decide('G');
} else if( pasive.indexOf( enemy.secondToLast ) ){
chooseAnAttack();
} else if( enemy.secondToLast == 'G' ){
decide('B');
}
} else if( enemy.lastMove = 'G' ) {
chooseAnAttack();
} else if( enemy.lastMove === 'W' ){
if( attacks.indexOf( enemy.secondToLast ) ){
decide('G');
} else if( pasive.indexOf( enemy.secondToLast ) ){
chooseAnAttack();
} else if( enemy.secondToLast == 'G' ){
decide('B');
}
}
```
[Answer]
# The Fool (C)
The Fool implores a rather erratic strategy, never repeating the same move twice unless forced to through lack of honour. His movements are largely based on randomness, making it hard to predict his actions. His well-being is the last thing on his mind, as his thoughts are set only upon bloodshed and ultimate victory
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
const char commands[] =
{
'W', 'B', 'G', 'I', 'P', 'O'
};
char select_candidate(const char c[])
{
unsigned i = 0;
int n_candidates = 0;
char candidates[sizeof(commands)];
for (; i < sizeof(commands); i++)
if (c[i])
candidates[n_candidates++] = c[i];
/* There are no candidates for actions, so the fool blindly attacks his opponent, hoping for the best */
return n_candidates == 0 ? 'I' : candidates[rand() % n_candidates];
}
int main(int argc, char *argv[])
{
unsigned i = 0;
int honour;
char candidates[sizeof(commands)];
char last_action;
srand(time(NULL));
memcpy(candidates, commands, sizeof(commands));
/* It's the first round, the fool selects a random action except for waiting */
if (argc != 7)
{
candidates[0] = 0;
putchar(select_candidate(candidates));
return 0;
}
last_action = argv[1][strlen(argv[1]) - 1];
honour = atoi(argv[5]);
if (honour == 0)
{
/* The fool realises he will meet his doom if he performs any of the following moves */
/* and removes them from his list of possible actions */
candidates[3] = 0;
candidates[4] = 0;
candidates[5] = 0;
/* Only omit the blocking action if the last action was blocking */
if (last_action == 'G')
candidates[2] = 0;
} else if (honour >= 7) {
/* If the fool has the opportunity to abuse power, he will */
candidates[0] = 0;
candidates[1] = 0;
}
/* However unintellegent, the fool decides never to repeat the same move twice */
for (; i < sizeof(commands); i++)
{
if (candidates[i] == last_action)
candidates[i] = 0;
}
/* The fool randomly selects a possible action and hopes for the best */
putchar(select_candidate(candidates));
return 0;
}
```
---
# The Prophet (C)
The Prophet uses the knowledge of his opponent's previous 2 moves in order to make a predict his next move and provides a swift and deadly counter-attack. Also, he does astrology and stuff.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(int argc, char* argv[])
{
char* hist;
char* enemy_hist;
int hist_len;
int enemy_hist_len;
int health;
int enemy_health;
int honour;
int enemy_honour;
if (argc != 7)
{
/* Always start with guarding */
putchar('G');
return 0;
}
srand(time(NULL));
/* Grab the command-line values */
hist = argv[1];
enemy_hist = argv[2];
health = atoi(argv[3]);
enemy_health = atoi(argv[4]);
honour = atoi(argv[5]);
enemy_honour = atoi(argv[6]);
hist_len = strlen(hist);
enemy_hist_len = strlen(enemy_hist);
/* Looks like the enemy is starving for honour. */
/* This means that they have to bow, so attack them, */
/* But only if we have the honour to do so. */
if (enemy_honour == 0 && honour > 0)
{
putchar('O');
return 0;
} else if (honour == 0) {
/* We have to bow */
putchar('B');
return 0;
} else if (honour <= 3) {
/* We have low honour, attack if the enemy has no honour, otherwise bow to restore some of our honour */
putchar(enemy_honour == 0 ? ((rand() % 2) ? 'I' : 'O') : 'B');
return 0;
}
switch (enemy_hist[enemy_hist_len - 1])
{
/* The enemy has previously performed a passive action, so they will likely attack this round */
case 'W':
case 'B':
case 'G':
putchar(hist[hist_len - 1] == 'G' ? 'P' : 'G'); /* Protect ourselves, using `guard` if we did not use it last turn */
return 0;
default:
if (enemy_hist_len >= 2)
{
switch (enemy_hist[enemy_hist_len - 2])
{
case 'I':
case 'P':
case 'O':
/* The enemy has attacked for the last 2 turns, they will likely rest now */
putchar((rand() % 2) ? 'I' : 'O');
return 0;
default:
/* Low health, block an incoming attack */
if (health <= 5)
{
putchar(hist[hist_len - 1] == 'G' ? 'P' : 'G');
return 0;
} else {
/* Choose randomly to bow or attack */
int decision = rand() % 3;
putchar(decision == 2 ? 'B' : decision == 1 ? 'I' : 'O');
return 0;
}
}
} else {
/* Attack! */
putchar((rand() % 2) ? 'I' : 'O');
return 0;
}
}
/* If somehow we get to this point, parry */
putchar('P');
return 0;
}
```
---
## Compilation
Both programs are written in C, and can be compiled with `gcc`:
```
gcc fool.c -o fool
gcc prophet.c -o prophet
```
---
## Running
### \*nix
```
./fool <args>
./prophet <args>
```
### Windows
```
fool.exe <args>
prophet.exe <args>
```
] |
[Question]
[
It frustrates me that when you say "base 16", the 16 is in base 10. We need a base neutral way of writing down numbers when favoring a specific base would be inappropriate.
## How it works
We define `<n>` to be the nth prime. So `<1>=2`, `<2>=3`, `<3>=5`. Note that every positive integer can be uniquely represented by the product of some number of `<>` expressions. For example `6` can be written as `<1>*<2>`.
However, in this form we still have numbers that need to be represented in some base. So we must recurse on each term. Until we reach the number 1, which has the same value almost in any base.
Your challenge is to print positive integer in this base neutral format.
I hope the examples will make things more clear:
## Test cases
| base 10 | base neutral | Explanation |
| --- | --- | --- |
| `1` | `1` | 1 can't be factored |
| `2` | `<1>` | 2 is the first prime |
| `3` | `<<1>>` | 3 is the second prime, 2 is the first prime |
| `4` | `<1> * <1>` | 2 times 2 |
| `5` | `<<<1>>>` | 5 is the third prime |
| `6` | `<1> * <<1>>` | 2 times 3 |
| `10` | `<1> * <<<1>>>` | |
| `13` | `<<1> * <<1>>>` | 6th prime |
| `255` | `<<1>> * <<<1>>> * <<<1> * <1>>>` | `3 * 5 * 17`, 17 is the 7th prime, 7 is the 4th prime |
You may replace `*` with any symbol of you prefer. You may replace `<>` with `{}`,`[]` or `()` if you prefer, as long as you don't use the symbol replacing `*`. The `1` must stay a `1` though. You may also add spaces or line breaks anywhere. The spaces in the examples are just for clarity and you may omit them.
For example, a valid output would be `[[1], [1]]` or `{{1 }%{1 }}` for the number 7.
This is code golf. Shortest answer in each language wins.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
λǐÞpvḟ›vx1w$∨
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQQSIsIiIsIs67x5DDnnB24bif4oC6dngxdyTiiKgiLCIiLCIxXG4yXG4zXG40XG41XG42XG4xMFxuMTNcbjI1NSJd)
Output is an array, so there is an extra pair of brackets on the outside. `1w$∨` can be removed if we can omit the `1`s.
```
λǐÞpvḟ›vx1w$∨
λ # Open a lambda for recursion
ǐ # Get the prime factors
Þpvḟ› # Find the one-indexed index of each in an infinite list of primes
vx # Recurse over each
1w$∨ # Logical OR with [1] (replace empty lists with [1])
```
[Answer]
# JavaScript (ES6), 92 bytes
Borrowing an optimization from [Jakque's answer](https://codegolf.stackexchange.com/a/254888/58563), as suggested by [@Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314).
```
f=(n,k=2,p=1)=>n<2?1:n%k?f(n,k+1,p+(P=d=>k%--d?P(d):d<2)(k)):`<${f(p)}>`+(n>k?'*'+f(n/k):'')
```
[Try it online!](https://tio.run/##FY29asMwFEb3PsUdGnRvJTuVUndQLXnKHshYChFWnB8FSTiiS8mzO@pw@ODAx7m6X3cf50suTUz@uCyTwSiCUSIbScbGXg1Sx1UYpn/Ppcgcd8YbG1ZN44cdetK@V4SBSB/6178JMz3sgWO0YWBvjNfjOpBmjJavb5AClICNgA8BnYBPAfK9UoXqOvh5aac0b914xgjGwpjiPd2O7S2dMLYl7ct8iSekNju/L24uuCHgwDSwOrVERMsT "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 96 bytes
*-4 thanks to [@Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314)*
```
f=(n,m,k=2,p=1)=>n>1?n%k?f(n,m,k+1,p+(P=d=>k%--d?P(d):d<2)(k)):[m]+`<${f(p)}>`+f(n/k,'*'):m?'':1
```
[Try it online!](https://tio.run/##JY29asMwFEb3PsUdGqRbXbuVU2dQInnqHsgYAhFWnB/FknBEltBndwUdDh8c@Dg3@7SPfrqmXIXoTvM8aB5oJK8bSlqiNsHILix8N/x7ISkJvtVOG7@oKtdtuUPlNg1yj6j240EcN@@vgSf8NUdRXp@e2AdDNXaMKTmv9yAJGoIlwTdBS7AikF@FIpq2hcNbPcTpx/YXHkAb6GN4xPupvsczD3WOuzxdw5ljnazbZTtlvkQQwBSwMiWIiPMf "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
m, // m = either undefined or '*'
k = 2, // k = current divisor
p = 1 // p = 1-based index of the smallest prime >= k
) => //
n > 1 ? // if n is greater than 1:
n % k ? // if k is not a divisor of n:
f( // do a recursive call:
n, // leave n unchanged
m, // leave m unchanged
k + 1, // increment k
p + ( // pass either p or p + 1
P = d => // according to the result of P(k)
k % --d ? // where P is a recursive helper function
P(d) // testing whether k is prime
: //
d < 2 //
)(k) //
) // end of recursive call
: // else:
[m] + // append m (force an empty string if undefined)
`<${f(p)}>` + // append '<', followed by f(p), followed by '>'
f( // append the result of a recursive call:
n / k, // divide n by k
'*' // enable the multiply sign
) // end of recursive call
: // else:
m ? '' : 1 // stop the recursion; append '1' if m is undefined
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~90~~ 89 bytes
```
f=lambda n,i=2,p=1:1//n or n%i and f(n,i+1,p+(f(i)>"."))or(n>i)*f" {f(n/i)}*"+f"<{f(p)}>"
```
[Try it online!](https://tio.run/##FYxBCsIwEADvvmJZELLNak17KyZ/idTogm5C6EWkb4/xOMww5bM9s86tJf@K79saQVn8xMW7xY2jQq6gR4GoKyTTnXVcrElGKOAZiXI1GoSGhPDtwSi0D2gTXjsV2gO21BcColCjPu7G8XSh5QBQquhmhAFPARn@S2o/ "Python 3 – Try It Online")
>
> "You may also add spaces or line breaks anywhere"
>
>
>
Wait a minute, I can totally (ab)use that!
## Explanation :
```
f=lambda n,i=2,p=1:
# f: recursive function
## n: input
## i: increment to have a prime that divide n
## p: prime index of i
1//n # if n == 1: return 1
or # else
n%i and f( # if i is not a divisor of n recurse
n, # with same input
i+1, # increment i
p+(f(i)>".")) # increment p if i is prime (no leading space)
or # then (assuming that i is prime and divide n and p the index of i)
(n>i)* # if n//i > 1
f" {f(n/i)}*" # recurse adding a space before and a "*" after
+f"<{f(p)}>" # add to the representation of i
```
-1 byte thanks to @Dominic van Essen
# [Python 3](https://docs.python.org/3/), ~~99 83~~ 77 bytes, cheaty (but totally legit) version
This version abuse of list representation and the fact that `<...> * 1` is "equal" to `<...>` to produce non canonic expressions. But the author authorised it so ¯\\_(ツ)\_/¯
`<...> * <...>` representation is `[...], [...]` with total result enclosed with `[]`
```
f=lambda n,i=2,p=1:1//n*[1]or n%i and f(n,i+1,p+2//len(f(i)))or[f(p)]+f(n//i)
```
[Try it online!](https://tio.run/##JcxBCsIwEEDRvacYCkLGTokTd4F4kdJFpI0O1EmI3Xj6GHD9@L98j1fWW2sp7PH9WCMoSXBUAnu2Vi8zL7mCngWirpBM55GpjM7afVOTjCBirnMyBZexu7WCLfVGQBRq1OdmmNwV/QmgVNHDCMEw3QeCz1H/h5n9xAu2Hw "Python 3 – Try It Online")
the process is the same but we check the length of `f(i)` do detect if it is prime.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆfÆC߀;¹?
```
**[Try it online!](https://tio.run/##y0rNyan8//9wW9rhNufD8x81rbE@tNP@v87h9qOTHu6coZL1qGGOgq2dwqOGuZqR//9HG@ooGOkoGOsomOgomOoomOkoGBoAMVDAyBTINzczjQUA "Jelly – Try It Online")**
A monadic Link that accepts a positive integer and yields a ragged list of ones - that is, a list of `1`s where inner nesting is the prime counting and adjacency is multiplication.
---
A full program that prints that without the outer `[]` is \$15\$ bytes:
```
ÆfÆC߀;¹?
ÇŒṘṖḊ
```
**[Try it online!](https://tio.run/##y0rNyan8//9wW9rhNufD8x81rbE@tNOe63D70UkPd854uHPawx1d/3UOt2c9apijYGun8Khhrmbk///RhjoKRjoKxjoKJjoKpjoKZjoKhgZADBQwMgXyzc1MYwE "Jelly – Try It Online")**
### How?
```
ÆfÆC߀;¹? - Helper Link: positive integer, I
Æf - prime factors
ÆC - number of primes up to (vectorises across that)
? - if...
¹ - ...condition: no-op
߀ - ...then: call this Link for each
; - ...else: concatenate (I) - N.B. Only 1 has no prime factors, so concatenate 1.
ÇŒṘṖḊ - Main Link: positive integer, I
Ç - call the Helper Link (with I)
ŒṘ - get the Python representation (of that)
Ṗ - pop
Ḋ - dequeue
- implicit print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 70 bytes
```
.+
$*
{+`\b(11+)(\1)+\b
$1*1$#2$*
\b1(1((?<!\b\3+(11+)))?)+\b
<$#2$*1>
```
[Try it online!](https://tio.run/##HcqxDkAwFAXQ/f6F6PDqJeK2ahJ@5A00MVgMYvPxJZ3PuY/nvPZSeoXr8OpmWUj1YvRqGY4dXRt@s0yhyDo3li1qXd6vdc21cCmFCIgYkTCBAxgRUvoA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
{`
```
Repeat until no more numbers can be decomposed.
```
+`\b(11+)(\1)+\b
$1*1$#2$*
```
Decompose numbers into their prime factors. (Note that this outputs the factors in descending order as that's golfier.)
```
\b1(1((?<!\b\3+(11+)))?)+\b
<$#3$*1>
```
Decompose primes into their index.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
≔⟦⟧θF²⊞υ1FE…·²NΦ…²ι¬﹪ιλ⊞υ⎇ι⁺⁺§υ⌊ι*§υ⌈ι⪫<>§υL⊞Oθω⊟υ
```
[Try it online!](https://tio.run/##VY5Bi8IwEIXv/oqQ02SJhy14chG8LFS2bhFv4iHWbDuQTmqauPrrYyIoOofHzPuGedN0yjVWmRiX44gtwW4v2UnMJ3/WMSgEq8PYQZCMf/KHW6kBSmpMGPGsN4paDYVkJQ3Br0N/0A6EkOwbjU/tk2Py1tZDZY/BWEDJjMj1TNhqR8pdM6nTbbjL0pd01JfMKyTsQw@Yr/MPnvSVqsuDJrCySMC/Fvxt50dT6zvIgb@DdspbByfJ/u9/zCe1Q/JQ2wFCGmMsZrM4PZsb "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⟦⟧θ
```
Start with no prime numbers discovered.
```
F²⊞υ1
```
Start with a dummy entry for `0` and an entry of `1` for `1`.
```
FE…·²N
```
Loop from `2` to the input...
```
Φ…²ι¬﹪ιλ
```
... finding the factors of each number, ...
```
⊞υ⎇ι
```
... if the number has nontrivial proper factors, then push...
```
⁺⁺§υ⌊ι*§υ⌈ι
```
... the concatenation of the representations for the lowest and highest factor with an intermediate `*`, otherwise push...
```
⪫<>§υL⊞Oθω
```
... the representation of the incremented count of primes found so far, wrapped in `<>`.
```
⊟υ
```
Output the final value.
[Answer]
# [Python 3](https://docs.python.org/3/), 108 bytes
```
f=lambda n,k=2,p=1,m=1:n>1and(n%k and f(n,k+1,p+all(k%i for i in range(2,k)),m)or[f(p)]+f(n/k,k,p,0))or[1]*m
```
[Try it online!](https://tio.run/##XY0xDsIwDEWv4qWqTQ3UZauUXgR1CCqBKI0bhS5w@RBWpi@9r6eX3vtz00spzqw23hYLysEMnIxwNDLqJFYX1CZAXXBY7044dXZdMTQe3JbBg1fIVh93HDgQcaQtXx0mmrtqnAMHTtzTj8p8iOVPEpa@pzFlrzu@9oyeTh/na2Egbo9Ty64iKl8 "Python 3 – Try It Online")
Suggested by Mukundan314. Outputs nested lists.
# [Python 3](https://docs.python.org/3/), ~~140 139 136~~ 135 bytes
```
f=lambda n,k=2,p=1,m='':(f(n,k+1,p+all(k%i for i in range(2,k)),m)if n%k else m+f'<{f(p)}>'+f(n/k,k,p,'*'))if n>1 else'1'if m==''else''
```
[Try it online!](https://tio.run/##XY7NDsIgEIRfZS/NsrJqqbdG@i4YixJ@Smgvanx2JD16/L5MZia/tueSLrVaHUy83Q0k9nrgrBVHjTgKK5qRirM0IQjfObBLAQcuQTHpMYuBPRFHchZS52EO6wxRWrx@rMj0nVC2irNnz5nxgLQHJ7UHUWGjqNvSjlj/yhWD6nsac3FpE@tWhKPT27p2ZSDG44Rsm6L6Aw "Python 3 – Try It Online")
* -1 thanks to Arnauld
* -3 thanks to Seb
Port of Arnauld's JavaScript answer. Outputs the string shown in the test cases.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
#0/@(Join@@Table@@@FactorInteger@#/.#->PrimePi@#/.{0}->1)&
```
[Try it online!](https://tio.run/##Fc1BC4JAFATg@/4NQQpWVy07FMmDICgshLpFxEtWXXDXsGcQon/dtsMc5pvDaKRKaiSV41RsJycQMDs2ygBc8VlLANhjTk17MCRL2YIjfMdLslZpmal/64PBS8K5O1kzdLNjYVn4@EjVm8QmlaakCjAJ18m5MbtG647s30eeuprUq/4C4N0dLzmasWchZxFnC86WnMWcrTgLAxsLURyzYfoB "Wolfram Language (Mathematica) – Try It Online")
Uses `{ }` to represent both operations, depending on the number of elements. Test output converts lists with >1 element into `NonCommutativeMultiply` (`**`) for clarity.
```
Join@@Table@@@FactorInteger@# prime factorize
#0/@ recurse on factors
/.#->PrimePi@# prime input: recurse on #prime instead
/.{0}->1 1=input: return 1
```
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 43 bytes
```
P/"*`"mapf"$P rev.= find:1+ @"map""Q1.,, |#
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Outputs as `[[[1]] [[[1]]] [[[1] [1]]]]` where each space replaces `*`.
For testing purposes:
```
[1 2 3 4 5 6 10 13 255] ( ; f>o ) map
P/"*`"mapf"$P rev.= find:1+ @"map""Q1.,, |#
```
## Explanation
Prettified code:
```
P/ \*` mapf ( $P rev.= find: 1+ @ ) map dup 1.,, |#
```
* `P/ \*` mapf` prime factors converted from frequency map to list
* `(...) map` for each prime factor...
+ `$P rev.= find: 1+` get its index (1-indexed)
+ `@` execute this line (i.e. recurse)
+ since 1's list of prime factor is empty, `map` doesn't trigger recursion on 1s
* `dup 1.,, |#` replace empty list with `[1]`
+ boolean check works here because empty lists are falsy in sclin
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"Di¸ëÒεÅPg®.V"©.V
```
Recursion isn't exactly 05AB1E's strong suit.. As in, I have to use strings and `eval`s to mimic recursive behavior.
Outputs just like some of the other answers as a nested list, including additional wrapped list around the entire output (e.g. `[[[1],[1]]]` for \$n=7\$).
[Try it online](https://tio.run/##ASMA3P9vc2FiaWX//yJEacK4w6vDks61w4VQZ8KuLlYiwqkuVv//Ng) or [verify all test cases](https://tio.run/##AUgAt/9vc2FiaWX/dnk/IiDihpIgIj95/yJEacK4w6vDks61w4VQZ8KuLlYiwqkuVv8s/1sxLDIsMyw0LDUsNiw3LDEwLDEzLDI1NV0).
**Explanation:**
```
"..." # Push the recursive string explained below
© # Store it in variable `®` (without popping)
.V # Evaluate and execute it as 05AB1E code,
# using the (implicit) input-integer as argument
# (after which the result is output implicitly)
D # Duplicate the current integer
i # If it's exactly 1:
¸ # Wrap this 1 inside a list: [1]
ë # Else:
Ò # Get the prime factors (including duplicates) of the integer
ε # Map over each prime factor:
ÅP # Convert it to a list of primes <= this prime factor
g # Pop and push the length to get the amount of primes in this list
®.V # Do a recursive call by evaluating and executing string `®`
```
[Answer]
# C++, 156 bytes
(+40 bytes of header includes)
[Try it online!](https://tio.run/##TY/NboMwEITP8BRbqkS2cFVMQqRinGOeohfiOMkiYiMw9IB4dspPovbgw858O@NVVfWhytzcxnc0qmwvGrLG1WhuR/9PQTtpOn8cx87iBU4EjYOONe6Spiu9tbTHK@mymNpQ7r/ETCjJGU6vYoW42pqIMMRMdoL2lSwkf2lFhoJWW4mbQvzcsdSk26CUEe27T4liyjtE4kQUs3QZYjE3vUm@VMViUKGsxDCMc@cjR0Mo9L6Xt86CaR9nXTcgoQfOYrZje5awA@MR4zsWJwkMwvemj8By04pD@tpbgrx/d0Ktm7Z00453IivEnhoVL1TZ1kGWQXDOGw08SiGYx2f4bHy7xTK6dXVePv01ZvVNMKUN/jD@Ag)
Header:
```
#include <string>
#include <iostream>
```
My attempt at code. I find this exercise horrible, yet fascinating :)
```
void F(int v,std::string&o){if(v<2)o+=49;int c=1,i=1,p,j;for(;++i<=v;){p=j=1;for(;++j<i;)p&=i%j;while(v%i==0){v/=i;o+=60;F(c,o);o+=62;if(v!=1)o+=42;}c+=p;}}
```
Footer (calling the function):
```
int main() {
auto numbers = { 1,2,3,4,5,6,10,13,255 };
for (int number : numbers) {
std::string result;
F(number, result);
std::cout << "base 10: " << number << "\tbase neutral: " << result << "\n";
}
}
```
Output:
```
base 10: 1 base neutral: 1
base 10: 2 base neutral: <1>
base 10: 3 base neutral: <<1>>
base 10: 4 base neutral: <1>*<1>
base 10: 5 base neutral: <<<1>>>
base 10: 6 base neutral: <1>*<<1>>
base 10: 10 base neutral: <1>*<<<1>>>
base 10: 13 base neutral: <<<1>>>
base 10: 255 base neutral: <<1>>*<<<1>>>*<<<1>>>
```
[Answer]
# [R](https://www.r-project.org), ~~94~~ 92 bytes
*Edit: -2 bytes thanks to pajonk*
```
f=\(n,i=2,p=1)`if`(n<2,1,`if`(n%%i,f(n,i+1,p+(sum(!i%%2:i)<2)),paste(f(n/i),"*<",f(p),">")))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHapMTi1Pi81NKSosQc26WlJWm6Fjdj0mxjNPJ0Mm2NdApsDTUTMtMSNPJsjHQMdSBMVdVMnTSQAm1DnQJtjeLSXA3FTFVVI6tMTRsjTU2dgsTiklQNoAr9TE0dJS0bJaDqAiDLTklTUxNix87ixIKCnEoNQytDAx1kN0DlFyyA0AA)Outputs non-minimal base-neutral representations, as allowed, including quite a lot of `1*`s, but all expressions should evaluate correctly.
Based initially on [Jakque's Python answer](https://codegolf.stackexchange.com/a/254888/95126) (upvote it) and golfed from there.
[Answer]
# Python 3, 483 bytes
```
f=lambda n,p=2:[]if n==1 else [p]+f(n//p,p=p)if n%p==0 else f(n,p=list(filter(lambda x:all(x%i!=0for i in range(2,(x//2)+1,2)),range(p+1,2*p)))[0])
g=lambda p,t=2,c=1:c if p in list(filter(lambda x:all(x%i!=0 for i in range(2,x)),range(2,t+1)))else g(p,t=list(filter(lambda x:all(x%i!=0 for i in range(2,x)),range(t+1,2*t)))[0],c=c+1)
r=lambda n:[[i]if i==1 else r(i)for i in[g(i)for i in f(n)]]
s=lambda n:str((lambda n:[[i]if i==1 else r(i)for i in [g(i)for i in f(n)]])(n))[1:-1]
```
[Try online!](https://tio.run/##pZBBa8QgEIXv@RXThQWncUm0N8H@EfGQpkkquO5gPKS/PtVNNy1soYVehJmH33vz6D29XcLTuo7ad@eX1w4CJy2VsW6EoLWAwc8DGLL1yELTUFYJi3YkrdtNzUpeezcnNjqfhsg@WYvqvGfL0T3odrxEcOACxC5MA5OcLU0jsRZcIvJtSWV6JEQ0rcVqumUinrTkvRaqh@xNBfOLHdz5LbuN5KkW2eQafmKF/g9auoZOW@gcss/sKu51KmNcKdPtZUbm8MYz07ehFInWVvPX5zlFxv6Ggp9YmF80Qp2EXe9uANmiqgAoupCY43A4PR84zBmD6wc)
More cleaner version:
```
f = lambda n, p=2: [] if n==1 else [p] + f(n//p, p=p) if n%p == 0 else f(n, p=list(filter(lambda x: all(x%i != 0 for i in range(2, (x//2)+1, 2)), range(p+1, 2*p)))[0])
g = lambda p, t=2, c=1: c if p in list(filter(lambda x: all(x%i != 0 for i in range(2, x)), range(2, t+1))) else g(p, t=list(filter(lambda x: all(x%i != 0 for i in range(2, x)), range(t+1, 2*t)))[0], c=c+1)
r = lambda n: [[i] if i == 1 else r(i) for i in [g(i) for i in f(n)]]
s = lambda n: str((lambda n: [[i] if i == 1 else r(i) for i in [g(i) for i in f(n)]])(n))[1:-1]
```
## Explanation:
`f` will factor the input numbers and return the factorization result in a list.
```
>>> f(12)
[2, 2, 3]
```
`g`'s input is a prime and return the index of that prime. In other words `n = g(p)` means that `p` is the `n`th prime number.
```
>>> g(2)
1
>>> g(3)
2
>>> g(13)
6
```
[Answer]
# JavaScript(ES2021)
## Nested list output version, ~~86~~ 80 bytes
```
f=(n,a=[1,[1]],m=1)=>a[n]??=n%++m?f(n,a,m,f(m,a)):[f(n>m?a[0]:a[0]++),...f(n/m)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=tZFPS8MwHIbxaD9FDsryozFdNweymvXkxcMUPJZAw5qUQv6MtkN07JN42UE_lH4aE4qD-efoJT948ibvQ_Lyal0l9_u3Ta8urt7vFcOWCFakpEg5J4alwBaisDzPmT2PY5OrECCGKGyIAJgXHixMLooxn4cljoFQSj1NDPDh3o-Tx5WzndOSalfj0pZ0LaobW-EpEFT6LBzI5TigpWuN0M2zrErayrUWK4kTkiY1GY0Aski5FmEte2QRQ2nmxzWaTvz09WgbnYa6HrWy2-jeJ0JDNtCDxNnW7o48bh_ulrTr28bWjXrCw2E48voj8pvhLvrhMJnN_MY3CQ__UWN4_6___QQ)
## String output version, ~~89~~ ~~85~~ 82 bytes
```
f=(n,a=[1,1],m=1)=>a[n]??=n%++m?f(n,a,m,f(m,a)):'<'+f(n>m?a[0]:a[0]++)+'>*'+f(n/m)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rZG9TsMwFEbFSJ7CQ5Ht2iR1SyXU1MnECANriBSrsSsk_1RpuhDlSVg6wEPB02ATEaCsLL7Sudc-n66fX6yr5fH4emjV5fXbveLIUsELRllJDWeYZ6KwZZ5ze0GIyVVoU0MVMlRgvIJrSDzLTC6KWbkKByGYwGz6yRODh5ffz243zu6dlrF2W1TZKt6J-sbWaIEpqPwoHsnVLKA71xihH59kXcWN3GmxkSihLNlSCDFOI-UagLRsgQUcsNSXNVjMffV-0EXnQdeCRu4PuvUTwZAOdAwx6Wz_O8ekGy70J2F-8DHLw_Q7TB_90c2XS9848Xn4P8Zhq1__9gE)
---
The output contains extraneous `*1`s.
This "string version" actually returns a number for input `1` and a string for other input numbers. This can be changed for +2 bytes.
---
## Explanation
### Algorithm
The gist of the algorithm is to find the smallest factor `m`≥2 of `n` by brute-force trial division. Note that such an `m` must exist because `n` itself fits the criteria. Also note that `m` must be prime. Let `m` be the `k`th prime
During each iteration of the brute-force loop, we call `f` on the current divisor and cache the results in an array `a`. This ensures each prime < `m` is processed exactly once before we find `m`.
That way, we can use a simple counter to determine `k`, by making `f(x)` increment the counter if and only if `x` is prime. Since `0` is not valid input, we can just use `a[0]` as the counter.
Once `m` is found, we recurse using the fact `n = m * (n/m) = <k> * (n/m)`. I.e.
```
f(n) = '<' + f(k) + '>*' + f(n/m)
```
with the base case being `f(1) = '1'`.
### Ungolfed code
Changed the brute-force division from recursion to loop. Also changed the initial loop variable to make the code more idiomatic.
```
function f(n, a = [1,[1]]) {
if (a[n] !== undefined) {
return a[n];
}
for (let m = 2;; m++) {
if (n % m !== 0) {
// This increments a[0] exactly once if m is prime
f(m, a);
} else {
// Found a factor m, which is the a[0]-th prime
// Increment the counter if m==n (i.e. n is prime)
const k = n > m ? a[0] : a[0]++;
// Recurse (discard cache to save keystrokes)
return a[n] = '<' + f(k) + '>*' + f(n/m)
}
}
}
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 61 bytes
```
{+`\b(11+)(\1)+\b
1$#2*1,$.1*1
11+
<$&>
(?=(11+)\1+\b|\b11)1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sKLUkMy9xwTJVDS0N94SlpSVpuhY3bau1E2KSNAwNtTU1Ygw1tWOSuAxVlI20DHVU9Ay1DLmAElw2Kmp2XBr2tmBVMYZANTUxSYaGmoZcS4qTkos3amq6J3DpaXOp6Blw1iio6BpBzF5wi9EYZAAQgTGEgJIwCo2JwRt5ABJ4AA)
Input is in unary. Output is same as OP except using `,` instead of `*`
## Explanation
```
+`\b(11+)(\1)+\b
1$#2*1,$.1*1
```
Completely factorize each composite number, using a loop that extract one factor per iteration.
So, we are left with only ones and primes in the working string
---
```
11+
<$&>
```
Wrap each prime in `<>`
---
```
(?=(11+)\1+\b|\b11)1
```
Now we need to convert each prime into its "prime index". We do so by removing `1`s:
* whose position from the end of the number is composite, or
* that is the first `1` in the number and is follow by at least another `1`
For example, take 5 as an example
```
1 1 1 1 1
↑ ↑ ↑ ↑ ↑
| | └-┴-┴------- Keep these
| └------------- Remove, because it is 4th 1 from the right, and 4 is composite
└--------------- Remove, because it is the first 1 and is followed by another 1
```
---
Finally, we loop all of the above (`{`) until fixpoint
] |
[Question]
[
Today you need to solve a very practical problem: How many loops do you need to have a certain number of sheets on your toilet paper roll? Let's look at some facts:
* The diameter of a bare toilet paper cylinder is 3.8cm
* The length of one sheet of toilet paper is 10cm.
* The thickness of one sheet of toilet paper is 1mm.
Before you wrap around the cylinder the first time, it has a circumference in cm of 3.8\*pi. Every time you wrap a sheet around the cylinder its radius increases by .1, therefore its circumference increases by .2\*PI. Use this information to find out how many loops it takes to fit *n* sheets of toilet paper. (Note: Use an approximation of Pi that is at least as accurate as 3.14159).
**Test Cases**:
**n=1**:
* 10/(3.8\*pi) = **.838 loops**
**n=2**:
* (How many full loops can we make?) 1 full loop = 3.8\*pi = 11.938.
* (How much do we have left after the 1st loop?) 20 - 11.938 = 8.062
* (How much of a 2nd loop does the remaining piece make?) 8.062/(4\*pi) = .642 loops
* Answer: **1.642 loops**
**n=3**:
* 1st full loop = 3.8\*pi = 11.938, 2nd full loop = 4\*pi = 12.566
* 30 - 11.938 - 12.566 = 5.496
* 5.496/(4.2\*pi) = .417
* Answer: **2.417 loops**
**n=100** => 40.874
[Answer]
# Pyth, ~~27~~ 23 bytes
```
+fg0=-QJc*.n0+18T50)cQJ
```
[Try it online.](https://pyth.herokuapp.com/?code=%2Bfg0%3D-QJc*.n0%2B18T50)cQJ&input=3&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=%2Bfg0%3D-QJc*.n0%2B18T50)cQJ&test_suite=1&test_suite_input=1%0A2%0A3%0A100&debug=0)
### Explanation
```
Q = input number (implicit)
f ) increment T from 1, for each T:
+18T add 18 to T, get radius
*.n0 multiply by pi to, get half the circumference
c 50 divide by 50, get circumference in sheets
J save it to J
=-Q decrement Q by it
g0 use this T if Q is now <= 0
+ add
Q Q (now <= 0)
c J divided by J (the last circumference)
and print (implicit)
```
[Answer]
# Haskell, ~~59~~ ~~46~~ 44 bytes
A scale factor of 5/pi is applied, so that a paper cylinder has a circumference of 19,20,21... cm and a sheet is 50/pi cm.
Saved 2 bytes thanks to xnor, by using an unnamed function.
```
x!s|s>x=1+(x+1)!(s-x)|1>0=s/x
(19!).(50/pi*)
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~29~~ ~~27~~ 26 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
R+18×3.6°µ0;+\³_÷µḞi0©ị+®’
```
[Try it online!](http://jelly.tryitonline.net/#code=UisxOMOXMy42wrDCtTA7K1zCs1_Dt8K14bieaTDCqeG7iyvCruKAmQ&input=&args=Mw)
[Answer]
# Haskell, 97 bytes
```
p&((m,x):(n,y):z)|y<p=p&((n,y):z)|1>0=m+(p-x)/(y-x)
t=(&zip[0..](scanl(+)0$map(*pi)[0.38,0.4..]))
```
Might be able to golf it further by moving the filtering from the `&` operator into a `takeWhile` statement, but given that it's not a golfing language this seems relatively competitive.
## Explanation
The stream of lengths of toilet paper that comprise full loops are first calculated as `scanl (+) 0 (map (* pi) [0.38, 0.4 ..]]`. We zip these with the number of full revolutions, which will also pick up the type `Double` implicitly. We pass this to `&` with the current number that we want to calculate, call it `p`.
`&` processes the list of `(Double, Double)` pairs on its right by (a) skipping forward until `snd . head . tail` is greater than `p`, at which point `snd . head` is less than `p`.
To get the proportion of this row that is filled, it then computes `(p - x)/(y - x),` and adds it to the overall amount of loops that have been made so far.
[Answer]
# C++, 72 bytes
```
float f(float k,int d=19){auto c=d/15.9155;return k<c?k/c:1+f(k-c,d+1);}
```
I used C++ here because it supports default function arguments, needed here to initialize the radius.
Recursion seems to produce shorter code than using a `for`-loop. Also, `auto` instead of `float` - 1 byte less!
[Answer]
# Lua, 82 bytes
```
n=... l,c,p=10*n,11.938042,0 while l>c do l,c,p=l-c,c+.628318,p+1 end print(p+l/c)
```
Not bad for a general-purpose language, but not very competitive against dedicated golfing languages of course. The constants are premultiplied with pi, to the stated precision.
[Answer]
# JavaScript, 77 bytes
```
function w(s,d,c){d=d||3.8;c=d*3.14159;return c>s*10?s*10/c:1+w(s-c/10,d+.2)}
```
```
function w(s,d,c){d=d||3.8;c=d*3.14159;return c>s*10?s*10/c:1+w(s-c/10,d+.2)}
function wraps(sheets, diameter, circumference) {
// Default the value of diameter
diameter = diameter || 3.8;
circumference = diameter * 3.14159;
if (circumference > sheets * 10)
return sheets * 10 / circumference;
return 1 + wraps(sheets - circumference / 10, diameter + .2);
}
document.getElementById('text').innerHTML = "0 => " + w(0)
+ "\n1 => " + w(1)
+ "\n2 => " + w(2)
+ "\n3 => " + w(3)
+ "\n100 => " + w(100)
+ "\n\n0 => " + wraps(0)
+ "\n1 => " + wraps(1)
+ "\n2 => " + wraps(2)
+ "\n3 => " + wraps(3)
+ "\n100 => " + wraps(100);
```
```
<pre id="text"></pre>
```
[Answer]
# C, 87 bytes
```
float d(k){float f=31.831*k,n=round(sqrt(f+342.25)-19);return n+(f-n*(37+n))/(38+2*n);}
```
Uses an explicit formula for the number of whole loops:
```
floor(sqrt(100 * k / pi + (37/2)^2) - 37/2)
```
I replaced `100 / pi` by `31.831`, and replaced `floor` with `round`, turning the annoying number `-18.5` to a clean `-19`.
The length of these loops is
```
pi * n * (3.7 + 0.1 * n)
```
After subtracting this length from the whole length, the code divides the remainder by the proper circumference.
---
Just to make it clear - this solution has complexity `O(1)`, unlike many (all?) other solutions. So it's a bit longer than a loop or recursion.
[Answer]
## C#, 113 bytes
```
double s(int n){double c=0,s=0,t=3.8*3.14159;while(n*10>s+t){s+=t;c++;t=(3.8+c*.2)*3.14159;}return c+(n*10-s)/t;}
```
Ungolfed:
```
double MysteryToiletPaper(int sheetNumber)
{
double fullLoops = 0, sum = 0, nextLoop = 3.8 * 3.14159;
while (sheetNumber * 10 > sum + nextLoop)
{
sum += nextLoop;
fullLoops++;
nextLoop = (3.8 + fullLoops * .2) * 3.14159;
}
return fullLoops + ((sheetNumber * 10 - sum) / nextLoop);
}
```
Results:
>
> for 1 sheet
>
>
>
> >
> > 0,837658302760201
> >
> >
> >
>
>
> for 2 sheets
>
>
>
> >
> > 1,64155077524438
> >
> >
> >
>
>
> for 3 sheets
>
>
>
> >
> > 2,41650110749198
> >
> >
> >
>
>
> for 100 sheets
>
>
>
> >
> > 40,8737419532946
> >
> >
> >
>
>
>
[Answer]
## PHP, 101 bytes
```
<?$p=pi();$r=3.8;$l=$argv[1]*10;$t=0;while($r*$p<$l){$t+=($l-=$r*$p)>0?1:0;$r+=.2;}echo$t+$l/($r*$p);
```
## Ungolfed
```
<?
$pi = pi();
$radius = 3.8;
$length_left = $argv[1]*10;
$total_rounds = 0;
while ($radius * $pi < $length_left) {
$total_rounds += ($length_left -= $radius * $pi) > 0 ? 1 : 0;
$radius += .2;
}
echo $total_rounds + $length_left/( $radius * $pi );
```
I feel like this could be done a little shorter, but I ran out of ideas.
[Answer]
# Python 3, ~~114~~ ~~109~~ 99 bytes
This function tracks the circumference of each layer until the sum of the circumferences is greater than the length of the number of sheets. Once this happens the answer is:
* One less than the number of calculated layers **+** length of leftover sheets **/** circumference of most recent layer
---
```
def f(n):
l,s=0,[]
while sum(s)<n:s+=[.062832*(l+19)];l+=1
return len(s)-1+(n-sum(s[:-1]))/s[-1]
```
**Update**
* **-10** [16-05-09] Optimized my math-ing
* **-5** [16-05-04] Minimized number of lines
[Answer]
# JavaScript, 44 bytes
```
w=(i,d=19,c=d/15.9155)=>i<c?i/c:1+w(i-c,d+1)
```
I used anatolyg's idea and translated the code into JavaScript.
[Answer]
# ><>, 46 44 bytes
```
a*0"Gq",:&a9+*\
?\:{$-{1+{&:&+>:{:})
;>{$,+n
```
Expects the number of sheets to be present on the stack at program start.
This uses an approximation of pi of `355/113 = 3.14159292...`, storing `pi/5` in the register. The current iteration's circumference lives on the stack, and `pi/5` is added on each iteration.
**Edit:** Refactored to store the circumference directly - previous version stored `pi/10` and started the diameter as `38`, which was 2 bytes longer.
[Answer]
# PHP, 79 bytes
```
function p($s,$d=3.8){$c=$d*pi();return $c>$s*10?$s*10/$c:1+p($s-$c/10,$d+.2);}
```
[Run code in Sandbox](http://sandbox.onlinephpfunctions.com/code/32c2ee9afe2c688d8541a02ad121e7c9ff757ee5)
I have pretty much only translated Ross Bradbury's answer for JavaScript into a PHP function, which is also recursive.
] |
[Question]
[
## The task
*Today's special offer: consonants and punctuation for FREE!*
Your program or function will be given as input the first 6 paragraphs of Lewis Carroll's famous novel *Alice's Adventures in Wonderland*, with all vowels `[aeiouAEIOU]` removed and all other characters left intact.
It must output the original text, byte-for-byte identical.
The shortest answer in bytes wins.
You may store your data in one or several files, as long as this is done [under the rules for scoring multiple files](https://codegolf.meta.stackexchange.com/a/4934/58563). Please consider providing a way to access these files in your answer if you do so.
As a reminder, fetching data from any other external source is forbidden ([this is a default loophole](https://codegolf.meta.stackexchange.com/a/1062/58563)). If you do that, you'll be trapped in the Rabbit hole for 6 months.
## Input
Your program or function will be given this exact ASCII string, where 703 vowels are missing:
```
lc ws bgnnng t gt vry trd f sttng by hr sstr n th bnk, nd f hvng nthng t d: nc r twc sh hd ppd nt th bk hr sstr ws rdng, bt t hd n pctrs r cnvrstns n t, "nd wht s th s f bk," thght lc "wtht pctrs r cnvrstns?"
S sh ws cnsdrng n hr wn mnd (s wll s sh cld, fr th ht dy md hr fl vry slpy nd stpd), whthr th plsr f mkng dsy- chn wld b wrth th trbl f gttng p nd pckng th dss, whn sddnly Wht Rbbt wth pnk ys rn cls by hr.
Thr ws nthng s _vry_ rmrkbl n tht; nr dd lc thnk t s _vry_ mch t f th wy t hr th Rbbt sy t tslf, "h dr! h dr! shll b lt!" (whn sh thght t vr ftrwrds, t ccrrd t hr tht sh ght t hv wndrd t ths, bt t th tm t ll smd qt ntrl); bt whn th Rbbt ctlly _tk wtch t f ts wstct-pckt_, nd lkd t t, nd thn hrrd n, lc strtd t hr ft, fr t flshd crss hr mnd tht sh hd nvr bfr sn rbbt wth thr wstct- pckt, r wtch t tk t f t, nd brnng wth crsty, sh rn crss th fld ftr t, nd frtntly ws jst n tm t s t pp dwn lrg rbbt-hl ndr th hdg.
n nthr mmnt dwn wnt lc ftr t, nvr nc cnsdrng hw n th wrld sh ws t gt t gn.
Th rbbt-hl wnt strght n lk tnnl fr sm wy, nd thn dppd sddnly dwn, s sddnly tht lc hd nt mmnt t thnk bt stppng hrslf bfr sh fnd hrslf fllng dwn vry dp wll.
thr th wll ws vry dp, r sh fll vry slwly, fr sh hd plnty f tm s sh wnt dwn t lk bt hr nd t wndr wht ws gng t hppn nxt. Frst, sh trd t lk dwn nd mk t wht sh ws cmng t, bt t ws t drk t s nythng; thn sh lkd t th sds f th wll, nd ntcd tht thy wr flld wth cpbrds nd bk-shlvs; hr nd thr sh sw mps nd pctrs hng pn pgs. Sh tk dwn jr frm n f th shlvs s sh pssd; t ws lblld "RNG MRMLD", bt t hr grt dsppntmnt t ws mpty: sh dd nt lk t drp th jr fr fr f kllng smbdy ndrnth, s mngd t pt t nt n f th cpbrds s sh fll pst t.
```
* Size: 1677 bytes
* Paragraph separator: `LF`
* SHA-256: df40659e07f6185ea348028dd22f137902fa50b9abcb790ff39353e189656c6f
## Output
Your code must print or return this exact string.
```
Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice "without pictures or conversations?"
So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy- chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.
There was nothing so _very_ remarkable in that; nor did Alice think it so _very_ much out of the way to hear the Rabbit say to itself, "Oh dear! Oh dear! I shall be late!" (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually _took a watch out of its waistcoat-pocket_, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat- pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.
In another moment down went Alice after it, never once considering how in the world she was to get out again.
The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down a very deep well.
Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled "ORANGE MARMALADE", but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody underneath, so managed to put it into one of the cupboards as she fell past it.
```
* Size: 2380 bytes
* Paragraph separator: `LF`
* SHA-256: 86abbfeb5dfa10bd9b266ea91723b9f79ab49306e2e8266174a0aa4c49ba7d57
You can use [this script](https://tio.run/##dVbfb9NIEH7vX7FUSEmlNJRSWtoKoUiUAwkOiZx0L0hl7R3bS5xdn3dd40P87b1vZh0nPFwf2nR3fnzzzTez@a4fdMhb28RT5w09PubehahK7817HSr1Ws1eXeosKyh7aQr9/Cwz19n55SXp6@dX5y@y6@LqWmcX1y/OLumcXuHm@dWFPtP6Ir@4zvSVeXk1uz2qKaoQW0Rr6Z/OtjSfFWF2smxJm3e2pvXg8vnsmaGHZyEa63AV/Tq21pXzk@ReJTSTf94OTfQwzBEkEoOdz0Klz19e4rBrDA7nyHmyNLakEOezin7MEIwL9DUta1/Ov63tv6Twc6Oe/oTxsiZXxurXV3f3o6E8krlR5y9enX116/erU4QWQ4bym8nTnzu@cPy5i7nf0mSpXr/e0/lGzdZdnlMIT2awmL1bffh493b269vJ4@OqtjmpXgeVUWmdQ/EqelWi@AdqBxVRt1G@UMHGyJfZoCpq8W@I@OOdihWpTLvNQmknlpV@YEPnYzVGM/4GlsjjWxV7ThjgVGmjGqIG8a2DlQTyfnMYn4FxvxBoobIuKhvFz3nV2Dx2LQUOCnqBNuhowTOiwWyhjhlPX2k4BQneBWJ8WrIsjnHmu7KKKnFw3Fs@iP8f@M3x0doLdIbFLbWGWC6ckUH73qmtRdY57nuqa4W/bJ/7rjYLVXD9XLmPyuhBbbUhcSyI6sR3qMHIIFSG2DXWnCxQA0W2YtemJh2AjgvZ6g0n14hlw3Cq8koDSM@50E18aGMlTrH1XVaLDxorbewayYFaJQZbcRRLQfI5FTpjyNWAov6ubCT1BQMJ9pkluLmNogEctdqpvPZgNgljefQXfieGdgoIXt1zcfdo5Va3G81YLCtHx1tYtcpYM3aBPTbc5b3TtssrxY0B/CjkDyyqinSiZAQW0rGNgeoC3f9cKQOTJ2r68AG90GgKuKkxqE@O1TyVyhSNWkAgj7RKF5Bfr1sDPvgsz7uWJ0EStwJd/JIXn@oHptxBETDDLSoJSbPyD1JYDChiMYRAtIUZ1gqYdRp60/XJrVgLpIO6NNQIl0HdRx4OjfrjnhCUiwMMS@51PG18vqF4n0axhnmCwtPAJ5FDVyjE8ky7xch5iLqN@9ogxpi0iuxFjQ3CUfLWhyD3ovCJAJlGYsoygg9xaQ4o2wO5kBX96gOkKkFd8JDtSuIdoDe0Ly2hzrpW1pKEQhusxy4aFpKd5TdCY8oKS9C@9G5yB6jYgWIChazK7x2eGlYftwMpgZcLbXyDPdUz9Fq3JY0FnFZY26rjtqbRJVPS8ugD7FjeTAf2rovJt@dPidQ9iMSO7L/DnVH5Pg2BTCpg7xbLuH6ZBV1iomWkfoMjafByaMviww6uLWjTCnU6LBJuXeDXAJNy0HhjG96102Az4gXP2XQiTU3w05IFgl19sqB5NnXGyEL0TSNlYD1i4Kbucxc8@JouCoiXDUdyZcsZLDlZkMujOzvtNtmYzMBkI/KQkHw1Lkjf10PS5/SK4AWNg@wHbuq4dPupLcBey@wIdJGiE7mneU2PBCcu/fhiVRpcObTuR1yqd7YNMektyujs4qWSEGq7k22/G4v0QmxTuOnpSu3Fg4gtuNOedoOsydvUJXbeTy7TwooJ0/IDEamn6A4aNU4irqBuXryFrWucjsPSZJ53WJojRD1F@PqBwq2SLT1qY@xb0D0qacLuZUivYNXJcwGVNVSGpVozDfvq1Xes4aL1W@iQdijHLLtONDoEMrc7BmqdkYA8/vxl9ecfd@rT6sun1cfV27vjxNS4iEr@kgXZBjQDjYmiwzEGbZs43Eh0fjxYqjIE/G2jxSgzCkHmeaHhA5BtbFIiz0bmzZDG2iFJJXOw1U6Xqb1N6pd8Lzmo64DQsNclymPr5X8) to test your output.
[Answer]
# [Python 2](https://docs.python.org/2/), 121 + 557 + 1 = 679 bytes
```
i=0
for c in open('a').read():i=i<<8|ord(c)
s=input();k=0
while i:s=s[:k]+'aeiouAEIO'[i/9%9]+s[k:];k+=i%9+1;i/=81
print s
```
[Try it online!](https://tio.run/##XVbretxEEv3vpyi8BNvE7khqXVp2DAuEyy6wgAPkY5OQ7Yt6ZhiNPFF3MhkWePXsqZbG7K4@z8VS96mqU6dOz3Yfl7dD8Xa12d6OkW7D0W0QYR9itzk9efPG0cVIYjVsX0URV7f0AemTs6OjdIOuqdcb4/QlnfSWdoHMYhiGBUVaRHo97imOjjyFGHHT7Gk5UghxpIHiksywPqeBny9f4/EQl2mnu6TB0khxZyksaelou3V4mras7yAQbHTD4pwMnvCqgbY2jrhLdng9hjgEDnNOxwixW0YKDBAQDSjnx/hngZvI@ngX8eX/9354/Gx4zPERxw7BjZwhB98NtAHiaaBd3wMPS2zvzsmPjA8kt6eN45W@TxSEfrvnMkPcurNzTmWZlm77gDW0WQOZXNhfkF0OAHVkaDdiAf@NpseaReJvyyhby@vxyIXAYAMF54Z@T/QEsW8M2Ngx@LCmPeoZkFyYmBfPhu@XibeJ6UAvkN4LGjfjGlG4JfGKhpGcY1qwZk3xbtXGIhukAuzdnglPNaR4gf@PoffgGnmN79D0DmrAkKE@vnNMpynV5Uw7i4N8HHejQxWRrB0hlBk18rpp1fI1@HbpUVyGudfMywafTD@YfhlR0NifXfFTjnLIy8YevLyIawIlh/TRthBtvACP8UWSX79O8Ok7ikYOiDecMwfQWZzT8nFqMboaIDY7hsC3N2lTnIUK7ZDBqjAQjYdWcLvnoNw94Ix3CcX1lFUKbkYeHd4C9Lg/Z1BuIIfCTQ9lgLJ5sR/jEFEe2vlLiNy9TeoWlLwlB5FSPy5SEhdLNNdN6nQLqGBgASD1DWaKV@6GNAcHbNSA@TtofrmbhnU3Ivw0Dmm48TYkRd3FYBgQxo0bQCpRHIaeOQsbSOaOXsfTPGsW0c95hKb/4jSPyzTsU3pxkiGLLG63nM4InU0cg5HBzTd83@NhKptHzm15OJHePGo8qUh8esT88@b@MJ67fp96O5tNP8Q992QzDfduZilyTSZpgStJuky@AuBFMq4lMqThTRT0GfqX2heTdLGREbBtw/3eTXphY9nwxlnWiVk3TkM37HlGrxJjWDtrFP7lwjyEfZ8oHaKdFBiXEAObDvqUNLQ1GK6kq/UFJvF1uDrkvky1hh1ttmHyFPY@9gQUsF0EQY@XLM3E5y/AHDdoaQqbgCZitiG4qynv3nDU45t/fE5f33z91aPjgyuPtMCR4gKYiVM/sXqzjftLRnCp0/061b1l@BQs/dE6tTTgdGH3HNFKlgoIYya2DDXEQ1ZzreHQ1y0mIoqTt6vr7MjfwtRpNdDtthtOT3B4ibHT7vTscnW9evhQ/XY7ulN7dhSu05F2ena1xq7dctV3tLoM1@Hp5fr5/RPdrW5fffTp3745ebp60N5rn98PT9eXz6/W969X99r7@dXqwbXKj7bjisfg7dtsvi6paeqcXFUq8s60VOiuJq8qQ6ZVlrq8yalpTQ1P0OILId4X4qkQ4uVeHE0IOTC8z1tyudZUqsZT4YqGMukrvGWecq8RwVcNEXYC5OJETNeTGaMARlZVBXW1lViqMtJdZ6ipnCfVakXGVS1VVaeBcTNtfsVvP/1wyEMCoyjKkrz1mkymaupUZalQsiLTZZoKmXVUN0iGjh8liGenlRB/EYsDRgkM7VxHma8dFV1bAEgqajPwUXWNxkmQlWQrWadaNngp8fTnX/FZzxgVMJzDUtPmBbWqbagtbEa@yzXVpfeUlRacSsV8/DozIRxe4ZBHzXk0qiDPO7Mqzygvs4zapihJNbUn1xUVyVz7idN0vStuxb38gNFwXzJbkSpbHAiuNUhe16Rl4dCmTFHHbS2K3P4XxgVaLI4PGAoY0uQwMI@2StW1lHd1S7os/MRMaeoKXWtLoqtEhliJB0J92YkDRguM3GFB3ZQSS/OaKiORDFflGiTYGNlR6WXOeSw@gcAYSvz7g2/yGUMzp75BSzxSqAuooqpAorRlhTZpSKNpGmjXM8bvD4QRP4iHn0Jgu/cPeRiuxbUWMSE02dYSVTlFjW8M6Qz3ykLi4JLKEF0LcdNaTkLcfHx9V4vlWlTeQZh1QUVdScp0iTy8Kal1UHirJSLUIAW1vDLvPRYffYg0xEPRzRgucWocVb7SkAHQStNKkrJQpLLcYeYMml5yb6/Ei38G8aWQp1N7ZoyO9WGqnCCxGktZaJ1GWkYBw1mcj20L8BpyIfGdeC/xmRBevztjeJ65Gj3IkDhpBeq6tsxweFUduULlVJTQrpdNcaePv4qfWWZiPJpHn/3DZY40ZIHAGE9d45tU0LrOJcTaAqhlJ6HfZxBopPyzlpz9o64V@JO1oVo2lttUkikwIErrCkVilmVetEReiLX97XpGys9mDPYPW2MBVI5kbMPRkZbMG0VFBXNqddMR1MLzcoatmLv8zT0h/hAvZgz2D@McWMjRiKqoLakODbYdmLFdh3sWXdZskszH6U0vHicT@bMW9o9SuwKiKjEvTduiwR47Obcih4nUZeVACkyV/i7ENw1m/sezd5665@LljMH@kXW@oaZQ3FsLF6jaGi3hCrxGS0xZT0uQxzhR8Qden93lkfyjgx072WJ4c2jdNUxPBmKVAhC8rCLMYjv31iZWgKJXMwb7R@crmA7kSarSGZxEeSqhbiplDhuUwIBc2Au/ndL42n/CHz/OGOwflcNUudqxaxhwquDwymGnlFB9VuMeJJMRPT@0VUi8hn/NGOwfbYnjqWy8xKDmhmTdsZ9K1GfrDk7pGtIajk3ii8/ZioW4FAP784zB/mEUS1RWaKGGcWUShlg1mJdaygwFOUyCaaYz6nsW6RNhM1SzmzGSfxQ4ilwJPRkmxeVdDhPp4LG58fA2jQSrEv5RiP@5vpwx2D@aAvOVKRAr2wbyKg3cKPdIRuO0siV@L9m8xMyNP4tv2wCdin@yxD6eMdg/rMLsZ3yiauvhyYWFPjqckBr2hSK7DmJFBJ79JymDn7iiZ9/OGOwf8IsCKoLfAKdFq8GpURCm1FBK3VloN6/nM1vs@cy/PBvEy8WMwf5RWlSMkQUfOc6S2iiJ0x6z3HSsNu63lzit6CthgbBmibHObo/mYz@dDfz7o0D3MKcGh51tkAfEXRhQ7DVO9LaCt5HQYvNdSua@EI8OWi/YP5SSHqskCGhhecYjJvyigT6QUVPC4NqKZ058KNp0TuKK4jBzBfsH3ApqVghXVZhzg9OAZNUiNwcj4qbOl/hUPPoBPxsqbux/AA "Python 2 – Try It Online")
This needs the following data saved in a file named `a`:
```
00000000: 7761 d548 fdb9 2ae6 f85b b98c e171 79b6 wa.H..*..[...qy.
00000010: ff19 d1aa 487f 2d27 03f5 030f 1fa1 df57 ....H.-'.......W
00000020: 0552 e6c3 df80 aeeb 75df 89a8 bd59 55ea .R......u....YU.
00000030: 2244 fcfa b086 e85c 2835 be0a 230e 67a1 "D.....\(5..#.g.
00000040: adde 0f6d 2e92 b038 905b 5e7a cc04 c536 ...m...8.[^z...6
00000050: dd7a b912 9897 92c0 fe1a 64ff 04c1 7387 .z........d...s.
00000060: a782 f2c0 0510 1400 9724 876f de25 31af .........$.o.%1.
00000070: f0c5 849d cd9b cca6 a32d 4808 e9b6 221c .........-H...".
00000080: 3b1f ff7f 38e9 1e69 a42f b038 4b65 e694 ;...8..i./.8Ke..
00000090: 1d94 6743 e616 5b3b c510 d7c5 7b3e 4f31 ..gC..[;....{>O1
000000a0: df7d 2fe9 62df 55c1 3c45 2ea9 5777 2af1 .}/.b.U.<E..Ww*.
000000b0: 3d9c d752 3963 ffd8 7f7b a052 423d f38b =..R9c...{.RB=..
000000c0: 181e 7562 2653 0a41 3fb4 9d57 9a3c d665 ..ub&S.A?..W.<.e
000000d0: 3bbd 5f5a 731e 4b93 3328 801d e1b0 04af ;._Zs.K.3(......
000000e0: ab51 9126 0412 9eae 7b88 8dcc c99a 7624 .Q.&....{.....v$
000000f0: 0610 09d5 a8f1 e940 bf5e d281 2497 f372 .......@.^..$..r
00000100: 7d0d a1e6 8dea a6e6 381a a134 8981 998c }.......8..4....
00000110: 6684 936b 637c 3d94 b287 8aa5 9186 3129 f..kc|=.......1)
00000120: c629 d9bd ac7a a10d 3178 2519 9a7e c45f .)...z..1x%..~._
00000130: bdd1 e128 526c 8e53 cef1 cee8 5cb4 adb9 ...(Rl.S....\...
00000140: 4ad2 7f4f 3799 73f8 5629 215b 645d 8971 J..O7.s.V)![d].q
00000150: 0ef7 7286 04c2 f596 d27e cfa7 fb46 0ef7 ..r......~...F..
00000160: aeaa d39f f163 d729 d094 887e e7a5 6169 .....c.)...~..ai
00000170: ef50 94b9 85a0 848f 4d66 4314 c3a5 bf56 .P......MfC....V
00000180: 5d3d d6d9 a4bc 88c3 8da5 3393 06bc 6e60 ]=........3...n`
00000190: 9448 47f3 a01b 36e0 fe3a dc6e a7d7 aa6d .HG...6..:.n...m
000001a0: b8e6 8354 aa38 039b 5788 6330 43d0 0b77 ...T.8..W.c0C..w
000001b0: 32a8 d419 b4b9 d1e1 ffe5 81bf e6a3 a54b 2..............K
000001c0: 725e 0850 3973 c4b2 31fb 5a5c c4cd c142 r^.P9s..1.Z\...B
000001d0: c851 0f57 acf9 12c6 de59 af38 83ee 5c50 .Q.W.....Y.8..\P
000001e0: eae2 0e1d f579 efe0 b871 3a29 6ec9 7167 .....y...q:)n.qg
000001f0: 4ca3 6379 b1b6 6b83 1f84 7e29 d4bc f36f L.cy..k...~)...o
00000200: 1d61 d26d 519b 05c7 b8f7 2bb9 fa44 95ae .a.mQ.....+..D..
00000210: 883f 9539 a924 bf6f 1297 dc83 74d5 9571 .?.9.$.o....t..q
00000220: 1345 b844 55b4 b423 3591 dd87 4b .E.DU..#5...K
```
---
# [Python 3.8](https://docs.python.org/3.8/), ~~848~~ ~~800~~ ~~789~~ ~~780~~ 776 bytes
Function that prints the result.
```
def f(s,k=0):[print(end='AEIOaeiou'[c//9%9]+s[k:(k:=k+c%9)])for c in b"R7/'.8:A017/B8=08/C/('B%:A:AAA.C70/'-./8B/?B080'-%;J9'A8I/BA/%6B8:)&:.I.A&?E?LR708?K8I/BA/%6EB/'A7.99/C:'0(/?MC/B'%/0-02-0)I</10-%I.B%9&$<$9?L/E0?J.B/9J(8;/$7620J1'7/&9:9.0(@22./'A:B2.&&.:(B8R7099B2K?JC/'A-(/&9'@82o-'o-'f(/%310?L8@/&/)8AJ0A1(.?MA%/A./(:J(/7.8(-.0H7/%I)L1/&8&H*?A&(?JA:$9?'A1(?@/&9)0J6/BR70&0A0-1A:&/&C0;(/'.0.@/-/&&99-8/&$9?(A0A&)A%.?JA9(J::I6@</&&D/60&/9(AI%1'K97/A-.9BB&&/&[[email protected]](/cdn-cgi/l/email-protection)///e%A0@1C0R7.&/:./A/A7.:A:/E/'A/?J%$;/&9@/3$:B7.&J0B@/')080J2DAJ3&R7/'A&@1B9%?LA:/1.@0/?L/1&:B&1-01Z81/1'1-0C/12EC/(1B7.(/1CA?A%?K/(AA1''?:A&02=060A?BB(%.?L(/'@:BJ9'?A(A-.(<1/?@/(/7/C/1(@71(0./80:J?((?C/1..).0/''(8I0KIB3/?BB&([[email protected]](/cdn-cgi/l/email-protection)//(/&09'%/0mS\SRR^KA1-'7&?909&5/9B7/BC/'B-&B8:@.BJ/-)A%%0AJ88@@.C/J?((/1'8"]
```
[Try it online!](https://tio.run/##XVTvb@O4Ef1@fwXPiH64Z4mUg8aSvIFMedOelWwLZAsU6O52UUtrK2eJq5JsdP7r995Qdj4UMBKbnHkz894bDmfbfle36aB//Gi@HdghNIvTvZjnnwb9omz4TTX3gXzY/f0/316@/y/4VHOeedmXX8ynUx6e8vvTL7WXzb/MD981q9mLYvvZ84oHcZpLkax4md6LlG95GJReLnMpZbxdCR5EMU9LXpQiFUHkrasskOmOl5J7d2Waz/083sXSLx6Kp@eVSIvH6@VDyQO5irOMb/NAhLz4sOVl4HERiWUk5rt3PBGRt4tLL/Nv3t1kxRN/EEUVlzyrwnTNb1Z3S1ElwYr7WZ7FItwslzEg83IZ@36ch2WKgllWLh@LaouLKERksEmX36MAn0PIvdtEFE/phvt8nspKyCSMiw/S4zLmYV6FfBWnYRSLX1fc282fEu6n/q9/KqQfFpXM0VKAjALp2VxUd7xEPV9IESUy97m/FesQ9Il4wyPu@1kWpdxHUiiF9OfSiwGShVWe7@427xDwnt8Jn2eh3HlJ8JituIzirCx9QGWbuEo45988KTbJVjyvYp/nMZccDEIM/oD5eFF5N2sK5rc3eYmQSpQbHsyhTLV8L6tbn/SU/iYpM694QloSbwQHsYmfl34SieRfacKTAN@2PFk@QOwEOCFPtrKQXvHIQymTIChy6YvlvbgTsijLEJM8YdJNXkL8QoboO3yXcBADBuGYJNysklDAJyKvijAscBTH8xjmCcJ0Jx535S0MVPqh3MRbwZHmi4ys0H/8/PH5@d@PMomClV9kIvP/zLMSZoSgZeTDYJu4rHgEOj0hqzTdAIFTEYyRzr78eGH3LOhqNhq2Pyqljsyyo2Wv@sysbtiBGWtxuD@zVjNjrGaK2Zbt1WnBFN23r7hWtnWZTc5UzTSzY81My9qGDUODW5dyeoNAMd2o44LtcUNRig211ThltXrVxipDZRZshhJja5khAINqQFnM8OOIQ3Q9Gy2@/H9uMfusPlJ91KmVaTR1SMVHxXoghoaNXQc8hNRds2AHTfhAas6sbyjy0DkKTDecaUxjh2a@oFZaFzp0BjGsPwGZNeYcsbpVAG3Yno0aAfTR@w4xR8ffQChDTfG4aowhMMVM06juzNg/Uft5DzZGAlcndsY8Cs2Zifn4s/pH63ibmDbsK9r7ynSvT6hCktg1U5o1DdGCmBOzb1F9jW7QCrDHMxHuZnD1DP22pjuAa/Slf2bTX1ADhvassz/PWOhabS@0kznYwepRN5jCsrrWMMoF1VLcFNW@gu/GXdnWXLQmXnr8J/rB9H8tBtLdfE23VOXaV2078PLVnhgoubYP2YytbQQe7Vdnv@7k4N13DI0eUE8tiAP4zF7aOthJYqhqYLZaG0PHvUuyF6PCO2yPKKMY01cpSO5LUVIPOPqtIXuaunLF95pWh1KAbs8LAiUBqRQOD3AGKLsEH7RVFuNBzt@MJfV6pxacPLAGJmWdPromohbiNpM7myNcoMgAaL3HTlHkqNweXLExA/bv6vl2nJZ11Cg/rYNbbvxRzlFvNQgGhJFwCqQyZpXqiDPTwzJv9Da0zRfPovqCVmj6Zad9bN2yT@3ZyYZkMjsM1I6GzyaOwYhqLgeHrsOlG5tWrhloOdHeZdVoU9H4dEX8U3J3Xc@xOzttL49Np@yZNOmn5R4vLFmaae@8QJM4X7p3BcBH93C16JCp323M/gL9nHzWWReJhIC0nvQeJ7/Qw9JT4sXWjtlGT0unzrSja8cYYi8exfvVmMsSdp2jVNl6cqBtYQZ6dKCT89Cwx3I5X50ibOKrWV97b92sZmT9YKY3hd4@ehMwwHA0MfvYkjUdn78BU/eQ1JV1QBMxgzHNeuq721PV2fPf/so@PH94ej@7vsqaHTWGMmDGTnoiuh/sOSeExindndzcA8G7Yu7DTk5S0@8bej01pCSrgDBiYiAoZa9dXWY1V10HbISNg59@OoQv8x9/AA "Python 3.8 (pre-release) – Try It Online")
Observations: `U` does not occur in the original text, so there are only 9 distinct vowels. There are at most 8 characters between two vowels.
This means that the value and position of each vowel can be encoded in a single base-81 digit.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 496 bytes
```
UT≔⮌⪪⪫E⁶S⸿¹θF”}➙¬⬤"K9dSmD⸿¤{qW26↶s›P?⌕»´[↧!²⊖~ks×◨﹪§^“σ@{″¦YO↓⊞⊗←,÷@vⅈ8⎇▷➙↖✳H Σ⧴Z↘?γ↙&HQ⪫‖³↗↧¦rⅉ⭆&(\²≡›¹,↗&~H*oηoIs·D +N⍘q↑Tθ7FI#*Nr↔№↘№⊟º⁼¶⊞↶⌊ζR‴C﹪-➙∕⌕∕Π℅ΠJ→6◨∧%9¤ÀAσRH✂,&πC∨<I=À=≧d⊗↓‹YA‖Y%℅_⦃⁺»⌊ζ⟦J≦χ:K3» ,M±g±Φ→*›t»Sυ_¶pA‹↷e¿ ⁸2+∨X⁵SmWAL]FK÷)›¤1⭆ξp₂T>V§?″(↧⁴↙b⁸1E↘Vⅈ⊗Yb⮌¶¿%℅Π;⁴Hz⊙0.×℅BSUa⁻~e⁶⸿⍘ΦδDÀ»m±D±≕Ss⌈βA|QA⌕↥D¬μB→↔⌕◧E℅⊖HιVU⌈τ↶ZF1Sn⌕\¤�|üA§Qt⌈⮌ρ»≕↶⁵Ks3ψ→χ}⌈093⦄LgW‴ιO².huρ▷⊙�K[№ê←⁷D{π▶BêTBAvlIθn⧴P;⎇ÀPξ→↘υU>|⌕⁺;⪫ω∨⁵◨‽Z⧴﹪↓ΦLτ,‖&!,⊗αJ-κ·Z∧⁼1⁴8№✂τEΦχl}§SV'‽5⊗⸿β=¤|KCTG⦃”«§AEIOaeiou÷℅ι⁹F﹪℅ι⁹⊟θ
```
[Try it online!](https://tio.run/##XVRhb@M2Ev3c/ArWiCX6EImUF40leQuZ8qatnaQtkgUOOBS3iK3Yci0xWpIb1yjut@feUHY@FDBsWZx5M/PeG67rJ7N@eWre3j6/bLfN82eza/loeqGs3W01f3h@fTb2mT92zc7x5ctO8/unjl9fsYXuvrlHZ3Z6y0ejKzb4wwzwk9DzVwBsXgzjg4eJCOM0VzKZiDL9UaZiLnhYDnOVK6Xi@USKMIpFWoqilKkMo@F0mYUqXYhSieF1meajII8XsQqKm@LuYSLT4vZ8eFOKUE3iLBPzPJRcFPdzUYZDISM5juRo8VEkMhou4nKYBZcfL7PiTtzIYhmXIlvydCouJ9djuUzCiQiyPIsln43HMSDzchwHQZzzMkXBLCvHt8VyjoOIIzKcpeOXKMRnw8XwQyKLu3QmAjFK1VKqhMfFvRoKFQueL7mYxCmPYvnLRAwXo7tEBGnwy78KFfBiqXK0FCKjQHo2kstrUaJeIJWMEpUHIpjLKQd9Mp6JSARBlkWpCJDElVTBSA1jgGR8meeL69lHBHwS1zIQGVeLYRLeZhOhojgrywBQ2SxeJkKI56GSs2QuHyZxIPJYKAEGIYa4wXyiWA4vpxQsPlzmJUKWspyJcARlluNPavkhID1VMEvKbFjcIS2JZ1KA2CTIyyCJZPKfNBFJiKe5SMY3EDsBDhfJXBVqWNwKrlQShkWuAjn@UV5LVZQlxyR3mHSWlxC/UBx984@JADFgEI5J@GyScAmfyHxZcF7gVRyPYpgn5OlC3i7KDzBQGXA1i@dSIC2QGVmhffzj8eHhv7cqicJJUGQyC34QWQkzQtAyCmCwWVwuRQQ6h1It03QGBEFFMEY6GLG/L777HSZ3XLmFrp7/4gN1s/jt6Xn38m1AW@A@7V531TP/zVQ7/dTwHfyfjUbYgO/8Cty/VN@al38esx7z95eOf6XY/729NWt2sGy11VpvmWNbx17NkTlTsQ2zzuHl6shqw6x1hmnmarbS@yum6bx@xbF2tc@scqbXzDB3WDNbs7piXVfh1Kfs3yFQzFR6e8VWOKEozbq1M3jL1vrVWKctlcFmo8ShdswSgEU1oFwN8GeLl@h6cHB4@GduMbh4pPIos9a2MtQg1T5o1gKQW3ZoGsAhZN1UV2xjCB5A1ZG1FUVuGs@AbbojTWldV4E8dFL70K6xiGHtHsissseIrWsN0Iqt2MEggD5m1SBm6@nrCKVbUzyOKmsJTDNbVbo5MvZv1H5YgYwDges9O2IcjeZsT3x88bn2rPU8W/YF3X1hpjV7FCFB3JRpw6qKSEHMnrn3qHaNZtAJoA9HotuP4MtZ@u9sswHTaMt8z/pvMAOCVqxx3w8Y953WJ9LJGmzjzMFUGMKx9drAJidUR3F9VP0Kuit/5Gp7UppoafFL7IPorw4DmWY0pVOqcu5r7RrQ8sXtGRg5tw/VrFu7CDS6L958zd7D@2cMjR5QT18RB3CZO7W1cb3CENXCamtjLb1ufZI72RTOYStEWc2YOStBap@KknjAMe8NuX3flS@@MrQ4lAJ0d7wiUNKPSuHlBsYAZafgjXHaYTzI@ad1pF7r1YKPO1bBo6wxW99EVEPcqjdntY0vNOmPzlssFAUetF@CMzRGwPKdHV8f@k09GFTvl8FvNr40@em9AqGALpJNg1LGnNYNMWZbGOad3Io2@WRYFL@i/en/uX4Xa7/ofXeuNyFZzHUddWPgsp5h8KGr04tN0@DQD037VnW0mfHFac1oS9F2f0LkU25zXs1Dc/TCnu6ZRrsjCdL2i304ceRopJU3Ag3iTemvFABv/Z1Vo0Gm/3Ix@wniee2c9y0SCQFpLYl96M1Cl0pLiSdPe14r02@cPtKCTj1hiD0ZFFdXZU8b2DSeUe3Wvf1cDSfQhQOVvIG6FTbLm2ofYQ1f7fTce@1ntQfWdra/T@jaowsBA3RbG7PHmnzp6fwTmKaFor6sB@qJ6aytpn3fzYqqDh5@/ZndP9zffRqcL2TDtgZDWTDjejkR3XbumBNC5YVu9n7ujuB9Mf9he6@obVcV3ZwGhiWngDBioiMo7c5dnWa1Z107rIOL36LX5v8 "Charcoal – Try It Online") Link is to verbose version of code. Based on @ovs's approach. Explanation:
```
UT
```
Turn off automatic padding.
```
≔⮌⪪⪫E⁶S⸿¹θ
```
Read in six lines of text, join them together (I could have used `\n` but `\r` made the code easier to write), split into characters, and reverse, thus resulting in a list that I can pop as I go.
```
F...«
```
Loop over a compressed data string.
```
§AEIOaeiou÷℅ι⁹
```
Take the ordinal of the character, divide it by 9, and cyclically index into the list of vowels. I used the character codes 36-111 for readability, making the uppercase vowels use codes 81-111, with the cyclic indexing mapping them to start of the list.
```
F﹪℅ι⁹
```
The remainder gives the number of non-vowels to print. Loop that many times.
```
⊟θ
```
Remove and print each character as needed from the list generated from the input.
[Answer]
# [Perl 5](https://www.perl.org/), 862 bytes
```
$g=join'',<>;@v=('aeiouAEIOU'=~/./g,'');for('%21@Q2BcAQb1CRBZaRACa@`SP2cBcCCA3b1Q@Q!1BCQC#QRAPQ 2ZDBPSBD1CSA@2#RB`Z@Ba413@C#ZS$e21RC$RD1CSA@2#ZSQ@SB12RQCb`QPaC$ZCaCPP1AQ!QZA!PZD2ZQAaQ 413P2P@"ZP"S$aCZQS$A3QBT@bBZA@"2!ZATA`R1@BRbQ1Pc1ZAZA1@SBcQZA0@A2`cRE21RRSQZDS$Ca@SA a@BPS2AZHQ XQ WPa@1ZQaS$bC1@A@ZBCDASA`a3$ZC@1CA1@bd@aB12@a!1T"1@40ZDaa@B@D ZS#@@c$CB`"S SA`c#1@BPZATB!CU21PASAQ!cB`A@CaRZ@a@Q1Q31A!@@BRQ"A@@"S cAS@@ZC@13$CBPdBbd2#2ZQ@@CZAB!PABPcD01`TRR1CA!2SSP@A@BS14AaAAG@3AS1caU210ABa1CACB12cBaCZQ@SAC$@0"ZA@BS1AZP"cR10DASS1@PZARATAZCZCDAZPE21@S@C1cRP3$cBaAa31QC$aA`BcPAa!Qf"AaA`Qa!SaAaZCZSa@acR10aAccC#@3$Q@cCA`PS"c@AQZBZaR!SC#SP`13$`a@S2cTBPS#@cA!0bZQaC#1@aB1CaA`c21`aQ1BARdC `c#aAa10ZA1Q@PPbD1TT3QZQC#SP@cC13aQA@a@ARPP1AX5FEE56dSAa R0C"QRPAZqBSR1CSa@SQ CRBc13TAA ZC@01SDBBC313aDC `aA`R'=~/./g){$c=-32+ord;substr($g,$p+=int$c/16,0)=$v[$c%16]and$p++}print$g
```
[Try it online!](https://tio.run/##XVTvj9u4Ef2ev2Js67C7iHdj2kk@3HZbUnLuWqDX6ocPd1BRxBIZW4llRkfy1jWK9l9P31D2fihg2JY48@bNmzccPrn@3bdvyf7py9fP9uZm/oc/Psrnp9ub5tPnr7@rD3/5@883T/998/BmP7@5uXvcfXW3N98thSyWqVZFK7IyrZtSZY3cVvlSpzrL1KoVhSwmIs2KbFaUKi9oWa/TvErXIquUXM7KdFvLtHkrVjKb1VXyaSnKLCmvx3VVyCoVy7LI2m2RN1lSZ02W50IVk6JWk7xeL@tCNQUBIV/mclrn0yppsrqoErUq0o1s01rJ6XJSq43alkKmZVuIXIta1UoAXANnIdVyq8sPKF5WRb2uErRRKWokuC5V/eeCfi3ol7yRoi6aKmkzIZWs02ytKrVtVmAlRQa41sgGdGUzEZupkG8X9boBiFxTXc2k1EmWbqcVIUnPQCUHqXSS/bwUOYCKiU63SmZNWctGFqJYCTWRIFxMlZRI06qSkkutgJObtDXLGdqXMqtVOslVmuv1Qmw3ZQkyk2VV5WCZVuKtapT6Ua5UJXSDYguVNojIwFSnrBV6zRK5mNYxXEFDXYoFmquEBMcS0tVZjW7rHBrJSmZCl/kqQbZqVqLIkkZtU52rZlLspqi2LZpJhTNkVY1sGK1RWmczuUoKqTO1zauplqqo2TSTKptV@RZtbSH7Um@g@kxqNVm0kDuDUhA1A6peim1TiFSVJiNIiApigTEWMs/btdhsVkVdMBZKiFVTKOioSrbLr@9@@PDh3XtTqYbKRTYtylzVv6UVlALBqiDYV4vVRimCwAtRrdM0WwFjjUKoXF68f/fvRD/dr5avvzrz6H9vfXC3yX6eDK@fPtuQ6Dfi/Xxx95Q8/yPR34n3/2yswdnr/wyOj/ffvvWaTp7avbV2T4H2gZ7dmYIztCMfAl62Z@oceSCTpdBRaw9zsnzePePYhi5mmu/JanIUTpp8R52hYTA4jSmHFwgUc8bu59TihKMsDTo4vCVtn50P1nOZOU1R4tQF8gzgUQ0o8yke9ngJ1tNTwJ//z/3T9FXF5VFGW28cE@TaJ0tHAN56OvU94BCiezOnnWN4AJkzHQ1H7vqogO@HM3fpw2Du5syki6FD7xFDxwOQyfjzPenOAtRQSyeHAP64tkfMPso3MMqgOR5HxnsGs@SNsf2Z6BfULluIcWJwe6Az2rEg50fhH15tuqjaqLOnj2D3kdzRHVCEBxIeyToyhkVBzIHCS9RRgwyYAPp0ZrljC7Gc5@fg@x2UBi03ofEbykCglvowmdJtZNpdRGdr0C64kzNoIpDWDja5oAaOG6O6Z8ht4lHo/GXSLMsRv6w@hP4toCHX3z3yKVe58tKhhywfw4GgyJU@puaDDveQMXyM5usPET7@R9PggHp2zhrAZeFCaxfGCWOoHlbTznt@fYxJ4WJTOIdaRHlL5K6T4GlfivLwgONeCIXDyCoWbx0vDqcAPZznDMrz41J4uYMxINkleOeCDWgP4/ziA0/vGKcFHw9k4FHq3T6SuO8wXDOa0@wfXlmeP5gfsVAceLJxCa7QaAHLd3V8dxo39eRQfVyGuNn4suynlwqMArl4bBaSEgVre1bMH2GYF3ENb/LFsCg@5/0Zn8K4i11c9JFdGE3IFgvDwGwcXDYqDD2subzY9T0OY9O8b2bgzXx4dVkz3lLQHk9YfM7tr6t56s9xsJd7prfhzAM5jot9umgUuKU2GoEbiaaMVwqA9/HO6kCQ7L/CA/2A4cXZhehbJDIC0o487NNoFr5Ujpx48XTU1bhx4@yZF/QxCobYi0FxdRl/2cC@j4raoEf7hQ5O4AsHU4oGGlpsVjTV4R5r@Owfr9y72Ks/0XHw433C1x5fCGhg2PsHqjr2ZZTzCzDdERONZSPQKMzgvXkcefctV52Wf/uRfip/@ut6er2QHe0dmvJQJozjRPRxCOfvGcHEQfeH2PfA8LFY/NAhTtQfW8M3p4Nh2SkQjJUYGMqGK6tLr/461wHrEB7@Bw "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~817~~ ~~816~~ 804 bytes
```
i;a;f(char*t){for(a=0;i="[A80:ABM9:D8KCB>C9K;02L1AMBMKK9JD8:0:78BK:KI:C91:.AWB1LBT8KL90AICB23B;S8J0KIOR_A8CKRCT8KL90AIO:0LB8AC:KD2:1;KRN;K1189:7:<71WA=9;:.S8J1A10@4@LR;K=LR9J:BU0DB<0@A7<U92C80BCD:81M8<<80LBM:</09A2MC]A8CCL:WLRK;0L9.;0B1LA9{:.y:.p1;08=;LRDK8090EKT9L92;JRN08K980DV0;B8A0;78U@80S/W;;[[email protected]](/cdn-cgi/l/email-protection)<UB7K^A819L9:7MB290K;C3;0:8:J89700BC:@[[email protected]](/cdn-cgi/l/email-protection)=00K<B719B1MT/82UCC8K97ALL1090BL8S9;99o0J9L8M;^A8/9B;8K9KB8AMB;K=0L9KR0/@<0BL894@MC8/T9LL801<C9U9NNT94]A80L0K8MC1JRMB;9;J8:KR;92BM19;7:h@9;92:;7L;9;NO;0;MC8/;9MMKI0JR:0MK921L@M09:E>C7LKIL128JR2;0LAMUB1LI0M97/D=;KI80;B8K;92MA82;:8B9CVK.2MI;9;8/<8:011DT8UUJ:=KIL10MK8J;:90;09C1189y\\f]]\\eVL9;.C/K@:C19?BLC8KL;0L:.KCBM8JU99.N0/8LTBBKJ8J;TK.2;92C"[a++];t+=i%9)i-=46,printf("%.*s%s",i%9,t,L"aeiouAEIO"+i/9);printf("t.");}
```
[Try it online!](https://tio.run/##XVVhb@JIEv2@v6IXaaRkh0CbHR3dbtjFNnMnsJ1IBJIPy2wU7AUzmB5vd184NLrfPveqDflwEiLYXfXq1atXneJuVxQ/fuzVq9reFNWr@cXdft9@MzevY672484fkeBhFOcynIo0iX9LZKr4IAuiPM7TVM6nIuThUMRpmM7CRAZhL3qOgyxeijSTPJol8eDXWD2KOU9nD4uXSCTpIrkePoQ8i0WUhOl0EAYqXdyrNAiEDIfhaBg8R2Opwh5ygyjgk0@TbKHScbaQ8zBe8Wk84pNoOFrJQSJ4nExDEeRiNBKAzMNRn8tokCdfUDDJwudsAdqZ7CkOcpH8HvbOYa8JFBdjlS2mqeCSf06XMpMDNV/cc5FKwadPXIEeV0Oxmgj@2H9WyOfL3sOM83yRxoNJ1kNGPgOBYLSKh@mfkQgAEg7zeCB5qpJfFQ9FOBdyyEEynEjOkZTLjHNUmQMkeIqnT9EsGnOejuJhIOMgX/bFYJUkYDGMsiwAuTgTj1JJ@Y3PZSZyhUJ9GStEpKCYx1AG/aUL3p@MKFh@muSJ6KOjTPBglMiVvL9fyk8QhGc8FXkSzBdIk2ouwnSh5CDOA6mGYTVBmUGohhnO7h8UV4SjZJ6nMz5fhDxP5SDIJjmX4effkmGWzrJggE4GEDjKV9B3xnM57E/HKoUwUDAFYB6JgQpFLJOntAfFAC76I5gnCKZLsVrNwzEBAV3MVSi54jIhK5zX6@2XL@v1X0@ZVL2kn07CJJC/xxnEyVAx7MGVuZivpOzd877IlnGczoGxRBnUTTp/vH78@EW5j@P9B3m7vxt/@ke3MXvttjedD71f7Afb6eKk67pZ5/Wv/bd/R59nD52P@768Vdc41@vcqv/@wAM7vu71zdu3fXn703ec1AU7WbbZaa13zLGdY2/mzJwp2ZZZ5/Byc2aVYdY6wzRzFdvoQ5dpOq/ecKxd5TPLkOmCGeZOBbMVq0rWNCVOfcrhHQLFTKl3XbbBCUVp1hTO4C0r9JuxTlsq02XrDmqcKscsIViUA0x33cHTDm/Be905Ofz6//Tf1521fiQOqFVoWxpiSQROmh0BemPZqa4BiZCiLrtsa6gEoMozO5YUua29DLZuztSqdU152yU2lQ9taosYdjwAmZX2fMeKSgO0ZBt2Mgigj9nUiNl5DRtCaQqKx1FpLYFpZstS12fGnlF7sYEiJwLXB3ZGQxrkbKt@b62XldeuVduyF9B7YeZoDqhCY3GKacPKkoRBzIG596hjATagAuzTmUT3Pfh6lp6drbekN4iZn1n7DW0g0YbV7mdIfuPJVhfpySJs68zJlOjDsaIwsMsF11FcG1W9QfHSH7nKXiZOyhzxlwYArf92aMnUt4pOqcqVWeFqKPPiDgyiXBvA4Kwr3B2UdC/ehPXBw/vfaBscUE93SQW4zV1obV07ZMzVwnKFsZZeH32Su9gV9mEbRFnNmLkOgwZ@KUrzA455J@QOLStffGNogSgF6O7cJVAaIZXCyy28AckuwVvjtEN7GOhX62h@Rz8vmLlhJWzKarPzJO4qjLds/Vnu4ANNFgD1IzaLIk/a78IVGz1gC6@ur07typ4MyrcL4VccX9p76r0GwUAwGpyGqIw5rWvSzB5hmnd5S9rpi2tRvUtL1D65dicrv/ItPdcakWzmmoboGDit1RiK6PLyYlvXOPRt09KVDa0n6F2WjXYVxNsj0p@S6@uCnuqzn@3lyqm1O9NMju16ny4qOepp471AnXhf@ssFwDt/fVVgyPR/XI/9E/Pz43PeukgkBKQdad6n1i90tRwp8WJrr2xp2rXTZ9pS5RVD7MWjuMRKe1nDuvaSale0DnQVzEDXDubkPdRssFzeV4c7rOKbVVfule/Vntixse2tQtcf3QpooNnZHnusyJpez6/ANEeM1Jf1QK0wjbWlannXG6q67izu/8XyRZ5N153r7WzYzqAtC21cO1HEHxt3Dgmj9LOuD77zhgr4cv7DDn6o9rgp6QY1GCaZBZKRFg1BaXfldenWXifbYCcu/7H@Bw "C (gcc) – Try It Online")
*12 bytes off thanks to ceilingcat.*
The function `f` accepts the given text (without vowels) as an argument and it prints the desired text on `stdout`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 568 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ï¥æ£░iï╘◙±Γn♪º↔gïÇ┌#w¡▒ åñGD/U▄$╝·ñ}$◙d░╒≡%►Σ┘ô♦╙xWv‼╖♣╛Yn≤┼7F╛«hw¡9ⁿ─┤ê\Ω╜jo(⌠Å▌╩ó░W╙â≤↨7sp↨♪÷○|╫g₧ñ»Q█░╧║Ωτα¼óΘ(ZN⌐╥Uδ~♠*>¥1,╝ⁿf↓╓2à↑☼│Qp≡°▼σ§xó),┴₧ZÉvj┘ç_e└▬`;úpπ↔E¬ƒ▀╘W○ß╫ ì▬W○♪¡÷╥K@≤ZφÄó☼P+<☺øt│¥↨╪ ê▄kI[☺╟▀↨┐>t╦¢F-x╣F|h√ZiE3èâ¼⌠Hû);&Σî╩☺d4☺σi♂∞îóF:;▬╚↓┼F→C◄╓Ω!ß═xªÄ→δ½Gôº{E▲◄╩╫┘╘£o¡╟Ü¥_^+èê╬*φG╬æCH┬mfΣ±┬dï⌂¥àΩ¶ô}∞T▓$xÄú╤∙╪ué≥↕Γ"¢sÉ╬É↨v+gΔä╖§|9¥¶·¶üφ║⌂aΦx⌡-+Æ&bò╪A;Ä╙6╪âqë0Çv↔‼☺§msⁿùVz↨v☺ô╟òö┬♠╪X╢╗Δ√G2ñùP╛2ΩΓ∟↓¥}¿Γ¼t╒╩OS≥UD'_ç╩9b♂╚jy§─╒│42╨Éε░►ëφCº╬‼_ö█V/╖}Z↑2Δ^♪└∞ò1¿ö╨╗⌐╛┌I`π▓◙≈┌]▌#⌐◘Σ;Ç◙°╛vJΔÑ←│6éÆ*Ñ┬╒≥ε┼l&'W♠f┴]┴↓_┬╩ä╗▼╥r%ªè♣▓↔Φa»¬┌-↨d┤╛εE,↨²└╠YâVΦL⌂♣"╬b)╠é
```
[Run and debug it](https://staxlang.xyz/#p=8b9d919cb0698bd40af1e26e0da71d678b80da2377adb12086a447442f55dc24bcfaa47d240a64b0d5f02510e4d99304d378577613b705be596ef3c53746beae6877ad39fcc4b4885ceabd6a6f28f48fddcaa2b057d383f317377370170df6097cd7679ea4af51dbb0cfbaeae7e0aca2e9285a4ea9d255eb7e062a3e9d312cbcfc6619d63285180fb35170f0f81fe51578a2292cc19e5a90766ad9875f65c016603ba370e31d45aa9fdfd45709e1d7208d1657090dadf6d24b40f35aed8ea20f502b3c010074b39d17d82088dc6b495b01c7df17bf3e74cb9b462d78b9467c68fb5a6945338a83acf44896293b26e48cca01643401e5690bec8ca2463a3b16c819c5461a4311d6ea21e1cd78a68e1aebab4793a77b451e11cad7d9d49c6fadc79a9d5f5e2b8a88ce2aed47ce914348c26d66e4f1c2648b7f9d85ea14937dec54b224788ea3d1f9d87582f212e2229b7390ce9017762b67ff84b7157c399d14fa1481edba7f61e878f52d2b92266295d8413b8ed336d88371893080761d1301156d73fc97567a17760193c79594c206d858b6bbfffb4732a49750be32eae21c199d7da8e2ac74d5ca4f53f25544275f87ca39620bc86a7915c4d5b33432d090eeb01089ed43a7ce135f94db562fb77d5a1832ff5e0dc0ec9531a894d0bba9beda4960e3b20af7da5ddd23a908e43b800af8be764affa51bb33682922aa5c2d5f2eec56c2627570666c15dc1195fc2ca84bb1fd27225a68a05b21de861afaada2d1764b4beee452c17fdc0cc598356e84c7f0522ce6229cc82&i=lc+ws+bgnnng+t+gt+vry+trd+f+sttng+by+hr+sstr+n+th+bnk,+nd+f+hvng+nthng+t+d%3A+nc+r+twc+sh+hd+ppd+nt+th+bk+hr+sstr+ws+rdng,+bt+t+hd+n+pctrs+r+cnvrstns+n+t,+%22nd+wht+s+th+s+f++bk,%22+thght+lc+%22wtht+pctrs+r+cnvrstns%3F%22%0AS+sh+ws+cnsdrng+n+hr+wn+mnd+%28s+wll+s+sh+cld,+fr+th+ht+dy+md+hr+fl+vry+slpy+nd+stpd%29,+whthr+th+plsr+f+mkng++dsy-+chn+wld+b+wrth+th+trbl+f+gttng+p+nd+pckng+th+dss,+whn+sddnly++Wht+Rbbt+wth+pnk+ys+rn+cls+by+hr.%0AThr+ws+nthng+s+_vry_+rmrkbl+n+tht%3B+nr+dd+lc+thnk+t+s+_vry_+mch+t+f+th+wy+t+hr+th+Rbbt+sy+t+tslf,+%22h+dr%21+h+dr%21++shll+b+lt%21%22+%28whn+sh+thght+t+vr+ftrwrds,+t+ccrrd+t+hr+tht+sh+ght+t+hv+wndrd+t+ths,+bt+t+th+tm+t+ll+smd+qt+ntrl%29%3B+bt+whn+th+Rbbt+ctlly+_tk++wtch+t+f+ts+wstct-pckt_,+nd+lkd+t+t,+nd+thn+hrrd+n,+lc+strtd+t+hr+ft,+fr+t+flshd+crss+hr+mnd+tht+sh+hd+nvr+bfr+sn++rbbt+wth+thr++wstct-+pckt,+r++wtch+t+tk+t+f+t,+nd+brnng+wth+crsty,+sh+rn+crss+th+fld+ftr+t,+nd+frtntly+ws+jst+n+tm+t+s+t+pp+dwn++lrg+rbbt-hl+ndr+th+hdg.%0An+nthr+mmnt+dwn+wnt+lc+ftr+t,+nvr+nc+cnsdrng+hw+n+th+wrld+sh+ws+t+gt+t+gn.%0ATh+rbbt-hl+wnt+strght+n+lk++tnnl+fr+sm+wy,+nd+thn+dppd+sddnly+dwn,+s+sddnly+tht+lc+hd+nt++mmnt+t+thnk+bt+stppng+hrslf+bfr+sh+fnd+hrslf+fllng+dwn++vry+dp+wll.%0Athr+th+wll+ws+vry+dp,+r+sh+fll+vry+slwly,+fr+sh+hd+plnty+f+tm+s+sh+wnt+dwn+t+lk+bt+hr+nd+t+wndr+wht+ws+gng+t+hppn+nxt.+Frst,+sh+trd+t+lk+dwn+nd+mk+t+wht+sh+ws+cmng+t,+bt+t+ws+t+drk+t+s+nythng%3B+thn+sh+lkd+t+th+sds+f+th+wll,+nd+ntcd+tht+thy+wr+flld+wth+cpbrds+nd+bk-shlvs%3B+hr+nd+thr+sh+sw+mps+nd+pctrs+hng+pn+pgs.+Sh+tk+dwn++jr+frm+n+f+th+shlvs+s+sh+pssd%3B+t+ws+lblld+%22RNG+MRMLD%22,+bt+t+hr+grt+dsppntmnt+t+ws+mpty%3A+sh+dd+nt+lk+t+drp+th+jr+fr+fr+f+kllng+smbdy+ndrnth,+s+mngd+t+pt+t+nt+n+f+th+cpbrds+s+sh+fll+pst+t.&a=1)
[Answer]
## ES2015 ~~800~~ 799 characters/bytes
```
(i,p=0)=>[..."2h`X_ikrabh`sinai`t`YXsVkrkrrr_tha`X^_`is`psaiaX^Vl{jXriz`sr`VgsikZWk_z_rWpvp}2haip|iz`sr`Vgvs`Xrh_jj`tkXaY`p~t`sXV`a^ac^aZzm`ba^Vz_sVjWUmUjp}`vap{_s`j{Yil`Uhgca{bXh`Wjkj_aYqcc_`Xrksc_WW_kYsi2hajjsc|p{t`Xr^Y`WjXqicO^XO^XFY`Vdbap}iq`W`Zir{arbY_p~rV`r_`Yk{Y`h_iY^_ayh`VzZ}b`WiWy[prWYp{rkUjpXrbYpq`WjZa{g`s2haWara^brkW`WtalY`X_a_q`^`WWjj^i`WUjpYrarWZrV_p{rjY{kkzgqm`WWu`gaW`jYrzVbX|jh`r^_jssWW`Wjq_{b```EVraqbta2h_W`k_`r`rh_krk`v`Xr`p{VUl`Wjq`dUksh_W{asq`XZaia{cur{dW2h`XrWqbsjVp}rk`b_qa`p}`bWksWb^ab:ib`bXb^at`bcvt`Ybsh_Y`btrprVp|`YrrbXXpkrWacnagarpssYV_p}Y`Xqks{jXprYr^_Ymb`pq`Y`h`t`bYqhbYa_`iak{pYYpt`b__Z_a`XXYiza|zsd`pssWYrq_ta``Y`WajXV`aM3<322>|rb^XhWpjajWf`jsh`st`Xs^Wsikq_s{`^ZrVVar{iiqq_t`{pYY`bXi"].map(r=>
(l=(v=r.charCodeAt()-49)%9,'AEIOaeiou'[(v-l)/9]+i.slice(p,p+=l))).join``
```
```
const f=
(i,p=0)=>[..."2h`X_ikrabh`sinai`t`YXsVkrkrrr_tha`X^_`is`psaiaX^Vl{jXriz`sr`VgsikZWk_z_rWpvp}2haip|iz`sr`Vgvs`Xrh_jj`tkXaY`p~t`sXV`a^ac^aZzm`ba^Vz_sVjWUmUjp}`vap{_s`j{Yil`Uhgca{bXh`Wjkj_aYqcc_`Xrksc_WW_kYsi2hajjsc|p{t`Xr^Y`WjXqicO^XO^XFY`Vdbap}iq`W`Zir{arbY_p~rV`r_`Yk{Y`h_iY^_ayh`VzZ}b`WiWy[prWYp{rkUjpXrbYpq`WjZa{g`s2haWara^brkW`WtalY`X_a_q`^`WWjj^i`WUjpYrarWZrV_p{rjY{kkzgqm`WWu`gaW`jYrzVbX|jh`r^_jssWW`Wjq_{b```EVraqbta2h_W`k_`r`rh_krk`v`Xr`p{VUl`Wjq`dUksh_W{asq`XZaia{cur{dW2h`XrWqbsjVp}rk`b_qa`p}`bWksWb^ab:ib`bXb^at`bcvt`Ybsh_Y`btrprVp|`YrrbXXpkrWacnagarpssYV_p}Y`Xqks{jXprYr^_Ymb`pq`Y`h`t`bYqhbYa_`iak{pYYpt`b__Z_a`XXYiza|zsd`pssWYrq_ta``Y`WajXV`aM3<322>|rb^XhWpjajWf`jsh`st`Xs^Wsikq_s{`^ZrVVar{iiqq_t`{pYY`bXi"].map(r=>
(l=(v=r.charCodeAt()-49)%9,'AEIOaeiou'[(v-l)/9]+i.slice(p,p+=l))).join``
console.log(f(`lc ws bgnnng t gt vry trd f sttng by hr sstr n th bnk, nd f hvng nthng t d: nc r twc sh hd ppd nt th bk hr sstr ws rdng, bt t hd n pctrs r cnvrstns n t, "nd wht s th s f bk," thght lc "wtht pctrs r cnvrstns?"
S sh ws cnsdrng n hr wn mnd (s wll s sh cld, fr th ht dy md hr fl vry slpy nd stpd), whthr th plsr f mkng dsy- chn wld b wrth th trbl f gttng p nd pckng th dss, whn sddnly Wht Rbbt wth pnk ys rn cls by hr.
Thr ws nthng s _vry_ rmrkbl n tht; nr dd lc thnk t s _vry_ mch t f th wy t hr th Rbbt sy t tslf, "h dr! h dr! shll b lt!" (whn sh thght t vr ftrwrds, t ccrrd t hr tht sh ght t hv wndrd t ths, bt t th tm t ll smd qt ntrl); bt whn th Rbbt ctlly _tk wtch t f ts wstct-pckt_, nd lkd t t, nd thn hrrd n, lc strtd t hr ft, fr t flshd crss hr mnd tht sh hd nvr bfr sn rbbt wth thr wstct- pckt, r wtch t tk t f t, nd brnng wth crsty, sh rn crss th fld ftr t, nd frtntly ws jst n tm t s t pp dwn lrg rbbt-hl ndr th hdg.
n nthr mmnt dwn wnt lc ftr t, nvr nc cnsdrng hw n th wrld sh ws t gt t gn.
Th rbbt-hl wnt strght n lk tnnl fr sm wy, nd thn dppd sddnly dwn, s sddnly tht lc hd nt mmnt t thnk bt stppng hrslf bfr sh fnd hrslf fllng dwn vry dp wll.
thr th wll ws vry dp, r sh fll vry slwly, fr sh hd plnty f tm s sh wnt dwn t lk bt hr nd t wndr wht ws gng t hppn nxt. Frst, sh trd t lk dwn nd mk t wht sh ws cmng t, bt t ws t drk t s nythng; thn sh lkd t th sds f th wll, nd ntcd tht thy wr flld wth cpbrds nd bk-shlvs; hr nd thr sh sw mps nd pctrs hng pn pgs. Sh tk dwn jr frm n f th shlvs s sh pssd; t ws lblld "RNG MRMLD", bt t hr grt dsppntmnt t ws mpty: sh dd nt lk t drp th jr fr fr f kllng smbdy ndrnth, s mngd t pt t nt n f th cpbrds s sh fll pst t.`));
```
## JavaScript (Node/Browser ES2015) 806 characters
```
(i,p=0)=>[...'3ypgoz|qrypzqzpphge||oyqpgnopzpqzqgne}{gzppexz|if|oof3yqzzppexpgyo{{p|gqhppgepqnqsnqi~prqneoe{fd~d{pqop{hz}pdyxsqrgypf{|{oqhssopg|soffo|hz3yq{{spgnhpf{gzsSngSngIhpetrqzpfpizqrhoepoph|hpyozhnoqypeirpfzfjfh|d{grhpf{iqxp3yqfqqnr|fpfq}hpgoqopnpff{{nzpfd{hqfieo{h||x~pffpxqfp{herg{ypno{ffpf{orpppHeqrq3yofp|oppyo||ppgped}pf{ptd|yofqpgiqzqstf3ypgfr{e|proqpprf|frnqr<zrprgrnqprsphryohprephrgg|fqsqxqheohpg|{ghnoh~rpphpypprhyrhqopzq|hhprooioqpgghzqtpfhoqpphpfq{gepqQ4>433@rngyf{q{fvp{yppgnfz|opnieeqzzophhprgz'].map(r=>
(l=(v=r.charCodeAt(0)-50)%10,'AEIOUaeiou'[(v-l)/10]+i.slice(p,p+=l))).join('')
```
In each character I pack both the vowel (including case) and number of source characters to copy. 10 vowels plus length of 0-8 makes 80 possible values to pack into a byte, which is ok.
## JavaScript 1273 characters
```
i=>{n='A2i2ea4e2ii5oe4e5i2eo4ii8e4ieo5ea5a4o4a2i5oi5oooe2o5i2e4ea4e1e2eio4eo1o4e4ie4a4e1a2i6ui4a4oiu2eo4oea2i1o4ii5a6ai5e2u2e2oao1o7o1u5A2i2e4io1u4iu2eo4oea2i1o7o4ea4oi2e2i4i4eo5i5a4e4a5eo1u6o5eo4a4a2ee4e1e4e6e1e4a6u2i7ee5e4e1a2u2e2o4a2i4aa1i7a1i4o1u5eo7e4o1ue2o4ei4ua5ii6ea1i2i1e6e4ue5a4i2eai4i5i4e2e4a5o2e6e6e2ea4oi5o4e6e2aae2i5a5o4iA2i2e4i4i4o4e6u4o1uo5ea4oe1a5eai4a4o2ie6O4e1a4O4e1a4I4a5ea2e7e5e4o1u5io2eaea6ioue4oe5a5e2o1u6oa2eoe2ea5i5ua5ei2e2ia5e1e2e4u1i2ea2u2a6u5e5eaiau1a7o1oaa5o1uoi5a1i4o1a4oe5a5o1o2eai4a6e4ui1eo4A2i2e4ae4oe4e1e5oi5aeao5e4i6a5ea4e2e4e2o2ee1eaai4i4e1ieaa1i4o1a5oe4oaa6oa2e2o1uoi4a5ui5i5u2i1o2i7eaao6ei1e4aei4a5ou2a2e5a4u4i4i2eoe1e2i4o4o4aaeai4o2e2ue5eeeIa2oe4o2e5o5e4A2i2e2aei5e2eoeoi2e2i5oi5eo7ea4oeo1ua2a1i6eai4o2ee7a1i5o4i2e2aue4o4o2ea4a6e4ie4ue6o6oue7aA2i2ea4oao2e5o4i4a2o1u5oi5ee5e2o2e4eo1u5ee5ai5o4ae5e1e4e5E1ie5ee5a4e5e1e4o5ee5e6o7o5ea5e5o4i2e2a5ee5o5oo1oa2o1u4ea5ooe5a4a4o1i5oae4e6i8e4i1e4oo1o4o4a5a2e2o1u5a5ea4o2i5o4ui4a4o1oa5oe1e2a5i7e5eo1o2ea5ei2eo5ee5a5o2i2e5a5e4e2eie4i5uo1a5a5o1o5ee5e2e2a6e2e4ea4a4a5iu2e4u4u2o4e7eo1o4o4aa5oo2e2o5e4eea5eae4i4a4a2ee4O2AEAA2A2E5u4oe5e1a4i2ao1i4e4i4ae9ei4o4i2eo4o5ea4o4e1ao4ii5o2e2o4uee1a6oa2a2e4ouiio2o2e2o5euo1a5a5ee5a4i'
j=p=0
z=''
while (n[j])z += n[j++]+i.slice(p,p+=((+n[j++])||(j--,3))-1)
return z}
```
Great challenge! Not very impressive submission.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 1364 bytes
```
^
A1i1e2a3e1i2i4o2e3e4i1e2o3i2i7e3i2e2o4e2a4a3o3a1i4o2i4o2o2o2e1o4i1e3e2a3ee1e2i2o3e2oo3e3i2e3a3ea1i5u2i3a3o2i2u1e2o3o2e2a1io3i2i4a5a2i4e1u1e1o2a2oo6ou4A1i1e3i2ou3i2u1e2o3o2e2a1io6o3e2a3o2i1e1i3i3e2o4i4a3e3a4e2ou5o4e2o3a3a1e2e3ee3e5ee3a5u1i6e2e4e3ea1u1e1o3a1i3a2ai6ai3ou4e2o6e3ou2e1o3e2i3u2a4i2i5e2ai1ie5e3u2e4a3i1e2a2i3i4i3e1e3a4o1e5e5e1e2a3o2i4o3e5e1a2a2e1i4a4o3i2A1i1e3i3i3o3e5u3ou2o4e2a3o2ea4e2a2i3a3o1i2e5O3ea3O3ea3I3a4e2a1e6e4e3ou4i2o1e2a2e2a5i2o2u2e3o2e4a4e1ou5o2a1e2o2e1e2a4i4u2a4e2i1e1i2a4ee1e3ui1e2a1u1a5u4e4e2a2i2a2ua6oo2a2a4ou2o2i4ai3oa3o2e4a4oo1e2a2i3a5e3u2ie2o3A1i1e3a2e3o2e3ee4o2i4a2e2a2o4e3i5a4e2a3e1e3e1o1e2ee2a2a2i3i3ei2e2a2ai3oa4o2e3o2a2a5o2a1e1ou2o2i3a4u2i4i4u1io1i6e2a2a2o5e2ie3a2e2i3a4o2u1a1e4a3u3i3i1e2o2ee1i3o3o3a2a2e2a2i3o1e1u2e4e2e2e2I2a1o2e3o1e4o4e3A1i1e1a2e2i4e1e2o2e2o2i1e1i4o2i4e2o6e2a3o2e2ou2a1ai5e2a2i3o1e2e6ai4o3i1e1a2u2e3o3o1e2a3a5e3i2e3u2e5o5o2u2e6a2A1i1e2a3o2a2o1e4o3i3a1ou4o2i4e2e4e1o1e3e2ou4e2e4a2i4o3a2e4ee3e4Ei2e4e2e4a3e4ee3o4e2e4e5o6o4e2a4e4o3i1e1a4e2e4o4o2oo2a1ou3e2a4o2o2e4a3a3oi4o2a2e3e5i7e3ie3o2oo3o3a4a1e1ou4a4e2a3o1i4o3u2i3a3oo2a4o2ee1a4i6e4e2oo1e2a4e2i1e2o4e2e4a4o1i1e4a4e3e1e2i2e3i4u2oa4a4oo4e2e4e1e1a5e1e3e2a3a3a4i2u1e3u3u1o3e6e2oo3o3a2a4o2o1e1o4e3e2e2a4e2a2e3i3a3a1e2e3O1A2E2A2A1A1E4u3o2e4ea3i1a2oi3e3i3a2e8e2i3o3i1e2o3o4e2a3o3ea2o3i2i4o1e1o3u2e2ea5o2a1a1e3o2u2i2i2o1o1e1o4e2u2oa4a4e2e4a3i
\d
$*
+s`1(.*i)(.)
$2$1
```
[Try it online!](https://tio.run/##XVRdb9tGEHzXr9gYebBTWQC/1CJ@KAw0LQI0DZAU6EtRl@JRIiPyyN4dzerXuzN7Jz8Ukmnq7nZ3dmb2XBt6W7@8/LV5zPqszeuizfq8L6e8LdqSK1OB39@3eOK9xImyLqaizniGf/y02cSzhca3COoRhuN4MK7AKgKqJe/xirB80cQIzLGuFcq6qvFsM2xlU14jeD8tpaLC/rQU/4/aT1oP6RDRFz0LlsiDmjVwTktFuIAKsC3bwbfCo66WrN9jpWwJS@uxn6LO635f9wXKIm7f4oWdIW9fLOgbKCtU7LMeebDSopZyhv2@RP2MlacMu1WbJWzlxKoZciMX0JXsNnWFD3cXFlJq2Rux15EoKNFWnwGy0MdH7QvN7AkdKEGLlsdfhfcckJgBRQAb7fOsqkPV@pI9tJEtvhHuovjBAUgp21gZf0u9n6gB0AIZxQHSOuWeptRzrSz05Dg2VMf6YFq9ocDYWNFXilwZAjTKwS0lrmh7Pacl1HdaOaLPYn00jkJsAbqreAyeoEavVfUE@s8QAlEWUhtbpzMm@jXShIOonlE7YMDnI6poTQQSqTaSacqyjSny5DDtSY0RhYLDEFyrJ2LevIV9KLCmUDV0uVaqOAhYq6ZKldrX@XXk1O4EANyAs6RKbalc0deL/qzVTjU3OJ0f@tgGLc@VKcZUmAyd0/YKRdcnzipJxShxV@cWoSjP1qhdW@mgU4FJSSujBGVUbyIHRRriSVO0zN7Tj3m0RTRYHqFwGPpM/VjEWwHZoSR0po1Si0hRtenywKfUOYeGC0dv3yYoETHhMFkeSxF0/zrgn7PH/EP@CFofsw/lonZtOaJgty/0ZN7@QLNM0R5FGjoMV7zmSi1AlTCH6kBkLihXzystS/Xz1ELkvt/8aTZv322@839nt7t3/d3t7m7zNn@bvbwMjaxeDidr7UmCnII8u4sEZ@QoPgQsHi7SOfE@OLESOjnY81Ys97tnbNvQaaR5L7YRJ2FtxHfSGZlng10NOb@mQDFn7GkrB@zwlJW5CQ6r0thn54P1LLOVG5RYuyCeCTyqIcv2Bj9OWATqmzXg5f@xP95svrI8yjTWG0eArL1aGZHw1ss6DEiHI81gtnJ0TI9E5iKj4cnjoAz4Yb6wSx9mc7clkk6PzoPHGRnPyCzGX@6l6SySGjnI6nCAX3cYcOak9M3MMjc8jy3jPZNZ8cbY4SLyB2p/OYCMlcntWS5oxwKcj8TvNr93ylrk2csT0D2JG90ZRShIeBDrxBiSgjNnCa@nxgZggASp1wvp1ha0nOfv4IcjmAYs90biE8yAoIMM4c2N3CrSLpFOa8gxuNUZNBGkaRxskrIGnounumfQbXQrdD4pTVpG/Cf7IPqfgIbccPfAXVa54mrCAFqewlnAyBU@VPOhCfegMTyp@Yazptd3NA0MqGe35AAuCwnWMUSFIaqH1RrnPZdHDQrJpnCOHHDKWxF3VYJqp6IUD3ncK6Bwjqi0@MFxcBiC7OGyZVLqx1JYPMIYoCwdPrpgA9qDnN98oHqjqgUfz2LgURncSUHcdxDXRHOa025jqT@QjxgoHlytDsE1NVrA8F0d361xUleH6nEYdLLxsPTTawVmAV2UzYJSkWDtQMb8CMO8kms4ycmwKL7l/MRfIc5ip4Me0YVoQloszDPROLgsMgw@rEkLx2HApjbNeTMzJ3O3SWPGKQXsuEPyGTtcR3MdLipsumcGGy4UZIyDvSaOAls6qBHYiJpSrxQkPumd1QGg2H/DTn6GeKpdUN8ikBkQNlLsNZqFl8rIwORp5dW4OHH2wgF9UMJwNhkUV5fxaQKHQRm1oYn2Cx2cwAsHKqmB5gMmS011vscYPvuHK/ZOe/WrjLOP9wmvPV4IaGA@@Z187ehLpfMbcroRimpZTRSJmb03DxH3cGDVmy@//SKfvnz69aeb64Xs5OTQlAczIcqJ0@McLu@ZwajQw1n7nplei@lXzqqoHw@GN6eDYekUEEYmZqay4Yoq9eqvus4Yh7D7Dw "Retina 0.8.2 – Try It Online") Simply encodes the vowels and distances between the vowels, which are used to slowly shuffle the consonants into place.
[Answer]
# Bash, 10 bytes + 1151 bytes + 1-char file name = 1162 bytes
```
bzip2 -d a
```
Output in `a.out`
File `a` is the output of `bzip2 alice.txt; mv alice.txt.bz2 a` where `alice.txt` is the required output.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 1391 bytes
```
`?A2Ȋ1Ɛ2Ȧ3Ɛ1Ȋ2Ȋ4Ǫ2Ɛ3Ɛ4Ȋ1Ɛ2Ǫ3Ȋ2Ȋ7Ɛ3Ȋ2Ɛ2Ǫ4Ɛ2Ȧ4Ȧ3Ǫ3Ȧ1Ȋ4Ǫ2Ȋ4Ǫ2Ǫ2Ǫ2Ɛ1Ǫ4Ȋ1Ɛ3Ɛ2Ȧ3ƐƐ1Ɛ2Ȋ2Ǫ3Ɛ2ǪǪ3Ɛ3Ȋ2Ɛ3Ȧ3ƐȦ1Ȋ5Ȕ2Ȋ3Ȧ3Ǫ2Ȋ2Ȕ1Ɛ2Ǫ3Ǫ2Ɛ2Ȧ1ȊǪ3Ȋ2Ȋ4Ȧ5Ȧ2Ȋ4Ɛ1Ȕ1Ɛ1Ǫ2Ȧ2ǪǪ6ǪȔ4A2Ȋ1Ɛ3Ȋ2ǪȔ3Ȋ2Ȕ1Ɛ2Ǫ3Ǫ2Ɛ2Ȧ1ȊǪ49⑨,?1Ǫ3Ɛ2Ȧ3Ǫ2Ȋ1Ɛ1Ȋ3Ȋ3Ɛ2Ǫ4Ȋ4Ȧ3Ɛ3Ȧ4Ɛ2ǪȔ5Ǫ4Ɛ2Ǫ3Ȧ3Ȧ1Ɛ2Ɛ3ƐƐ3Ɛ5ƐƐ3Ȧ5Ȕ1Ȋ6Ɛ2Ɛ4Ɛ3ƐȦ1Ȕ1Ɛ1Ǫ3Ȧ1Ȋ3Ȧ2ȦȊ6ȦȊ3ǪȔ4Ɛ2Ǫ6Ɛ3ǪȔ2Ɛ1Ǫ3Ɛ2Ȋ3Ȕ2Ȧ4Ȋ2Ȋ5Ɛ2ȦȊ1ȊƐ5Ɛ3Ȕ2Ɛ4Ȧ3Ȋ1Ɛ2Ȧ2Ȋ3Ȋ4Ȋ3Ɛ1Ɛ3Ȧ4Ǫ1Ɛ5Ɛ29⑨,?2Ɛ1Ɛ2Ȧ3Ǫ2Ȋ4Ǫ3Ɛ5Ɛ1Ȧ2Ȧ2Ɛ1Ȋ4Ȧ4Ǫ3Ȋ2A2Ȋ1Ɛ3Ȋ3Ȋ3Ǫ3Ɛ5Ȕ3ǪȔ2Ǫ4Ɛ2Ȧ3Ǫ2ƐȦ4Ɛ2Ȧ2Ȋ3Ȧ3Ǫ1Ȋ2Ɛ5O4ƐȦ3O4ƐȦ3I4Ȧ4Ɛ2Ȧ1Ɛ6Ɛ4Ɛ3ǪȔ4Ȋ2Ǫ1Ɛ2Ȧ2Ɛ2Ȧ5Ȋ2Ǫ2Ȕ2Ɛ3Ǫ2Ɛ4Ȧ4Ɛ1ǪȔ5Ǫ2Ȧ1Ɛ2Ǫ2Ɛ1Ɛ2Ȧ4Ȋ4Ȕ2Ȧ4Ɛ2Ȋ1Ɛ1Ȋ2Ȧ4ƐƐ1Ɛ3ȔȊ1Ɛ2Ȧ1Ȕ1Ȧ5Ȕ4Ɛ4Ɛ2Ȧ2Ȋ2Ȧ2ȔȦ6ǪǪ2Ȧ2Ȧ4ǪȔ2Ǫ2Ȋ4ȦȊ3ǪȦ3Ǫ2Ɛ4Ȧ4ǪǪ1Ɛ2Ȧ2Ȋ3Ȧ5Ɛ3Ȕ2ȊƐ2Ǫ3A2Ȋ1Ɛ3Ȧ2Ɛ3Ǫ2Ɛ3ƐƐ4Ǫ2Ȋ4Ȧ2Ɛ2Ȧ2Ǫ4Ɛ3Ȋ5Ȧ4Ɛ2Ȧ3Ɛ1Ɛ3Ɛ1Ǫ1Ɛ2ƐƐ2Ȧ2Ȧ2Ȋ3Ȋ3ƐȊ2Ɛ2Ȧ2ȦȊ3ǪȦ4Ǫ2Ɛ3Ǫ2Ȧ2Ȧ5Ǫ2Ȧ1Ɛ1ǪȔ2Ǫ2Ȋ3Ȧ4Ȕ2Ȋ4Ȋ4Ȕ1ȊǪ1Ȋ6Ɛ2Ȧ2Ȧ2Ǫ5Ɛ2ȊƐ3Ȧ2Ɛ2Ȋ3Ȧ4Ǫ2Ȕ1Ȧ1Ɛ4Ȧ3Ȕ3Ȋ3Ȋ1Ɛ2Ǫ2ƐƐ1Ȋ3Ǫ3Ǫ3Ȧ2Ȧ2Ɛ2Ȧ2Ȋ3Ǫ1Ɛ1Ȕ2Ɛ4Ɛ2Ɛ2Ɛ19⑨,?I3Ȧ1Ǫ2Ɛ3Ǫ1Ɛ4Ǫ4Ɛ3A2Ȋ1Ɛ1Ȧ2Ɛ2Ȋ4Ɛ1Ɛ2Ǫ2Ɛ2Ǫ2Ȋ1Ɛ1Ȋ4Ǫ2Ȋ4Ɛ2Ǫ6Ɛ2Ȧ3Ǫ2Ɛ2ǪȔ2Ȧ1ȦȊ29⑨,?2Ɛ2Ȧ2Ȋ3Ǫ1Ɛ2Ɛ6ȦȊ4Ǫ3Ȋ1Ɛ1Ȧ2Ȕ2Ɛ3Ǫ3Ǫ1Ɛ2Ȧ3Ȧ5Ɛ3Ȋ2Ɛ3Ȕ2Ɛ5Ǫ5Ǫ2Ȕ2Ɛ6Ȧ2A2Ȋ1Ɛ2Ȧ3Ǫ2Ȧ2Ǫ1Ɛ4Ǫ3Ȋ3Ȧ1ǪȔ4Ǫ2Ȋ4Ɛ2Ɛ4Ɛ1Ǫ1Ɛ3Ɛ2ǪȔ4Ɛ2Ɛ4Ȧ2Ȋ4Ǫ3Ȧ2Ɛ4ƐƐ3Ɛ39⑨,?E1Ȋ2Ɛ4Ɛ2Ɛ4Ȧ3Ɛ4ƐƐ3Ǫ4Ɛ2Ɛ4Ɛ5Ǫ6Ǫ4Ɛ2Ȧ4Ɛ4Ǫ3Ȋ1Ɛ1Ȧ4Ɛ2Ɛ4Ǫ4Ǫ2ǪǪ2Ȧ1ǪȔ3Ɛ2Ȧ4Ǫ2Ǫ2Ɛ4Ȧ3Ȧ3ǪȊ4Ǫ2Ȧ2Ɛ3Ɛ5Ȋ7Ɛ3ȊƐ3Ǫ2ǪǪ3Ǫ3Ȧ4Ȧ1Ɛ1ǪȔ4Ȧ4Ɛ2Ȧ3Ǫ1Ȋ4Ǫ3Ȕ2Ȋ3Ȧ3ǪǪ2Ȧ4Ǫ2ƐƐ1Ȧ4Ȋ6Ɛ4Ɛ2ǪǪ1Ɛ2Ȧ4Ɛ2Ȋ1Ɛ2Ǫ4Ɛ2Ɛ4Ȧ4Ǫ1Ȋ1Ɛ4Ȧ4Ɛ3Ɛ1Ɛ2Ȋ2Ɛ3Ȋ4Ȕ2ǪȦ4Ȧ4ǪǪ4Ɛ2Ɛ4Ɛ1Ɛ1Ȧ5Ɛ1Ɛ3Ɛ2Ȧ3Ȧ3Ȧ4Ȋ2Ȕ1Ɛ3Ȕ3Ȕ1Ǫ3Ɛ6Ɛ2ǪǪ3Ǫ3Ȧ2Ȧ4Ǫ2Ǫ1Ɛ1Ǫ4Ɛ3Ɛ2Ɛ2Ȧ4Ɛ2Ȧ2Ɛ3Ȋ3Ȧ3Ȧ1Ɛ2Ɛ3O2A3E3A3A2A2E5Ȕ3Ǫ2Ɛ4ƐȦ3Ȋ1Ȧ2ǪȊ3Ɛ3Ȋ3Ȧ2Ɛ8Ɛ2Ȋ3Ǫ3Ȋ1Ɛ2Ǫ3Ǫ4Ɛ2Ȧ3Ǫ3ƐȦ2Ǫ3Ȋ2Ȋ4Ǫ1Ɛ1Ǫ3Ȕ2Ɛ2ƐȦ5Ǫ2Ȧ1Ȧ1Ɛ3Ǫ2Ȕ2Ȋ2Ȋ2Ǫ1Ǫ1Ɛ1Ǫ4Ɛ2Ȕ2ǪȦ4Ȧ4Ɛ2Ɛ4Ȧ3Ȋ2`÷⑷:`12345678`-[|ℤ`,`*]⑸⅀ß
```
[Try it online!](https://tio.run/##dVXBihtHEL37Kyp7soN2QTOjteM9mIU4wRDHYAdyCMGLNJEGa6aZdDc7EeSQQ3LZkw265xJE2B9w7gavvmN/xHn1qnu0BAJiNN1dXfXq1aua9U@rT58unpwX@6vpx7fFfld@fDvdX2FZ3VwXH99iWdnRzXXJ/YfYxAt3Kl6pcEtPd1O7ZU/7wRvM6KHM/rGnr1fqkm74b05LWtDVbL@FUUnnar3fJhh0W9AmgwKE2X6nLwpfDad6aUfnpzfX@22VUiwZd78t/9dj9cXtu78nT6aGLoefkhfcMsgVYxL2ruLOfjszQkiFsoF3Zs3HjP8Kcws/pzyreKJhE2LjsNRMdjDSR0nwdItLXBmpBAfbLSugJMwIF1D3V4xX0lRh5uLyAoBrElPDfnM9pXFhWRepOCnrinFmmrtiKkhCxWtK4IHTkkjVFtQSZFaHkWssJQS6N2W5Zy8qPSvT37Mq28HrqRHE/Fm0lAOfM@4UzNAi2NVpKoS5SApMKgVwkkXipknnukxkbDNNWg9WqiIEg83ndr87VUlxoSwwUROg1Wp3QKOGd3jfpZJodVQkI3m7MQeKpcoOLVMjstR@SNyk4jFZE1kKkuqrmroq8l6Cldo5Qx8pmh5yUDkQn1HFZkhaNe8315TYVQad7rAOU3qj2Lamh5F/6xy2WZlllMAyganplJlouUyJz7QZMugpaVEeznPtEoDK6msdfKdTE4u5cUYhslNZYzBzEP1dPFiy9UzkKVhWWplrmgtqU0tPweksaxIOijtDNQ8jy4P87Mj8ASYZsIqWCWbatsFm5NGKFqVhf2qNNJqW2cL6j6sZZ2Aa1hmB5ZVscMp5bargfDTrPMVZWM0jMbsztc7y98CkxVFOoNVBXGNPW9cz@mGy01k16kTb1Bq/OLTP2LHFmJRNLm6a/3L8qhBPRVETB/vwwDCjzHILWSHLNEK3NgfwswF7mj9PWbnGh2VmQYsDwl2RRuGd6f@iOC@flueQ7Xnx1Gaj4bCpTFGwY@0izh5ZX@Ua2edpJJDfi/FbXGUsJkDO2dTZRFCaHGmruO9AL@4QNGoHVhcf3t@@e//4YlqU1ez04aOL4x9@vf39r4vJxec/3r775/aP3z78@elTu5AhyHzlnFtJlFWUS7@R6GtZSogRm/ONNF5CiF6cxEbmbj0Rp@fNJY5dbHizfixuIV7isJDQSFNL39c45ZX16ALBfO1WE5njRK2c9IvosSsLd@lDdEHDTOQIIYYmSlAHAdHgZXKExQqbQH00RLz89@6To3uvNDzCLFyovQLU2IOTDg7vBxnaFu5gsmjriSy9uoejeiNdrZbLlgyEtt9oliH29YOJImlo2rcBNtKt4VnqsDmWRePgtJa5DB4G@vPzFjYr0terl36h9jiqQ1BnTkJdu3Yj8j1iv5yDjEGdu7VskI4DuGDEn9z7riFrxnOQ10D3Wnzn1wiiBYln4rzUtZICm7XE0apbAAyQwPWwUbqZAsMFXcfQLsE0YPnPxJ5gBgTNpY2fHcl9Im0S6SoNWUY/@BpJRFksPGSSvEa1M6vmEnTXPIpNSJVWWjr8K/sg@ueIhHz74ExPNUrGtYgtaHkd1wJGMnxULcRFPAaN8TXF167pnu9IGhgQz02UA6gsJljLaBVGUQOktvAh6HbHSzHJFMqROayCE/G5ElrtFFSLBz9@BBTXhorB514bR6/Ae9xM1KnWT0NhcwlhgLJkvPTRRaSHcr4JUavXsVrQcS81NCqtXxHEcYPi1ibOenVyz2n9gbxDQ6nh4NgE2TVSQPNlxTeDdergEd2agZ2Nh1M9jRHUC@jSsjlQKhKda5Wx0EEwI7m1dnISLIJPtH9sFa0XGza6oYsmQpVY7HtF46EyYxh8uDptLNsWh0xa@63utTNP7qU20y4FbDtR8vVum1tzaDcsbJozrYsbLUhnjT0kjqKmNKcQNBGKkiMFjlecWQ0AivslnshXKB5rF6lbXFQPuNZpsQcTiw6VTi8mTZPX2lvHuY026BkJg20SKEZXHVIHti0ZdXFh8osNlKADB1WigPo5OouiWh@jDS/DWcbeMNcwSNcHmyc69nQgIIF@FU7kVaO6JJ1v4NN3qCjD0pER04dQnxnudq5Rj15@@7U8f/n8my@P8kD2svJIKoCZaOWEddfHzWP1ULPQ7Zp59@qewfiTNSsaunmtk9NDsKoUEKZM9OrKxYwq5RpyXXu0Qzz5Fw "Keg – Try It Online")
## Explanation
```
`...` # The huge to-be evaluated string
# that says what the program should do in the encoding
÷ # Split the string into individual characters
⑷ # Map over the string
:`12345678`-[|ℤ`,`*]⑸
# If the string is in 1-8, multiply the comma by that integer.
⅀ # Join the whole stack
ß # Evaluate the generated code
```
[Answer]
# [PHP](https://php.net/), ~~2224~~ 1592 bytes
```
for(;$a=$argv[1][$i];$i++){foreach(["A"=>"UHULUNUO","E"=>"LSUJUP","I"=>"=IG<","O"=>"===CUG","e"=>"1822313:3K4Z7B8?8V99:::H:I:Q;1;2;E;J=P=S?:?>?Z@4AAC@D9DHF1FQG8G:GEGMH1I?IRIYJ>K;MEN4NCOEOHP=QTRDRGRHRLS7S9S=S>SDSET7TNTVTXUBUDV<VDWHWNX<XO","a"=>"2:2D4R7>7A8G:L;F;H<L=2=L=R>C?A?K?U@6@8@K@WALB;BOBSD@DGE>E@EZFOG>HYJ1KEL=O7NOOCPBQ3Q:QMSJSMTGU6UAV7W6WWWXXS","i"=>"191H1N1Z2Z3<3I4T6J7X9H:9:E;V?EE5E6J<LSQSR;RJV6VNWAX8","o"=>"1?242O2Q3>45626F7;:P;=<9<O=5><>J>Q?7?<A?B3B@D7DEE5EWFAFGHSIIIXJMK?KFKJMNNKNPNYO1O=OAOZPPQ7T4UWVWTKTMVZWGWIWUX2X:X;","u"=>"4Y7W8>9B<A>L@7AYDTE4EYF8FZIPRSSZT3WLX4XC","ea"=>"3Q8=<Q=@=FV3W<WP","ou"=>"5;5F6Z8R97<D>6?2A1DIHWL3P>","ai"=>"8I8O9QA9CZHZIE","ie"=>"9RB1EIOW","ui"=>"@3","oi"=>"V9","ua"=>"@M","ei"=>"CT","oa"=>"A<D3RUXE","oo"=>"@SAINMP2Q1QJT?","ee"=>"397G7O?YBECHFCLLM<Q9"]as$c=>$b)for($j=-1;$d=$b[++$j];)if($i==(ord($d)-49)*42+ord($b[++$j])-49)$r.=$c;$r.=$a;}echo preg_replace(["/(\\s)(t|s)h(n)?(?= )/i","/(h(?=r)|g|d)(rs|r\\W|t)/","/wh(?!a)/","/ (w|h|s)(s |d |v)/","/(\\W)nd/","/(th|w(?=t)|m|F)(n|th|r)/","/b(o)?t/","/ (a)?nt/","/([^namlie])d(\\W)/","/(?<= )(t|n)(\\W|s)/","/(d(?!r|n)|c(?!r)|cr|m|h|w(?!n))(w|n|ss|m|r)/","/(\\W)s /","/ (n)?r /","/([^iu])ng/"],["$1$2he$3","$1e$2","whe"," $1a$2","$1and","$1i$2","b$1ut"," $1not","$1ed$2","i$1$2","$1o$2","$1as "," $1or ","$1ing"],str_replace(["lc","bb","dd"," f ","bfr","fr ","vr","nc","bk","ctr","stn","nsd","wll","mk"," ","tht","lf","ftr"," tm","hl","lk"],["Alice","abbi","udde"," of ","before","for ","ver","once","book","icture","sation","nside","well","mak"," a ","that","elf","after"," time","hole","like"],$r));
```
[Try it online!](https://tio.run/##ZVRpc@o6Ev1@f4Uu5Q94shVLwmKMgbCHfTMhN5PCFmAutvBISvyox/z2O90ypF7VVLlsS@o@ffp0t0Iv/FOyQnhvjzxpaGtTW/Pd11vq/U3bvxva/uZG/xuONmvXS74lqgmznJi35735YD5M3CYauO5N5935CFYdXJmdVgn@h@rfNJ/nLVhtcJXKp9OZVKaYecmucrW8lV8UCsVisV3sFMdGykgbDaNrjsypVbTK1qqSrVafK/VCvd1MNcetfKvYarT67VTH6kw6r93yi9FvDLKD52Fj2B6Z49mkPmlN2pPeNDctTM1peVqfNma52WC2mC3ntXl9UVrU7bY9WJaWyHyNjNLFdD07yZVzVYDvGU2jXeqZabNnTsrPVtV6seaVp0q@8lKxq72aURvWpvVKvdUoNyqNVXPYKrdfu6mXRs8c5gbD4fOoNs6Mi@P@tDvtz1rzp3l1kbOfbNteLqcQca80KKTaqUFqlV5lSplOdvbUzS0L7WKh2DAWVqPx2HjqlnrT8XRiTLqLp8XAri7z4HtUvlY6mx6mx5ly9vEp/dTMGcWRYZYKpaH5WC6Vu@WxlbNKVauWqVXquTqi2c1qs9WedjqdZbf/Yr00X7r9weBlMBq8DlNDc1gdrkajcW6WndsLe/Yy6y9Wdsvu2PNlellcGhD5EyNnX3N2vlyolarlXiVXfa3PGtnGazPfXHVGk@l0NcvYvWV2@YyVVsJmxnmzNDYrZnORsUs2NsdRIT0aj82nVX5SyJXq5ScrXU3VO227lxmVsSZKonwnPyyMq4XnVXvVaaBwqnsKk1qq0RnayEnZVTKIqn4XBdxVkSt9JKF2n2dooHarpXpmMl8i2lFpWZlWO4P@KD1OjbszC11UkEwh18oNrdda47ndfO71@qVxIfG@FpprljVHxxnRfpt3KUOjpua83dxov98Nfb9NanvTTB45TWpUv8sW9H9l0zdqeTFSmxq/NzXXUJ@18d@N6x1JyDe7D74J/bW7gQF7SP76JfSkPAvdSzLdSlom0R/2QPAh6cGC6@fdmepJLs781y/7LPUHPIvg7Oc6/ifJ6OyBf1KQMyXnr3gXcG2d0fhfeucIwKR@Ds5NPcnOsMFjOyd51C15AVrrFov/k2//ZuvA32/edaqg4l2rBPSALdNxE4LG2xTYcNg8u/gDHw6BVMyfTNeBHzsLAVv8H9wEuQSFrDm5Bt1/vuts95B4v31LaCkt7W00LLuW2mhp@EbeBt5ES63VEr6Mqu9erR0t9SljA3aUsR9VJ3sEUxvHq6cgseWRkxiC7SCskPwf5fFdRHXgRTEO2aKps@Xw3iq3L/xlyuoAL1fiWkiGuwJdIt@Hd4CHBB2kh7z8LSIoYyIDeHto5R9U3lV/72Kaa8fBRvikVCV9jINv8HZG75j31wZBjkx5OMcjBtq78lPZiLXcH2MuewUSbWI6a8VnHRNaI6ONorTeyk1Mah@gvXf08ePvDxugpnFdN/78@eO7JBLE2THGdkSSnSRf/EQkp6CPkBI2nRPxOBEgJmFEesRhh1vC8Nz7gmMmPeVJi4S5hBMZuUR4xKMkDCmcKpfDNwQE45TtbokDJ2jFSAhKwy5x2RcHuQWGuSUJCBF5kggEEBANUDAZbwebwDoRgfz/52slfkwxPIRxoWgcCWLsiJEAAGGuoIgAByauT28JVB7gAYieSEDRcusrBYQfnjBLIUOq3yITT5mGvgAbEhwAmVBxuiOuxwCUEodEHAzw4Y4PNjslX4gooYv2cESFQDBGBKXMPxFiQ@yJA2JECM4O5ATpMCAnYuHvf8w8pVqssyAfwO6D8IAfIAgWRBqEcUIpigI2ByK/rQIXyAATgI5OKLdKQYUTuJbC34LSQIv/JPEblAGBHOLLnwm4jZCpdxEdW4NAo0ecQhKSuC6HNrmgSrSLrbwvkJuqI@mJS6VRlgC@qD4I/R8JCXFfN/AUo1x5udIHWT7kgYAiV/pQNSFdeQcyyg/VfP5Bwat/SBo4QDx2ixpAl8kLra2MKwxFFdBqLhcCtwPlJC9tCp1D4BogghHCr5XAal@CYvEAh38TkoeYlQrucBwcdAF0ebpFUKwfhoLNLTQGSHYx3nLJJKQH5fwtJFYvUNWCPg4JhR4lPt8pEnceFJfGzUl39z8Y1h@YBzBQaBgxNQRXaEgBhu/a8V4UT2rEIXo8DGqy4cWwn74jIArIhWVjICkhkjEfFRMBNMy3uBQn@dKwEPwW5ydeyXgWPTXoMTsZNyG2mAxDZMOhy2KFQQ9GLxtb34dDlTTOGw1xMu9/XMYMpxRoxycoPvr619GM/JMq7OWe8Zk8YUGCeLCji0YSU3JUI2AiqinVlQLAO3VneUCQsL/kPWlC8VTtpOpbcEQEcAuw2FHcLHipBOh46WmlK@XxxLETDqihBAPbS4PC1UXFZQJ9XynKpBu3n/SgE/DCgSqpBgodmCzVVIc7GMMvYVy5eypXEZEgFPF9gtceXgiQQLgT92TqYV8qOX8DJg@goiqsAoqFCYWgRszbdzBqYjJokf6k36snrhcyJzsOSQlQRsblBOsglKciIlBVaP@g8g4RXgVTDzmoiorAoXhzcmhY7BQQDJUIEYrJK6tLruJa1xDGQd7/Dw "PHP – Try It Online")
Haha this is such a longest mess :D well this takes a double approach by replacing some english generic syntaxes, then adding the missing vowels. Actually doing it the other way round so that some generic replacements are avoided because proper vowels were inserted first. Still optimizations to do I guess..
EDIT: saved 632 bytes by encoding the positions with the following:
* each position is converted to base 42 (the answer! 41 would have been enough, doesn't change the count anyway)
* gives 2 digits. Each digit is represented by the char code of the value + 49 (so it starts with "1" to prevent a falsey value)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~575~~ ~~574~~ ~~568~~ 563 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•zʒβßαØä₁«&ƒa*O¶¾8ΓÍ₃Ê1eéÿ¡¸;‹nθ¯õ!šìLx‘Â0·äLègα&íΘ∞ÜΣ<Ã5U≠₄ˆδø¿»·V.A×Ø€ćꔀQý!¦:üÜ©zт8λóÞš÷—2Ô(9È∍,\&Ćø
æ—₃Ƶ“°R₁ƶмŠ₆wÎl£ΩfεjÍŒÒwœ'².yŵÓ:jÐδ-‰øεžƒt£„cçQ¨RXJα≠’§krèýF∊¥ï·ǝ('₄“©wGßÙKMв\Ƶ¢j«ŽÞí‹ÂâäÝ–Σ-…ëĀº< \¼·²QS²„;É2тT6%> Po,¶úÒ‰ðC”‡ÖζpH¬tŸÞbΩ`™¦š˜°ƶÔ¾ÉëÑηhÁbg>1©
zµÏ|-Bó
?₂Äo›]Iþd]dlÈ₄Ćθ)MιζŠ3_)U¾ǝ£ÜŽ8”ÏвƵ^Î₆»Θª∊eÞJ8JèO¶₁û∊Kƒ–q×L÷=£AγõиisoÃeþ¶åβв"\¨"ι>т&«ǝôŠe°Í.%+cÿ“ZS÷&(ι+›1ßΘF>é4”קoìÂ₄jœ´â¿¦Ÿ~ë^†¡ÎVÎÝα7eæ‚°?ôΛ¼èp
dŒΛ¡ˆĀ∞€—À¢<·»+¹ʒ”qmý∞âMZîPéƵáøԔ₄ðwƼaxæ₄UU≠³ý¡ÅΩ66yΘE±ðcƶceåι.üWv₁¤Ãi«Š41×β4ëαÐWΔaŠRùmàÝå=åÔ≠%Úм“Z½ŽæYÏα´ŒiݲÚ∞Iª\ã¡.&тèã×ùÜ•74вvy9‰`žÀè?Fć?
```
-6 bytes thanks to *@Neil*.
[Try it online.](https://tio.run/##XVVtbxNXFv6eX3GxRBqKYy0tSymhRO3u0paStoRSdqu0KTMTe4hnboa5VxmMVpXrpClUArpJtKRsnOYFQkzoNjFx4pAXpHsyRirSKPyF@SPsOXfsfFjJsmfuPfc8z3nOc66HxBXj6sDr13Fx/sYf41EVfo1WYQoexKXv1XJ7Y/zKm5@pdbV7MpqA23FpBH46NgAVeK7mVL0rLm7yqK5@h9qhcA6enL8eF6eg9Ce1AQ/Ow1IuWm2H36Kp@OYMTEcLp2Hkz5fiW7NxafTlWLQGdfVcbamNLzPvwz2YiktP9n6Ex3GxjE8XYOeQWjwF2zCtKjdelU5GW/AUZhBjIy5OvgWTHe/Czfjm7XRf@94Y1NtgEZeRXKMWF6fVSi9yb6zvb4eINRbAHUctRJVsVBuE2@E4jAfhxBuqminAD6oGE6cG4edorTMurkA9qoW7jXGpFuLijAmPLqil3r@fi1aJdPEX9SjvwxLsnI1v/qQewu9q40W54w2shjArwYfwK/zySc9@ta9RU/ODajncgRn4DSWCEszDAyjHxYloAYEWYXmvqJ6dZn1qW22o6oWLqoqAXXDrrVelL04cPsM@H0qrdXgG48Rq5S8kSnEO/h2tex@pJzKsw4wRVb6NR@fVYjj3EiturMOk2oVbsAz/ijZs@N7InTmmKm03sMK7/@z8AJ62dcelEowOxcVnX38Mu9bXloMSlkb3xqL6kZ5oM1oPZ9/uP3JJ7b4oqwWYDndOIizc3a82at/AHRRSbUVT6jEWPwAz506egyX0BQoNW7j0SQOpTlyDe@dh4z218H70FGr79atiCEYGYBdreRhV96upPrWUijbPvCq1q@UXZVgLZwfUCtzOHD5qwnOU8auLsNHeEW0eRZbH0IhTZ89A5TjxuKceDcETKCHjwXBCrcE8umcxrH8Hy9/ExVk1B3e@hDtQjlbfGSA33Fcr3bAW/Udtw5LXZoXj@Dj3cmyviGZEg6FdoKjmT6P8W0fV5h/IvnzNhR2y6nzPV/Dfz6HSqMEcjKg6TGpTjsJKAGNq@8p1zF8avURWVk9hB6F/iConThSiqb@pVVgxG@vmANa7mYHty8M0RQ9g5CraYfb4MbgXVY/DMg7Yz5ejySvhbC9sujALZXj4HjxEoFuzh@H@/jZJoXbQQIv/gLvRqloLx69CWVXhPhL8WD3ugwU1l2l/VUI/LuD0bMI0ju87x/erw4V30TPfhrtQhKXus3s/dr9@nUqlHJMFghk5znmOSZaTbNgvMOlbLMuElLhoFJjtMyGkzziTNjN4Ps047dvDuM2lrU9apxg3mc9kYDJhM9tinmfhrj6SP0iBYL7Fc2lm4A5FceaZ0sdVZvJhX0guCCbNUggR2JIJSiAQDbOkU/iSw0VknQokPvz/2e5U20WCRxiTC8sngoQdcOZiwg7BAsfBdBhiOlaaZX1Kj4msAnMtisw6WgHheAWqUkjPOpImJrYO9RyBMczNY2ZmiUInM22OSS1msMDHAPr4hoMxOS2fR1k8k@JxyxKCknEmLIs7BcYuI3avgWIElJznWQHL4UhOJMJn2r6wtWqJzoL1I7t@5rt@HkGoIbKLcZ9ZFomCMXkmD6JcE8kgE0wdFEhuXYKGE/QuhZNFpZGWf4gl36gMCmQwRx5KsQ7N1G6KTtZgWekHvoVFSGaaPtqkmVVSXBJlD6Pclt6Stmh2mmRx8ZfUR6GvSSzId4500S6htHiZ0kFZ@mWeoSIt@tg1IU3ZiTLKfm0@J6/T62csGjkgHk@TBugy2aSVlUmHsakCrWb6QtCyqw/Jpk3ROczAKMEZ81udoG43Qal5mMc/ICTzCSsNbvg0OHQEs8tCmpJS/wgKF7NoDJSsGZz1JZdYHrZzUEjqnqu7hT72mIUeZY6f0yQ6bWyulZjTymXaOPUfmbs4UBQYcD0ErdRYAg5fy/F2kExq4CN6Mgx6svGLk58OECgLykVt4ygpY5JzhxQTLhrmQFyLJrlpWARP0/wkbzKZRVsPesJOJiYki0nPIzY@uixRGPXgVnMh6zi4qYumebM8msxMW3PMaEqRdrJD4tNZpzWagVPQjW3eMw6XBWqImwx20NRIUkmGNgIVok2prxRMnNN3lo0EGb8uM@wsNk/3Tmrf4kHKgMdcanaQmIUuFZcONj2tdbX8ZOJ4gQa0SwuGsU2D4tVlieYEOo5WlEszsZ@00Ql04WCXtIE8AydLmyrfiWM4LLpa3G1dqwiY64nkPqFrjy4ELMDLiQy7aJMvtZyDmNN3saMaVidKhPGEsLoS3o5BqKneTz9kPb095/@aal3IPsv5WJRAZWTSTox2PVk4RRks3Wgnr@v2KL0G0x@W1x0VrmHRzemjYckpKBgp4VEqLlusmrWKVl89HAeZwf@j/wE)
**Explanation:**
```
•zʒβ...×ùÜ• # Compressed integer 224641896896148016938368561552335098644440638806788380400165012285773501511250520005365941174208862664146279830408159028683082511746603646891689033010607628801437815480712915937924652809275189770660278010281318902097091708373828682312372672780477399419735631443886176059155071050262476552107016396780364226771683546971818103868361088000198778349003798076521493395410165779115606867484976791281038122102473781863665290228860335504663518108519671908117249856499506351874454875954494300437192218659256356139029651017435075963148812076901839173173452741192124604287091826161488097642846505252520037487674529824294243076129434563729383043104197923479360824310056655097918512677989534664676292688146822517512437302732254580913876380548881065041539680195011501730965834481558588377458598325965058885027168108789089635332449928831687357681298337708316403895593386671522073867265788780974012285668758807646711339460091042314668721692971679186845632617647310449657373332887652449016140311441573605606672295627533091777550161610779991335347646888360976210146797195084763186022703803722123461953373745423277449265741179310520405868463753966730206640071346865760122413333839703653337550179608290258257704143816340134609444894565369164030543611560755320287705090985654855136258294063356183305469030387994762970933038946455313934
74в # Converted to base-74 as list: [14,11,19,27,10,20,38,21,28,37,11,19,30,20,65,28,20,19,39,19,36,27,30,9,38,21,38,21,21,21,10,39,11,28,19,27,1,10,19,20,30,19,3,30,28,20,28,27,1,9,47,22,29,27,21,20,13,19,30,21,19,9,2,30,20,38,45,18,38,10,13,10,21,18,3,57,3,40,14,11,28,20,3,31,20,13,19,30,21,19,9,2,57,30,19,27,21,11,10,29,29,19,39,38,27,28,36,19,3,49,39,19,30,27,9,19,28,1,28,46,1,28,45,13,56,19,37,28,1,9,13,10,30,9,29,18,0,56,0,29,3,40,19,57,28,3,22,10,30,19,29,22,36,20,47,19,0,11,2,46,28,22,37,27,11,19,18,29,38,29,10,28,36,12,46,46,10,19,27,21,38,30,46,10,18,18,10,38,36,30,20,14,11,28,29,29,30,46,31,3,22,39,19,27,21,1,36,19,18,29,27,12,20,46,35,1,27,35,1,27,34,36,19,9,55,37,28,3,40,20,12,19,18,19,45,20,21,22,28,21,37,36,10,3,49,21,9,19,21,10,19,36,38,22,36,19,11,10,20,36,1,10,28,4,11,19,9,13,45,40,37,19,18,20,18,4,54,3,21,18,36,3,22,21,38,0,29,3,27,21,37,36,3,12,19,18,29,45,28,22,2,19,30,14,11,28,18,28,21,28,1,37,21,38,18,19,18,39,28,47,36,19,27,10,28,10,12,19,1,19,18,18,29,29,1,20,19,18,0,29,3,36,21,28,21,18,45,21,9,10,3,22,21,29,36,22,38,38,13,2,12,56,19,18,18,48,19,2,28,18,19,29,36,21,13,9,37,27,31,29,11,19,21,1,10,29,30,30,18,18,19,18,29,12,10,22,37,19,19,19,25,9,21,28,12,37,39,28,14,11,10,18,19,38,10,19,21,19,21,11,10,38,21,38,19,57,19,27,21,19,3,22,9,0,47,19,18,29,12,19,55,0,38,30,11,10,18,22,28,30,12,19,27,45,28,20,28,22,46,48,21,22,55,18,14,11,19,27,21,18,12,37,30,29,9,3,40,21,38,19,37,10,12,28,19,3,40,19,37,18,38,30,18,37,1,28,37,6,20,37,19,37,27,37,1,28,39,19,37,46,57,39,19,36,37,30,11,10,36,19,37,39,21,3,21,9,3,31,19,36,21,21,37,27,27,3,38,21,18,28,46,65,28,2,28,21,3,30,30,36,9,10,3,40,36,19,27,12,38,30,22,29,27,3,21,36,21,1,10,36,56,37,19,3,12,19,36,19,11,19,39,19,37,36,12,11,37,36,28,10,19,20,28,38,22,3,36,36,3,39,19,37,10,10,45,10,28,19,27,27,36,20,13,28,31,13,30,55,19,3,30,30,18,36,21,12,10,39,28,19,19,36,19,18,28,29,27,9,19,28,17,23,24,23,14,14,42,31,21,37,1,27,11,18,3,29,28,29,18,73,19,29,30,11,19,30,39,19,27,30,1,18,30,20,38,12,10,30,22,19,1,45,21,9,9,28,21,22,20,20,12,12,10,39,19,22,3,36,36,19,37,27,20]
v # Loop over each integer `y` in this list:
y9‰ # Take the divmod-9 of the current integer
` # Pop and push both y//9 and y%9 separated to the stack
žÀ # Push builtin string "aeiouAEIOU"
è # And (0-based) index y%9 into this string
? # Pop and print this character (without trailing newline)
F # Then loop y//9 amount of times:
ć? # And extract, pop, and print the first character of the string
# (which will use the implicit input-string in the very first iteration)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•zʒβ...×ùÜ•` is `224...934` and `•zʒβ...×ùÜ•74в` is `[14,11,19,...,37,27,20]`.
[Answer]
# Deadfish~, 18625 bytes
```
{{i}dddd}iiiiic{{i}dddddd}iiicdddcddddddciic{{d}iii}ic{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}dddd}iiiiiiciiiciiciiciiiiiccdddddciiiiic{d}iiic{{d}iii}dc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}icddc{i}iiiiic{{d}ii}ddddc{{i}dd}iiiiiic{d}{d}iiic{i}iiic{i}dddc{{d}i}ic{{i}dd}iiiic{d}dc{i}dc{d}dddcdc{{d}iii}iic{{i}dd}dc{d}ic{{d}iii}c{{i}dd}iiic{d}c{i}icc{d}dciiiiic{d}iiic{{d}iii}dc{{i}dddd}iiiiiic{i}{i}iiic{{d}i}ic{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}dd}iiic{d}c{i}cic{d}dddddc{i}iiic{{d}ii}ddc{{i}dd}dcdc{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}dddd}iiiiiicdc{i}iiicdddc{{d}iiii}dddc{d}ddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}dc{d}ic{{d}iii}c{{i}ddd}iic{d}iiic{i}{i}ic{d}dddciiiiic{d}iiic{{d}iii}dc{{i}dd}ddciciiiiic{d}ddciciiiiic{d}iiic{{d}iii}dc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}ddc{i}ic{{d}iiiii}dddc{d}{d}ddddddc{{i}dd}dcdc{d}dciic{{d}iii}ic{{i}dd}dciiic{{d}ii}ddc{{i}dd}iiiiciiic{d}ddddcddddddciic{{d}iii}ic{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}iic{d}iiiciiic{{d}iii}iic{{i}dd}c{d}dcc{i}ic{d}dcdc{{d}iii}iic{{i}ddd}iiiciiiiiciiiiiicdddddc{{d}ii}ic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}dddd}iiiiiic{i}iiiccddddc{{d}iii}dddddc{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}dd}iiic{d}c{i}cic{d}dddddc{i}iiic{{d}ii}ddc{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}dd}iic{d}dddcddddciiiciiiiiciiiiic{d}iiic{{d}iiii}ic{d}ddc{{i}dddd}iiiiiic{i}{i}dcdc{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}ddd}iic{d}iiiciiic{{d}iii}iic{{i}dd}ddcic{{d}ii}ic{{i}dd}c{d}iiicddddddc{i}{i}dddcicdddc{d}dddc{i}iiiic{{d}ii}dddc{{i}dd}dciiic{{d}ii}ddc{{i}ddd}dddc{i}iicdc{i}ddc{d}{d}iiic{i}iiicic{d}{d}iic{i}{i}dc{d}dciiiiiicdciiiiic{{d}ii}dddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddd}iiic{i}ic{{d}iii}ddc{d}ddciic{{i}dddd}iiic{i}iiic{d}c{{d}iii}iic{{i}d}dddc{d}dddddc{d}iiic{i}{i}dc{{d}ii}ddddc{{i}ddd}iiic{i}c{{d}ii}dddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}dd}iiiiicddc{d}ddddc{{d}iii}ic{{i}dd}dc{d}ic{{d}iii}c{{i}dddd}iiiiic{{d}iiii}dddddc{{i}dddd}iiiiiic{i}iiiccddddc{{d}iiii}dddc{d}cddc{{i}dd}iiiic{d}ddc{i}dddciiiiiic{d}ddddcic{i}iic{{d}ii}ddddc{i}{i}{i}iiic{{i}dddddd}iiicdddcddddddciic{{d}iii}iciic{{i}dd}iiiiic{d}ddddc{i}ic{d}ddc{i}dddciiiiiicdc{{d}ii}ddddc{{i}dd}c{d}iiicddddddc{i}{i}dddcicdddc{d}dddc{i}iiiic{{d}ii}dddc{{i}dd}dciiic{{d}ii}ddc{{i}ddd}dddc{i}iicdc{i}ddc{d}{d}iiic{i}iiicic{d}{d}iic{i}{i}dc{d}dciiiiiicdciiiiic{{d}iiiii}ddc{d}{d}{d}ic{d}{d}ddddc{{i}ddd}iiic{i}{i}{i}ddc{{d}ii}ic{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}ddd}dddc{i}iicdciiiiic{d}cdddddcic{i}iiic{d}iciiiiic{d}iiic{{d}iii}dc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}dd}dc{i}ddc{d}ic{{d}ii}iic{{i}dd}dddcddddciiiiic{d}c{{d}iii}iic{i}ddc{{i}dddd}dddc{i}{i}ddc{{d}ii}dddc{{i}d}dddc{d}{d}iic{i}dddcc{{d}iii}ddddddc{{i}dddd}iiiiic{i}{i}ddc{{d}ii}dddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}dddc{i}iiciiiiiic{d}ic{d}iic{{d}iiiii}ddddddc{d}ddc{{i}ddd}c{i}dciiic{{d}ii}ddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iic{i}dddciiiiic{{d}ii}ddddc{{i}ddd}ddcdddc{i}{i}iiiic{{d}i}ic{{i}dd}dddc{d}ddciiicic{{d}iii}ic{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}ddd}cdcc{i}dddc{{d}iii}ddddddc{{i}dd}iiiiiic{d}{d}iiic{i}iiic{i}dddc{{d}i}ic{{i}dd}iiic{d}iiic{d}iiicc{i}ic{i}dc{{d}i}ic{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}iiicicicdddddc{d}iiicdddddc{{d}iiii}iciiic{d}ddc{{i}d}dddc{d}dddddcdddc{i}iiiiic{d}ddcdddc{i}iiic{{d}ii}ddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}dd}cddddc{d}iiicddddc{i}{i}ddciicdddc{d}dddc{{d}iii}ic{{i}dd}dc{d}ic{{d}iii}c{{i}dd}dddc{d}ddc{i}cddciiiiic{d}iiic{{d}iii}dc{{i}dddd}iiiiic{{d}iiii}dddddc{{i}ddd}ddcdddc{i}ddc{i}ciiiiiic{{d}iii}ddddddc{d}dddc{{i}ddd}dddciiiiic{d}iiic{i}ddciiiiic{{d}ii}iic{{i}d}dddc{d}iiciiiiiic{d}ic{d}iic{{d}iii}iic{{i}dddd}iiiiiiciiic{{d}iii}ic{{i}d}dddc{d}iiciiiciic{d}ddc{{d}iii}ddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}dd}iiiicddcdddciiiiiic{d}{d}ic{i}c{d}iiic{{d}iii}ic{{i}dd}dc{d}ic{{d}iii}c{{i}ddd}icddc{i}iiiiicc{d}dciiiiic{d}iiic{{d}iii}dc{{i}dd}iiiiicdddddc{{d}ii}c{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}c{d}iiicddddddc{i}ddcddciiiiic{d}iiic{{d}iii}dc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}ddcdddc{i}ddc{i}c{d}cddddc{i}iiiic{{d}iii}dc{d}ddc{{i}d}dddc{d}dddddcdddc{i}dc{{d}ii}iic{{i}dd}iiiciic{d}{d}iiiccic{i}dcddc{i}iiic{{d}i}ic{{i}dddd}iiiiic{{d}iiii}dddddc{{i}ddddd}iiiiic{i}{i}dddcic{i}ic{d}dddddc{{d}iii}ic{{i}ddddd}c{i}iiiiicicc{i}dddc{i}ic{{d}ii}ddddc{{i}d}dddc{d}ddddc{i}ic{d}ddc{{d}iii}ddc{{i}dd}c{d}iiiciiiiicdddc{{d}iii}dddddc{{i}ddd}dc{i}{i}c{d}{d}c{i}iiiic{{d}ii}dddc{{i}dd}iic{d}{d}iiic{i}iiic{{d}ii}iic{{i}ddd}dddc{i}dciiiciiiic{d}ddddc{{d}iii}ic{{i}dddd}iiiiiic{i}{i}iiic{{d}i}ic{{i}ddd}iicdddc{i}iiic{{d}iii}iic{d}{d}{d}ddddddc{{i}ddd}iiiic{i}{i}cdddc{i}iiic{d}dddc{{d}iii}ic{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}dd}ddciciiiiic{d}ddciciiiiic{d}iiic{{d}iii}dc{{i}dd}iiicddddc{{d}ii}ic{{i}dddd}iiic{i}{i}iiic{d}{d}iiic{i}iiic{i}dddc{d}{d}ddddddc{{d}iiii}dddc{{i}dd}iic{d}dddc{i}ddc{d}ddc{i}{i}dddc{d}iiic{d}cic{i}c{d}iiic{{d}iii}ic{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddc{d}iiic{i}{i}dc{{d}iiii}iiic{d}{d}{d}iiic{{i}dd}ddciciiic{{d}ii}ddc{{i}ddd}ddciiiiicdddddc{{d}iii}iic{i}{i}{i}iiic{{i}dddddd}iiicdddcddddddciic{{d}iii}ic{{i}dd}iiiic{d}ddciciiiiicdddc{{d}iii}dddddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}dd}iiicddddc{{d}ii}ic{{i}dddd}iiic{i}{i}iiic{d}{d}iiic{i}iiic{i}dddc{d}{d}ddddddc{{d}iiii}dddc{{i}dd}dddc{i}ddc{d}{d}iiciiiiic{{d}iii}ddc{{i}dd}dciiiiiicdc{{d}ii}ddddc{{i}dd}dc{d}ic{{d}iii}c{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}d}dddc{d}{d}ddc{i}{i}iiiic{{d}i}ic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iicdddcddddc{i}{i}dddc{{d}ii}ddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddddd}c{i}iiiiicicc{i}dddc{i}ic{{d}ii}ddddc{{i}dd}iiic{d}{d}iic{i}{i}iiiic{{d}i}ic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iiic{i}icdc{d}ddddc{i}dddcddddddc{{d}iiii}iic{d}ddciic{{i}dddddd}iiiiic{i}{i}iiiiic{{d}iii}ddc{{i}ddd}ddcicddddc{i}{i}dddc{{d}ii}dcdc{{i}ddddd}dddc{i}{i}iiiiic{{d}iii}ddc{{i}ddd}ddcicddddc{i}{i}dddc{{d}ii}dcdc{{i}dddddd}ic{{d}iiiiii}dc{{i}dd}iiic{d}dc{d}iiic{i}icc{{d}iii}ddddddc{{i}dddd}iiiiiiciiic{{d}iii}ic{{i}ddd}iiiiiic{d}dc{i}{i}dc{d}dddddc{{d}iii}iicicddc{i}ddc{{i}dd}dc{d}dddddcdddc{i}dc{{d}ii}iic{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}dd}iiiic{d}ddc{i}dddciiiiiic{d}ddddcic{i}iic{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}dd}dc{i}dddc{d}{d}iiic{i}iiic{{d}ii}ddc{{i}dddd}iiiiiciiiiic{i}iiiic{d}dddddc{i}iiiciiiiic{d}{d}ddc{i}{i}dddc{d}ddddc{i}iiiiic{{d}iii}dc{d}ddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}dd}dc{d}ddcc{i}{i}ddcdddcc{d}dddcdc{{d}iii}iic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}dd}iiiic{d}ddc{d}iiic{i}{i}dc{{d}ii}ddddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}dd}dciiiiiic{d}ddddcic{i}iic{{d}ii}ddddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iic{d}iiic{i}{i}ic{d}{d}iiic{{d}iii}ic{{i}d}dddc{d}iicdc{d}cic{i}iiic{d}dddcdc{{d}iii}iic{{i}dddd}iiiiic{i}{i}dc{{d}ii}ddddc{{i}dd}iiiic{d}ddcic{i}c{{d}iii}dc{d}ddc{{i}dddd}iiiiiic{i}{i}dcdc{{d}ii}ddddc{{i}dddd}iiiiic{i}{i}dc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}dd}iiiic{d}dciiiic{d}iic{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}dddd}iiiiic{i}icc{{d}iii}ddddddc{{i}dd}iiic{d}ddddcc{i}ddc{d}iicdc{{d}iii}iic{{i}dd}iciiiic{d}ddc{i}ic{d}dddddc{{d}iii}ic{{i}dd}ddc{d}dddc{i}{i}dcicdddc{d}{d}iiic{i}ic{{d}iii}iiic{i}{i}ddc{d}{d}{d}iiic{{i}dddd}iiiiiic{i}{i}dcdc{{d}ii}ddddc{{i}d}dddc{d}dddddcdddc{i}dc{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddddd}c{i}iiiiicicc{i}dddc{i}ic{{d}ii}ddddc{{i}dddd}iiiiiciic{i}{i}dddcic{d}{d}c{i}icc{i}iiic{{d}i}ic{{i}dddd}iiic{i}{i}icdddddccddddc{{d}iii}dddddc{{i}dddd}iiiiic{{d}iiii}dddddc{{i}d}dddc{d}{d}ddc{i}{i}dc{d}{d}iiiciiiiic{{d}iii}ddc{{i}dd}dciiiiiicdc{{d}ii}ddddc{{i}dd}dc{d}ic{{d}iii}c{{i}ddd}iiic{i}icdc{{d}ii}dddc{{i}d}dddc{d}{d}ddc{i}ddc{i}cic{d}{d}iiic{i}iic{d}ddddc{i}{i}dc{{d}iii}dc{{i}ddd}dddcdc{d}ddc{i}ddcddddddc{i}iiiiic{d}{d}dc{{d}iiiii}dc{d}ddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}ddd}iiiiiiciiiccddddcddddddcdc{{d}iii}iic{{i}dddd}iiiiic{i}{i}dc{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}iii}ddc{d}ddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}iiiic{d}ddcdddc{i}dc{{d}ii}iic{{i}ddd}iic{i}iiicdddcc{d}icddddcdc{{d}iii}iic{{i}dd}dcdc{{d}iiii}ddddddc{d}ddc{i}{i}{i}iiic{{i}dddddd}iiicdddcddddddciic{{d}iii}ic{{i}dd}iiicic{d}{d}ic{i}{i}dddciic{d}dddddcdc{{d}iii}iic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}ddd}cdcc{i}iiiiic{{d}iii}ddc{d}ddc{{i}ddd}c{i}dciiic{{d}ii}ddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}ddd}ciiiiiic{d}dc{i}{i}ddc{d}dcdddcdc{{d}iii}iic{{i}dddd}iiiiiciic{i}iiiiicdddciiiicc{{d}ii}dddc{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}dd}dddcddddciiiiic{d}c{{d}iii}iic{{i}dd}iiiic{d}ddc{d}iiic{i}{i}dc{{d}ii}ddddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}iic{d}iiiciiic{{d}iii}iic{{i}dd}ddc{d}ic{i}{i}dddc{d}{d}iiic{i}iiic{{d}ii}ddc{{i}dddd}iiiiiiciiicic{i}dciiic{d}dddc{{d}iii}ic{{i}dd}iiic{d}ddddcc{i}dc{{d}ii}iic{{i}dddd}iiiiic{{d}iiii}dddddc{{i}dd}iic{d}{d}iiicicc{i}dddc{i}ic{{d}ii}ddddc{{i}d}dddc{d}ddddc{i}ic{d}ddc{{d}iii}ddc{{i}ddd}dciiiic{i}ic{d}ddcdddc{i}iiic{{d}ii}ddc{{i}dddd}iiiiic{{d}iiii}dddddc{{i}d}dddc{d}{d}ddc{i}ddc{i}cic{d}{d}iiic{i}iic{d}ddddc{i}{i}dc{{d}iii}dc{d}dddc{{i}dd}cdc{d}ddc{i}ddcddddddc{i}iiiiic{{d}iii}ddc{d}ddc{{i}dd}dciiic{{d}ii}ddc{{i}dddd}iiiiic{{d}iiii}dddddc{{i}d}dddc{d}{d}ddc{i}{i}dc{d}{d}iiiciiiiic{{d}iii}ddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}iiiic{d}{d}ic{i}cddddddc{{d}iii}ic{{i}dd}dciiiiiicdc{{d}ii}ddddc{{i}dd}dc{d}ic{{d}iii}c{{i}ddd}iiic{i}ic{{d}iii}ddc{d}ddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dddd}iiiiiic{i}{i}dcdddcddddcdddddciiiiic{d}iiic{{d}iii}dc{{i}d}dddc{d}ddddc{i}ic{d}ddc{{d}iii}ddc{{i}ddd}dddc{i}{i}ddcdddc{d}iciiiiiiciiiic{d}c{i}iciiiiic{{d}ii}iiic{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}dd}iic{d}{d}iiic{i}iiic{{d}ii}iic{{i}dddd}iiiiiciic{i}iiiiicdddciiiicc{{d}ii}dddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}ciiicddddc{i}dddc{d}iic{{d}iii}iic{{i}dddd}iiiiiciiiiic{i}iiiic{d}dddddc{i}iiic{{d}ii}ddc{{i}ddd}iiic{i}ic{{d}iii}ddc{d}ddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}ddd}c{i}dciiiciicic{d}iiic{d}dddc{i}{i}dc{d}dddddc{i}dddc{i}iiic{{d}i}ic{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}ddd}iiiic{i}icddcic{{d}ii}ddddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}dciiiic{d}iic{{d}iii}ic{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}iiic{d}ddddcc{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}dd}cdcic{{d}ii}c{{i}ddd}ddc{i}ic{i}ddc{d}ic{{d}ii}iic{{i}dddd}iiiiic{{d}iiii}dddddc{{i}ddd}iiiiiic{d}dc{i}{i}dddc{d}dcddc{{d}iii}ic{{i}dd}iic{d}{d}iiicicc{i}dddc{i}ic{{d}iii}dc{{i}dddd}dc{i}dddcdddc{d}iiic{{d}iii}ic{{i}dd}iiiiic{d}iiic{d}cic{i}iiic{{d}ii}ddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iicdddcdciiicddc{{d}iiiii}dddddc{d}{d}{d}ddddddc{{i}dddd}iiic{{i}dddddd}dddc{{d}ii}iic{{i}dddd}iiiiic{i}iiiciciiiiic{d}ddcdddc{i}iiic{{d}ii}ddc{{i}dd}dddciicddc{d}iic{i}dciiiiiic{{d}ii}ddddc{{i}ddd}ddc{i}ic{i}ddc{d}ic{{d}ii}iic{{i}d}dddc{d}{d}iic{i}dciiiiiic{{d}ii}ddddc{i}{i}{i}iiic{{i}dddddd}iiicdddcddddddciic{{d}iii}ic{{i}dddd}iiiiiciiiiic{i}iiiic{d}dddddc{i}iiic{{d}ii}ddc{{i}ddd}iiic{i}ic{{d}iii}ddc{d}ddc{{i}dd}ddc{d}ic{i}{i}dddc{d}{d}iiic{i}iiic{{d}ii}ddc{{i}dd}dcdc{d}dciic{{d}iii}ic{{i}ddd}dddc{i}iicdciiiiic{d}cdddddcic{i}iiic{d}iciiiiic{d}iiic{{d}iii}dc{{i}ddd}iic{i}dddc{i}ddc{{d}i}iiic{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}d}dddc{d}iiciiicddddddc{d}iic{{d}iii}iic{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}icddc{i}iiiiic{{d}ii}ddddc{{i}dd}dciiiiiicdc{{d}ii}ddddc{{i}dddd}iiiiiciiiiiicddddddc{i}ddciiiiic{{d}iiii}ddddc{d}{d}{d}ddddddc{{i}ddd}iiiic{i}{i}cdddc{{d}iii}ic{{i}dd}iic{d}{d}iiicicc{i}dddc{i}ic{{d}iii}dc{{i}dddd}dc{i}dddcdddc{d}iiic{{d}iii}ic{{i}d}dddc{d}{d}iic{i}dciiiiiic{{d}ii}ddddc{{i}dd}iiicicddc{d}{d}iiic{i}ddcddcic{i}iic{{d}ii}ddddc{{i}dd}dcdc{{d}ii}iic{{i}ddd}iiiiiicdddciicddddddc{{d}iii}ic{{i}dddd}iiiiic{{d}iiii}dddddc{{i}dd}iiiicic{d}iiicc{d}ic{i}dddc{{d}iii}ddddddc{{i}ddd}c{i}dciiic{{d}ii}ddc{{i}dd}iiicddddcddc{d}iic{{d}iii}ic{{i}d}dddc{d}{d}ddc{i}{i}iiiic{{d}ii}iiic{d}ddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}iiiic{d}ddcdddc{i}dc{{d}ii}iic{{i}ddd}ddciiiiic{i}dddcc{d}dcdc{{d}iii}iic{{i}dd}iiiciic{d}{d}iiiccic{i}dcddc{i}iiic{{d}i}ic{{i}ddd}ddc{i}ic{i}ddc{d}ic{{d}iiii}ddddddc{d}ddc{{i}dd}iiicddddc{{d}ii}ic{{i}dd}iiiciic{d}{d}iiiccic{i}dcddc{i}iiic{{d}i}ic{{i}dd}iiiic{d}ddc{d}iiic{i}{i}dc{{d}ii}ddddc{i}{i}{i}iiic{{i}dddddd}iiicdddcddddddciic{{d}iii}ic{{i}ddd}iic{d}iiiciiic{{d}iii}iic{{i}dd}ddciciiiiic{{d}ii}ddddc{{i}dddd}iiiiic{{d}iiii}dddddc{{i}dd}dddciicddc{d}iic{i}dciiiiiic{{d}ii}ddddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}iiiic{d}ddciciiiiicdddc{{d}iii}dddddc{{i}dddd}iiiiicic{i}iiiciiiiiicdc{{d}ii}ddddc{{i}dd}iiicicdddddcicc{d}iiiciiiiic{d}iiic{{d}iii}dc{{i}ddd}iicdddc{i}iiicic{d}ddddc{i}dddcddddddc{{d}iii}c{{i}dddd}iiiiiiciiicic{i}dciiic{d}dddc{{d}iii}ic{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}c{i}dciiiiiic{d}iiic{d}c{{d}iii}iic{{i}ddd}iicdddc{i}iiicic{d}ddddc{i}dddcddddddc{{d}iii}c{{i}ddd}cdddddc{i}iccdddciiiiic{d}iiic{{d}iii}dc{{i}ddd}ddc{i}ic{i}ddc{d}ic{{d}ii}iic{{i}dddd}iiiiic{{d}iiii}dddddc{{i}dd}iiiiiic{d}{d}iiic{i}iiic{i}dddc{{d}i}ic{{i}ddd}ddcicc{i}ic{{d}ii}c{{i}d}dddc{d}{d}iic{i}dddcc{{d}iiii}ddc{d}{d}{d}ddddddc{{i}dddd}dc{i}{i}{i}iiiiiic{i}ic{d}ddcdddc{i}iiic{{d}ii}ddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}d}dddc{d}{d}iic{i}dddcc{{d}iii}ddddddc{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}dd}iiiiiic{d}{d}iiic{i}iiic{i}dddc{{d}i}ic{{i}ddd}ddcicc{i}ic{{d}iii}iic{d}ddc{{i}dd}dciiic{{d}ii}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}cdc{i}dddcc{{d}iii}ddddddc{{i}dd}iiiiiic{d}{d}iiic{i}iiic{i}dddc{{d}i}ic{{i}dd}iiic{d}iiiciiic{i}ddc{d}dc{i}iiic{{d}ii}iiic{d}ddc{{i}ddd}c{i}dciiic{{d}ii}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}iic{d}iiiciiic{{d}iii}iic{{i}dd}cddddc{d}iiic{i}dciiiiiiciiiiic{{d}i}ic{{i}dd}dc{d}ic{{d}iii}c{{i}dd}iiiic{d}dciiiic{d}iic{{d}iii}ic{{i}dddd}iiiiic{i}{i}ddc{{d}ii}dddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}d}dddc{d}{d}iic{i}dciiiiiic{{d}ii}ddddc{{i}ddd}ddc{i}ic{i}ddc{d}ic{{d}ii}iic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iiiiiiciiiccddddc{{d}iii}dddddc{{i}dddd}iiiiicic{i}iiiciiiiiicdc{{d}ii}ddddc{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}iiiicdddddc{{d}ii}ic{{i}d}dddc{d}iicdc{d}cic{i}iiic{{d}ii}ddc{{i}d}dddc{d}dddddc{d}iiic{i}{i}dc{{d}ii}ddddc{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}ddd}ic{i}ddcddddddciiiiic{d}iiic{{d}iii}dc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iic{d}iiic{i}iiiiicc{d}dc{i}dc{{d}ii}iic{{i}dd}ddc{d}ic{i}{i}dcddddc{{d}iii}c{d}ddddc{{i}dddddd}ddc{i}{i}{i}iiiiic{i}dcicic{{d}iii}ddc{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}dd}iiiicddc{d}icddddcdc{{d}iii}iic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iiiiiiciiiccddddc{{d}iii}dddddc{{i}ddd}ddc{i}ic{i}ddc{d}ic{{d}ii}iic{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}dd}dciiiiiicdc{{d}ii}ddddc{{i}d}dddc{d}dddddc{d}iiic{i}{i}dc{{d}ii}ddddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}ddd}dddc{i}iicddcddddciiiiic{d}iiic{{d}iii}dc{{i}dd}iiiicdddddc{{d}iii}iiic{d}ddc{{i}dddd}iiiiiic{i}{i}dcdc{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}dd}iiiicdddddcc{{d}ii}ic{{i}ddd}ddcdddc{i}{i}dddc{d}iiic{{d}iii}dddddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}iiic{d}ddddcc{{d}iii}ic{{i}dddd}iiiiic{i}iiic{i}icdddddc{d}ddciciiiiic{d}iiic{{d}iiiiii}ddddc{d}{d}{d}iiic{{i}dd}iiiic{d}ddcdddc{i}dc{{d}ii}iic{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}iiiiiiciiiccddddcddddddcdc{{d}iii}iic{{i}dddd}iiiiic{i}{i}dc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}dd}iiic{d}cdddddcic{i}iiiic{{d}ii}dddc{{i}dd}dc{d}ic{{d}iii}c{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}d}dddc{d}{d}iic{i}dddcc{{d}iiii}ddddc{d}ddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}ddciciiiiic{d}dcddddddciicdc{{d}iii}iic{{i}dd}iiiic{d}ddc{d}iiic{i}{i}dc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{i}{i}c{{d}i}ic{{i}d}dddc{d}{d}iic{i}iiic{d}dddc{{d}iii}ic{{i}ddd}ciiiciiicc{d}iiicdc{{d}iii}iic{{i}d}dddc{d}ddddc{i}ic{d}ddc{{d}iii}ddc{{i}ddd}dddc{i}{i}ddcdddddc{d}ddddc{i}iiic{d}ddddc{i}{i}dddc{d}ddddc{i}iiiiic{{d}ii}dddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dddd}iiiiiic{i}iiiccddddc{{d}iiii}ddc{{i}ddd}c{d}dcdddc{i}dddc{i}c{d}{d}iiic{i}iiiic{{d}iiiii}ddddddc{d}{d}{d}iiic{{i}ddd}iicdddc{i}iiic{d}dddc{{d}iii}ic{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}iiiic{d}ddcdddc{i}iiic{d}dddc{{d}iii}ic{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}dd}iiic{d}{d}iic{i}{i}iic{{d}i}iiic{{i}dd}dddc{d}ddc{i}iiiiiciiic{{d}ii}dddc{{i}dddd}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}c{d}iiicddddddc{i}{i}dddcicdddc{d}dddc{i}iiiic{{d}ii}dddc{{i}ddd}iic{i}iiic{d}iiic{d}iiic{{d}iii}dc{{i}dd}iiiiicdddddcdcdc{{d}ii}iic{{i}dd}c{d}dciic{i}iic{{d}iii}ic{d}ddddc{{i}ddddd}ic{i}{i}icdddc{{d}iii}ic{{i}dd}iiiicdddddccddddc{{d}iii}dddddc{{i}ddd}ddc{i}ic{i}ddc{d}ic{{d}ii}iic{{i}dddd}iiiiic{{d}iiii}dddddc{{i}ddd}iiiic{d}ic{i}{i}dddc{{d}ii}ddc{{i}ddd}c{i}iicdddcddc{{d}ii}iiic{{i}dd}dcdc{d}ic{{d}iii}ic{{i}dd}dc{d}ic{{d}iii}c{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}dd}iiic{d}dcdddc{i}dddc{i}c{d}{d}iiic{i}iiiic{{d}ii}dddc{{i}dddd}iiiiic{i}{i}ddc{{d}ii}dddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}dd}c{d}dddddc{i}{i}ddcc{d}ddddcdc{{d}iiiiii}dc{d}{d}{d}iiic{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}ddd}iiiiiic{d}dciciiic{i}dddcc{d}iiicdc{{d}iii}iiciic{{i}dddddd}iiiiiciiic{d}{d}iiic{i}iiic{d}iiicddc{{d}iiiiii}iiic{{i}dddddd}iiiiic{d}ddc{i}{i}dddcdddddc{d}ddc{i}ic{d}dciiicic{d}{d}{d}dddddc{i}c{d}ddc{{i}dddd}iiiiiic{i}{i}dcdc{{d}ii}ddddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}ddd}ic{i}ic{d}dddcddddc{i}{i}dc{{d}ii}ddddc{{i}ddd}ddciiiiic{i}c{d}{d}iic{i}iiiiiccdcddddddciiiiiciiiiiic{d}iiic{d}iic{i}dciiiiiic{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}d}dddc{d}{d}ddc{i}{i}ddc{{d}ii}dddc{{i}ddd}dc{i}ddciiiciiiiciiiiic{{d}iiii}dddc{d}{d}ddddddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}ddciiiiicdddddc{{d}iii}iic{{i}dd}ddciciiiiic{{d}ii}ddddc{{i}ddd}iiiiiicdddciicddddddc{{d}iii}ic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}ddc{i}iiiicdddcic{{d}ii}c{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iiiic{d}ic{i}{i}dddc{{d}ii}ddc{{i}ddd}c{i}dciiic{{d}ii}ddc{{i}ddd}cdcddddc{i}{i}dddc{{d}ii}ddc{{i}dd}dc{d}ic{{d}iii}c{{i}ddd}iiiiicddciiiccdddciiiiic{d}iiic{{d}iii}dc{{i}dd}iiicddddcddc{d}iicdddc{i}iiic{d}dc{i}{i}ic{{d}i}ic{{i}dd}iiiiic{d}iiic{d}cic{i}iiicddddc{d}icddddc{i}{i}dc{d}ddc{{d}iiii}c{d}ddc{{i}dd}iiicddddc{{d}ii}ic{{i}dd}dddc{d}ddc{i}iiic{d}dddciiiiiicddcdc{{d}iii}iic{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}ciiiiicdc{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}ddd}iiiciiiiiciiiiiicdddddc{{d}ii}ic{{i}dd}dcdc{d}ic{{d}iii}ic{{i}dd}dc{d}ic{{d}iii}c{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}dddc{i}{i}ddcdddddc{d}ddddc{i}iiic{d}ddddc{i}{i}dddc{d}ddddc{i}iiiiic{{d}ii}dddc{{i}dddd}iiiiic{i}{i}ddc{{d}ii}dddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}cdc{i}dddcc{{d}iii}ddddddc{{i}dd}c{d}dddddc{i}{i}ddcic{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}iii}c
```
No input, so I'm just making it up.
] |
[Question]
[
## Introduction
[A229037](https://oeis.org/A229037) has a quite intriguing plot (at least for the first few terms):
![](https://i.stack.imgur.com/JQY1V.png)
There is the conjecture, that it might indeed have some kind of fractal property.
### How is this sequence constructed?
Define `a(1) = 1, a(2) = 1` then for each `n>2` find a minimal positive integer `a(n)` such that for every arithmetic 3 term sequence `n,n+k,n+2k` of indices, the corresponding values of the sequence `a(n),a(n+k),a(n+2k)` is *not* an arithmetic sequence.
## Challenge
Given a positive integer `n` as an input, output the first `n` terms `a(1), ... , a(n)` of this sequence. (With any reasonable formatting. Possible leading/trainling characters/strings are irrelevant.)
There are snippets for generating this sequence available, but I think other approaches might be more golfable/more suitable for certain languages.
Please let us know how your progrm works. If you come a cross a particularly efficient algorithm you might want to mention that too, as it would allow to plot more terms of the sequence in shorter time.
### First few test cases:
```
1, 1, 2, 1, 1, 2, 2, 4, 4, 1, 1, 2, 1, 1, 2, 2, 4, 4, 2, 4, 4, 5, 5, 8, 5, 5, 9, 1, 1, 2, 1, 1, 2, 2, 4, 4, 1, 1, 2, 1, 1, 2, 2, 4, 4, 2, 4, 4, 5, 5, 8, 5, 5, 9, 9, 4, 4, 5, 5, 10, 5, 5, 10, 2, 10, 13, 11, 10, 8, 11, 13, 10, 12, 10, 10, 12, 10, 11, 14, 20, 13
```
### More testcases:
```
a(100) = 4
a(500) = 5
a(1000) = 55
a(5000) = 15
a(10000) = 585
```
All terms up to `n=100000` are available here: <https://oeis.org/A229037/b229037.txt>
Thanks @MartinBüttner for the help and encouragement.
[Answer]
## Python 2, 95 bytes
```
l=[];n=input()
exec"a=min(set(range(n))-{2*b-c for b,c in zip(l,l[1::2])});print-~a;l=[a]+l;"*n
```
The main trick is in generating the numbers the new value must avoid. Keeping the reversed sequence so far in `l`, let's look at what elements might form a three-term arithmetic progression with the value we're about to add.
```
? 4 2 2 1 1 2 1 1 a b c
^ ^ ^ ? 4 2
^ ^ ^ ? 2 1
^ ^ ^ ? 2 2
^ ^ ^ ? 1 1
```
The other numbers are the paired members of `l` and every second element of `l`, so `zip(l,l[1::2])`. If this pair is `(b,c)` then the arithmetic progression `(a,b,c)` happens for `a=2*b-c`. After generating the set of `a`'s to avoid, the code takes the minimum of the complement, prints it, and prepends it to the list. (Actually, the computation is done with numbers decreased by 1, and printed 1 higher, to let `range(n)` serve as a universe of candidates.)
[Answer]
## Mathematica, 95 bytes
```
For[n_~s~k_=0;n=0,n<#,For[i=n,--i>0,s[2n-i,2f@n-f@i]=1];For[++n;i=1,n~s~i>0,++i];Print[f@n=i]]&
```
Certainly not the golfiest approach, but this is actually fairly efficient, compared to the algorithms I tried from the OEIS page.
As opposed to checking all the forbidden values for each *s(n)* when we get there I'm using a sieve-based approach. When we find a new value *s(n)* we check immediately which values this forbids for *m > n*. Then we just solve the *s(n+1)* by looking for the first value that wasn't forbidden.
This can be made even more efficient by changing the conditional `--i>0` to `2n-#<=--i>0`. In that case, we avoid checking forbidden values for *n* greater than the input.
For a somewhat more readable version, I started with this code, which stores the results up to `max` in a function `f`, and then golfed it to the above one-line pure function:
```
max = 1000;
ClearAll[sieve, f];
sieve[n_, k_] = False;
For[n = 0, n < max,
temp = f[n];
For[i = n - 1, i > 0 && 2 n - i <= max, --i,
sieve[2 n - i, 2 temp - f[i]] = True;
];
++n;
i = 1;
While[sieve[n, i], ++i];
f@n = i;
]
```
[Answer]
# Haskell, ~~90~~, ~~89~~, ~~84~~, 83 bytes
Can probably be golfed more, but this is still a decent ~~first~~ attempt:
```
a n|n<1=0|n<3=1|1<2=[x|x<-[1..],and[x/=2*a(n-k)-a(n-k-k)||a(n-k-k)<1|k<-[1..n]]]!!0
```
Ungolfed:
```
a n | n<1 = 0
| n<3 = 1
| otherwise = head (goods n)
goods n = [x | x <- [1..], isGood x n]
isGood x n = and [ x - a(n-k) /= a(n-k) - a(n-k-k) || a(n-k-k) == 0 | k <- [1..n] ]
```
This is a simple implementation which returns '0' for out of bounds. Then, for each possible value, it checks that for all k <= n and in bounds, [x, a(x-k), a(x-2k)] is not an arithmetic sequence.
Upper bound on time complexity (using the fact from the OEIS page that a(n) <= (n+1)/2:
```
t n <= sum[ sum[2*t(n-k) + 2*t(n-k-k) | k <- [1..n]] | x <- [1..(n+1)/2]]
<= sum[ sum[4*t(n-1) | k <- [1..n]] | x <- [1..(n+1)/2]]
<= sum[ 4*t(n-1)*n ] | x <- [1..(n+1)/2]]
<= 4*t(n-1)*n*(n+1)/2
->
O(t(n)) == O(2^(n-2) * n! * (n+1)!)
```
I'm not sure how good this bound is because calculating the first 1k values of 't' and using a linear model on the logs of the values gave appx. O(22^n), with p-value < 10^(-1291), in case it matters.
On an implementation level, compiling with '-O2', it took ~35 min to calculate the first 20 values.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~33~~ 31 bytes
```
;Ė{~b.hℕ₁≜∧.¬{ġh₃hᵐs₂ᶠ-ᵐ=}∧}ⁱ⁽↔
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/rItOq6JL2MRy1THzU1Puqc86hjud6hNdVHFmY8amrOeLh1QvGjpqaH2xboApm2tUDZ2keNGx817n3UNuX/fyPT/1EA "Brachylog – Try It Online")
*In case it matters: The 2-byte golf was possible thanks to a feature I [requested](https://chat.stackexchange.com/transcript/message/49663867#49663867) after working on this challenge.*
### Explanation
We iteratively generate the sequence as a list in reverse order, e.g. `[2,2,1,1,2,1,1]`, and reverse it at the end.
There are a couple of nested predicates here. Let's look at them from the inside out. The first one, `ġh₃hᵐs₂ᶠ-ᵐ=`, takes a candidate subsequence `a(n),a(n-1),...,a(0)` and determines whether `a(n),a(n-k),a(n-2k)` is an arithmetic sequence for some `k`.
```
ġ Group the list into equal-length sublists (with the possible exception of
the last sublist, which might be shorter)
h₃ Get the first 3 sublists from that list
hᵐ and get the head of each of those 3 sublists
We now have a list containing a(n),a(n-k),a(n-2k) for some k
s₂ᶠ Find all 2-element sublists of that list: [a(n),a(n-k)] and [a(n-k),a(n-2k)]
-ᵐ Find the difference of each pair
= Assert that the two pairwise differences are equal
```
For example, with input of `[1,2,1,1,2,1,1]`:
```
ġ has possible outputs of
[[1],[2],[1],[1],[2],[1],[1]]
[[1,2],[1,1],[2,1],[1]]
[[1,2,1],[1,2,1],[1]]
[[1,2,1,1],[2,1,1]]
[[1,2,1,1,2],[1,1]]
[[1,2,1,1,2,1],[1]]
[[1,2,1,1,2,1,1]]
h₃ has possible outputs of
[[1],[2],[1]]
[[1,2],[1,1],[2,1]]
[[1,2,1],[1,2,1],[1]]
hᵐ has possible outputs of
[1,2,1]
[1,1,2]
[1,1,1]
s₂ᶠ has possible outputs of
[[1,2],[2,1]]
[[1,1],[1,2]]
[[1,1],[1,1]]
-ᵐ has possible outputs of
[-1,1]
[0,-1]
[0,0]
= is satisfied by the last of these, so the predicate succeeds.
```
The next predicate outwards, `~b.hℕ₁≜∧.¬{...}∧`, inputs a subsequence `a(n-1),a(n-2),...,a(0)` and outputs the next bigger subsequence `a(n),a(n-1),a(n-2),...,a(0)`.
```
~b.hℕ₁≜∧.¬{...}∧
~b. The input is the result of beheading the output; i.e., the output is
the input with some value prepended
.h The head of the output
ℕ₁ is a natural number >= 1
≜ Force a choice as to which number (I'm not sure why this is necessary,
but the code doesn't work without it)
∧ Also,
. the output
¬{...} does not satisfy the nested predicate (see above)
I.e. there is no k such that a(n),a(n-k),a(n-2k) is an arithmetic sequence
∧ Break unification with the output
```
Finally, the main predicate `;Ė{...}ⁱ⁽↔` takes an input number and outputs that many terms of the sequence.
```
;Ė{...}ⁱ⁽↔
; Pair the input number with
Ė the empty list
{...}ⁱ⁽ Using the first element of the pair as the iteration count and the second
element as the initial value, iterate the nested predicate (see above)
↔ Reverse, putting the sequence in the proper order
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 19 bytes
This is my first Jelly answer in quite a while. Glad to be back.
This is a port of [my APL answer](https://codegolf.stackexchange.com/a/191345/47581) which itself is an adaptation of many of the algorithms used here. The main difference is that this is 0-indexed.
**Edit:** -5 bytes thanks to Jonathan Allan.
[Try it online!](https://tio.run/##ATAAz/9qZWxsef//4biKbTLJk@G5geG4pF8KxbtK4bifw4fhuYI7CjHDh8KhVf///zEwMDA "Jelly – Try It Online")
```
Ḋm2ɓṁḤ_
ŻJḟÇṂ;
1Ç¡U
```
**Explanation**
```
Ḋm2ɓṁḤ_ First link. Takes our current sequence S as our left argument.
We are trying to calculate, of an arithmetic progression A B C,
the C using the formula, C = 2*B - A
Ḋ Remove the first element of S.
m2 Get every element at indices 0, 2, 4, ...
This is equivalent to getting every second element of S, a list of As.
ɓ Starts a dyad with reversed arguments.
The arguments here are S and As.
ṁ This molds S in the shape of As, giving us a list of Bs.
Ḥ We double the Bs.
_ And subtract As from 2 * Bs.
ŻJḟÇṂ; Second link. Takes S as our left argument.
Ż Append a 0 to S.
J Range [1, len(z)]. This gets range [1, len(S) + 1].
ḟÇ Filter out the results of the previous link, our Cs.
Ṃ Take the minimum of Cs.
; And concatenate it with the rest of the sequence so far.
1Ç¡U Third link. Where we feed our input, n.
1 A list with the element 1.
Ç¡ Run the previous link n times.
U Reverse everything at the end.
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 37 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Many thanks to Adám for his help in writing and golfing this answer in [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard), a great place to learn the APL language. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKNdIe3/o5691Y96t@o86l3xqKtZ41HvZkPtR52LgEKadbqH1hs96loKZEcbHZ7@qLfhUS@Qs/lRT5fR4e0gDWB1sbWPehc/6psKNGINyFCutEdtEx719hkCjVavrVbXUQdKgnCROlC1@qOuRUaPerYD@clF6mnqCo965yqUFCWmpOUplOQrAKn/j9omgpykkQZyRO2hFYYGBgYA "APL (Dyalog Extended) – Try It Online")
**Edit:** -6 bytes thanks to Adám
```
⌽{⍵,⍨⊃(⍳1+≢⍵)~-¯2⊥⍵[2×⍀⍥⍳⌊2÷⍨≢⍵]}⍣⎕,⍬
```
**Explanation**
```
{⍵,⍨⊃(⍳1+≢⍵)~-¯2⊥⍵[2×⍀⍥⍳⌊2÷⍨≢⍵]} ⍵ is our right argument, the sequence S
⌊2÷⍨≢⍵ We start by calculating X = ⌊len(S)÷2⌋
⍳ Get a range [1, X]
2×⍀⍥ With that we can get S[:X] and S[:X×2:2]
or S up to halfway and every 2nd element of S
-¯2⊥⍵[ ] And with that we can get 2*S[:X] - S[:X×2:2]
Which is C=2*B-A of a progression A B C
(⍳1+≢⍵)~ We remove these Cs from our possible a(n)s
I use range [1, len(S)+1]
⊃ Get the first result, which is the minimum
⍵,⍨ And then prepend that to S
⌽{...}⍣⎕,⍬
{...}⍣⎕ We iterate an "input" ⎕ times
,⍬ with an empty list ⍬ as the initial S
⌽ and reversing S at the end as we have built it backwards
```
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~43~~ ~~39~~ 38 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Here is a faster but less golfy solution that can calculate `⍺(10000)` in a few seconds.
```
⌽{⍵,⍨⊃(⍳1+≢⍵)~-⌿⍵[1 2 1∘.×⍳⌊2÷⍨≢⍵]}⍣⎕,⍬
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe3/o5691Y96t@o86l3xqKtZ41HvZkPtR52LgEKadbqPevYDGdGGCkYKho86Zugdng6Uf9TTZXR4O0g9WFls7aPexY/6pgJNWAMykyvtUduER719hkCT1Wur1XXUgZIgXKQOVK3@qGuR0aOe7UB@cpF6mrrCo965CiVFiSlpeQol@QpA6v@jtokgF2mkgdxQe2iFoQEQAAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 71 bytes
```
->n,*a{a.fill(0,n){|s|([*1..n]-(1..s/2).map{|o|2*a[s-o]-a[s-2*o]})[0]}}
```
[Try it online!](https://tio.run/##NcWxCsMgEADQPV@RUSVeTvf2R@SG6yAEjEpth6B@u20Iect7f1/H8I@hn3FRXBn8FoLAJcraShNOGYBIWvwrq5Wwc64tNavYFZ1In1mVqEuH1PvIs3eGpjN7ZfAekSBw@Ywf "Ruby – Try It Online")
Generates all forbidden values, then takes the complement of that array in (1..n) and takes the first value of the result. That means I am assuming that `a[n] <= n` for all n, which is easily proven using induction (if the first n/2 terms are all less than n/2, then there can't be an arithmetic progression leading to n).
The syntactic trick here is also mildly interesting: `*a` is used to initialize an array of additional arguments (which would be ignored if we passed any), and then `a.fill` mutates the argument array and implicitly returns it.
[Answer]
## MATLAB, 156 147 bytes
I've finally gotten to golf this down a bit:
```
N=input('');s=[0;0];for n=1:N,x=s(n,~~s(n,:));try,a(n)=find(~ismember(1:max(x)+1,x),1);catch,a(n)=1;end,s(n+1:2*n-1,end+1)=2*a(n)-a(n-1:-1:1);end,a
```
Ungolfed:
```
N=input(''); % read N from stdin
s=[0;0];
for n=1:N,
x=s(n,~~s(n,:)); % x=nonzeros(s(n,:));
try,
a(n)=find(~ismember(1:max(x)+1,x),1); % smallest OK number
catch,
a(n)=1; % case of blank page for n
end,
s(n+1:2*n-1,end+1)=2*a(n)-a(n-1:-1:1); % determined new forbidden values
end,
a % print ans=...
```
Input is read from STDIN, and printing is done automatically with `ans=` and stuff appended. I hope this qualifies as "reasonable" output.
This is also a sieve-based solution: the variable `s(i,:)` keeps track of those sequence values which are *forbidden* for `a(i)`. The `try-catch` block is needed to treat the case of an empty (meaning full zero) `s` matrix: in this case the lowest value of `1` is already allowed.
However, the memory need (or runtime?) gets pretty messy above `N=2000`. So here's a non-competing, more efficient solution:
```
%pre-alloc
s = zeros([N,fix(N*0.07+20)]); %strict upper bound, needs adjusting later
i = zeros(1,N);
a = 1;
for n = 2:N,
x = s(n,1:i(n));
if isempty(x),
a(n) = 1;
else
a(n) = find(~ismember(1:max(x)+1,x),1);
end,
j = n+1:min(2*n-1,N);
i(j) = i(j)+1;
s(N,max(i(j))) = 0; %adjust matrix size if necessary
b = a(n-1:-1:1);
s(sub2ind([N,size(s,2)+1],j,i(j))) = 2*a(n)-b(1:length(j));
end
```
In this implementation the `s` matrix again contains forbidden values, but in a well-ordered way, without any zero blocks (which are present in the competing version). The index vector `i` keeps track of the number of forbidden vectors in `s`. At first sight cells would be great to keep track of the information stored in `s`, but those would be slow, and we couldn't index a bunch of them at the same time.
One nasty feature of MATLAB is that while you can say `M(1,end+1)=3;` and automatically expand a matrix, you can't do the same with linear indexing. It sort of makes sense (how should MATLAB know the resulting array size, in the framework of which it should interpret the linear indices?), but it still surprised me. This is the reason for the superfluous line `s(N,max(i(j))) = 0;`: this will expand the `s` matrix for us whenever necessary. The starting size guess `N*0.07+20` comes from a linear fit to the first few elements, by the way.
In order to test runtime, I also checked a slightly modified version of the code, where I initialized the `s` matrix to have size `N/2`. For the first `1e5` elements this seems to be a very generous guess, so I removed the expansion step of `s` mentioned in the previous paragraph. These together imply that the code will be faster, but also less robust at very high `N` (since I don't know how the series looks like there).
So here are a few runtimes, comparing
* v1: the competing golfed version,
* v2: the low-starting-size, fool-proof version and
* v3: the generous-starting-size, might-fail-for-large-N version.
I measured these on R2012b, taking the best of 5 runs inside a named function definition with `tic/toc`.
1. `N=100`:
* v1: `0.011342 s`
* v2: `0.015218 s`
* v3: `0.015076 s`
2. `N=500`:
* v1: `0.101647 s`
* v2: `0.085277 s`
* v3: `0.081606 s`
3. `N=1000`:
* v1: `0.641910 s`
* v2: `0.187911 s`
* v3: `0.183565 s`
4. `N=2000`:
* v1: `5.010327 s`
* v2: `0.452892 s`
* v3: `0.430547 s`
5. `N=5000`:
* v1: N/A (didn't wait)
* v2: `2.021213 s`
* v3: `1.572958 s`
6. `N=10000`:
* v1: N/A
* v2: `6.248483 s`
* v3: `5.812838 s`
It would seem that the `v3` version is significantly, but not overwhelmingly faster. I don't know whether an element of uncertainty (for very large `N`) is worth the minor increase in runtime.
[Answer]
# [Uiua](https://uiua.org), 28 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⇌⍥(⊂⊗0⍘⊚∸↥0-⬚∞-,▽◿2⇡⧻...)∶[]
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oeM4o2lKOKKguKKlzDijZjiipriiLjihqUwLeKsmuKIni0s4pa94pe_MuKHoeKnuy4uLiniiLZbXQpmIDEwMAojIDEsIDEsIDIsIDEsIDEsIDIsIDIsIDQsIDQsIDEsIDEsIDIsIDEsIDEsIDIsIDIsIDQsIDQsCiMgMiwgNCwgNCwgNSwgNSwgOCwgNSwgNSwgOSwgMSwgMSwgMiwgMSwgMSwgMiwgMiwgNCwgNCwKIyAxLCAxLCAyLCAxLCAxLCAyLCAyLCA0LCA0LCAyLCA0LCA0LCA1LCA1LCA4LCA1LCA1LCA5LAojIDksIDQsIDQsIDUsIDUsIDEwLCA1LCA1LCAxMCwgMiwgMTAsIDEzLCAxMSwgMTAsIDgsIDExLAojIDEzLCAxMCwgMTIsIDEwLCAxMCwgMTIsIDEwLCAxMSwgMTQsIDIwLCAxMw==)
I don't think I like the "quadruplicate" up front...
Takes n and outputs the first n values of the sequence.
```
⇌⍥(⊂⊗0⍘⊚∸↥0-⬚∞-,▽◿2⇡⧻...)∶[] input: n
⇌⍥(...):[] repeat n times to the empty list and reverse the result...
⊂⊗0⍘⊚∸↥0-⬚∞-,▽◿2⇡⧻... input: current list L reversed, output: next item prepended
▽◿2⇡⧻. extract every 2nd element using mask 0 1 0 1...
-⬚∞-, . 2L minus the above, where the above is padded with ∞
↥0 convert negatives to 0 to appease ⍘⊚
∸ prepend 0 to get 1 at the first iteration
⍘⊚ inverse where; counts of 0, 1, ...
⊗0 index of 0 (the smallest nonnegative integer
not in the list before ⍘⊚)
⊂ . prepend it to L
```
[Answer]
## ES6, 114 bytes
```
n=>[...r=Array(n)].map((x,i,s)=>{for(y=1;x&&x[y];y++);r[i]=y;for(j=i;++j<n;s[j][y+y-r[i+i-j]]=1)s[j]=s[j]||[]}&&r
```
Returns an array of the first n elements of the sequence, so the indices are 1 off the ungolfed version below. I used the sieve approach. This version slows down after about n=2000; a previous version avoided reading off the beginning of the array which meant it didn't slow down until about n=2500. An older version used the sieve array as a list of forbidden values rather than a boolean array of which values were forbidden; this could get to about n=5000 without breaking sweat. My original version tried to use bitmasks but that turned out to be unhelpful (and was also far too long at 198 bytes).
The not quite so slow version ungolfed:
```
function smoke(n) {
result = [];
sieve = [];
for (i = 1; i <= n; i++) {
value = 1;
if (sieve[i]) {
while (sieve[i][value]) {
value++;
}
}
result[i] = value;
for (j = 1; j < i && i + j <= n; j++) {
if (!sieve[i + j]) sieve[i + j] = [];
sieve[i + j][value + value - result[i - j]] = true;
}
}
return result;
}
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~12.5~~ 10.5 bytes (21 nibbles)
```
.~~1/-,~!*2$`%~>>@-
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWm_Xq6gz1dXXqFLWMVBJU6-zsHHQhMlAFCxZyQRgA)
Outputs the infinite sequence.
'Nnumbers-the-new-value-must-avoid' approach taken from [xnor's Python answer](https://codegolf.stackexchange.com/a/69284/95126).
```
.~~1/-,~!*2$`%~>>@- # full program
.~~1/-,~!*2$`%~>>@-$ # with implicit variable shown:
.~~ # append until null,
1 # starting with the 1-element list [1]:
# get the numbers the new value must avoid:
! # zip together:
*2$ # twice the current list
`%~>>@ # and its even-indexed elements
- # by subtraction,
- # now remove the numbers to avoid from
,~ # the infinite list of natural numbers
/ $ # and get the first element.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ƒ¯Âxsιθ-∞sKнˆ
```
Inspired by the [Python](https://codegolf.stackexchange.com/a/69284/52210), [Nibbles](https://codegolf.stackexchange.com/a/266181/52210), and [Jelly](https://codegolf.stackexchange.com/a/191386/52210) answers, so make sure to upvote those as well!
[Try it online.](https://tio.run/##ASIA3f9vc2FiaWX//8aSwq/DgnhzzrnOuC3iiJ5zS9C9y4b//zQw)
**Explanation:**
```
ƒ # Loop the (implicit) input+1 amount of times:
¯ # Push the global array (empty by default)
 # Bifurcate it; short for Duplicate & Reverse copy
x # Double each value in the reversed list (without popping)
s # Swap so the non-doubled reversed list is at the top again
ι # Uninterleave it into two parts
θ # Pop and leave the last part, for all (0-based) odd-indiced values
- # Remove the values in the lists from one another at the same positions,
# removing any trailing items, since the lists are of unequal lengths
∞ # Push an infinite positive list: [1,2,3,...]
s # Swap so the generated list is at the top again
K # Remove all those values from the infinite list
н # Pop and keep the first/smallest value remaining
ˆ # Pop and add it to the global array for the next iteration
# (after the loop, the global array that's still on the stack after the
# bifurcation is output implicitly as result, hence why we loop +1 amount
# of times)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 65 bytes
```
f=(n,x=1,g=d=>--d?2*f(d)-x!=f(2*d-n)?g(d):g(n,++x):x)=>n>0?g(n):f
```
[Try it online!](https://tio.run/##JcpBDoMgEEDRs3THCNOg3WEHz2JEyLQGjBhDevhSkv7ly3/N15yXg/cTY3JrrZ5EVIV6FciRRXTT0HnhAMuNvBg6hxGm0MCENkpZwBQgG61uGsH46tMhmPqRnw89SsmwpJjTtt63FAQrLxigftN@cvOK@ZyXN2b@rNTrfz8 "JavaScript (Node.js) – Try It Online")
Slow
] |
[Question]
[
You are transported in a parallel universe where people write mathematical equations on computers as ASCII art by hand. As a LaTeX addict, this is totally unacceptable, and you ought to automate this process somewhat.
Your goal is to write a program that outputs an ASCII version of an equation inputed as a LaTeX math command.
### Mandatory LaTeX commands to support
* Sum: the LaTeX command for a sum is `\sum_{lower bound}^{upper bound}`
The ASCII figure you have to use for sums is:
```
upper bound
___
\ `
/__,
lower bound
```
* Product: the LaTeX command for a product is `\prod_{lower bound}^{upper bound}`
The ASCII figure you have to use for products is:
```
upper bound
____
| |
| |
lower bound
```
* Fraction: the LaTeX command for fractions is `\frac{numerator}{denominator}`
The ASCII figure you have to use for fractions is:
```
numerator
-----------
denominator
```
Anything that is not one of those three commands is displayed as is. For example, `\sum{i=3}^{e^10}\frac{3x+5}{2}`should be displayed as
```
e^10
___ 3x+5
\ ` ----
/__, 2
i=3
```
### Inputs
The input is a LaTeX command passed as a string (or your language's equivalent to strings). LaTeX commands can be nested, for instance `\frac{\frac{1}{2}}{3}` is a valid input. Inputs are supposed to be always correct (no need to check LaTeX's syntax in your code). Inputs will only consist of the three LaTeX commands presented above and 'text' that you won't need to format.
LaTeX commands will always come with the syntax presented above, i.e. sums and products will always have upper and lower bounds (although they can be empty) and there will always be a numerator and denominator for fractions.
We assume that the bounds of sums and products are at most 4 characters long (= the width of the sum and product symbols), so that you don't have to worry about possible overlap issues. For similar reasons, we assume that the bounds are just 'text' and will never be LaTeX commands, e.g. `\sum_{\sum_{1}^{2}}^{1}` is not a valid input.
### Outputs
Your program's output is the ASCII representation of the LaTeX command you were given as input.
Your program has to take horizontal alignment into account: for instance, the bounds of the sum or the product have to be horizontally aligned with the sum or product symbol (which are both 4 characters wide).
If the bound has an odd number of characters, it does not matter whether it is one character off to the right or to left of the center, whichever is fine. The fraction's line has to be as long as the numerator or the denominator, whichever is the longest.
Your program has to take vertical alignment into account: for instance, `\frac{\frac{1}{2}}{3} = \frac{1}{6}` should be displayed as
```
1
-
2 1
- = -
3 6
```
For sums and products, since the symbols are 4 characters high, the vertical center is assumed to be the second line from the top.
Horizontal spacing is assumed to be correct in the given input, i.e. the spaces in the input should be displayed in the output.
### Test cases
* Input `abc = 2`
Output `abc = 2`
* Input `e = \sum_{n=0}^{+inf} \frac{1}{n!}`
Output
```
+inf
___ 1
e = \ ` --
/__, n!
n=0
```
* Input `e^x = 1 + \frac{x}{1 - \frac{x}{2 + x - ...}}`
Output
```
x
e^x = 1 + ---------------
x
1 - -----------
2 + x - ...
```
* Input `\prod_{i=1}^{n} \frac{\sum_{j=0}^{m} 2j}{i + 1}`
Output
```
m
___
\ ` 2j
n /__,
____ j=0
| | -------
| | i + 1
i=1
```
* Input `\frac{sum}{prod} = \sum_{frac}^{prod} sum`
Output
```
prod
sum ___
---- = \ ` sum
prod /__,
frac
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins.
[Answer]
# Python 2, ~~656~~ ~~627~~ 618 bytes
```
M=max
O=lambda l,o=2:[(p+o,c)for p,c in l]
def C(s,m=0):
if''<s<'}'[m:]:f,w,h,d,s=C(s,1);F,W,H,D,s=C(s);e=M(d,D);return[O(f,e-d)+O(F,w*1j+e-D),w+W,M(h-d,H-D)+e,e,s]
if'\\'!=s[:1]:return[[(0,s[:1])]*m,m,m,0,s[1:]]
t=s[1]<'s';e=s[1]>'f';f,w,h,d,s=C(s[5+t+e:]);F,W,H,D,s=C(s[1+e:]);g=M(w,W);G=C('-'*g)[0]
if e:f,w,h,F,W,H=F,W,H,f,w,h;g=4;p=C('| |')[0];G=C('_'*(3+t))[0]+[O(C('/__,')[0])+[(1,'\\'),(1+3j,'`')],O(p,1)+O(p)][t]
x=M(w,W,g);return[O(f,(x-w)/2*1j)+O(F,(x-W)/2*1j+h+3**e)+O(G,(x-g)/2*1j+h),x,h+3**e+H,h+e,s]
f,w,h,d,s=C(raw_input())
for y in range(h):print"".join(dict(f).get(y+x*1j,' ')for x in range(w))
```
Takes input on STDIN and writes output to STDOUT.
The program assumes that no other control sequence than `\frac`, `\sum` or `\prod` appears in the input (i.e., it won't show as normal text,) and that `~` doesn't appear as well (it [has a special meaning in math mode](https://tex.stackexchange.com/questions/203686/what-does-the-tilde-character-do-in-math-mode) anyway.)
On the other hand, the program *does* support arbitrary formulas as limits for `\sum` and `\prod`.
## Explanation
It works just like TeX! (well, sort of...)
Each subformula (starting from single characters and building up to more complex formulas) is turned into a box, with an associated width, height and depth (baseline).
Boxes of simpler formulas are combined into bigger boxes to form complex formulas, and so on.
The contents of each box are represented as a list of position/character pairs, relative to the top-left corner of the box; when boxes are combined into a bigger box, the positions are offset according to the relative positions of the smaller boxes inside the bigger one, and the lists are concatenated.
Eventually, we end up with a top-level box, which is converted to a printable form.
---
To spice it up a little, the following version also supports square roots:
```
M=max;R=range
O=lambda l,o=2:[(p+o,c)for p,c in l]
def C(s,m=0):
if''<s<'}'[m:]:f,w,h,d,s=C(s,1);F,W,H,D,s=C(s);e=M(d,D);return[O(f,e-d)+O(F,w*1j+e-D),w+W,M(h-d,H-D)+e,e,s]
if'\\'!=s[:1]:return[[(0,s[:1])]*m,m,m,0,s[1:]]
t=s[1]<'s';e=s[1]>'f';f,w,h,d,z=C(s[5+t+e:])
if'r'>s[2]:return[O(f,1j+h*1j+1)+O(C('_'*w)[0],1j+h*1j)+[(h,'\\')]+[(h-y+y*1j+1j,'/')for y in R(h)],w+1+h,h+1,d+1,z]
F,W,H,D,s=C(z[1+e:]);g=M(w,W);G=C('-'*g)[0]
if e:f,w,h,F,W,H=F,W,H,f,w,h;g=4;p=C('| |')[0];G=C('_'*(3+t))[0]+[O(C('/__,')[0])+[(1,'\\'),(1+3j,'`')],O(p,1)+O(p)][t]
x=M(w,W,g);return[O(f,(x-w)/2*1j)+O(F,(x-W)/2*1j+h+3**e)+O(G,(x-g)/2*1j+h),x,h+3**e+H,h+e,s]
f,w,h,d,s=C(raw_input())
for y in R(h):print"".join(dict(f).get(y+x*1j,' ')for x in R(w))
```
Examples:
* `\frac{-b +- \sqrt{b^2 - 4ac}}{2a}`
```
_________
-b +- \/b^2 - 4ac
-----------------
2a
```
* `|v| = \sqrt{ \sum_{i}^{} v[i]^2 }`
```
_____________
/ ___
|v| = / \ ` v[i]^2
/ /__,
\/ i
```
[Answer]
# LaTeX, 540 532 characters
Disclaimer: This is not perfect and arguably does not count as a valid answer.
```
\usepackage[LGRgreek]{mathastext}
\renewcommand{\sum}{\kern-1ex\displaystyle\mathop{\vphantom{\int}\begin{array}{l}\mbox{\underline{\hspace{12pt}}}\\ \mbox{\textbackslash}\hspace{8pt}`\\\mbox{/\underline{\hspace{8pt}},}\end{array}}\displaylimits}
\renewcommand{\prod}{\kern-1ex\displaystyle\mathop{\vphantom{\int}\begin{array}{c}\mbox{\underline{\hspace{16pt}}}\\|\ \ \ \ | \\| \ \ \ \ |\end{array}}\displaylimits}
\renewcommand{\frac}[2]{\mathop{\xleaders\hbox{-}\hfill\kern0pt}\limits^{#1}_{#2}}
\DeclareMathSizes{10}{10}{10}{10}
```
Some help from @Fatalize, see comments for details.
### Test:
**Input:** `\prod_{i=1}^{n} \frac{\sum_{j=0}^{m} 2j}{i + 1}`
**Output:**
![enter image description here](https://i.stack.imgur.com/khHFY.png)
As you can see, the output does not exactly follow the spec. This may disqualify my answer, but I still think it's worth posting.
I wrote this on sharelatex.com. You can play with it [here](https://www.sharelatex.com/project/558ecd2ae49358a12c6f5913).
] |
[Question]
[
Sometimes when I'm typing out an IPv4 address, I get all the numbers right, but I forget to type one or more periods. I'd like to have a program (or function) that takes my broken IPv4 address and outputs all possible valid placements of the missing periods.
## Input
The input will always be a string that is a transformation of a valid IPv4 address (see particulars below). It will always have been transformed solely by the elimination of one or more period characters.
You submission does not need to handle inputs outside of this format.
## Output
A collection or list, in no particular order or format, of strings representing all valid IPv4 addresses that can be created from the input by the insertion of period characters into the input.
* The output may be a language-native list or other ordered or unordered collection type.
* Alternatively, it may be a string sequence of IPv4 address delimited in some clear way.
+ If you use a single-character delimiter to delimit your string, periods and digits are not allowed as that single-character delimiter. I realize that, unlike numbers, periods as delimiters are not *ambiguous* (since every fourth period would necessarily be a delimiter) but for the sake of readability, I am disallowing it.
## IPv4 address format
While IPv4 addresses are really just a sequence of four binary octets, this challenge uses a restricted dotted decimal format.
* An IPv4 address is a four decimal values separated by three periods.
* Each of the four values are in the range `0` to `255`, inclusive.
* **Leading zeros are not allowed** in any number value. (Standalone one-character `0` is allowed; any other number beginning with a zero is not: `052`, `00`, etc.)
## Test Cases
Input is on the first line, output on second line (here, structured as a comma-separated list of quoted strings, separated by commas, surrounded by `[` `]`, but you may use any reasonable format or structure, as specified above). Some examples have notes on a third line to highlight the application of a particular rule.
```
192.168.1234
["192.168.1.234", "192.168.12.34", "192.168.123.4"]
192.1681234
["192.16.81.234", "192.168.1.234", "192.168.12.34", "192.168.123.4"]
(Note: 192.1681.2.34 (etc.) is illegal because 1681 is greater than 255)
1921681.234
["19.216.81.234", "192.16.81.234", "192.168.1.234"]
1921681234
["19.216.81.234", "192.16.81.234", "192.168.1.234", "192.168.12.34", "192.168.123.4"]
192.168.1204
["192.168.1.204", "192.168.120.4"]
(Note: 192.168.12.04 is illegal because of leading zero)
192.168.123
["1.92.168.123", "19.2.168.123", "192.1.68.123", "192.16.8.123", "192.168.1.23", "192.168.12.3"]
192.168.256
["192.168.2.56", "192.168.25.6"]
(Note: Any combination that would leave 256 intact is illegal)
120345
["1.20.3.45", "1.20.34.5", "1.203.4.5", "12.0.3.45", "12.0.34.5", "120.3.4.5"]
(Note: 12.03.4.5 (etc.) is illegal due to leading zero.)
012345
["0.1.23.45", "0.1.234.5", "0.12.3.45", "0.12.34.5", "0.123.4.5"]
(Note: the first segment must be 0, because `01` or `012` would be illegal.)
000123
["0.0.0.123"]
```
(I made these examples by hand, so please alert me to any mistakes you may find.)
[Answer]
# C (gcc/linux), 125 121 bytes
```
i;f(char*a){do{char*y=a,s[99],*x=inet_ntop(2,&i,s,99);for(;*x&&!(*x^*y&&*x^46);++x)y+=*x==*y;*x|*y||puts(s);}while(++i);}
```
Loops over **all** possible IPv4 addresses, and does a custom comparison that skips over extra dots in the generated ip address (but not in the main comparison address) to decide whether to print or not. **Very slow, but should finish within 1 hour on a reasonable PC**.
[Answer]
# Pyth, 24 bytes
```
f&q4lJcT\.!-J`M256jL\../
```
[Try it online](https://pyth.herokuapp.com/?code=f%26q4lJcT%5C.%21-J%60M256jL%5C..%2F&test_suite=1&test_suite_input=%22192.168.1234%22%0A%22192.1681234%22%0A%221921681.234%22%0A%221921681234%22%0A%22192.168.1204%22%0A%22192.168.123%22%0A%22192.168.256%22%0A%22120345%22%0A%22012345%22%0A%22000123%22&debug=0)
### How it works
```
./Q all partitions of input
jL\. join each on .
f filter for results T such that:
cT\. split T on .
J assign to J
l length
q4 equals 4
& … and:
-J`M256 J minus the list of representations of [0, …, 255]
! is false (empty)
```
# Pyth, 17 bytes, very slow
```
@FjLL\.,^U256 4./
```
**Warning. Do not run.** Requires approximately 553 GiB of RAM.
### How it works
```
, two-element list of:
^U256 4 all four-element lists of [0, …, 255]
./Q all partitions of input
jLL\. join each element of both on .
@F fold intersection
```
[Answer]
# Perl 5, 91 bytes
```
<>=~/^(([1-9]?|1\d|2[0-4])\d|25[0-5])\.?((?1))\.?((?1))\.?((?1))$(?{print"$1.$3.$4.$5 "})^/
```
The program expects a single line of a single input and outputs space-delimited list of candidates.
### Explanation
The program exploits the backtracking feature of regex to loop over all possibilities of forming a valid IPv4 address from the input string.
```
^(([1-9]?|1\d|2[0-4])\d|25[0-5])\.?((?1))\.?((?1))\.?((?1))$
```
The IPv4 regex with optional `.`, nothing of note here.
```
(?{print"$1.$3.$4.$5 "})
```
A code evaluation expression which prints out the content of the capturing groups.
```
^
```
Make the match fails and force backtracking.
### Example run
```
$ echo "012345" | perl G89503.pl
0.12.34.5 0.12.3.45 0.1.23.45 0.1.234.5 0.123.4.5
```
[Answer]
## JavaScript (ES6), ~~147~~ ~~141~~ 135 bytes
```
f=(s,n=0)=>(a=s.split`.`)[3]?a.every(s=>s==`0`|s[0]>0&s<256)?s+' ':'':[...s].map((_,i)=>i>n?f(s.slice(0,i)+`.`+s.slice(i),i):``).join``
```
```
<input placeholder=Input oninput=o.textContent=f(this.value)><div id=o style=font-family:monospace;width:1em>Output
```
Edit: saved 6 bytes thanks to @apsillers. Saved another 6 bytes by copying @YOU's validity test.
[Answer]
# Python 3, 232 bytes
```
import re,itertools as t,ipaddress as k
R=range
i=input()
for d in R(5):
for p in t.combinations(R(len(i)),d):
n=i;o=0
for a in p:n=n[:a+o]+'.'+n[a+o:];o+=1
try:k.ip_address(n);print(n*(not re.search(r'\D?0\d',n)))
except:0
```
Pretty simple: We place periods everywhere and print if the IP address with the periods placed is valid. We check the validity of the IP adresses by (ab)using `ipaddress.ip_address`, which raises an exception if the input is not a valid IP address. The challenge defines some additional rules that `ip_address` doesn't handle (namely, that there can be no leading zeroes), so we check for those too with a regular expression, then print.
Outputs each solution on a new line, mixed with an arbitrary number of blank lines.
Example run:
```
$ echo 012345 | python fixip.py
0.1.23.45
0.1.234.5
0.12.3.45
0.12.34.5
0.123.4.5
$ echo 000123 | python fixip.py
0.0.0.123
_
```
Here's my older, 248-byte Python 2 solution. The second and third indent levels are `\t` (raw tab) and `\t` (raw tab plus space) respectively. This plays *really* badly with Markdown, so the tabs have been replaced by two spaces.
```
import socket,re,itertools as t
R=range
i=input()
for d in R(5):
for p in t.combinations(R(len(i)),d):
n=i;o=0
for a in p:n=n[:a+o]+'.'+n[a+o:];o+=1
try:
socket.inet_aton(n)
if n.count('.')==3and not re.search(r'\D?0\d',n):print n
except:0
```
Requires the input surrounded with quotes (e.g. `"123.456.789"`). Outputs each generated IP address on a new line.
*Saved 9 bytes thanks to @grawity!*
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 110 bytes
```
:ef:{".",@N.|.}ac:3f:{@n:"."rz:cacb.}a.
,4yeN,?:N:6i.@nMl4,M:{:7&<256}a
~c[A:B]h:@N:Bc.
:ef:{,"0":"9"y:.m?}ac.
```
[Try it online!](http://brachylog.tryitonline.net/#code=OmVmOnsiLiIsQE4ufC59YWM6M2Y6e0BuOiIuInJ6OmNhY2IufWEuCiw0eWVOLD86Tjo1aS5Abk1sNCxNOns6NiY8MjU2fWEKfmNbQTpCXWg6QE46QmMuCjplZjp7LCIwIjoiOSJ5Oi5tP31hYy4&input=IjAxMjMuNDUi&args=Wg&debug=on)
[Answer]
# Python 3, ~~262~~ 260 bytes
```
p,l,L,T=set(),-1,len,tuple
while l<L(p):l=L(p);p|={T(z[:i]+(y[:j],y[j:])+z[i+1:])for z in set(p)or[T(input().split("."))]for i,y in enumerate(z)for j in range(1,L(y))}
print(['.'.join(x)for x in p if L(x)==4and all(y=='0'or y[0]!='0'and int(y)<256for y in x)])
```
No libraries used, but late and longer, may be I am missing some obvious golfing techniques.
Results anyway.
```
for x in 192.168.1234 192.1681234 1921681.234 1921681234 192.168.1204 192.168.123 192.168.256 120345 012345 000123; do
echo $x | python3 ipv4.py
done;
['192.168.123.4', '192.168.1.234', '192.168.12.34']
['192.16.81.234', '192.168.1.234', '192.168.123.4', '192.168.12.34']
['19.216.81.234', '192.168.1.234', '192.16.81.234']
['19.216.81.234', '192.168.123.4', '192.168.12.34', '192.16.81.234', '192.168.1.234']
['192.168.1.204', '192.168.120.4']
['192.16.8.123', '19.2.168.123', '1.92.168.123', '192.168.1.23', '192.168.12.3', '192.1.68.123']
['192.168.25.6', '192.168.2.56']
['1.20.3.45', '1.203.4.5', '12.0.34.5', '120.3.4.5', '1.20.34.5', '12.0.3.45']
['0.1.23.45', '0.12.3.45', '0.12.34.5', '0.123.4.5', '0.1.234.5']
['0.0.0.123']
```
] |
[Question]
[
*Prindeal* (pronounced [prin-dee-al](http://www.pronunciationgenerator.com/v/1mJVa/prindeal.mp4)) is a new [esoteric](http://esolangs.org/wiki/esoteric_programming_language) programming language that only has four commands: ***pr***int, ***in***crement, ***de***crement, and ***al***ias. Despite its minimalism, complex mathematical operations can be done in Prindeal by cleverly combining the four commands.
Your task in this [code golf](https://codegolf.stackexchange.com/tags/code-golf/info) challenge is to write the shortest program that can run Prindeal code.
The spec is long but I've tried to make it as clear as possible and I believe that if you make the effort to learn Prindeal you'll find it to be quite elegant!
---
# Intrepreting Prindeal
## Preprocessing
Before a Prindeal program can be interpreted these things need to be removed from it in this order:
1. Anything after a `#` sign to the end of the line it's on, plus the `#` itself. (These are comments.)
2. Trailing whitespace on any line.
3. Completely empty lines.
For example, the Prindeal program
```
p cat #The next line has 7 trailing spaces.
p dog
#p mouse
```
would be preprocessed into
```
p cat
p dog
```
From here on we'll assume this preprocessing step has been done.
## Variables
We quickly need to define variables before showing how they are used.
Variables (and references to variables) are what are passed into the arguments of Prindeal commands. **Variables are always global**, so modifications to a variable, no matter where they occur, are reflected everywhere.
Each variable holds a **non-negative [arbitrary-precision](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) integer** (0, 1, 2, 3, ...). Variables do not need to be pre-initialized - **they always start with the value 0** the first time they are used or called for.
A variable name may be any non-empty string of alphanumerics and underscores that does not start with a digit - `[a-zA-Z_][0-9a-zA-Z_]*` in [regex](https://en.wikipedia.org/wiki/Regular_expression). They are case sensitive, so `spiny_lumpsuck3r` and `Spiny_lumpsuck3r` are different variables.
## Execution
Prindeal is an [imperative](https://en.wikipedia.org/wiki/Imperative_programming) programming language. When a Prindeal program is run its [statements](https://en.wikipedia.org/wiki/Statement_(computer_science)) are executed from top to bottom in order and then the program ends.
Every **non-indented** line in a Prindeal program is a statement that involves the execution of a single command which may or may not take arguments.
Indented lines only occur after *alias* commands. Specifically, exactly **three lines indented with single spaces occur after every *alias* command** and are considered a part of it. So *alias* statements are really four lines long. (They could be one line, four is merely more readable.)
### Non-*alias* Statements
With the exception of *alias*, every statement in a Prindeal program has the form:
```
[command name] [argument 1] [argument 2] [argument 3] ...
```
There may be an arbitrary number of arguments (including none at all). Each argument is always a **variable** or (as we'll see when discussing *alias*) a **reference to a variable**.
Once done executing, **each statement is flagged as either a *failure* or *success*** depending on if errors were encountered or not. (This only really matters when we get around to using *alias*.)
The built-ins *print*, *increment*, and *decrement* are statements with the above form. Here is what they do:
1. *print* has command name `p` and takes one argument. It prints the name of the variable passed in and its value (in decimal) separated by " = ", then a newline. It is always flagged as a *success*.
For example, the Prindeal program
```
p _MyVariable_321
p screaming_hairy_armadillo
```
would output
```
_MyVariable_321 = 0
screaming_hairy_armadillo = 0
```
because all variables start at 0. (The spaces before and after the equals sign are required.)
2. *increment* has command name `i` and takes one argument. It increments the value of the variable passed in by 1. It is always flagged as a *success*..
For example, the program
```
i alpaca
p alpaca
i alpaca
p alpaca
```
would output
```
alpaca = 1
alpaca = 2
```
Note how `alpaca` was incremented from 0 to 1 even though it had never been accessed before.
3. *decrement* has command name `d` and takes one argument. If the variable passed in is nonzero its value is decremented by 1 and the statement is flagged as a *success*. If the variable passed in is 0 then nothing is done and the statement is flagged as a *failure*.
For example, the program
```
i malamute
p malamute
d malamute #success
p malamute
d malamute #failure
p malamute
d akita #failure
p akita
```
would output
```
malamute = 1
malamute = 0
malamute = 0
akita = 0
```
Notice that decrementing a variable with value 0 is the only way to produce a *failure*.
### The *alias* Statement and Aliased Commands
The *alias* command has a special syntax and is the most powerful because it can be used to define new commands. The *alias* command name is `a` and an *alias* statement has the form:
```
a [name of new command]
[statement A]
[statement B]
[statement C]
```
Where each `[statement X]` represents any non-*alias* statement, i.e. something with the form `[command name] [argument 1] [argument 2] [argument 3] ...`.
The aliased command's name `[name of new command]` may be any non-empty string of alphanumerics and underscores that does not start with a digit - `[a-zA-Z_][0-9a-zA-Z_]*` in regex.
(This is the same set of names as variables but aliased **commands and variables are different things used in different places**. A variable could be named the same as a command with no ill consequences.)
When an *alias* statement is executed, a new command is added alongside the original four `p` `i` `d` `a` commands. The new command can be used as the `[command name]` in statements and called with arguments just like any other non-*alias* command.
When a statement with an aliased command name is executed, exactly **two more statements from its original *alias* statement are run:**
* `[statement A]` is always run
* `[statement B]` is run if `[statement A]` was a *success*
* `[statement C]` is run if `[statement A]` was a *failure*
Statements A, B, and C are **always run [lazily](https://en.wikipedia.org/wiki/Lazy_evaluation)**, i.e. they are evaluated on the fly at the time they are run.
When done executing, **the aliased command is flagged with the same *success* or *failure* flag as statement B or C, whichever one was executed**. (*alias* statements themselves do not need to be flagged since they cannot occur within themselves.)
>
> **Alias Example 1**
>
>
> Say we want a new command that increments the variable `frog` twice. This alias statement achieves it:
>
>
>
> ```
> a increment_frog_twice
> i frog
> i frog
> d frog
>
> ```
>
> Statement A (`i frog`) is always run and always flagged as a *success*
> so statement B (`i frog`) is also always run and the variable `frog`
> is thus incremented by 2. The `increment_frog_twice` command is always
> flagged as a *success* because statement B is always run and B is
> always a *success*. Statement C (`d frog`) is never run.
>
>
> So the output to
>
>
>
> ```
> a increment_frog_twice
> i frog
> i frog
> d frog
> p frog
> increment_frog_twice
> p frog
>
> ```
>
> would be
>
>
>
> ```
> frog = 0
> frog = 2
>
> ```
>
>
We can generalize this example so that *any* variable can be incremented twice by giving the aliased command an argument.
**Within an *alias* statement the positive integers 1, 2, 3, etc. represent the 1st, 2nd, 3rd, etc. arguments passed into the aliased command.** (These arguments might be plain variables or references to variables themselves.) These numbers can only appear within the arguments of statement A, B, and C in an *alias* statement. It doesn't make sense for them to appear elsewhere.
>
> **Alias Example 2**
>
>
> This generalizes the last example - any variable passed into `increment_twice` will be incremented by 2 because `1` is a reference to the first argument passed in:
>
>
>
> ```
> a increment_twice
> i 1
> i 1
> d 1 #never reached
> p toad
> increment_twice toad
> p toad
>
> ```
>
> The output of this program would be
>
>
>
> ```
> toad = 0
> toad = 2
>
> ```
>
> We could then alias another command that takes in two arguments and calls `increment_twice` on both of them:
>
>
>
> ```
> a increment_twice
> i 1
> i 1
> d 1 #never reached
> a increment_both_twice
> increment_twice 1
> increment_twice 2
> d 1 #never reached
> increment_both_twice platypus duck
> p platypus
> p duck
>
> ```
>
> The output here would be
>
>
>
> ```
> platypus = 2
> duck = 2
>
> ```
>
>
It's important to realize that aliased commands can be recursive, as this is where their true power lies. For example, we can make a command that sets any variable passed in to 0:
>
> **Alias Example 3**
>
>
> The `set_to_zero` command takes one argument and sets its variable to 0 and is flagged as a *success* when done:
>
>
>
> ```
> a set_to_zero
> d 1
> set_to_zero 1
> i _dummy_
> i oryx
> i oryx
> i oryx
> p oryx
> set_to_zero oryx
> p oryx
>
> ```
>
> The output of this program would be
>
>
>
> ```
> oryx = 3
> oryx = 0
>
> ```
>
> What's happening is that when `set_to_zero oryx` is run, `d 1` successfully decrements `oryx` from from 3 to 2, then `set_to_zero 1` is called, which is the same as calling `set_to_zero oryx` again. So the process repeats until `d 1` is a *failure*, stopping the recursion and increment the `_dummy_` variable so a *success* is produced.
>
>
>
---
# Challenge
Write a program that can execute Prindeal code exactly as described above. Take the Prindeal code in via stdin, the command line, or as a text file. Print the Prindeal program's output to stdout or your language's closest alternative.
Alternatively, you can write a function that takes in the code as a string and prints or returns the output string.
Additionally, you can assume that:
* The input Prindeal code will only contain newlines and [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) and (optionally) that it ends with an empty line.
* The input code will be valid Prindeal - well formed and syntactically correct.
* Running the code will not produce any infinite loops nor any invalid references to commands that have not been defined or arguments that have not been given.
* The command names `p`, `i`, `d`, and `a` will never be aliased over. (You may ***not*** assume that variables will not have these names.)
Also, it doesn't matter if your variable values aren't truly arbitrary-precision integers as only numbers less than about 1000 will be tested. It's also alright if you language has recursion limits (such as [Python](https://docs.python.org/2/library/sys.html#sys.setrecursionlimit)) that more complex Prindeal programs might encounter as long as the test program below works.
# Test Program
Here is a large Prindeal program that builds up the operations of addition, multiplication, and exponentiation through the use of dummy variables (starting with `_` by convention) and many helper aliases:
```
#Command Definitions:
a s #flag as a success
i _
d _
d _
a f #flag as a failure
d _
d _
d _
a z #1 = zero
d 1
z 1
s
a n #1 = one
z 1
i 1
s
a move #2 += 1, 1 = zero
moveH 1 2
move 1 2
s
a moveH #move helper
d 1
i 2
f
a dupe #2 += 1, 3 += 1, 1 = zero
dupeH1 1 2 3
dupe 1 2 3
s
a dupeH1 #dupe helper
d 1
dupeH2 2 3
f
a dupeH2 #dupe helper
i 1
i 2
s
a copy #2 = 1
z 2
copyH 1 2
s
a copyH #copy helper
dupe 1 2 _copy
move _copy 1
s
a addTo #1 += 2
copy 2 _add
#testing comments #
move _add 1#in weird places # just because #
s
#it's a g##d idea
###
a add #1 = 2 + 3
#its a good idea
z 1
addH 1 2 3
s
##
#
a addH #add helper
#this is a comment
addTo 1 2 #as is this
addTo 1 3
s
a mul #1 = 2 * 3
mulH1 1 2
mulH2 1 3
s
a mulH1 #mul helper
z 1
copy 2 _mul
s
a mulH2 #mul helper
mulH3 1 2
mulH2 1 2
s
a mulH3 #mul helper
d _mul
addTo 1 2
f
a mulBy #1 *= 2
mul _mulBy 1 2
copy _mulBy 1
s
a pow #1 = 2^3
powH1 1 3
powH2 1 2
s
a powH1 #pow helper
n 1
copy 2 _pow
s
a powH2 #pow helper
powH3 1 2
powH2 1 2
s
a powH3 #pow helper
d _pow
mulBy 1 2
f
#Running Tests:
p A
p B
p C
n A #A = 1
n B #B = 1
add C A B #C = A + B = 1 + 1 = 2
p ____
p A
p B
p C
add B A C #B = A + C = 1 + 2 = 3
p ____
p A
p B
p C
mul d B C #d = B * C = 3 * 2 = 6
p ____
p d
mulBy d B #d = d * B = 6 * 3 = 18
p ____
p d
d A #A = A - 1 = 1 - 1 = 0
mulBy d A #d = d * A = 18 * 0 = 0
p ____
p d
pow A C B #A = C ^ B = 2 ^ 3 = 8
p ____
p A
p B
p C
pow A B C #A = B ^ C = 3 ^ 2 = 9
p ____
p A
p B
p C
pow C A B #C = A ^ B = 9 ^ 3 = 729
p ____
p A
p B
p C
```
(If you're playing around with this code be aware that many of the commands will fail if the same variable is given multiple times as an argument. This can easily be fixed but the resulting code is longer.)
Your Prindeal interpreter should be able to produce the exact output:
```
A = 0
B = 0
C = 0
____ = 0
A = 1
B = 1
C = 2
____ = 0
A = 1
B = 3
C = 2
____ = 0
d = 6
____ = 0
d = 18
____ = 0
d = 0
____ = 0
A = 8
B = 3
C = 2
____ = 0
A = 9
B = 3
C = 2
____ = 0
A = 9
B = 3
C = 729
```
# Scoring
The shortest code in bytes wins. Tiebreaker goes to earlier submission.
*Brownie Bonus: Write a cool program in Prindeal. I implemented addition and multiplication, can you do subtraction or division?*
[Answer]
# Pyth, ~~162~~ 136 bytes
```
JfTmchcd\#).zKHW<ZlJI!e=T@J~+Z1=@Tk)=k0 .x=J+]h=Nm.xL@Tskd@K=NhT+]+tN0>J~Z0,=Y.x@H=eT0?qN\pps[Td\=dYb)?xGN?qN\iXHThY?YXTH_1=k1XKT:JZ=+Z3
```
[Demonstration.](https://pyth.herokuapp.com/?code=JfTmchcd%5C%23).zKHW%3CZlJ%3DG%40JZI!eG%3D%40GT)%3DT0%3DNhGI.x%7DNK0%3Dkm.xL%40Gskd%40KN%3DJ%2B%5Dhk%2B%5D%2Btk0%3EJhZ%3DZ0)E%3DeG%3DY.x%40HG0%3D%2BZ1IqN%5Ca%20XKG%3AJZ%2BZ3%3D%2BZ3)IqN%5Cpjd%5BG%5C%3DY))IqN%5Ci%20XHGhY)IqN%5CdIY%20XGH_1)E%3DT1&input=%23Command%20Definitions%3A%0Aa%20s%20%20%20%20%20%20%20%20%20%20%20%20%20%23flag%20as%20a%20success%0A%20i%20_%0A%20d%20_%0A%20d%20_%0Aa%20f%20%20%20%20%20%20%20%20%20%20%20%20%20%23flag%20as%20a%20failure%0A%20d%20_%0A%20d%20_%0A%20d%20_%0Aa%20z%20%20%20%20%20%20%20%20%20%20%20%20%20%231%20%3D%20zero%0A%20d%201%0A%20z%201%0A%20s%0Aa%20n%20%20%20%20%20%20%20%20%20%20%20%20%20%231%20%3D%20one%0A%20z%201%0A%20i%201%0A%20s%0Aa%20move%20%20%20%20%20%20%20%20%20%20%232%20%2B%3D%201%2C%201%20%3D%20zero%0A%20moveH%201%202%0A%20move%201%202%0A%20s%0Aa%20moveH%20%20%20%20%20%20%20%20%20%23move%20helper%0A%20d%201%0A%20i%202%0A%20f%0Aa%20dupe%20%20%20%20%20%20%20%20%20%20%232%20%2B%3D%201%2C%203%20%2B%3D%201%2C%201%20%3D%20zero%0A%20dupeH1%201%202%203%0A%20dupe%201%202%203%0A%20s%0Aa%20dupeH1%20%20%20%20%20%20%20%20%23dupe%20helper%0A%20d%201%0A%20dupeH2%202%203%0A%20f%0Aa%20dupeH2%20%20%20%20%20%20%20%20%23dupe%20helper%0A%20i%201%0A%20i%202%0A%20s%0Aa%20copy%20%20%20%20%20%20%20%20%20%20%232%20%3D%201%0A%20z%202%0A%20copyH%201%202%0A%20s%0Aa%20copyH%20%20%20%20%20%20%20%20%20%23copy%20helper%0A%20dupe%201%202%20_copy%0A%20move%20_copy%201%0A%20s%0Aa%20addTo%20%20%20%20%20%20%20%20%20%231%20%2B%3D%202%0A%20copy%202%20_add%0A%20move%20_add%201%0A%20s%0Aa%20add%20%20%20%20%20%20%20%20%20%20%20%231%20%3D%202%20%2B%203%0A%20z%201%0A%20addH%201%202%203%0A%20s%0Aa%20addH%20%20%20%20%20%20%20%20%20%20%23add%20helper%0A%20addTo%201%202%0A%20addTo%201%203%0A%20s%0Aa%20mul%20%20%20%20%20%20%20%20%20%20%20%231%20%3D%202%20*%203%0A%20mulH1%201%202%0A%20mulH2%201%203%0A%20s%0Aa%20mulH1%20%20%20%20%20%20%20%20%20%23mul%20helper%0A%20z%201%0A%20copy%202%20_mul%0A%20s%0Aa%20mulH2%20%20%20%20%20%20%20%20%20%23mul%20helper%0A%20mulH3%201%202%0A%20mulH2%201%202%0A%20s%0Aa%20mulH3%20%20%20%20%20%20%20%20%20%23mul%20helper%0A%20d%20_mul%0A%20addTo%201%202%0A%20f%0Aa%20mulBy%20%20%20%20%20%20%20%20%20%231%20*%3D%202%0A%20mul%20_mulBy%201%202%0A%20copy%20_mulBy%201%0A%20s%0Aa%20pow%20%20%20%20%20%20%20%20%20%20%20%231%20%3D%202%5E3%0A%20powH1%201%203%0A%20powH2%201%202%0A%20s%0Aa%20powH1%20%20%20%20%20%20%20%20%20%23pow%20helper%0A%20n%201%0A%20copy%202%20_pow%0A%20s%0Aa%20powH2%20%20%20%20%20%20%20%20%20%23pow%20helper%0A%20powH3%201%202%0A%20powH2%201%202%0A%20s%0Aa%20powH3%20%20%20%20%20%20%20%20%20%23pow%20helper%0A%20d%20_pow%0A%20mulBy%201%202%0A%20f%0A%0A%23Running%20Tests%3A%0Ap%20A%0Ap%20B%0Ap%20C%0An%20A%20%20%20%20%20%20%20%20%20%23A%20%3D%201%0An%20B%20%20%20%20%20%20%20%20%20%23B%20%3D%201%0Aadd%20C%20A%20B%20%20%20%23C%20%3D%20A%20%2B%20B%20%3D%201%20%2B%201%20%3D%202%0Ap%20____%0Ap%20A%0Ap%20B%0Ap%20C%0Aadd%20B%20A%20C%20%20%20%23B%20%3D%20A%20%2B%20C%20%3D%201%20%2B%202%20%3D%203%0Ap%20____%0Ap%20A%0Ap%20B%0Ap%20C%0Amul%20d%20B%20C%20%20%20%23d%20%3D%20B%20*%20C%20%3D%203%20*%202%20%3D%206%0Ap%20____%0Ap%20d%0AmulBy%20d%20B%20%20%20%23d%20%3D%20d%20*%20B%20%3D%206%20*%203%20%3D%2018%0Ap%20____%0Ap%20d%0Ad%20A%20%20%20%20%20%20%20%20%20%23A%20%3D%20A%20-%201%20%3D%201%20-%201%20%3D%200%0AmulBy%20d%20A%20%20%20%23d%20%3D%20d%20*%20A%20%3D%2018%20*%200%20%3D%200%0Ap%20____%0Ap%20d%0Apow%20A%20C%20B%20%20%20%23A%20%3D%20C%20%5E%20B%20%3D%202%20%5E%203%20%3D%208%0Ap%20____%0Ap%20A%0Ap%20B%0Ap%20C%0Apow%20A%20B%20C%20%20%20%23A%20%3D%20B%20%5E%20C%20%3D%203%20%5E%202%20%3D%209%0Ap%20____%0Ap%20A%0Ap%20B%0Ap%20C%0Apow%20C%20A%20B%20%20%20%23C%20%3D%20A%20%5E%20B%20%3D%209%20%5E%203%20%3D%20729%0Ap%20____%0Ap%20A%0Ap%20B%0Ap%20C&debug=0)
Golfed out 26 characters by inlining variables and changing from `I` and `E` based control flow to `?` and `.x` based control flow.
For the first time ever, I ran out of variables in Pyth. Every single variable in Pyth (`bdkGHNTY` and `JK`) was in use, and I wanted to use `b` as a newline. Fortunaely, I was able to use `N` to mean two completely different things in different parts of the program, and so it still works.
### Ungolfed (run with -m):
```
JfTmchcd\#).z
KH
W<ZlJ
I!e=T@J~+Z1
=@Tk)
=k0
.x
=J+]h=Nm.xL@Tskd@K=NhT+]+tN0>J~Z0
,
=Y.x@H=eT0
?qN\p
ps[Td\=dYb)
?xGN
?qN\i
XHThY
?Y
XTH_1
=k1
XKT:JZ=+Z3
```
[Answer]
# Python 2, ~~600~~ ~~584~~ ~~397~~ 373 bytes
This is my own golfed reference solution. Anyone is welcome to improve it or follow its logic in their own answer as long as attribution is given.
The neat part about it is that no recursion is done, so it will never have problems with Python's recursion limit. For example, [Sp's](https://codegolf.stackexchange.com/a/54559/26997) Countup Prindeal program can run indefinitely.
```
p=filter(len,[l.split('#')[0].split()for l in input().split('\n')]);m={};v={};i=0
while i<len(p):
s=p[i]
if'('in`s`:s=s[f]
n,f=s[0],0
if n in m:a,b,c=([s[int(g)]if g.isdigit()else g for g in t]for t in m[n]);p=[a,(b,c)]+p[i+1:];i=0;continue
s=s[1]
q=v.get(s,0)
if'd'>n:m[s]=p[i+1:i+4];i+=3
elif'i'<n:print s,'=',q
elif'd'<n:v[s]=q+1
elif q:v[s]-=1
else:f=1
i+=1
```
It's a program that takes in the quoted program string with newlines escaped, e.g.
`'p _MyVariable_321\np screaming_hairy_armadillo'`.
I took various golfing cues from [Sp's](https://codegolf.stackexchange.com/a/54559/26997) and [Pietu's](https://codegolf.stackexchange.com/a/54547/26997) answers. Thanks guys :)
[Answer]
# Python 3, ~~345~~ ~~336~~ ~~335~~ 328 bytes
```
a=0
A={}
V={}
def f(l):
if l[0]in"d p i":c,u=l;U=V[u]=V.get(u,0)+"pi".find(c);S=U<0;V[u]+=S;c<"p"or print(u,"=",U)
else:d=lambda q:[w.isdigit()and l[int(w)]or w for w in A[l[0]][q]];S=f(d(1+f(d(0))))
return S
for z in open("P"):
l=z.split("#")[0].split()
if"a "==z[:2]:a,s,*x=3,l[1]
elif l*a:x+=l,;a-=1;A[s]=x
elif l:f(l)
```
*(-6 bytes thanks to @orlp)*
Still golfing. Assumes the program is stored in a file named `P`.
Putting the calls to `f` inside the lambda `d` would save a few bytes, but it would make the last test case hit max recursion depth.
## Some Prindeal programs
### The useless subtraction program
Here is [a useless subtraction program](http://pastebin.com/8u4hXDdd). It's useless because, even though it subtracts properly, it doesn't return success/failure accordingly.
The output should be:
```
a = 15
b = 6
__________ = 0
a = 9
b = 6
```
### Countup
```
a helper
p 1
countup 1
i success
a countup
i 1
helper 1
d failure
countup n
```
Counts upwards and prints `n` forever. Could possibly work as a test for interpreter speed (beware the long tracebacks on keyboard interrupt).
[Answer]
# JavaScript (ES6), 273 ~~258~~
**Edit** Fixed bugs and added a real test suite.
Not counting leading spaces and newlines.
Surely can be golfed a little more.
Too tired to write an explanation now, I think it's a good example of using closures to keep alive temporary values (parameters).
Test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go)
```
F=p=>(
p=p.match(/^[^#\n]+/gm).filter(r=>r.trim(o='',v=[])),
s={
'':_=>1,
p:a=>o+=a+` = ${v[a]||0}\n`,
i:a=>v[a]=-~v[a],
d:a=>v[a]&&v[a]--,
a:(n,j)=>s[n]=(u,t,a)=>x(p[!x(p[j+1],0,a,1)+j+2],0,a,1)
},
p.map(x=(r,i,w,l,a=r.split(/ +/).slice(l).map(x=>-x?w[x]:x))=>s[a[0]](a[1],i,a)),
o
)
// TEST
$('#O tr').each(function() {
var $cells = $(this).find('td')
var prg = $cells.eq(0).text()
console.log(prg)
var output = F(prg)
$cells.eq(1).text(output)
})
```
```
#O td { vertical-align:top; white-space: pre; border: 1px solid #888; font-family:monospace }
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr><th>Program</th><th>Outpout</th></tr>
<tbody id=O>
<tr><td>p _MyVariable_321
p screaming_hairy_armadillo</td><td></td></tr>
<tr><td>i alpaca
p alpaca
i alpaca
p alpaca</td><td></td></tr>
<tr><td>i malamute
p malamute
d malamute #success
p malamute
d malamute #failure
p malamute
d akita #failure
p akita</td><td></td></tr>
<tr><td>a increment_frog_twice
i frog
i frog
d frog
p frog
increment_frog_twice
p frog</td><td></td></tr>
<tr><td>a increment_twice
i 1
i 1
d 1 #never reached
a increment_both_twice
increment_twice 1
increment_twice 2
d 1 #never reached
increment_both_twice platypus duck
p platypus
p duck</td><td></td></tr>
<tr><td>a set_to_zero
d 1
set_to_zero 1
i _dummy_
i oryx
i oryx
i oryx
p oryx
set_to_zero oryx
p oryx</td><td></td></tr>
<tr><td>#Command Definitions:
a s #flag as a success
i _
d _
d _
a f #flag as a failure
d _
d _
d _
a z #1 = zero
d 1
z 1
s
a n #1 = one
z 1
i 1
s
a move #2 += 1, 1 = zero
moveH 1 2
move 1 2
s
a moveH #move helper
d 1
i 2
f
a dupe #2 += 1, 3 += 1, 1 = zero
dupeH1 1 2 3
dupe 1 2 3
s
a dupeH1 #dupe helper
d 1
dupeH2 2 3
f
a dupeH2 #dupe helper
i 1
i 2
s
a copy #2 = 1
z 2
copyH 1 2
s
a copyH #copy helper
dupe 1 2 _copy
move _copy 1
s
a addTo #1 += 2
copy 2 _add
#testing comments #
move _add 1#in weird places # just because #
s
#it's a g##d idea
###
a add #1 = 2 + 3
#its a good idea
z 1
addH 1 2 3
s
##
#
a addH #add helper
#this is a comment
addTo 1 2 #as is this
addTo 1 3
s
a mul #1 = 2 * 3
mulH1 1 2
mulH2 1 3
s
a mulH1 #mul helper
z 1
copy 2 _mul
s
a mulH2 #mul helper
mulH3 1 2
mulH2 1 2
s
a mulH3 #mul helper
d _mul
addTo 1 2
f
a mulBy #1 *= 2
mul _mulBy 1 2
copy _mulBy 1
s
a pow #1 = 2^3
powH1 1 3
powH2 1 2
s
a powH1 #pow helper
n 1
copy 2 _pow
s
a powH2 #pow helper
powH3 1 2
powH2 1 2
s
a powH3 #pow helper
d _pow
mulBy 1 2
f
#Running Tests:
p A
p B
p C
n A #A = 1
n B #B = 1
add C A B #C = A + B = 1 + 1 = 2
p ____
p A
p B
p C
add B A C #B = A + C = 1 + 2 = 3
p ____
p A
p B
p C
mul d B C #d = B * C = 3 * 2 = 6
p ____
p d
mulBy d B #d = d * B = 6 * 3 = 18
p ____
p d
d A #A = A - 1 = 1 - 1 = 0
mulBy d A #d = d * A = 18 * 0 = 0
p ____
p d
pow A C B #A = C ^ B = 2 ^ 3 = 8
p ____
p A
p B
p C
pow A B C #A = B ^ C = 3 ^ 2 = 9
p ____
p A
p B
p C
pow C A B #C = A ^ B = 9 ^ 3 = 729
p ____
p A
p B
p C
</td><td></td></tr>
</tbody>
</table>
```
[Answer]
# C#6, 653 bytes
Here's my entry, amidst a sea of Python...
```
class P{string[]l;string r="";Dictionary<string,int>v=new Dictionary<string,int>();Dictionary<string,int>s=new Dictionary<string,int>();public string R(string t){l=t.Split('\n');for(int i=0;i<l.Length;i++){var z=l[i].Split(' ');if(z[0]=="a"){s.Add(z[1],i);i+=3;}else E(i, null);}return r;}bool E(int n,string[]p){var z=l[n].Split(' ');var a=z.Skip(1).Select(x=>Char.IsDigit(x[0])?p[int.Parse(x)-1]:x).ToArray();if(a.Length>0&&!v.ContainsKey(a[0]))v[a[0]]=0;if (z[0]=="p")r+=$"{a[0]} = {v[a[0]]}\n";else if(z[0]=="i")v[a[0]]++;else if(z[0]=="d")if(v[a[0]]>0)v[a[0]]--;else return false;else{var y=s[z[0]];return E(y+1,a)?E(y+2,a):E(y+3,a);}return true;}}
```
Expanded and commented:
```
class Prindeal
{
string[] lines;
string result = "";
Dictionary<string, int> variables = new Dictionary<string, int>();
Dictionary<string, int> statements = new Dictionary<string, int>();
public string Run(string text)
{
lines = text.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
// Split on spaces to get the statement and any arguments
var z = lines[i].Split(' ');
// Are we defining a new statement?
if (z[0] == "a")
{
// Add to the statements dictionary, step over definition statements
statements.Add(z[1], i);
i += 3;
}
else
{
// Execute the statement
Execute(i, null);
}
}
return result;
}
bool Execute(int lineNumber, string[] parameters)
{
// Split on spaces to get the statement and any arguments
var z = lines[lineNumber].Split(' ');
// Parse the arguments - if it's a number, get the corresponding
// parameter from the calling statement
var arguments = z.Skip(1).Select(
x => Char.IsDigit(x[0]) ?
parameters[int.Parse(x) - 1] :
x)
.ToArray();
// If the first argument isn't already in the variables dict, add it
if (arguments.Length > 0 && !variables.ContainsKey(arguments[0])) variables[arguments[0]] = 0;
// Print statement, using string interpolation
if (z[0] == "p")
result += $"{arguments[0]} = {variables[arguments[0]]}\n";
// Increment statement
else if (z[0] == "i")
variables[arguments[0]]++;
// Decrement statement
else if (z[0] == "d")
if (variables[arguments[0]] > 0)
variables[arguments[0]]--;
else
return false;
else
{
// Get the line number to jump to
var y = statements[z[0]];
// Execute A ? B : C
return Execute(y + 1, arguments) ? Execute(y + 2, arguments) : Execute(y + 3, arguments);
}
// If we reach this point, it's from a 'p', 'i' or 'd' statement which has succeeded
return true;
}
}
```
To use it, simply instantiate the class and call the `R()` method, for example:
```
string prindealText = new StreamReader("prindeal.txt").ReadToEnd();
Console.WriteLine(new P().R(prindealText));
```
[Answer]
# Common Lisp, ~~758~~ ~~646~~ 619
```
(progn(set-macro-character #\#(get-macro-character #\;))(setf(readtable-case *readtable*):invert)(#3=defun v(s)(if(boundp s)(eval s)0))(#3# i(s)(set s(1+ (v s))))(#3# d(s)(and(plusp(v s))(set s(1-(v s)))))(#3# p(s)(format t"~A = ~A~%"s(v s)))(defmacro a(n . p)`(#3#,(cadr n)(&rest g)(if,@p)))(#3# k(s)(typecase s(integer`(nth,(1- s)g))(symbol `',s)(t(list*(car s)(mapcar 'k(cdr s))))))(#3# r()(prog(l p q)$(setf p()l(make-string-input-stream(or(read-line()()())(return))))@(when(setf p(read l()()))(push p q)(go @))(if q(return(k(reverse q)))(go $))))(do ((x(r)(r)))((not x))(eval(if(eq(car x)'a)`(,@x,(r),(r),(r))x))))
```
Put this in `file.lisp` and call for example `sbcl --script file.lisp`; input is read from the standard input stream.
This version parses a *superset* of Prindeal: without not much difficulties, you can access all Common Lisp from a Prindeal source. I consider this a *feature* of the intepreter.
### Commented version
```
;; copy-readtable is only used during development, so that I do not
;; mess with my running environment. The real code starts with the
;; progn below, which is superfluous of course inside a let.
(let ((*readtable* (copy-readtable)))
;; I use PROGN in the golfed version so that I can have the whole
;; program as a unique tree. This allows me to define reader
;; variables like #3=defun in order to gain a few bytes by writing
;; #3# instead of defun. Reader variables are removed in
;; this human-friendly version.
(progn
;; Let # point to the same reader function as ;
;; Of course, ; is still usable as a comment delimiter
(set-macro-character #\#
(get-macro-character #\;))
;; :invert does what is necessary to enable case-sensitive reading
;; and printing of symbols
(setf (readtable-case *readtable*) :invert)
;; value of symbol, or zero
(defun v(s)(if(boundp s)(eval s)0))
;; increment
(defun i(s)(set s(1+ (v s))))
;; decrement
(defun d(s)(and(plusp(v s))(set s(1-(v s)))))
;; print
(defun p(s)(format t"~A = ~A~%"s(v s)))
;; alias: wrap an "if" inside a "defun".
;; YES, that means you can redefine ANY lisp function with "a" !
;; A safer version would properly intern symbols in a dedicated package.
;;
;; Notice the G variable. We take advantage of the "unhygienic"
;; (what a bad adjective) nature of macros to create a context
;; where G is bound to the argument list. The same G is referenced
;; implicitely later.
(defmacro a(n . p)`(defun,(cadr n)(&rest g)(if,@p)))
;; Canonicalize expressions:
;;
;; - if s is a symbol, return s quoted. All functions manipulate
;; symbols in order to allow the undeclared use of variables. With
;; symbols, we can check for boundness.
;;
;; - if s is an integer, then we are inside an alias definition. The
;; integer is replaced by an access to the s'th element of the
;; implicit argument list G using (nth (1- s) g). G will be bound
;; when the expressions is injected in the defun corresponding to
;; the alias, or else an error will be signaled: either because G
;; is unbound, or because you defined a variable named G which is
;; by construction not a list. Since we do not sanitize properly
;; the input, you could bind G globally to a list, but that would be
;; nasty.
;;
;; - Finally, if s is a list, apply k to all but the first
;; elements of s. The first element is a symbol but we do not
;; need to quote it because we want to call the function
;; associated with the symbol. Due to the Lisp-2-ness
;; of Common Lisp, functions and variables can coexist
;; with the same name.
;;
(defun k(s)(typecase s
(integer`(nth,(1- s)g))
(symbol`',s)
(t(list*(car s)(mapcar #'k(cdr s))))))
;; Reader function
(defun r()
(prog (l ; current line, as an input-stream reading a string
p ; current read form
q ; whole line and return value, as a list
)
;; PROG includes an implicit TAGBODY. Below, $ and @ are
;; labels for GO statements (gotos).
$ (setf
;; emtpy p
p ()
;; Read a whole line and if we do not fail, build an input
;; stream to read from it.
l (make-string-input-stream
(or (read-line()()()) ;; try to read a line,
(return) ;; but return from prog if we reach
;; the end of file.
)))
@ (when (setf p (read l()()))
;; Read a lisp expression, put it in p and if p is not nil
;; push it into q. A nil could happen at the end of the
;; line or if someone (you know who) inserted an empty list
;; in the file being read.
;;
;; Thanks to the readtable which now handles comments
;; and spaces for us, nothing needs to be done here to
;; preprocess the input.
(push p q) (go @))
;; If we read an empty line, q can be nil. In this case, go
;; back to $ and read another line. If q is not nil, reverse
;; it (we pushed, remember), canonicalize it and return the
;; result.
(if q (return(k(reverse q))) (go $)))
)
;; Read/eval loop. When reading "(a name)", we read the three
;; next lines and append them to the first so that it builds a
;; call the the alias definition macro a. Otherwise, just eval x.
(do((x(r)(r))((not x))
(eval (if (eq(car x'a))
`(,@x,(r),(r),(r))
x)))))
```
# Example
```
~$ sbcl --script file.lisp < testfile
A = 0
B = 0
C = 0
____ = 0
A = 1
B = 1
C = 2
____ = 0
A = 1
B = 3
C = 2
____ = 0
d = 6
____ = 0
d = 18
____ = 0
d = 0
____ = 0
A = 8
B = 3
C = 2
____ = 0
A = 9
B = 3
C = 2
____ = 0
A = 9
B = 3
C = 729
```
If we replace `eval` by `print` in the read/eval loop, then we can see what is being evaluated:
```
(a 's (i '_) (d '_) (d '_))
(a 'f (d '_) (d '_) (d '_))
(a 'z (d (nth 0 g)) (z (nth 0 g)) (s))
(a 'n (z (nth 0 g)) (i (nth 0 g)) (s))
(a 'move (moveH (nth 0 g) (nth 1 g)) (move (nth 0 g) (nth 1 g)) (s))
(a 'moveH (d (nth 0 g)) (i (nth 1 g)) (f))
(a 'dupe (dupeH1 (nth 0 g) (nth 1 g) (nth 2 g))
(dupe (nth 0 g) (nth 1 g) (nth 2 g)) (s))
(a 'dupeH1 (d (nth 0 g)) (dupeH2 (nth 1 g) (nth 2 g)) (f))
(a 'dupeH2 (i (nth 0 g)) (i (nth 1 g)) (s))
(a 'copy (z (nth 1 g)) (copyH (nth 0 g) (nth 1 g)) (s))
(a 'copyH (dupe (nth 0 g) (nth 1 g) '_copy) (move '_copy (nth 0 g)) (s))
(a 'addTo (copy (nth 1 g) '_add) (move '_add (nth 0 g)) (s))
(a 'add (z (nth 0 g)) (addH (nth 0 g) (nth 1 g) (nth 2 g)) (s))
(a 'addH (addTo (nth 0 g) (nth 1 g)) (addTo (nth 0 g) (nth 2 g)) (s))
(a 'mul (mulH1 (nth 0 g) (nth 1 g)) (mulH2 (nth 0 g) (nth 2 g)) (s))
(a 'mulH1 (z (nth 0 g)) (copy (nth 1 g) '_mul) (s))
(a 'mulH2 (mulH3 (nth 0 g) (nth 1 g)) (mulH2 (nth 0 g) (nth 1 g)) (s))
(a 'mulH3 (d '_mul) (addTo (nth 0 g) (nth 1 g)) (f))
(a 'mulBy (mul '_mulBy (nth 0 g) (nth 1 g)) (copy '_mulBy (nth 0 g)) (s))
(a 'pow (powH1 (nth 0 g) (nth 2 g)) (powH2 (nth 0 g) (nth 1 g)) (s))
(a 'powH1 (n (nth 0 g)) (copy (nth 1 g) '_pow) (s))
(a 'powH2 (powH3 (nth 0 g) (nth 1 g)) (powH2 (nth 0 g) (nth 1 g)) (s))
(a 'powH3 (d '_pow) (mulBy (nth 0 g) (nth 1 g)) (f))
(p 'A)
(p 'B)
(p 'C)
(n 'A)
(n 'B)
(add 'C 'A 'B)
(p '____)
(p 'A)
(p 'B)
(p 'C)
(add 'B 'A 'C)
(p '____)
(p 'A)
(p 'B)
(p 'C)
(mul 'd 'B 'C)
(p '____)
(p 'd)
(mulBy 'd 'B)
(p '____)
(p 'd)
(d 'A)
(mulBy 'd 'A)
(p '____)
(p 'd)
(pow 'A 'C 'B)
(p '____)
(p 'A)
(p 'B)
(p 'C)
(pow 'A 'B 'C)
(p '____)
(p 'A)
(p 'B)
(p 'C)
(pow 'C 'A 'B)
(p '____)
(p 'A)
(p 'B)
(p 'C)
```
### Macroexpansion
If we pick the following alias definition:
```
(a 'powH2 (powH3 (nth 0 g) (nth 1 g)) (powH2 (nth 0 g) (nth 1 g)) (s))
```
... we can see references to a variable named `g` which is nowhere to be found in the lexical scope. But after macroexpansion, here is the actual code being evaluated:
```
(defun powH2 (&rest g)
(if (powH3 (nth 0 g) (nth 1 g))
(powH2 (nth 0 g) (nth 1 g))
(s)))
```
Now, `g` refers to the argument list of the function being defined.
[Answer]
# Python 2, 486 bytes
**This is the reference solution which I golfed more (currently -98 bytes).**
```
import sys;sys.setrecursionlimit(2000)
def r(s):
n=s[0]
if n in A:f=lambda i:r([s[int(t)]if'0'<t[0]<':'else t for t in A[n][i]]);return f(1+(f(0)or 0))
k=s[1]
if'i'<n:print k,'=',V.get(k,0)
elif'd'<n:V[k]=-~V[k]if k in V else 1
elif'a'<n:
if~-(k in V)or V[k]<1:return 1
V[k]-=1
else:A[k]=s[2:]
A={};V={};c=filter(bool,([l,l[:l.find('#')]]['#'in l]for l in input().split('\n')))
while c:
s=c[0].split();c=c[1:]
if'a'!=s[0]:r(s)
else:r(['a',s[1]]+map(str.split,c[:3]));c=c[3:]
```
Changes (that I recall):
* automatic boolean-integer conversion (`[l,l[:l.find('#')]]['#'in l]`).
* set or increment in one statement (`V[k]=-~V[k]if k in V else 1`)
* more aliases to longer expressions (`k=s[1]`)
* no counter in the main loop, clearing the input list instead
* `print` automatically adding spaces (`print k,'=',V.get(k,0)`)
* checking digits 1-9 (`'0'<t[0]<':'`)
* flipping the return values of `r` around to save `return`s
* removing repetition of slicing and splitting (`map(str.split,c[:3]))`)
[Answer]
# C++, 752 bytes
**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter (yet again!)**
This one is C++ - as idiomatic as I could make it.
That means making it more C++-ish and less C-ish.
That also means it is bigger than the equivalent C program.
I think C++ rivals Java for the most verbose standard library.
```
#import<bits/stdc++.h>
#define a first
#define c(s);else if(B==#s)
#define e(n)(n=regex_replace(n,regex{"^ *(.*?) *(#.*)?$"},"$1")).size()
#define f(n)for(;getline(cin,n),!e(n););
#define i p.top().a
#define j p.size()
#define k n[o[0]]
#define U;using
U namespace std;U g=string;U h=istream_iterator<g>U s=vector<g>;map<g,s>m;map<g,int>n;stack<pair<pair<int,s>,s>>p;main(int v){for(g X,Y,Z;getline(cin,X);)if(e(X))for(p.push({{0,{X,"",""}},{}});bool z=j;){g B;s C,o;copy(h(stringstream(i.second[i.a])>>B),h(),back_inserter(C));for(g x:C)o.push_back((v=atoi(&x[0]))>0?p.top().second[v-1]:x);if(0)c()c(p)cout<<o[0]+" = "<<k<<'\n'c(i)k++c(d)k-=z=k c(a){f(X)f(Y)f(Z)m[o[0]]={X,Y,Z};}else{p.push({{0,m[B]},o});continue;}while(j&&i.a)p.pop();j?i.a-=~!z:0;}}
```
[Try it online!](https://tio.run/##fVLRctowEHzPVygmk@iCcMlrZJsZ8g3MkFDKCCEbYVvWWDKleNxfpwdOSZqHas723WrndLuWtHaUSXk6DXRpq9pHa@3dN@c3cjgMt8nNYKNSbRQRJNW189daUgdcFU4RndJpHA8cXPcUNUBNXKtMHVa1soWQCLFL3QY/yCMNHyeAn0H4CJO7oGPB3VMAEDp9VPSjT4p90qqmPFO@QIBKbZgBdns@gAO/EjWxoa8shVBcsR1iX/rlxCyqxXi5vCIz3jhtspsZMaJUzuKgBLXzGcli52vcwnQba8yVKFfaq1r4qo6yZEZcvFeyL3gpbJQxl5TvmTY@Mdx5IfPICl33L0SRg5FY5GlDESB7aM8aMzJnr@ztH6lzFInuKjqHiw82tI3b0rYds3bOggCj61jbdcDXVVWQY7zj0GZkyh15YRWXlf1Ft7QX0kugOnRKVmaz0KFYQpJMgW0psDVOutLGqRol0hcA3g91eH6B6nLs6kyhdB@jAZreH9BHgGQ8@ev8e9v96Gn5fACOc49BUgwLsmp8FJ2dHwYkJkEU5VH08N08SKohHw4l3UA@io9xjtdKoB8oOKWv@LxB2f@xuL3Y0/HufOfaT06Ui@myYxV6gOd7bRrFu59bXSi6u79HkYDc84B8N8FqFP@@PT6PededTpqUohBl49WN/Ug315TgGrhGSuXcfxip0EVTf@khcu0F6dcnxgX@Aw "C++ (gcc) – Try It Online")
Below is the original. If anyone can think of a way to make it more idiomatic and shorter at the same time please let me know.
```
#include <array>
#include <iostream>
#include <map>
#include <regex>
#include <sstream>
#include <stack>
typedef std::vector<std::string> List;
typedef std::pair<std::string, List> Statement;
typedef std::array<std::string, 3> Alias;
typedef std::pair<long, Alias> IndexedAlias;
typedef std::pair<IndexedAlias, List> Item;
std::map<std::string, Alias> aliases;
std::map<std::string, long> variables;
std::stack<Item> stack;
std::regex re("^ *(.*?) *(#.*)?$");
int main()
{
std::string line, line1, line2, line3;
while (std::getline(std::cin, line)) // control-Z to exit
{
line = std::regex_replace(line, re, "$1");
if (line.empty()) continue;
stack.push(Item{ { 0, { { line, "", "" } } }, {} });
bool flag;
while (!stack.empty())
{
Statement statement;
std::istringstream ss(stack.top().first.second[stack.top().first.first]);
ss >> statement.first;
std::copy(std::istream_iterator<std::string>(ss), std::istream_iterator<std::string>(), std::back_inserter(statement.second));
List arguments;
std::transform(std::begin(statement.second), std::end(statement.second), std::back_inserter(arguments),
[](std::string arg){ int i = atoi(arg.c_str()); return i > 0 ? stack.top().second[i - 1] : arg; });
flag = true;
if (statement.first == "")
;
else if (statement.first == "p")
std::cout << arguments[0] << " = " << variables[arguments[0]] << std::endl;
else if (statement.first == "i")
variables[arguments[0]]++;
else if (statement.first == "d")
variables[arguments[0]] -= (flag = variables[arguments[0]]);
else if (statement.first == "a")
{
do { std::getline(std::cin, line1); line1 = std::regex_replace(line1, re, "$1"); } while (line1.empty());
do { std::getline(std::cin, line2); line2 = std::regex_replace(line2, re, "$1"); } while (line2.empty());
do { std::getline(std::cin, line3); line3 = std::regex_replace(line3, re, "$1"); } while (line3.empty());
aliases.insert(std::make_pair(arguments[0], Alias{ { line1, line2, line3 } }));
}
else
{
stack.push(Item{ { 0, aliases[statement.first] }, arguments });
continue;
}
while (!stack.empty() && stack.top().first.first) stack.pop();
if (!stack.empty()) stack.top().first.first += 1 + !flag;
}
}
std::cout << "-- Variables --" << std::endl;
std::transform(std::begin(variables), std::end(variables), std::ostream_iterator<std::string>(std::cout, "\n"),
[](std::map<std::string, long>::value_type pair){ std::ostringstream ss; ss << pair.first << " = " << pair.second; return ss.str(); });
std::cout << "-- Aliases --" << std::endl;
std::transform(std::begin(aliases), std::end(aliases), std::ostream_iterator<std::string>(std::cout, "\n"),
[](std::map<std::string, Alias>::value_type pair){ std::ostringstream ss; ss << pair.first << " = [1]:" << pair.second[0] << " [2]:" << pair.second[1] << " [3]:" << pair.second[1]; return ss.str(); });
std::cout << "---------------" << std::endl;
return 0;
}
```
[Answer]
# [Uiua](https://uiua.org) (tentative), 468 characters
**Note that due to a bug in the interpreter, there is a spurious error preventing proper execution. Once the bug is fixed, I will update this answer to reflect that. Until then, I'm leaving the (tentative) in the heading.**
```
p←⊂↯→(⊟∶□0□,)¬/+≡(|2≅!)→(↯→∶⧻).≡⊢.→(.!⊡1)!→→(⊡2)⊡1,∶
;∧(|2!⊡∶(⊂□1⊟□&p/+∺(×≅→∶∷!⊢∶⊡1.),∶&pf⊂∶" = ",p)_(⊂□1⊟□∺([∶∷□]+→(∶→≅.)!⊡1∶!⊢.)p)_(⊂⊟→□→≡(⍜'⊡1⍜!'↥0)/×≡(≥0!⊡1).∺([∶∷□]-∶→(∶→≅.)!⊡1∶!⊢.)p)_(|2↬2∶□/(⊂⊂∶@ ∷!)⊡-∶2!⊢,∶↬2∶□/(⊂⊂∶@ ∷!)⊢,∶→→;∺(|2⍜'↘1∺(|2□⍣(!⊡parse)(→;;)!)⊜□≠,@ !)→,↘1⊡∶!⊡2,⊗∶≡⊢!⊡2,⊢,)⊗∶["p""i""d"]!⊢,∶⊜□≠@ .!∶)⊂{1[{"1"0}]}□→(▽¬∵(|1↥=@ ∶=@a.⊢!).)≡(⍜'↘1(∵⍜!(↘1))⍜⊢(⍜!(↘2)))⊜·▽∵(4;).+1⇡÷4⧻.▽∵(|1↥=@ ⊢∶≅"a ".↙2!)..▽↧1∵⧻.∵⍜!(⇌▽\↥×≠@\r∶≠@ ..⇌▽=0\+=@#.)⊜□≠@\n.&ru@\00
```
This is my first Uiua program of more than a couple dozen characters, so I'm sure there's lots of places I could golf it more effectively. It was a good opportunity to practice the language, though :)
## Non-minified version
```
# preexec state_alias_array command -> state_array command_arg alias_array
preexec ← (
⊡1,∶ # put state on top
!→→(⊡2) # get aliases (for later)
→(.!⊡1) # get variable name (put two copies on stack for later)
≡⊢. # get list of current variable names
¬/+≡(|2 ≅!) →(↯→∶⧻). # test if we need to add a new variable
⊂↯→(⊟∶□0□,) # add variable if necessary
)
# exec<T> state_alias_array command -> state_alias_array
execp ← (
preexec
&pf⊂∶" = ", # print "varName = "
&p/+∺(×≅→∶∷!⊢∶⊡1.),∶ # print "varValue\n"
⊂□1⊟□
)
execi ← (
preexec
∺([∶∷□]+→(∶→≅.)!⊡1∶!⊢.) # increment the relevant variable
⊂□1⊟□ # reform state_alias_array
)
execd ← (
preexec
∺([∶∷□]-∶→(∶→≅.)!⊡1∶!⊢.) # decrement the relevant variable
/×≡(≥0!⊡1). # check if <0
→≡(⍜'⊡1⍜!'↥0) # reset back up to 0
⊂⊟→□ # reform state_alias_array
)
execcall ← (|2
⊢, # get alias name
⊗∶≡⊢!⊡2, # get index of call
↘1⊡∶!⊡2, # get subcommands
→,
∺(|2
⊜□≠,@ ! # split box"thing 1 2" into [box"thing" box"1" box"2"]
⍜'↘1∺(|2 □⍣(!⊡parse)(→;;)!) # turn the 1 and 2 into first and second arguments
)
→→; # original call no longer necessary
□/(⊂⊂∶@ ∷!)⊢,∶ # join [box"i" box"dog"] into box"i dog"
↬2∶ # call first
⊡-∶2!⊢,∶ # select second or third based on success
□/(⊂⊂∶@ ∷!) # join [box"i" box"dog"] into box"i dog"
↬2∶
)
execline ← (|2
∶⊜□≠@ .!∶ # split command
!⊡∶execp_execi_execd_execcall⊗∶["p""i""d"]!⊢, # dispatch correct command
)
&ru@\00
⊜□≠@\n. # split lines
∵⍜!(
▽=0\+=@#. # remove comments
⇌▽\↥×≠@\r∶≠@ ..⇌ # remove trailing whitespace
)
▽↧1∵⧻. # remove blank lines
▽∵(|1 ↥=@ ⊢∶≅"a ".↙2!).. # get alias definitions
⊜· ▽∵(4;).+1⇡÷4⧻. # separate out each alias
≡(
⍜⊢(⍜!(↘2)) # remove alias decl
⍜'↘1(∵⍜!(↘1)) # remove indentation
)
→(▽¬∵(|1 ↥=@ ∶=@a.⊢!).) # remove alias definitions from command list
⊂{1 [{"123illegalvariable" 0}]}□ # group last success, state array and alias array
∧execline # exec all instructions
;
```
[Answer]
# Python 3, 1322 bytes
**Golfed:**
```
import re,sys;sys.setrecursionlimit(2000);F,L=filter,list
class P:
N,O,F=0,{},{}
def __init__(S,c):
S.B,S.E={"p":S.P,"i":S.I,"d":S.D,"a":S.L},dict(enumerate(F(None,[i.split('#')[0].rstrip()for i in c.splitlines()])))
while S.N in S.E:S.X(S.E[S.N])
def V(S, v, y, z=0):
if re.match("[\w_][\d\w_]*",v):
if not v in y:
if z is not None:y[v]=z
else:return False
return True
return False
def A(S):S.N+=1
def P(S,v):
if S.V(v,S.O):print("{0} = {1}".format(v, S.O[v]));return True
return False
def I(S,v):
if S.V(v, S.O):S.O[v]+=1;return True
return False
def D(S,v):
if S.V(v,S.O)and S.O[v]>0:S.O[v]-=1;return True
return False
def L(S,v):
e=[]
if S.V(v,S.F,e):
for i in range(3):S.A();e.append(S.E[S.N].lstrip())
return True
return False
def C(S,c,v):
def R(Z,v):
for i in re.findall("\s(\d+)", Z):Z=Z.replace(" %s"%i," %s"%v[int(i)-1])
return Z
Q,m,f=map(lambda l:R(l,v),S.F[c])
if S.X(Q,False):return S.X(m,False)
return S.X(f,False)
def X(S,Z,C=True):
u=re.match("\s?([\w_][\d\w_]*)\s?([\w_][\d\w ]*)?",Z)
if u:
c,v=map(lambda i:''if i is None else i,u.groups());v=L(F(None,v.split(' ')))
if S.V(c,S.F,None):
T=S.C(c, v)
if C:S.A()
elif S.V(c,S.B,None):
T=S.B[c](*v)
if C:S.A()
else:return False
return T
return False
```
**Ungolfed:**
```
import re
class Prindeal:
iline = 0
local = {}
udef = {}
content = {}
def __init__(self, c):
self.built = {
"p": self.print,
"i": self.increment,
"d": self.decrement,
"a": self.alias,
}
self.content = dict(enumerate(filter(None, [i.split('#')[0].rstrip()for i in c.splitlines()])))
while self.iline in self.content:
self.execute_line(self.content[self.iline])
def validate_name(self, varname, stack, default=0):
if re.match("[\w_][\d\w_]*", varname):
if not varname in stack:
if default is not None:
stack[varname] = default
else:
return False
return True
return False
def advance_stack(self):
self.iline += 1
def print(self, varname):
if self.validate_name(varname, self.local):
print("{0} = {1}".format(varname, self.local[varname]))
return True
return False
def increment(self, varname):
if self.validate_name(varname, self.local):
self.local[varname] += 1
return True
return False
def decrement(self, varname):
if self.validate_name(varname, self.local) and self.local[varname] > 0:
self.local[varname] -= 1
return True
return False
def alias(self, aliasname):
indexed_lines = []
if self.validate_name(aliasname, self.udef, indexed_lines):
for i in range(3):
self.advance_stack()
indexed_lines.append(self.content[self.iline].lstrip())
return True
return False
def execute_alias(self, cmd, variables):
def parse_args(line, variables):
for i in re.findall("\s(\d+)", line):
line = line.replace(" %s" % i, " %s" % variables[int(i) - 1])
return line
init, success, failure = map(lambda l: parse_args(l, variables), self.udef[cmd])
if self.execute_line(init, False):
return self.execute_line(success, False)
return self.execute_line(failure, False)
def execute_line(self, line, cont=True):
valid_execution = re.match("\s?([\w_][\d\w_]*)\s?([\w_][\d\w ]*)?", line)
if valid_execution:
cmd, variables = map(lambda i: '' if i is None else i, valid_execution.groups())
variables = list(filter(None, variables.split(' ')))
if self.validate_name(cmd, self.udef, None):
temp = self.execute_alias(cmd, variables)
if cont:
self.advance_stack()
elif self.validate_name(cmd, self.built, None):
temp = self.built[cmd](*variables)
if cont:
self.advance_stack()
else:
return False
return temp
return False
```
**Usage:**
```
P(c)
```
Where `c` is the text content.
**Examples:**
*Single-line strings are accepted:*
* `P("p cat")`
* `P("p dog\ni dog\np dog")`
*Multi-lined strings are also accepted:*
```
P("""
p dog
i dog
p dog
""")
```
Or:
```
P("""p dog
i dog
p dog""")
```
Etc.
**Notes:**
This works correctly for all test cases, but reaches the recursion limit on:
```
pow C A B #C = A ^ B = 9 ^ 3 = 729
```
Hence the `sys.setrecursionlimit(2000)`.
[Answer]
# Haskell, 1009
I did my best to golf it; my ungolfed code consisted of over 3,000 characters. At this point I can't remember what all the functions are doing so golfing it more mean guessing what will break it and what won't.
```
import qualified Data.Map as M
import Control.Monad.State.Lazy
import Data.List
type A=M.Map String
data P=P(A Int)(A([String]->StateT P IO Int))
a f=evalStateT f(P M.empty$M.fromList[("i",\(b:_)->(+1)%b),("d",\(b:_)->pred%b),("p",\(b:_)->i b>>= \v->liftIO(putStrLn$b++"="++show v)>>q 1)])
e(k:l)=do{(P v a)<-get;put.P v$M.insert k(m l)a;q 1}
g t s f= \a->t a>>= \b->if b>0then s a else f a
f%k=f<$>i k>>= \v->if v<0then k#0>>q 0else k#v>>q 1
i k=get>>= \(P v _)->q$M.findWithDefault 0 k v
k#v=get>>= \(P b a)->put$P(M.insert k v b)a
l k=get>>= \(P _ a)->q$a M.!k
f s=let(f:a)=r s in($a)<$>l f>>=id
m(t:s:f:_)=g(k t)(k s)(k f)
k s=let(f:b)=r s in\a->($(map((\y z->if all(\c->c>'/'&&c<':')z then y!!(read z-1)else z)a)b))<$>l f>>=id
n=dropWhileEnd(==' ').takeWhile(not.(=='#')).dropWhile(==' ')
o[]=[]
o(l:ls)|(head.r$l)=="a"=(l:take 3 ls):(o$drop 3 ls)|1>0=[l]:o ls
p s|length s>1=e$(n.tail.head$s):tail s|1>0=f.head$s
q=return
main=join$a.(\s->mapM_ p(o.filter(not.null).map n.lines$s))<$>getContents
r=words
```
[Answer]
# Python - ~~695~~ 688 bytes
```
def p(v):print v,"=",w.get(v,0)
def i(v):w[v]=w.get(v,0)+1
def d(v):
if v in w:
<TAB>w[v]-=1
<TAB>if not w[v]:del w[v]
else:return 1
def a(n,b,d,h):
def g(*a):
<TAB>i=1;f=b;s=d;t=h
<TAB>for v in a:v=q+v+q;k=q+j(i)+q;f=c(f,k,v);s=c(s,k,v);t=c(t,k,v);i+=1
<TAB>y=u(t,e)if u(f,e)else u(s,e);i=1;return y
e[n]=g
q="'";w=x={};u=eval;e={'a':a,'d':d,'i':i,'p':p};import sys;l=sys.stdin.readlines();r="";j=str;c=j.replace;sys.setrecursionlimit(2000)
for h in l:
h = h.strip()
if not h:continue
l = h.split();f=l[0];n=f+"("
if "#" in f:continue
for g in l[1:]:
<TAB>b=g.find("#")+1
<TAB>if b:g=g[:b-1]
<TAB>if g:n+="'%s',"%g
<TAB>if b:break
if x:x-=1;d+='"%s)",'%n
else:x=(f=="a")*3;d=n
if not x:d+=")\n";r+=d
exec r in e
```
`<TAB>` is a literal tab character.
[Answer]
# APL (Dyalog Unicode), ~~449~~ ~~422~~ ~~388~~ 383 bytes
This is a somewhat optimized APL version of a program to run the Prindeal code. It assumes that the index origin is 0 (⎕IO←0). The Prindeal program to run is in an enclosed string array P.
```
z
L←0
V←N←F←M←⍬
r←{⍬≡h←⍸⎕D∊⍨⊃¨t←↑⍵:t⋄t[h]←⍺[⍎¨t[h]]⋄t}
R←{⍵/⍨∊0≠⍴∘∊¨⍵}{' '(≠⊆⊢)⍵/⍨~∨\'#'=⍵}∘∊¨P
k:e↑L⌷R
L+←1
→k/⍨L<⍴R
{y}←e c;x
y←1
→((⊃c)∘≡∘,¨'pida')/p i d a
y←e c r x⌷⍨2-e c r 0⌷x←↑F[M⍳0⌷c]
→0
p:N[x],’=‘,2⊥⌽↑V[x←g c]
→0
i:V[x]←⊂{⍬≡⍵:1⋄⊃⍵:0,∇1↓⍵⋄1,1↓⍵}↑V[x←g c]
→0
d:→0/⍨~y←(,0)≢m←↑V[x←g c]
V[x]←⊂m↓⍨-(1=⍴m)⍱⊃⌽m←{⍬≡⍵:⍬⋄~⊃⍵:1,∇1↓⍵⋄0,1↓⍵}m
→0
a:M←M,1⌷c
F←F,⊂R[L+1+⍳3]
L+←3
x←g c
x←N⍳1⌷c
→0/⍨x<⍴N
N←N,1⌷c
V←V,⊂,0
```
The code length was a bit less until I reread the specification that requires arbitrary precision integers. I added code to provide this functionality although I'd hate to wait around for a Prindel program that requires this feature to execute. Dialog APL does have some prewritten routines ('big') to provide this functionality, However, I felt it would be a bit of a cheat to use all that extra 'hidden' code and call it an inherent part of the language.
In any case, the program consists of eight basic functions as follows:
```
z - this function initializes variables, strips comments, trailing blanks and empty lines; then loops through the Prindeal program code.
e - this executes a Prindeal statement either an inherent statement (p,i,d,a) or a defined alias. Recursive.
g - gets a reference to a variable value (defines if as-of-yet undefined)
r - at execution time, resolves numerical reference to arguments in alias functions
```
Comments and improvements are welcomed. I first dabbled in APL in the late 60s and early 70s. Life took me in another direction, but apparently I never lost my interest in the language. I recently took a look at the state of the language (via Dialog) and found that what was a powerful language back in the day had only grown in complexity and capability. I'm using some of these code golf challenges to introduce me to the newer (to me) language features and have a bit of fun ... lifelong learning.
In any case, here is the output from the test program:
```
z
A = 0
B = 0
C = 0
____ = 0
A = 1
B = 1
C = 2
____ = 0
A = 1
B = 3
C = 2
____ = 0
d = 6
____ = 0
d = 18
____ = 0
d = 0
____ = 0
A = 8
B = 3
C = 2
____ = 0
A = 9
B = 3
C = 2
____ = 0
A = 9
B = 3
C = 729
```
```
] |
[Question]
[
*Inspired by [this](https://codegolf.stackexchange.com/questions/138068/kill-it-with-fire "Kill it With Fire").*
## Background
The [evil farmer](https://codegolf.stackexchange.com/questions/138068/kill-it-with-fire "Kill it With Fire") has decided to burn your wheat field down in order to drive up the prices. To ensure total destruction, he has also soaked your field in gasoline. Even more unfortunately, you happened to be walking on the field when it was lit on fire, and you must get out quickly to survive.
## Challenge
Given a field containing wheat, fire and your location, determine if you can make it out of the field in time.
A field consists of wheat (here represented by `.`) and fire (`F`). Here your location is marked with a `O`. For example:
```
...F...F
F.......
........
.F......
....O...
...F....
........
.F....F.
```
Every second you move to any adjacent cell (but not diagonally), and every fire spreads to every adjacent cell. If you can't move to a cell that will not be on fire, you die. If you make it out of the field, you survive. Let's see what happens in this example:
```
...F...F
F.......
........
.F......
....O...
...F....
........
.F....F.
..FFF.FF
FF.F...F
FF......
FFF.....
.F.F.O..
..FFF...
.F.F..F.
FFF..FFF
FFFFFFFF
FFFFF.FF
FFFF...F
FFFF....
FF.FF.O.
.FFFFFF.
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFF.FF
FFFFF.FF
FFFFFFFO
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFFO <-- you made it out and survived, barely
FFFFFFFF
FFFFFFFF
FFFFFFFF
```
## Rules
* Your input is the field as a grid. You may choose any input format, including a string with line separators or a 2D array.
+ You may **not** take as input the locations for fire and/or yourself.
+ You may use any 3 distinct values as wheat, fire and your position, including non-strings for array input.
+ Fields are always at least 1x1 in size, rectangular and contain no invalid characters.
+ Any field will contain exactly one of the value representing your location, and every other position may or may not be fire.
* Your output is one of two distinct values for "you survive" or "you die", as usual in [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'").
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test cases
### Survived
```
O
```
```
....
.O..
....
```
```
FFFFF
.....
..O..
.....
```
```
FFFF
FFFO
FFFF
```
```
.F....
......
......
.F....
..O...
.FF...
.F....
..FF..
```
```
...F...F
F.......
........
.F......
....O...
...F....
........
.F....F.
```
### Didn't survive
```
FFF
FOF
FFF
```
```
F.F
.O.
F.F
```
```
....F
.....
..O..
.....
F....
```
```
.F....F.
........
........
F..O....
........
.....F..
```
```
...F...F
F......F
........
.F......
....O...
...F....
........
.F....F.
```
```
F..F
.O..
FF..
```
[Answer]
# Snails, 15 bytes
```
\Oo!{.,fee7.,\F
```
[Try it online!](https://tio.run/##K85LzMwp/v8/xr9SsVpPJy011VxPJ8bt/389Nz0g4NLTQ6Fggv4QnhuKIIgLAA "Snails – Try It Online")
`1` means survival while `0` means death.
Since it is impossible to outrun the fire, it is never useful to try to go around it. The best route is always a straight line. So there are only four possible choices of escape route. To determine if a direction is safe, we check for any `F` in the "fire cone" pointing in that direction.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~283~~ ~~218~~ ~~209~~ 208 bytes
```
lambda F:f(F)&f(F[::-1])
def f(F):l=F.split();w=len(l[0])+1;i=F.index('O');x,y=i/w,i%w;r=range(len(l));return all('F'in''.join(n)for n in[[l[i][x+abs(i-y):]for i in r],[l[i][max(0,y+x-i):i+x-y+1]for i in r]])
```
[Try it online!](https://tio.run/##tVPLboMwELz7K6xUrb2C0DjpE8TVVz6AcCACUleOExHawNdTm6dT5VbVkpf1zrC7Hq1PTfVxVOt2H25bmR52WYq5X1AOD9rEvr9kCaAsL7CJ@TLk3vkkRUUhuIQyV1TGqwQcFgiNCJXlNSURgaB2m1A8XlxxfwnKsEzVPqcdHSAo8@qrVDiVkhJOhCLE@zwKRRUUxxIrLFQcy1gkce2kuzMVywb8xEBCQ7hM3B49pDVduY1TLwX4Qn8ah9m0BNpC5DJjOMSLxcLzPG42MtYs5E0OtyLR4PBbHO7pTAh1edcmbzSeNlMVzY2GP2fyUw9zs9BYbKRZvOeZh/SOjOEz/DJUsZtDVx2i8QacXwXNcc7z@k@avE3tIx51N5ix9wHT5XRCXdLC2GqW74Y@fX8Wndk6cLul0eF917@hKxXY@rYM/C8yTAPYzTxz2QZ8hE@lUBXe0/w71VPfVSfYweeqpAIA7oZXRbaKALQ/ "Python 2 – Try It Online")
Takes input as a newlines separated string, and returns `True/False` for `Dead/Alive`
Works by checking each direction(udlr) for `F`ire in by looking outward:
Example:
Input:
```
FFFFF
.....
..O..
.....
```
Fire checks:
```
Up: Down: Left: Right:
FFFFF F F
... .. ..
O O ..O O..
... .. ..
```
If all directions contain fire you die, otherwise there is an escape.
Edit: Back to taking a string as input, and now only checks for up/right, but also checks the input backwards (giving down/left)
Saved a lot of bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) and [Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista)
[Answer]
# JavaScript, 174 bytes
```
a=>+(t=>g=a=>t--?g(a.map((l,y)=>l.map((c,x)=>(h=v=>[(a[y-1]||[])[x],(a[y+1]||[])[x],a[y][x+1],a[y][x-1],c].includes(v),!c&&h()?p=1:[2,0,1].find(h))))):p)((p=a+'!').length)(a)
```
Input format:
* Array of Array of Integers
* 2 for `F`, 1 for `.`, 0 for `O`
Output:
* Truthy value (1) for survive
* Falsy value (NaN) for die
Try It:
```
f=a=>+(t=>g=a=>t--?g(a.map((l,y)=>l.map((c,x)=>(h=v=>[(a[y-1]||[])[x],(a[y+1]||[])[x],a[y][x+1],a[y][x-1],c].includes(v),!c&&h()?p=1:[2,0,1].find(h))))):p)((p=a+'!').length)(a)
t=s=>f(s.trim().split('\n').map(x=>x.split('').map(n=>({F:2,'.':1,O:0}[n]))))
console.log(t(`
FFFFF
.....
..O..
.....
`))
console.log(t(`
FFFF
FFFO
FFFF
`))
console.log(t(`
.F....
......
......
.F....
..O...
.FF...
.F....
..FF..
`))
console.log(t(`
...F...F
F.......
........
.F......
....O...
...F....
........
.F....F.
`))
console.log(t(`
FFF
FOF
FFF
`))
console.log(t(`
F.F
.O.
F.F
`))
console.log(t(`
....F
.....
..O..
.....
F....
`))
console.log(t(`
.F....F.
........
........
F..O....
........
.....F..
`))
console.log(t(`
...F...F
F......F
........
.F......
....O...
...F....
........
.F....F.
`))
```
Consider a cellular automaton. There are 3 states for a cell `O` (reachable by people), `F` (catch fired), `.` (nothing just happened). The rule for create next generation is:
```
for each cell:
me and my 4 neighborhoods,
if anyone is `F` then result is `F`,
otherwise, if anyone is `O` then result is `O`
otherwise, keep state `.`
```
Once there is an cell on edge has `O` state, the people survive. If this not happened in enough amount generation, then the people died.
```
// check for all neighbors:
h=v=>[(a[y-1]||[])[x],(a[y+1]||[])[x],a[y][x+1],a[y][x-1],c].includes(v)
// if me == 'O' and i'm edge (neighbors contain _undefined_), then survive
!c&&h()?p=1
// Otherwise apply the given rule
:[2,0,1].find(h)
```
[Answer]
# Octave, 71 bytes
```
@(a)(A=blkdiag(0,a,0))<3||any((bwdist(A>2,'ci')>bwdist(A==2,'ci'))(!A))
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNRU8PRNiknOyUzMV3DQCdRx0BT08a4piYxr1JDI6k8JbO4RMPRzkhHPTlTXdMOJmBrCxXR1FB01NT8n5hXrMEVbaigoADDxkhsMJ8LQwgFc@GWQkgbE6/bCLe0MdXsBovFcmn@BwA "Octave – Try It Online")
or
[Verify all test cases!](https://tio.run/##3VXLboMwELz7K@gJr4RQsG@ljso/9FZxcAikKIhWxWkVNfl2amEKNhiapJyKtJYZz673MYjXRPCPtBbvB/FydJjj@z76Qo58nh0Syw1SL4FcOmugZkvGUGdx60rlYpiFOw4xF3kyuuLqEBlDtCmrq4rO53H9Eb2wsLEXvSmg4Rlb5jX019oU3FDpBQnORyHzFLp4LrTtzDlEGS@qtBf6QEN9Y4hFTrrkAlPIpE@iO7WNIlhM/xMz1C@dbMVVDf2FQqcG@@eLltY0/ZeaNhRpU6U5Kr2p57B@xBxwxDbFfpvzHV553FsBPNDTiZdHjDef27wSOFoTz01yF9Y/AGMtAvguAqgzxssqRPLwDbtPaSXycueon8q9CyhJiyI7lDjzFAYDpvoqTabCoP4G "Octave – Try It Online")
Input format:
* 2D array of integers
* `1` for `.`, `2` for `O` and `3` for `F`
Output:
* `true` and `false`
Explanation:
Explanation:
```
A=blkdiag(0,a,0) % add a boundary of 0s around the array
A<3 % return truthy when there is no fire
bwdist(A>2,'ci') % city block distance transform of binary map of fire
bwdist(A==2,'ci') % city block distance transform of binary map of your location
any(...)(!A) % check if there is at least one element on the boundary of
% the fire distance map has its distance greater than
% that of distance map of your location
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 243 bytes
```
^.*O(.|¶)*|(.|¶)*O.*$|(.|¶)*(¶O|O¶)(.|¶)*
O
m`^((.)*) (.*¶(?<-2>.)*(?(2)(?!))O)
$1#$3
m`^((.)*O.*¶(?<-2>.)*(?(2)(?!)))
$1#
T`p`\O`#| ?O ?
+m`^((.)*)[O ](.*¶(?<-2>.)*(?(2)(?!))F)
$1#$3
+m`^((.)*F.*¶(?<-2>.)*(?(2)(?!)))[O ]
$1#
}T`p`F`#|.?F.?
O
```
[Try it online!](https://tio.run/##dY0xDsIwDEV3n8KoHewgLFFWRDavXtiAKgwMDCCEGMO1eoBeLDSojRiopTjf1pPf8/K63s8pteKMJPYduzj@Jq6eMvWdRRvSOIPBLbREwo6RxPUd@e2q2Q0zeWqY/ILZGOp1VW8KajMgYwZhHx7haKGK6A09LIvhYHiak@gkKbjOWfKZr@idTTqIxKt4sJQQUfOD3HMBlqA/GxuD/mMUPw "Retina – Try It Online") Requires the background to be spaces rather than `.`s (or some other regexp-safe character could be used). Explanation:
```
^.*O(.|¶)*|(.|¶)*O.*$|(.|¶)*(¶O|O¶)(.|¶)*
O
```
If there is an `O` on any edge, delete everything else (survival case)
```
m`^((.)*) (.*¶(?<-2>.)*(?(2)(?!))O)
$1#$3
```
Place a `#` in any space above an existing `O`.
```
m`^((.)*O.*¶(?<-2>.)*(?(2)(?!)))
$1#
```
And a `#` in any space below an existing `O`.
```
T`p`\O`#| ?O ?
```
Change the `#`s to `O`s, and also any space to the left or right of an existing `O`.
```
+m`^((.)*)[O ](.*¶(?<-2>.)*(?(2)(?!))F)
$1#$3
```
Place `#`s above any existing `F`s. These can overwrite `O`s as well as spaces.
```
+m`^((.)*F.*¶(?<-2>.)*(?(2)(?!)))[O ]
$1#
```
Place `#`s below any existing `F`s, also overwriting `O`s as well as spaces.
```
}T`p`F`#|.?F.?
```
Change the `#`s to `F`s, and also any `O` or space to the left or right of an existing `F`. Repeat until the `F`s have consumed everything.
```
O
```
Return `1` for survival, `0` if not.
] |
[Question]
[
To interpret a positive integer very literally, write it in English words (without "and"), replace hyphens with spaces, replace each resulting word with its number value, and concatenate the results into a single number.
To write a positive integer more than 99 but less than 1000 in English words, prefix its last two digits written in English with **`[first digit in English]`**`hundred` with a trailing space.
To write a positive integer more than 999 but less than 1 million in English words, use the following syntax: **`[part before the last 3 digits in English]`**`thousand`**`[last 3 digits in English]`**, all separated by spaces.
The task is to input a positive integer (less than 1 million) and output it, interpreted very literally.
# Examples
```
1 -> 1 (one)
10 -> 10 (ten)
16 -> 16 (sixteen)
23 -> 203 (twenty three)
111 -> 110011 (one hundred eleven)
123 -> 1100203 (one hundred twenty three)
1234 -> 110002100304 (one thousand two hundred thirty four)
12345 -> 1210003100405 (twelve thousand three hundred forty five)
123456 -> 110020310004100506 (one hundred twenty three thousand four hundred fifty six)
1056 -> 11000506 (one thousand fifty six)
101101 -> 11001100011001 (one hundred one thousand one hundred one)
110110 -> 1100101000110010 (one hundred ten thousand one hundred ten)
```
Feel free to add more test cases if necessary.
This is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 76 bytes
```
f=lambda n,k=1000:n>19and(f(n/k,k/10)+`k-k%4*5`)*(n>=k)+f(n%k,k/10)or`n`[:n]
```
[Try it online!](https://tio.run/##TZDRCsIwDEWf9Sv6IrY6MWm7gYP6IyJsIsNRzWT64tfPtKubL7c39zQh7fPzvnWkh6Fx9/pxudaCMu8QAEo64qGmq2wk7X3m9whqW/mdX9lNXqmNpKPzast0lWjXV1SdSjoPTdfznJdoSZwkZmKNa5UJiRAsjL4Ivoheh1yPuTbRm9QQO/gYS8RUYhoYb4dg6tDGpgg0iwE75XkAIQTDYiGfSTGPCdyy5FCkHSb6l3E57wKjpJ0i/DGYID/hXC4Xz76lN38O/5uK4txr@AI "Python 2 – Try It Online")
Test suite from Chas Brown.
A fully recursive solution that splits on place values `k=1000`, `k=100`, and `k=10`. The separator for the place values is computed as `k-k%4*5`, which maps
```
1000 -> 1000
100 -> 100
10 -> 0
```
By stopping when `n<=19`, we avoid one-word numbers in the teens being split up.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~44~~ 43 bytes
```
:(!>
ℍZ:₸Z¤1>∧'0פṙ$×:dẏ×,↑ℍṙ×
@3eZ,↑¦↓3eṙ×
```
Longer than my original answer, but it works now.
~~fixed my code again but now it's twice as sad~~
[Try it online!](https://tio.run/##S0/MTPz/30pD0Y7rUUtvlNWjph1Rh5YY2j3qWK5ucHj6oSUPd85UOTzdKuXhrv7D03UetU0EKgOKHZ7O5WCcGgUSOLTsUdtk41Sw4P//hkbGBgYGAA "Gaia – Try It Online")
```
@3eZ,↑¦↓3eṙ× Main function.
@3eZ Input divmod 1000, pushes input div 1000 then input mod 1000
, Pair those two value into a list
↑¦ Run the upper function on both
↓ Call the function below (loops to top function)
3eṙ The string "1000"
× Join the list with "1000"
ℍZ:₸Z¤1>∧'0פṙ$×:dẏ×,↑ℍṙ× Helper function. Called with 1 argument.
ℍZ Divmod with 100
:₸Z Copy the mod part and divmod with 10
Stack is: [100s digit, arg mod 100, 10s digit, 1s digit]
¤1> Bring 10s digit to the top and check if it's greater than 1
∧ Logical AND with 1s digit. (results in 0 or 1)
'0× Multiply the character 0 by that result
¤ Bring 'arg mod 100' to the top
ṙ$ Get its string representation and split it into characters
(simply doing digit list doesn't work in the case it's 0)
× Join this with the multiplied '0' string
:d Copy and parse as a number
ẏ Is it positive? (0 or 1)
× Multiply the string of the number by that result.
, Pair: gives the list [100s digit, string from above]
↑ Call the function above
> Remove the first ^ elements from the pair
ℍṙ× Join the resulting list with the string "100"
:(!> Helper function 2. In this program it is only called with a list.
:( Copy and get the first element.
! Boolean negate (0 or 1)
> Remove that many characters from the start of the list
```
[Answer]
# [Python 3](https://docs.python.org/3/)+[inflect](https://pypi.org/project/inflect/), 193 bytes
```
import inflect,re
exec("for i in re.sub('(and)|\W',' ',%sinput())).split():\n for j in range(0,6**8):\n if i in %sj):\n print(j,end='')\n break"%(('inflect.engine().number_to_words(',)*2))
```
[Try it online!](https://tio.run/##LY7dCoJAEIXve4pFkJ2RRawgIug5uhHEn9HWdHbZXamgdzfT7g7f4Tsc@w53w8d51qM1LgjN7UB1UI529KIaotY4oRcsHKV@qkBCyQ1@8ptUUkgVe812CoCIqbeDXtIlZ/Gz@tUquSPI1ClJzmsjdLvtxb7fgLBOc4BeETdXKXFllaPyEcUA8v8oJe40E2DK01iRK4IpnsY1HqTC5IA4z/ss@wI "Python 3 – Try It Online")
Very naive solution which uses Python's `inflect` library. Here is the unfurled code:
```
import inflect,re
for i in re.sub('(and)|\W+',' ',inflect.engine().number_to_words(input())).split():
for j in range(0,6**8):
if i in inflect.engine().number_to_words(j):
print(j,end='')
break
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ ~~23~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₄вεтвεSÐP@θ1Ký0Û]тý₄ý
```
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/195172/52210), so make sure to upvote him as well.
-5 bytes thanks to *@Grimy*.
[Try it online](https://tio.run/##yy9OTMpM/f//UVPLhU3ntl5sApHBhycEOJzbYeh9eK/B4dmxF5sO7wXKH977/7@hgQEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R00tFzad23qxCUQGH54Q4HBuh6H34b0Gh2fX1l5sOrwXqODw3v86/6MNdQwNdAzNdIyMgQwgyxAoAGIbGZuACVMIaQaUBROGQKRjCKaBMgaxAA).
**Explanation:**
```
₄в # Convert the (implicit) input-integer to base-1000 as list
# i.e. 119100 → [119,100]
# i.e. 23 → [23]
ε # Map each value to:
тв # Convert the value to base-100 as list
# i.e. [119,100] → [[1,19],[1,0]]
# i.e. [23] → [[23]]
ε # Map each value `y` to:
S # Convert the current value to a list of digits
# i.e. [[1,19],[1,0]] → [[[1],[1,9]],[[1],[0]]]
# i.e. [[23]] → [[[2,3]]]
Ð # Triplicate this list
P # Take the product of each inner list of digits
# i.e. [[[1],[1,9]],[[1],[0]]] → [[[1],[9]],[[1],[0]]
# i.e. [[[2,3]]] → [[6]]
@ # Check if it's larger than or equal to each digit
# i.e. [[[1],[1,9]],[[1],[0]]] and [[[1],[9]],[[1],[0]]
# → [[[1],[1,1]],[[1],[1]]]
# i.e. [[[2,3]]] and [[6]] → [[[0,0]]]
θ # Keep only the last check of each
# i.e. [[[1],[1,1]],[[1],[1]]] → [[[1],[1]],[[1],[1]]]
# i.e. [[[0]]]
1K # Remove all 1s from each 'string'
# i.e. [[[1],[1]],[[1],[1]]] → [[[""],[""]],[[""],[""]]]
# i.e. [[["0"]]]
ý # Join the list of digits by this string
# i.e. [[[1],[1,9]],[[1],[0]]] and [["",""],["",""]]→ [[1,19],[1,0]]
# i.e. [[[2,3]]] and [["0"]] → [[203]]
0Û # Remove any trailing 0s
# i.e. [[1,19],[1,0]] → [[1,19],[1,""]]
# i.e. [[203]] → [[203]]
] # Close both maps
тý # Join the inner lists by "100"
# i.e. [[1,19],[1,""]] → [110019,1100]
# i.e. [[203]] → [203]
₄ý # And then those strings by "1000"
# i.e. [110019,1100] → 11001910001100
# i.e. [203] → 203
# (after which the result is output implicitly)
```
[Answer]
# [PHP](https://php.net/), ~~137~~ ~~136~~ 143 bytes
```
function f($n){return$n>99?$n>999?f(substr($n,0,-3)).(1e3).f(substr($n,-3)):$n[0].'100'.f($n[1].$n[2]):($n>20&&$n%10?(0^$n/10).'0'.$n[1]:+$n);}
```
[Try it online!](https://tio.run/##TZDRjoMgEEXf@QrS0AKpSwftNlF364dYN@kajPuCRvCp6be7g7RNCTn3cmcyEMZ@XL6qEdnNtvV/g6WdYFbeJuPnyTJ7zvNqZV51ws2/zk9YTyD5yKRUQptMqvdCiAtma2gU1wBchXG1bhQybWSBp3MKux2zWw2VgB9mDxqk4ti6NhZ7vL68L8wb5x39pjXhmicIWHkKTLPAY0x0LMcM5fjUz5c5xQFPhYdq3HFEsOiakpBumMy17al4vODq6OokvRGKy7T9ED4pZopuLnZTkvvyDw "PHP – Try It Online")
[Answer]
# JavaScript, 69 bytes
Recursively splits and joins based on place values stored in `k`. Inspired by [xnor's Python answer](https://codegolf.stackexchange.com/a/195181).
```
f=(n,k=1e3)=>n<20?+n||'':(n<k?'':f(n/k|0,k/10)+[k-10&&k])+f(n%k,k/10)
```
[Try it online!](https://tio.run/##PY7BCoMwEETvfoWXmoRoTdRKKVo/RDyIGGlXkqLiyX9PV1O7LPOGWRj23a7t3E2vzxKtd2tVSXUIpexTVj51kYiK620j5EF1ARVSUR3DJkKIpWC8hkiKIICGcTxcwMVWmYku/bz4Rvm1RyQJUcSh@a5JumvmEunOLkNkJ29/k7uCk@JHiesqdouuYZ6P0xk9m7G/jmag6niEMfsF "JavaScript (V8) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ ~~32~~ ~~31~~ 29 bytes
```
⪫E↨Nφ⪫E↨ι¹⁰⁰⪫↨λχ…0›Πλ﹪λχ100Iφ
```
[Try it online!](https://tio.run/##VY3PCsIwDMZfZfSUQoXu4h@8ucNQmOzgC8Ra2KC2JeuUPX3NqhdzSD6@/PLFDEgmoMu5p9EnuITRQ4cRTjhZOPs4p@v8vFsCqapaa83jnxmLz/bNkkdawP2IBqcEjhfNYpxthhBBaKGqliwmDuwpPGbzRTqWLqyntZZcqnqvTXCyWEXJKu@lPOa83e0POm9e7gM "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes thanks to @Grimmy. Saved a further byte by finding a better way to choose between `0` or the empty string from a boolean. Saved a further 2 bytes because `Base(l, 10)` conveniently returns an empty array when `l` is zero. Explanation:
```
N Input number
↨ φ Convert to base 1000 as an array
E Map over elements
ι Current element
↨ ¹⁰⁰ Convert to base 100 as an array
E Map over elements
λ Current element
↨ χ Convert to base 10 as an array
⪫ Join with
0 Literal `0`
… Truncated to length
λ Current element
Π Digital product
› Is greater than
λ Current element
﹪ Modulo
χ Predefined variable 10
⪫ Join with
100 Literal string `100`
⪫ Join with
φ Predefined variable 1000
I Cast to string
```
Example: `67890` ⇒ `[67, 890]` ⇒ `[[67], [8, 90]]` ⇒ `[[607], [8, 90]]` ⇒ `[607, 810090]` ⇒ `6071000810090`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~110~~ 115 bytes
```
def F(n,o=""):
for i in 1000,100:
if n>=i:o+=F(n//i)+str(i);n%=i
return o+'0'[:0<n%10<=n>19].join(str(n))*(n>0)
```
[Try it online!](https://tio.run/##TZHBcoMgEIbP9SmYzGSAyjSLqIk25NiXyOSWOKWHJaP20Ke3u0q1l5/d//sHFnj@jJ8R3TTdH534UGii3@10m4ku9iKIgMICgCEhT4RO4MWHNuaesodD0Pkw9irod9z7kIn@MX73KGIuQV5bOOPewtnjxTa3t68YUHEatX5VeAE98RloBj7lqqwR0kpthLLAJcx1AUYWkOzZp2Vpa@7qJeWoLsAtwNqUs2m/GbOxRgpXJgsKEgfl6lcM2ARHUkK1kXrbhnlJUkGdhlvpP4/abRZYJM00wz8GK@S7qeZ05EeXDTknODKU@tZmL88@4EifRI@vZ/F@0NMv "Python 3 – Try It Online")
Pretty simple. Hundreds and thousands are handled recursively.
+5 bytes but fixed a bug with `F(100)` thanks to @ChasBrown.
[Answer]
# JavaScript, ~~95~~ ~~93~~ 92 bytes
```
f=n=>n>999?f(n/1e3|0)+[1e3]+f(n%1e3):n>99?(n/100|0)+'100'+f(n%100):n>20&&(x=n%10)?n-x+''+x:n
```
[Try it online!](https://tio.run/##PY7LCoMwEEX3foWbmoTUdnxUqqB@iLgQMaVFkqIiLvrv6YypDeGemzkw5NWt3dxPz/cSrndrVanLSld5nteK62s0JB8QskG2EgcnLKIgX5MFIMuQzFkAsjEEAd9Keotah5tkTG6FtspMfBnmxTfKbzwWsTMG7JlRxgll6iaR026GSA/e/iVzCw7CjxFet4IqtlZ4Pp7e6NmMw2U0D672jwhhvw "JavaScript (V8) – Try It Online")
---
* -2 bytes ([@Shaggy](https://codegolf.stackexchange.com/questions/195155/interpret-numbers-very-literally/195187?noredirect=1#comment464488_195187)): store `n%10` in a variable
* -1 byte ([@Arnauld](https://codegolf.stackexchange.com/questions/195155/interpret-numbers-very-literally/195187?noredirect=1#comment464518_195187)): replace `'1000'` with `[1e3]`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~106~~ ~~105~~ ~~100~~ 107 bytes
```
f=lambda n:n/T and f(n/T)+`T`+f(n%T)or(n>=H)*`n/H*T+H`+'0'[:n%10>0<n%H>19].join(`n%H`)*(n%H>0)
H=100;T=1000
```
[Try it online!](https://tio.run/##TZHBboMwEETP5St8QbYBNWsbSKCFMx/ALYpkogiVql0ikku/nq7BhV7GM/NW1oLvP8@PEfU899VX9329dQxLPLSswxvrBTkZ29bGZMNWjpPAumpkZPHQRG3c2JgDP5cYKqjhHcOmVsXl9XMcUFhKVkbClSCDplIAb61TmPtxYpg82IDsLFTCuOIyYUKBs7B4DQnX4Oulp2ONuUv5OmXIazArUMrPKX/fgl2xjWiT@go0iYF06zMHXAmGJIVsJ/l@jeMpSQa5X26j/zqK@y6wit9pgX8MNui@TRSnI@WEF9Sc4Oggl5cyeLlPAz7pl9EzyEWq6hHMvw "Python 2 – Try It Online")
Saved 5 bytes adapting the `.join` approach of [randomdude999's](https://codegolf.stackexchange.com/a/195161/69880) answer; lost 7 bytes fixing a bug :).
] |
[Question]
[
Given an ordered list of same-case letter strings (a-z XOR A-Z) where each string is preceded by 0 or more space ( ) characters, output the same list but with the strings sorted at each level of indentation. Indentation depths under different parents count as distinct lists for sorting purposes.
## Example
If your input is:
```
bdellium
fox
hound
alien
aisle
wasabi
elf
alien
horseradish
xeno
irk
wren
tsunami
djinn
zebra
```
your output should be
```
aisle
horseradish
xeno
wasabi
alien
elf
bdellium
alien
fox
hound
djinn
zebra
irk
tsunami
wren
```
If you like, think of it like a directory listing, and you need to sort the names within each directory.
## Minutiae
* An item may be indented by any number of spaces. If it is indented by the same number of spaces as the previous item it belongs in the same sort hierarchy as the previous item. If it is indented by more spaces it is the start of a new sub-hierarchy.
* If a line is indented by *fewer* spaces than the line above it, it links up to the closest sub group above it with the same # or fewer spaces before it (like horseradish in the above example, which links onto the wasabi group above it because wasabi is the first item above it to not have more spaces than horseradish)
* You must preserve the indenting level of each input item in your output
* Tabs in the output are disallowed
* The first line of the input will never be indented
* Your program must handle at least one of all-uppercase and all-lowercase strings; it doesn't have to handle both.
## Scoring
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer which uses the fewest bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 117 bytes
```
lambda S:[s[-1]for s in sorted(reduce(lambda t,s:t+[[v for v in t[-1]if v.count(' ')<s.count(' ')]+[s]],S,[[]]))[1:]]
```
[Try it online!](https://tio.run/##bYzNboMwEITP5SlWuRgUGik9ouYBeuqBo@ODiY3Y1KyRf0jal6e4DlIO3dPM7DczfYfB0tvSn86LkWOnJLQN9/z1KHrrwAMSeOuCVqXTKl50@aBC7Zuw53yGxM2JC6mFPcyHi40USgasevdPRuy5F6Jua86FqCp@bIRY2hMvXlintDEYR1YDg3XynsWwdlWW0qCmJCV6o3N2k152yOp1ANbTps/5E502nNdOKvTD9r1rsn8tdF8pu7kMBx9JjpikuiLRxgP86M5JVoiimBxSgN0HTTE0u4dlZ2KHq0Uq2ypHG/cZw/9gv6LV8gs "Python 2 – Try It Online")
Takes as input a list of strings; and outputs a list of strings, sorted as required.
The idea is to turn each element into a list which contains the "absolute path" as a list; and then let Python handle the sorting. E.g. if the input is:
```
[
'a',
' c',
' d',
' b'
]
```
Then via the `reduce()`, we convert to a list of lists:
```
[
['a'],
['a',' c'],
['a',' c', ' d'],
['a',' b']
]
```
which gets sorted as:
```
[
['a'],
['a',' b']
['a',' c'],
['a',' c', ' d'],
]
```
and then output the last element of each list in the list-of-lists to get:
```
[
'a',
' b'
' c',
' d',
]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 31 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous prefix lambda, takes and returns list of strings.
```
{⍵[⍋{1=≢⍵:⍺⋄⍵}⍀↑' '(,⊂⍨⊣=,)¨⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79boR73d1Ya2jzoXATlWj3p3PepuAbJqH/U2PGqbqK6grqHzqKvpUe@KR12LbXU0D60ASsbW/k971DbhUW/fo76pnv6PupoPrTcGqgbygoOcgWSIh2fwf6BAmoJ6UkpqTk5maS7QJAWFtPwKMJ2RX5qXAmYl5mSm5gFZiZnFOalgkfLE4sSkTDBTQSE1Jw3KgikEaS4qTi1KTMkszoDKVaTm5QOZmUXZQLK8CKyupLg0LzEXZE5KVmZeHlSlgkJValJRojoA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` "dfn"; `⍵` is argument
`⍵[`…`]` index the argument with the following indices:
`' '(`…`)¨⍵` apply the following tacit function to each string with space as left argument:
`,` concatenate the space to the string
`⊣=` Boolean list indicating where the space is equal to each character that
`,⊂⍨` use that to partition (begin part where true) the concatenation of space and string
`↑` mix list of lists of strings into matrix of strings
`{`…`}⍀` vertical cumulative reduction by this "dfn"; `⍺` and `⍵` are upper and lower args:
`≢⍵` the length of the lower string
`1=` is that equal to 1? (i.e. is there nothing but the single space there?)
`:⍺` if so, return the upper argument
`⋄⍵` else, return the lower argument
`⍋` grade up (find indices which will sort that)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 47 bytes
```
+-1m`(?<=^\2(\S+).*?¶( *))
$1
O$`
$L$&
\S+
```
[Try it online!](https://tio.run/##JYs9DsIwDEZ3n8JDhPojkMoM6gWQGBhYKlRXcVVDkkpJKyoOxgG4WAhl@Z7t58/zJI6qGMttZdusPhxvzT5rLmW@K@rPO8MizxFUhXBWLaiT2kCSCBhjp9kYmS0g9uOSchhnpxPJCDsgCYbT9qRAnaQBkU2/8v/wK/jAnrSEYb0v7EYQ/4CrT34KsyMroO/i3OoRX9x5@gI "Retina – Try It Online") Note: Several lines have trailing spaces. Explanation:
```
+-1m`(?<=^\2(\S+).*?¶( *))
$1
```
The first step is to insert each word into following lines at the same indentation. For example, with the lines `aisle`, `wasabi` and `elf` the resulting lines are `aisle`, `aisle wasabi` and `aisle wasabi elf`. I discovered this regex by trial and error so there may be edge cases with it.
```
O$`
$L$&
```
We can now sort the lines case-insensitively.
```
\S+
```
Delete all of the inserted words.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~120 83 81 63 54 37 47~~ 42 bytes
*-5 bytes thanks to nwellnhof*
```
{my@a;.sort:{@a[+.comb(' ')..*+1]=$_;~@a}}
```
[Try it online!](https://tio.run/##bY5BC8IwDIXv/RVhiG4KBS8eHML@h4qkLsNom0rr0Cn612edBy9e3kvyvgc5U7CL3nUwbmAF/cN1FZY6@nBZPipcz/TeO5NPYFJoPZ3Nt6vRrnxV@Hz2pYrYQZNnpiZruXUKoPG3pAffSp0cLZMo5GgpbVeMaDgNAGSbwb/ApxAiBaw5Hob7jcQrDid1DSm/xFbQsaqPLDLkAHcyATNtWSgW@uhZ8mwjWaF@XyXyrjCp@cv1bw "Perl 6 – Try It Online")
This uses [Chas Brown's method](https://codegolf.stackexchange.com/a/171009/76162). An anonymous code block that takes a list of lines and returns a list of lines.
### Explanation:
```
{ } # Anonymous code block
my@a; # Declare a local list
.sort # Sort the given list of lines
:{ } # By converting each line to:
@a[+.comb(' ')..*+1]=$_; # Set the element at that indentation level onwards to that line
~@a # And return the list coerced to a string
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~112~~ 101 bytes
```
import StdEnv
f=flatten
?e=[0\\' '<-e]
$[h:t]#(a,b)=span(\u= ?u> ?h)t
=sort[[h:f($a)]: $b]
$e=[]
```
#
```
f o$
```
[Try it online!](https://tio.run/##TZC9bsMwDIR3PwWBGLANJEDnoGqWdijQLaOtgbapWK1MBfpp0j58XQWO6278jrwDjp0h5Gm0fTQEI2qe9Hi2LsAx9C/8mSmhDIZAnB1I1A9NU0DxuCOZ5fWwD3JT4rathD8jl00UcIhPcBiqkAmfQup0o8ocK7mHvE2eFCGnY0AXsg2oyF3QlkGAApsnxQen@eSTUNdF25MxOo6F3EJdACh7XcbBRu4XQKOJZ0DtDS36BT22eiEAMmqFf6ZbnPPksNd@WC@uxHYm7T7m4eIWT/CRcbyH9@@aeTUCfFPrsJAyS8XS84xm8lD@1b23rKafLq1Pftq9vk3PX7fALkH7Cw "Clean – Try It Online")
Anonymous function `:: [[Char]] -> [[Char]]` which wraps `$ :: [[Char]] -> [[[Char]]]` into the right output format. `$` groups the strings into "more spaces than" and "everything else afterwards", recurses over each group and sorts when they're adjoined. At each step, the list being sorted looks like:
```
[[head-of-group-1,child-1,child-2..],[head-of-group-2,child-1,child-2..]..]
```
# [Clean](https://github.com/Ourous/curated-clean-linux), 127 bytes
```
import StdEnv
$l=[x++y\\z<- ?(map(span((>)'!'))l),(x,y)<-z]
?[h:t]#(a,b)=span(\(u,_)=u>fst h)t
=sort[[h:flatten(?a)]: ?b]
?e=[]
```
[Try it online!](https://tio.run/##TZDBbsIwEETv@YqtQIotwg8gTC7toVJvHI1VbRKHuHU2ke2UwMc3NYWU3vbtzow0W1qNNLVdNVgNLRqaTNt3LsA@VC/0lSytkONqdT4cLts15KzFnvkeibEdT59Szi3P2Jid@XZ9UUkum01QC4ZZwcWv7MCG7J2LYVf7AA0PifAxXUZdbTEETSxHrjaQF9GthVTTPqALyQLqgcpgOgIBy4g@OENHH0nKtKi0tWZoU5WBTAHqbpzHphuomgGt0XQDNN7qeX9Cj4WZCUDb@gH/TNc457XDyvjmoRg1dTcy7vM2nNzsCX4gbO/h1YchehgBLrpwmCqVCLg@wBrSHthf13tLPn2X8Xz00/r1bXo@XwPLCMUP "Clean – Try It Online")
Defines the function `$ :: [[Char]] -> [[Char]]` which separates the strings into tuples in the form `(spaces, letters)` which are recursively sorted by the helper function `? :: [([Char],[Char])] -> [[([Char],[Char])]]`.
Explained:
```
$ list // the function $ of the list
= [ // is
spaces ++ letters // the spaces joined with the letters
\\ sublist <- ? ( // from each sublist in the application of ? to
map ( // the application of
span ((>)'!') // a function separating spaces and letters
) list // to every element in the list
)
, (spaces, letters) <- sublist // the spaces and letters from the sublist
]
? [head: tail] // in the function ? of the head and tail of the input
# (group, others) // let the current group and the others equal
= span ( // the result of separating until ... is false
\(u, _) = u > // only elements where there are more spaces
fst head // than in the head of the input
) tail // the tail of the input
= sort [
[head // prepend the head of the input to
: flatten (?group) // the flat application of ? to the first group
] // and prepend this to
: ?others // the application of ? to the other group(s)
]
? empty = [] // match the empty list
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 23 bytes
```
jeMtSuaG+f</Td/HdeGHQ]Y
```
[Try it here!](https://pyth.herokuapp.com/?code=jeMtSuaG%2Bf%3C%2FTd%2FHdeGHQ%5DY&input=%5B%27bdellium%27%2C+%27++fox%27%2C+%27++hound%27%2C+%27++alien%27%2C+%27aisle%27%2C+%27++wasabi%27%2C+%27++++elf%27%2C+%27++++alien%27%2C+%27++horseradish%27%2C+%27++++xeno%27%2C+%27irk%27%2C+%27wren%27%2C+%27tsunami%27%2C+%27djinn%27%2C+%27++++++zebra%27%5D&debug=0)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~114~~ ~~100~~ ~~92~~ 88 bytes
```
x=>x.map(y=>a=a.split(/ */.exec(y)[0]||a)[0]+y,a="_").sort().map(x=>/ *\w+$/.exec(x)[0])
```
[Try it online!](https://tio.run/##LY/RbsMgDEXf@QpU7QHWju69oj@yVYsTnNUtgQgnC5n67xlJ9@Jj@95ryTf4AW4S9cNbiA6X1i7ZnrPpoFezPYMFw72nQR3l69FgxkbN@uP98njAiv18ALv72mnDMQ1Kb7lyoLg/p/3LfyKvVr2cmhg4ejQ@fqtWVbVD72nshJRtzKVe4xhcIXjCIIDYY5kmYKipNFKibzc@DWsgMSZwxNdtnzFEQekuplT0gccAHQl3oxA2XcpfrBNUz58qUWl9Wv4A "JavaScript (Node.js) – Try It Online")
Similar approach to Chas Brown's Python answer, but using regular expressions instead.
## Explanation
```
x => x.map( //
y => a = a.split( // Renders the indentation paths
/ */.exec(y)[0] // Checks the indentation level
|| a // If this is the top level, go to root
)[0] + y, // Appends the child to the parent
a = "_" // At first the cursor is at the root
) //
.sort() // Sorts the indentation paths
.map( //
x => / *\w+$/.exec(x)[0] // Extracts only the last level of the path
) //
```
[Answer]
# [K4](https://kx.com/download/), 51 bytes
**Solution:**
```
{,/(1#'r),'.z.s@'1_'r:(w_x)@<x@w:&s=&/s:+/'" "=/:x}
```
**Example:**
```
q)k){,/(1#'r),'.z.s@'1_'r:(w_x)@<x@w:&s=&/s:+/'" "=/:x}("bdellium";" fox";" hound";" alien";"aisle";" wasabi";" elf";" alien";" horseradish";" xeno";"irk";"wren";"tsunami";"djinn";" zebra")
"aisle"
" horseradish"
" xeno"
" wasabi"
" alien"
" elf"
"bdellium"
" alien"
" fox"
" hound"
"djinn"
" zebra"
"irk"
"tsunami"
"wren"
```
**Assumptions:**
a. That each hierarchy will start with the lowest level, i.e. you will not get:
```
bdellium
fox
hound
alien
```
**Explanation:**
```
{,/(1#'r),'.z.s@'1_'r:(w_x)@<x@w:&s=&/s:+/'" "=/:x} / the solution
{ } / lambda function, implicit x
" "=/:x / " " equal to each right (/:) x
+/' / sum up each
s: / save as s
&/ / find the minimum (ie highest level)
s= / is s equal to the minimum?
& / indices where true
w: / save as w
x@ / index into x at these indices
< / return indices to sort ascending
@ / index into
( ) / do this together
w_x / cut x at indices w
r: / save as r
1_' / drop first from each r
.z.s@ / apply recurse (.z.s)
,' / join each both
( ) / do this together
1#'r / take first from each r
,/ / flatten
```
[Answer]
# Perl 5, 166 bytes
```
sub f{my$p=shift;my@r;while(@i){$i[0]=~/\S/;$c=$-[0];if($p<$c){$r[-1].=$_ for f($c)}elsif($p>$c){last}else{push@r,shift@i}}sort@r}push@i,$_ while<>;print sort@{[f 0]}
```
Ungolfed (sort of):
```
sub f {
my $p = shift;
my @r;
while(@i) {
$i[0] =~ /\S/;
$c = $-[0];
if($p < $c) {
$r[-1] .= $_ for f($c)
} elsif ($p > $c) {
last
} else {
push @r, shift @i
}
}
sort @r
}
push @i, $_ while <>;
print sort@{[f 0]}
```
It's a pretty straightforward recursive implementation. We check the indentation level by searching for the first non-space character (`/\S/`) and getting its index (`$-[0]`). Unfortunately, we actually have to *declare* a handful of variables that are used in the recursion, or else they'll be implicitly global and the recursion won't work correctly.
] |
[Question]
[
Help! I seem to have an annoying echo in some of my arrays, and I'd like to get rid of it. When this occurs, the original array repeats itself somewhere in the middle causing the values to be added to each other.
For example, the array `[ 422, 375, 527, 375, 859, 451, 754, 451 ]` contains an echo of itself like so:
```
[ 422, 375, 527, 375, 859, 451, 754, 451 ] <-- array with echo (input)
[ 422, 375, 105, 0, 754, 451 ] <-- original array (output)
[ 422, 375, 105, 0, 754, 451 ] <-- echo of original array
```
Example 2:
```
[ 321, 526, 1072, 899, 6563, 798, 7038, 3302, 3032, 3478, 1806, 601 ] <-- input
[ 321, 526, 751, 373, 5812, 425, 1226, 2877, 1806, 601 ] <-- output
[ 321, 526, 751, 373, 5812, 425, 1226, 2877, 1806, 601 ]
```
**It's also possible that there is no echo in the array, in which case return the original array:**
Example 3:
```
[ 623, 533, 494, 382 ] <-- input
[ 623, 533, 494, 382 ] <-- output
```
## Challenge:
Given an array that may contain an echo, remove it and return the array without an echo.
### Input:
* An array, list, delimited string, punched cards or your platform-suitable equivalent, containing three or more integers, in the range of \$0\leq n\lt10000\$ with at least one element \$\gt 0\$.
* The echo cannot begin at the first or after the last element.
* The echo will only occur once or not at all within the input.
### Output:
* An array, list, etc of integers \$0\leq n\lt10000\$, with the echo removed.
* If there is no echo, return the original array.
### Rules and scoring:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes for each language wins.
* [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) and [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) apply.
* [Loopholes forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) (of course).
* Please provide link with a test for your code ([TIO.run](https://tio.run/), etc).
* A clear explanation for your answer is highly recommended.
### Test cases:
**With echo:**
```
[ 422, 375, 527, 375, 859, 451, 754, 451 ]
[ 422, 375, 105, 0, 754, 451 ]
[ 321, 526, 1072, 899, 6563, 798, 7038, 3302, 3032, 3478, 1806, 601 ]
[ 321, 526, 751, 373, 5812, 425, 1226, 2877, 1806, 601 ]
[ 4330, 3748, 363, 135, 2758, 3299, 1674, 1336, 4834, 2486, 4087, 1099, 4098, 4942, 2159, 460, 4400, 4106, 1216, 3257, 1638, 2848, 3616, 3554, 1605, 490, 1308, 2773, 3322, 3284, 4037, 7109, 4171, 5349, 2675, 3056, 4702, 4229, 1726, 5423, 6039, 8076, 6047, 7088, 9437, 4894, 1946, 7501, 5331, 3625, 5810, 6289, 2858, 6610, 4063, 5565, 2200, 3493, 4573, 4906, 3585, 4147, 3748, 3488, 5625, 6173, 3842, 5671, 2555, 390, 589, 3553, 3989, 4948, 2990, 4495, 2735, 1486, 3101, 1225, 2409, 2553, 4651, 10, 2994, 509, 3960, 1710, 2185, 1800, 1584, 301, 110, 969, 3065, 639, 3633, 3544, 4268 ]
[ 4330, 3748, 363, 135, 2758, 3299, 1674, 1336, 4834, 2486, 4087, 1099, 4098, 4942, 2159, 460, 4400, 4106, 1216, 3257, 1638, 2848, 3616, 3554, 1605, 490, 1308, 2773, 3322, 3284, 4037, 2779, 423, 4986, 2540, 298, 1403, 2555, 390, 589, 3553, 3989, 4948, 2990, 4495, 2735, 1486, 3101, 1225, 2409, 2553, 4651, 10, 2994, 509, 3960, 1710, 2185, 1800, 1584, 301, 110, 969, 3065, 639, 3633, 3544, 4268 ]
[ 24, 12, 52, 125, 154, 3, 567, 198, 49, 382, 53, 911, 166, 18, 635, 213, 113, 718, 56, 811, 67, 94, 80, 241, 343, 548, 68, 481, 96, 79, 12, 226, 255, 200, 13, 456, 41 ]
[ 24, 12, 52, 125, 154, 3, 567, 198, 25, 370, 1, 786, 12, 15, 68, 15, 88, 348, 55, 25, 55, 79, 12, 226, 255, 200, 13, 456, 41 ]
[ 1, 3, 2 ]
[ 1, 2 ]
[ 0, 1, 3, 2, 0 ]
[ 0, 1, 2, 0 ]
```
**Without echo:**
```
[ 623, 533, 494, 382 ]
[ 623, 533, 494, 382 ]
[ 1141, 1198, 3106, 538, 3442, 4597, 4380, 3653, 1370, 3987, 1964, 4615, 1844, 5035, 2463, 6345, 4964, 4111, 5192, 8555, 5331, 3331, 4875, 6586, 5728, 4532, 5972, 2305, 3491, 6317, 2256, 2415, 5788, 4873, 6480, 2080, 5319, 4551, 6527, 5267, 4315, 2178, 2615, 5735, 5950, 6220, 7114, 6259, 5000, 4183, 6822, 6927, 7150, 8003, 5603, 3154, 8231, 5005, 5743, 6779, 4530, 4029, 5336, 6105, 4777, 6183, 6838, 5725, 6819, 8584, 3142, 3840, 3291, 4284, 2933, 4859, 2906, 5176, 2853, 2110, 2048, 4389, 4501, 2267, 2704, 431, 1495, 2712, 3008, 187, 3487, 630 ]
[ 1141, 1198, 3106, 538, 3442, 4597, 4380, 3653, 1370, 3987, 1964, 4615, 1844, 5035, 2463, 6345, 4964, 4111, 5192, 8555, 5331, 3331, 4875, 6586, 5728, 4532, 5972, 2305, 3491, 6317, 2256, 2415, 5788, 4873, 6480, 2080, 5319, 4551, 6527, 5267, 4315, 2178, 2615, 5735, 5950, 6220, 7114, 6259, 5000, 4183, 6822, 6927, 7150, 8003, 5603, 3154, 8231, 5005, 5743, 6779, 4530, 4029, 5336, 6105, 4777, 6183, 6838, 5725, 6819, 8584, 3142, 3840, 3291, 4284, 2933, 4859, 2906, 5176, 2853, 2110, 2048, 4389, 4501, 2267, 2704, 431, 1495, 2712, 3008, 187, 3487, 630 ]
[ 4791, 1647, 480, 3994, 1507, 99, 61, 3245, 2932, 8358, 6618, 1083, 5391, 3498, 4865, 1441, 3729, 5322, 5371, 6271, 2392, 1649, 5553, 9126, 3945, 2179, 3672, 2201, 4433, 5473, 4924, 6585, 6407, 3862, 6505, 1530, 5293, 4792, 6419, 6739, 3258, 3839, 3891, 7599, 2576, 5969, 5659, 6077, 5189, 1325, 4490, 5694, 6567, 6367, 5724, 5756, 6450, 5863, 4360, 2697, 3100, 3779, 4040, 4653, 1755, 3109, 2741, 3269 ]
[ 4791, 1647, 480, 3994, 1507, 99, 61, 3245, 2932, 8358, 6618, 1083, 5391, 3498, 4865, 1441, 3729, 5322, 5371, 6271, 2392, 1649, 5553, 9126, 3945, 2179, 3672, 2201, 4433, 5473, 4924, 6585, 6407, 3862, 6505, 1530, 5293, 4792, 6419, 6739, 3258, 3839, 3891, 7599, 2576, 5969, 5659, 6077, 5189, 1325, 4490, 5694, 6567, 6367, 5724, 5756, 6450, 5863, 4360, 2697, 3100, 3779, 4040, 4653, 1755, 3109, 2741, 3269 ]
[ 235, 121, 52, 1249, 154, 26, 5672, 1975, 482, 3817, 532, 9104, 1661, 171, 6347, 2124, 1122, 7175, 558, 8101, 667, 934, 798, 2404, 3424, 5479, 672, 4808, 956, 789, 123, 2255, 2549, 200, 126, 4562, 41 ]
[ 235, 121, 52, 1249, 154, 26, 5672, 1975, 482, 3817, 532, 9104, 1661, 171, 6347, 2124, 1122, 7175, 558, 8101, 667, 934, 798, 2404, 3424, 5479, 672, 4808, 956, 789, 123, 2255, 2549, 200, 126, 4562, 41 ]
[ 1, 1, 1, 1, 1 ]
[ 1, 1, 1, 1, 1 ]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
t"GX@WQB&Y-~?w]x
```
[Try it online!](https://tio.run/##y00syfn/v0TJPcIhPNBJLVK3zr48tuL//2gFEyMjHQVjc1MdBVMjcyjLwtRSR8HE1FBHwdzUBMxSiAUA) Or [verify all test cases](https://tio.run/##RZXLih1HDIb3forGi6xOoKSSVFWrmBDIOhCwHTNg422yG4hXfvWJvr8nCQxNTR@VLv9F/deX5z9fPr88v/31w7v3v/38w8cfv//099O3l6fx9cMvf3z7/eXTFe6Pa658XOnr9bTzPK5Ie1wrQ6fr6c2na7oRVY/Lxupb@3RYZc2OO7sfY/ZzzkHGMXnG6je2R9@pcWeJDqBOEMtdm13SV/K/k9JqBa9n34o9@@yxOY@9qE1MDCrGia7ipn6r00YMnkZBcytSJpeK1nzfRfU@Gc1qJGkG9QYha01mECodT6XZCVaXJfECghl99gKqOZLOFjM3lHS/QCjDJzPPfrPH0vxBnrG7yglyxj60cKIAeijzNBp06NjWXZVvam3QqeJNDEDLLFBzxu12JizReY@i4TZjWaz/kA7qpjKXacYNdllM5JnMAgxJvQaHiMO5MQaXcwTvEVcwZuJkGn2bk9cDjFx3o5AP/fbNnjL5aR44agx5bbTY0uBNAvRUJn47RfBgwgLAlgntZECH15aOXE3ckuQAJwangr8QqB0oig2X2xb49vHYEPNl6oUa4OSdgvowv0yGAPStAas64iBFKb0npeHgRsbCBtSLjYQOilhAZ2igoQGblGY0LQ1GUwFDGgXO@0edCbj/fVxDb4osOUUuVfcdaBbCi36mBJ@yX0Br5EFgcyOPSrlsDVGKG06BZJkYCNEjEwbSajjkCcWYAbAd7C6RvEpUz9jAVIkQcjmGFMJdHFtOvNXiFMTA31AUVaibC0F2BioGffrgmdO0fJBPaSX1xtEs3HJjoXjdGeg5T8omPqDNgjPrIMe9CTb5N6TWcRmZ@JYdoBbPKdVsZ6K@pczBrbXUyZTpsHZqJbULwWetxfnOD/KNAGhs@t@3oi0kvRhabSCmleJHbGrNugybxopom0O8POAD2zWD6gENunDwhfSCZu3VjaZ9O7Rpl6xOZ/NWT6uT0AotHElAWycHika50OlQ3m1B83zdNeQbW9ojRRMpwkreR3tz3aAAbk45ybVNJnLpkvyqbXCk@XniplCWlkScwSKAo30kieOp0v6qoMe5cUoloJvISNe@W1SpMLlPa8L1Ddk676PP19FGAtzUVum1SfyAvDSZdEJb6BuQdVS9BCDPJhV7LIRbkVqQmCQmq8wLm7X79EWTXAZkx225pa2qL4cvIdYX/nX8/3/X0z8).
### Explanation
Polynomial division for the win!
```
t % Implicit input. Duplicate
" % For each (do the following as many times as input length)
G % Push input again. This will be the output if no solution exists
X@ % Push current iteration index, k
WQB % 2 raised to that, add 1, convert to binary. Gives [1 0 ... 0 1] (k-1 zeros)
&Y- % Two-output polynomial division (deconvolution). Gives quotient and remainder
~ % Logical negate: transforms zeros into 1, nonzeros into 0
? % If all values are nonzero (i.e. if remainder was all zeros): solution found
w % Swap. This moves the copy of the input to top (to be deleted)
] % End
x % Delete. This deletes the quotient if it was not a solution, or else deletes
% the copy of the input
% End (implicit). Since it is guaranteed that at most one solution exists, at this
% point the stack contains either the solution or the input
% Implicit display
```
[Answer]
# [Haskell](https://www.haskell.org/), 167 bytes
First it is important to notice that if there is an echo present, then the input array is a convolution of another array with some array of the form `[1,1],[1,0,1],[1,0,0,1],...`.
This means we just have to check this for all these arrays. But discrete convolution/deconvolution is the same as polynomial multiplication/long division, so this is just an implementation using polynomials, each time returning the quotient if possible.
One trick that shortened the whole thing a little bit was in addition to the arrays above also checking for `[1]` as a base case, because if no other array works, the deconvolution with `[1]` will work and will return the original polynomial.
```
import Math.Polynomial
import Data.Ratio
p=poly LE
c z=last[polyCoeffs LE q|k<-zipWith const[p(take k(1:repeat 0)++[1])|k<-[0..]]z,(q,r)<-[quotRemPoly(p z)k],r==zero]
```
[Try it online!](https://tio.run/##TVGxjtswDN39FRxjnJuTKImSgvqWtlsLFLd0CDwogQ8x7NiOow41@u8p6R7QLgT9@PjeE31J974dhseju87TkuFbypf992n4NU7XLg3FO/w55bR/TbmbirmeeQxfvxRnWOsh3fNRgE9T@/Z2Zxhuv/uPH9Zu/tHlC5ynUQi7nPoW@p0@LO3cpgyqfHo66qYU7lHt902zVrtbtZT8efs55df2Kil2M6xl31RLXa/tMjXwSFDDESzi4bDlGdNQgfGuAof@vQsuVmCdrsA7u3XQFKe/iz7q/zc1Wd6yQfFqjEzWTjEQWYB436BlPYwGWdW4wChprloFw44mCsfGIBLETG2tIB6jTBGlekYIpaKJuFnK1DlWiBpJnDcX7Rk35JmDqJhvrREX67naiJyOXGAmWcloAqEgSnydUXKBKEwvLmS1vMEb0URJbsLWh7jdRV6IzrO7iyR5SI5GyrOy04F7zWuSIYoyxc2deEpGqvOSx3lH4uWEE0jcDXGPFCWhVnJXL@@yynJvSV6tvXPbVDL47WK8wP@oKK6pG/lHzUs3ZtidIcFzDamEl5d/2EmwU1k8/gA "Haskell – Try It Online")
[Answer]
# [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript), ~~211~~ ~~171~~ 145 bytes
```
s=>{for(n=x=0,y=s.length;++x<y/2&!n;)for(n=s.slice(i=0,x);i+x<y-x&&n;)n=(n[i+x]=s[i+x]-n[i++])<0?0:n;return n&&n.slice(1-x)+''==s.slice(1-x)?n:s}
```
[Try it online](https://tio.run/##7VjJbhtHED1rvqKtg0yClNJL9Saa8cn@gRxpHgiGshkIQ5ukBNqGv12p93qk6BAgviUODEjNZk91La/W4R@r@9Vhvd9@PF7el4dP84fD/NevN7v9qJ@f5nb6eX64ut30748fZpPJ6dXnX/zFi342bgSHq8Ptdr0ZbZXwNJ5tQXB5urhQgn4@6hd6sJwf@HGJb5Pl@JV9ba/72X5zvNv3plfagYe7PI0nL1/On5ji4HV/ffj2MOu6m7t@fdzuerPa71ef33y6W90eRqep@TI2X7sz1caM7ld7szZzY2dm/cqcHrU268lkbLqzs@2NGX1ZrJfmxdyc9HOsZ2dNj9lZN@ye7s3nXx45dN@6rgP34@ZwPKiExWIRvJua6NPUOJv91JRapybFFKYm16KLDbqGYPVZsAGrZD1xxeqdZN1y2hnzjE2OugtZ78filFx8VGqPR77k/PzmcrrozEI8mOaI@3nYlahaCDjlKNw1MX/ROquLffYczDrzr9vTUU3lj0sCURDtgl7yOeK7h0YuZcFx0KtSgu69FOxtAUsLGrFQWKqoVO@ISFK2Iharg1TnXQLLiEsJlvnShPI8AhyXAJVUC3kWJBnWhEAslR6SgjLIKhaMM0wPonufAHWwEZplS@s9tM8wP4oPMDzoSbGZIAj42KJSqoCnlAoVqhBJS84BgCbAqIiqVskXyCpAJyWciAVoMSag5mGuqhPgZ2iuptC4ArOc5CekBXIjOSdHGwuwiwkW@RhhC2CIkKfggKJirxgDl1oJb6Wv4DFHnwQHvdXlOBdg5HlXEkID@upNtTLiUajwkWKIYwcVNT5wEgF0ICc8qwnEFhYmAKhhAnWiwB0@lSHef8hA0nPI8PQVlPFRiBLyTEl@PGcMxcUDBUSUxyfYAZfAEEOUE2WEHWj0uDpISMAXsU3fOXgRS3aMVs0dUIEB9C5QVZAhAr6AIoFtcVATRayp0AoQUGR@OGYH/D4UsO9QFach47KyLanRu9gE4rO0pEImNmp8focCA1qO8nzTBxn4@KCJxDMt4e1xO@L3gSghfGJgDAkxbZR/c95uqAwn9CiMCwzryGIvCHyJFfUoAOCQInMJxmvQEZAEXyfHGBEGEN0lyLoUhJFPGgd3RVfRXBjGQ0XjKgUVM0XAGbOH5yKajAoHZgEZpLUMDg8OqeKBmTocfHKhp5FUSRgIFmsMjt0QAZ7YI7Ux0RbHgEL78qlxgM6xRlZVj/aomGCPpI@25XsB/4KkTdWz7oNeE4PRgTUwWIqHRXqLnBGOqSV2DKzR6ASRhSexG0tGO0wDfyCvCDCcoH9pOefgC63LlgUMiLFw@EqPsu971vfoMlssPOWZpd4iFtWD1AHJ64mDz1aIBmpEqxeO3d2yr2cGMTQLQ7D9jJOfcfIPcTKMcgvJlSVcOMswDDjQRIt6jdESLvVwu6oGV4dhjAFPW1irKss5u0NJ7GQs8LkB49ksMKIkz0ElIGRUJJ7G1kZQa0OV5kY2KIaJh3EigZ2ijUao@4mjURLoGEqCA6NlC4BDoucolSElCSBPmU3Pc6oo3JfK2buyvwLgyB6pExnoLRwYHQB2Aa4TTgUxVUpPBBGrOhYpkhG8SSLbPRJFAhqzT0g1zUDOOAwZC4dLS7vMGYFDqc9ETC8Mc9FPt/zH3PI4IXFSay9P2AAtFgm@MBAeV1H6pDC/UdtY@KqzHDHhOL6BaC1FzjoOMg7eyI4viYCjcApMHJow8/LVTsdBVA6hbZKJoGd84HUEtmZCgwHCt8kl8i2H8wsU1AHGPxuh/h@2PJYyxxFr@Hsayp4dLbvlrONPA1c3u/2b1frD6PHXitGWP0@sd/1hd7u5ut29Hz3//eLTaLuwy/F0u3DL8evz3@7W683hcH59/na1vb3bb8yludnd9b9fv@vPJwPx5Pxdvzl93KyPm3bOy7Pum/6fPfwJ)
40 bytes from [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
Another 26 bytes from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
My first code golf answer, invalidates potential offsets, and returns either the original or the new array dependent on what it finds.
If anyone knows how to make it shorter pls let me know, seems like a fun game.
[Answer]
## Haskell, ~~112~~ ~~111~~ 110 bytes
```
l=length
(!)=splitAt
f a=last$a:[x|i<-[1..l a],let (h,t)=i!a;o=h++zipWith(-)t o;(x,y)=l t!o,all(>=0)o,sum y<1]
```
[Try it online!](https://tio.run/##TY7LasMwEEX3@YoJdCGRidHD8qOOCv2ArrswpmjhxKLyg1qFpPTf3XHTNoXhMnO49zKdm1/bEJYl2NAOp9ht2JbbeQo@PsbqCM4GN8c7d1@fP/1hX8skCeAaDG0E1mHk1m9dNdput/vw07OPHdvzCGPFznjhNkDcjuhCYA9W8BHn9x4uB9ksvfMDWOjd9PQCbHrzQ4QEjhzqDQDUkCqFoHODYFT@sxWmREiNRMhN@r1Bg1e7VnJ1ZghS5JQsSrJmJtPkLQsSoUm1Fmur0KumORFZCMpk4tZEPRRSf7fAX4QgVnrFmSJkNEla0i@6UP8bbgNNs3wB "Haskell – Try It Online")
```
f a=
i<-[1..l a] -- for all indices 'i' of the input array 'a'
(h,t)=i!a -- split 'a' at 'i' into 'h' and 't'
-- e.g. a: [1,2,3,4], i: 1 -> h: [1], t:[2,3,4]
o= -- calculate the original array by
h++ -- prepended 'h' to
zipWith(-)t o -- the (element-wise) difference of
-- 't' and itself
(x,y)=l t!o -- split 'o' at position <length of t>
--
-- example:
-- a: [0,1,3,2,0]
-- h: [0]
-- t: [1,3,2,0]
-- now
-- o: [0,1,2,0,0]
-- x: [0,1,2,0]
-- y: [0]
--
, -- 'o' is valid, if
all(>=0)o -- all elements of 'o' are not negative
,sum y<1 -- and 'y' is all zeros
[x| ] -- keep 'x' (a valid echo array) if 'o' is valid
last $ a :[ ] -- if there's no echo, the list of 'x's is empty
-- and 'a' is picked, else the last of the 'x's
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~131~~ ~~129~~ ~~120~~ ~~119~~ ~~102~~ ~~98~~ ~~97~~ ~~96~~ 95 bytes
```
(w=#;Do[(w=v/.#)&/@Thread[#==PadLeft[v=Array[x,L-d],L]+v~PadRight~L]~Solve~v,{d,L=Tr[1^#]}];w)&
```
[Try it online!](https://tio.run/##RZXbSmVHEIbv5yk2CEMmWYl9qKruZthgIMyVF0Myd2JgE00UMhkQcRJEX93U929JQNrea3XX4T/U@ny4v7n@fLi//e3w8mG3f/nm6/7k/U9fLvL/w@kPJ@/enp59urm7PlxdnOz3Hw9X59e/31887H@8uzv8c/H3dv791eV2fvndw3O@@/n2j5v75/PL51@@/Plw/fywPV5t5/tPdxf115PLp8v3X9@9ffl4d/vX/dm3H3anZ7vHN4/W2rbrw7edt/G6m762nXnddsNNu6ftzWNvlUOx7WoZeWmuPBUePY@tmUvpufZeCFg6q418UmfJO1EUxPI9WYyjXK09E7bh/G5ErDGMxz0v2ey5bzbZlzlIzRkrJLRlmaRVVRsZ1qywVvLVVoOQzqWgsjaPSfXcaaxGccIU8hWOjNFpQZjkeTL1DDAyLYEHCHTLfQuA6sWpbNByAkn1A4DcWqflnk9mGWrfiFNmZllGTJuLEpYFMBdF7pUCG2TMmlVFm@SaoBPBEyuA5h6g1mg3y@lwROXZipqbtFVt/Ie0kdcVOap6nGDnQUfNnV6AwcmX4HBisU@MwWUtwbvEFYxVcdIrdddG3GZg1HTXAvFQb97MLp1XfcFRYsjjSompDJ44QHdF4t0KDhc6DABMmVCOG3S0mMioqYajINlASYVSoR/Isy4YsgmVsw7gze2qRcRHVSmkAKaWIUgP8aPKDWA@1V9EnlgoUTrPRqnXuOE2MAH5bKKghSAGyFUkkMgAjUsyapYCLZmAIDqB8XzHltfHX9uu8CAI4V3EknLqWK0mqKilS@su4xmMmi@01SfKCJfBRhGbGGEFIEYV@CZm5D9DVQmF7KAztQJuXRhd@nhVp1abQBSOBnw0vCh0MzmO7NgqdSl4gT5hCLKQ1wdazAhkNOpshdV71dRBOaFZlLNGvXCrVUZJi2MEavblckgrUFaNPZPAy3EITOJPCI3V5GHOp@LANFi7FDMbHeUtRTZujaFKuvyGq13TKA0IPmMM9sf4IJ8IgMak/nkUczXJzoqmGohpmrQlMjVfm7zqlemQDod2yb8VHJcMqgb014RDG8jOKLa@GrFq0hbN2CGXU1mXdlKYnAzTqJECNG@8IGZEC5sNxrMqWO6vU4ZwZUp5hEgexVfI9UivjyMmYOtdJmqaIx21ZEreag4syb0vOzIoM0shjb7MQCMtJIFjp9DkCqPGPjFJOJhXceFNk26QJazKeBoQTV@Pqf1c@mwtzSKwdc2THJicL3DnVf7ssGaa/h5L2UP4sSanuGOg2zDXaMQj1hliLXBZmk/fMqmlwLUdHTc0T/XNaEOI5YVXs///9/T08i8 "Wolfram Language (Mathematica) – Try It Online")
−1 byte thanks to [attinat](https://codegolf.stackexchange.com/users/81203/attinat): we can write `L=Tr[1^#]` instead of `L=Length@#` when the argument is a list of numbers.
**Code explanation:** Iterate through the shrinkage `d` (difference between input and output lengths). For each output list length, construct a list of unknowns `v={x[1],x[2],...,x[L-d]}` and add it to itself left-padded and right-padded to length `L` (`PadLeft[v,L]+PadRight[v,L]`), then set this sum equal to the input list and solve for the unknowns `x[1]...x[L-d]`. Pick the shortest solution, which is the last one generated: just keep overwriting the variable `w` every time a solution is found.
Un-golfed version:
```
F = Function[A, (* A is the input list *)
Module[{L = Length[A], (* length of A *)
v, (* list of unknowns *)
x, (* unknowns in v *)
w = A}, (* variable for solution, defaults to A *)
Do[ (* loop over shrinkage: d = Length[A]-Length[output] *)
v = Array[x, L - d]; (* list of unknowns to be determined *)
(w = v /. #) & /@ (* overwrite w with every... *)
Solve[ (* ...solution of... *)
Thread[PadLeft[v,L]+PadRight[v,L]==A], (* ...v added to itself, left-padded and right-padded, equals A *)
v], (* solve for elements of v *)
{d, L}]; (* loop for shrinkage from 1 to L (the last case d=L is trivial) *)
w]]; (* return the last solution found *)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 24 bytes
```
ðsạ\FḣL_¥,+¥Ż⁹¡$µⱮLṪ⁼¥Ƈȯ
```
[Try it online!](https://tio.run/##LZS7jh1FEIZznsKBMxqpq7qquluWCB35DZYVEYnljIjM62RfAgILbWIhLgEWC8jBWYF4jT0vcvj@sXWkmTkz3VX13/rlN69efXe5PPz67eOfb796/vjHjy@@Pt21z093//x1vrk/vX16@v38288vHu/fnW/@Pt39e/vfL5fH@w/Pzq@/f/LFl0/Or3949nDLi6efPdye3/z08nzz4fT@9P5yuboK9zZmtvR53FfuFmltZuh@3a6GG1@rWZ/e1t6tskabe7XZx2pjdCr0wSXmarZ6teraGHyiZrCGDTay@Uz@ODWsZvBqVIs1onksnvqadOFrdKrHDm9umqd6i@hcjOLmVhRJ1hb9fR0N9C6Z2aonWzvFOx/nHEwojKyj7pht0oJKE1QjdvMC9ehJ/wkS@GC6Cd4MHyAZu60@hSnY29dqO6gSa9NsR8FUV6lhTOEQuay38kXlBdoq/kaHgMyCAQcGbQfkMhqDau7FyBbzE1lBj1SpMk2/oCGLcT2TSYGWFAcs3zZP8ATQvcXRFscQbeJzGIOZU8ghVNtpWGjLRKyPlrwdG3Ihg1fGGMjH34Sroc283sWizugFEwhJ1wyo9Fpo7Gp2GIQbbBoSiLvCK7ZhNhbcL5sw5G1bl0Jl6khBIDvb6INC02RDKFuau2q2jTPkM8ZnnmBhxsR/1I6FuhvRJgwYQgETnClBhYAZAg6hlSFRpjl33uupdZ6LPYgm9phPX81CiOk3ZLOUtwPuIzdyj4VulfLx7CIe@@2ChzKxFmJTDg@UBpg8qK9mcGOb4Ei8jy7RJRZgK1Epp@N1sUMfDI8VZRDRA2vAKorSIye2YBvlAQ9KLjlMaUXSUn5JqSZlsRtR9Dq2MVXulCe9Q7IFT4Qq@xGoRb0F@7Vd0WAdDoAajA8PqLmccVmsUsHiOdVyyNQkJRVhLA7eOSdPRz2oAxYAF/Otw00W8kF0xR/4SqNv8a8DxxWDNFJGZlBIvvOOraFd3fCDC5tPjABA/H043XTydB06U7Gh/5C2mIQlFUqptFJSs@MnvAP/jjr0RpPxMaAU6Et2YBvUi@ZShvDDmAdICMohy7pyONCT8nxQpLbMNnYcrCsiUtEZOTgA5ViZDO@WYl7BHGPhzEpIMxGZruNgUrTCZG8FzXVSLj2trdN4K8AQlMojJwnrOoSnyf@sVvgpVVuNSkxwQQR8ObFQQSLnBuaMQeC98DQ21/ksPTvCxOHuqTNGJ6RPwWfhEaBPv@vr/wE "Jelly – Try It Online")
A monadic link that takes and returns a list of integers. Technically, the successful results are nested in two further lists, but when run as a full program the implicit output to stdout ignores the redundant lists.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~113~~ ~~123~~ ~~128~~ ~~127~~ ~~123~~ 122 bytes
```
def f(a,i=1):
e=a[:i]
for v in a[i:-i]:e+=v-e[-i],
return i<=len(a)/2and(min(e)>=0<e[-i:]==a[-i:]and e or f(a,i+1))or a
```
[Try it online!](https://tio.run/##TVVdbxtHDHy2fsW@WarP6S6X3A8h6h9R9SA7p/gAW3JtOYgb5Le7nDmlCAyceXvcITkcUs/v54fTUT4@voyHcFjuh2mTVutFGDf77XraLcLh9BK@hekY9ttpfTvt1uPN5tvtuHVzWISX8fz2cgzT583jeFzuV3/K/vhl@TQdl@Pqr038DL/1buNg@O/fwhgckIFu0mrl9p6hz@Pr2e@vF1d3YYPvq8XVdAgz6obod6v1Jdz18RRenx@n87U7ufvsdTs7La7u/Wj7/eaduX8f3pH9v9Pz8u5mG3d/TEPgv5u71W5x9Qvx9DJ9/QSgr@eH8ONnGO8fTr@9ng6H1/Hs1hBe357C@M/b/vE14NJ03D/6@d/HHz@vP3nAp/15OeczzPkM03DvBAzIbIGM9shnu7japuHy50ziLcgQ8hAuBg9VYFYbgkm9WM36ENTcrZrSomuWBK/iALH6rdbdrVhxxNqbP2L2Z84RiDHjqdVPUot@p8QZJah7IJDCGZdT9phSDe8CzFSq4jj7NW3ZbdEGO7aK4PDRiJDa1cNIYsLFYVUjngkRk6QCSMOlgtykzUF5bqgtlWiAiYgX4VJrRhGkxf0RKTtA9bAAruAgq9tSwFWOhswqinYukX0FRaaSUXT2kxYrCVDgxOZRugJTW0cKXQuYjkTOCQkK@tGSZ1WkIVYDO6XgRCNIMytgTVCup5PRJmTupbC4hrKS1v@ZVsQ1IpfEGhu4s4KKxAy1gAZDPCcHHh22cwxeeie9nb1CxxJ7khPyTgJcUXAkvKsF@kG@ftOrNHzKHT1yDnGckKJrAycGojOR8K0XOEdUWECgywTpmKIdUlr4pWc/FdoFbFsmAYBq87HDKUEhlkxVGEWqqF2towu5gcNilGKNrBuS6QXhSmKayhqoVAX/JSuFQ5@U0LvUMRRk8tJHPrVBJ8XAllWBag3D4cGh3QwBegcTMFNFT6EoUcS1iq45AiIq8pSIp@XEEQXHhYPrc8lacEsSxk7KjICcrRu1JBFKTgobM2NxHpcG/AbNly5UO/y9N2C14OnAfqsJKvJbRFbcqpWZZCoT@jfOrUsV/NRaYc/4YN4ZABsN@be57Qm9cDVGzj8Y49xJZzu5jISqtoQ58llA2ykUidCmd5A5QD9CHqRGJRuQ6SzZxK0UuY8q5wGZ5RguW6kicirKuaQIOJwW/YCLDg0VNN0TQ6PzZSSBGBvlBwhvJVtWOCJQX64zLaDXMsatCIcuQzAeEl85ND1hdeSucxOpfIpEUJoqCDGdx1yUogKZihxzK2ifgfbEdphwLVREKQrCS@U0CVdto90613zn4IJe4/D5doF/RPssgd6U0TjlqrTSGb2QQjy9rRiQCukWNe4RjIlmTLwUDJrPHxc/BRPRbp2HrnL5cMFKJWN@IewWi53/Wj@/TMdz2P8yLj/jl9fFx38 "Python 2 – Try It Online")
1 byte thx to [TFeld](https://codegolf.stackexchange.com/users/38592/tfeld); and 1 byte thx to [Sebastian Kreft](https://codegolf.stackexchange.com/users/88102/sebastian-kreft).
On each call to `f`, we construct a potential echo of length `len(a)-i`. The first part is just the first `i` bytes of a; the remainder is calculated so that the 'echoed sum' will be correct for the 'overlapped' section of the echo sum (i.e., the echo-sum is correct up to `a[:-i]`).
Then the very short-cutted comparison, un-golfed, gives:
```
if i>=len(a)/2+1:
return a # because it can't be that short, so there is no echo
else:
if min(e)>=0 # all elements are non-negative
and e[-i:]==a[-i:]: # and the tails are the same
return e # it's a match!
else:
return f(a,i+1) # recurse
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 93 bytes
```
(b=#;Do[a=#;Do[a[[i+j]]-=a[[j]],{j,2k}];a/.{__?(#>=0&),0}:>(b=a~Drop~-i),{i,k=Tr[1^#]/2}];b)&
```
[Try it online!](https://tio.run/##PZLNTltBDIX3eYpISAjopYw9np9bFMqC7ovUXZSigEAERKlQuorCq6f@HFopmjvx2MfnHPtluX68f1muV3fL3cNsd3Q7Ozi/ep0vPz7z@erT02JxOvObf4fN06DP28X58uzz5ubm69HBxSwdHg9p@@XCS5fvV2@vv99PV8fDZjU8z368zeXnweJMveL2@HB3/Wd1v55Pvr@tfq0vTx4uT77dPb6eXW4mG1MdprmVYVq0fdx6GYepFRmmrVjctsNkk1VIqsNUUvOiPnpWLTV72tj9SNnPnBOAKXNa84j05DU1BYj5O12MVEole0Nthf8KotRmhLMXWc9@V@vcU2@0JscSDW00b6ISbKvDmiVOoZ@oVCALRRVm2vdNI14QJjUVYBL9EimtZSSEJ55Pp@wAzdsC3HAgm9@1YlROBWYNyW4k7BsGFdOM5OyRnlrIN3BS9y6jgWl9hMJoFZtTIGeBoDKMLs6qaqdXx51aiVjCtFIqrilynU5mRjB3KSGuI0us/Xfa6FsCuUpo7HhXKoq0FLRgQ6Gfm0PGyN09xpdxDHvHmBUTk5hJFniLgquGRxq1Vlke@Hqlqyw85ZEZuYeEBYq@GUQKRudA4m2sJCcUVgz0NYFOMcahtbNGinUIUL5AMc8cijA1tgOV5Hh4FNAre4GVsXPC9nE0CXN8VGQBAOcOTWMgBi42VGC7QJGd31NQBq44GOOQGAZbEfsuwUq58rj/N0yTB@JR//0kIho5sq@YbCprVHJM1kLOdrKdLHZ/AQ "Wolfram Language (Mathematica) – Try It Online")
Returns the shortest echo present in the list.
[Answer]
# [PHP](https://php.net/), 124 bytes
```
function($a){while(!$z&&++$y<$c=count($b=$a))for($x=0;$x<$c&$z=0<=$b[$x+$y]-=$b[$x++];);return array_slice($b,0,$c-$y)?:$a;}
```
[Try it online!](https://tio.run/##7VhtS1xXEP7urziVi7pkA@dlzpxzXBcJpaWBQAL5mIqY7Vptw65cV2oS8tvtPM/d6KqhzcemBJLrdc7MnJlnXq8XZxc3B4cXZxdu3vfL/rifXyz71fni9z0/mrjudHpzerWYrc6Xi73uZPTxr7Pzd/O9H7oPOztPnnTvD7rZdLa8Wqz2urdTOx@dLvu97nrqJ921ne10H6b@YNq9fdNdG/fR0/Xrk6PJaNLPV1f9wp30/cn748t357O5KRn7cTd72r0fHe53J5NPN5OtrW41v1xduql7s@X4355OYhy7VPLY5VjWbzW3sZMcxq5k4Zs7Gj/iD94efpPHWMj3WbcpuP3n7cjd0f1n4j/JhPsym/SHYtFsCBFO4Cesg1XJCGpehVbNRHMqVfAYuQXoUbWHHWkyiRiMHvAooGU7q@CCgmbKqtkcxQhJoFcgB7XVSM2YSxtMiNF@iRkaPdxMQMdIsoHiV5gLaioDTqXqwB/ycCl@1gpTYGkeuPHza4x4iF2KAZbgCl9MtjZTolmBBCwpPuGq5BF5n/CUAiOqNxn1G37dqSpIn1TgUoVBQi8Hs2op96RpkHObWWm3QRzuJRgSGKGS8XuEfUELMEwJTtUkiA1QEl@h3INH/BB3ASCBSa2mVgSQSPAENShUZggp/Ix1uJT0jLAERaZLI44eLAV@pcRSMH7clAryxuOOUABCQr5FRaUkT@iLJw4R1hcAkSUmQJAasqsQDoEej9g2gU6pyL3QhJh6ak6AVhnyGswqjRV3VaCjCop4gJazAjVmgJnDHIDl5gqdq3ArSLlFWioTH5o10McK7CwpA7MJvgCGjPsMHHA0vBvGwKU1wtsYK0QsMCYpwG4LPugCjCJlRZEksNckzcuMo9QQI8MQ5AATLVNAyQA6URPOmoLZw0MFgJYmMCcLwhG1brSsbzKZjI47IuNVWc1CpFB5xvINBuRR06ZFQ8vACyqGjZDFoehFoaGABG071VCQ/RHd2xNKDTQMFyKLY2BfDYCyBM40xLjSW2UfR2zZ1MxtWC@QyAKoeZ9UxKShXktlLwXQQyPNrGi6DgOtn8YHXf1/4s/DOA1DCILDHL9Hjl8c44p7cmLyCufundyXzh7LD3N6GNqbsvfpj9aHIMxHQJJYlJnDS1C2khs6asIkT5rZCTBhrWQ4dRWZqoEZLkx/NgpBz7CIsG7JE7AX5NAwLFmE657Mp1RESjMKLZeIpsEg2@VoHQn1b92YUUYGWDSUmwX0lMqVAi1BhRuHxzOnwJUM5alc1GzI0pfAzQXjOOqgATbnljkXIvYzwwTvaFnZD92qQn9FXmmLnFzgt7LmCoJnYuLWCI9Mipqx9@jQlnLilMEsy2ybynVQCka7rvUDeUOAOwvsr0PHCMLsRzez9gvE2PZiY0pw@YycUDkUrguIVGSPiR5tzSJIG1AGkTjEguwXGBvW3S5wW/HcUwpnGyxLG/n7PVe@58q/5crD/mKdlR8OwtWM@cD9LHt0Y3RdxDYi/mYjYp7WWxmU@8rO1/gRwXWiKocyPyvKgFBki@MUiNy7EnLHrsRpHj5e0K9TkyGenLXMlwgvRRK/T4ZND/NAuempwMZU0UI1e350IDI5cjMsuEUlcHJwfkcuSJXvtfFrsHFVANKZ494WTPB7RDIHDpiEGAoXnKyNtyvRxNMijFopyGKVzM0FFSMJO0ZU1JyVItc15o5H5GWov8J1hzt2LETMBDbWvO@h@a@F5kH1DNuC8Jk@xy2M4ziRc@tosrV1uuznJ7OzPbf@a8XJpb25kftoHF3vpq47xdkbf@RGE6PNZ2dLt/18se/c9tj9cblcHM8Xs@Vv81uusdv@dfHyarX/mKFfn/549uf@l8QDxV/98ur4p5cvbm/b5Or6kZtO75MgN3KHbvfVs9evd92@2/352fMXu7eKNjR@uvkb "PHP – Try It Online")
**Explanation:**
Create a copy of the input array and loop through each possible offset of the echo. For each column, subtract the value in the offset position from the corresponding value in the original position to determine the value necessary to add up to the input. If it is valid (\$\gt 0\$), replace the contents of that column with that value. Continue to the end and if no values are invalid, it is a correct answer.
```
function( $a ) {
// iterate through all possible offsets of echo
while( ! $b && ++$y < $c = count( $b = $a ) ) {
// create a copy of input array, iterate through all elements
for( $x = 0; $b && $x < $c; ) {
// if difference between the elements in the offset copy of
// the array is positive, subtract the value in the input array
// from the offset array in the same column
if ( ( $b[ $x+$y ] -= $b[ $x++ ] ) < 0 ) {
// result is not valid, erase array and break out of loop
$b = 0;
}
}
}
// truncate output array to correct size. if still contains values,
// it is a valid result. otherwise return the original array
return array_slice( $b, 0, $c-$y ) ?: $a;
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 111 bytes
```
def f(r,l=1):o=r[:l];o+=(v-o[-l]for v in r[l:]);return l<len(r)and(min(o)<any(o[-l:])and f(r,l+1)or o[:-l])or r
```
[Try it online!](https://tio.run/##7ZjJbhtHEIbveoqJTiRMA71Ub7J1CnLIKQ8gCIFgU4gAhhRGlBM/vVLfP7IkOAbiW@LAhDBsdVfX8tc6vP14/O2wzw8P77fX0/Vq3uzO4/rscD5fnO0u3xxena8@vD5cvN5dXh/m6cN0s5/mi93Z5frNvD3ez/tp93a33a/m9dX@/er3m/3qsH57tf@44opT@e7C9FVc@/3DxZlzYjU/HLd3x1/fXd1t76bz6eJkdZFT3Ewl1c0UQ0ubqY@xmWqpeTO10f0Rsj9zDn6WQ@ZpzXdiD36nhni5mV4wacVXufnt0qMTWypOmzhKvbWX99YbF28Jjq1wvT2uenEVDEatmFbIeKaMwR/hxak4/duGOGcuGEIQGrNfSK3wf0KXWJuxnf2a9ezrZJ116LAL0FhAVRvmElMUDtXZmgWeEYkxxQrLwqWKTakvQrVfACVWILIRkBcgaViSszB0eiRlZ9BcLIwbZmfzdapAnENBsxZkeUL7hunFUsbo7Ds9NAFg8AndpQyDp/WBCsOEYhDnDJgVCB1N16qmjqwOOrWyYwHQSqmgljDX1cn4F83dFBnXMStae0LakFvEuUbZ2MGuVCxKpWALMBTkOThQDNaOMbiMIXiHfIXHonySI3q7u9k3MEq6a5WwQF@/6VYWjvLAR44h2xEVPTbYKQCdxYmzUSEOWFgB0MMEdYrhjlS7ovybDCPfR0aSp1AmFRNG5JeTfHuu8Jz2pE6AQDglvuEGLFnxRYgLZGIOGt8eEQEVeAlsuS7iRB4tKlQ9caCCAWp3NDXSw@ALEhW2PaIltWtRYak8gKjkiEoN3K669RWKspsbV51prwt9LIs4vvuSTyThQs33V4hX@YuSltCFxFs2F2Hse73maNnQfyKoREzJChsTjlB9YXeREU3@w5qsIC4q6UaYWxnUngyeuRZlDtZ6iAmBimdrVESYwkXeMXKsZlOciybinRIHLURB@1i99LROdawF/EpLOKrQSlw4IGXyxesW/s2RxEiA5P6FT@tyLClUTX4PPEuO6neEc1UX9AYkW6LihyaV6sIBncsoqqCJFuiYsCbFS1iyu8O/k6J1JNV46D0NFA48s6KjJyzyW@JM9NUljUtWPabqF5WZqo5rjbZXH/mDvCOg@EH/vmRYxBdeg4PKFYipTKQhd6qzJ9XyEptaKZ5KyskUCD73oHQgVZNwSC2Y0KAiLNUhqocHde@mqEWzrBj7HiXfo@QfomQp7taGqrVpZlEQaHApgdLM8IhDE053xXB0fhxX4Bi6itRQ5VYj6FU9S7W8LbAk9QVGkZo0kGQCxkVyWpaOQWHNwxYnqhUpSBKmmWU1hWUEoshXjUDV0DH3ivtKUL3HHSVpZGpIqQbgtam9Jc0PXes@NFkPdVLgLeqGPnlBH3BficAbM44z9f9Sh6RXQcjT3UqCNEK3WlFjJ00s04JTJdE8/zTNKGAC7rYl6ZqmAQ2fqQkxv6D557tT/mNOeZyENJAtb0csAEv1QW8FQicOqp51pTZlTTVvxKBJEr/pNcPLKOkaNbJEnNGi3v9Ao2vYqxqOGG315uZTH0XDZJo1AZgUHrxzYGoTMowNaZlRil5lNKmgoI8q6WlU@n9Y8mnqev57nL1ebKxPLk9O@AXhap430/bP2@274/Y9vyY8/wxwdjL553B/nM6n65UTrrVxc629H86fri2E/rmdb/bH1enP@3eHefaj6Wp/98d2Pl3/jeD2/nh2upmemD6f/XJ/fDx0KZ8f/vRJ4umz0gvNdne3/VyPHz/T4uEv "Python 3 – Try It Online")
The solution takes some ideas from [@Chas Brown's solution](https://codegolf.stackexchange.com/a/188196/88506) such as the recursive structure and the construction of the output array. Meanwhile, it also makes some changes in the judging criteria as well as putting the for loop into a generator expression to allow a single-line solution. The ungolfed version is shown in the following. Here, the array `out` is computed all the way to the end of the input array and then we check whether the last `l` elements of it are all zero. If so, the first `len(arr)-l` elements are returned as the answer if all of them are non-negative.
# Ungolfed, non-recursive version
```
def remove_echo(arr):
l = 1
while l < len(arr):
out = arr[:l]
out += (v - out[-l] for v in arr[l:])
if min(out) >= 0 and out[-l:] == [0] * l:
return out[:-l]
l += 1
return arr
```
[Try it online!](https://tio.run/##7ZjLTlxHEIb3PEWHFSRjqe8XFLKJssgqD4CQhfBBRhoGNAx2/PSkvr/HQEikeJc4MkKHpru6Ln9dz7n7tHt/u0mP1zd3t9ud2zzc3H1yF/duc/f4brly2@Xm9sPydrl8f3t0sd0enxw4@1m7Uxe0@vj@er3Y/z@69bJ5QcHP7cPO6Gzv7GR9/qfdH07d0Qf3hvXZm/W5u7rdug/ueiPi9cn58RP19ZW7ud4cGeGx@@nUeXexebe/dnLuTk/dmT9337v1s1R@tsvuYbsR3cmbF7LXSJ6K70lM4ONuud@9vby4X@5N3bODo7MUw8qVWFcu@BZXro@xcrXUtHJtdHv4ZM@UvJ0ln3jmZjuhe7tTfThfuRdMWrFVana79GDEORajjRzF3trLe8crE58jHFvhetuvejEVMoxayVoh45kyeHv4F6fi9G8bYpy5kBGC0JDsQmyF/yO6hNoy28mu5Z5sHXNn7TvsPDTZo2oe2STGIByqsc3Z8wxIDDFUWBYuVWyKfQrVfgGUUIEoD488D0nDkpSEodEjKRmDZmJh3DA7ZVvHCsTJFzRrXpZHtG@YXnJMGJ1sp/smADJ8fDcpI8Mz94EKIwtFL84JMCsQGpqmVY0dWR10amUne0ArpYJaxFxTJ@FfNDdTZFzHrJDbE9IZuUWca5CNHexKxaJYCrYAQ0GegQPFYG0Yg8sYgnfIV3gsyCcpoLe5m/0MRlF3cyUs0NdumpWFozTwkWHIdkBFiw12CkAnceJsVIg9FlYAtDBBnZJxR6xdUf5VhpHtIyPKUygTSxZG5JeRfH2usJy2pI6AQDhF/sINWJLiixAXyMQcNLY9AgIq8BLYcl3AiTxaUKha4kAFA9TuaJpJjwxfkKiw7QEtqV1ThVl5AFHJEZQauF116wsUZTc1rhrTXid9KFMcf/vMJ5JwUvP3C8Sr/AVJi@hC4s3NKYx9q9cczQ39J4JKxJSksMnCEaq/2Z0yQpb/sCYpiItKeibMcxnUngSeqRZlDtZaiAmBimdrUERkhYu8k8mxmrLiXDQB75QwaCEK2n310jN3qmMt4FdaxFGFVmLCASmRL1a38G8KJEYEJPMvfFqXY0mhmuV3z7OkoH5HOFd1QWtAsiUofmhSsU4O6FxGUQWNtEDDhDUpXvzM7g7/TorWEVXjobc0UDjwTIqOHrHIbokz0VdnGpekekzVLyozVR03N9pe3fMHeUNA8YP@fWZYwBdWg73KFYipTMQhd6qzR9XyEppaKZ6KysnoCT7zoHQgVaNwiM1noUFFmNUhqId7de@mqEWzpBj7FiXfouQfomQW99yGqnXWzKIg0OBSPKWZ4RGHRpxuiuHotB9X4Oi7itRQ5VYj6FU9S7W8TVii@gKjSI0aSBIBYyI5LbNjUFjTyNOJakUKkohpOSc1hTkCUeSrRqCa0TH1ivuKV73HHSVqZGpIqRnAa1N7i5ofutZ9aLIe6qTAW9QNbfKC3uO@EoA3JByX1f9LHZJeBSFPcysJ0gjdmosaO2mSEy04VhLN8k/TjALG4@48k65pGtDwGZsQswuaf7455T/mlP0kpIFsvh2xACzVB70VCJ0wqHq5K7Upa6p5I3hNkvhNrxlWRknXoJEl4IwW9P4HGl3DXtVwxGirNzeb@igaWablJgCjwoN3DkxtQoaxIc4ZpehVRpMKCtqoEp9Gpf@HJZ@nruff/ez1YuP44PzggO8N9ua/csvvd8vlbnnHt4fnzwDzY8L8fPH6A8jB/qsEp9@dPjF4@v5wt73e7I4Of91c3m63duQuNvcfl@3h8V8I7h52J4cr98T0@ey3h93@kO8erw5/@Szx8Fn9SbOs75fXevz8SovHPwA "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes
```
≔⁰ζF⊘Lθ«≔E⊕ι⁰ηFLθ§≔ηκ⁻§θκ§ηκ¿⬤η¬κ≔⊕ιζ»F⁻Lθζ⊞υ⁻§θι∧ζ∧¬‹ιζ§υ±ζIυ
```
[Try it online!](https://tio.run/##bVLLbtswEDwnX8EjBagAudzlAz0ZvTRAEuQe5CDYiiXUlRtLDooU/XZ3h3abAu0hDj3ceezQ66E7rPfd7nRazfO4naxrzVvz8fp5fzD2c7d77Tf2tp@2y2BfmqYxP66vLoN33Td7M60P/dd@WnRqbFrj9G9Q9lWlv/PMmbNabqZN/90OrfnSmrtxOs72N/aimLL/HlE/lRqfjV3tdkDu94sFepH7xx7Bf56jn8X/JMBdYx6O82CP/3EGeTVt7Nv5H3xu@3m2Y@W9p1Lufb/tlt4q3NR8D4dxWuynbl7sUb@fTo@PhkPQGkPirJ8xtMYHaQ0lwXcqRYGYGHCIreEc9EyccXY5Ke4ww67oPBcmvfUCJKoss8OndzruyUdICkgx6Djls2nFRWASnUDGwc9hJCWNFAIRqJnhFFQgqS2Ek2@NBNYzxaTU4ATJktN5JkL6RIoIk@pEFxTJLkWcGTouq0thaHIuiFBYb5O4qhw8ApIqS/aaKlKGV0Y7MQJhh9JEIlojrKtxFGFBcl2lLpexlofjpWmGr1Tl6OuOGd1JxEYkgl1Qg8BPy8FEwVk7Ri@l1HpLfSu8mK9vEjxye4IuMTqiyuUowF1l6paCq1DwRtohYI@IPmMBLyg6VCXclYhhhw0jCtSfCeII4zkoZvP0dPrwuvsF "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰ζ
```
Assume there's no echo.
```
F⊘Lθ«
```
Try all possible start points of echo. Note: I may have misread the question and might not be trying enough sizes of echo, in which case the `⊘` would not be necessary.
```
≔E⊕ι⁰η
```
Start with an array of zeros the same size as the start point of the echo.
```
FLθ§≔ηκ⁻§θκ§ηκ
```
For each element in the original array, subtract the element in the echo array cyclically from it. Each element in the echo array thus builds up the alternating sum of the elements that distance apart.
```
¿⬤η¬κ≔⊕ιζ»
```
If all of the alternating sums are zero then save this as a possible start point. (So if there is more than one possibility then the largest possible start point is used.)
```
F⁻Lθζ⊞υ⁻§θι∧ζ∧¬‹ιζ§υ±ζ
```
Build up the echoing array by subtracting elements after the start point from the appropriate previously calculated element.
```
Iυ
```
Cast to string for implicit output on separate lines.
] |
[Question]
[
Python is the fastest-growing major programming language today. It is the most wanted language for the third year in a row, meaning that developers who do not yet use it say they want to learn it.[[1]](https://insights.stackoverflow.com/survey/2019#key-results)
The reason for Python's popularity is its many versions.[citation needed] There are in fact 116 versions of Python, including two development versions.
Your task is to output/print a list of all the Python versions, in whatever order you like, and on whatever format you like. You may not use any built-in functions that have this information stored.
You are free to choose the output format, but each version must be identified on the standard way: `1.1`, `2.3.0`, `2.7.10` and so on.
The complete list2 of Python versions, comma-separated is shown below:
```
1.1, 1.2, 1.3, 1.4, 1.5, 1.5.1, 1.5.2, 1.6, 2.0, 2.0.1, 2.1, 2.1.1, 2.1.2, 2.1.3, 2.2, 2.2.1, 2.2.2, 2.2.3, 2.3, 2.3.1, 2.3.2, 2.3.3, 2.3.4, 2.3.5, 2.4, 2.4.1, 2.4.2, 2.4.3, 2.4.4, 2.5, 2.5.1, 2.5.2, 2.5.3, 2.5.4, 2.6, 2.6.1, 2.6.2, 2.6.3, 2.6.4, 2.6.5, 2.6.6, 2.6.7, 2.6.8, 2.6.9, 2.7, 2.7.1, 2.7.2, 2.7.3, 2.7.4, 2.7.5, 2.7.6, 2.7.7, 2.7.8, 2.7.9, 2.7.10, 2.7.11, 2.7.12, 2.7.13, 2.7.14, 2.7.15, 2.7.16, 3.0, 3.0.1, 3.1, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.2 , 3.2.1, 3.2.2, 3.2.3, 3.2.4, 3.2.5, 3.2.6, 3.3.0, 3.3.1, 3.3.2, 3.3.3, 3.3.4, 3.3.5, 3.3.6, 3.3.7, 3.4.0, 3.4.1, 3.4.2, 3.4.3, 3.4.4, 3.4.5, 3.4.6, 3.4.7, 3.4.8, 3.4.9, 3.4.10, 3.5.0, 3.5.1, 3.5.2, 3.5.3, 3.5.4, 3.5.5, 3.5.6, 3.5.7, 3.6.0, 3.6.1, 3.6.2, 3.6.3, 3.6.4, 3.6.5, 3.6.6, 3.6.7, 3.6.8, 3.7.0, 3.7.1, 3.7.2, 3.7.3
```
or by major versions:
```
1.1
1.2
1.3
1.4
1.5, 1.5.1, 1.5.2
1.6
2.0, 2.0.1
2.1, 2.1.1, 2.1.2, 2.1.3
2.2, 2.2.1, 2.2.2, 2.2.3
2.3, 2.3.1, 2.3.2, 2.3.3, 2.3.4, 2.3.5
2.4, 2.4.1, 2.4.2, 2.4.3, 2.4.4
2.5, 2.5.1, 2.5.2, 2.5.3, 2.5.4
2.6, 2.6.1, 2.6.2, 2.6.3, 2.6.4, 2.6.5, 2.6.6, 2.6.7, 2.6.8, 2.6.9
2.7, 2.7.1, 2.7.2, 2.7.3, 2.7.4, 2.7.5, 2.7.6, 2.7.7, 2.7.8, 2.7.9, 2.7.10, 2.7.11, 2.7.12, 2.7.13, 2.7.14, 2.7.15, 2.7.16
3.0, 3.0.1
3.1, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5
3.2, 3.2.1, 3.2.2, 3.2.3, 3.2.4, 3.2.5, 3.2.6
3.3.0, 3.3.1, 3.3.2, 3.3.3, 3.3.4, 3.3.5, 3.3.6, 3.3.7
3.4.0, 3.4.1, 3.4.2, 3.4.3, 3.4.4, 3.4.5, 3.4.6, 3.4.7, 3.4.8, 3.4.9, 3.4.10
3.5.0, 3.5.1, 3.5.2, 3.5.3, 3.5.4, 3.5.5, 3.5.6, 3.5.7
3.6.0, 3.6.1, 3.6.2, 3.6.3, 3.6.4, 3.6.5, 3.6.6, 3.6.7, 3.6.8
3.7.0, 3.7.1, 3.7.2, 3.7.3
```
The challenge is a fixed output challenge, and very close to a [kolmogorov-challenge](/questions/tagged/kolmogorov-challenge "show questions tagged 'kolmogorov-challenge'"), except that the output format is optional.
2The list is taken from the official Python website, [here](https://www.python.org/download/releases/) and [here](https://www.python.org/doc/versions/). There are some versions that aren't included, such as `0.9.0` .. `0.9.9` and `1.5.1p1`. You must use the list above, even if you find versions that aren't included. I've decided to stick with the official lists, since otherwise someone would probably find a `2.1.0.1.2` version or something like that.
[Answer]
# JavaScript (ES6), ~~128 125~~ 124 bytes
*Saved 1 bytes thanks to @OlivierGrégoire*
Outputs each version on a separate line. Ordered from highest to lowest major version, and from lowest to highest revision.
```
f=(r=v=28)=>v?r<parseInt('0111131000244655ah002678b8940'[v],36)?(1+v/10).toFixed(1)+(r|v>22?'.'+r:'')+`
`+f(r+1):f(+!v--):''
```
[Try it online!](https://tio.run/##DchLDoIwFEDRubtw1PdSi235iMTCzMQ1GBMqtIohlBTSOHDvlTs6uR8d9NL5YV7Z5HoTo1XgVVCyRFWHxl9m7Rdzm1YgXGylgnMus6zIc/3eVJzKZ3nOOLmHxyEtsAFBw1FwTFZ3Hb6mB4EU/C/UUjYkIdRXhCBtdy214KnAygLdB8Zw@7Fz0@JGk4zuBRYQ4x8 "JavaScript (Node.js) – Try It Online")
### How?
The major and minor versions are held in the variable \$v \in [0..27]\$:
* major = \$\lfloor v/10+1\rfloor\$
* minor = \$v \bmod 10\$
The revision is held in the variable \$r\ge0\$. The maximum value of \$r\$ depends on \$v\$ and is stored in a lookup table encoded in Base-36. Any \$0\$ in this table means that this version was not released at all.
Besides, we use the test \$v>22\$ to know whether the revision should be included even when it's \$0\$ (starting with Python 3.3.0).
[Answer]
# Pyth, 52 bytes
```
.emj\.+W|d>k18,h/k8%k8dbxLG"abbbbdbaceegffkrcghilije
```
Try it online [here](https://pyth.herokuapp.com/?code=.emj%5C.%2BW%7Cd%3Ek18%2Ch%2Fk8%25k8dbxLG%22abbbbdbaceegffkrcghilije&debug=0).
Output is a nested list, with elements grouped by major and minor version. There is an empty list at the start of the output, and another one after `1.6`. Full output is as follows:
```
[[], ['1.1'], ['1.2'], ['1.3'], ['1.4'], ['1.5', '1.5.1', '1.5.2'], ['1.6'], [], ['2.0', '2.0.1'], ['2.1', '2.1.1', '2.1.2', '2.1.3'], ['2.2', '2.2.1', '2.2.2', '2.2.3'], ['2.3', '2.3.1', '2.3.2', '2.3.3', '2.3.4', '2.3.5'], ['2.4', '2.4.1', '2.4.2', '2.4.3', '2.4.4'], ['2.5', '2.5.1', '2.5.2', '2.5.3', '2.5.4'], ['2.6', '2.6.1', '2.6.2', '2.6.3', '2.6.4', '2.6.5', '2.6.6', '2.6.7', '2.6.8', '2.6.9'], ['2.7', '2.7.1', '2.7.2', '2.7.3', '2.7.4', '2.7.5', '2.7.6', '2.7.7', '2.7.8', '2.7.9', '2.7.10', '2.7.11', '2.7.12', '2.7.13', '2.7.14', '2.7.15', '2.7.16'], ['3.0', '3.0.1'], ['3.1', '3.1.1', '3.1.2', '3.1.3', '3.1.4', '3.1.5'], ['3.2', '3.2.1', '3.2.2', '3.2.3', '3.2.4', '3.2.5', '3.2.6'], ['3.3.0', '3.3.1', '3.3.2', '3.3.3', '3.3.4', '3.3.5', '3.3.6', '3.3.7'], ['3.4.0', '3.4.1', '3.4.2', '3.4.3', '3.4.4', '3.4.5', '3.4.6', '3.4.7', '3.4.8', '3.4.9', '3.4.10'], ['3.5.0', '3.5.1', '3.5.2', '3.5.3', '3.5.4', '3.5.5', '3.5.6', '3.5.7'], ['3.6.0', '3.6.1', '3.6.2', '3.6.3', '3.6.4', '3.6.5', '3.6.6', '3.6.7', '3.6.8'], ['3.7.0', '3.7.1', '3.7.2', '3.7.3']]
```
If this isn't acceptable, prepend `.n` to the code to have output as a flattened list, at a cost of 2 bytes.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 109 bytes
```
for(int j,k=1;;k++)for(j=@" [SOH][SOH][SOH][SOH][ETX][SOH][NUL][NUL][NUL][STX][EOT][EOT][ACK][ENQ][ENQ]
[DC1][NUL][NUL][STX][ACK][BEL][BS][VT][BS][TAB][EOT]"[k];j-->0;)Print($"{k*.1+1:N1}"+(j<1&k<17?"":"."+j));
```
Contains many unprintables, whose codes are shown in the brackets. This is a full program. The null bytes are replaced by `\0`s in the TIO link, since my device can't copy and paste them.
Saved one byte thanks to @OlivierGregoire.
[Try it online! (Thanks to @OlivierGregoire for implanting the null bytes)](https://tio.run/##Sy7WTS7O/P8/Lb9IIzOvRCFLJ9vW0No6W1tbEySUZaukwAgEzIwMDAxMLCxsrKwxeYJAJhs7BzcHJ4tSdHasdZaurp2BtWZAEdAADRWl6mwtPUNtQys/w1olbY0sG0O1bBtDc3slJSslPSXtLE1N6///AQ "C# (Visual C# Interactive Compiler) – Try It Online")
# Explanation
Each character in the string represents how many minor versions in the major position. For example, the character at index 5(`ETX`) has an ASCII value of three, and corresponds to the major version `1.5.x` which has three minor versions. The program takes the ascii value of the current character and loops that many times, printing the minor versions before moving on to the next major version.
For some versions, there are gaps to the next versions. To fix that, the string contains null bytes, so that the program loops zero times when it encounters those.
The unprintable string contains these character values:
```
1,1,1,1,3,1,0,0,0,2,4,4,6,5,5,10,17,0,0,2,6,7,8,11,8,9,4
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 134 bytes
```
v->{for(int a=0,b;;)for(b="0111131000244655:A002678;894".charAt(++a)-48;b-->0;)System.out.printf("%.1f%s ",a*.1+1,b<1&a<23?"":"."+b);}
```
[Try it online!](https://tio.run/##HU5BboMwELznFZalVLiAZSckpTFQRT33FKmXqoe1g1NTMAibSFXE26mTuezMzs5qGrhC2px/F9WCc@gDjEW3FULDJFujkPPgw7j25oy64EUnPxp7@fpGMF4ceZwi1IQndPKmpXqyypve0vfeuqmrx@IzRCuky@WaVjfdj5GxHkHJEikEuWtZYsYDtpwxtsmy/W53OAa2f8lF/pphqn5gPPoojoGkWS5kmlZMkNOf83VH@8nTIVTyOsJryvXaIZzAM@UxT2TBn6DYbN8wPmCKY0nEvIhHY01BqXrwkZ3altx382pe/gE "Java (JDK) – Try It Online")
The versions are printed from the highest to the lowest.
## Credits
* -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
* -3 bytes thanks to [Embodiment of Ignorance](https://codegolf.stackexchange.com/users/84206/embodiment-of-ignorance)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 105 bytes
```
11* 111131 244655TS 2678E894
L$`.
$&_$.`
T
10
E
11
S
17
.+_
*
Lv$`_+(.)(.)
$1.$2.$.%`
,16`(...)\.0
$1
```
[Try it online!](https://tio.run/##DYu7DoMwEAT7/QoXF8RLK44YAx9ARwclki9FijQpoii/79xqitFI@3l@X@@HlgLVNqjvriGEMcY0TefhluZlW9aIXYyQKgsNJ3TA5hcc0BnsMlrsP7Hc1WwciFJGCm@GXpPVJJuLg/dS/g "Retina – Try It Online") Loosely based on @Arnauld's solution. Explanation:
```
11* 111131 244655TS 2678E894
```
Insert the string consisting of 11 spaces followed by the given characters.
```
L$`.
$&_$.`
```
For each character, list it suffixed with a `_` and its column number.
```
T
10
E
11
S
17
```
Convert the three letters to numeric values.
```
.+_
*
```
Convert the numeric values to unary.
```
Lv$`_+(.)(.)
$1.$2.$.%`
```
For each value up to the given value, use that as the suffix for the version number, extracting the major and minor from the column number.
```
,16`(...)\.0
$1
```
Delete the zero suffix for the first 16 versions that have one.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 51 bytes
```
+⁵D;ⱮḶ}j€”.
“øṄƇịɱ⁽Ɱj>⁶7,Ẉ¢’b18Ė0ị$Ƈç/€ḣ3$€1¦€17R¤¦
```
[Try it online!](https://tio.run/##y0rNyan8/1/7UeNWF@tHG9c93LGtNutR05pHDXP1uB41zDm84@HOlmPtD3d3n9z4qHEvUEWW3aPGbeY6D3d1HFr0qGFmkqHFkWkGQHmVY@2Hl@sDtT7csdhYBUgbHloGIs2DDi05tOz/oUXeQF7kfwA "Jelly – Try It Online")
A niladic link that outputs a list of lists of `.`-separated integers, grouped by major version. On TIO, there’s some footer code to print these prettily.
[Answer]
# [33](https://github.com/TheOnlyMrCat/33), 484 bytes
```
"1."es[lz1azpois4m]"1.5"pi"1.5."z1apoiapoi"1.6"pi"2.0"pip".1"pizcz"2.1"''pie"."e''es[lz1azpois3m]"2.2"''pie"."et''es[lz1azpois3m]"2.3"''pie"."et''es[lz1azpois5m]"2.4"''pie"."et''es[lz1azpois4m]"2.5"''pie"."et''es[lz1azpois4m]"2.6"''pie"."et''es[lz1azpois9m]"2.7"''pie"."et''es[lz1azpois16m]"3.0"pip".1"pi"3.1"''pie"."et''es[lz1azpois5m]"3.2"''pie"."et''es[lz1azpois6m]"3.3."''es[lzpoi1azs8m]"3.4."''es[lzpoi1azs11m]"3.5."''es[lzpoi1azs8m]"3.6."''es[lzpoi1azs9m]"3.7."''es[lzpoi1azs4m]
```
I wanted to give this a go in my brainf\*ck-style language.
It prints each python version required for the challenge, delimited by newlines.
Here's a small explanation.
```
[lz1azpois4m] | Imitates a for loop starting at 1
[ 1az 4m] | For i in range 1 through 4
p | - Print the string declared previously (1.5., 3.4., etc.)
o | - Print the current value of i
i | - Print a newline
[lzpoi1azs8m] | Imitates a for loop starting at 0
[ 1az 8m] | For i in range 0 through 7
poi | Print the version
```
] |
[Question]
[
Given the Dowker notation of a knot and its crossing signs, calculate its bracket polynomial.
Although there are more technical definitions, for this challenge it is enough to think of a **knot** as something made physically by attaching the two ends of a string together. Since knots exist in three dimensions, when we draw them on paper, we use **knot diagrams** - two-dimensional projections in which the crossings are of exactly two lines, one over and one under.
[![enter image description here](https://i.stack.imgur.com/598Yp.png)](https://i.stack.imgur.com/598Yp.png)
Here (b) and (c) are different diagrams of the same knot.
How do we represent a knot diagram on paper? Most of us aren't Rembrandt, so we rely on **Dowker notation**, which works as follows:
Pick an arbitrary starting point on the knot. Move in an arbitrary direction along the knot and number the crossings you encounter, starting from 1, with the following modification: if it's an even number and you're currently going *over* the crossing, negate that even number. Finally, pick the even numbers corresponding to 1, 3, 5, etc.
Let's try an example:
[![enter image description here](https://i.stack.imgur.com/WNZse.png)](https://i.stack.imgur.com/WNZse.png)
[Taken with permission from wikimedia user Czupirek](https://commons.wikimedia.org/wiki/File:Dowker-notation-example.svg)
On this knot, we chose "1" as our starting point and proceeded to move up and to the right. Every time we go *over* or *under* another piece of the rope, we assign the crossing point the next natural number. We negate the even numbers corresponding to strands that go over a crossing, for example `[3,-12]` in the diagram. So, this diagram would be represented by `[[1,6],[2,5],[3,-12],[-4,9],[7,8],[-10,11]]`. Listing the buddies of 1, 3, 5, 7, etc gives us `[6,-12,2,8,-4,-10]`.
There are a few things to note here. First, the Dowker notation is *not* unique for a given knot, as we can choose an arbitrary starting point and direction. But, given the notation, one can fully determine the structure of the knot (technically, up to reflection of its prime knot components). While not all Dowker notations can form possible knots, in this problem you can assume that the input represents an actual knot.
To avoid the ambiguity between a knot's reflections, and to make the challenge easier to solve, you will also be given a list of **crossing signs** as input.
[![enter image description here](https://i.stack.imgur.com/ptzRJ.gif)](https://i.stack.imgur.com/ptzRJ.gif)
In a positive crossing the lower line goes to the left from the point of view of the upper line. In a negative crossing it goes to the right. Note that reversing the direction of going around the knot (i.e. reversing both the *over* line and *under* line) doesn't change the crossing signs. In our example the crossing signs are `[-1,-1,-1,1,-1,1]`. They are given in the same order as the Dowker notation, i.e. for crossings numbered 1, 3, 5, 7, etc.
In this challenge we will be calculating the **bracket polynomial** of a knot. It's an object that is invariant across most transformation of the knot diagram - a concept which makes it supremely useful in knot theory analysis. (Again, most knot theorists compute the bracket polynomial as an intermediate product on their way to computing the Jones polynomial, which is invariant across *all* transformations, but we will not be doing that.) So how does it work? The bracket polynomial is a Laurent polynomial - one in which the variable (traditionally named \$A\$) can be raised to negative powers, as well as positive.
For a given knot diagram \$D\$, the three rules for the polynomial, represented as \$\langle D\rangle\$, are:
[![enter image description here](https://i.stack.imgur.com/owShn.png)](https://i.stack.imgur.com/owShn.png)
1. A sole loop without any crossings has polynomial 1.
2. If we have a diagram consisting of \$D\$ and a loop disconnected from \$D\$, the polynomial for both is the polynomial for \$D\$ times \$(-A^2-A^{-2})\$.
3. This rule is the trickiest. It says that if you have a crossing in \$D\$ that looks like [![enter image description here](https://i.stack.imgur.com/cqwhK.png)](https://i.stack.imgur.com/cqwhK.png), then you can use this rule to simplify the knots in two different ways:
[![enter image description here](https://i.stack.imgur.com/gZQKu.png)](https://i.stack.imgur.com/gZQKu.png)
In the image above, the outlined crossing in the first diagram, which is of the form [![enter image description here](https://i.stack.imgur.com/cqwhK.png)](https://i.stack.imgur.com/cqwhK.png), can be transformed into [![enter image description here](https://i.stack.imgur.com/5yzGn.png)](https://i.stack.imgur.com/5yzGn.png) as in the second figure (a.k.a. **positive smoothing**), or [![enter image description here](https://i.stack.imgur.com/I95lY.png)](https://i.stack.imgur.com/I95lY.png) as in the third figure (**negative smoothing**).
So, the bracket polynomial of the first diagram is the bracket polynomial of the second times \$A\$ plus the third times \$A^{-1}\$, i.e.,
[![enter image description here](https://i.stack.imgur.com/ZKvF3.png)](https://i.stack.imgur.com/ZKvF3.png)
Confused yet? Let's do an example, trying to find the bracket polynomial of [![enter image description here](https://i.stack.imgur.com/lhpIJ.png)](https://i.stack.imgur.com/lhpIJ.png) (Note: this is two knots linked together. This sort of diagram will not be a potential input in this challenge since the inputs will only be single knots, but it may appear as an intermediate result in the algorithm.)
We first use rule 3
[![enter image description here](https://i.stack.imgur.com/ieKDr.png)](https://i.stack.imgur.com/ieKDr.png)
We use rule 3 again on both of the new knots
[![enter image description here](https://i.stack.imgur.com/04CRC.png)](https://i.stack.imgur.com/04CRC.png)
We substitute these 4 new knots into the first equation.
[![enter image description here](https://i.stack.imgur.com/Cauac.png)](https://i.stack.imgur.com/Cauac.png)
Applying rules 1 and 2 to these 4 tell us
[![enter image description here](https://i.stack.imgur.com/uZe1G.png)](https://i.stack.imgur.com/uZe1G.png)
So, this tell us
[![enter image description here](https://i.stack.imgur.com/AUp57.png)](https://i.stack.imgur.com/AUp57.png)
Congrats on completing your brief intro to knot theory!
# Input
Two lists:
* Dowker notation, e.g. `[6,-12,2,8,-4,-10]`. Numbering of the crossings must start from 1. The corresponding odd numbers `[1,3,5,7,...]` are implicit and must *not* be provided as input.
* Signs (`1`/`-1` or if you prefer `0`/`1` or `false`/`true` or `'+'`/`'-'`) for the crossings corresponding to the Dowker notation, e.g `[-1,-1,-1,1,-1,1]`.
Instead of a pair of lists, you could have a list of pairs, e.g. `[[6,-1],[-12,-1],...`
# Output
Print or return the polynomial, for instance \$A^{-2}+5+A-A^3\$, as a list of coefficient-exponent pairs (or exponent-coefficient pairs) in increasing order of the exponents and without any zero coefficients, e.g. `[[1,-2],[5,0],[1,1],[-1,3]]`.
Alternatively, output an odd-length list of coefficients correspondings to exponents \$-k\ldots k\$ for some \$k\in \mathbb{N}\$, e.g. `[0,1,0,5,1,0,-1]`. The central element is the constant term (coefficient before \$A^0\$). The leftmost and rightmost elements must not be both 0.
# Rules
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. None of the standard loopholes can be used, and libraries that have tools to calculate either Dowker notations, or Bracket polynomials, cannot be used. (A language that contains these libraries still can be used, just not the libraries/packages).
# Tests
```
// 4-tuples of [dowker_notation, crossing_signs, expected_result, description]
[
[[],[],[[1,0]],"unknot"],
[[2],[1],[[-1,3]],"unknot with a half-twist (positive crossing)"],
[[2],[-1],[[-1,-3]],"unknot with a half-twist (negative crossing)"],
[[2,4],[1,1],[[1,6]],"unknot with two half-twists (positive crossings)"],
[[4,6,2],[1,1,1],[[1,-7],[-1,-3],[-1,5]],"right-handed trefoil knot, 3_1"],
[[4,6,2,8],[-1,1,-1,1],[[1,-8],[-1,-4],[1,0],[-1,4],[1,8]],"figure-eight knot, 4_1"],
[[6,8,10,2,4],[-1,-1,-1,-1,-1],[[-1,-7],[-1,1],[1,5],[-1,9],[1,13]],"pentafoil knot, 5_1"],
[[6,8,10,4,2],[-1,-1,-1,-1,-1],[[-1,-11],[1,-7],[-2,-3],[1,1],[-1,5],[1,9]],"three-twist knot, 5_2"],
[[4,8,10,2,12,6],[1,1,-1,1,-1,-1],[[-1,-12],[2,-8],[-2,-4],[3,0],[-2,4],[2,8],[-1,12]],"6_3"],
[[4,6,2,10,12,8],[-1,-1,-1,-1,-1,-1],[[1,-10],[2,-2],[-2,2],[1,6],[-2,10],[1,14]],"granny knot (sum of two identical trefoils)"],
[[4,6,2,-10,-12,-8],[1,1,1,1,1,1],[[1,-14],[-2,-10],[1,-6],[-2,-2],[2,2],[1,10]],"square knot (sum of two mirrored trefoils)"],
[[6,-12,2,8,-4,-10],[-1,-1,-1,1,-1,1],[[1,-2],[1,6],[-1,10]],"example knot"]
]
```
# External resources
Not necessary for the challenge, but if you are interested:
* [A paper on Knot Polynomials](https://www.mathi.uni-heidelberg.de/~lee/Andre_Nasim.pdf)
* [A paper on Dowker Notation](https://www.math.csusb.edu/reu/previouswork/jw09.pdf)
---
sandbox posts: [1](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/16791#16791), [2](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/16801#16801)
thanks @ChasBrown and @H.Pwiz for catching a mistake in my definition of Dowker notation
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 1316 bytes
```
(({})<({()<(({}<>))><>}){(({})[()()]<{([{}]({})<>({}<>))}{}(([({}<>)]<<>({}<>)<>((({})<<>{({}<>)<>}<>>))>)){({}<>)<>}<>{}(({}<{}(({}<{({}<>)<>}>))>))<>{({}<>)<>}>)}<>>){(({}){}()<({}<>)>)<>{}(({}){}<>)<>}<>{}{}(()){(<({}<({}<>)>)>)<>((){[()](<(({})<>){({}[({})]<>({}<>))}{}({}<>({}<{}<>{({}<>)<>}>)[()])<>({}({})[()])(([()]{()(<({}[({})]())>)}{})<{(<{}{}>)}{}><>{()((<({}()[({}<>)])<>>))}{}<{}{}>)((){[()]<({}()<({}<({}<<>({()<({}<>)<>>}<>){({}[()]<(({})<({()<({}<>)<>>})<>>)<>{({}[()]<<>({}<>)>)}{}>)}<>>)<>>)>)((){[()](<{}(({})<<>(({})<(<<>({}<<>({}<(()()){({}[()]<([{}]()<>)<>({}<<>{({}({})<>[({}<>)])}{}{}>){({}<>)<>}<>>)}{}>{})>)>)<>{}{({}<>)<>}<>([({}<>)]<((()))>)(())<>({}<>)<>{}({}[()]){<>({}<<>(()()){({}[()]<({}<<>{({}<>)<>}>){({}[({})]<>({}<>))}{}(({})<<>({}<>)<>([{}])>)>)}{}{}>)<>({}<(({})())>[()]<>)}{}({}<<>{}([{}]()<{({}<>)<>}>){({}({})<>[({}<>)])}{}{}>){({}<>)<>}<>{}{}{}>{})>)>)}{}){(<{}(({})<<>(({}{})<<>(<({}<>)>)<>{}{({}<>)<>}<>>(({}){}){})>)>)}>}{}){(<{}([{}]<({}<<>([{}]()<>)<>({}<<>{({}({})<>[({}<>)])}{}{}>){({}<>)<>}<>>({})({}){})>)>)}{}>)}{}){{}(([{}]){}<>{}{}<<>({}<>{}){([{}]({}()()<{}({}<>)(())<>>))}{}{}{}>{})(())<>{{}({}<>)(())<>}(<>)<>}{}}{}{}<>{}{}({}<{{}({}<>)(())<>}<>{{}{((<(())>))}{}}{}{{}({}<>)(())<>}>)<>{{}({}<(<()>)<>([]){{}({}<>)(())<>([])}{}>)<>{{}({}<>)<>}{}{}({}<>)<>}<>
```
[Try it online!](https://tio.run/##nVRNSwQxDP0re0wOC66IeCj9I0MP60EQxYPX0N8@5uWj0ymIIOx2pulL8vKSzuv3/f3r@vZ5/9h3IulcSEgXfS2VuZbaWexgIyZuRWiT3gxZA9SlE22@aSXN@vSApUpadEVQ5tkCb93lY5w4cvaubAGcj@JBFkc4dHeew8KEVIZKpBNj0XIaFWdYjQ8qUP5zVXhzbmcacPb6Q5nGUICbamfpPBahgo4MSgJ8bFcRS/HAEadubNJ0SwZgcnTUKAFJR93q0gd5QKcGDoAFdvoGygKdiyuK/5GSohdoXYQML18JkzBltYFgb7mBJIQpdVTXvarzJMCksGzgfHjME6GJzo6P2bIEJrwMagutQSW79kuTs9KcWpTDoQ84Z9EKQ0MteM3xMCYhwJrrbwnEbaEBJkVW8ePtNOknFWPsOYPUIwx45dT8t0lW9hQ@hpjFLj2kkigkNbT08ZFAS0pcpOigq551u03OkE6eXrrh4i7jaiw48xRcJbtqHB4Lqh4ZFOlfgK3xAoMp@j1OjMO0KXXfny/Xm/4e8bDl5aL7J7c@XG4/ "Brain-Flak – Try It Online")
I regret nothing. Input is a flattened list of pairs.
```
# Part 1: extract edges
(({})<
({()<(({}<>))><>}){
(({})[()()]<
{([{}]({})<>({}<>))}{}(([({}<>)]<<>({}<>)<>((({})<<>{({}<>)<>}<>>))>)){({}<>)<>}
<>{}(({}<{}(({}<{({}<>)<>}>))>))<>{({}<>)<>}
>)}
<>>){(({}){}()<({}<>)>)<>{}(({}){}<>)<>}<>
{}{}(())
# Part 2: Compute bracket polynomial
{
# Move degree/sign to other stack
(<({}<({}<>)>)>)<>
# If current shape has crossings:
((){[()](<
# Consider first currently listed edge in set
# Find the other edge leaving same crossing
(({})<>){({}[({})]<>({}<>))}{}
# Move to top of other stack
# Also check for twist
({}<>({}<{}<>{({}<>)<>}>)[()])
# Check for twist in current edge
<>({}({})[()])
(
# Remove current edge if twist
([()]{()(<({}[({})]())>)}{})<{(<{}{}>)}{}>
# Remove matching edge if twist
<>{()((<({}()[({}<>)])<>>))}{}<{}{}>
# Push 1 minus number of twists from current vertex.
)
# If number of twists is not 1:
((){[()]<
# While testing whether number of twists is 2:
({}()<
# Keep sign/degree on third stack:
({}<({}<
# Duplicate current configuration
<>({()<({}<>)<>>}<>){({}[()]<(({})<({()<({}<>)<>>})<>>)<>{({}[()]<<>({}<>)>)}{}>)}
# Push sign and degree on separate stacks
<>>)<>>)
# If number of twists is not 2: (i.e., no twists)
>)((){[()](<{}
# Make first copy of sign/degree
(({})<<>(({})<
# Make second copy of sign/degree
(<<>({}<<>({}<
# Do twice:
(()()){({}[()]<
# Prepare search for vertex leading into crossing on other side
([{}]()<>)
# While keeping destination on third stack:
<>({}<
# Search for matching edge
<>{({}({})<>[({}<>)])}{}
# Replace old destination
{}>)
# Move back to original stack
{({}<>)<>}<>
>)}{}
# Add orientation to degree
>{})>)>)
# Move duplicate to left stack
<>{}{({}<>)<>}<>
# Create "fake" edges from current crossing as termination conditions
([({}<>)]<((()))>)(())<>
# Create representation of "top" new edge
({}<>)<>{}({}[()])
# While didn't reach initial crossing again:
{
# Keep destination of new edge on third stack
<>({}<<>
# Do twice:
(()()){({}[()]<
# Search for crossing
({}<<>{({}<>)<>}>){({}[({})]<>({}<>))}{}
# Reverse orientation of crossing
(({})<<>({}<>)<>([{}])>)
>)}{}
# Remove extraneous search term
{}
# Push new destination for edge
>)
# Set up next edge
<>({}<(({})())>[()]<>)
}
# Get destination of last edge to link up
{}({}<
# Find edge headed toward original crossing
<>{}([{}]()<{({}<>)<>}>){({}({})<>[({}<>)])}
# Replace destination
{}{}>)
# Move everything to left stack
{({}<>)<>}
# Clean up temporary data
<>{}{}{}
# Push new sign/degree of negatively smoothed knot
>{})>)
# Else (two twists)
# i.e., crossing is the twist in unknot with one half-twist
>)}{}){(<{}
# Copy sign and degree+orientation
(({})<<>(({}{})<
# Move sign to left stack
<>(<({}<>)>)
# Move copy of configuration to left stack
<>{}{({}<>)<>}
# Add an additional 4*orientation to degree
<>>(({}){}){})>)
>)}
# Else (one twist)
>}{}){(<
# Invert sign and get degree
{}([{}]<({}<
# Search term for other edge leading to this crossing
<>([{}]()<>)
# With destination on third stack:
<>({}<
# Find matching edge
<>{({}({})<>[({}<>)])}{}
# Replace destination
{}>)
# Move stuff back to left stack
{({}<>)<>}<>
# Add 3*orientation to degree
>({})({}){})>)
>)}{}
# Else (no crossings)
>)}{}){{}
# If this came from the 2-twist case, undo splitting.
# If this came from an initial empty input, use implicit zeros to not join anything
# New sign = sign - 2 * next entry sign
(([{}]){}<>{}{}<
# New degree = average of both degrees
<>({}<>{})
# Find coefficient corresponding to degree
{([{}]({}()()<{}({}<>)(())<>>))}{}{}
# Add sign to coefficient
{}>{})
# Move rest of polynomial back to right stack
(())<>{{}({}<>)(())<>}
# Set up next configuration
(<>)<>
}{}
}{}{}<>{}
# Step 3: Put polynomial in correct form
# Keeping constant term:
{}({}<
# Move to other stack to get access to terms of highest absolute degree
{{}({}<>)(())<>}<>
# Remove outer zeros
{{}{((<(())>))}{}}
# Move back to right stack to get access to lower order terms
{}{{}({}<>)(())<>}
>)<>
# While terms remain:
{
# Move term with positive coefficient
{}({}<(<()>)<>([]){{}({}<>)(())<>([])}{}>)<>{{}({}<>)<>}{}
# Move term with negative coefficient
{}({}<>)<>
}<>
```
[Answer]
# [K (ngn/k)](https://git.sr.ht/%7Engn/k), ~~196 193 185 177~~ 172 bytes
-2 bytes [thanks to @coltim](https://chat.stackexchange.com/transcript/message/56836284#56836284)
```
{N::2*n:#x;+/(-m-|/m:#'b)(|0,)/'b:(+/1-2*s){,/(&0|2*x;(#1_?{y[x]&:y@|x;y}[+,/y]/!N){-x+|x,:&4}/1;&0|-2*x)}'N!({(x,'1+|x;x+/:!2)}'(0<x)|:/'+(2*!n;-1+x|-x))@'/:+(0<y)=s:!n#2}
```
[Try it online!](https://ngn.bitbucket.io/k#eJx9kmFv2jAQhr/3VxjYwCaxEhvKWnvT+qkf+wcQoil1IAKSzDHFCOhv310ILV2rSZZ1Ouuee987p2r/oJTs56rjdRBRvuaHaK06vSdGD3HIot6TokEkuOxXbB9GtBsfZN9r2hHT3/vd2E+6and38Hp3HAdhtJtErQe25z44+FB1h8dIaKiAas+OvYcW3VMf9gS8ah9EqiUhS+Ofnh1U1Auo7LdyzUXgD9wzdteLVACvO/arUq28I49XV/dqX46Xk7DH6ZR2SvZdMr5U3dfXUqVjUDE5kmhrk7I0lriCzIr8xVhHrKk2K3fl1P7b2I/l5NWq+0iC5cdiqeljmmQr7bVlWO5M5Ui6yWcuK/IrR1uxhhMKEuv2Jl/mhWszSIcScjrkggzOebLN3IIkZJGsUu62GXBoWVSZy14MmdmiqrJ8zt6q+amc/7c+N/Pki3pJhloQgbJGH8vdtrgAVF8oqE6IIRkRiRDAUJDxQ5/EwH3NdNtm84XjiyR/Ns/EWZMW2Ypgm5AMpuKNcAMMjhB+5tzUHJQXY4TBDfDSbL6xhhvENpxhw0GKiAl64jXofDTlZ2ECMNcY3KLkAQBLk7vkQtX1R9rwJOwTTSAJmRLNIhgNQ3ALTLewxjSjP1Nl47XRKCRM/Gz4A1hqWbuX6H6A7tGRJPVAhAT8aDp4Hz3iRPP6r1C8Y8RJhOCWRhhADkhDIM1tkue7WiOh1WZNirTefPYMU8lmyeq8sstlIxR1osp67+R9+2JYC6878LoZRz/1B4mhYfVnk1jzueE6s7aw71+k6Teq+4A7mEVNfbN38VMaX00H45N1uTq1aLO/t/UzVA==)
ungolfed:
```
f:{ /args: x:dowker notation, y:crossing signs
N::2*n:#x /n:number of crossings, N:twice n
s:1-2*!n#2 /s:all possible sets of smoothing signs for the crossings (n*(2^n) matrix of -1 1)
S:{(x,'1+|x;0 1+\:x:(0<x)|:/y,-1+x|-x)} /S:smoothe the crossing numbered x,y in dowker notation (x can be negative)
a:N!(x S'2*!n)@'/:+~y=s /generate all possible smoothed knots (results consist of neighbour pairs that form sets of disjoint unknots)
u::{#1_?{y[x]&:|y x;y}[+,/x]/!N} /count number of disjoint unknots in a smoothed knot, minus one
/ ^^^^^^^^^^^^^^^^^^^^^ / transitive closure
g::{-x+|x,:&4} /if x=L(A) is a laurent polynomial represented as list of coefficients centred on A^0 (the constant term)
/ / then g[x] represents (-A^2-A^(-2))*L(A)
b:(+/s){,/(0<x)|:/(u[y]g/1;&2*x|-x)}'a /build a laurent polynomials for each set of smoothing signs
+/(-m-|/m:#'b)(|0,)/'b} /centre them and pad them to form a matrix and sum them to get the bracket polynomial
```
] |
[Question]
[
Olympic vine-swingers perform their routines in standard trees. In particular, Standard Tree `n` has vertices for `0` up through `n-1` and edges linking each nonzero vertex `a` to the vertex `n % a` below it. So, for example, Standard Tree 5 looks like this:
```
3
|
2 4
\ /
1
|
0
```
because the remainder when 5 is divided by 3 is 2, the remainder when 5 is divided by 2 or by 4 is 1, and the remainder when 5 is divided by 1 is 0.
This year, Tarzan will be defending his gold with new routines, each of which begins at vertex `n - 1`, swings to vertex `n - 2`, continues to vertex `n - 3`, etc., until finally he dismounts to vertex `0`.
The score for a routine is the sum of the scores for each swing (including the dismount), and the score for a swing is the distance within the tree between its start and end points. Thus, Tarzan's routine on Standard Tree 5 has a score of 6:
* a swing from `4` to `3` scores three points (down, up, up),
* a swing from `3` to `2` scores one point (down),
* a swing from `2` to `1` scores one point (down), and
* a dismount from `1` to `0` scores one point (down).
Write a program or function that, given a positive integer `n`, computes the score of Tarzan's routine on Standard Tree `n`. Sample inputs and outputs:
```
1 -> 0
2 -> 1
3 -> 2
4 -> 6
5 -> 6
6 -> 12
7 -> 12
8 -> 18
9 -> 22
10 -> 32
11 -> 24
12 -> 34
13 -> 34
14 -> 36
15 -> 44
16 -> 58
17 -> 50
18 -> 64
19 -> 60
20 -> 66
21 -> 78
22 -> 88
23 -> 68
24 -> 82
```
Rules and code scoring are as usual for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
[Answer]
# C, ~~98~~ 97 bytes
```
F(i){int c[i],t=i-2,n=0,p;for(;++n<i;)for(p=c[n]=n;p=i%p;c[p]=n)t+=c[p]<n-1;return i>2?t*2:i-1;}
```
This calculates the distance between each pair of points with the following formula:
* Add the distance from the root to node A
* Add the distance from the root to node B
* Subtract 2\* the length of the common root of A and B
This has the advantage that when applied to all pairs, it's the same as:
* Add 2\* the distance from the root to each node
* Subtract 2\* the length of the common root of each node pair
* Subtract the distance from the root to the first node
* Subtract the distance from the root to the last node
To make the logic simpler, we assume we're going from node 0 to node n-1, rather than n-1 to 0 as the question states. The distance from the root node to node 0 is obviously 0 (they're the same). And we can see that for (most) trees, the distance from the last node to the root is 2:
```
n+1 % n = 1 for all n > 1
and: n % 1 = 0 for all n >= 0
therefore: n % (n % (n-1)) = 0 for all n > 2
```
This means we have some special cases (n<2) but we can account for those easily enough.
Breakdown:
```
F(i){ // Types default to int
int c[i], // Buffer for storing paths
t=i-2, // Running total score
n=0, // Loop index
p; // Inner loop variable
for(;++n<i;) // Loop through all node pairs (n-1, n)
for(p=c[n]=n;p=i%p;c[p]=n) // Recurse from current node (n) to root
t+=c[p]<n-1; // Increase total unless this is a common
// node with the previous path
return i>2? :i-1; // Account for special cases at 1 and 2
t*2 // For non-special cases, multiply total by 2
}
```
Thanks @feersum for 1 byte saved
---
### Bonus: Trees!
I wrote a quick-and-dirty program to see what these trees look like. Here's some of the results:
```
6:
5 4
| |
1 2 3
\|/
0
```
---
```
8:
5
|
7 3 6
| \ /
1 2 4
'--\|/--'
0
```
---
```
13:
08
|
11 05 10 09 07
| \ / | |
02 03 04 06 12
'-----\ /---'--'
01
|
00
```
---
19:
```
12
|
07 14
\ /
05 15 11
\ / |
17 04 08 16 13 10
| '-\ /--' | |
02 03 06 09 18
'---------\ |/-----'--'--'
01
|
00
```
---
```
49:
31
|
30 18 36
| \ /
19 38 27 13 39 29 32
\ / | \ / | |
26 11 22 44 10 20 40 17 34
| '-\ /--' '-\ /--' \ /
47 23 46 05 09 15 45 43 41 37 33 25 35 28
| \ / '--------------\ |/-------'-----' | | | | | | |
02 03 04 06 08 12 16 24 48 14 21 42
'----'--------------------------\ |/----------------'--'--'--'--'--' \ |/
01 07
'-----------------\ /-----------------'
00
```
[Answer]
# Python 2, 85 bytes
```
def f(a,i=1):h=lambda n:n and{n}|h(a%n)or{0};return i<a and len(h(i)^h(i-1))+f(a,i+1)
```
[Answer]
# Perl, ~~65~~ ~~59~~ ~~55~~ 54 bytes
Includes +2 for `-ap`
Run with the tree size on STDIN:
```
for i in `seq 24`; do echo -n "$i: "; vines.pl <<< $i; echo; done
```
`vines.pl`:
```
#!/usr/bin/perl -ap
$_=map{${"-@F"%$_}|=$_=$$_|$"x$p++.1;/.\b/g}1-$_..-1
```
## Explanation
If you rewrite the tree
```
3
|
2 4
\ /
1
|
0
```
to one where each node contains the set of all its ancestors and itself:
```
{3}
|
{2,3} {4}
\ /
\ /
{1,2,3,4}
|
{0,1,2,3,4}
```
Then we can describe e.g. all the nodes the path from 4 to 3 as:
* All nodes that contain 3 but not 4 (going down from 3)
* All nodes that contain 4 but not 3 (going down from 4)
* The highest node that contains both 3 and 4 (the join)
The number of edges is one less than the number of nodes so we can use that to
ignore the join point, so the number of edges on the path from 4 to 3 is 3 because:
* The number of nodes that contain 3 but not 4: 2 nodes
* The number of nodes that contain 4 but not 3: 1 node
Notice that this also works for a path that directly goes down to its target, e.g. for the path from 3 to 2 the number of edges is 1 because:
* The number of nodes that contain 2 but not 3: 0 nodes
* The number of nodes that contain 3 but not 2: 1 node
We can then sum over all these combinations.
If you instead look at just a node, e.g. node 2 with ancestor set `{2,3}`. This node is going to contribute once when processing the path `2 to 1` because it contains a 2 but not a 1. It will contribute nothing for the path `3 to 2` since it has both 2 and 3, but it will contribute once when processing the path `4 to 3` since it has 3 but no 4. In general a number in the ancestor set of a node will contribute one for each neighbour (one lower of higher) that is not in the set. Except for the maximum element (4 in this case) which only contributes for the low neighbour 3 since there is no path `5 to 4`. Simular 0 is one sided, but since 0 is always at the root of the tree and contains all numbers (it is the ultimate join and we don't count joins) there is never any contribution from 0 so it's easiest to just leave node 0 out altogether.
So we can also solve the problem by looking at the ancestor set for each node, count the contributions and sum over all nodes.
To easily process neighbours I'm going to represent the ancestor sets as a string of spaces and 1's where each 1 at position p represents that n-1-p is an ancestor. So e.g. in our case of `n=5` a 1 at position 0 indicates 4 is an ancestor. I will leave off trailing spaces. So the actual representation of the tree I will build is:
```
" 1"
|
" 11" "1"
\ /
\ /
"1111"
```
Notice that I left out node 0 which would be represented by `"11111"` because I'm going to ignore node 0 (it never contributes).
Ancestors with no lower neighbour are now represented by the end of a sequence of 1's. Ancestors with no higher neighbour are now represented by the start of a sequence of 1's, but we should ignore any start of a sequence at the start of a string since this would represent the path `5 to 4` which doesn't exist. This combination is exactly matched by the regex `/.\b/`.
Building the ancestor strings is done by processing all nodes in the order `n-1 .. 1` and there set a 1 in the position for the node itself and doing an "or" into the descendant.
With all that the program is easy enough to understand:
```
-ap read STDIN into $_ and @F
map{ }1-$_..-1 Process from n-1 to 1,
but use the negative
values so we can use a
perl sequence.
I will keep the current
ancestor for node $i in
global ${-$i} (another
reason to use negative
values since $1, $2 etc.
are read-only
$$_|$"x$p++.1 "Or" the current node
position into its ancestor
accumulator
$_= Assign the ancestor string
to $_. This will overwrite
the current counter value
but that has no influence
on the following counter
values
${"-@F"%$_}|= Merge the current node
ancestor string into the
successor
Notice that because this
is an |= the index
calculation was done
before the assignment
to $_ so $_ is still -i.
-n % -i = - (n % i), so
this is indeed the proper
index
/.\b/g As explained above this
gives the list of missing
higher and lower neighbours
but skips the start
$_= A map in scalar context
counts the number of
elements, so this assigns
the grand total to $_.
The -p implicitly prints
```
Notice that replacing `/.\b/` by `/\b/` solves the roundtrip version of this problem where tarzan also takes the path `0 to n-1`
Some examples of how the ancestor strings look (given in order `n-1 .. 1`):
```
n=23:
1
1
1
1
1
1
1
1
1
1
1
11
1 1
1 1
1 1
11 11
1 1
11 1 1 11
1 1
1111 11 11 1111
111111111 111111111
1111111111111111111111
edges=68
n=24:
1
1
1
1
1
1
1
1
1
1
1
1
1 1
1 1
1 1
1 1
1 1
1 1 1 1
1 1
11 1 1 11
1 1 1 1
1 1 1 1
1 1
edges=82
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 36 bytes
```
{+/0 0⍉1↓⌊.+⍨⍛⌊⍨⍣≡⍵∨∘.(∨/,∊⍵|⍨,)⍨⍳⍵}
```
```
{+/0 0⍉1↓⌊.+⍨⍛⌊⍨⍣≡⍵∨∘.(∨/,∊⍵|⍨,)⍨⍳⍵}
(v/,∊⍵|⍨,) are either of the arguments equal to 5 mod another argument
⍵∨∘.(∨/,∊⍵|⍨,)⍨⍳⍵ matrix of distances
⌊.+⍨⍛⌊⍨⍣≡ find minimum distances between each points
+/0 0⍉1↓ drop the first row, diagonal, sum
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6u19Q0UDB71dho@apv8qKdLT/tR74pHvbOBTDBj8aPOhY96tz7qWPGoY4aeBpDW13nUAZTbWgOU19EEK9oM5Nb@TwMa@Ki371FX86PeNY96txxab/yobSLQquAgZyAZ4uEZ/B8okKlzaEXaoRWZQNVgO3s3G5kCAA "APL (Dyalog Extended) – Try It Online")
[Answer]
# Mathematica, ~~113~~ ~~103~~ 102 bytes
```
(r=Range[a=#-1];Length@Flatten[FindShortestPath[Graph[Thread[r<->Mod[a+1,r]]],#,#2]&@@{#,#-1}&/@r]-a)&
```
-10 bytes thanks to @feersum;
-1 byte thanks to @MartinEnder
The following is *far* quicker (but longer, unfortunately, at **158 bytes**):
```
(a=#;If[a<4,Part[-{1,1,1,-6},a],If[EvenQ@a,-2,1]]+a+4Total[Length@Complement[#,#2]&@@#&/@Partition[NestWhileList[Mod[a,#]&,#,#!=0&]&/@Range@Floor[a/2],2,1]])&
```
[Answer]
# J, 37 bytes
```
[:+/2(-.+&#-.~)/\|:@(]|~^:(<@>:@[)i.)
```
Usage:
```
f=.[:+/2(-.+&#-.~)/\|:@(]|~^:(<@>:@[)i.)
f 10
32
f every 1+i.20
0 1 2 6 6 12 12 18 22 32 24 34 34 36 44 58 50 64 60 66
```
[Try it online here.](http://tryj.tk/)
[Answer]
## JavaScript (ES6), ~~118~~ 116 bytes
```
n=>[...Array(n)].map(g=(_,i)=>i?[...g(_,n%i),i]:[],r=0).reduce(g=(x,y,i)=>x.map(e=>r+=!y.includes(e))&&i?g(y,x):x)|r
```
Lack of a set difference function really hurts, but some creative recursion reduces the byte count a bit. Edit: Saved 2 bytes by removing an unnecessary parameter.
] |
[Question]
[
[Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) recently hit 100K, and has come up with some [pretty awesome languages](https://github.com/m-ender?tab=repositories). We're going to have a bit of fun with one of them, [Hexagony](https://github.com/m-ender/hexagony) (and a bit of regex for [Retina](https://github.com/m-ender/retina))
As a brief overview, you need to write a program that **inputs a Hexagony grid and determines if there is a path on that grid that matches a string of text**
## Generating
Hexagony generates hexagons from a string of text using the following steps:
1. Calculate the minimum hexagon size (take the length of the string and round up to the nearest [hex number](https://oeis.org/A003215))
2. Wrapping the text into a hexagon of the above size
3. Filling the remaining locations with `.`.
For example, the string of text `abcdefghijklm` requires a hexagon of side-length 3, and therefore becomes:
```
a b c
d e f g
h i j k l
m . . .
. . .
```
Now, notice that there are 6 possible directions you can travel in a hexagon. For example, in the above hexagon, `e` is adjacent to `abfjid`.
## Wrapping
Furthermore, in Hexagony, hexagons wrap:
```
. . . . . a . . . . f . . a . .
a b c d e . . b . . . . g . . . b . . f
. . . . . . g . . c . . . . h . . a . c . . g .
. . . . . . . . h . . d . . . . u . . b . . d . . h . .
f g h i j k . i . . e . . j . . c . e . . i . .
. . . . . . j . . f k . . d . . . j . .
. . . . . k . . . . e . . k . .
```
If you look at the 2nd and 4th example, notice how `a` and `k` are in the same spots, despite the fact that you are wrapping in different directions. **Due to this fact, these spots are only adjacent to 5 other locations**.
To make this clearer:
```
a b c d
e f g h i
j k l m n o
p q r s t u v
w x y z A B
C D E F G
H I J K
```
1. Edges wrap to their opposite neighbor (`b->I` and `G->j`).
2. Top/bottom corners wrap to the opposite *center* corner and up/down (`d->K,p` and `H->a,v`).
3. Center corners wrap to both the top and bottom corners (`v->a,H`)
## Paths
A *path* to be a sequence of adjacent locations without returning to the same location.
```
a b c
d e f g
h i f k l
m . . .
. . .
```
In the above hexagon, `aefkgm` is a valid path. However, `abfd` is not a valid path (`f` and `d` aren't adjacent), and `abea` isn't valid (returns to the `a` location).
**We can use these paths to match text (like regex)**. An alpha-numeric character matches itself (and only itself), and a `.` matches any character. For example, the path `aej..lgm` would match `aej..lgm`, `aejAAlgm`, `aeja.lgm`, or `aej^%gm`.
# Input/Output
Your program should take two strings (in any order). The first string will be nonempty, and consist of only alphanumeric characters `[a-zA-Z0-9]`. This will represent the hexagon you are operating on. The second string will consist of printable characters.
**You need to return a truthy value iff there is a path in the hexagon that matches the string of text given, otherwise a falsy value.**
# Test cases
Truthy:
```
"a","a"
"ab","a"
"ab","b"
"ab","ba"
"ab","aba"
"ab","&"
"ab","#7.J!"
"ab","aaaaaa"
"ab","bgjneta"
"ab","cebtmaa"
"abcdefg","dfabcg"
"AbCDeFG","GCbAeFD"
"aaaabbb","aaababb"
"abcdefghijklmnopqrs","alq"
"abcdefghijklmnopqrs","aqnmiedh"
"abcdefghijklmnopqrs","adhcgkorbefjimnqlps"
"11122233344455","12341345123245"
"abcdefgh","h%a"
"abcdefghijklm","a)(@#.*b"
"abcdefghijklm","a)(@#.*i"
"abcdefghij","ja"
"abcdefghijklmno","kgfeia"
"abcdefghijklmno","mmmmmiea"
"abcdefghijklmno","mmmmmlae"
"abcdefghijklmno","ja"
"abcdefghijklmnopqrs","eijfbadhmnokgcsrql"
```
Falsy:
```
"a","b"
"a","%"
"a","."
"a","aa"
"a","a."
"ab","#7.J!*"
"ab","aaaaaaa"
"ab","aaaabaaa"
"ab","123456"
"abcdefg","bfgedac"
"abcdefg","gecafdb"
"abcdefg","GCbaeFD"
"aaaabbb","aaaaabb"
"abcdefghijklmnopqrs","aqrcgf"
"abcdefghijklmnopqrs","adhlcgknbeifjm"
"abcdefghijklmnopqrs","ja"
"abcdefghijklm","a)(@#.*&"
"abcdefghijklmno","a)(@bfeijk"
"abcdefghijklmno","kgfeic"
"abcdefghijklmno","mmmmmmiea"
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your answers as short as possible in your favorite language.
[Answer]
# [Retina](http://github.com/mbuettner/retina), 744 bytes
Sorry folks, no Hexagony this time...
*Byte count assumes ISO 8859-1 encoding.*
```
.+¶
$.'$*_¶$&
^_¶
¶
((^_|\2_)*)_\1{5}_+
$2_
^_*
$.&$*×_$&$&$.&$*×
M!&m`(?<=(?=×*(_)+)\A.*)(?<-1>.)+(?(1)!)|^.*$
O$`(_)|.(?=.*$)
$1
G-2`
T`d`À-É
m`\A(\D*)(?(_)\D*¶.|(.)\D*¶\2)((.)(?<=(?<4>_)\D+)?((?<=(?<1>\1.)\4\D*)|(?<=(?<1>\D*)\4(?<=\1)\D*)|(?<=\1(.(.)*¶\D*))((?<=(?<1>\D*)\4(?>(?<-7>.)*)¶.*\6)|(?<=(?<1>\D*)(?=\4)(?>(?<-7>.)+)¶.*\6))|(?<=(×)*¶.*)((?<=(?<1>\1.(?>(?<-9>¶.*)*))^\4\D*)|(?<=(?<1>\D*)\4(?>(?<-9>¶.*)*)(?<=\1)^\D*)|(?<=(?<1>\1\b.*(?(9)!)(?<-9>¶.*)*)\4×*¶\D*)|(?<=(?<1>\D*\b)\4.*(?(9)!)(?<-9>¶.*)*(?<=\1.)\b\D*))|(?<=(?<1>\1.(?>(?<-11>.)*)¶.*)\4(.)*¶\D*)|(?<=(?<1>\1(?>(?<-12>.)*)¶.*)\4(.)*¶\D*)|(?<=(?<1>\1.(?>(?<-13>.)*¶\D*))\4(\w)*\W+.+)|(?<=(?<1>.*)\4(?>(?<-14>.)*¶\D*)(?<=\1.)(\w)*\W+.+))(?<=\1(\D*).+)(?<!\1\15.*(?<-1>.)+))*\Z
```
Expects the target string on the first line and the hexagon on the second line of the input. Prints `0` or `1` accordingly.
[Try it online!](http://retina.tryitonline.net/#code=JShTYMKmCi4rwrYKJC4nJCpfwrYkJgpeX8K2CsK2CigoXl98XDJfKSopX1wxezV9XysKJDJfCl5fKgokLiYkKsOXXyQmJCYkLiYkKsOXCk0hJm1gKD88PSg_PcOXKihfKSspXEEuKikoPzwtMT4uKSsoPygxKSEpfF4uKiQKTyRgKF8pfC4oPz0uKiQpCiQxCkctMmAKVGBkYMOALcOJCm1gXEEoXEQqKSg_KF8pXEQqwrYufCguKVxEKsK2XDIpKCguKSg_PD0oPzw0Pl8pXEQrKT8oKD88PSg_PDE-XDEuKVw0XEQqKXwoPzw9KD88MT5cRCopXDQoPzw9XDEpXEQqKXwoPzw9XDEoLiguKSrCtlxEKikpKCg_PD0oPzwxPlxEKilcNCg_Pig_PC03Pi4pKinCti4qXDYpfCg_PD0oPzwxPlxEKikoPz1cNCkoPz4oPzwtNz4uKSspwrYuKlw2KSl8KD88PSjDlykqwrYuKikoKD88PSg_PDE-XDEuKD8-KD88LTk-wrYuKikqKSleXDRcRCopfCg_PD0oPzwxPlxEKilcNCg_Pig_PC05PsK2LiopKikoPzw9XDEpXlxEKil8KD88PSg_PDE-XDFcYi4qKD8oOSkhKSg_PC05PsK2LiopKilcNMOXKsK2XEQqKXwoPzw9KD88MT5cRCpcYilcNC4qKD8oOSkhKSg_PC05PsK2LiopKig_PD1cMS4pXGJcRCopKXwoPzw9KD88MT5cMS4oPz4oPzwtMTE-LikqKcK2LiopXDQoLikqwrZcRCopfCg_PD0oPzwxPlwxKD8-KD88LTEyPi4pKinCti4qKVw0KC4pKsK2XEQqKXwoPzw9KD88MT5cMS4oPz4oPzwtMTM-LikqwrZcRCopKVw0KFx3KSpcVysuKyl8KD88PSg_PDE-LiopXDQoPz4oPzwtMTQ-LikqwrZcRCopKD88PVwxLikoXHcpKlxXKy4rKSkoPzw9XDEoXEQqKS4rKSg_PCFcMVwxNS4qKD88LTE-LikrKSkqXFo&input=YcKmYQphwqZhYgpiwqZhYgpiYcKmYWIKYWJhwqZhYgomwqZhYgojNy5KIcKmYWIKYWFhYWFhwqZhYgpiZ2puZXRhwqZhYgpjZWJ0bWFhwqZhYgpkZmFiY2fCpmFiY2RlZmcKR0NiQWVGRMKmQWJDRGVGRwphYWFiYWJiwqZhYWFhYmJiCmFsccKmYWJjZGVmZ2hpamtsbW5vcHFycwphcW5taWVkaMKmYWJjZGVmZ2hpamtsbW5vcHFycwphZGhjZ2tvcmJlZmppbW5xbHBzwqZhYmNkZWZnaGlqa2xtbm9wcXJzCjEyMzQxMzQ1MTIzMjQ1wqYxMTEyMjIzMzM0NDQ1NQpoJWHCpmFiY2RlZmdoCmEpKEAjLipiwqZhYmNkZWZnaGlqa2xtCmEpKEAjLippwqZhYmNkZWZnaGlqa2xtCmphwqZhYmNkZWZnaGlqCmtnZmVpYcKmYWJjZGVmZ2hpamtsbW5vCm1tbW1taWVhwqZhYmNkZWZnaGlqa2xtbm8KbW1tbW1sYWXCpmFiY2RlZmdoaWprbG1ubwpqYcKmYWJjZGVmZ2hpamtsbW5vCmVpamZiYWRobW5va2djc3JxbMKmYWJjZGVmZ2hpamtsbW5vcHFycwpiwqZhCiXCpmEKX8KmYQphYcKmYQphX8KmYQpfIzdKISrCpmFiCiM3Sl8hKsKmYWIKYWFhYWFhYcKmYWIKYWFhYWJhYWHCpmFiCjEyMzQ1NsKmYWIKYmZnZWRhY8KmYWJjZGVmZwpnZWNhZmRiwqZhYmNkZWZnCkdDYmFlRkTCpmFiY2RlZmcKYWFhYWFiYsKmYWFhYWJiYgphcXJjZ2bCpmFiY2RlZmdoaWprbG1ub3BxcnMKYWRobGNna25iZWlmam3CpmFiY2RlZmdoaWprbG1ub3BxcnMKamHCpmFiY2RlZmdoaWprbG1ub3BxcnMKYSkoQCMuKibCpmFiY2RlZmdoaWprbG0KYSkoQGJmZWlqa8KmYWJjZGVmZ2hpamtsbW5vCmtnZmVpY8KmYWJjZGVmZ2hpamtsbW5vCm1tbW1tbWllYcKmYWJjZGVmZ2hpamtsbW5vCmFhwqZhCmFhYcKmYQphYWFhwqZhCnJmwqZhYmNkZWZnaGlqa2xtbm9wcXJz) (The first line enables a test suite, where each line is a test case, using `¦` for separation instead of a linefeed.)
The proper way to solve this challenge is with a regex of course. ;) And if it wasn't for the fact that this challenge also involves the [unfolding procedure of the hexagon](https://codegolf.stackexchange.com/q/66708/8478), this answer would actually consist of nothing but a single ~600-byte long regex.
This isn't quite optimally golfed yet, but I'm quite happy with the result (my first working version, after removing named groups and other stuff required for sanity, was around 1000 bytes). I think I could save about 10 bytes by swapping the order of the string and the hexagon but it would require a complete rewrite of the regex at the end, which I'm not feeling up to right now. There's also a 2-byte saving by omitting the `G` stage, but it slows down the solution considerably, so I'll wait with making that change until I'm sure I've golfed this as well as I can.
### Explanation
The main part of this solution makes extensive use of [balancing groups](https://stackoverflow.com/a/17004406/1633117), so I recommend reading up on them, if you want to understand how this works in detail (I won't blame you if you don't...).
The first part of the solution (i.e. everything except the last two lines) is a modified version of my answer to [Unfolding the Hexagony source code](https://codegolf.stackexchange.com/a/87581/8478). It constructs the hexagon, while leaving the target string untouched (and it actually constructs the hexagon before the target string). I've made some changes to the previous code to save bytes:
* The background character is `×` instead of a space so that it doesn't conflict with potential spaces in the input.
* The no-op/wildcard character is `_` instead `.`, so that grid cells can be reliably identified as word characters.
* I don't insert any spaces or indentation after the hexagon is first constructed. That gives me a slanted hexagon, but that is actually much more convenient to work with and the adjacency rules are fairly simple.
Here is an example. For the following test case:
```
ja
abcdefghij
```
We get:
```
××abc
×defg
hij__
____×
___××
ja
```
Compare this with the usual layout of the hexagon:
```
a b c
d e f g
h i j _ _
_ _ _ _
_ _ _
```
We can see that the neighbours are now all of the usual 8 Moore-neighbours, except the north-west and south-east neighbours. So we need to check horizontal, vertical and south-west/north-east adjacency (well and then there are the wrapping edges). Using this more compact layout also has the bonus that we'll be able to use those `××` at the end to determine the size of the hexagon on the fly when we need it.
After this form has been constructed, we make one more change to the entire string:
```
T`d`À-É
```
This replaces the digits with the extended ASCII letters
```
ÀÁÂÃÄÅÆÇÈÉ
```
Since they are replaced both in the hexagon and in the target string this won't affect whether the string is matched or not. Also, since they are letters `\w` and `\b` still identify them as hexagon cells. The benefit of doing this substitution is that we can now use `\D` in the upcoming regex to match *any* character (specifically, linefeeds as well as non-linefeed characters). We can't use the `s` option to accomplish that, because we'll need `.` to match non-linefeed characters in several places.
Now the last bit: determining whether any path matches our given string. This is done with a single monstrous regex. You might ask yourself **why?!?!** Well, this is fundamentally a backtracking problem: you start somewhere and attempt a path as long as it matches the string, and once it doesn't you backtrack and try a different neighbour from the last character that worked. The *one thing* that you get for free when working with regex is backtracking. That's literally the only thing the regex engine does. So if we just find a way to describe a valid path (which is tricky enough for this kind of problem, but definitely possible with balancing groups), then the regex engine will sort out finding that path among all possible ones for us. It would certainly be possible to implement the search manually with multiple stages ([and I've done so in the past](https://codegolf.stackexchange.com/a/58119/8478)), but I doubt it would be shorter in this particular case.
One issue with implementing this with a regex is that we can't arbitrarily weave the regex engine's cursor back and forth through the string during backtracking (which we'd need since the path might go up or down). So instead, we keep track of our own "cursor" in a capturing group and update that at every step (we can move to the position of the cursor temporarily with a lookaround). This also enables us to store all past positions which we'll use to check that we haven't visited the current position before.
So let's get to it. Here is a slightly saner version of the regex, with named groups, indentation, less random order of neighbours and some comments:
```
\A
# Store initial cursor position in <pos>
(?<pos>\D*)
(?(_)
# If we start on a wildcard, just skip to the first character of the target.
\D*¶.
|
# Otherwise, make sure that the target starts with this character.
(?<first>.)\D*¶\k<first>
)
(?:
# Match 0 or more subsequent characters by moving the cursor along the path.
# First, we store the character to be matched in <next>.
(?<next>.)
# Now we optionally push an underscore on top (if one exists in the string).
# Depending on whether this done or not (both of which are attempted by
# the engine's backtracking), either the exact character, or an underscore
# will respond to the match. So when we now use the backreference \k<next>
# further down, it will automatically handle wildcards correctly.
(?<=(?<next>_)\D+)?
# This alternation now simply covers all 6 possible neighbours as well as
# all 6 possible wrapped edges.
# Each option needs to go into a separate lookbehind, because otherwise
# the engine would not backtrack through all possible neighbours once it
# has found a valid one (lookarounds are atomic).
# In any case, if the new character is found in the given direction, <pos>
# will have been updated with the new cursor position.
(?:
# Try moving east.
(?<=(?<pos>\k<pos>.)\k<next>\D*)
|
# Try moving west.
(?<=(?<pos>\D*)\k<next>(?<=\k<pos>)\D*)
|
# Store the horizontal position of the cursor in <x> and remember where
# it is (because we'll need this for the next two options).
(?<=\k<pos>(?<skip>.(?<x>.)*¶\D*))
(?:
# Try moving north.
(?<=(?<pos>\D*)\k<next>(?>(?<-x>.)*)¶.*\k<skip>)
|
# Try moving north-east.
(?<=(?<pos>\D*)(?=\k<next>)(?>(?<-x>.)+)¶.*\k<skip>)
)
|
# Try moving south.
(?<=(?<pos>\k<pos>.(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)
|
# Try moving south-east.
(?<=(?<pos>\k<pos>(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)
|
# Store the number of '×' at the end in <w>, which is one less than the
# the side-length of the hexagon. This happens to be the number of lines
# we need to skip when wrapping around certain edges.
(?<=(?<w>×)*¶.*)
(?:
# Try wrapping around the east edge.
(?<=(?<pos>\k<pos>.(?>(?<-w>¶.*)*))^\k<next>\D*)
|
# Try wrapping around the west edge.
(?<=(?<pos>\D*)\k<next>(?>(?<-w>¶.*)*)(?<=\k<pos>)^\D*)
|
# Try wrapping around the south-east edge.
(?<=(?<pos>\k<pos>\b.*(?(w)!)(?<-w>¶.*)*)\k<next>×*¶\D*)
|
# Try wrapping around the north-west edge.
(?<=(?<pos>\D*\b)\k<next>.*(?(w)!)(?<-w>¶.*)*(?<=\k<pos>.)\b\D*)
)
|
# Try wrapping around the south edge.
(?<=(?<pos>\k<pos>.(?>(?<-x>.)*¶\D*))\k<next>(?<x>\w)*\W+.+)
|
# Try wrapping around the north edge.
(?<=(?<pos>.*)\k<next>(?>(?<-x>.)*¶\D*)(?<=\k<pos>.)(?<x>\w)*\W+.+)
)
# Copy the current cursor position into <current>.
(?<=\k<pos>(?<current>\D*).+)
# Make sure that no matter how many strings we pop from our stack of previous
# cursor positions, none are equal to the current one (to ensure that we use
# each cell at most once).
(?<!\k<pos>\k<current>.*(?<-pos>.)+)
)*
# Finally make sure that we've reached the end of the string, so that we've
# successfully matched all characters in the target string.
\Z
```
I hope that the general idea is roughly clear from this. As an example for how one of those movements along the path works, let's look at the bit that moves the cursor south:
```
(?<=(?<pos>\k<pos>.(?>(?<-x>.)*)¶.*)\k<next>(?<x>.)*¶\D*)
```
Remember that lookbehinds should be read from right to left (or bottom to top), because that's the order they are executed in:
```
(?<=
(?<pos>
\k<pos> # Check that this is the old cursor position.
. # Match the character directly on top of the new one.
(?>(?<-x>.)*) # Match the same amount of characters as before.
¶.* # Skip to the next line (the line, the old cursor is on).
) # We will store everything left of here as the new
# cursor position.
\k<next> # ...up to a match of our current target character.
(?<x>.)* # Count how many characters there are...
¶\D* # Skip to the end of some line (this will be the line below
# the current cursor, which the regex engine's backtracking
# will determine for us).
)
```
Note that it's not necessary to put an anchor in front of the `\k<pos>` to ensure that this actually reaches the beginning of the string. `<pos>` always starts with an amount of `×` that can't be found anywhere else, so this acts as an implicit anchor already.
I don't want to bloat this post more than necessary, so I won't go into the other 11 cases in detail, but in principle they all work similarly. We check that `<next>` can be found in some specific (admissible) direction from the old cursor position with the help of balancing groups, and then we store the string up to that match as the new cursor position in `<pos>`.
[Answer]
# Python 3, ~~990~~ ~~943~~ ~~770~~ 709 bytes
First answer, yay!
EDIT: Golfed adjacency list making. I now use a slightly different formula
EDIT 2: Removed unnecessary fluff, golfed a lot more.
EDIT 3: Shortened the code for conversion from index in list to coordinates, golfed a few more things.
The majority of the bytes relates to making the adjacency list (it has the most potential to be golfed). From then, it's a simple matter of brute-forcing the solution (which I might be able to do in less bytes).
### Golfed:
```
from math import*
b=abs
c=max
e=range
f=len
A=input()
B=input()
C=ceil(sqrt((f(A)-.25)/3)+.5)
D=3*C*~-C+1
E=2*C-1
F=C-1
A+='.'*(D-f(A))
G=[set()for x in e(D)]
I=lambda H:sum(E+.5-b(t-F+.5)for t in e(int(H+F)))
for x in e(D):
r=sum([[J-F]*(E-b(J-F))for J in e(E)],[])[x];q=x-I(r);s=-q-r;a=lambda q,r:G[x].add(int(q+I(r)));m=c(map(b,[q,r,s]))
if m==F:
if q in(m,-m):a(-q,-s)
if r in(m,-m):a(-s,-r)
if s in(m,-m):a(-r,-q)
for K,L in zip([1,0,-1,-1,0,1],[0,1,1,0,-1,-1]):
M,H=q+K,r+L
if c(map(b,[M,H,-M-H]))<C:a(M,H)
def N(i,O,P):
Q=O and O[0]==A[i]or'.'==A[i];R=0
if(2>f(O))*Q:R=1
elif Q:R=c([(x not in P)*N(x,O[1:],P+[i])for x in G[i]]+[0])
return R
print(c([N(x,B,[])for x in e(D)])*(f(B)<=D))
```
### Ungolfed w/ explanation:
```
from math import*
#Rundown of the formula:
# * Get data about the size of the hexagon
# * Create lookup tables for index <-> coordinate conversion
# * q=0, r=0 is the center of the hexagon
# * I chose to measure in a mix of cubic and axial coordinates,
# as that allows for easy oob checks and easy retrevial
# * Create the adjacency list using the lookup tables, while
# checking for wrapping
# * Brute-force check if a path in the hexagon matches the
# expression
# shorten functions used a lot
b=abs
c=max
e=range
# Get input
prog=input()
expr=input()
# sdln = Side length
# hxln = Closest hexagonal number
# nmrw = Number of rows in the hexagon
# usdl = one less than the side length. I use it a lot later
sdln=ceil(sqrt((len(prog)-.25)/3)+.5)
hxln=3*sdln*~-sdln+1
nmrw=2*sdln-1
usdl=sdln-1
# Pad prog with dots
prog+='.'*(hxln-len(prog))
# nmbf = Number of elements before in each row
# in2q = index to collum
# in2r = index to row
nmbf=[0]*nmrw
in2q=[0]*hxln
in2r=[0]*hxln
# 4 5
# \ /
# 3 -- -- 0
# / \
# 2 1
# dirs contains the q,r and s values needed to move a point
# in the direction refrenced by the index
qdir=[1,0,-1,-1,0,1]
rdir=[0,1,1,0,-1,-1]
# generate nmbf using a summation formula I made
for r in e(nmrw-1):
nmbf[r+1]=int(nmbf[r]+nmrw+.5-b(r-sdln+1.5))
# generate in2q and in2r using more formulas
# cntr = running counter
cntr=0
for r in e(nmrw):
bgnq=c(-r,1-sdln)
for q in e(nmrw-b(r-sdln+1)):
in2q[cntr]=bgnq+q
in2r[cntr]=r-usdl
cntr+=1
# adjn = Adjacency sets
adjn=[set()for x in e(hxln)]
# Generate adjacency sets
for x in e(hxln):
#Get the q,r,s coords
q,r=in2q[x],in2r[x]
s=-q-r
# a = function to add q,r to the adjacency list
a=lambda q,r:adjn[x].add(q+nmbf[r+usdl])
# m = absolute value distance away from the center
m=c(map(b,[q,r,s]))
# if we are on the edge (includes corners)...
if m==usdl:
# add the only other point it wraps to
if q in(m,-m):
a(-q,-s)
if r in(m,-m):
a(-s,-r)
if s in(m,-m):
a(-r,-q)
# for all the directions...
for d in e(6):
# tmp{q,r,s} = moving in direction d from q,r,s
tmpq,tmpr=q+qdir[d],r+rdir[d]
# if the point we moved to is in bounds...
if c(map(b,[tmpq,tmpr,-tmpq-tmpr]))<sdln:
# add it
a(tmpq,tmpr)
# Recursive path checking function
def mtch(i,mtst,past):
# dmch = Does the place we are on in the hexagon match
# the place we are in the expression?
# out = the value to return
dmch=mtst and mtst[0]==prog[i]or'.'==prog[i]
out=0
# if we are at the end, and it matches...
if(2>len(mtst))*dmch:
out=1
# otherwise...
elif dmch:
# Recur in all directions that we haven't visited yet
# replace '*' with 'and' to speed up the recursion
out=c([(x not in past)*mtch(x,mtst[1:],past+[i])for x in adjn[i]]+[0])
return out
# Start function at all the locations in the hexagon
# Automatically return false if the expression is longer
# than the entire hexagon
print(c([mtch(x,expr,[])for x in e(hxln)])*(len(expr)<=hxln))
```
~~So close to Retina! :(~~ Yay, beat Retina!
[Answer]
## Javascript (ES6), ~~511~~ ~~500~~ 496 bytes
```
(H,N)=>{C=(x,y)=>(c[x]=c[x]||[])[y]=y;S=d=>(C(x,y=x+d),C(y,x),C(s-x,s-y),C(s-y,s-x));r=(x,p,v)=>{p<N.length?(v[x]=1,c[x].map(n=>!v[n]&&(H[n]==N[p]||H[n]=='.')&&r(n,p+1,v.slice()))):K=1};for(e=x=K=0;(s=3*e*++e)<(l=H.length)-1;);H+='.'.repeat(s+1-l);for(a=[],b=[],c=[[]],w=e;w<e*2;){a[w-e]=x;b[e*2-w-1]=s-x;for(p=w;p--;x++){w-e||S(s-e+1);w<e*2-1&&(S(w),S(w+1));p&&S(1)}a[w]=x-1;b[e*3-++w]=s-x+1}a.map((v,i)=>S(b[i]-(x=v)));[N[0],'.'].map(y=>{for(x=-1;(x=H.indexOf(y,x+1))>-1;r(x,1,[]));});return K}
```
### Ungolfed and commented
```
// Entry point
// H = haystack (the string the hexagon is filled with)
// N = needle (the substring we're looking for)
(H, N) => {
// C(x, y) - Helper function to save a connection between two locations.
// x = source location
// y = target location
C = (x, y) => (c[x] = c[x] || [])[y] = y;
// S(d) - Helper function to save reciprocal connections between two locations
// and their symmetric counterparts.
// d = distance between source location (x) and target location
S = d => (C(x, y = x + d), C(y, x), C(s - x, s - y), C(s - y, s - x));
// r(x, p, v) - Recursive path search.
// x = current location in hexagon
// p = current position in needle
// v = array of visited locations
r = (x, p, v) => {
p < N.length ?
(v[x] = 1, c[x].map(n => !v[n] && (H[n] == N[p] || H[n] == '.') &&
r(n, p + 1, v.slice())))
:
K = 1
};
// Compute e = the minimum required edge width of the hexagon to store the haystack.
// Also initialize:
// x = current location in hexagon
// l = length of haystack
// s = size of hexagon (number of locations - 1)
// K = fail/success flag
for(e = x = K = 0; (s = 3 * e * ++e) < (l = H.length) - 1;);
// Pad haystack with '.'
H += '.'.repeat(s + 1 - l);
// Build connections c[] between locations, using:
// x = current location
// w = width of current row
// p = position in current row
// Also initialize:
// a[] = list of locations on top left and top right edges
// b[] = list of locations on bottom left and bottom right edges
for(a = [], b = [], c = [[]], w = e; w < e * 2;) {
a[w - e] = x;
b[e * 2 - w - 1] = s - x;
for(p = w; p--; x++) {
// connection between top and bottom edges
w - e || S(s - e + 1);
// connections between current location and locations below it
w < e * 2 - 1 && (S(w), S(w + 1));
// connection between current location and next location
p && S(1)
}
a[w] = x - 1;
b[e * 3 - ++w] = s - x + 1
}
// Save connections between top left/right edges and bottom left/right edges.
a.map((v, i) => S(b[i] - (x = v)));
// Look for either the first character of the needle or a '.' in the haystack,
// and use it as the starting point for the recursive search. All candidate
// locations are tried out.
[N[0], '.'].map(y => {
for(x = -1; (x = H.indexOf(y, x + 1)) > -1; r(x, 1, []));
});
// Return fail/success flag.
return K
}
```
### Test cases
The snippet below will walk through all truthy and falsy test cases.
```
let f =
(H,N)=>{C=(x,y)=>(c[x]=c[x]||[])[y]=y;S=d=>(C(x,y=x+d),C(y,x),C(s-x,s-y),C(s-y,s-x));r=(x,p,v)=>{p<N.length?(v[x]=1,c[x].map(n=>!v[n]&&(H[n]==N[p]||H[n]=='.')&&r(n,p+1,v.slice()))):K=1};for(e=x=K=0;(s=3*e*++e)<(l=H.length)-1;);H+='.'.repeat(s+1-l);for(a=[],b=[],c=[[]],w=e;w<e*2;){a[w-e]=x;b[e*2-w-1]=s-x;for(p=w;p--;x++){w-e||S(s-e+1);w<e*2-1&&(S(w),S(w+1));p&&S(1)}a[w]=x-1;b[e*3-++w]=s-x+1}a.map((v,i)=>S(b[i]-(x=v)));[N[0],'.'].map(y=>{for(x=-1;(x=H.indexOf(y,x+1))>-1;r(x,1,[]));});return K}
let truthy = [
["a","a"],
["ab","a"],
["ab","b"],
["ab","ba"],
["ab","aba"],
["ab","&"],
["ab","#7.J!"],
["ab","aaaaaa"],
["ab","bgjneta"],
["ab","cebtmaa"],
["abcdefg","dfabcg"],
["AbCDeFG","GCbAeFD"],
["aaaabbb","aaababb"],
["abcdefghijklmnopqrs","alq"],
["abcdefghijklmnopqrs","aqnmiedh"],
["abcdefghijklmnopqrs","adhcgkorbefjimnqlps"],
["11122233344455","12341345123245"],
["abcdefgh","h%a"],
["abcdefghijklm","a)(@#.*b"],
["abcdefghijklm","a)(@#.*i"],
["abcdefghij","ja"],
["abcdefghijklmno","kgfeia"],
["abcdefghijklmno","mmmmmiea"],
["abcdefghijklmno","mmmmmlae"],
["abcdefghijklmno","ja"],
["abcdefghijklmnopqrs","eijfbadhmnokgcsrql"]
];
let falsy = [
["a","b"],
["a","%"],
["a","."],
["a","aa"],
["a","a."],
["ab","#7.J!*"],
["ab","aaaaaaa"],
["ab","aaaabaaa"],
["ab","123456"],
["abcdefg","bfgedac"],
["abcdefg","gecafdb"],
["abcdefg","GCbaeFD"],
["aaaabbb","aaaaabb"],
["abcdefghijklmnopqrs","aqrcgf"],
["abcdefghijklmnopqrs","adhlcgknbeifjm"],
["abcdefghijklmnopqrs","ja"],
["abcdefghijklm","a)(@#.*&"],
["abcdefghijklmno","a)(@bfeijk"],
["abcdefghijklmno","kgfeic"],
["abcdefghijklmno","mmmmmmiea"]
];
console.log(
'Testing truthy test cases:',
truthy.every(v => f(v[0], v[1])) ? 'passed' : 'failed'
);
console.log(
'Testing falsy test cases:',
falsy.every(v => !f(v[0], v[1])) ? 'passed' : 'failed'
);
```
] |
[Question]
[
Given a snippet of ***fizz buzz*** output with all numbers removed, fill in the correct numbers with the lowest possible values such that the ***fizz buzz*** snippet is correct. For the purposes of this challenge, `fizz` and `buzz` have their usual values of 3 and 5, respectively.
If the input is an invalid sequence of `fizz`, `buzz` and empty lines, then instead output just `zzubzzif` (with or without newlines).
Input and output may be newline separated lines, or whatever array-of-strings format is convenient to your language.
You may ignore or do whatever you like with capitalisation.
You will need to choose to handle one or more of these: `fizzbuzz`, `fizz buzz`, `buzz fizz`, etc, but you must choose at least one of these formats.
You may assume that all input is some sequence of `fizz`, `buzz` and empty lines.
# Examples
Input:
```
fizz
```
Output:
```
2
fizz
4
```
Input:
```
buzz
fizz
```
Output:
```
buzz
fizz
7
```
Input:
```
fizzbuzz
```
Output:
```
13
14
fizzbuzz
16
17
```
Input:
```
```
Output:
```
1
```
Input:
```
fizz
fizz
```
Output:
```
zzubzzif
```
Input:
```
```
Output:
```
zzubzzif
```
[Answer]
# Java, 205 bytes
```
s->{o:for(int i=0,j,h=s.length;++i<16;){for(j=h;j-->0;)if(s[j].contains("fizz")^(i+j)%3<1||s[j].contains("buzz")^(i+j)%5<1)continue o;String z=i+"";for(j=1;j<h;)z+="\n"+(i+j++);return z;}return"zzubzzif";}
```
Takes a `String[]` as input and returns a `String`.
Expanded, runnable code:
```
public class C {
static final java.util.function.Function<String[], String> f = s -> {
o:
for (int i = 0, j, h = s.length; ++i < 16;) {
for (j = h; j --> 0;) {
if (s[j].contains("fizz") ^ (i + j) % 3 < 1 ||
s[j].contains("buzz") ^ (i + j) % 5 < 1) {
continue o;
}
}
String z = i + "";
for (j = 1; j < h;) {
z += "\n" + (i + j++);
}
return z;
}
return "zzubzzif";
};
public static void main(String[] args) {
System.out.print(f.apply(new String[]{"fizz", "", "buzz"}));
}
}
```
[Answer]
# C#, 212 bytes
I did the unthinkable. I used a `goto` statement to break out of a loop!
```
string[]R(string[]a){for(int i,l=a.Length,n=0;n++<15;){for(i=l;i-->0;)if(((n+i)%3<1?"fizz":"")+((n+i)%5<1?"buzz":"")!=a[i])goto z;for(i=l;i-->0;)a[i]=a[i]==""?""+(n+i):a[i];return a;z:;}return new[]{"zzubzzif"};}
```
This takes advantage of the fact that the sequence must start within the first 15 elements.
Indentation and new lines for readability:
```
string[]R(string[]a){
for(int i,l=a.Length,n=0;n++<15;){
for(i=l;i-->0;)
if(((n+i)%3<1?"fizz":"")+((n+i)%5<1?"buzz":"")!=a[i])
goto z;
for(i=l;i-->0;)
a[i]=a[i]==""?""+(n+i):a[i];
return a;
z:;
}
return new[]{"zzubzzif"};
}
```
[Answer]
# CJam, 72 bytes
```
"zzubzzif":MaqN/:Q,_F+{)_[Z5]f%:!MW%4/.*s\e|}%ew{:sQ1$A,sff&:s.e|=}=N*o;
```
The program will [exit with an error](https://codegolf.meta.stackexchange.com/a/4781) if it has to print **zzubzzif**.
Using the Java interpreter, STDERR can be closed to suppress an eventual error message. If you try the program in the [CJam interpreter](http://cjam.aditsu.net/#code=%22zzubzzif%22%3AMaqN%2F%3AQ%2C_F%2B%7B)_%5BZ5%5Df%25%3A!MW%254%2F.*s%5Ce%7C%7D%25ew%7B%3AsQ1%24A%2Csff%26%3As.e%7C%3D%7D%3DN*o%3B&input=%0A%0Afizzbuzz%0A%0A), ignore all output after the first line.
### How it works
```
"zzubzzif" e# Push that string.
:Ma e# Save it in M and wrap in in an array.
qN/:Q e# Split the input into lines and save in Q.
,_F+ e# Count the lines and add 15 to a copy of the result.
{ e# For each integer I between 0 and lines+14:
)_ e# Increment I and push a copy.
[Z5] e# Push [3 5].
f% e# Map % to push [(I+1)%3 (I+1)%5].
:! e# Apply logical NOT to each remainder.
MW%4/ e# Push ["fizz" "buzz"].
.* e# Vectorized string repetition.
s\ e# Flatten the result and swap it with I+1.
e| e# Logical OR; if `s' pushed an empty string, replace it with I+1.
}% e#
ew e# Push the overlapping slices of length "lines".
{ e# Find; for each slice:
:s e# Cast its elements to string (e.g., 1 -> "1").
Q1$ e# Push the input and a copy of the slice.
A,s e# Push "0123456789".
ff& e# Intersect the slice's strings' characters with that string.
:s e# Cast the results to string. This replaces "fizz", "buzz"
e# and "fizzbuzz" with empty strings.
.e| e# Vectorized logical OR; replace empty lines of the input
e# with the corresponding elements of the slice.
= e# Check the original slice and the modified input for equality.
}= e# Push the first match or nothing.
e# We now have ["zzubzzif"] and possibly a solution on the stack.
N* e# Join the topmost stack item, separating by linefeeds.
o e# Print the result.
; e# Discard the remaining stack item, if any.
```
[Answer]
# Perl, 140 bytes
```
$f=fizz;$b=buzz;@a=<>;@x=map{s!\d!!gr.$/}@s=map{$_%15?$_%3?$_%5?$_:$b:$f:$f.$b}(++$c..$c+$#a)while$c<15&&"@x"ne"@a";print$c<15?"@s":zzubzzif
```
**Explanation**
1. `@a` is the array of input lines
2. Inside the `while` loop,
3. `@s` has the generated fizz-buzz sequence
4. `@x` is the same as `@s` but with numbers replaced with empty strings and a new line appened to every element (to match with `@a`)
5. `$c` is a counter from 1 to 15
6. The loop runs till `@x` becomes the same as the input `@a`
7. Outside the loop, the output is `@s` or zzufzzib based on whether `$c` was in its limits or not
[Answer]
# Python, 176 Bytes
Could probably do a lot better, but first attempt at Golf. Tips appreciated :)
Shrunk
```
def f(a):l=len(a);g=lambda n:'fizz'*(n%3<1)+'buzz'*(n%5<1);r=range;return next(([g(x)or x for x in r(i%15,i%15+l)]for i in r(1,16)if all(g(i+x)==a[x]for x in r(l))),g(0)[::-1])
```
Original
```
def f(a):
l = len(a)
g = lambda n: 'fizz'*(n%3<1)+'buzz'*(n%5<1)
r = range
return next(
(
[g(x) or x for x in r(i % 15,i % 15 + l)]
for i in r(1,16)
if all(
g(i + x) == a[x] for x in r(l)
)
),
g(0)[::-1]
)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 127 bytes
```
f=(n,j=1)=>j<99?(M=n.map((e,i)=>e?e:j+i)).some((e,i)=>e!=((J=j+i)%3?J%5?J:'buzz':'fizz'+(J%5?'':'buzz')))?f(n,j+1):M:'zzubzzif'
```
[Try it online!](https://tio.run/##jZNda4MwFIbv9yuyi5KEZorfRmaFDXZR1l@wDmpt7BSrUu0G/vnuWGuYYV8XITnnxPd5Lkwev8dNcszq9q6sduJ8TkNSsjw0aLjI7zmPyCostUNcEyJYBk0RiSCfZ5RqTXUQsnsbErIM@8HMipYzJ1oGeHvqOhzgNINtTvomxtcupTRKe9DcoMEqwF132nZdluJzUpVNVQitqPYkJS8YMzQkwI5fKb1RL1zy/rp0GVwvjR/8fPm75hj/L8wv8RuDIZOhJ4hhyGbo4dQfhtJjyB/PQ98wxtqwYNlDdZ25sDw559MsEyCmNU0zXTkFjsm/pllAsqSYpZhZwLEUN1u62cCxJ242kGzpZituDnAcxc2Rbg5wnImbCyRXurmKmwscV3HzpJsHHG/i5gHJk26e4uYDx1fcfOnmA8efuHEgcenGFTcOHD5x22hHURdxIojOkL6Hn2RdYnhMdZG1ZDj3r00UKFwgUUDRJm9EX@90GsEPFfS9tnquPsTxMW4EgZdEz58 "JavaScript (Node.js) – Try It Online")
I came across this challenge by accident after clicking on one of the answerers' profiles. Expects an array of lowercase strings.
## How?
FizzBuzz loops every 15 lines, which means that we can reasonably expect that by the time the start counter reaches 99, we will have looped through fizzbuzz a few times, hence allowing us to stop the recursion and instead output "zzubzzif".
If the counter is still less than 99, then we first fill in the falsy lines (empty strings) with their numbers, and check if it makes a valid FizzBuzz snippet using `some`. If one doesn't fit in, then recall the function with `j+1`. Otherwise return `M`.
[Answer]
# [Python 2](https://docs.python.org/2/), 173 bytes
```
import re
def f(u,i=0,s=""):
exec"s+=`i%3/2*'Fizz'+i%5/4*'Buzz'or-~i`+' ';i+=1;"*100;s=s.replace("'","");return re.findall(' '.join(['\d+'if not x else x for x in u]),s)[0]
```
[Try it online!](https://tio.run/##JY67isMwFER7f4UQhCtZiuM8tlmjZov9CceQEF@RGxzJ6AFZF/l1ryDNDFOcmZn/0t27w5pND6Dhl5alGAwrPWcfEgtYjWiZFVmTaXU0nMvviuELbzwqc6HNcXeoP5yizdfuVMNPLsGH7ZsuChh0pMy@4/W@bbtoYhNwnq43FBy4Lm1dwJSDK0uNJTdep0kUqHl4cqKH86iALHM@sRfDKWIx60NRciwPUkfZt8M6B3JJlJdSrv8 "Python 2 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 200 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 25 bytes
```
L:↵ƛ₍₃₅kF½ɽ*∑∴;l'vSǍ?⁼;h:[|kF⇩Ṙ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiTDrihrXGm+KCjeKCg+KChWtGwr3JvSriiJHiiLQ7bCd2U8eNP+KBvDtoOlt8a0bih6nhuZgiLCIiLCJbXCJidXp6XCIsIFwiZml6elwiLCBcIlwiXSJd)
Modern golfing languages with fractional byte encodings amiright.
I got this down from 27.something bytes to 25 bytes in drafts through a lot of fiddling with element ordering.
## Explained
```
L:↵ƛ₍₃₅kF½ɽ*∑∴;l'vSǍ?⁼;h:[|kF⇩Ṙ
L:↵ƛ₍₃₅kF½ɽ*∑∴; # Generate fizzbuzz for the first (10 ** len(input)) numbers using the standard fizzbuzz approach.
l # in windows of len(input)
' # filtered to keep only
vSǍ # windows where all converted to string with digits removed
?⁼ # exactly equals the input
h:[|kF⇩Ṙ # if that's an empty list, return the string "zzibzzuf", else the first item.
```
] |
[Question]
[
## Introduction
In this challenge, we will be dealing with a certain ordering of the positive integers.
The ordering goes like this:
```
3, 5, 7, 9, 11, ...
2*3, 2*5, 2*7, 2*9, 2*11, ...
4*3, 4*5, 4*7, 4*9, 4*11, ...
8*3, 8*5, 8*7, 8*9, 8*11, ...
16*3, 16*5, 16*7, 16*9, 16*11, ...
...
... 64, 32, 16, 8, 4, 2, 1
```
We first list all odd integers greater than 1 in ascending order.
Then we list two times odd integers greater than 1, then 4 times, then 8 times, and so on: for all **k**, we list **2k** times the odd integers greater than 1 in ascending order.
Finally, we list the powers of two in *descending* order, ending at 1.
Every positive integer occurs in this "list" exactly once.
More explicitly, consider two distinct positive integers **A = n·2p** and **B = m·2q**, where **n, m ≥ 1** are odd, and **p, q ≥ 0**.
Then **A** comes before **B** in the ordering, if one of the following conditions holds:
* **n > 1**, **m > 1** and **p < q**
* **1 < n < m** and **p = q**
* **n > m = 1**
* **n = m = 1** and **p > q**
This ordering appears in the surprising mathematical result known as [Sharkovskii's theorem](https://en.wikipedia.org/wiki/Sharkovskii's_theorem), which concerns the periodic points of dynamical systems.
I will not go into the details here.
## The task
Your task in this challenge is to compute the above ordering.
Your inputs are two positive integers **A** and **B**, which may be equal.
Your output is a truthy value if **A** comes before **B** in the ordering, and a falsy value otherwise.
If **A = B**, your output should be truthy.
You can take **A** and **B** in either order, as long as you're consistent.
You don't have to worry about integer overflow, but your algorithm should theoretically work for arbitrarily large inputs.
## Test cases
Truthy instances
```
3 11
9 6
48 112
49 112
158 158
36 24
14 28
144 32
32 32
32 8
3 1
1 1
```
Falsy instances
```
1 2
1 5
11 5
20 25
2 8
256 255
256 257
72 52
2176 1216
2176 2496
```
[Answer]
## JavaScript (ES6), ~~53~~ 49 bytes
```
f=(a,b)=>b<2||a>1&&(a&b&1?a<=b:a&1|~b&f(a/2,b/2))
```
Explanation:
* If b is 1, then a precedes (or equals) b
* Otherwise, if a is 1, then a does not precede b
* Otherwise, if both a and b are odd, then use regular inequality check
* Otherwise, if a is odd, then it precedes b
* Otherwise, if b is odd, then a does not precede b
* Otherwise, divide both a and b by 2 and try again.
Edit: Saved 2 bytes thanks to @Arnauld.
[Answer]
# Python 2, 87 71 bytes
```
k=lambda n:[n&~-n<1,(n&-n)*cmp(n&~-n,1),n/(n&-n)]
lambda a,b:k(a)<=k(b)
```
This probably won't win any size awards, but this answer works by constructing a 3-tuple using 3 expressions from an integer that when lexicographically ordered will result in the correct ordering.
In readable terms, the tuple is for **A = n·2p**:
```
[n == 0, p * (1 - 2*(n == 0)), n]
```
[Answer]
## Python 2, 50 bytes
```
lambda*l:cmp(*[([-n][n&n-1:],n&-n,n)for n in l])<1
```
Each number is mapped to a triple whose sorted order is the desired order.
* The primary value is `[-n][n&n-1:]`, which handles the powers of 2 at the end. The bitwise "and" `n&n-1` is zero exactly when `n` is a power of `2`. If so, we get the list `[-n]`, and otherwise the empty list `[]`. This puts all powers of 2 at the end of the order, in decreasing order.
* The secondary value `n&-n` extracts the power-of-2 factor of `n`.
* The final value `n` tiebreaks equal powers of 2 in favor of the greater number.
The respective tuples are passed to `cmp` to see if that comparison is `<=0`. Python 3 would save a byte with float division `(n&n-1<1)/n` for the first value in the triple, but lacks `cmp`.
[Answer]
## JavaScript (ES6), ~~70~~ 64 bytes
Could probably be golfed some more, but as a first attempt:
```
x=>y=>(a=x&-x,x/=a,b=y&-y,y/=b,y<2?x>1|b<=a:x>1&(b>a|b==a&y>=x))
```
Takes input with currying syntax `(x)(y)`. Returns `0` / `1`.
### Test cases
```
let f =
x=>y=>(a=x&-x,x/=a,b=y&-y,y/=b,y<2?x>1|b<=a:x>1&(b>a|b==a&y>=x))
console.log('Testing truthy instances ...');
console.log(f(3)(11));
console.log(f(9)(6));
console.log(f(48)(112));
console.log(f(49)(112));
console.log(f(158)(158));
console.log(f(36)(24));
console.log(f(14)(28));
console.log(f(144)(32));
console.log(f(32)(32));
console.log(f(32)(8));
console.log(f(3)(1));
console.log(f(1)(1));
console.log('Testing falsy instances ...');
console.log(f(1)(2));
console.log(f(1)(5));
console.log(f(11)(5));
console.log(f(20)(25));
console.log(f(2)(8));
console.log(f(256)(255));
console.log(f(256)(257));
console.log(f(72)(52));
console.log(f(2176)(1216));
console.log(f(2176)(2496));
```
[Answer]
# [Perl 6](http://perl6.org/), ~~89~~ 84 bytes
```
->\a,\b{my \u=*>max a,b;a==first a|b,flat [1,2,4...u].&{(3*$_,5*$_...u for $_),.reverse}}
```
```
{my \u=*>@_.max;@_[0]==first @_.any,flat [1,2,4...u].&{.map(*X*(3,5...u)),.reverse}}
```
([Try it online.](https://tio.run/#VHmyh))
Not exactly short, but I thought it would be interesting to write a solution that actually generates the ordering sequence (up to a safe upper bound for each sub-sequence), and then checks which input appears in it first.
For example:
* For input `2, 3` it generates:
```
3 5
6
12
4 2 1
```
...and then observes that `3` appears before `2`.
* For input `9, 6` it generates:
```
3 5 7 9 11
6 10
12
24
48
16 8 4 2 1
```
...and then observes that `9` appears before `6`.
It could be smarter and generate even less of the sequence, but that would take more bytes of code.
[Answer]
# Python 2, 54 bytes
```
f=lambda a,b:b<2or[f(a/2,b/2),a>1,0,1<a<=b][a%2+b%2*2]
```
A recursive solution similar to Neil's.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 27 bytes
```
1⊃∘⍋⍮⍥{p⍵⍮⍨-⍵⍴⍨⍵=2*p←⊥⍨~⊤⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/w0fdTU/6pjxqLf7Ue@6R71Lqwse9W4FM1fogllbgCwgw9ZIqwCo4VHXUiC/7lHXEqBY7f80kFBvH8S4ruZD640ftU0E8oKDnIFkiIdn8H/1nNS0EoXMYoXUioLU5JLUFIWSotJUHYWizPQMsHhaYk5xqjqXhpGJQpqCiYGmgoaJAZBlZKIJFbMAiVnAxcCyJhYgdRYQHVwQFkIdUJZLV1cXqt/MBChuZgLVDxYH84yNgOLGRhAVYHEjiCIA "APL (Dyalog Extended) – Try It Online")
A tacit dyadic function whose left argument is `a` and the right is `b`.
The approach is almost identical to [xnor's Python 2 solution](https://codegolf.stackexchange.com/a/103993/78410), in that we convert each number to a nested array and do lexicographical comparison between them.
### Part 1: Convert number to nested array
```
{p⍵⍮⍨-⍵⍴⍨⍵=2*p←⊥⍨~⊤⍵} ⍝ Input: positive integer N
⊤⍵ ⍝ Convert N to binary digits
~ ⍝ Flip all the bits (1 to 0, 0 to 1)
p←⊥⍨ ⍝ Count trailing ones and assign it to p
⍝ (maximum power of 2 that divides N)
⍵=2* ⍝ Test if N itself is equal to 2^p
-⍵⍴⍨ ⍝ If true, create 1-element array containing -N;
⍝ otherwise, an empty array
p⍵⍮⍨ ⍝ Form a 2-element nested array;
⍝ 1st element is the above, 2nd is [p, N]
```
### Part 2: Compare two nested arrays
```
1⊃∘⍋⍮⍥f ⍝ Input: A (left) and B (right)
⍥f ⍝ Evaluate f A and f B
⍮ ⍝ Create a 2-element nested array [f A, f B]
⍋ ⍝ Grade up; indexes of array elements to make it sorted
⍝ Here, the result is [0 1] if A ≤ B, [1 0] otherwise
1⊃∘ ⍝ Take the element at index 1 (0-based)
```
The dfn syntax does support conditional statements e.g. `{a:x ⋄ b:y ⋄ z}` meaning `if a then x else if b then y else z`, but it's way too verbose to use in this case.
[Answer]
# Mathematica, 65 bytes
```
OrderedQ[{1,#}&/@#//.{a_,b_/;EvenQ@b}->{2a,b/2}/.{a_,1}->{∞,-a}]&
```
Unnamed function taking a list of positive integers and returning `True` if the list forms an ascending sequence in the Sharkovskii order, `False` otherwise. (In particular, the input list doesn't have to have only two elements—we get the added functionality for free.)
The heart of the algorithm is the function `{1,#}&/@#//.{a_,b_/;EvenQ@b}->{2a,b/2}`, which repeatedly moves factors of 2 around to convert an integer of the form `m*2^k`, with `m` odd, to the ordered pair `{2^k,m}` (and does so to every element of the input list). `OrderedQ` then decides whether the resulting list of ordered pairs is already sorted; by default, that means in increasing order by the first element, then increasing order by the second element.
That's exactly what we want, except numbers that are powers of 2 follow different rules. So before checking in with `OrderingQ`, we apply one last rule `/.{a_,1}->{∞,-a}`, which converts (for example) `{64,1}` to `{∞,-64}`; that puts powers of 2 in the correct spot in the ordering.
[Answer]
# Haskell, ~~143~~ 138 bytes
Basically a relatively straightforward implementation of the criteria:
```
e n=head[k-1|k<-[0..],n`mod`(2^k)>0] -- exponent of 2
f n=n`div`2^e n -- odd part
a#b|n<-f a,p<-e a,m<-f b,q<-e b=n>1&&(m>1&&p<q||n<m&&p==q||m<2)||n<2&&m<2&&p>q||a==b
```
[Try it online!](https://tio.run/nexus/haskell#FYtNCoMwEIXXeooBSzBgRIXSTcYTdNelWExQUSRjbG278e52snk/H@85MxMg@M/@2F93ggu8p/XHdk1u5wCE02D6ZlHlsWjVFHneZtS5te/S6rnIumjjkUfU9fM3oJQvUsYmsQdpNYLJvFYDmwvNZltoFqkuhUhdUK@3g7eOEyJHpysZQCWEC@JrhgbRQhxFAOf5Bw "Haskell – TIO Nexus")
[Answer]
# Python, ~~159~~ ~~158~~ ~~153~~ ~~144~~ ~~142~~ 141 bytes
*Saved ~~a~~ 2 bytes thanks to Kritixi Lithos!*
This is mainly just to practice golfing my Python!
Used the formula given by the OP rather than the ways of all the cleverer answers
```
f=lambda a,p=0:(a&1)*(a,p)or f(a>>1,p+1)
t=lambda(n,p),(m,q):(n==1)*(m==1)&(p>=q)or (m>1)&(p<=q)|(n<=m)&(p==q)or m==1
lambda a,b:t(f(a),f(b))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
ΣxÓs1ǝzDg≠i(]Q
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3OKKw5OLDY/PrXJJf9S5IFMjNvD//2hjHQVDw1gA "05AB1E – Try It Online") or [validate all test cases](https://tio.run/##LYs9CsJQEIT7PcWCjYWFO2/3/fTB3iMoiKSySCNCDmBtLQQ8gIdIYechvMhzjSnmmxmGOXW7fXuowGYxPpv6fpzHWyev@6U5fq5Du@z7bV3VwCJUOJJmTyAtk4l5tUwhMpREGdmpHEABM31lIZnkDzaSH7BmOH2G@dts9kQJbCBIiiyQ@E/QEr8).
] |
[Question]
[
You have locked your bike with a combination lock of 3 digits. Now you want to go for a ride and need to unlock it with the help of following program.
## Input
### 1st parameter
The digit combination of your lock in *locked* state. It must be different from the 2nd parameter (=the combination of *unlocked* state). (Or else your bike could be stolen!)
Range 000..999. Leading zeros must not be omitted.
### 2nd parameter
The digit combination of your lock in *unlocked* state. This value is your goal.
Range 000..999. Leading zeros must not be omitted.
## Output
A list of each state of the combination lock after each "rotation" including the initial state (which is always the 1st parameter) and the last step (which is always the 2nd paramater).
## Algorithm
You start "rotating" the first digit one by one until you reach the correct digit in *unlocked* state. But, because you are in knowledge of the whole unlock-code, **you rotate the digit in the direction in which you need the smallest amount of rotations to reach the digit in *unlocked* state**. In case of a tie you can choose whatever direction you prefer.
When you have reached the correct first digit, you start the same procedure with the 2nd and then with the 3rd.
The order of digits is to understand as a circle:
`... 9 0 1 2 3 4 5 6 7 8 9 0 1 2 ...`
This means, that the smallest amount of rotations from 1 to 9 is not
`1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9` = 8
but
`1 -> 0 -> 9` = 2.
## Notes
* You can rely on [Default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* You can change the order of the parameters.
## Examples
### Example 1, correct
```
Input: 999 001
Output:
999
099
009
000
001
```
### Example 2, correct
```
Input: 000 292
Output:
000
100
200
290
291
292
```
### Example 3, wrong output
```
Input: 999 121
Wrong output:
999
899 // Wrong because wrong rotation direction.
799
699
...
Correct output:
999
099
199
109
119
129
120
121
```
### Example 4, wrong input
```
Input: 1 212 // Wrong because no leading zeros.
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest answer wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~113~~ ~~107~~ ~~105~~ ~~99~~ 95 bytes
```
a,b=input()
i=0
print a
for x in a:
while x-b[i]:a[i]=x=(x+(x-b[i])%10/5*2-1)%10;print a
i+=1
```
[Try it online!](https://tio.run/##NY3NCoMwEITv@xSLUPBnpUnEQy15EvEQbYoLJRGxNH36NCplYdhvBmaW7zZ7p@LkH1ZnWRYNjZrd8t7yAlgLWFZ2Gxp4@hUDskPTAX5mflkM9djz0JkkOug8VPnpFBcprm2parl/938DcqVlPAjSEoANdsJ9GEtsYn@jdAP1ggTJARJLahMrakgdfOaSVMp/ "Python 2 – Try It Online")
Takes input as lists of integers
---
Saved:
* -6 bytes, thanks to Joel
* -4 bytes, thanks to Jitse
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
_æ%5ḣT$ṂṠ⁸_%⁵ðƬ
```
A dyadic Link accepting the start-code on the left and the target-code on the right as lists of integers (in \$[0,9]\$, lengths equal but otherwise arbitrary) which yields a list of lists of the codes from start-code to target-code.
**[Try it online!](https://tio.run/##ATUAyv9qZWxsef//X8OmJTXhuKNUJOG5guG5oOKBuF8l4oG1w7DGrP///1s5LDEsMV3/WzIsMywyXQ "Jelly – Try It Online")**
### How?
```
_æ%5ḣT$ṂṠ⁸_%⁵ðƬ - Link: list of integers, s; list of integers, t
Ƭ - collect up values until a fixed point is reached applying:
ð - the dyadic chain: (i.e. f(x, t) where x starts off as s)
_ - subtract (t from x) (vectorises) - i.e. [ta-xa, tb-xb, tc-xc]
5 - literal five
æ% - symmetric modulo (vectorises) - i.e. [[-4..5][ta-xa], [-4..5][tb-xb], [-4..5][tc-xc]]
$ - last two links as a monad:
T - truthy indices - e.g. [0,-4,1]->[2,3]
ḣ - head to index (vectorises) [[0,-4],[0,-4,1]]
Ṃ - minimum [0,-4]
Ṡ - sign (vectorises) [0,-1]
⁸ - chain's left argument (x)
_ - subtract (vectorises) - i.e. move the single spindle one in the chosen direction
⁵ - literal ten
% - modulo (since 9+1=10 not 0)
```
[Answer]
# JavaScript (ES6), ~~73 72~~ 70 bytes
*Saved 2 bytes thanks to @tsh*
Takes input as 2 arrays of digits in curried syntax `(a)(b)`. Returns a string.
```
a=>g=b=>b.some(x=>d=x-(a[++i]%=10),i=-1)?a+`
`+g(b,a[i]+=d/5<5/d||9):b
```
[Try it online!](https://tio.run/##fYzLDoIwEEX3fgUbQycdHsWwwDj4IbUJLQVSg9SIMSz49yqJOxNzlvfcc9UvPbcPd38mk7dd6CloqgcyVJt09reOLVRbWhKmJedO7UnkgI4SAWfNm13DB2ZQS6c42aw8lZld1wqOJrR@mv3YpaMfWM9khR8UMJljjkJBxKP4MsWw@/HENjNZ4AGLf963J7DYDhDe "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = initial combination
g = b => // b[] = target combination
b.some(x => // for each digit x in b[]:
d = // compute the difference d:
x - // between x
(a[++i] %= 10), // and the corresponding digit in a[]
// we apply a mod 10, because it may have exceed 9
// during the previous iteration
i = -1 // start with i = -1
) ? // end of some(); if it's truthy:
a + `\n` + // append a[] followed by a line feed
g( // followed by the result of a recursive call:
b, // pass b[] unchanged
a[i] += // add either 1 or 9 to a[i]:
d / 5 < 5 / d // add 1 if d / 5 < 5 / d
|| 9 // otherwise, add 9
) // end of recursive call
: // else:
b // stop recursion and return b[]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes
```
_æ%5+⁹⁹rḊ€%⁵J;Ɱ"$ẎṄḢ}⁺¦¥ƒ
```
[Try it online!](https://tio.run/##AU4Asf9qZWxsef//X8OmJTUr4oG54oG5cuG4iuKCrCXigbVKO@KxriIk4bqO4bmE4biifeKBusKmwqXGkv///1s3LCAyLCAxXf9bMywgNCwgOV0 "Jelly – Try It Online")
Full program.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~101~~ 97 bytes
```
a,c=input()
print a
for i in 0,1,2:
while a[i]!=c[i]:a[i]=(a[i]+(a[i]-c[i])%10/5*2-1)%10;print a
```
[Try it online!](https://tio.run/##VY9Bi8IwEIXPzq8YEWmrI9tEerDSo169eAs5dGPEoLQlRNRfXyetLiyBx2Tel5eZ7hUubSN7055slSRJX5OpXNPdQ5pB510TsIZz69GhazAnQbIEfFzczWKtnJ5WhrWMZZVGXQ66it1sLvKfYiFXIlbbT1rPvwDAGHH0d1vCJPgX68Q@rcE4CdcDDdwytgu4O@x33rc@Ur/e1leA2TlVggpaa1Ib4qMzmI2vorXhUYUmVJLWJHXWfyBSOfEaGgai4PsIwJ/PKw7@/3D4Jn75Nw "Python 2 – Try It Online")
3 bytes thx to [Joel](https://codegolf.stackexchange.com/users/88506/joel).
Takes input as lists of ints.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
_ż+¥⁵AÞḢṠxAƊ×€ʋ"JṬ€$$Ẏ;@W}+\%⁵
```
[Try it online!](https://tio.run/##y0rNyan8/z/@6B7tQ0sfNW51PDzv4Y5FD3cuqHA81nV4@qOmNae6lbwe7lwDZKmoPNzVZ@0QXqsdowpU@v//f0MdIx3j/yY6pjqWAA "Jelly – Try It Online")
A dyadic link taking as its left argument the unlock code and its right the current locked state, both as lists of integers.
This feels far too long!
[Answer]
# [PHP](https://php.net/), 114 bytes
```
for([,$a,$b]=$argv;$i<3;($x=$a[$i]-$b[$i])?(print$a._).$a[$i]=($y=$a[$i]+(5/$x>$x/5?-1:1))<0?9:$y%10:++$i);echo$b;
```
[Try it online!](https://tio.run/##LYpbCsIwFEQ3M0JC@rpKP/Jos5BSJBG1@bEhSElXHyv6M4fDmbjEYmw89rEmNlVwFfw8wKXnphHMRTPkQyeEuYb/glsWU3i94Zorb35pYNj/L8H6FnlEbntbkyLOTWelwn6iTgmBwPX9tqzwupQipSx0pg8 "PHP – Try It Online")
My solution probably sucks, but that is the best I can think of for now!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
θ≔EθIιθF³«≔⁻﹪⁺⁻I§ηι§θι⁵χ⁵ζF↔櫧≔θι﹪⁺§θι÷ζ↔ζχ⸿⪫θω
```
[Try it online!](https://tio.run/##VY9BC4IwFMfP@imGpzdYkEUH6SR1MRD8AF2WWg3Glm5aGH72NafCOjx4/733fj9WPmlbSsqNKVomNDT4GKZKsYeAnL6gIehElQaGMUHT7C5bBHuMvmGwrjHRKchl1XEJBZ969@LuUp2Jqv7AkyCHWHOz5IOteLs0g@UHTpDelOSdrmHATrW4/GuCfOUfl6BM6DPrWWUB1unBZt3kCeb/Rtc28uJFMjFB3m5nDEdjkiRB8S42m57/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ
```
Print the initial position.
```
≔EθIιθ
```
Change the initial position string into an array of numeric digits for calculation purposes.
```
F³«
```
Loop over each digit in turn.
```
≔⁻﹪⁺⁻I§ηι§θι⁵χ⁵ζ
```
Calculate the number of rotations needed to unlock that digit. This is a number from `-5` to `4` where `-5` means 5 downward rotations and `4` means 4 upward rotations.
```
F↔ζ«
```
Loop over each rotation.
```
§≔θι﹪⁺§θι÷ζ↔ζχ
```
Update the digit according to the sign of the rotation.
```
⸿⪫θω
```
Output the digits as a string on a new line.
[Answer]
# T-SQL 2008, 170 bytes
I added some linebreaks to make it readable
```
DECLARE @1 char(3)='123',@2 char(3)='956'
DECLARE @r int,@s int,@ int=0
g:SET @+=1
h:SELECT @r=substring(@1,@,1)+9,@s=@r-substring(@2+'1',@,1)
IF @s=9GOTO g
PRINT @1
SET @1=stuff(@1,@,1,(@r+@s/5%2*2)%10)
IF @<4GOTO h
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1097687/unlock-your-lock)**
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 101 bytes
```
a=>b=>{for(int i=0;i<3;i++)for(;a[i]!=b[i];a[i]+=(a[i]-b[i]+10)%10<5?9:1,a[i]%=10)Print(a);Print(a);}
```
[Try it online!](https://tio.run/##RYyxCoMwEIZ3n6IdhISckCgd2ngpXTp16NZBHDQo3BJBLR3EZ0@TVloO7u777ufslNmJ/PXpbElurmq42JkG9wVjevQNmhbN0g8jC3JHKDWVhSYheHS6qajeYxv6ZxXI4siiEEryVMnycD6eFESdYlD3MTxiDde/ZfU6SXrmuldVL0cItfKNJEhQK9fJY6S5u5HrWIB/VsXrRjkUkIesfwM "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 36 bytes
```
10|[+/\@,#:@4 2 1#~[:>&|/`]}10|-,:-~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DQ1qorX1Yxx0lK0cTBSMFAyV66Kt7NRq9BNia4FyujpWunX/Nbm4UpMz8hUswTANqN1AwRAipK4OkzIEQqCckYKxghG6HESbIcj8/wA "J – Try It Online")
Will add explanation tomorrow.
[Answer]
# MATLAB, ~~100~~ 89 bytes
A different approach (using implicit expansion to create a subtraction matrix) reduces 11 bytes:
```
function f(a,b);c = mod(a-b+5,10)-5;a,mod(a-cumsum(repelem(eye(3).*sign(c),abs(c),1)),10)
```
[Original 100 byte solution]
```
function f(a,b);c=mod(a-b+5,10)-5;a,for n=1:3;for r=1:abs(c(n));a(n)=mod(a(n)-sign(c(n)),10),end;end
```
Both called by passing the inputs as 3-element arrays, e.g. `f([9 1 1], [2 3 2])`
[Answer]
# [Java (JDK)](http://jdk.java.net/), 139 bytes
```
a->b->{for(int i;;a[i]+=(a[i]-b[i]+10)%10<5?9:1,a[i]%=10){System.out.println(""+a[i=0]+a[1]+a[2]);for(;i<3&&a[i]==b[i];i++);if(i>2)break;}}
```
[Try it online!](https://tio.run/##fVBNi4MwFLz3VzwKLbrGYCxlaVPdw8Le9tSjeIhWS6xfmFgokt/uJir7xbIk5jnzJpNJCnZnbnG5jbxqm05CoTHuJS9x3tep5E2Nn@gqLZkQ8M54DcMKoO2TkqcgJJO63Bt@gUr3rLPseH2NYmDdVdiTFOBt8TnxWkYxem1q0VdZN8MwhByCkblh4oZD3nSWpoFTyiIeO4FlipuYf@LZG@Kd9i@HI0GG3gSaGs4PIbMKN73ErT5clrW1Xju6H3ixLsQsfmxTY035abfdmr1BYDwpdxyb8tzioW8nXcZuVKmRTqmndGaAzIQUECy3ARj0OKBpgkIaeMhMAkrDb5qZ9maNP23wf2t@@BBkZP/77BE8I9h9adQcV18PrCXzlPg457Y/Y@eYtW35sAwdebGNWZpmrZwx0S@06P540KWnVuZT4wc "Java (JDK) – Try It Online")
Same algorithm as everyone, rolled differently because Java's `System.out.println` is pretty expensive!
[Answer]
# [C (clang)](http://clang.llvm.org/), 125 bytes
```
t,*d;f(*a,*b){for(t=d=a;t?printf("%d%d%d\n",*a,a[1],a[2]):d++,t=*d-b[d-a],d-a<3;*d=(*d+=!~*d*10)%10)t?*d+=(t+10)/5&1?1:-1:0;}
```
[Try it online!](https://tio.run/##HY3hCoIwFIX/@xQmGNuctBVJuIYPYvsxuxlCrZAFitirr7vu4R7O/bhwruX1Yd09BM8ZqJ4wy1lHl/41Eq9BW@Wb9zg435Msh6iLyzg@2VYatL2hNRQF95pB2bVQWsPRzgfFQBMGhd58GTApaI7rm0iILzDvjlvZyLqUtVBrwIb0aQdHaLokSbym1uhF8IqfVvUHcwQVggpBTyY@U5WkOOPNf0aXCpWs4Qc "C (clang) – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 162 bytes
```
{s:Array<Int>,e:Array<Int>->var i=0
o@while(i<3){println(""+s[0]+s[1]+s[2])
while(s[i]==e[i]){if(i>1)break@o
i++}
s[i]=(s[i]+if((e[i]-s[i]+10)%10>5)9 else 1)%10}}
```
[Try it online!](https://tio.run/##pVhtbxs3Ev7uXzEWeogEy2utHCeWERtJ0wYwkNaHNofgEPgDpaWkPa@WKsmN7Lr@7blnhuRqZbsFridY613yITmvz8zqxviqrL8dHdFlvW78GdXGL8t6QXNjyS81FXqumsqT187TTDnt9gDmyY2hsvZ6oa0jt9azcl7qgjalX2Kh1ZpxRbkovaOp9hutaxqNRqTqgiaTCTm9VlZ5LJneMVRhEzXT2R4/vLdapoIUpaOZKTQtTDWn2VJVla4X@oyBS@/X7uzoiOd5OnNezW70LVCAZDOzOvrtKJ@MTl@fMPxfdWVmN3RnGksfcSeH/ds0tFRfNfEcDpXZaXmjgzIKh6@mZa18aWrGyxZmTsdRvYx@NhteRRtVw1IGgorkitG2hOSsdK2xNyabIEPpk600LXW1xo4Mn5uqMhv2wNqahVWrYBDxjtzl8ANbbqW9tjLyid3EknQFZQFFkXBYHZVjPEzkdUaXnlYNNpvy6vlcWw3h59asRKRxLdj2JOqf8/CjE4IunW0HGfWvLOnK6Y4dZ6apCj7IeQPf7Q8Y/wt7iEMiyxAPGX3UqmC9f9fWuCAaghGrJOBWpUdABGNAtr9jAgYmgZMRPnFwfVVVowk3gl4YVWX/n4BXjU/uekdVCSBE0Wq2DMfy02NjsliSBnM2tmB71niZ7EH4WdXI4byurEtfqqo1OvU3yxILoIGqNurOCWonUMTiHIU8UylMOa/Xzy/sul7x2qDUu2phLCJ21SYNDrc@iVkverJ6XlrsHpxhah2zm@@a2peV5IkV/YIJrNWzhH/eR983fggrz1QTgoqU1RF6U5tNpYtFa9LNEgEWdzhkUhjyCslDI6bybaQgJ8IDC8AuwICYg9F8TEhYQNyKKQdaqZWBEnxWco2wIZJ6q1G7@WM1LkViplDeQJEvgzYzVYPUjHEsPZBfEdNCnUkuBq2tRoZKWH5e6jAmnCUHRzmTMcUFLf2KBaKvRBtEBJPLTBeNDRwnSgTPpyCpt@x0bIssJZmxBcIT8kdmR@QIpWEUJ/ByF2hvVtpZFTg6yzKa0IhyGoMzX9IJvaLXdNqOYT5sj81WWtVuiGOV/xPTt75k6we@ylmGCcvC@SgkSYcX2BmXY7685MsJX17x5TVfTvkyoXM65QXTprNwlKbGIfJ/Nqh@bdSzv6yu7hDT9EOsjpdHV2Sb6hEqFCHRo7UbP7RZ6cL@P96q1Totjg@UD5M/twXgTCrnaJRHhonPMjaR6spzO9uMn92GoePJuN2Gn3Mek3H@5kK0gOzsdjykjTWgIbNluI5k@Tinz535MHqKb/RxmEy5HLZKztxGfOwBYjSbR6rm/IW6ec4H8ncknhs/0vxlkrWsH4mKoMvHT8WpDVVdis@oDcvYgRxKByJxuTRWWiKE6waeRcWOzvzQ1CFtJX9A8SvUVUf6dl0pEHegcGkj1GpaKMLJReAiHJJqPv2zDREhbuQp91vKWiZphJErf9ehzSIwHsucclgSnY/hbNS1qNMpNJBy3tQh/53rJ/QZveO931zW/mK4R/iEpd3xAd3vYQrn/KBnlciE80QmKFDo27ZpDAQk0ECHLAu4FV7ZaNGGE7VAURiyJTcBysU3pAyEJFRlG7c9pxGeEQfavsVN2Kgf5t7QcZQrSFY62Pku0GFjpaeR8t8xQZbAn2WjLjSSt0MTYIohlfME5W4N1CbdBFdPET3qwnqQMwmqb7nyATiPkYDOQVztGPnCC28nsAKV@MaiV1lL0DhDU1D6DWvLfsY@CSr6QxmzzugKQttN6SDEyqAKYCUokAMrgmt9G7UJ2q4tevWq7vd6B8nlX0bX2/v8@kBw/GkHx9cDGYwGb8fF8td0fh6DJA6wH8IO5Ty554LyQbuxaPZW9EhABh2Eox9Ybjmq9abkXvAJF2MXwoMjGnaalwvUr451QvXuFE6OOrcs5/Cob3E13jHoMzxXFNKVIGSRlehTFCciOvwIDJttOLZdTHcLYxdN1aDm6RYHu6@Q2B5ffoeBcJXuWv6J1Z4Ycmt5tlt/x6aHf4rlTz4a/CMfwcgng874pL3nNrwzkTN6b8fSchvJQOjrJ9YjRW7n/Su9dQX6YI37yi5c4odfPQJs8QxFRJZrdxS6g82cqSQLhLV2DqBfdUhKUCY8iJcLQe3IhOIaCbXNaDTxtKbzAM5fjdF4gqC/3buzDrPpzsPhhTDM@WjPvBVj9Ms3x4P7bqZIinBuOMmFgHJfyuvzc43r4L6c98uLfBADe688OHjYk3lBHWC6z8BDeQreujgZTML7kbjj4eFbCHV7x72c0LUQYYey27eyoBxMaFljjyVb5vsFi6VIOHGF67yJs3Gtmkk1SSTF7Wr7sic70nupgmLamRY62iYNZzrz0RwWAGcbtJCGOYjqZjWVziZh4/FDCrXgDqQnbC/davhhICK3UmXnMsYulGKNJGFbfERe9gf7@xk4vfT9HvVCmAd6AS6TMriPRo3@@CMshcsyjiPojvHjNvrb@XxnPuUNBMM7/CVCcKGqd3bRcNX@Mdmh30mi3veqCFvtQ5yky3tTo28PvJ8cgDjqlOyETL8ZPLV2h3zkjZTLjXf88wEMzx0J5w1zVdZaK1DJkL0zgNGCUVZqTfdRCnSyrewS@n0ul3HyS@mvD1@MXoAQHlrDyo4Z/Mx8d8@Fbx@MwO/A9CD23lIQTv0rIHhp9DftWyivuuZNZZ3Na/VvTei8isRc9KTMfeDQ/u4@KPMfU9afTKAo5PXgodfq0GObfnfPmjxBncVwW3etHOntquM37rBXQkY7MoXSzfzW/nSW0QcTX@55UDqIIqgWoE91esBKD3xfW2vsGUoiDKmmlU7VtlW5jUukM3s@/nLn9qMazJv9nYDhX4VK56/m/fivdYNELQYmQ@K/wbAdGQ0Jf/lgMGzBcfEuYtRZM@ZdWvgYax@veXpOC8d70Dgc@PxBeUeSzoG8bIBP25P8z6Hx18HRS5G9Gx27Zw22jQ2snyoveDvUXa6i3/4L "Kotlin – Try It Online")
] |
[Question]
[
The bank has been broken into, and all the local mafia thugs have an unusual alibi: they were at home playing Connect 4! In order to assist with the investigation, you are asked to write a program to validate all the Connect 4 boards that have been seized in order to check that the positions are indeed positions from a valid Connect 4 game, and have not been hastily put together as soon as the police knocked on the door.
The rules for connect 4: players `R` and `Y` take it in turns to drop tiles of their colour into columns of a 7x6 grid. When a player drops a tile into the column, it falls down to occupy the lowest unfilled position in that column. If a player manages to get a horizontal, vertical or diagonal run of four tiles of their colour on the board, then they win and the game ends immediately.
For example (with `R` starting), the following is an impossible Connect 4 position.
```
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R| | | | |
| | |Y| | | | |
|R| |Y| | | | |
```
Your program or function must take in a Connect 4 board and return either
* A falsy value, indicating that the position is impossible or
* A string of numbers from 1 to 7, indicating one possible sequence of moves leading to that position (the columns are numbered `1` to `7` from left to right, and so the sequence `112`, for example, indicates a red move in column `1`, followed by a yellow move in column `1`, followed by a red move in column `2`). You may choose a column-numbering other than 1234567 if you like, as long as you specify in your solution. If you want to return the list in some other format; for example as an array `[2, 4, 3, 1, 1, 3]` then that is fine too, as long as it is easy to see what the moves are.
You can choose to read the board in in any sensible format including using letters other than `R` and `Y` for the players, but you must specify which player goes first. You can assume that the board will always be 6x7, with two players.
You may assume that the positions you receive are at least physically possible to create on a standard Connect 4 board; i.e., that there will be no 'floating' pieces. You can assume that the board will be non-empty.
This is code golf, so shortest answer wins. Standard loopholes apply.
**Examples**
```
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | | --> 1234567 (one possible answer)
| | | | | | | |
|R|Y|R|Y|R|Y|R|
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R| | | | | --> false
| | |Y| | | | |
|R| |Y| | | | |
| | | | | | | |
| | |Y| | | | |
| | |R| | | | |
| | |Y| | | | | --> 323333 (only possible answer)
| | |R| | | | |
| |Y|R| | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | | --> false (this is the position arising after
| |Y|Y|Y|Y| | | the moves 11223344, but using those moves
| |R|R|R|R| | | the game would have ended once R made a 4)
| | | | | | | |
| | | | | | | |
|Y| | | | | | |
|R|Y| | | | | | --> 2134231211 (among other possibilities)
|R|R|Y| | | | |
|Y|R|R|Y| | | |
| | | | | | | |
| | | | | | | |
|Y| | | | | | |
|R|Y| | | | | | --> false (for example, 21342312117 does not
|R|R|Y| | | | | work, because Y has already made a diagonal 4)
|Y|R|R|Y| | |R|
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | | --> 112244553 or similar
|Y|Y| |Y|Y| | |
|R|R|R|R|R| | |
```
[Answer]
# JavaScript (ES6), ~~202 194 187~~ 183 bytes
Takes input as a matrix with \$2\$ for red, \$4\$ for yellow and \$0\$ for empty. Returns a string of 0-indexed moves (or an empty string if there's no solution). Reds start the game.
```
m=>(p=[...'5555555'],g=(c,s=o='')=>/2|4/.test(m)?['',0,2,4].some(n=>m.join``.match(`(1|3)(.{1${n}}\\1){3}`))?o:p.map((y,x)=>m[m[y][x]--^c||p[g(c^6,s+x,p[x]--),x]++,y][x]++)&&o:o=s)(2)
```
[Try it online!](https://tio.run/##zZOxbsIwEIZ3noKhImflMGDcDkiGvUM7dDRGQWlIg3Ac4agKIjx7ioBWJtClBVqf7OHTyfp0vz2fvk9tuEyyvJ2a16iaiUqLIWRCUkq9@/3yFMYCQrTCCM8jYthhJe/QPLI5aDKSnoddZMgVtUZHkIqhpnOTpEFA9TQP3yCAXtknQNe9u3W62YzHPbLubwJCRmaQbXsygBUW24u11HKlZKHa7UlYlpmMIZw8oPULzHaUYKF8H3c9vk9aLTMwwhJgpApNas0iogsTw@PL8xO1@TJJ42S2ghnIRrMpu@iUwkuj7QTwa6uGIoQ0rizFThGvS7nol1L8JwZnu7iDbjKp7qnBvhzEDnV5KX7@tZwgVh8eRwf@Ryn2J/HtgzuKj10xvguhm0jxzx/oPvTDWZ8Uu1V8NSnuSLFvpaoP "JavaScript (Node.js) – Try It Online")
### How?
The recursive function \$g\$ attempts to replace all \$2\$'s and \$4\$'s in the input matrix with \$1\$'s and \$3\$'s respectively.
While doing so, it makes sure that we don't have any run of four consecutive odd values until all even values have disappeared (i.e. if a side wins, it must be the last move).
The row \$y\$ of the next available slot for each column \$x\$ is stored in \$p[x]\$.
### Commented
```
m => ( // m[] = input matrix
p = [...'5555555'], // p[] = next row for each column
g = (c, // g = recursive function taking c = color,
s = o = '') => // s = current solution, o = final output
/2|4/.test(m) ? // if the matrix still contains at least a 2 or a 4:
['', 0, 2, 4] // see if we have four consecutive 1's or 3's
.some(n => // by testing the four possible directions
m.join`` // on the joined matrix, using
.match( // a regular expression where the number of characters
`(1|3)(.{1${n}}\\1){3}` // between each occurrence is either 1, 10, 12 or 14
) // (horizontal, diagonal, vertical, anti-diagonal)
) ? // if we have a match:
o // abort and just return the current value of o
: // else:
p.map((y, x) => // for each cell at (x, y = p[x]):
m[ //
m[y][x]-- // decrement the value of the cell
^ c || // compare the original value with c
p[ // if they're equal:
g( // do a recursive call with:
c ^ 6, // the other color
s + x, // the updated solution
p[x]-- // the updated row for this column
), // end of recursive call
x // then:
]++, // restore p[x]
y // and restore m[y][x]
][x]++ // to their initial values
) && o // end of map(); yield o
: // else:
o = s // we've found a solution: copy s to o
)(2) // initial call to g() with c = 2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 57 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒṪŒ!µ0ịŒṬ¬a³ZU,Ɗ;ŒD$€Ẏṡ€4Ḅo1%15;Ḋ€ṢṚ$Ƒƙ$Ȧȧœị³$2R¤ṁ$ƑµƇṪṪ€
```
Takes a matrix where `0` is unfilled, `1` played first, and `2` played second. Yields a list of 1-indexed columns, empty if a fake was identified.
**[Try it online!](https://tio.run/##y0rNyan8///opIc7Vx2dpHhoq8HD3d0g3ppDaxIPbY4K1TnWZX10kovKo6Y1D3f1Pdy5EMgwebijJd9Q1dDU@uGOLpDEzkUPd85SOTbx2EyVE8tOLD86GWjIoc0qRkGHljzc2QiUOLT1WDvQBiACKv///390tIEOEozl0iFSwBBdwAhZwBAsAFUTGwsA "Jelly – Try It Online")** (too inefficient for more than 7 pieces to run in under a minute)
Note:
1. Assumes that no "floating" pieces are present (fix this by prepending `ZṠṢ€Ƒȧ` for +6 bytes)
2. Assumes that the empty board is a fake
[Answer]
# [Python 2](https://docs.python.org/2/), ~~295~~ 285 bytes
```
def f(a):
if 1-any(a):return[]
p=sum(map(len,a))%2
for i in R(7):
if a[i][-1:]==`p`:
b=a[:];b[i]=b[i][:-1];L=f(b)
if L>1>(`1-p`*4in','.join([J((u[j]+' '*14)[n-j]for j in R(7))for n in R(12)for u in[b,b[::-1]]]+b+map(J,zip(*[r+' '*7for r in b])))):return L+[i]
R=range;J=''.join
```
[Try it online!](https://tio.run/##vVRda9swFH2ef8WlZUhKnFCHQiHB@QGle/GbUQWRY7lRSGQhyd1a@t@zK8fJlj6Mja2TwPY5V1fnfliyL2HTmtnhUKsGGirZPAHdQDaR5iUip0LnDBcJ2Nx3e7qXlu6USSVjn2cJNK0DDdpAQe/Q9RO6Sq4Fn2Rzkecru0IOqlzyuVhUaMjjg88nmVg85A2tGJrR52GZLekqm9jV6FYbkpLpttWG8ntKO74VYwJklN0ybiZbESW3J0kWkTmibNajDhGv0orPo4wQ42ocg75PX7WlI@76ze7iShf9KsFwDHnCwxjjS4rcSfOkFvc5OUZyuIaw0R6azqyDbg04hRvsZfDIKwjKB1hLrzzuGFrYv0CtvHaqhuOyeXINWV@sYgE3/Ue5ACXXG1i3u26PGXiQ4NqvMSR0Rx@nvy1AmjqyaHQKWrOLllpBZ6FtgNwQ368gGX5Q04KVda3NE3gr18qzpG/qPnyRgfrYHp/7qVN2h1ZKCqxzRtgPokTihmBLhmLwIXvsQV9LNvUYlaUMTnWGoaY8i/aptzsdKHkj7FxefyIfDWGCiSTBUuVACHmDi5n8NS7wWeKM7@INFVCr@XCt4qQVfjev8pKJI25YvhP4mUkGqRNzFGz@l@CQYfdLvfIdLv7IXp5xL/X8z/pWnucpy@Kyb8nrB/0jl7jXisdCxmPBfUh9k4aQhibt0uf0VeDxtA6vD5ApXD2afHmV4oU8nF68bgdzcvgO "Python 2 – Try It Online")
-10 thx to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king).
Input is a list of strings representing the columns; with '1' for Red and '0' for Yellow. The strings are not ' '-padded. So the (falsey) case:
```
| | | | | | | |
| | | | | | | |
|Y| | | | | | |
|R|Y| | | | | |
|R|R|Y| | | | |
|Y|R|R|Y| | |R|
```
is input as:
```
[
'0110',
'110',
'10',
'0',
'',
'',
'1'
]
```
Output is a list of column indexes, 0-indexed, that could make the board; or `None` if it's not valid.
Accepts the empty board as valid (returns the empty list `[]` instead of `None`).
This approach is recursive from the last move to the first move: based on the parity of the total number of moves taken, we remove either the last Red move or the last Yellow move (or fail if that is not possible); check the resulting board to see if the opponent has 4-in-a-row (in which case fail, because the game should have stopped already); otherwise, recurse until the board is empty (which is valid).
The 4-in-a-row code is the most bloaty part. All the diagonal strings for the matrix `b` are generated by:
```
[
''.join(
(u[j]+' '*14)[n-j] for j in range(7)
)
for u in[b,b[::-1]]for n in range(12)
]
```
which first lists out the 'down-sloping' diagonals, and then 'up-sloping' ones.
] |
[Question]
[
## Problem Description
Imagine you're a turtle on a grid. You're given two numbers ***f*** and ***b***, and you're facing east. You perform a march across the grid, counting each of the cells you encounter, according to the following rules:
* By default, you write the count to the cell you're in, then walk forward.
* If the count is divisible by ***f***, you write `F` to the cell you're in, then turn right, then walk forward.
* If the count is divisible by ***b***, you write `B` to the cell you're in, then turn left, then walk forward.
* If the count is divisible by both ***f*** and ***b***, you write `FB` to the cell you're in, then walk forward.
* If you reach a square you've already been to, you stop.
For example, following these rules using ***f*** = 3 and ***b*** = 5 will generate a pattern like this:
```
F 28 29 FB 1 2 F
26 4
F B B F
23 7
22 8
F B B F
19 11
F 17 16 FB 14 13 F
```
## The challenge
Write a program or function that accepts two numbers as input, corresponding to ***f*** and ***b***, and produces as output the pattern for these numbers given by the rules above.
Formatting requirements:
* Each cell is two characters wide
* Cell contents are right aligned within these two characters
* Cells on the same row are delimited by a space
* The first column of cells must contain a non-empty cell
* All rows must contain non-empty cells
* Trailing whitespace is not required, but allowed
* However, the total width of each row must not exceed 3 times the number of non-empty columns
Your code must work for provided test cases.
Standard loopholes are disallowed.
This is code golf; shortest answer in bytes wins.
## Test cases
*(f=3, b=5 case repeated here as a courtesy convenience).*
```
f=3, b=5 ->
F 28 29 FB 1 2 F
26 4
F B B F
23 7
22 8
F B B F
19 11
F 17 16 FB 14 13 F
f=4, b=10 ->
F 25 26 27 F
23 29
22 1 2 3 F
21 5
FB 6
19 7
18 B 9 F
17 11
F 15 14 13 F
f=3, b=11 ->
F 16 17 F
14 19
13 1 2 F
F B 4
10 5
F 8 7 F
f=5, b=9 ->
F 41 42 43 44 1 2 3 4 F
39 6
38 7
37 8
F B B F
34 11
33 12
32 13
31 14
F 29 28 B B 17 16 F
26 19
F 24 23 22 21 F
f=5, b=13 ->
F 31 32 33 34 F
29 36
28 1 2 3 4 F
27 6
F B 7
24 8
23 9
22 B 12 11 F
21 14
F 19 18 17 16 F
```
[Answer]
## Python 2, ~~379~~ ~~338~~ 326 bytes
Takes input as two numbers, separated by a comma. Eg. `4,5` or `(4,5)`
```
d=x=y=i=q=Q=e=E=0
p={}
f,b=input()
while(x,y)not in p:
i+=1;l,r=i%b<1,i%f<1;d=(d+r-l)%4;p[x,y]=[[`i`,'F'][r],' F'[r]+'B'][l].rjust(2);q=min(q,x);Q=max(Q,x);e=min(e,y);E=max(E,y)
if d%2:x+=(d==1)*2-1
else:y+=(d!=2)*2-1
h,w=E-e+1,Q-q+1
A=[h*[' ']for x in' '*w]
for x,y in p:A[x-q][y-e]=p[x,y]
print'\n'.join(map(' '.join,A))
```
### Version that works if path is longer than 99, ~~384~~ ~~343~~ 330 bytes
Shows 2 significant digits.
```
d=x=y=i=q=Q=e=E=0
p={}
f,b=input()
while(x,y)not in p:
i+=1;l,r=i%b<1,i%f<1;d=(d+r-l)%4;p[x,y]=[[`i%100`,'F'][r],' F'[r]+'B'][l].rjust(2);q=min(q,x);Q=max(Q,x);e=min(e,y);E=max(E,y)
if d%2:x+=(d==1)*2-1
else:y+=(d!=2)*2-1
h,w=E-e+1,Q-q+1
A=[h*[' ']for x in' '*w]
for x,y in p:A[x-q][y-e]=p[x,y]
print'\n'.join(map(' '.join,A))
```
### Examples:
`input=(4,16)`
```
F 21 22 23 F
19 25
18 26
17 27
FB 1 2 3 F
15 5
14 6
13 7
F 11 10 9 F
```
`input=(6,7)` (truncating version)
```
F 63 64 65 66 67 FB 1 2 3 4 5 F
F 57 58 59 60 B B 8 9 10 11 F
55 13
F 51 52 53 B B 15 16 17 F
49 19
48 20
F 45 46 B B 22 23 F
43 25
42 26
41 27
F 39 B B 29 F
37 31
36 32
35 33
34 34
F B B F
31 37
30 38
29 39
28 40
27 41
FB FB
25 43
24 44
23 45
22 46
21 47
F B B F
18 50
17 51
16 52
15 53
F 13 B B 55 F
11 57
10 58
09 59
F 07 06 B B 62 61 F
04 64
03 65
F 01 00 99 B B 69 68 67 F
97 71
F 95 94 93 92 B B 76 75 74 73 F
F 89 88 87 86 85 FB 83 82 81 80 79 F
```
@Edit: Thanks to Jonathan Allan, Copper, and shooqie for savings me a bunch of bytes.
[Answer]
# Excel VBA, ~~347~~ 421 bytes
New version, to deal with the whitespace-requirements. Not having this in my first version was an oversight n my part, but this takes its toll in the bytecount... It now cuts and pastes the used range to cell `A1`.
```
Sub t(f, b)
x=70:y=70:Do:s=s+ 1
If Cells(y,x).Value<>"" Then
ActiveSheet.UsedRange.Select:Selection.Cut:Range("A1").Select:ActiveSheet.Paste:Exit Sub
End If
If s Mod f=0 Then Cells(y,x).Value="F":q=q+1
If s Mod b=0 Then Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q Mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub
```
---
Here's the old version that did not move the end result to `A1`
```
Sub t(f,b)
x=70:y=70:Do:s=s+1:if Cells(y,x).Value<>"" then exit sub
If s Mod f=0 Then
Cells(y,x).Value="F":q=q+1
End If
If s Mod b=0 Then
Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
End If
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub
```
Starts at 70, 70 (or BR70 in Excel) and walks around it. Function is called with the `f` and `b` as parameters: `Call t(4, 16)`
@Neil just saved me a bunch of bytes, thanks!
[Answer]
# Excel VBA, ~~284~~ ~~278~~ ~~277~~ ~~261~~ ~~259~~ ~~255~~ ~~254~~ ~~253~~ 251 Bytes
`Sub`routine that takes input as values, `F`, `B` and outputs to cells on the `Sheets(1)` Object (which is restricted to the `Sheets(1)` object to save 2 Bytes)
```
Sub G(F,B)
Set A=Sheet1
R=99:C=R
Do
I=I+1
Y=Cells(R,C)
If Y<>""Then A.UsedRange.Cut:[A1].Select:A.Paste:End
If I Mod F=0Then Y="F":J=J+1
If I Mod B=0Then Y=Y+"B":J=J+3
Cells(R,C)=IIf(Y="",i,Y)
K=J Mod 4
If K Mod 2Then R=R-K+2 Else C=C+1-K
Loop
End Sub
```
### Usage:
```
Call G(3, 4)
```
[Answer]
# C, 305 Bytes
**Thanks to @ceilingcat for finding a much better (and shorter) version**
```
#define z strcpy(G[x]+y,
F(f,b){int G[99][99]={},d=3,x=49,y=x,i=1,q=0,s=99,t=0,u=s,v=0;for(;!G[x][y];i++)q=!(i%f)*2|i%b<1,q-3?q?d=q-1?z"F"),d+3&3:!z"B")-~d%4:sprintf(z""),"%d",i):z"FB"),d%2?x+=d-2:(y+=d-1),s=s>x?x:s,t=t<x?x:t,u=u>y?y:u,v=v<y?y:v;for(;v/u;u+=puts(""))for(x=s;t/x;)printf("%2s ",G[x++]+u);}
```
[Try it online!](https://tio.run/##ZZBBbsIwEEX3nCJxlcquJ4IksEjMEIkFHAJlUWJSeVFKsB05ofTq1FbbVRfWfP2ZP352m7617ePxJE@dOp@iKdLm2l5Guj@4ho8w29EOjuymzibaH8qyCQdvd5BYgMNlCSM6UJhBjwvQWJZgvLCoYcCF6D6uVMRh12FshOKc9RhTlXTsJf9UyXHtc2lR97XEPs3qiewIA8mL56KKJ7IlLP2SybLSl6sH6OhEfJskkoBilR/ehukkrx1HmeYVHUPNmOfQG1e7SnsYsw7KeCS7Geuxsh5sWAc1/OANcyssx4s1mvr9LJgOtTBzJ9jvxSTJdUTAP4Tzhlsm7o/3V3Wm7OY/qIAVE7O/vPDOCsp/TlaE1Dc "C (gcc) – Try It Online")
A slightly more indented version:
```
#define z strcpy(G[x][y],
char G[99][99][3];
d=3,x=49,y=49,i=1,q,s=99,t,u=99,v;
F(f,b)
{
for(;!*G[x][y];i++)
{
q=(!(i%f))<<1|!(i%b);
q==3&&z"FB");
if(q==2)z"F"),d=(d+3)%4;
if(q==1)z"B"),d=(d+1)%4;
!q&&sprintf(G[x][y],"%d",i);
if(d%2)x+=d-2;else y+=d-1;
s=s>x?x:s;t=t<x?x:t;u=u>y?y:u;v=v<y?y:v;
}
for(y=u;y<=v;puts(""),y++)for(x=s;x<=t;x++)printf("%2s ",G[x][y]);
}
```
Here is a 364 byte version that handles numbers bigger than 100
```
#define g G[x][y]
#define z strcpy(g,
char G[99][99][9];d=3,x=49,y=49,i=1,q,s=99,t,u=99,v;F(f,b){for(;!*g;i++){q=(!(i%f))<<1|!(i%b);q==3&&z"FB");if(q==2)z" F"),d=(d+3)%4;if(q==1)z" B"),d=(d+1)%4;!q&&sprintf(G[x][y],"%2d",i);if(d%2)x+=d-2;else y+=d-1;s=s>x?x:s;t=t<x?x:t;u=u>y?y:u;v=v<y?y:v;}for(y=u;y<=v;puts(""),y++)for(x=s;x<=t;x++)printf("%2s ",g+strlen(g)-2);}
```
[Answer]
# JavaScript (ES6), 230 ~~240~~
```
(f,b)=>(d=>{for(g=[s=x=y=d];!(r=g[y]=g[y]||[])[x];d&1?d&2?y?--y:g=[,...g]:++y:d&2?x?--x:g=g.map(r=>[,...r]):++x)o=++s%f?'':(++d,'F'),s%b||(--d,o+='B'),r[x]=o||s})(0)||g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `).join`
`
```
*Less golfed*
```
(f,b)=>{
for(g=[s=x=y=d=0]; !(r = g[y]= g[y]||[])[x]; )
{
o=++s%f?'':(++d,'F')
s%b||(--d,o+='B')
r[x]=o||s,
d&1
? d&2 ? y ? --y : g=[,...g] : ++y
: d&2 ? x ? --x : g=g.map(r=>[,...r]) : ++x
}
return g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `)
.join`\n`
}
```
**Test**
```
F=
(f,b)=>(d=>{for(g=[s=x=y=d];!(r=g[y]=g[y]||[])[x];d&1?d&2?y?--y:g=[,...g]:++y:d&2?x?--x:g=g.map(r=>[,...r]):++x)o=++s%f?'':(++d,'F'),s%b||(--d,o+='B'),r[x]=o||s})(0)||g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `).join`
`
function update()
{
var i = I.value.match(/\d+/g)||[],f=+i[0],b=+i[1]
O.textContent = (f>0 & b>0) ? F(f,b) : ''
}
update()
```
```
<input id=I value="3 5" oninput="update()">
<pre id=O></pre>
```
[Answer]
# Perl, 275 bytes
Indentation is provided for readability and is not part of the code.
```
($f,$e)=@ARGV;
for($i=$x=1,$y=0;!$m{"$x,$y"};$i++){
($g,$m{"$x,$y"})=$i%$e&&$i%$f?($g,$i):$i%$f?($g+1,B):$i%$e?($g-1,F):($g,FB);
($g%=4)%2?($y+=$g-2):($x+=1-$g);
($a>$x?$a:$b<$x?$b:$x)=$x;
($c>$y?$c:$d<$y?$d:$y)=$y
}
for$k($c..$d){
printf("%*s",1+length$i,$m{"$_,$k"})for$a..$b;
say
}
```
Explanation:
The code works by keeping track of a hash of all places the turtle has been, and the appropriate value, stored in `%m`. For example: in `3 5`, `$m{0,2}` contains `2`, and `$m{1,-3}` = `26`. It continues in this fashion until it reaches a place that has already been defined. Additionally, it keeps track of the current boundaries of the turtle's path, using `$a,$b,$c,$d` as maximums and minimums.
Once it reaches a place it has already been, it prints the path using the boundaries, everything padded with spaces.
There is no limit to the size of the path, nor the size of the numbers.
[Answer]
# [PHP](https://php.net/), 292 bytes
```
for($x=$y=$u=$l=0;!$q[$x][$y];$s="") {
++$i%$argv[1]?:$a-=1+$s="F";
$i%$argv[2]?:$a+=1+$s.="B";
$q[$x][$y]=$s?:$i;
$z=[1,-2,-1,2][$a=($a+4)%4];
$y+=$z%2;
$x+=~-$z%2;
$u>$y?$u=$y:$d>$y?:$d=$y;
$l>$x?$l=$x:$r>$x?:$r=$x;
}
for(;$l++<=$r;print"\n")for($j=$u-1;$j++<=$d;)echo str_pad($q[$l-1][$j],3," ",0);
```
[Try it online!](https://tio.run/##PY/RaoNAEEXf@xV2uYLL7pasSV/cTIQ@9CesFIlto0hi16RoSvvrdtZCXmbucJiZe/tDP2/znuv7yScYCRPhQuho5e7xWWAsC0ylw0BCyOhbKTQxKv/xVdgyz1AZsirAZ@FuJF2IWsgDiSdGt0uEgWHjcKXCapNqY3XKpKKEVzYy3vCzSRGuceowKvo1//Kyw5QHa1OGOmhuPDh0O4w5G8aYwQfNjQf3ExIxVmpL8K73zfEsXo5CLklbjmmsQ7vg2sm3/eEUDWf/2ld1Evx2xrKvttRrLSKhV9LdzfO8nh//AA "PHP – Try It Online")
Indents are for clarity, not counted.
Follows much the same algorithm as the Perl answer. Track where the turtle has been in a 2D array, `$a` tracks where the turtle is facing, and `$u, $d, $l, $r` track the boundaries for printing. `str_pad` allows us to ensure that each entry is exactly 3 spaces wide for the print formatting.
For some reason I can't fathom, PHP doesn't mind me not initializing half the variables to 0, but screws up the formatting if I don't initialize others, even though it usually treats uninitialized variables as 0 when they're first used. Hence the `$x=$y=$u=$l=0` bit.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~267~~ ~~262~~ ~~258~~ ~~249~~ ~~245~~ 243 bytes
```
f,b=input()
X=x=Y=y=i=p=0
g={}
S=sorted
while(p in g)<1:i+=1;g[p]='F'[i%f:]+'B'[i%b:]or`i`;p+=1j**(i/f-i/b);X,_,x=S([X,x,int(p.real)]);Y,_,y=S([Y,y,int(p.imag)])
j=Y
while j<=y:print' '.join(g.get(i+j*1j,'').rjust(2)for i in range(X,x+1));j+=1
```
[Try it online!](https://tio.run/##Lc6xboMwGATg3U/hpbINDimpukD@JUNfIAsIoQZUcH4rtS3HUbGqPjs1areTvpPuXAxXaw7rOssR0LhH4II0sEALERAcPBMF3z/kDHfrw/RBvq54m7ijaKgSx7LCHMpada4H9sY6fJqrPmenLY1Vb/0FL7VLFZ1lHPfzDvejqBv5Lhc4866Ri0QTuCv8NNxEL@o2UdyolfGf8HNQiYiG9m@d6iPEyvnEjLJCWzRcFWoKHHOdlVoyJgqvH/fAD2K2nuL21g9GTTwt5qUQtU6f1vVFvv4C "Python 2 – Try It Online")
] |
[Question]
[
# Introduction
Unlike English, German is considered to have quite a [phonemic writing system](https://en.wikipedia.org/wiki/Phonemic_orthography). That means that the correspondence between spelling and pronunciation is close. Given any word you aren't familiar with, you would still know how to pronounce it because of the spelling system. This means a computer should be able to do it too right?
# Challenge
Write a program or function that takes as input a string representing a German word, and prints or returns its pronunciation in the [International Phonetic Alphabet (IPA)](https://en.wikipedia.org/wiki/International_Phonetic_Alphabet).
I am of course **not going to make you learn German or the full IPA**. This one [Wikipedia section](https://en.wikipedia.org/wiki/German_orthography#Grapheme-to-phoneme_correspondences) provides almost all the German to IPA rules you need, and I've coded an ungolfed C# [reference implementation](https://gist.github.com/DPenner1/5bc495780c76cba524699320bcbdbafe#file-germanipaguesser-cs).
Also provided in that link is a [list](https://gist.github.com/DPenner1/5bc495780c76cba524699320bcbdbafe#file-germanwordlist-txt) of 400 common German words and their IPA pronunciation (needed for validation). Taking an example from that list, if the input is `solltest`, the correct output is `ˈzɔltəst`.
The reference implementation adds two helpful rules not mentioned in the Wikipedia section: It assumes word stress is on first syllable (very likely in German), and uses a better heuristic for determining when the letter "e" represents the schwa sound /ə/. It also implements special processing for prefixes, but that didn't improve results as much as I thought it would.
# Details
To be considered a valid entry, your program must meet the following requirements:
* Your IPA output must be an exact match for at least 300 of the 400 words in the [reference word list](https://gist.github.com/DPenner1/5bc495780c76cba524699320bcbdbafe#file-germanwordlist-txt) (the reference implementation gets 333 correct)
* Your program must make a guess for any plausibly German word. So we have a technical requirement, this will mean that for any input that matches the regex `[a-zA-ZäÄöÖüÜ][a-zäöüß]*` and has at least one vowel (aeiouyäöü), you must produce non-whitespace-only output and not error out.
* The program must be deterministic (always produce the same output given the same input)
* Otherwise, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden (especially the one about fetching off-site resources)
Miscellaneous things you are allowed to do:
* Have leading and trailing whitespace in your output if you must
* Use any pre-existing character encoding in the output (I can't imagine anything other than Unicode working well, but if you can, congrats)
* Assume the input is in some normalized form like Unicode normalization forms NFD, NFC, etc. For example, is ä written as a single character or a base character + a combining character?
* Use [standard input and output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) methods
# Scoring & IPA Characters
Scoring is in bytes. Be warned that the German characters and the IPA characters are 2 bytes in UTF-8. Also, the IPA character U+0327 COMBINING INVERTED BREVE BELOW ( ̯) is a Unicode combining character and is a 2 byte UTF-8 character on its own. That means something like ɐ̯ would count as 4 bytes in UTF-8. For the curious, this symbol means the vowel does not form the syllable nucleus (the previous one does instead).
Also, beware of these IPA characters that in some fonts look like other ASCII characters: ɡ, ɪ, ʏ, ː (marks a long vowel), ˈ (marks which syllable has the stress in a multisyllable word).
# How the reference word list was created
*This section is extra info not needed for the challenge.*
The word list was grabbed from [this Wiktionary word frequency list](https://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/German_subtitles_1000), removing repeats because of casing difference and two words that didn't have German entries in the English Wiktionary (oh & hey). The IPA was from looking at both the English and German Wiktionaries. Where multiple pronunciations were offered, I chose the more formal and standard one. If this wasn't clear, I chose the one that most fit the general rules.
I also had to standardize how the letter "r" is pronounced. It is heavily dependent on the region how this letter pronounced, and Wiktionary was not at all consistent in which one it chose. I felt it tended towards the following: "r" is pronounced /ɐ̯/ when followed by a long vowel and a vowel does not follow, otherwise, it is ʁ. So, I changed all of them to follow that rule, except for the ver- and er- prefixes that were quite consistently /(f)ɛɐ̯/. Similarly, I standardized "eu" as /ɔʏ̯/.
[Answer]
# PHP, 3311 2988 2916 2845 2759 2671 2667 2509 2484 bytes, passing 301/400
>
> `<?$f=fopen(__FILE__,r);fseek($f,__COMPILER_HALT_OFFSET__);eval(strtr(stream_get_contents($f),[F=>'=>',M=>'==','&'=>'&&',H=>'function ',A_=>'array',G=>'if',4=>'for','|'=>'||','~'=>'))','%'=>str,7=>'=$',8=>'[]',9=>'!$','@'=>'count(','#'=>';$',5=>'return ',3=>':(']));__halt_compiler();define(J,[ieh,ah,aa,Ah,eh,ee,ie,ih,oh,oo,Oh,uh,Uh,au,eu,Au,ei,ai,ey,ay,a,e,i,o,u,A,O,U,y])#b7e=8;Hv($a){5in_A_($a,J);}Hn($a){5!v($a);}Hpronounce($w){global$b,$e#w=%tr(%tolower(%tr($w,[ßF1,ÄF2,äF2,ÖF0,öF0,ÜF6,üF6]~,[1FS,2FA,0FO,6FU])#W=8#L7w;while($L)4each(A__merge([tzsch,dsch,tsch,zsch,sch,chs,ch,ck,dt,ng,nk,pf,ph,qu,ss,th,tz,b,c,d,f,g,h,j,k,l,m,n,p,r,s,S,t,v,w,x,z],J)as$c){$l=%len($c);G(sub%($L,0,$l)M$c){$W87c#L=sub%($L,$l);break;}}$s=8#l=@$W);4($o7t7i=0#i<$l#i++){$c7W[$i]#p7i?$W[$i-1]:0#n7iM$l-1?0:$W[$i+1];G(9n|!(n($c)&$cM$n&n($W[$i+2]~)$s[$o]87c;G($p&((9n&v($c)&n($p~|(n($n)&v($W[$i+2]~~$s[++$o]=8;}$s[@$s)-1]|A__pop($s);4each($s as$z){$b87t#t+=@$z)#e87t;}$o=[sieFziQ,duFduQ,'die'FdiQ,derFdeQT,zuFtsuQ,wirFviQT,mirFmiQT,denFdeQn,dassFdas,erFeQT,soFzoQ,warFvaQT,fürFfyQT,jaFjaQ,wieFviQ,dirFdiQT,nurFnuQT,demFdeQm,ihnFiQn,auchFaUBx,ihrFiQT,daFdaQ,schonFʃoQn,wennFvEn,malFmaQl,gutFguQt,nachFnaQx,willFvIl,mussFmUs,habFhaQp,vorFfoQT,ihmFmiQm,tunFtuQn][$w]?:'';G($o)goto x#P7B7S7V7Z=0;@$s)>1&$o=[verFfET,daFda,geFgC][join($s[0])]#o&$P=1&A__shGt($s);(($P|@$s)M2)&$o.=W)|(@$s)>2&$d=1&$h=(int)@$s)/2)#w=A__merge(...$s);4each($w as$l){G(0<$S--)continue#n7w[$B+1]#p7w[$B-1]#f=''#Z+=in_A_($B,$b)#f7lMd&9n?t3$lMb&(9n|$nMt)?p3$lMg&(9n|$nMt)?((9n&$pMi)?K:k)3$lMc?(($nMA|$nMe|$nMi)?ts:k)3$lMch?(($pMa|$pMo|$pMu)?x:K)3$lMchs|$lMx?ks3$lMck?k3$lMdsch?dZ3$lMdt|$lMth?t3$lMph|$lMv?f39f&$lMg?g3$lMh?(v($n)?h:'')3$lMng?N3$lMnk?Nk3$lMqu?kv3$lMr?((!v($n)&9nMt)?T:R)3$lMsch?S3$lMss|$lMS?s3$lMtsch|$lMtzsch|$lMzsch?tS3$lMtz|$lMz?ts3$lMw?v3$lMs?(9p&($nMp|$nMt~?S3v($n)?z:s):$f~~~~~~~~~~)#U=0;G(v($l~{G(%len($l)>1)($f=[auFaUB,euFcYB,eiFaIB][$l])|$U=1;else{G(n($n)&((9w[$B+2]&$n!=n)|v($w[$B+2]~)$U=1;G($lMe){$U=9n?:$U;G(9w[$B+2]){G($nMr)($f=A)&$U=9S=1;G($nMm|$nMl)$f=C;}}elseG($nMch)$U=0;G(in_A_($B,$e~$U=0;}$f=($U|9Z)&9f?($l[0]MO?D3$l[0]MU?y3$l[0]MA?E:$l[0]~).Q39f?($lMe?((9n|(9w[$B+2]&($nMn|$nMs~)?C:E)3$lMA?E3$lMi?I3$lMo?c3$lMu?U3($lMU|$lMy)?Y:$l~~~:$f)#V++;}$f7f?:$l;G($d&$ZM$h)$f.=W#o.7f#B++;}G(%pos($o,W)M=false&$V>1)$o=W.$o;4(#j++<%len($o);)G($o[$j]M$o[$j+1])$o=sub%($o,0,$j).sub%($o,$j+1);x:5%tr($o,[SFʃ,ZFʒ,KFç,gFɡ,NFŋ,QF'ː',WFˈ,TFɐ̯,BF'̯',RFʁ,AFɐ,EFɛ,OFœ,IFɪ,YFʏ,UFʊ,cFɔ,CFə,DFø]);}`
>
>
>
Defines `pronounce(string $word)`.
Usage:
```
assert(
pronounce('darüber') == "daˈʁyːbɐ"
);
```
One note: 3 prefixes and 33 words are hard-coded, and some of the code is mildly optimized towards the testing list.
Testing code is [here](https://gist.github.com/cmura81/48afb93c48bf15ad2f07e10b2510aba8), though it does depend on [this file](https://github.com/edge-of-the-wind/Mistral/blob/master/tools/west/west_includes/console_output.php).
To test:
```
php test.php all
```
Powered by the tears of ternary statements.
**EDIT 7**: Squeezed off ~170 bytes by writing a preprocessor into the program. As a consequence, the actual program (everything after `__halt_compiler();`) is kinda hard to read. If you want the unprocessed program, switch `eval` with `print` in the third statement.
] |
[Question]
[
This is inspired by [Monday Mini-Golf #6: Meeesesessess upp teeexexextext](https://codegolf.stackexchange.com/q/61885/8478)
## Background
[ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) have difficulty entering text on his usual webpage. Whenever he use digits or letters, the text will be meeesesessessesseesseessedessed up. Your task is to help him type so the normal behavior is achieved.
## The transform
The transform affects runs of alphanumeric (`[0-9A-Za-z]`) characters delimited by any nonalphanumeric characters. In the following example, the first line would be transformed into the second (the other lines show the breakdown of the transform)
```
An12num:
Annn1n12n12nn12nn12nun12nun12numn12num
A
nn
n1
n12
n12nn12n
n12nun12nu
n12numn12num
```
In particular, any alphanumeric character after the first in a run will be transformed into *the entire run so far except for the first character*. Furthermore, if the character is a letter (as opposed to a digit), the character will be turned into *twice* the run.
Thankfully, backspace will delete last character and also resets the beginning of the run.
## Task
This time your task is not to perform the transformation. Instead, given an input string, you must return an encoded text that, if transformed, will result in the input. The output must be as short as possible, where `\<char>` counted as a single character.
Text is encoded as follows:
```
\ -> \\
backspace character -> \b
linefeed -> \n
```
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
## Test cases
Each test case is two lines, the first being input, the second output.
```
Heeeeeelp me. It shouldn't be messed up.
Hee \blp\b me\b. It\b sh\bou\bld\bn't be\b me\bss\bed\b up\b.
alert("Hello, world!");
al\ber\bt("He\bll\bo, wo\brl\bd!");
1223234234523456
123456
```
[Answer]
# CJam, 207
```
{_,1>{:E1<_0{:I2$,+E=:C+:R1>C'9>)*+:P,E,<{EP#{L0}{PRI)1}?}{PE#L{R8cP,E,-*+}?0}?}g}&}:U;LqS+'a+{_'[,_el^A,s+&,V={+}{s\V!:V{L{:BU_aL?B,,1>Bf{_2$<U_{_W=8>S8c+*+\@>j+}{?;}?}+{,}$0=}j}|\}?}%s'\8cN++'\"\bn"f+er-2<
```
[Try it online](http://cjam.aditsu.net/#code=%7B_%2C1%3E%7B%3AE1%3C_0%7B%3AI2%24%2C%2BE%3D%3AC%2B%3AR1%3EC'9%3E)*%2B%3AP%2CE%2C%3C%7BEP%23%7BL0%7D%7BPRI)1%7D%3F%7D%7BPE%23L%7BR8cP%2CE%2C-*%2B%7D%3F0%7D%3F%7Dg%7D%26%7D%3AU%3BLqS%2B'a%2B%7B_'%5B%2C_el%5EA%2Cs%2B%26%2CV%3D%7B%2B%7D%7Bs%5CV!%3AV%7BL%7B%3ABU_aL%3FB%2C%2C1%3EBf%7B_2%24%3CU_%7B_W%3D8%3ES8c%2B*%2B%5C%40%3Ej%2B%7D%7B%3F%3B%7D%3F%7D%2B%7B%2C%7D%240%3D%7Dj%7D%7C%5C%7D%3F%7D%25s'%5C8cN%2B%2B'%5C%22%5Cbn%22f%2Ber-2%3C&input=Meeesesessessesseesseessedessed%20upp%20teeexexextext)
**Explanation:**
Almost forgot to write this :p
The problem is solved in several steps:
* the text is separated into runs of alphanumeric characters (let's call them words) and runs of non-alphanumeric characters (non-words)
* non-words are printed as they are, and words are fixed
* fixing a word is done recursively (with memoization): split the word into 2 chunks in every possible way (including empty 2nd chunk), try to unmess the first chunk (see below), fix the 2nd chunk and join the results with a space-backspace if needed; take the shortest sub-solution
* unmessing a chunk means finding a minimal string of alphanumeric characters possibly followed by some backspaces (but with no backspaces in the middle) that when messed up, result in the given chunk; it is done with a simple greedy algorithm, going from left to right, building the unmessed string and its messed version in parallel, and determining the next needed character at each step; some chunks can not be unmessed
] |
[Question]
[
The word `BANANA` appears exactly once in this [word search](https://en.wikipedia.org/wiki/Word_search):
```
B A N A A N B B
A B A N A B A N
A N A B N N A A
N N B A A A N N
N A A N N N B A
A N N N B A N A
N A A B A N A N
B A N A N B B A
```
The word search above contains only one occurrence of the word `BANANA` looking up, down, left, right, or diagonally, but it has lot of similar words, like `BANANB`, `BANNANA`, `BNANA`, etc.
Your job is to build a program that will generate infuriating word searches like this one.
Your program will take as input:
* One word, in all capital letters, containing from three to seven unique letters with at least four letters total.
* One number, to represent the dimension of the square grid for the word search. The number must be at least the number of letters in the word.
And then, output a word search using only the letters in the word, that contains *exactly one* occurrence of the input word, and as many *infuriators* as possible.
An infuriator is defined as a string that has a [Damerau-Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) of one from the target word and begins with the same letter as the word. For `BANANA`, this would include words like:
* `BANBNA`, where one of the letters was substituted.
* `BANNANA` or `BANAANA`, where an extra letter was added.
* `BANAN`, `BNANA`, where a letter was deleted, but not `ANANA`, since there's no longer a `B`.
* `BAANNA` or `BANAAN`, where two consecutive letters were switched.
When counting infuriators on a word search grid, they may overlap, but you cannot count a large string if it completely contains a smaller string you've already counted, or vice versa. (If you have `BANANB`, you can't count it again if you've already counted the `BANAN` or the backwards `BNANA` inside it.) You also cannot count any strings that completely contain or are completely contained by the target word itself (you cannot count the specific `BANAN` that is part of `BANANA`, nor `BANANAA` or `BANANAN`.)
---
Your program will be tested on a specific word list composed of the words that fit the input word requirement (to be given later once I've generated it), on a grid size equal to double the length of the word, and will be scored on the number of infuriators present in each grid. Please post your results for the inputs `BANANA 12`, `ELEMENT 14`, and `ABRACADABRA 22` for verification.
[Answer]
# JavaScript
Bonus: You can seed the Word search. Default seed is: "codechallenge"
```
ws = document.getElementById("word_search");
Math.seedrandom("CodeChallenge");
m = -1;
n = 0;
x = 0;
var addMethod = 1;
var addFail = 0;
var final = false;
function reset() {
ws.innerHTML = '';
}
function write(str1) {
ws.innerHTML += "<h1>" + str1 + "</h1>";
}
document.getElementById("word").oninput = function () {
document.getElementById("word").value = document.getElementById("word").value.toUpperCase();
};
document.getElementById("size").onblur = function () {
if (document.getElementById("word").value.length > document.getElementById("size").value) {
document.getElementById("size").value = document.getElementById("word").value.length;
}
if (document.getElementById("word").value == "") {
document.getElementById("size").value = "0";
}
};
document.getElementById("go").onclick = function () {
reset();
word = document.getElementById("word").value.toUpperCase();
size = document.getElementById("size").value;
if (size == 0) {
word = "BANANA";
return;
}
data = new Array();
for (var i = 0; i < size; i++) {
data[i] = new Array();
for (var j = 0; j < size; j++) {
data[i][j] = "NONE";
}
}
while (add(dld(word)))
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
if (data[i][j] == "NONE") {
data[i][j] = word.charAt(Math.floor(Math.random() * word.length))
}
if (data[i][j] == "") {
data[i][j] = word.charAt(Math.floor(Math.random() * word.length))
}
}
}
finalput(Math.floor(Math.random() * size), Math.floor(Math.random() * size), word);
for (var i = 0; i < size; i++) {
write(data[i].toString().replace(/,/g, ""));
}
};
function test(x1, y1, x2, y2) {
if (x2 > size || x2 < 0 || y2 > size || y2 < 0 || x1 > size || x1 < 0 || y1 > size || y1 < 0) {
return false;
}
try {
switch (true) {
case x1 == x2 && y1 < y2:
for (var c = y1; c < y2; c++) {
if (data[x1][c] != "NONE") {
return false;
}
}
break;
case x1 == x2 && y1 > y2:
for (var c = y2; c < y1; c++) {
if (data[x1][c] != "NONE") {
return false;
}
}
break;
case y1 == y2 && x1 < x2:
for (var c = x1; c < x2; c++) {
if (data[y1][c] != "NONE") {
return false;
}
}
break;
case y1 == y2 && x2 < x1:
for (var c = x2; c < x1; c++) {
if (data[y1][c] != "NONE") {
return false;
}
}
break;
case y1 != y2 && x1 != x2:
var x = x1;
var y = y1;
while (true) {
if (x == x2 || y == y2) {
return true;
}
if (data[x][y] != "NONE") {
return false;
}
if (x < x2) {
x++;
} else {
x--;
}
if (y < y2) {
y++;
} else {
y--;
}
}
break;
}
} catch (err) {
return false;
}
return true;
}
function put(arg1, arg2, str1) {
var w = Math.floor(Math.random() * 8) + 1;
for (var l = 0; l < 8; l++) {
switch (w) {
case 1:
//Right
if (test(arg1, arg2, arg1, arg2 + str1.length)) {
for (var h = arg2; h < arg2 + str1.length; h++) {
data[arg1][h] = str1.charAt(h - arg2);
}
} else {
w++;
}
break;
case 2:
if (test(arg1, arg2, arg1 + str1.length, arg2 + str1.length)) {
var g = arg1 - 1;
var h = arg2 - 1;
var i = -1;
while (i < str1.length) {
g++;
h++;
i++;
data[g][h] = str1.charAt(i);
}
} else {
w++;
}
break;
case 3:
//Down
if (test(arg1, arg2, arg1 + str1.length, arg2)) {
for (var h = arg1; h < arg1 + str1.length; h++) {
data[h][arg2] = str1.charAt(h - arg1);
}
} else {
w++;
}
break;
case 4:
if (test(arg1, arg2, arg1 + str1.length, arg2 + str1.length)) {
var g = arg1 + 1;
var h = arg2 - 1;
var i = -1;
while (i < str1.length) {
g--;
h++;
i++;
data[g][h] = str1.charAt(i);
}
} else {
w++;
}
break;
case 5:
//Left
if (test(arg1, arg2, arg1, arg2 - str1.length)) {
for (var h = arg2; h > arg2 - str1.length; h--) {
data[arg1][h] = str1.charAt(Math.abs(h - arg2));
}
} else {
w++;
}
break;
case 6:
if (test(arg1, arg2, arg1 + str1.length, arg2 + str1.length)) {
var g = arg1 + 1;
var h = arg2 + 1;
var i = -1;
while (i < str1.length) {
g--;
h--;
i++;
data[g][h] = str1.charAt(i);
}
} else {
w++;
}
break;
case 7:
//UP
if (test(arg1, arg2, arg1 - str1.length, arg2)) {
for (var h = arg1; h > arg1 - str1.length; h--) {
data[h][arg2] = str1.charAt(Math.abs(h - arg1));
}
} else {
w++;
}
break;
case 8:
if (test(arg1, arg2, arg1 + str1.length, arg2 + str1.length)) {
var g = arg1 - 1;
var h = arg2 + 1;
var i = -1;
while (i < str1.length) {
g++;
h--;
i++;
data[g][h] = str1.charAt(i);
}
} else {
w++;
}
break;
}
}
}
function finalput(arg1, arg2, str1) {
if (final == false) {
try {
var w = Math.floor(Math.random() * 8) + 1;
console.log(arg1 + "," + arg2 + "," + w);
for (var l = 0; l < 8; l++) {
switch (w) {
case 1:
//Right
for (var h = arg2; h < arg2 + (str1.length - 1); h++) {
data[arg1][h] = str1.charAt(h - arg2);
if(h<0){throw "err";}
}
break;
case 2:
var g = arg1 - 1;
var h = arg2 - 1;
var i = -1;
while (i < str1.length - 1) {
g++;
h++;
i++;
data[g][h] = str1.charAt(i);
if(h<0){throw "err";}
}
break;
case 3:
//Down
for (var h = arg1; h < arg1 + (str1.length - 1); h++) {
data[h][arg2] = str1.charAt(h - arg1);
if(arg2<0){throw "err";}
}
break;
case 4:
var g = arg1 + 1;
var h = arg2 - 1;
var i = -1;
while (i < str1.length - 1) {
g--;
h++;
i++;
data[g][h] = str1.charAt(i);
if(h<0){throw "err";}
}
break;
case 5:
//Left
for (var h = arg2; h > arg2 - (str1.length - 1); h--) {
data[arg1][h] = str1.charAt(Math.abs(h - arg2));
if(h<0){throw "err";}
}
break;
case 6:
var g = arg1 + 1;
var h = arg2 + 1;
var i = -1;
while (i < str1.length - 1) {
g--;
h--;
i++;
data[g][h] = str1.charAt(i);
if(h<0){throw "err";}
}
break;
case 7:
//UP
for (var h = arg1; h > arg1 - (str1.length - 1); h--) {
data[h][arg2] = str1.charAt(Math.abs(h - arg1));
if(arg2<0){throw "err";}
}
break;
case 8:
var g = arg1 - 1;
var h = arg2 + 1;
var i = -1;
while (i < str1.length - 1) {
g++;
h--;
i++;
data[g][h] = str1.charAt(i);
if(h<0){throw "err";}
}
break;
}
}
final = true;
} catch (err) {
console.count("Anwser Fail");
setTimeout(finalput(Math.floor(Math.random() * (size - (word.length * 2))) + word.length, Math.floor(Math.random() * (size - (word.length * 2))) + word.length, str1),50);
}
}
return arg1 + "," + arg2 + "," + w;
}
function add(str1) {
switch (addMethod) {
case 1:
if (typeof x == "undefined") {
var x = Math.floor(Math.random() * size + 1);
var y = Math.floor(Math.random() * size + 1);
}
try {
while (data[x][y] != "NONE" && addFail <= 10) {
x = Math.floor(Math.random() * size + 1);
y = Math.floor(Math.random() * size + 1);
addFail++;
}
} catch (err) {
return true;
addFail++;
}
if (addFail == 11) {
addMethod = 2;
return add(str1);
}
try {
put(x, y, str1);
} catch (err) {
return true;
}
addFail = 0;
return true;
break;
case 2:
m++;
if (m == size) {
m = 0;
n++;
}
if (n == size) {
addMethod = 3;
return add(str1);
}
try {
if (data[n][m] == "NONE") {
put(n, m, str1);
}
} catch (err) {
return true;
}
case 3:
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
if (data[i][j] == "NONE") {
data[i][j] = str1.charAt(Math.floor(Math.random() * str1.length));
}
}
}
return false;
}
}
function dld(str1) {
var result = "";
switch (Math.floor(Math.random() * 4)) {
case 0:
//replace one letter
var q = Math.floor(Math.random() * (word.length - 1)) + 1;
result = word.slice(0, q) + word.charAt(Math.floor(Math.random() * word.length)) + word.slice(q + 1, word.length);
break;
case 1:
//Add one letter
var q = Math.floor(Math.random() * (word.length - 1)) + 1;
result = word.slice(0, q) + word.charAt(Math.floor(Math.random() * word.length)) + word.slice(q, word.length);
break;
case 2:
//Delete letter
var q = Math.floor(Math.random() * (word.length - 1)) + 1;
result = word.slice(0, q) + word.slice(q + 1, word.length - 1);
break;
case 3:
var q = Math.floor(Math.random() * (word.length - 1)) + 1;
result = word.slice(0, q) + word.charAt(q + 1) + word.charAt(q) + word.slice(q + 2, word.length);
break;
}
if (result.search(str1) != -1) {
return dld(str1);
}
return result;
}
```
```
<script src="http://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.3.10/seedrandom.min.js"></script>
<div id="word_search" style="line-height: 10%;font-family:'Courier New', Courier, monospace"></div>
<input type="text" id="word" value="BANANA" placeholder="BANANA"></input>
<input type="number" id="size" value="12" placeholder="Size"></input>
<input type="button" id="go" value="Go!"></input>
```
BANANA - 12:
```
AANananabABA
BNBAAANNNNAB
NABNAAANANNA
BAAABNNNNANB
BAANAANAAAAA
NABANANBNNBN
ABBAANBBAAAN
BNANBNBAAAAA
AANAANAANNAA
BNBNBBBNAANA
ABBNABBBANNB
ABNBAAAABNNA
```
ELEMENT - 14:
```
MEEMMLNLETELEN
LLENNMENEEMEEE
MEMELMEELTELEN
NNMEEEEETNTLNM
TLLEMTETNMNEEE
EELEELLENENTTE
EELMEMELMMLTTE
EEMNLENeTEENLN
EEEETElELEEEEE
EEMNEeMENEMTET
ENNNmNENEEEEEE
ETEeNEELLENLEE
LLnELTNEMLLEEE
EtTELLEENMEMNE
```
Good luck:
ABRACADABRA - 22:
```
DRADCBBAAAABABABARBCCB
DBCABAAADABACDBAAAARBA
CDABBDRBRRBDARRDCRARRA
BAAAACRABRACBARAAABBRC
ACARDARARAAAABRABAADBB
BBAAAARBCDRAACDAADARAB
ABBAAAARABBBAAABACDAAA
AADARDARAAARABRCBABRBB
ARRADCCDACRAAAAAADBAAC
AAAABBARDBAARRCABRDDAA
RADABRAAARAABRRAARDARB
AARARCRBAACARBABRDDDAA
BABACDCCARCRAAADCABARA
RBABACAAAAAACDARRBCACR
RARABBADRARBCRAABRDRAR
BBRAAAAABRBAAABRAACRAR
BAADRAAAABRDAAABBBBAAA
RAADRACDAADABRACAAABRR
AARAAABBAAABRAABCCBAAR
RAAAAAARBRRBARAAAAAARR
RCAAAAARARBRCCBBCCACAA
DAAAABARDABADRAADAAACC
```
>
> If you run this in the snippet, and look at the console, the last number will show the coords of the beginning of the answer.
>
>
>
Extra: MISSISSIPPI - 32:
```
SPSSIIPSMIMIMPMISPPIIPSIIIIISSSS
ISISIISSMPPPISSIISPPPSPSISSSIPMP
PSPMIIMISMISSIPMPIIIIISIMIMSSSSI
PSIISPSIPSPSIPIPMMMIPIISSMMISMMM
SPIISIPMSISPMPPPMIMPIISISIIISIPS
ISSIISMISSPMIPPISSSMSIISIISSMIPS
SSPISIMSSSIPSSSPMSSPISPPSSSSPSSM
IPMIISMISSSSSSSSSPSMPISISIMIISSP
IISSSSMMPSPSISIIISISSMMSISIMPSPP
IIIIIIMIISISMPPPIIISSMSSIPSSSISI
IPIIPPSSSSIISIISSMIPIISSPPSSIPIS
PSISPIIISPPSIIMPIIPSSSSSISPIISSS
SIISSIMSIISSISSSSMIISSIPSIIIIIII
MPSSISSSISISSPMPSISSISSSSISIIMII
ISPSIIIPIIIISMSSMIIPMSSSPSSSSSSS
SSIIIISPIIPIPISIPSMPPMSSSISIIIPI
IPPIPMPIPSIIPPISSPISPSPIIIISIIMS
SPMSSPIIPPSSISISIPSSPSIIISIIIPIP
PSSIIIISMSSIIIMSSIIIPSMPMSIPIIIM
IISSSIIMIMPMISPPIPMMMIIIPSPPSPIS
SISISSIISISSISPSSSSPSIIISIPPISSI
IMSIPSISIIMPSSSISISIISIPSSSSISII
PMIPPPSSISIIISSSSSIIIPISSISIPSMI
ISIPSMMMSMISPISIPSSPSSPISSISIIIS
SISMIIISSIIMSIPMSSSSIPSSSPISPSPI
PPSPISSSISPSIIISSSSPIPSSMIPSSSPS
SSIMSSIISIIPSPSIPSSMSIIIMSSSIPPP
PMSISSPMISIIISIIPSPSPSMSIMISIMIP
IPSISSIIPSSPIMSSSSSSSSSSIIIPISSI
PSIIMIMIISPSSIMISMMPPIPPSSMISMII
IPPIPSIISSSSIPIIPIMMISSIPISIIIIP
IPPISSIMSIIPPSISIISSSMIIIPSIISSS
```
>
> Try to find MISSISSIPPI! I will comment the answer later. No cheating.
>
>
>
[Answer]
# C++
I wrote this one up today. It is not the most efficient way and does not always generate the most random looking word searches but it gets the job done and it does it relatively quick.
**Bonus:** Supports Palindromes too!!!
It works by taking input for the word and the size of the word search. It then generates infurators by dropping letters, inserting letters, or flipping letters. It then adds those to the grid as well as the correct word. It then checks all instances of the first letter in every direction for the word. If 1 instance is not found ( 2 for palindromes ) it brute forces the cycle over. It then outputs the word search to console as well as a file.
Here it is at 213 lines of code with whitespace and comments.
```
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <time.h>
// Keep Track of Coordinates
struct XY {
public:
int X;
int Y;
};
// Just in case someone breaks the rules
std::string ToUppercase( const std::string& pWord ) {
char *myArray = new char[ pWord.size() + 1 ];
myArray[ pWord.size() ] = 0;
memcpy( myArray, pWord.c_str(), pWord.size() );
for ( unsigned int i = 0; i < pWord.size(); i++ ) {
if ( (int) myArray[ i ] >= 97 && (int) myArray[ i ] <= 122 ) {
myArray[ i ] = (char) ( (int) myArray[ i ] - 32 );
}
}
return std::string( myArray );
}
// Random number between a max and min inclusively
int RandomBetween( int pMin, int pMax ) {
return rand() % ( pMax - pMin + 1 ) + pMin;
}
// Find all instances of a character
std::vector<XY> FindHotspots( const std::vector<char> &pWordSearch, char pFirstChar, unsigned int pLength ) {
std::vector<XY> myPoints;
for ( unsigned int i = 0; i < pLength; i++ ) {
for ( unsigned int j = 0; j < pLength; j++ ) {
if ( pWordSearch[ i * pLength + j ] == pFirstChar ) {
XY myXY;
myXY.X = i;
myXY.Y = j;
myPoints.push_back( myXY );
}
}
}
return myPoints;
}
// Searchs each index from specific point in certain direction for word
// True if word is found
bool Found( const std::vector<char> &pWordSearch, const std::string &pWord, int pRow, int pCol, int pX, int pY, int pLength ) {
for ( unsigned int i = 0; i < pWord.length(); i++ ) {
if ( pRow < 0 || pCol < 0 || pRow > pLength - 1 || pCol > pLength - 1 )
return false;
if ( pWord[ i ] != pWordSearch[ pRow * pLength + pCol ] )
return false;
pRow += pX;
pCol += pY;
}
return true;
}
// Goes through all the hotspots and searchs all 8 directions for the word
int FindSolution( const std::vector<char> &pWordSearch, const std::string &pWord, unsigned int pLength ) {
std::vector<XY> myHotspots = FindHotspots( pWordSearch, pWord[ 0 ], pLength );
int mySolutions = 0;
for ( unsigned int i = 0; i < myHotspots.size(); i++ ) {
if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, 0, pLength ) )
mySolutions++;
if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, 1, pLength ) )
mySolutions++;
if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 0, 1, pLength ) )
mySolutions++;
if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, 1, pLength ) )
mySolutions++;
if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, 0, pLength ) )
mySolutions++;
if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, -1, pLength ) )
mySolutions++;
if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 0, -1, pLength ) )
mySolutions++;
if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, -1, pLength ) )
mySolutions++;
}
return mySolutions;
}
// Generate words that are similar
//
// 1. Word with last character same as first
// 2. Word with 1 character removed
// 3. Word with 1 character added
std::vector<std::string> GenerateInfurators( const std::string &pWord ) {
std::vector<std::string> myInfurators;
for ( unsigned int i = 0; i < pWord.size() / 2; i++ ) {
char myReplace = '0';
do {
myReplace = pWord[ RandomBetween( 0, pWord.size() - 1 ) ];
} while ( myReplace == pWord[ pWord.size() - 1 ] );
myInfurators.push_back( pWord.substr( 0, pWord.size() - 2 ) + myReplace );
}
for ( unsigned int i = 1; i < pWord.size() - 2; i++ ) {
myInfurators.push_back( pWord.substr( 0, i ) + pWord.substr( i + 1 ) );
std::string myWord = pWord;
myInfurators.push_back( myWord.insert( i, 1, pWord[ i - 1 ] ) );
}
return myInfurators;
}
// Adds word in random position in word search
void AddWordRandomly( std::vector<char> &pWordSearch, const std::string &pWord, unsigned int pLength ) {
int myXDirec = 0;
int myYDirec = 0;
do {
myXDirec = RandomBetween( -1, 1 );
myYDirec = RandomBetween( -1, 1 );
} while ( myXDirec == 0 && myYDirec == 0 );
int myRow = 0;
if ( myXDirec == 0 ) {
myRow = RandomBetween( 0, pLength - 1 );
} else if ( myXDirec > 0 ) {
myRow = RandomBetween( 0, pLength - pWord.size() - 1 );
} else {
myRow = RandomBetween( pWord.size(), pLength - 1 );
}
int myCol = 0;
if ( myYDirec == 0 ) {
myCol = RandomBetween( 0, pLength - 1 );
} else if ( myYDirec > 0 ) {
myCol = RandomBetween( 0, pLength - pWord.size() - 1 );
} else {
myCol = RandomBetween( pWord.size(), pLength - 1 );
}
for ( unsigned int i = 0; i < pWord.size(); i++ ) {
pWordSearch[ myRow * pLength + myCol ] = pWord[ i ];
myRow += myXDirec;
myCol += myYDirec;
}
}
// Checks for palindromes
bool WordIsPalindrome( const std::string &pWord ) {
for ( unsigned int i = 0; i < pWord.size(); i++ ) {
if ( pWord[ i ] != pWord[ pWord.size() - 1 - i ] )
return false;
}
return true;
}
int main() {
// Handle all input
std::string myWord;
std::cin >> myWord;
myWord = ToUppercase( myWord );
std::string myStrLength;
std::cin >> myStrLength;
unsigned int mySideLength = std::stoi( myStrLength );
// Setup variables
// New time seed
// Generate infurators
// Add words
std::vector<char> myWordSearch;
srand( ( unsigned int ) time( 0 ) );
std::vector<std::string> myWords = GenerateInfurators( myWord );
myWords.push_back( myWord );
bool myWordIsPalindrome = WordIsPalindrome( myWord );
// Brute force words until 1 instance only
// 2 instances for palindromes
do {
for ( unsigned int i = 0; i < mySideLength * mySideLength; i++ ) {
myWordSearch.push_back( myWord[ RandomBetween( 0, myWord.size() -1 ) ] );
}
for ( unsigned int j = 0; j < 10; j++ ) {
for ( unsigned int i = 0; i < myWords.size() - 1; i++ ) {
AddWordRandomly( myWordSearch, myWords[ i ], mySideLength );
}
}
AddWordRandomly( myWordSearch, myWord, mySideLength );
} while ( ( FindSolution( myWordSearch, myWord, mySideLength ) != 1 && !myWordIsPalindrome ) ||
( FindSolution( myWordSearch, myWord, mySideLength ) != 2 && myWordIsPalindrome ) );
// Output to console && text file
std::ofstream myFile( "word_search.txt" );
for ( unsigned int i = 0; i < mySideLength; i++ ) {
for ( unsigned int j = 0; j < mySideLength; j++ ) {
myFile << myWordSearch[ i * mySideLength + j ] << "";
std::cout << myWordSearch[ i * mySideLength + j ] << " ";
}
myFile << "\n";
std::cout << "\n" << std::endl;
}
myFile.close();
system( "pause" );
return 0;
}
```
I am far from a C++ expert so I'm sure there's places where this code could be improved but I was happy with how it ended up.
Here's the outputs.
```
BANANA-12:
BBBBBABANABB
BBANAAANANBB
BABAANABBABA
BNAANAAANABN
BANNNNNANBBB
AANABNNANNAA
NAANANAAAABA
ANNNBAANNNBN
ABABNAANABNA
BNNANNAAANNB
BBABAAANBBAB
BBANANNBBABB
ELEMENT-14:
MLELEMEEETNEET
EMTTELTEETELEE
EMNNELEENLNTEL
TLTNEEMEEELMTM
TLEMLNLMEEEETE
TTEEEEEENLNTLE
NETNENEEMTTMEN
ELELTETEEMNMEE
MTEEMTNEEEENEM
ELENEEEMMENNME
ELLEELELTMLETL
ETLTNEMEEELELE
EELTLLLLLMNEEE
EEEELEMNTLEEEE
ABRACADABRA-22:
ACRABAACADABBADBRRAAAA
BBABAABAARBAAAARBAABAA
RARRARBAAABRRRRAAABBRA
DABARRARABBBBABABARABR
BRBACABBAAAABAARRABDAD
ABRRCBDADRARABAACABACR
DCAAARAABCABRCAAAARAAA
AAABACCDCCRACCDARBADBA
CAARAAAAAACAAABBAACARA
ADRABCDBCARBRRRDAABAAR
RARBADAARRAADADAABAAAB
BBRRABAABAAADACACRBRAA
ARBBBDBRADCACCACARBABD
CAARARAAAACACCDARARAAA
ARABADACRARCDADABADBBA
RARAADRRABADBADAABBAAA
RAAAABBBARRDCAAAAAARRA
BABBAAACRDBABCABBBRAAR
AARARAARABRAAARBRRRAAB
BAAAARBRARARACAARAAAAA
ADCBBABRBCBDBRARAARBAA
AARBADAAAARACADABRAABB
Bonus: RACECAR-14:
RRACEARCECARAR
RRRRRRRRRCARAR
RARRAACECARAAA
CCACECRREAECAR
RECEAEEAAECEAE
RCRRREACCCCEAR
RRRARCERREERRR
CCARAAAAECCARC
ECECARRCCECCRR
CARRRACECCARAC
ACRACCAAACCCAR
ARRECRARRAAERR
RRCRACECARRCRR
RRRRACECRARRRR
```
I may update this to generate slightly more "random" looking word searches.
[Answer]
### Excel VBA
```
Dim l() As String
w = InputBox("w")
n = InputBox("n")
ReDim l(Len(w))
Var = w
q = Len(w)
For i = 1 To Len(w)
l(i) = Left(Var, 1)
Var = Right(Var, Len(w) - i)
Next i
Cells(Int((q) * Rnd + 1), Int(((n - q) * Rnd + 1))).Select
r = Int((3) * Rnd + 1)
If r = 1 Then
For i = 0 To q - 1
ActiveCell.Offset(0, i) = l(i + 1)
Next
ElseIf r = 2 Then
For i = 0 To q - 1
ActiveCell.Offset(i, 0) = l(i + 1)
Next
ElseIf r = 3 Then
For i = 0 To q - 1
ActiveCell.Offset(i, i) = l(i + 1)
Next
End If
For i = 1 To n
For j = 1 To n
If Cells(i, j) = "" Then
Cells(i, j) = l(Int((q - 1) * Rnd + 1))
End If
Next j
Next i
```
It works by first randomly placing the word in the spread sheet, random in both position and direction, then filling the non-empty spaces in the surrounding grid by randomly choosing from all but the last letter of the word.
BANANA Output (2, 1):
```
N B N A N A N N A B B A
A A N A A A B A N A A N
N N A B A N B N B A N N
B A B N A N N A N A B N
N N A N A N N A A A A B
A A B A N N A B A N A A
A A A A A N A N A A N A
A N A B B A N A N B N N
A A N N A B A N A B N A
A N A N A N B A B N A A
A N A A B A B N N N B A
B A A A N N N A B N A A
```
ELEMENT Output (6, 5):
```
E E L M M M L E E N M M E E
E E M E L E E M E E E E E L
E N E E E E E L E N E E E E
L E M M M E E L E L N L M E
E L L L E E M L E M M E E E
L E M L N N L M E E L E M N
L L N E M M M E E N E E E L
E E N E N L E N M L N N N M
M E E M M N E E M E E E E L
N E M M M E E L N L N E L E
L M E L M M N N L E E T E M
E E E N L M E E M E E E E E
M E E E E L N M L E E E E E
N L L M E M E L E M E M N E
```
ABRACADABRA Output (2, 3):
```
R B A R A R D R D A A R R D R A A C A R B A
C B B R R A A A R A B A C R A A A D D A C A
B A B R A C A D A B R A R A A R D B B B C R
C R C A A R B D R A A A R A R D D B R B D A
C A D A C A A D B A R D A A D D B D R A R B
A A R R R B R B R B A A R C R B C A A A A A
A R A B R A R A C D R A A R C A D C B C C D
D R A A A D B C C R A A R B B A B A R B C R
A R B R R C D R R B D A B A C C B A A A R R
A A D A A A B D R A B A R A D B A A B B D R
C A A B R R B A B B R A A C A D A R A A A A
A R R C R R A R C A B A A A R A A R A R C R
D B C A B A A A A B C A B B D A R R B B R A
B A C B B D C B D B A A A A D A R R C C A R
A A R R R R D A R C A A B A B C C A A R A R
C A B A B R B C B B C B D A A R A R A B D D
R A A A C B R D R B B R A R C D A A C A D A
A D B A C R A C B A R A A A A C A R D A D B
A R B B A A R A B A R A A R A R B R D B D A
R B D B B A B R C D A C A A R C B A B B D R
B C B A B A B D D B B R B B B A A R R A A C
R D A C A A A R C R R A C R C A B R B A R A
```
] |
[Question]
[
**You are an enterprising dot** who wants to increase the land under its control. This is quite simple - travel outside your current land and loop back into your land and everything in that loop is now owned by you. But there is a catch. If some other dot somehow finds your loop and crosses it, you die.
If you haven't already tried it, go to [Splix.io](https://splix.io) and try a game. Use the arrow keys to control your movement.
GIF
[![enter image description here](https://i.stack.imgur.com/vqXNL.gif)](https://i.stack.imgur.com/vqXNL.gif)
Credit: <http://splix.io/>
## Specifics
All players start at random positions on a 200x200 board. (I reserve the right to change this :). You will have a certain amount of moves to amass the greatest number of points possible. Points are tallied by:
* The number of players you have killed times 300
* The amount of land you own at the end of the round
This brings up the point that others can steal your land. If they start a loop that intersects some of your land, they can claim it. If you die during the round, you lose all points for that round.
Each round has a randomly selected group of players (max 5 unique players) (subject to change). Every player participates in an equal number of rounds. Your bot's final score is determined by its average per-game score. Each game consists of 2000 turns (also subject to change). All bots make their moves at the same time.
### Death Cases
**Head Butt**
![head butt](https://i.stack.imgur.com/AcuOu.png)
Both players die when they head butt each other. This is still true even when both players are at the edge of their space.
![head butt](https://i.stack.imgur.com/pWstT.png)
However, when only one of the players is in his land, the other player dies.
[![enter image description here](https://i.stack.imgur.com/Tbwiu.png)](https://i.stack.imgur.com/Tbwiu.png)
**Line Cross**
![enter image description here](https://i.stack.imgur.com/bQn5q.png)
In this case, only the purple player dies.
You can't cross your own line.
[![enter image description here](https://i.stack.imgur.com/hHMr1.png)](https://i.stack.imgur.com/hHMr1.png)
**Exiting the board**
![player going off the board](https://i.stack.imgur.com/h9d4E.png)
If a player attempts to exit the board, he will die and lose all points.
### Capturing area
A player will capture area when he has a trail and he enters his own land again.
![enter image description here](https://i.stack.imgur.com/PaRJm.png)
Red fills in between the two red lines. The only case where a player does not fill in is when another player is inside the loop. To be clear, this only applies when the other player himself is in the loop, not just land owned by him. A player can capture land from another person. If a player cannot fill in the area surrounded by his trail, the trail is converted directly to normal land. If the player inside another players land loop dies, the area in that loop is filled. Every time a player dies, the board is reexamined for an area that can be filled in.
## Controller details
The controller is [here](https://github.com/JJ-Atkinson/splix-controller-ppcg). It is very similar to the original game, but small changes have been made to make this a better fit for KotH and for technical reasons. It is built with [@NathanMerrill](https://codegolf.stackexchange.com/users/20198/nathan-merrill)'s [KotHComm library](https://github.com/nathanmerrill/KotHComm), and with substantial help from @NathanMerrill as well. Please let me know of any bugs you find in the controller in [the chat room](http://chat.stackexchange.com/rooms/52901/splix-io-controller). To be consistent with KotHComm, I have used Eclipse collections throughout the controller, but bots can be written using only the Java Collections library.
Everything is packaged in an uberjar on the [github releases page](https://github.com/JJ-Atkinson/splix-controller-ppcg/releases). To use it, download it and attach it to your project so you can use it for auto-compleat (instructions for [IntelliJ](https://stackoverflow.com/questions/1051640/correct-way-to-add-external-jars-lib-jar-to-an-intellij-idea-project), [Eclipse](https://stackoverflow.com/questions/3280353/how-to-import-a-jar-in-eclipse)). To test your submissions, you run the jar with `java -jar SplixKoTH-all.jar -d path\to\submissions\folder`. Ensure that `path\to\submissions\folder` has a subfoler named `java`, and to place all your files there. Do not use package names in your bots (although it may be possible with KotHComm, it's just a bit more trouble). To see all options, use `--help`. To load all the bots, use `--question-id 126815`.
## Writing a bot
To start writing a bot, you must extend **`SplixPlayer`**.
* `Direction makeMove(ReadOnlyGame game, ReadOnlyBoard board)`
+ This is where you decide which move you want your bot to make. Must not return null.
* `HiddenPlayer getThisHidden()`
+ Get the **`HiddenPlayer`** version of `this`. Useful for comparing your bot to the board.
### `enum Direction`
* Values
+ `East` *(x = 1; y = 0)*
+ `West` *(x = -1; y = 0)*
+ `North` *(x = 0; y = 1)*
+ `South` *(x = 0; y = -1)*
* `Direction leftTurn()`
+ Get the **`Direction`** that you would get if you made a left turn.
* `Direction RightTurn()`
+ Get the **`Direction`** that you would get if you made a right turn.
### `ReadOnlyBoard`
This is the class where you access the board. You can either get a local view (20x20) of the board with the player positions shown, or a global view (the entire board) with only the information of who owns and claims positions on the board. This is also where you get your position.
* `SquareRegion getBounds()`
+ Retrieve the size of the board.
* `MutableMap<com.nmerrill.kothcomm.game.maps.Point2D,ReadOnlySplixPoint> getGlobal()`
+ Get a global map of the board.
* `MutableMap<com.nmerrill.kothcomm.game.maps.Point2D,ReadOnlySplixPoint> getView()`
+ Same as `getGlobal()`, except that it is limited to a 20x20 area around your player, and that it shows player positions.
* `Point2D getPosition(SplixPlayer me)`
+ Get the position of your player. Use as `board.getPosition(this)`.
* `Point2D getSelfPosition(ReadOnlyBoard)`
+ Get your position on the board. Usage: `Point2D mypos = getSelfPosition(board)`
### `ReadOnlyGame`
`ReadOnlyGame` only provides access to the number of turns left in the game through `int getRemainingIterations()`.
### `ReadOnlySplixPoint`
* `HiddenPlayer getClaimer()`
+ Get the `HiddenPlayer` version of who is claiming a point - claiming = a trail.
* `HiddenPlayer getOwner()`
+ Get who owns a point.
* `HiddenPlayer getWhosOnSpot()`
+ If the player is positioned on this point, return the hidden version of it. Only works in `getLocal()`.
### `Point2D`
Unlike the other classes here, `Point2D` is contained in the KotHComm library. `com.nmerrill.kothcomm.game.maps.Point2D`
* `Point2D(int x, int y)`
* `int getX()`
* `int getY()`
* `Point2D moveX(int x)`
* `Point2D moveY(int y)`
* `Point2D wrapX(int maxX)`
+ Wrap the `x` value to be within the range of `maxX`.
* `Point2D wrapY(int maxY)`
+ Wrap the `y` value to be within the range of `maxY`.
* `int cartesianDistance(Point2D other)`
+ This translates to how many turns it would take for a player to move from point a to point b.
## Clojure support
The Clojure compiler is bundled with the `SplixKoTH-all.jar`, so you can use Clojure for your bot! Refer to my `random_bot` to see how to use it.
## Debugging a bot
The controller comes with a debugger to help test strategies. To start it, run the jar with the `--gui` option.
To attach the debugger to your jar, follow [these instructions](https://www.linkedin.com/pulse/debug-jar-files-intellij-idea-maksym-lushpenko) for IntelliJ, or [these instructions](https://stackoverflow.com/questions/1732259/eclipse-how-to-debug-a-java-program-as-a-jar-file) for Eclipse (Eclipse version untested).
[![enter image description here](https://i.stack.imgur.com/uOdji.jpg)](https://i.stack.imgur.com/uOdji.jpg)
If you are using a debugger with your code, you can use this to help visualize what your bot is seeing. Set a breakpoint at the beginning of `makeMove` on your bot, and ensure that it only pauses the current thread. Next, click the start button on the UI and step through your code.
[![enter image description here](https://i.stack.imgur.com/CKAh2.gif)](https://i.stack.imgur.com/CKAh2.gif)
Now, to put it all together:
# Running bots
To run your bots with others, you need to run the jar on the releases page. Here is a list of flags:
* `--iterations` (`-i`) <= `int` (default `500`)
+ Specify the number of games to run.
* `--test-bot` (`-t`) <= `String`
+ Run only the games that the bot is included in.
* `--directory` (`-d`) <= Path
+ The directory to run submissions from. Use this to run your bots. Ensure that your bots are a in a subfolder of the path named `java`.
* `--question-id` (`-q`) <= `int` (only use `126815`)
+ Download and compile the other submissions from the site.
* `--random-seed` (`-r`) <= `int` (defaults to a random number)
+ Give a seed to the runner so that bots that use random can have results reproduced.
* `--gui` (`-g`)
+ Run the debugger ui instead of running a tournament. Best used with `--test-bot`.
* `--multi-thread` (`-m`) <= `boolean` (default `true`)
+ Run a tournoment in multi-thread mode. This enables a faster result if your computer has multiple cores.
* `--thread-count` (`-c`) <= `int` (default `4`)
+ Number of threads to run if multi-thread is allowed.
* `--help` (`-h`)
+ Print a help message similar to this.
To run all the submissions on this page, use `java -jar SplixKoTH-all.jar -q 126815`.
# Formatting your post
To ensure that the controller can download all the bots, you should follow this format.
```
[BotName], Java // this is a header
// any explanation you want
[BotName].java // filename, in the codeblock
[code]
```
Also, do not use a package declaration.
---
# Scoreboard
```
+------+--------------+-----------+
| Rank | Name | Score |
+------+--------------+-----------+
| 1 | ImNotACoward | 8940444.0 |
| 2 | TrapBot | 257328.0 |
| 3 | HunterBot | 218382.0 |
+------+--------------+-----------+
```
---
Please let me know if any portion of the rules are unclear, or if you find any errors in the controller in the [chat room](https://chat.stackexchange.com/rooms/52901/splix-io-controller).
## Have fun!
[Answer]
# ImNotACoward, Java
This bot is a ~~coward~~ survival expert. If there is no enemy nearby, he claims a part of the land. If the loop of another player can be reached safely, he ~~stabs the other player in the back~~ engages the other player in a duel. If the other player cannot be attacked safely, he ~~flees~~ performs a strategic retreat to his own land.
```
ImNotACoward.java
import org.eclipse.collections.api.map.MutableMap;
import org.eclipse.collections.api.set.MutableSet;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.factory.Maps;
import org.eclipse.collections.impl.factory.Sets;
import com.jatkin.splixkoth.ppcg.game.Direction;
import com.jatkin.splixkoth.ppcg.game.SplixPlayer;
import com.jatkin.splixkoth.ppcg.game.readonly.HiddenPlayer;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlyBoard;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlyGame;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlySplixPoint;
import com.nmerrill.kothcomm.game.maps.Point2D;
import com.nmerrill.kothcomm.game.maps.graphmaps.bounds.point2D.SquareRegion;
public class ImNotACoward extends SplixPlayer {
private static final MutableSet<Direction> DIRECTIONS = Sets.mutable.of(Direction.values());
private static class Board {
public MutableSet<Point2D> allPoints = null;
private SquareRegion globalBounds = null;
private SquareRegion viewBounds = null;
private MutableMap<Point2D, ReadOnlySplixPoint> global = null;
private MutableMap<Point2D, ReadOnlySplixPoint> view = null;
public void update(ReadOnlyBoard readOnlyBoard) {
if (this.allPoints == null) {
this.allPoints = readOnlyBoard.getGlobal().keysView().toSet();
this.globalBounds = readOnlyBoard.getBounds();
}
this.viewBounds = readOnlyBoard.viewingArea;
this.global = readOnlyBoard.getGlobal();
this.view = readOnlyBoard.getView();
}
public boolean inBounds(Point2D point) {
return globalBounds.inBounds(point);
}
public boolean inView(Point2D point) {
return viewBounds.inBounds(point);
}
public ReadOnlySplixPoint getSplixPoint(Point2D point) {
return inView(point) ? view.get(point) : global.get(point);
}
public MutableSet<Point2D> getNeighbors(Point2D point) {
return DIRECTIONS.collect(d -> point.move(d.vector.getX(), d.vector.getY())).select(this::inBounds);
}
public MutableSet<Point2D> getNeighbors(MutableSet<Point2D> points) {
return points.flatCollect(this::getNeighbors);
}
public MutableSet<Point2D> getBorders(SquareRegion region) {
return allPoints.select(p -> region.inBounds(p) &&
(p.getX() == region.getLeft() || p.getX() == region.getRight() ||
p.getY() == region.getTop() || p.getY() == region.getBottom() ||
p.getX() == globalBounds.getLeft() || p.getX() == globalBounds.getRight() ||
p.getY() == globalBounds.getTop() || p.getY() == globalBounds.getBottom()));
}
}
private class Player {
public final HiddenPlayer hiddenPlayer;
public MutableSet<Point2D> owned = Sets.mutable.empty();
private MutableSet<Point2D> unowned = null;
private MutableSet<Point2D> oldClaimed = Sets.mutable.empty();
public MutableSet<Point2D> claimed = Sets.mutable.empty();
private MutableSet<Point2D> oldPos = Sets.mutable.empty();
public MutableSet<Point2D> pos = Sets.mutable.empty();
public Player(HiddenPlayer hiddenPlayer) {
super();
this.hiddenPlayer = hiddenPlayer;
}
public void nextMove() {
owned.clear();
unowned = null;
oldClaimed = claimed;
claimed = Sets.mutable.empty();
oldPos = pos;
pos = Sets.mutable.empty();
}
public MutableSet<Point2D> getUnowned() {
if (unowned == null) {
unowned = board.allPoints.difference(owned);
}
return unowned;
}
public void addOwned(Point2D point) {
owned.add(point);
}
public void addClaimed(Point2D point) {
claimed.add(point);
}
public void setPos(Point2D point) {
pos.clear();
pos.add(point);
}
public void calcPos() {
if (pos.isEmpty()) {
MutableSet<Point2D> claimedDiff = claimed.difference(oldClaimed);
if (claimedDiff.size() == 1) {
pos = board.getNeighbors(claimedDiff).select(p -> !claimed.contains(p) && !board.inView(p));
} else if (!oldPos.isEmpty()) {
pos = board.getNeighbors(oldPos).select(p -> owned.contains(p) && !board.inView(p));
} else {
pos = owned.select(p -> !board.inView(p));
}
}
}
}
private Board board = new Board();
private Point2D myPos = null;
private final Player nobody = new Player(new HiddenPlayer(null));
private final Player me = new Player(new HiddenPlayer(this));
private MutableMap<HiddenPlayer, Player> enemies = Maps.mutable.empty();
private MutableMap<HiddenPlayer, Player> players = Maps.mutable.of(nobody.hiddenPlayer, nobody, me.hiddenPlayer, me);
private MutableSet<Point2D> path = Sets.mutable.empty();
private Player getPlayer(HiddenPlayer hiddenPlayer) {
Player player = players.get(hiddenPlayer);
if (player == null) {
player = new Player(hiddenPlayer);
players.put(player.hiddenPlayer, player);
enemies.put(player.hiddenPlayer, player);
}
return player;
}
private Direction moveToOwned() {
MutableSet<Point2D> targets = me.owned.difference(me.pos);
if (targets.isEmpty()) {
return moveTo(myPos);
} else {
return moveTo(targets.minBy(myPos::cartesianDistance));
}
}
private Direction moveTo(Point2D target) {
return DIRECTIONS.minBy(d -> {
Point2D p = myPos.move(d.vector.getX(), d.vector.getY());
return !board.inBounds(p) || me.claimed.contains(p) ? Integer.MAX_VALUE : target.cartesianDistance(p);
});
}
@Override
protected Direction makeMove(ReadOnlyGame readOnlyGame, ReadOnlyBoard readOnlyBoard) {
board.update(readOnlyBoard);
myPos = readOnlyBoard.getPosition(this);
path.remove(myPos);
for (Player e : players.valuesView()) {
e.nextMove();
}
for (Point2D point : board.allPoints) {
ReadOnlySplixPoint splixPoint = board.getSplixPoint(point);
getPlayer(splixPoint.getOwner()).addOwned(point);
getPlayer(splixPoint.getClaimer()).addClaimed(point);
getPlayer(splixPoint.getWhosOnSpot()).setPos(point);
}
for (Player e : players.valuesView()) {
e.calcPos();
}
if (me.owned.contains(myPos) && path.allSatisfy(p -> me.owned.contains(p))) {
path.clear();
}
if (path.isEmpty()) {
MutableSet<Point2D> enemyPositions = enemies.valuesView().flatCollect(e -> e.pos).toSet();
int enemyDistance = enemyPositions.isEmpty() ? Integer.MAX_VALUE :
enemyPositions.minBy(myPos::cartesianDistance).cartesianDistance(myPos);
if (enemyDistance < 20) {
MutableSet<Point2D> enemyClaimed = enemies.valuesView().flatCollect(e -> e.claimed).toSet();
if (!enemyClaimed.isEmpty()) {
Point2D closestClaimed = enemyClaimed.minBy(myPos::cartesianDistance);
if (closestClaimed.cartesianDistance(myPos) < enemyDistance) {
return moveTo(closestClaimed);
} else if (enemyDistance < 10) {
return moveToOwned();
}
}
}
if (me.owned.contains(myPos)) {
if (!me.getUnowned().isEmpty()) {
Point2D target = me.getUnowned().minBy(myPos::cartesianDistance);
if (target.cartesianDistance(myPos) > 2) {
return moveTo(target);
}
}
int safeSize = Math.max(1, Math.min(enemyDistance / 6, readOnlyGame.getRemainingIterations() / 4));
SquareRegion region = Lists.mutable
.of(new SquareRegion(myPos, myPos.move(safeSize, safeSize)),
new SquareRegion(myPos, myPos.move(safeSize, -safeSize)),
new SquareRegion(myPos, myPos.move(-safeSize, safeSize)),
new SquareRegion(myPos, myPos.move(-safeSize, -safeSize)))
.maxBy(r -> me.getUnowned().count(p -> r.inBounds(p)));
path = board.getBorders(region);
} else {
return moveToOwned();
}
}
if (!path.isEmpty()) {
return moveTo(path.minBy(myPos::cartesianDistance));
}
return moveToOwned();
}
}
```
[Answer]
# TrapBot, Java
```
TrapBot.java
import com.jatkin.splixkoth.ppcg.game.Direction;
import com.jatkin.splixkoth.ppcg.game.SplixPlayer;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlyBoard;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlyGame;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlySplixPoint;
import com.nmerrill.kothcomm.game.maps.Point2D;
import com.nmerrill.kothcomm.game.maps.graphmaps.bounds.point2D.SquareRegion;
import javafx.util.Pair;
import org.eclipse.collections.api.map.MutableMap;
import org.eclipse.collections.impl.factory.Lists;
import java.util.Comparator;
/**
* Trap bot goes to the wall and traces the entirety around. Hopes that
* the players in the middle die and that nobody challenges him. Nearly
* all turns are left turns.
*/
public class TrapBot extends SplixPlayer {
/**
* Mode when the bot is attempting to reach the wall from it's original spawn
* location.
*/
public static final int MODE_GOING_TO_WALL = 1;
/**
* Mode when we have reached the wall and are now going around the board.
*/
public static final int MODE_FOLLOWING_WALL = 2;
private int mode = MODE_GOING_TO_WALL;
public static int WALL_EAST = 1;
public static int WALL_NORTH = 2;
public static int WALL_WEST = 3;
public static int WALL_SOUTH = 4;
/**
* How long the bot would like to go before he turns around to go back home.
*/
private static final int PREFERRED_LINE_DIST = 5;
private int distToTravel = 0;
private Direction lastMove = Direction.East;// could be anything that's not null
private int lastTrailLength = 0;
@Override
protected Direction makeMove(ReadOnlyGame game, ReadOnlyBoard board) {
Direction ret = null;
MutableMap<Point2D, ReadOnlySplixPoint> view = board.getView();
int trailLength = getTrailLength(board, view);
if (trailLength == 0) {
int closestWall = getClosestWall(board);
Direction directionToWall = getDirectionToWall(closestWall);
if (lastTrailLength != 0) {
ret = lastMove.leftTurn();
// move to the other half of 2 width line so we can start without shifting to the left
}
if (mode == MODE_GOING_TO_WALL && ret == null) {
int distCanTravel = getDistCanTravel(
getSelfPosition(board), board.getBounds(), directionToWall);
if (distCanTravel == 0) mode = MODE_FOLLOWING_WALL;
else ret = directionToWall;
distToTravel = distCanTravel;
}
if (mode == MODE_FOLLOWING_WALL && ret == null) {
int distCanTravel = 0;
ret = directionToWall;
while (distCanTravel == 0) {// keep turning left until we can get somewhere
ret = ret.leftTurn();
distCanTravel = getDistCanTravel(
getSelfPosition(board), board.getBounds(), ret);
}
distToTravel = distCanTravel;
}
}
// once we have started we are on auto pilot (can't run after the before block)
else if (trailLength == distToTravel || trailLength == (distToTravel + 1))
ret = lastMove.leftTurn();
if (ret == null)// if we don't have a move otherwise, we must be on our trail. ret same as last time
ret = lastMove;
lastTrailLength = trailLength;
lastMove = ret;
return ret;
}
int getClosestWall(ReadOnlyBoard board) {
Point2D thisPos = getSelfPosition(board);
return Lists.mutable.of(
new Pair<>(WALL_NORTH, board.getBounds().getTop() - thisPos.getY()),
new Pair<>(WALL_SOUTH, thisPos.getY()),
new Pair<>(WALL_EAST, board.getBounds().getRight() - thisPos.getX()),
new Pair<>(WALL_WEST, thisPos.getX())
).min(Comparator.comparingInt(Pair::getValue)).getKey();
}
/**
* This goes around some intended behavior in the controller to get the correct result. When a player goes outside
* his territory the land under him is converted to a trail -- on the next step of the game. So a trail length may
* be the count of the trail locations plus one. That is what this function calculates. Depends on the whole trail
* being contained inside the view passed to it.
* @return
*/
int getTrailLength(ReadOnlyBoard board, MutableMap<Point2D, ReadOnlySplixPoint> view) {
boolean isPlayerOutsideHome = !view.get(getSelfPosition(board)).getOwner().equals(getThisHidden());
int trailLength = view.count(rop -> rop.getClaimer().equals(getThisHidden()));
return trailLength + (isPlayerOutsideHome? 1 : 0);
}
/**
* Calculate how far we can travel in the direction before we hit the wall.
* @return
*/
int getDistCanTravel(Point2D currPos, SquareRegion bounds, Direction direction) {
for (int i = 1; i <= PREFERRED_LINE_DIST; i++) {
if (!bounds.inBounds(currPos.move(direction.vector.getX()*i, direction.vector.getY()*i)))
return i-1;
}
return PREFERRED_LINE_DIST;
}
/**
* Get which direction needs to be traveled to reach the specified wall.
* Requires that neither Direction nor the values of `WALL_...` change.
* @param targetWall
* @return
*/
Direction getDirectionToWall(int targetWall) {
return Direction.values()[targetWall-1];
}
}
```
This is perhaps the most simple bot. All it does is trace out the edge of the board, doubling back on itself to reduce risk of being killed.
[Answer]
# random\_bot, Clojure
This is **RandomBot**, but I had to stick to naming conventions, and some issues prevent me from using the hyphen in the name, so underscores reign! The `make-move` fn returns a vec with the first item being the `Direction` you want to move in, and the second being the state you want to be passed back to you on the next turn. Do not use any external atoms, since this code may be running multiple games in parallel.
```
random_bot.clj
(ns random-bot
(:import
[com.jatkin.splixkoth.ppcg.game Direction]))
(defn make-move [game board state]
[(rand-nth [Direction/East
Direction/West
Direction/North
Direction/South])
nil])
```
[Answer]
# HunterBot, Java
```
HunterBot.java
import com.jatkin.splixkoth.ppcg.game.Direction;
import com.jatkin.splixkoth.ppcg.game.SplixPlayer;
import com.jatkin.splixkoth.ppcg.game.readonly.HiddenPlayer;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlyBoard;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlyGame;
import com.jatkin.splixkoth.ppcg.game.readonly.ReadOnlySplixPoint;
import com.nmerrill.kothcomm.game.maps.Point2D;
import org.eclipse.collections.api.map.MutableMap;
import org.eclipse.collections.api.set.ImmutableSet;
import org.eclipse.collections.impl.factory.Sets;
import java.util.Comparator;
/**
* This bot looks for any trail points left behind by another player and sets that as his target. If the target ever
* disappears, it will continue on in hopes that the player will return soon, or if another target appears, it will
* go towards that one. Works best when the other player repeatedly goes in the same general direction.
*/
public class HunterBot extends SplixPlayer {
private Point2D lastTarget;
private Direction lastMove = Direction.East;
@Override
protected Direction makeMove(ReadOnlyGame game, ReadOnlyBoard board) {
Point2D thisPos = getSelfPosition(board);
MutableMap<Point2D, ReadOnlySplixPoint> global = board.getGlobal();
MutableMap<Point2D, ReadOnlySplixPoint> targets = global.select((pt, rosp) ->
!rosp.getClaimer().equals(getThisHidden())
&& !rosp.getClaimer().equals(new HiddenPlayer(null)));
if (targets.size() == 0 && lastTarget == null) {
lastMove = lastMove.leftTurn();
return lastMove;
}
Point2D target = null;
if (targets.size() == 0) target = lastTarget;
else target = targets.keysView().min(Comparator.comparingInt(thisPos::cartesianDistance));
if (target.equals(thisPos)) {
lastTarget = null;
if (global.get(thisPos).getOwner().equals(getThisHidden())) {
lastMove = lastMove.leftTurn();
return lastMove;
} else
// time to go home
target = global.select((z_, x) -> getThisHidden().equals(x.getOwner())).keySet().iterator().next();
}
lastTarget = target;
lastMove = makeSafeMove(target, global, board, thisPos);
return lastMove;
}
private Direction makeSafeMove(Point2D targetLocation, MutableMap<Point2D, ReadOnlySplixPoint> map, ReadOnlyBoard board, Point2D currLoc) {
Point2D dist = targetLocation.move(-currLoc.getX(), -currLoc.getY());
ImmutableSet<Direction> possibleMoves = Sets.immutable.of(Direction.values())
.select(x -> {
Point2D pos = currLoc.move(x.vector.getX(), x.vector.getY());
return !board.getBounds().outOfBounds(pos) && !getThisHidden().equals(map.get(pos).getClaimer());
});
Direction prefMove;
if (Math.abs(dist.getX()) > Math.abs(dist.getY()))
prefMove = getDirectionFroPoint(new Point2D(normalizeNum(dist.getX()), 0));
else
prefMove = getDirectionFroPoint(new Point2D(0, normalizeNum(dist.getY())));
if (possibleMoves.contains(prefMove)) return prefMove;
if (possibleMoves.contains(prefMove.leftTurn())) return prefMove.leftTurn();
if (possibleMoves.contains(prefMove.rightTurn())) return prefMove.rightTurn();
return prefMove.leftTurn().leftTurn();
}
private Direction getDirectionFroPoint(Point2D dir) {
return Sets.immutable.of(Direction.values()).select(d -> d.vector.equals(dir)).getOnly();
}
private int normalizeNum(int n) { if (n < -1) return -1; if (n > 1) return 1; else return n;}
}
```
One of the most basic bots. It searches the board for spots to kill others, and it will follow the shortest path possible to get to a killing position. If it is outside its territory, it will make random moves until it has another opening to kill another player. It has some logic to prevent it fomr running over itself, and when all other players are dead it goes back to its home. Once home it just goes in a little square.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/80493/edit).
Closed 7 years ago.
[Improve this question](/posts/80493/edit)
Inspired by the [job-interview with Joel Grus](http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/), the goal of this challenge is to write a [tensorflow](https://www.tensorflow.org/) (or other deep/machine learning) program that *learns* [Fizzbuzz](https://en.wikipedia.org/wiki/Fizz_buzz#Programming_interviews) and correctly prints out the answers to the positive integers less than 1000.
You can assume there are files named `train.csv` and `test.csv` and each contain a sorted list of sequential integers and the fizzbuzz answer:
```
...
100, buzz
101, 101
102, fizz
103, 103
104, 104
105, buzz
...
150000, fizzbuzz
```
`test.csv` spans 1-1000 and `train.csv` spans 1001-150000.
## Rules
1. You must not hard-code the rules to Fizzbuzz anywhere in your program. The output must be from a machine learned representation that is learned *while running the code*.
2. You must utilize `train.csv` in the training set and check your output against `test.csv`. You cannot use `test.csv` during training.
3. You must get all outputs correct from `test.csv` (but as is case with deep-learning, we'll allow your code to fail this rule no more than 5% of the time).
4. You may use any language and any external module (eg. python/tensorflow) as long they explicitly perform some kind of learning. Reference both the language and the module in the title of your post.
5. This is a popularity contest, so the submission with the most votes after one week wins.
]
|
[Question]
[
Your job is to open a browser window **of the default browser** to <http://codegolf.stackexchange.com>.
Your code must open the browser itself, and cannot rely on an open one.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
---
>
> Moderator note: A large number of answers to this challenge use the URLs <http://ppcg.lol> or <http://ppcg.ga>. These URLs did direct to <https://codegolf.stackexchange.com> at the time, but have since expired. By [this meta discussion](https://codegolf.meta.stackexchange.com/q/25421/66833), they have been allowed to stay, with the note that they are currently invalid.
>
>
>
[Answer]
# [Oration](https://github.com/ConorOBrien-Foxx/Assorted-Programming-Languages/tree/master/oration), 41 bytes
Not winning, but sure was fun. As of right now, I'm only 1 bytee behind python!
```
I need webbrowser
Now open "http:ppcg.ga"
```
Explanation:
`I need` compiles to `import $1` with `webbrowser` being the module.
`Now` runs the following command from the module as `module.command` with the arguments of anything following.
So this compiles to:
```
#!/usr/bin/env python3
import webbrowser
webbrowser.open("http:ppcg.ga")
```
I do end up needing the `http:` part though, and it can't be shortened.
[Answer]
# Batch, 17 bytes
Saved 3 bytes thanks to Mego.
```
start www.ppcg.ga
```
This will open in your default browser if you run it from the windows command line.
I think it'll work in Powershell too, but I'm not sure.
[Answer]
## GNU Emacs, ~~29~~ ~~27~~ ~~14~~ 33 bytes
```
(eww"codegolf.stackexchange.com")
```
The previous answer with a URL shortener was:
```
(eww"ppcg.ga") ;; 14 bytes
```
However:
>
> Much like ppcg.lol, ppcg.ga has been unregistered, invalidating this answer. But unlike last time, there is no replacement short url. (@lyxal)
>
>
>
[EWW](https://www.gnu.org/software/emacs/manual/html_mono/eww.html) is a browser inside Emacs. The `browse-web` function is an alias for `eww`, and so that makes `eww` the *default browser* in Emacs:
>
> Your job is to open a browser window of *the default browser* to <http://codegolf.stackexchange.com>.
>
>
>
Thanks to @CoolestVeto, @Jonathan Leech-Pepin and @zyabin101.
[Answer]
# PowerShell, ~~17~~ 16 Bytes
```
saps www.ppcg.lol
```
Using an even shorter domain provided by Milo.
```
saps www.ppcg.ga
```
---
While `start` is a known alias for `Start-Process` there is another one for `saps`. You can see this from `Get-Alias`. It follows the convention for similar `Start-` and `Stop-` cmdlets.
---
As those URLs no longer exist the only way to make this work is to use the horribly inefficient 36 characters for
`saps http:codegolf.stackexchange.com`
At least we can drop the slashes no problem
[Answer]
# Terminal (OSX), ~~20~~ ~~18~~ 17 bytes
```
open http:ppcg.ga
```
*Saved 2 thanks to CoolestVeto*
[Answer]
# MATLAB, ~~28~~ 25 bytes
```
web www.ppcg.lol -browser
```
* `www` is shorter than `http://` and ensures that the address is processed as a URL
* This is shorter using the implicit function call (which casts inputs as strings) rather than the explicit version `web('www.ppcg.lol', '-browser')`.
* If you are on a OS X, this can be simplified to `web ppcg.lol -browser` as MATLAB will automatically append an `http://` (**21 bytes**)
**Alternatives**:
* On windows this can be shortened to (**19 bytes**)
```
!start www.ppcg.lol
```
* On OS X (**21 bytes**)
```
!open http://ppcg.lol
```
* The following would work in a deployed MATLAB application (**16 bytes**)
```
web www.ppcg.lol
```
* If the built-in browser could be used this could be reduced even further as `http` is implied (**12 bytes**)
```
web ppcg.lol
```
[Answer]
# [AutoHotKey](https://autohotkey.com/), 16 bytes
```
Run www.ppcg.lol
```
[Answer]
# Python, ~~52~~ ~~48~~ ~~47~~ ~~45~~ 44 bytes
Shamelessly borrowing that shortened link.
```
from webbrowser import*;open("http:ppcg.ga")
```
Thanks to CrazyPython for -4 bytes, and Sp3000 for a further one.
Edit: shaved 2 more off thanks to CoolestVeto
Edit: thanks to MD XF for registering ppcg.ga and saving another byte
[Answer]
# Java 7, 151 bytes
```
class P{public static void main(String[]a)throws Exception{java.awt.Desktop.getDesktop().browse(new java.net.URI("http:codegolf.stackexchange.com"));}}
```
Java is not the best language for golfing...
Here's the same program in a more readable format:
```
class P {
public static void main (String[] a) throws Exception {
java.awt.Desktop.getDesktop().browse(new java.net.URI("http:codegolf.stackexchange.com"));
}
}
```
Saved 2 bytes by removing `//` in the URI/L~~, and another byte by switching to `.ga` from `.lol` (indirectly thanks to @Milo)~~
[Answer]
# Bash, ~~24~~ 22 bytes
```
xdg-open http:ppcg.lol
```
Not as short as some others. `firefox ppcg.lol` is shorter, but it doesn't meet question spec.
[Answer]
# Java 8, ~~115~~ 112 bytes
```
interface P{static void main(String[]a)throws Exception{java.awt.Desktop.getDesktop().browse(new java.net.URI("http:ppcg.ga"));}}
```
Java is not the best language for golfing...
Here's the same program in a more readable format:
```
interface P {
static void main (String[] a) throws Exception {
java.awt.Desktop.getDesktop().browse(new java.net.URI("http:ppcg.ga"));
}
}
```
Saved 2 bytes by removing `//` (thanks @CoolestVeto), and another byte by switching to `.ga` from `.lol` (indirect thanks to @Milo)
[Answer]
# [Pylongolf](https://github.com/lvivtotoro/pylongolf), 11 bytes
```
"ppcg.lol"p
```
Pushes ppcg.lol into the stack then `p` opens it.
[Answer]
# JavaScript, 34 bytes
```
require('open')('http://ppcg.lol')
```
Uses Node.js
[Answer]
# Applescript, 28 bytes
* 3 bytes saved thanks to @CoolestVeto.
```
open location"http:ppcg.lol"
```
[Answer]
# Mathematica, 28 bytes
```
SystemOpen@"http://ppcg.lol"
```
[Answer]
# R, 26 bytes
`shell.exec("www.ppcg.lol")`
I don't know of any shorter way to do this in R.
[Answer]
# Actionscript 3, 117 bytes
```
package{import flash.display.Sprite;public class A extends Sprite{function A(){navigateToUrl("ppcg.lol","_blank")}}}
```
Like Java, this is not a great golfing language. Here's the code with formatting:
```
package
{
import flash.display.Sprite;
public class A extends Sprite
{
function A()
{
navigateToUrl("ppcg.lol", "_blank")
}
}
}
```
[Answer]
# Rebol 2, 16 15 bytes
```
browse"ppcg.ga"
```
if you accept an error before opening the page on Linux, no error on Windows
**20 bytes** without an error
```
browse http:ppcg.lol
```
[Answer]
# Perl 5, ~~66~~ ~~57~~ 76 bytes
Should work everywhere, but needs that import :(
8 bytes saved with @msh210 comment.
```
use Browser::Open open_browser;open_browser"http:codegolf.stackexchange.com"
```
Also, for funsies :
### Perl 5 (Windows), ~~34~~ 48 bytes
```
system "start http://codegolf.stackexchange.com"
```
### Perl 5 (Unix), ~~31~~ 49 bytes
```
system "xdg-open http:codegolf.stackexchange.com"
```
[Answer]
# [Red](http://www.red-lang.org), 40 bytes
```
browse http://codegolf.stackexchange.com
```
[(Don't) Try it online!](https://tio.run/##K0pN@R@UmhId@z@pKL@8OFUho6SkwEpfPzk/JTU9PydNr7gkMTk7tSI5IzEvPVUvOT/3/38A "Red – Try It Online")
`ppcg.ga` no longer works, so needed to include the full domain name. But its funny that Red has its own URL data type!
[Answer]
# Factor, ~~38~~ ~~36~~ ~~26~~ 29 bytes
```
[ "http:t.ly/-E-J" open-url ]
```
I didn't know one could golf-off the `//` in the protocol.
[Answer]
# RFO-BASIC, 22 bytes
```
BROWSE "http:ppcg.lol"
```
Read about RFO-BASIC at [laughton.com](http://laughton.com/basic).
[Answer]
# VBScript, 57 bytes
I used to have lots of fun creating tiny programs in VBScript, back in 2010.
I've remembered this language and used the code on: <https://stackoverflow.com/a/13401872/2729937>
It still works on Windows 7, at least.
```
set S=CreateObject("WScript.Shell")
S.run("www.ppcg.ga")
```
This is a bit different from the usual `start www.ppcg.lol`, in the sense that it executes the `www.ppcg.ga` directly, with an implicit `start`.
An alternative way would be `"cmd.exe /C start www.ppcg.ga"`.
[Answer]
# VBA, 84 bytes
```
Sub Main()
ThisWorkbook.FollowHyperlink("http://codegolf.stackexchange.com")
End Sub
```
[Answer]
# [Zsh](https://www.zsh.org/) on MacOS, 19 bytes
```
open http:t.ly/-E-J
```
[Try it online!](https://tio.run/##qyrO@P8/vyA1TyGjpKTAqkQvp1Jf11XX6/9/AA "Zsh – Try It Online") (`t.ly` is a URL shortener).
[Answer]
# Common Lisp, 31 bytes
```
(ext:shell "open http:ppcg.ga")
```
Note: This worked at the time of writing. The domain `ppcg.ga` has since expired, making this answer no longer valid.
[Answer]
# C#, 33 bytes
```
Process.Start("http://ppcg.lol");
```
Opens the default browser to the web address
[Answer]
# VB.NET, ~~32~~ 30 bytes
```
Process.Start("http:ppcg.lol")
```
[Answer]
# Game Maker Studio, 26 bytes
```
url_open('http://ppcg.ga')
```
[Answer]
# PHP (OSX), 33 bytes
```
<?php exec("open http:ppcg.lol");
```
# PHP (Windows), 34 bytes
```
<?php exec("start http:ppcg.lol");
```
] |
[Question]
[
Note that this is not the same as [Print the alphabet four times](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times).
This task is to write a program to generate four copies of each letter of the English alphabet, one letter per line, on standard output:
```
A
A
A
A
B
B
B
B
```
etc.
The output should include newlines after each letter.
Lowercase letters and/or extra whitespace are acceptable.
The solution must be a complete program.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with a lower score being the goal.
[Answer]
## APL (5)
```
⍪4/⎕A
```
Matrix format (`⍪`) of 4-replication (`4/`) of alphabet (`⎕A`).
[Answer]
# Python 2 - 37
```
for i in range(104):print chr(i/4+65)
```
As `i` goes from 0 to 104, it is divided by four and added to the ASCII value for `A`, and the resulting character is printed.
[Answer]
# R, 30 28 27 25
```
write(rep(LETTERS,e=4),1)
```
---
Former version with 30 bytes:
```
cat(rep(LETTERS,e=4),sep="\n")
```
[Answer]
## C, 59
I submit this, an uncompetitively long answer, simply because I don't see a C submission yet. And that makes me sad. :-/
LATER: Props to @moala for doing a "/4" int version of this, saving 13 chars!
```
float i;main(){while(i<26)printf("%c\n",65+(int)i),i+=.25;}
```
[Answer]
# J: ~~18~~ 13
```
4#u:65+i.26 1
```
I'm still pretty shaky with J, so this could probably be improved
[Answer]
## Ruby, 23
```
puts ([*?A..?Z]*4).sort
```
All credit to @manatwork -- upvote his comment, not this. :)
[Answer]
# PowerShell: 32 23
**Golfed code:**
```
[char[]](65..90*4)|Sort
```
**Walkthrough:**
`[char[]](`...`)` takes an array of objects and converts them to ASCII characters.
`65..90` are the ASCII codes for A-Z.
`*4` repeats the series 4 times.
`|Sort` sorts the output.
**Note:**
If you want this written to a file, just throw `>`, followed by a file name, at the end.
[Answer]
## Haskell, 46
```
x a=a++a
main=putStr$['A'..'Z']>>=x.x.(:"\n")
```
[Answer]
# Befunge 98 - 18
```
1+::'g`#@_4/'A+,a,
```
Works by storing a number and ending when it reaches 104. Prints out the corresponding character of the alphabet for the number divided by 4, followed by a newline. But if I need not add a newline after each letter, then it is 16 chars:
```
1+::'g`#@_4/'A+,
```
Can be reduced if I can print more characters (ie all of them four times)(~~7~~ 6 chars, even works in Befunge 93):
```
1+:4/,
```
With newline:
```
1+:4/,a,
```
[Answer]
# C, ~~46~~ ~~44~~ 43
~~46~~:
```
i;main(){while(i<104)printf("%c\n",65+i++/4);}
```
~~44~~:
```
i=260;main(j){for(;(j=i++>>2)<91;puts(&j));}
```
44 too:
```
i=260;main(j){while(j=i++>>2,j<91)puts(&j);}
```
Thanks to @marinus, 43:
```
i=260;main(j){while(j=i++/4,j<91)puts(&j);}
```
Should I add a bounty for getting to 42? :)
[Answer]
**Java: 56**
```
for(int i=0;i<104;)System.out.println((char)(i++/4+65));
```
edit: changed from 'print' to 'println'
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 48 bytes
```
+++[[-<+>>++<]+>]<<<<<<+[->,++++[->.<<<.>>]>+<<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fW1s7OlrXRtvOTlvbJlbbLtYGDLSjde10tEGSunZ6QL6enV2snbaNTez//wA "brainfuck – Try It Online")
Prints in lowercase, separated by carriage returns. Uses wrapping 8 bit cells as well as cells left of the origin, though you can prepend a `>` to counter the latter.
[Answer]
# GolfScript: ~~17~~ 15 characters
```
26,{65+...}%+n*
```
[Answer]
# Bash: 24 characters
```
printf %s\\n {A..Z}{,,,}
```
[Answer]
**BrainF\*** ,79 60
```
+++++++++++++[->++>+>+++++<<<]>>---<[->>>++++[-<.<.>>]<+<<]
```
[Answer]
## Forth, 37
```
'h 0 [do] [i] 4 / 'A + emit cr [loop]
```
[Answer]
# Actually, 6 bytes
```
4ú*SÖi
```
[Try it here!](http://actually.tryitonline.net/#code=NMO6KlPDlmk&input=)
Explanation
```
4ú*SÖi
4 * Do 4 times
ú Create string of alphabet in lowercase
S Sort it
Ö Switch Case
i Push each character of string
```
4 Bytes with lowercase and no newline:
```
4ú*S
```
[Answer]
# 16-bit x86 machine code MS-DOS COM, 25 bytes
In hex:
```
B409BA160189D7B96800F6C1037502FE05CD21E2F5C3400A24
```
This is a complete MS-DOS .COM program. Copy the byte sequence to the file with .com extension and run it from DOSBox
Disassembly:
```
00: B4 09 mov ah,0x09 ;INT 21h "Write string to STDOUT" function
02: BA 16 01 mov dx,0x116 ;Address of the string s ('$'-terminated)
05: 89 D7 mov di,dx ;Because there's no way to dereference address in DX
07: B9 68 00 mov cx,104 ;CX=26*4
_0000000A:
0A: F6 C1 03 test cl,0x03 ;When lower two bits are zero...
0D: 75 02 jne _00000011 ;...do not skip the next instruction
0F: FE 05 inc b,[di] ;*s++
_00000011:
11: CD 21 int 21 ;Print the string
13: E2 F5 loop _0000000A ;Until --CX==0
15: C3 retn
16: 40 db 0x40 ;s[0], starts with 'A'-1
17: 0A db 0x0A ;'\n'
18: 24 db '$' ;Terminator required by the print function
```
[Answer]
# [Perl 5](https://www.perl.org/), 20 bytes
```
print"$_
"x4for A..Z
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvREklnkupwiQtv0jBUU8v6v9/AA "Perl 5 – Try It Online")
---
# [Perl 5](https://www.perl.org/) + `-M5.10.0`, 20 bytes
```
eval"say;"x4for A..Z
```
[Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHqTix0lqpwiQtv0jBUU8v6v//f/kFJZn5ecX/dX1N9QwN9AwA "Perl 5 – Try It Online")
[Answer]
# x86-16 ASM, IBM PC DOS, ~~22~~ 19 bytes
**Binary:**
```
00000000: 400a 24b8 1109 8bd6 b168 d0c8 102c cd21 @.$......h...,.!
00000010: e2f8 c3 ...
```
Build with `xxd -r` and test in DOSBox or your favorite DOS VM.
**Unassembled:**
```
40 0A 24 DB '@', 0AH, '$' ; the letter + NL + '$' string terminator
B8 0911 MOV AX, 0911H ; AH = DOS print string; AL = 0001 0001 bit pattern
8B D6 MOV DX, SI ; DX to output string
B1 68 MOV CL, 26*4 ; Loop 4 times for each letter in alphabet
ALOOP:
D0 C8 ROR AL, 1 ; roll repeating bit pattern to the right
10 2C ADC BYTE PTR[SI], CH ; add rightmost bit to ASCII character
CD 21 INT 21H ; print letter to console
E2 F8 LOOP ALOOP ; continue looping
C3 RET ; return to DOS
```
**Notes:**
For most flavors of DOS, we know the values of many CPU registers at the [start of execution](http://www.fysnet.net/yourhelp.htm) and we know `SI` is `0100H`, and `CH` is `0`. So by placing the output string in the beginning of the program, `[SI]` will already be pointing to it. These bytes (`'@',0AH,'$'`) decode to two benign instructions (`INC AX`, `OR AH, [SI]`), which have no effect on the program.
`AL` contains the bit pattern of `0001 0001` which is bit rolled right each time and the rightmost bit added to the ASCII value of the output char in memory.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 5 bytes
```
kAdds
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=kAdds&inputs=&header=&footer=)
Look ma, no Unicode!
```
kA # Uppercase output
dd # Quadruple
s # Sorted
# (j flag) join by newlines
```
[Answer]
# [Jelly](//github.com/DennisMitchell/jelly), 5 bytes
```
ØAx4Y
```
[Try it online!](//jelly.tryitonline.net#code=w5hBeDRZ)
Explanation:
```
ØAx4Y Main link
ØA “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
4 4
x Repeat each element of x y times
Y Join x with newlines
```
[Answer]
# Q (13)
.........
```
-1@''4#'.Q.A;
```
[Answer]
**AWK, 48**
Lets try it with AWK...
```
END{s=65;for(i=104;i--;s+=0==i%4)printf"%c\n",s}
```
As suggested by [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) we can get rid of 2 chars
**AWK, 46 (Edit)**
```
END{for(i=104;i--;s+=0==i%4)printf"%c\n",s+65}
```
**AWK,40** (editing [MarkReed](https://codegolf.stackexchange.com/users/4133/mark-reed)'s code)
```
END{for(;i<104;){printf"%c\n",i++/4+65}}
```
[Answer]
## PowerShell, 21
```
65..90|%{,[char]$_*4}
```
A slightly different approach to Iszi's. And shorter :-)
[Answer]
**C# LINQ ~~115 Bytes~~110 Bytes**
```
Enumerable.Range(65, 26).SelectMany(i => Enumerable.Repeat(i,4))
.ToList().ForEach(i=> Console.WriteLine((char)i));
```
[Answer]
# 05AB1E, 6 bytes
```
A4×{S»
```
Explanation:
```
A # Push 'abcdefghijklmnopqrstuvwxyz'
4× # Repeat four times
{ # Sort
S # Split into list
» # Join by newlines
# Implicit print
```
Without newlines, 4 bytes
```
A4×{
```
[Try it online!](http://05ab1e.tryitonline.net/#code=QTTDl3tTwrs)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Aε4F=
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f8dxWEzfb//8B "05AB1E – Try It Online")
[Answer]
# Mathematica ~~50 41~~ 30
With help from alephalpha and Mark S.
```
Print/@{#,#,#,#}&/@Alphabet[];
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 46 bytes
```
for(var a=259;a++<363;WriteLine((char)(a/4)));
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb9IoyyxSCHR1sjU0jpRW9vG2MzYOrwosyTVJzMvVUMjOSOxSFMjUd9EU1PT@v9/AA "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
Here's an array representing a standard deck of cards, including two Jokers.
```
[
"AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS",
"AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD",
"AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH",
"AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC",
"J", "J"
]
```
It's composed in this manner:
* There are four suits; hearts, spades, diamonds, and clubs (H, S, D, C).
* Each suit has one card for the numbers 2 to 10, plus 4 'picture' cards, Ace, Jack, Queen, and King (A, J, Q, K).
* For each combination of suit and value, there should be one item in the array, which is a string, and is made up of the value followed by the suit (Whitespace between these is permitted).
* On top of that, there are two Joker cards ('J').
* Write in any language you please.
* Golf it up! Try to produce this output in the smallest number of bytes.
* It does not matter what order the output is in.
[Answer]
# JavaScript (ES6), ~~62~~ 60 bytes
```
f=n=>n>51?'JJ':[('JQKA'[k=n>>2]||k-2)+'CDHS'[n&3],...f(-~n)]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PztTQXt3LS90qWkPdK9DbUT062zbPzs4otqYmW9dIU1vd2cUjWD06T804VkdPTy9NQ7cuTzP2f3J@XnF@TqpeTn66RpqGpuZ/AA "JavaScript (Node.js) – Try It Online")
[Answer]
## [Bash](https://www.gnu.org/software/bash/) ~~43~~ 34 bytes
```
d=({A,J,Q,K,{2..10}}{H,S,D,C} J J)
```
[Try it online!](https://tio.run/##S0oszvj/P8VWo9pRx0snUMdbp9pIT8/QoLa22kMnWMdFx7lWwUvBS/N/anJGvoJKdUq0Q2ztfwA "Bash – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~200~~ 197 bytes
```
+[[<+>->++<]>]+<++++<<+++[->+++>+++++>+>+<<<<]>+.<<.>>.--<<<[->>+++<<]>>+>[<<.>.-.+>.<<.<<[>>>+.>.<<.<+<-]>[-<+>>>+<<]>>.>.<<.>+++++++++.>.<<.>+.>.<<.>++++++.>.,++++[-<-------->]>[[-<+>]>]<<[<]>>>]
```
[Try it online!](https://tio.run/##VU5bCsMwDDuQZp/A6CLGH2thUAr9GOz8mZxsHxXEQQ9kb@/ncb0@@zkGMgM0AlEsBIToma2hX09KDCXgEU66maginPHSz2zHzcHOyKVUXwRhxTRtIld@Gau@8ec3XeSBeUvYD1TPLNK12tFVrDG@ "brainfuck – Try It Online")
Uses one negative cell (+1 bytes to fix), wrapping cells (lots o' bytes to fix) and 0 on EOF (+2 bytes to remove dependancy).
Outputs
```
J J 10H 2H 3H 4H 5H 6H 7H 8H 9H AH JH KH QH 10S 2S 3S 4S 5S 6S 7S 8S 9S AS JS KS QS 10D 2D 3D 4D 5D 6D 7D 8D 9D AD JD KD QD 10C 2C 3C 4C 5C 6C 7C 8C 9C AC JC KC QC
```
### Explanation:
```
+[[<+>->++<]>] Sets the tape to powers of 2
TAPE: 1 2 4 8 16 32 64 128 0 0'
+<++++<<+++[->+++>+++++>+>+<<<<] Uses the 64 and the 128 to generate the suit letters
TAPE: 1 2 4 8 16 32 0' 73 83 68 67
I S D C
>+.<<.>>.--<< Prints the Jokers
<[->>+++<<]>>+> Uses the 16 to create 49
TAPE: 1 2 4 8 0 32 49 72' 83 68 67
H S D C
[ Loop over the suits
<<.>.-.+>.<<.<< Print the 10 card with a leading space
TAPE: 1 2 4 8' 0 32 49 Suit
[>>>+.>.<<.<+<-] Use the 8 to print the other 8 number cards
TAPE: 1 2 4 0' 8 32 57 Suit
>[-<+>>>+<<] Move the 8 back into place while also adding it to the 57
TAPE: 1 2 4 8 0' 32 65 Suit
>>.>.<<. Print the Ace
>+++++++++.>.<<. Print the Jack
>+.>.<<. Print the King
>++++++.>.<<. Print the Queen
TAPE: 1 2 4 8 0 32 81' Suit
>>, Clear the current suit
++++[-<-------->] Subtract 32 to get back to 49 (reusing the space is longer than just subtracting 32)
TAPE: 1 2 4 8 0 32 49 0' MoreSuits?
>[[-<+>]>]<<[<]>>> Shift all the remaining suits over one
TAPE: 1 2 4 8 0 32 49 Suit?'
] End on the character of the next suit and repeat
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~28~~ ~~27~~ ~~25~~ ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2TŸ.•-Ÿ•S«.•ôì•âJ„jjS«u
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fKOToDr1HDYt0j@4AksGHVoM4h7ccXgOiFnk9apiXlQUULf3/HwA)
-1 byte thanks to *@Emigna* removing the `S` after `"HSDC"`, because `√¢` does this implicitly.
**Explanation:**
```
2T≈∏ # Push list in the range [2,10]: [2,3,4,5,6,7,8,9,10]
.•-Ÿ• # Push compressed string "ajqk"
S # Convert it to a list of characters: ["a","j","q","k"]
¬´ # Merge the two lists together: [2,3,4,5,6,7,8,9,10,"a","j","q","k"]
.•ôì• # Push compressed string "cdhs"
√¢ # Cartesian product of each (pair each character of both lists):
# [[2,"a"],[2,"d"],[2,"h"],...,["k","d"],["k","h"],["k","s"]]
J # Join each pair together to a single string:
# ["2a","2d","2h",...,"kd","kh","ks"]
„jjS # Push string "jj", and convert it to a list of characters: ["j","j"]
¬´ # Merge both lists together:
# ["2a","2d","2h",...,"kd","kh","ks","j","j"]
u # Convert everything to uppercase:
# ["2A","2D","2H",...,"KD","KH","KS","J","J"]
# (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•-Ÿ•` is `"ajqk"` and `.•ôì•` is `"cdhs"`.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~550~~ 504 bytes
```
++++++++++[>+++>+++++>+++++++<<<-]>++>->[>+>+>+>+<<<<-]>----->++++.<<<<.>>>>.<<<<.>>>>>--->+++++++++++++<<<<<.-.+>>>>.<<<<<.>.-.+>>>>+.<<<<<.>.-.+>>>>++++.-----<<<<<.>.-.+>>>>>.<<<<<<.>>++++++++[-<+.>>>>.<<<<<.>.>>>>+.<<<<<.>.>>>>++++.-----<<<<<.>.>>>>>.<<<<<<.>>]>.>>.<<<<<.>>>>.>.<<<<<.>>>>+.>.<<<<<.>>>>++++++.>.<<<<<.>>>.>>+.<<<<<.>>>>.>.<<<<<.>>>>------.>.<<<<<.>>>>-.>.<<<<<.>>>.>>++++.<<<<<.>>>>.>.<<<<<.>>>>+.>.<<<<<.>>>>++++++.>.<<<<<.>>>.>>>.<<<<<<.>>>>.>>.<<<<<<.>>>>------.>>.<<<<<<.>>>>-.>>.
```
[Try it online!](https://tio.run/##nVBBCoAwDHtQaV9Q@hHxoIIgggfB98@2urlOT0aQJWkT57gPyzYf05oSFHSiL/Gj3BIzY69EUNS9Hr5ENPgcmUKieE6SzQJ2DwnKoE5mDi/Bcr2iMe5VaynfjQwUUmPkd14T1puSV8ypCUTmqCWq6tpdL8Uotbv5J/6rrm4hzy1iexSNp3QC "brainfuck – Try It Online")
[Old answer, also online!](https://tio.run/##vVBbCsMwDDuQsU9gdJHSj7VQKIV9DHr@zHGehrGfwRQIlmSsONvrcT6Pe79Soo4FdsFLVElVeTUChrnlaBE5w/skKwLDqNDMDnWPhXpj7uzZrCTBWSETs3ImFJljSFzR0ujXuDouSF/i2p/8bcFqfMybPE@cOMYL4p5RzDylNw "brainfuck – Try It Online")
[Answer]
# Java 10, ~~153~~ ~~151~~ ~~125~~ ~~77~~ 75 bytes
```
v->("AJQK2345678910".replaceAll("1?.","$0H,$0S,$0D,$0C,")+"J,J").split(",")
```
-28 bytes thanks to *@OlivierGrégoire*.
-50 bytes thanks to *@mazzy*.
[Try it online.](https://tio.run/##PY9PS8NAEMXv/RTD0sOupkvqfwkqQQ8SaUEKXsTDuo2ycbJZdieBIv3scUqDMO8wM495v2nMYBbN9md0begiQcO97smhPilmFk1KsDLO/84AnKc6fhlbw/rQAmwoOv/9/gFWvnVuC4MqeL5ncSUy5CyswcMdjMPiXoqyen05O7@4vLq@uV3mQsc6IJ8rEaVYPmiRiXn@nM3zDeuJ9ZgJdSqqrBJKp4COJFvUWBwDQv@JHDDlDAeAlknlP5VRE@YuUd3qricdeEXoZRmj2SVN3dEsvbbS94hKTS/sxz8)
**Explanation:**
```
v-> // Method with empty unused parameter and String-array return-type
"AJQK2345678910"
.replaceAll("1?.", // Replace every loose character (or "10" as single char)
"$0H,$0S,$0D,$0C,") // with "cH,cS,cD,cC,", where c is the character
+"J,J") // Append "J,J"
.split(",") // And split everything by commas
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 bytes
*1 byte saved thanks to Probie by using `1+‚ç≥9` instead of `1‚Üì‚ç≥10`*
```
'JJ',,'HCDS'∘.,⍨'AKJQ',⍕¨1+⍳9
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v8ahvql/wo941mo96@9SBHOdIdfXixJwSdfVH3S1AfrCrXqizr4u6elJ@hUJ@noJumm1@HlCya3FqXmJSTmqwo0@IOtejjva0/@peXuo6Ouoezi7B6o86ZujpPOpdoe7o7RWoDmRNPbTCUPtR72bL/0C1/9MA "APL (Dyalog Unicode) – Try It Online")
This is a full program. In the TIO link, I have enabled boxing so that the individual elements of the array can be distinguished.
Here is the boxed output.
```
┌─┬─┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬───┬───┬───┬───┐
│J│J│AH│AC│AD│AS│KH│KC│KD│KS│JH│JC│JD│JS│QH│QC│QD│QS│2H│2C│2D│2S│3H│3C│3D│3S│4H│4C│4D│4S│5H│5C│5D│5S│6H│6C│6D│6S│7H│7C│7D│7S│8H│8C│8D│8S│9H│9C│9D│9S│10H│10C│10D│10S│
└─┴─┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴───┴───┴───┴───┘
```
`'JJ',` 2 jokers concatenated to
`,` the raveled form of
`‚àò.,‚ç®` the matrix created by concatenating every combination of
* `'HCDS'` this string against
* `'AKJQ',` this string with
+ `⍕¨` the stringified forms of each of
- `1+‚ç≥9` the numbers 2..10 (1 plus the range 1..9)
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 75 bytes
```
j4d*1-2k:d%4+1g:'0-!#v_>,d/1g,' ,!#v_3
CHSDA234567890JQK@;1'< ^,;,k2"J J" <
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/P8skRctQ1yjbKkXVRNsw3UrdQFdRuSzeTidF3zBdR11BB8Qz5nL2CHZxNDI2MTUzt7A08Ar0drA2VLdRiNOx1sk2UvJS8FJSsPn/HwA "Befunge-98 (FBBI) – Try It Online")
## Program structure
[![enter image description here](https://i.stack.imgur.com/y4N8r.png)](https://i.stack.imgur.com/y4N8r.png)
At first, the stack is filled with `0`'s, and `j` does not jump over the initialisation. The initialisation pushes `4 * 13 = 52`, which is the program counter. In the following iterations the trailing `3` causes the pointer to jump over this part.
```
1-2k:d%4+1g,d/1g,' ,!#v_ Main loop
1- decrement counter
2k: duplicate counter three times
d% counter mod 13 ...
4+ ... + 4 is the position of the card in the Data section
1g, get the card from row 1 and print it
d/ counter / 13 is the position of the suit in the Data section
1g, get the suit from row 1 and print it
' , print a space as seperator
! negate the counter (0 for non-zero, 1 for 0)
_ If the counter is 0, move West ...
#v ... and move to the termination
otherwise, continue with the next iteration
```
Code that prints 10:
```
'0-!#v_> Checks if Card is '0'
'0- subtract the '0' from the card
! negate (1 for '0', 0 for all other cards)
_ If card was '0', move West
#v and go South to print '10'
Else continue to go East
;1'< ^,; Prints '10'
< Go West
1' Push '1'
; Jump to ...
; ... the next semicolon
, Print '1'
^ Go back to the main loop
The '0' will be printed by the main loop
```
Termination:
```
@; ... ;,k2"J J" <
< Go West
"J J" Push "J J"
,k2 Print it
; Jump to ...
; ... the next semicolon
@ terminate the program
```
[Answer]
# [R](https://www.r-project.org/), 65 bytes
```
c(outer(c('A',2:10,J<-'J','Q','K'),c('S','D','H','C'),paste),J,J)
```
[Try it online!](https://tio.run/##K/r/P1kjv7QktUgjWUPdUV3HyMrQQMfLRlfdS11HPRCIvdU1dYBSwUCmCxB7ALEzUKggsbgkVVPHS8dL8/9/AA "R – Try It Online")
-2 Bytes thanks to @Giuseppe and @JayCe suggestions
[Answer]
# Powershell, ~~63~~ ~~61~~ ~~59~~ 56 bytes
-3 bytes: thanks [ConnorLSW](https://codegolf.stackexchange.com/users/59735/connorlsw)
```
2..10+'AJQK'[0..3]|%{"$_`H";"$_`S";"$_`D";"$_`C"};,'J'*2
```
[Answer]
## [Perl 5](https://www.perl.org/), 41 bytes
```
sub{J,J,map<"$_"{S,D,H,C}>,A,2..10,J,Q,K}
```
[Try it online!](https://tio.run/##K0gtyjH9r5Jm@7@4NKnaS8dLJzexwEZJJV6pOljHRcdDx7nWTsdRx0hPz9AAKBmo413735qrtDhVwSWxJNHKyqU0tyC1yJqroCgzr0QBwlOIVknTtdPQjLX@DwA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~67~~ 64 bytes
```
print(*[a+b for a in['10',*'A23456789JQK']for b in'CHSD'],*'JJ')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQys6UTtJIS2/SCFRITMvWt3QQF1HS93RyNjE1MzcwtIr0Fs9FiSbBJRVd/YIdlGPBcp7ealr/v8PAA "Python 3 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), ~~78~~ ~~76~~ ~~74~~ 68 bytes
```
print['1'*(a<'1')+a+b for a in'A234567890JQK'for b in'CHSD']+['J']*2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68kWt1QXUsj0QZIaWonaicppOUXKSQqZOapOxoZm5iamVtYGngFequDhJNAws4ewS7qsdrR6l7qsVpAUwA "Python 2 – Try It Online")
Alt:
# [Python 2](https://docs.python.org/2/), 68 bytes
```
print[a+b for a in['10']+list('A23456789JQK')for b in'CHSD']+['J']*2
print['1'[a>'0':]+a+b for a in'A234567890JQK'for b in'CHSD']+['J']*2
```
---
saved
* -3 bytes, thanks to ovs
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 30 bytes
```
"JJ",/("AKQJ",$2+!9),'/:"SHDC"
```
[Try it online!](https://tio.run/##y9bNS8/7/1/Jy0tJR19DydE7EMhQMdJWtNTUUde3Ugr2cHFW@v8fAA "K (ngn/k) – Try It Online")
`!9` is the list `0 1 ... 8`
`2+!9` is the list `2 3 ... 10`
`$` to string
`,` concatenate
`,'/:` concatenate each with each right, i.e. Cartesian product; normally it's `,/:\:` or `,\:/:` but on the right we have only scalars (`"SHDC"`), so we can use `'` instead of `\:`
`"JJ",/` join (concat reduce) the list on the right using `"JJ"` as initial value for the reduction
[Answer]
# MS-SQL, 137 bytes
```
SELECT v.value+s.value
FROM STRING_SPLIT('A-2-3-4-5-6-7-8-9-10-J-Q-K','-')v,STRING_SPLIT('H-S-D-C--','-')s
WHERE s.value>''OR v.value='J'
```
An array of values in SQL is returned as separate query rows. Uses the `STRING_SPLIT` function [introduced in SQL 2016](https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql).
It includes the jokers by adding two "blank string" suits to take advantage of the existing "J" for Jack, then filtering out rows we don't want. Shorter than using `UNION ALL` statements to add the jokers.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 61 bytes
```
->{[*0..52,52].map{|x|['JAKQ'[w=x%13]||w-2,'SDHC'[x/13]]*''}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1646WstAT8/USMfUKFYvN7GguqaiJlrdy9E7UD263LZC1dA4tqamXNdIRz3YxcNZPbpCHygSq6WuXlv7v0AhLTr2PwA "Ruby – Try It Online")
[Answer]
# C# .NET, 114 bytes
```
o=>(new System.Text.RegularExpressions.Regex("1?.").Replace("AJQK2345678910","$0H,$0S,$0D,$0C,")+"J,J").Split(',')
```
Port of [my Java answer (credit to *@mazzy*)](https://codegolf.stackexchange.com/a/166628/52210).
[Try it online.](https://tio.run/##RY9PSwMxEMXv@ymGUGhCY9iq9Q@1FamKrPRQV/BQeohxWiIxWTZZXZF@9nWKLB7eYWbe4/3GxCMTauyM0zHC8icDiEkna6D8jgk/1H3jzVV4fUeTJJ1q63frzRy2sy7M5tzjV298xjapJ9w1Ttd3bVVjjDb4eFhhy9n4WjFBQ@W0Qc5uitXj8cnp5Oz84nKcM8kG@YMc5CXplrSQTIxYIQvKlJWziQ/lUHQA0@yf8DPYN1hq63nPBVocPoCeaUEAwaF6qW2i0jUb/TlVEShFrRK23DfOCWrbMDGl8D7bd78)
---
Interesting alternative of [**119 bytes** by *@Corak*](https://codegolf.stackexchange.com/questions/166623/generate-a-deck-of-cards?page=2&tab=votes#comment402916_166635).
```
using System.Linq;o=>new[]{"J","J"}.Concat(from s in"SDCH"from n in"A234567890JQK"select(n=='0'?"10":n+"")+s).ToArray()
```
[Try it online.](https://tio.run/##RY5LS8QwFIX3/RWXu5mE1lDfj9qRYUSkOgsZwUXpIsZUIp0bTFJlGPrba0YpLu7icM53@ZQ/UNbpsfeG3mG99UFvxKOhzyJRnfQeVrsEwAcZjJrqu57UtX390CpksXKRrJs5tFCOtpyT/q6bHVaYxRvE0pKSgbXObsCDIVzfLu/xN9I@Lo6OT07Pzi8u8@rpAb3u4ldGZTnLZzd4mOMVpYg89Vw824Vzcsv4CFAk/1Zf1rzBShpikwtIvreGSTg6eNtp8eJM0AxrTP@WorKRiqIZtIz6ruM8xQZ5EeEhGcYf)
If an `System.Collections.Generic.IEnumerable<string>` instead of `string[]` is an acceptable output, the trailing `.ToArray()` can be dropped so it becomes **109 bytes**.
**Explanation:**
```
using System.Linq; // Required import for the `from .. in ..` and `select` parts
o=> // Method with empty unused parameter and string-array return-type
new[]{"J","J"} // Return a string-array containing two times "J"
.Concat( // And add:
from s in"SDCH" // Loop over the suits
from n in"A234567890JQK"
// Inner loop over the cards
select(n=='0'? // If the current card item is '0'
"10" // Use 10 instead
: // Else:
n+"") // Simply use the card item as is
+s)// And append the suit
.ToArray() // Convert the IEnumerable to an array
```
[Answer]
## PHP, ~~108~~ ~~99~~ 97 Bytes
[Try it online!](https://tio.run/##Dcu7CgIxFEXRfr4ihBQJnML3gygiWkisxHIYhqDRCOpcrikU8dtjitXtTZFyXqwoklC8rB1cYy8dB3@Kul7D4YA9BhhihDEmmGKGOfq9xr9UMt@yeGb/aR@Br0ErRnjTvTsHLYWE3KkkjsW22KgkjbG/qqoy8e2ZWi69sfkP)
[Try it online! (Edit 1)](https://tio.run/##K8go@P/fxr4go0BBpcg22kvHK9Y6Lb8oNTE5QyPaUcdLJ1DHW8dIx1jHRMdUx0zHXMdCx1LH0CA2sVilRLMaqCWxqCixMj43tSg9VUOlSCfaQ0@lRCcYRLiACGcgEatpXfu/oCgzryS@CKhG0/o/AA)
**Code**
```
<?php $r=[J,J];foreach([A,J,Q,K,2,3,4,5,6,7,8,9,10]as$t)
$r=array_merge($r,[H.$t,S.$t,D.$t,C.$t]);
```
Tried to use purely php funcions, but bytecount was lower with a loop :(
**Output (using `print_r`)**
```
Array
(
[0] => J
[1] => J
[2] => HA
[3] => SA
[4] => DA
[5] => CA
[6] => HJ
[7] => SJ
[8] => DJ
[9] => CJ
[10] => HQ
[11] => SQ
[12] => DQ
[13] => CQ
[14] => HK
[15] => SK
[16] => DK
[17] => CK
[18] => H2
[19] => S2
[20] => D2
[21] => C2
[22] => H3
[23] => S3
[24] => D3
[25] => C3
[26] => H4
[27] => S4
[28] => D4
[29] => C4
[30] => H5
[31] => S5
[32] => D5
[33] => C5
[34] => H6
[35] => S6
[36] => D6
[37] => C6
[38] => H7
[39] => S7
[40] => D7
[41] => C7
[42] => H8
[43] => S8
[44] => D8
[45] => C8
[46] => H9
[47] => S9
[48] => D9
[49] => C9
[50] => H10
[51] => S10
[52] => D10
[53] => C10
)
```
**Edit**
Thanks to @JoKing by suggesting change `explode(" ","H$t S$t D$t C$t")` for `[H.$t,S.$t,D.$t,C.$t]`
[Answer]
# [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), 169 bytes
`␀` represents a literal NUL byte `\x00`.
```
<[.<]␀J J HA HK HQ HJ H01 H9 H8 H7 H6 H5 H4 H3 H2 SA SK SQ SJ S01 S9 S8 S7 S6 S5 S4 S3 S2 DA DK DQ DJ D01 D9 D8 D7 D6 D5 D4 D3 D2 CA CK CQ CJ C01 C9 C8 C7 C6 C5 C4 C3 C2
```
This is the naive solution.
Because this program contains a NUL byte, there's no easy way to use TIO. Run this in the [Python interpreter](https://ideone.com/L2byRe) using
```
data = bytearray(b'<[.<]\x00J J HA HK HQ HJ H01 H9 H8 H7 H6 H5 H4 H3 H2 SA SK SQ SJ S01 S9 S8 S7 S6 S5 S4 S3 S2 DA DK DQ DJ D01 D9 D8 D7 D6 D5 D4 D3 D2 CA CK CQ CJ C01 C9 C8 C7 C6 C5 C4 C3 C2')
```
[Answer]
# Japt, ~~32~~ ~~30~~ 26 bytes
```
'J²¬c"JQKA"¬c9õÄ)ï+"CHSD"q
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=J0qyrGMiSlFLQSKsYzn1xCnvIkNIU0QicSltcQ==&input=LVE=)
```
'J²¬c"JQKA"¬c9õÄ)ï+"CHSD"q
'J :Literal "J"
² :Repeat twice
¬ :Split
c :Concatenate
"JQKA"¬ : Split "JQKA"
c : Concatenate
9õ : Range [1,9]
Ä : Add 1 to each
) : End concatenation
ï : Cartesian Product
"CHSD"q : Split "CHSD"
+ : Join each pair to a string
```
[Answer]
## Batch, 118 bytes
```
@for %%s in (C D H S)do @(for /l %%r in (2,1,10)do @echo %%r%%s)&for %%r in (J Q K A)do @echo %%r%%s
@echo J
@echo J
```
[Answer]
# [J](http://jsoftware.com/), 41 bytes
```
'J';^:2,'HCDS',&.>/~(":&.>2+i.9),;/'AJQK'
```
[Try it online!](https://tio.run/##y/r/PzU5I1/dS906zspIR93D2SVYXUdNz06/TkPJCkgbaWfqWWrqWOurO3oFeqv//w8A "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~67~~ 66 bytes
```
c(paste(rep(c('A',2:10,J<-'J','Q','K'),4),c('S','D','H','C')),J,J)
```
[Try it online!](https://tio.run/##K/pfYfs/WaMgsbgkVaMotUAjWUPdUV3HyMrQQMfLRlfdS11HPRCIvdU1dUw0dYCywUCeCxB7ALGzuqamjpeOl@b/3MSSoswKjYpoQytTo1gdQ2NNropoU2MrU5PY/wA "R – Try It Online")
Only one more byte than [digEmAll's golfier solution](https://codegolf.stackexchange.com/a/166648/80010). Inspired by[Giuseppe's solution](https://codegolf.stackexchange.com/a/158100/80010) to [this related challenge](https://codegolf.stackexchange.com/q/158060/80010) - the same Giuseppe who golfed one byte off by answer!
I'm posting separately since it's a slightly different approach taking advantage of the fact that 4 is not a divisor of 13 and that the output does not need to be in any particular order.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~126~~ ~~137~~ 133 bytes
```
#define S(X)"A"X,"2"X,"3"X,"4"X,"5"X,"6"X,"7"X,"8"X,"9"X,"10"X,"J"X,"Q"X,"K"X,
#define c (char*[54]){S("S")S("D")S("H")S("C")"J","J"}
```
[Try it online!](https://tio.run/##Rc5NS8NAEAbge37Fy5bCblpt1cQP0gpVD6InyaXQ9hA2iR1IN7JJBSn97XEmErw87MzOvIy9@LS2G5Gz1TEvsGjanOrL/WM3youSXIFUr41aqfVUXQs3QiTEwq1wJ9wLD8LVXHwTPoR3JhjiLLTdZz7cxNHOnFKtUmXYl97X3mdleFsSzh25FoeMnP6uKTc4BYC0KOFHWXtowhLzBIQF4ijBZEKGv4Avz3OlVuMGagq7oZ2RndkMDR2oynz1w6WcgjBccYhN/uunoR5Sto5HlpD@ON86Tvyr@0xftEfv@Irg3P0C "C (gcc) – Try It Online")
+11 bytes to be more complete thanks to Jakob.
-4 bytes thanks to Zachary
Mostly abusing of preprocessor to compress the suits. Could probably be out-golfed, but is pretty efficient all things considered.
[Answer]
# Javascript (ES6) 77 74 72 bytes
This is a complete program.
```
`J,J,${[..."A23456789JQK",10].map(c=>[..."SDHC"].map(s=>c+s))}`.split`,`
```
[Answer]
# C (gcc, clang), 138 bytes
```
#define p(c)putchar(c)
int main(){for(char*q,*r="CDHS";*r;r++)for(q="A234567890JQK";*q;q++)(48==*q)&&p(49),p(*q),p(*r),p(32);puts("J J");}
```
Approach is to encode the sequences in character arrays.
**Sample Output**
```
AC AD AH AS 2C 2D 2H 2S 3C 3D 3H 3S 4C 4D 4H 4S 5C 5D 5H 5S 6C 6D 6H 6S 7C 7D 7H 7S 8C 8D 8H 8S 9C 9D 9H 9S 10C 10D 10H 10S JC JD JH JS QC QD QH QS KC KD KH KS J J
```
[Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VoUAjWbOgtCQ5I7EIyOLKzCtRyE3MzNPQrE7LB4oAhbUKdbSKbJWcXTyClay1iqyLtLU1QXKFtkqORsYmpmbmFpYGXoHeQMlC60KgpIaJha2tVqGmmlqBhomlpk6BBpADIotApLGRpjXQwmINJS8FLyVN69r//wE)
[Answer]
# Oracle SQL, 164 bytes
Not a golfing language but...
```
SELECT CASE WHEN LEVEL>52THEN'J'ELSE DECODE(MOD(LEVEL,13),1,'A',11,'J',12,'Q',0,'K',MOD(LEVEL,13))||SUBSTR('HDSC',CEIL(LEVEL/13),1)END FROM DUAL CONNECT BY LEVEL<55
```
[Try it online - SQL Fiddle](http://sqlfiddle.com/#!4/ae2cc8/456)
[Answer]
# [Lua](https://www.lua.org), ~~156~~ ~~127~~ ~~138~~ 129 bytes
```
loadstring'r={"J","J"}for x=1,52 do p=x%4+1r[#r+1]=({"A",2,3,4,5,6,7,8,9,10,"J","Q","K"})[x%13+1]..("SDHC"):sub(p,p)end return r'
```
[Try it online!](https://tio.run/##HY3JCsIwFAB/JTwpTeijmC5ukIPoQfQkHouHdBOhJCFNoVD67TF4mNsMM0zS98IPWrajs1/1ia1Y4A4YWHttySw4lhlpNTFijoqE22pjE/4WdIEzYIY5FljiDvd4wCPyLf7rZ@ABK6vmiOdBT1MKr@vtAuw0TjU1aFinWmI7N1lFbOxNmDvqZD10aaNVIx3tKUNAAoz5Hw "Lua – Try It Online")
Based on Jo King's code.
As he suggested in the comments, my original answer wasn't valid (I'm still learning how code golf works üò¨), and linked a better and valid answer. Then I made it smaller.
---
### Original solution (156 bytes):
```
r={}s="SDHC"c={"J","Q","K"}t=table.insert for x in s:gmatch"."do for y=1,13 do t(r,(y==1 and"A"or y>10 and c[y-10]or y)..x)end end for _=1,2 do t(r, "J")end
```
```
r={} -- initializes the result table
s="SDHC" -- initializes the suits' string, it's better to be a string because we're just looping through it
c={"J","Q","K"} -- initializes some of the special cards
t=table.insert -- stores the table.insert call inside the 't' variable
for x in s:gmatch"."do -- loops through the suits, calling each one 'x'
for y=1,13 do -- 'y' is the current card
t(r,(y==1 and"A"or y>10 and c[y-10]or y)..x) -- adds the card accompanied by the suit to the result ('r') table
-- y==1 and"A"or y>10 and c[y-10]or y means if we're at the first card, it's an "A", else if we're past the 10th card, it's a special card, else, it's the number itself
end
end
for _=1,2 do t(r, "J")end -- loop 2 times, adding a "J" to the result table
```
I just want to say that I'm new to this Code Golf stuff, so if I'm doing something wrong, feel free to tell me.
I know this answer isn't one of the smallest, I just wanted to challenge myself.
If you have suggestions for reducing my code you can say too. :)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~ 43 ~~ 42 bytes
```
{|(|(2..10),|<A J Q K>X~ <S D H C>),|<J J>}
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@7@6RqNGw0hPz9BAU6fGxlHBSyFQwdsuok7BJljBRcFDwdkOJO6l4GVX@784sVIBpE1D8z8A "Perl 6 – Try It Online")
```
{|(|(^9+2),|<A J Q K>X~ <S D H C>),|<J J>}
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@7@6RqNGI85S20hTp8bGUcFLIVDB2y6iTsEmWMFFwUPB2Q4k7qXgZVf7vzixUgGkS0PzPwA "Perl 6 – Try It Online") from [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)
## Expanded:
```
{ # bare block lambda
|( # flatten into outer list
|( # flatten into left-side list for X~
^9 + 2
# 0+2 ..^ 9+2
# 2 ..^ 11
# 2 .. 10
),
| # flatten into left-side list for X~
< A J Q K >
X~ # cross using &infix:« ~ » (string concatenation)
<S D H C>
),
|< J J > # flatten two `J`s into outer list
}
```
[Answer]
# QBasic 4.5, ~~114~~ ~~142~~ 127 bytes
```
dim r$(54)
FOR i=1TO 52
m=i MOD 13
r$(i)=MID$("JQKA2345678910",1+m,1-(m=12))+MID$("CDHS",(i-1)\13+1,1)
NEXT
r$(53)="J
r$(54)="J
```
Release Notes:
* V1.0 Initial deploy
* V1.1 Misread the challenge requirements, so switched to a more expensive array `r$`. All the rest of the code is pretty much the same.
* V1.2 Suggestions from @TaylorScott lead to a complete rewrite saving 15 bytes!
**Sample output**
If we add this snippet to our code, we can see what is put into `r$`:
```
for i = 1 to ubound(r$)
?r$(i)
next
QC
KC
AC
2C
3C
4C
5C
6C
7C
8C
9C
10C
JC
QD
KD
AD
[... snip ...]
6S
7S
8S
9S
10S
JS
J
J
```
**But how?** Well, let me tell you:
```
dim r$(54) ' create a 54-slot array for our results
FOR i=1TO 52 ' Loop through the numbers 1-52 in var i
m=i MOD 13 ' Take i mod 13 to select a value (saved as m)
' , and (not saved) i intdiv 13 to get a suit
r$(i)= ' assigns to slot i in the result array
MID$("JQKA2345678910" ' a substring from the string with all the values
,1+m ' from position 1-13 (13 % 13 = 0, but QBasic strings are 1-based.
' Hence the + 1)
,1-(m=12)) ' taking 1 char by default, and 2 for the Ten
' Note that m=12 evaluates to 0 for 0-11, and to -1 for 12
+ MID$("CDHS",(i-1)\13+1,1) ' and take 1 char from the suits-string
NEXT
r$(53)="J ' Then append 2 jokers
r$(54)="J ' These strings are auto-closed by the QBasic compiler.
```
[Answer]
# Pyth, ~~26~~ 25 bytes
```
+ B\JsM*+tSTc"JQKA"1"CDHS
```
Saved a byte thanks to hakr14.
[Try it here](http://pyth.herokuapp.com/?code=%2B+B%5CJsM%2a%2BtSTc%22JQKA%221%22CDHS&debug=0)
### Explanation
```
+ B\JsM*+tSTc"JQKA"1"CDHS
tST Get the range from 2 to 10...
+ c"JQKA"1 ... plus the list ['J', 'Q', 'K', 'A'].
* "CDHS Take the Cartesian product with the suits.
sM Stick the ranks and suits together.
+ B\J Add the jokers.
```
] |
[Question]
[
At runtime, keep prompting for *a line of input* until the user inputs something (other than an empty newline), i.e. does not just press `Enter` or `OK`. Output or result is neither required nor prohibited.
### Pseudo-code 1
```
myform = new form("GUI")
myform.mytxt = new editfield("")
myform.ok = new button("OK")
repeat
waitfor(myform.ok,"click")
until myform.mytxt.content <> ""
```
### Pseudo-code 2
```
LET TEXT = ""
WHILE TEXT = "" DO
TEXT = PROMPT("")
ENDWHILE
```
### Example 1
Program runs and immediately pops up a form with a single text field and an `OK` button.
User clicks the `OK` button.
Nothing happens.
User pastes "hello world" into the text field and clicks the `OK` button.
Program terminates.
### Example 2
Function is called and immediately displays a blank line and a blinking cursor.
User presses `Enter`.
Cursor moves down one line.
User presses `Enter`.
Cursor moves down one line.
User presses `P``P``C``G``Enter`
Function returns.
[Answer]
# TI-BASIC, 2 bytes
```
:Prompt X
```
TI-BASIC does this automatically. Once input is given, it will quit.
Here is a GIF:
[![enter image description here](https://i.stack.imgur.com/5dI5B.gif)](https://i.stack.imgur.com/5dI5B.gif)
Watch the count on the `enter` key in the Key Press History. Created with **TI-SmartView CE** and [ezgif.com](https://ezgif.com/).
[Answer]
# [Python 3](https://docs.python.org/3/), 18 bytes
```
while''==input():0
```
[Try it online!](https://tio.run/nexus/python3#@1@ekZmTqq5ua5uZV1BaoqFpZfC/oCgzr0QDytdUUFYIzsgvVyhKzU3MzMvMS1cAy@j95@LiSkxK5kpJTQMA "Python 3 – TIO Nexus")
[Answer]
# JavaScript, ~~37~~ ~~22~~ 17 bytes
```
while(!prompt());
```
```
while(!prompt());
```
## Explanation
The `while` keyword starts the `while` loop. In the condition of the loop, `!prompt()` asks for input and checks whether it is given or not. If it isn't given, the body of the loop is executed, which in our case is empty, then the interpreter goes back to the loop condition. The same process happens over and over again until the user gives the input.
[Answer]
# sed, 4
```
/./q
```
Waits for a line of input that has 1 or more characters, then quits.
[Try it online](https://tio.run/nexus/sed#@6@vp1/4/z8XV15@nm5qbkFJJRcA). But it works better on a live shell:
```
sed '/./q'
```
[Answer]
# Java, 55 bytes
```
void f()throws Exception{while(System.in.read()==10);}}
```
If I remember correctly (it's been a while since I've been active on PPCG), my program can just be a function.
This is system specific; it only works on systems where the end-of-line character is a single newline. If the end-of-line character is instead a carriage return, replace the `10` with `13`. On Windows, this doesn't work, as end-of-line on windows is `\r\n`.
This makes use of the fact that I can read directly from `System.in`.
[Answer]
# HTML5, ~~33~~ 22 bytes
```
<form><input required>
```
```
<form><input required>
```
## Explanation
The `required` attribute on the `<input>` causes the browser to inform the user "this field is required"-sort-of-message, if they do not enter a value. However, when they enter a value, the value is sent to the URL of the `action` attribute of the `<form>` (which in our case is the current file itself, since we haven't specified any value explicitly).
This was tested on the latest version of Google Chrome (version 55.0). May work in other browsers and versions.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
W!w
```
[Try it online!](http://pyth.herokuapp.com/?code=W%21w&input=%0A%0A%0Aabc%0Adef&debug=0)
Translated to Python:
```
while Pnot(input()):
pass
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ɠṆ¿
```
Not much to look at on TIO, I'm afraid.
[Try it online!](https://tio.run/nexus/jelly#@39ywcOdbYf2///PxcWVmJTMlZKaBgA "Jelly – TIO Nexus")
### How it works
This is a niladic program, meaning that it takes no input arguments. The implicit argument and return value are both **0** in this case.
`¿` (while) is a quick that pops two links from the link stack: a condition (`Ṇ`) and a body.
`Ṇ` is a monadic atom: flat logical NOT. If the previous return value is falsy (here, **0** or an empty string), it returns **1** and the body is called.
`ɠ` is a niladic atom; it reads a raw line from STDIN and returns the result.
Once `ɠ` reads a non-empty line, `Ṇ` returns **0** and we break out of the loop.
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 26 bytes
```
+[>,----------[[-]<[-]>]<]
```
[Try it online!](https://tio.run/nexus/brainfuck#@68dbaejCwfR0bqxNkBsF2sT@/8/FxdXYlIyV0pqGgA "brainfuck – TIO Nexus")
[Answer]
# Perl 5, 8+1 (-p or -n flag) bytes
```
/./&&die
```
Takes input from stdin and dies as soon as the regex matches anything except a newline.
[Answer]
# C, ~~52 bytes~~, ~~33 bytes~~, 29 bytes
-19 bytes thanks to Justin
-4 bytes thanks to Christoph
```
main(){while(getchar()==10);}
```
10 is equal to '\n' - In case this isn't obvious.
[Answer]
## Bash, 51 bytes (39 without "#!/bin/bash")
It's my first time participating in PPCG, so dont be to rude ;D
```
#!/bin/bash
read a
while [ -z "$a" ]
do
read a
done
```
[Answer]
# R, ~~27~~ ~~24~~ ~~23~~ 22 bytes
```
while(!sum(scan()^0))t
```
Takes input from stdin, and repeat as long as input is of length 0. Cut off some bytes due to Jarko Dubbeldam and MickyT. Replaced the `{}` with `t` to save another byte.
[Answer]
# [Java](http://openjdk.java.net/), ~~128~~ 126 bytes
2 bytes thanks to Kevin Cruijssen.
```
import java.util.*;class a{public static void main(String[]a){for(Scanner s=new Scanner(System.in);s.nextLine().isEmpty(););}}
```
[Try it online!](https://tio.run/nexus/java-openjdk#LcexDsIgEADQna9gBAd@gDi6uTEahyul5gwcDXdtbZp@Ozo4vbyOZa5N9BtWcItgdhcfMzBrOOZlyBg1C8iPteKoCyCZIA3p9XiCPabaTIhAlJrmK6VN/2fCzpKKQ7KeHaWP3JGSsQ75VmbZjfXWn2fvSikYohrT9AU "Java (OpenJDK 8) – TIO Nexus")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 8 11 bytes
```
NF{exit}
```
Wait for input. If the number of fields in input is more than 0, exit.
**EDIT:**
I've just realized that this doesn't work for input containing whitespace characters only. IFS needs to be set to empty string using `-F ""` command line option. Therefore +3 bytes.
[Try it online!](https://tio.run/nexus/awk#@@/nVp1akVlS@/8/F5fCv/yCksz8vOL/um4KSkoA "AWK – TIO Nexus")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 66 bytes
```
class C{static void Main(){for(;System.Console.ReadLine()!="";);}}
```
[Try it online!](https://tio.run/nexus/cs-core#@5@ck1hcrOBcXVySWJKZrFCWn5mi4JuYmaehWZ2WX6RhHVxZXJKaq@ecn1ecn5OqF5SamOKTmZeqoaloq6RkrWldW/v/PwA "C# (.NET Core) – TIO Nexus")
-6 bytes thanks to raznagul.
[Answer]
## QBasic 4.5, 15 bytes
```
INPUT a$:IF a$=""THEN RUN
```
Asks for input, then checks if any was given. If not, `RUN` restarts the program.
[Answer]
# Ruby, 13 bytes
```
gets until/./
```
I wish `gets` took a Regexp argument.
[Answer]
# PHP, 18 bytes
```
while(!readline())
```
[Answer]
# SpecBAS - 34 bytes
```
1 DO : INPUT a$: LOOP UNTIL a$<>""
```
Just loops until non-empty string is entered.
[Answer]
# Perl, 15 12 bytes (11 + -n flag)
-3 bytes thanks to manatwork
```
1/0if$/ne$_
```
Explanation:
The -n flag places a read loop around the program, turning it into:
```
LINE:
while (<>) {
1/0 if $/ ne $_ # Spaces added for clarity.
}
```
Where "<>" reads a line from stdin to the variable $\_. If the line contained more than the ending newline (ne is string inequality, $/ is the input record separator which defaults to newline), a division by zero is performed which causes the program to output an error message and terminate.
[Answer]
# Mathematica, ~~26~~ 20 bytes
```
For[,Input[]==Null,]
```
[Answer]
## Haskell, ~~19~~ 17 bytes
```
f=do""<-getLine;f
```
Defines a function `f` that if it reads the empty line calls itself again. When reading a non-empty line an exception is raised and the recursion is stopped.
Edit: @Laikoni replaced the parameter with a pattern match and saved 2 bytes. Thanks!
[Answer]
# [Aceto](https://github.com/L3viathan/Aceto), ~~9~~ ~~5~~ 4 bytes
`r`ead a value, negate it (`!`; implicitly casting to a boolean), and mirror horizontally if the value is truthy (`|`).
```
!
r|
```
[Answer]
# Java, ~~66~~ ~~64~~ 60 bytes
```
int a(){return!System.console().readLine().isEmpty()?0:a();}
```
My first Java answer, would love some tips!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 4 bytes
```
W¬Sω
```
## Explanation
```
W While
¬S Logical not of string input
ω Print ""
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
[IõÊ#
```
Explanation:
```
[ Start infinite loop
I One line of input
Ê Not equal to
õ Empty string
# Break if true
```
[Try it online!](https://tio.run/nexus/05ab1e#@x/teXjr4S7l//@5uLgSk5K5UlLTAA "05AB1E – TIO Nexus")
[Answer]
# PowerShell, 20 Bytes
```
for(;!(read-host)){}
```
runs a for loop,
`read-host` prompts for input
if read-host returns nothing it evals to false, so we invert that `!(...)` and use that as the loop end check.
much shorter than any `do{$a=read-host}while($a-eq"")` type solution involving variables.
[Answer]
# Swift, 22 bytes
```
while readLine()==""{}
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 5 bytes
```
{l!}g
```
[Try it online!](https://tio.run/nexus/cjam#@1@do1ib/v8/FwgkJiUDAA "CJam – TIO Nexus")
(TIO doesn't really show the proper behaviour)
**Explanation**
```
{ e# Do:
l e# Read next line of input
! e# Boolean negate (empty strings are falsy)
}g e# Pop the top of stack, if truthy, repeat.
```
] |
[Question]
[
Given three sidelengths of a triangle, evaluate its aspect ratio *AR* given the following formula:
[![enter image description here](https://i.stack.imgur.com/NUubd.png)](https://i.stack.imgur.com/NUubd.png)
where
[![enter image description here](https://i.stack.imgur.com/ZkGvs.png)](https://i.stack.imgur.com/ZkGvs.png)
The closer to equilaterality a triangle is, the closer to `1` its aspect ratio is. The aspect ratio is bigger or equal to `1` for valid triangles.
### Inputs
The input is three real positive numbers which can be encapsulated in a list or anything similar if need be.
Your program must output the same value no matter what the order in which the three sidelengths are inputted is.
Those three numbers will always be valid sidelengths of a triangle (degenerate triangles like one with sidelengths `1`, `1` and `2` will not be given as input). You need not worry about floating point inaccuracies when values become extremely close to a degenerate triangle (e.g. it is acceptable that your program would error `division by 0` for input `[1, 1, 1.9999999999999999]`).
The input can be given through `STDIN`, as a function argument, or anything similar.
### Outputs
The output is a real number bigger or equal to `1` with the standard accuracy that is acceptable in your language.
The output may be printed to `STDOUT`, returned from a function, or anything similar.
### Test cases
```
Inputs Output
1 1 1 1
3 4 5 1.25
42 42 3.14 ≈ 6.9476
14 6 12 1.575
6 12 14 1.575
0.5 0.6 0.7 ≈ 1.09375
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 7 bytes
```
SH_÷@HP
```
[Try it online!](http://jelly.tryitonline.net/#code=U0hfw7dASFA&input=&args=MC41LDAuNiwwLjc)
## Explanation
[![enter image description here](https://i.stack.imgur.com/zeShr.png)](https://i.stack.imgur.com/zeShr.png)
Let’s read this chain:
* The implicit argument is a list `[a, b, c]`.
* First we read `S`. This takes the sum: `a + b + c`.
* Then, we read `H`. This halves it: `(a + b + c)/2`. (This is `s`.)
* Then, we read a dyad `_` (subtract), followed by another dyad. This is a **hook**: it lacks a right argument, so it receives the argument to this chain, `[a, b, c]`, giving us `[s-a, s-b, s-c]`. (This is the [**fifth chain pattern in the table here**](https://github.com/DennisMitchell/jelly/wiki/Tutorial#how-do-we-walk-down-the-chain).)
* Then, we read the dyad-monad pair `÷@H`. This is a **fork**: `÷@` is division with the arguments flipped, and `H` is halve, so our working value gets `H`alf the argument to this chain `÷`’d by it. This vectorizes; we’re left with `[(a/2)/(s-a), (b/2)/(s-b), (c/2)/(s-c)]`. (This is the [**second chain pattern in the table here**](https://github.com/DennisMitchell/jelly/wiki/Tutorial#how-do-we-walk-down-the-chain).)
* Finally, we take the product with `P`, getting us `abc/(8(s-a)(s-b)(s-c))`.
[**View a tree-like graph of how the links fit together.**](https://i.stack.imgur.com/8NcIq.png)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes
This answer is based on [Emigna's 05AB1E answer](https://codegolf.stackexchange.com/a/101258/47581). Many thanks to Dennis and Lynn for their help in figuring this answer out. Golfing suggestions welcome! [Try it online!](http://jelly.tryitonline.net/#code=U1_huKTigbjDt1A&input=&args=Myw0LDU)
```
S_Ḥ⁸÷P
```
**Ungolfing**
```
Implicit argument [a, b, c].
S Take the sum, a+b+c or 2*s
Ḥ Take the double, [2*a, 2*b, 2*c].
_ Vectorized subtract, giving us [2*(s-a), 2*(s-b), 2*(s-c)].
⁸÷ Vectorized divide the initial left argument, the input [a, b, c],
by [2*(s-a), 2*(s-b), 2*(s-c)].
P Take the product giving us the aspect ratio, abc/8(s-a)(s-b)(s-c).
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes
```
S÷_2Pİ
```
[Try it online!](http://jelly.tryitonline.net/#code=U8O3XzJQxLA&input=&args=MC41LCAwLjYsIDAuNw)
### How it works
```
S÷_2Pİ Main link. Argument: [a, b, c]
S Sum; compute 2s := a + b + c.
÷ Divide; yield [2s ÷ a, 2s ÷ b, 2s ÷ c].
_2 Subtract 2; yield [2s ÷ a - 2, 2s ÷ b - 2, 2s ÷ c - 2].
P Product; yield (2s ÷ a - 2)(2s ÷ b - 2)(2s ÷ c - 2).
İ Invert; yield 1 ÷ (2s ÷ a - 2)(2s ÷ b - 2)(2s ÷ c - 2).
```
[Answer]
# JavaScript, 38 bytes
This is a ([curried](http://meta.codegolf.stackexchange.com/a/8427/24877)) lambda:
```
a=>b=>c=>a*b*c/(b+c-a)/(a+c-b)/(a+b-c)
```
(If you assign it to a variable `f` you'd need to call it like `f(3)(4)(5)`)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 7 bytes
05AB1E uses [CP-1252](http://www.cp1252.com) encoding.
```
O¹·-¹/P
```
[Try it online!](http://05ab1e.tryitonline.net/#code=T8K5wrctwrkvUA&input=WzQyLDQyLDMuMTRd)
**Explanation**
```
O # sum input
¹ # push input again
· # multiply by 2
- # subtract from sum
¹/ # divide by input
P # product
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~8~~ 7 bytes
```
tsGE-/p
```
[Try it online!](http://matl.tryitonline.net/#code=dHNHRS0vcA&input=WzE0IDYgMTJd)
### Explanation
Let's use input `[3 4 5]` as an example
```
t % Take input implicitly. Duplicate
% STACK: [3 4 5], [3 4 5]
s % Sum of array
% STACK: [3 4 5], 12
G % Push input again
% STACK: [3 4 5], 12, [3 4 5]
E % Multiply by 2, element-wise
% STACK: [3 4 5], 12, [6 8 10]
- % Subtract, element-wise
% STACK: [3 4 5], [6 4 2]
/ % Divide, element-wise
% STACK: [0.5 1 2.5]
p % Product of array. Implicitly display
% STACK: 1.25
```
[Answer]
## R, 34 29 bytes
```
x=scan();prod(x/(sum(x)-2*x))
```
Reads input from stdin and store as the R-vector `x`. Then make use of R's vectorization to form the denominator.
[Answer]
# Haskell, 36 bytes
This defines the function `#` which takes three arguments.
```
(a#b)c=a*b*c/(b+c-a)/(a+c-b)/(a+b-c)
```
You have to call it as follows: `(3#4)5`
A little bit longer but perhaps more golfable:
```
p=product
f v=p v/p((sum v-).(2*)<$>v)
```
[Answer]
# MATLAB, ~~64 38~~ 25 bytes
This is an anyonmous function that implements the formula as provided:
```
@(v)prod(v./(sum(v)-2*v))
```
It assumes the input to be a list of three values e.g. `[3,4,5]`. This example is used in following explanation:
```
sum(v) = 3+4+5 = 12
sum(v)-2*v = 12 - 2*[3,4,5] = 12 - [6,8,10] = [6,4,2]
v./(sum(v)-2*v)) = [3,4,5] ./ [6,4,2] = [0.5,1,2.5]
prod(v./(sum(v)-2*v)) = 0.5 * 1 * 2.5 = 1.25
```
[Answer]
## Mathematica, 20 bytes
```
1##&@@(#/(Tr@#-2#))&
```
Takes input as a list of three values, which is referred to as `#` inside the function. `Tr@` is the shortest way to sum a list (to get `2s`) and `1##&@@(...)` multiplies the three factors `i/(2s-2i)` for `i` in `a, b, c`.
If the inputs are integers or rational numbers, you'll get an exact result.
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
lambda a,b,c:a*b*c/(b+c-a)/(a+c-b)/(a+b-c)
```
[Try It Online!](https://tio.run/nexus/python3#PU3LCsMwDLvvK3SMOzd9pR0U9ie72BmBwtaVsv/PnBxmLEtCAifc8cgveetTIKwcV2m0iZ3Ta2yFOifGWlnbSDl9TjhhKCMSth1uYJQlhpsYgTEXGUbThskPofjBgsVqYzFVGGrS@5nR@6WcG60X2Bzntn9d@j@i/AM "Python 3 – TIO Nexus")
[Answer]
# Minecraft 1.8, 1607 bytes + 85 blocks = 1692 blytes
**Warning: *Not* golfed. Golfed will take up to 1*/*3 less blytes.**
Here is a commented screenshot:
[![enter image description here](https://i.stack.imgur.com/mZDQN.png)](https://i.stack.imgur.com/mZDQN.png)
* The inputs are `a`, `b`, and `c`,and the output is `fin`
* `fin`, and all other variables in Minecraft are integers, so the standard Minecraft accuracy is 0 decimal points
* The green border: the command blocks on the left will activate after the ones on the right, which are just variable initializations.
* The lever (grey-brown rectangle in the down right) is the contraption trigger
* **It takes up so much because of the way Minecraft handles variables**. A very simplified overview:
+ `/scoreboard objectives add name dummy` creates a new variable named "`name`"
+ `/scoreboard players set @p name number` sets the variable `name` to `number`. Number must be a real number, not a variable.
+ `/scoreboard players operation @p name += @p name2` increments `name` by `name2`. `name2` must be a variable, not a number.
- `-=`, `/=`, `*=`, `=` and more can be used instead `+=` to decrement, multiply, divide, etc.
* I'm not going to post all the 43 commands here. It would help golfing this, but would also help drive me crazy copypasting
* *If 1.9 command blocks would be used, the solution would (at least) use 42 blocks less. If one-letter variables would be used, almost 200 bytes would be saved.*
[Answer]
# OCaml, 51 bytes
```
fun a b c->a*.b*.c/.(b+.c-.a)/.(a+.c-.b)/.(a+.b-.c)
```
Yay, separate operators for floats...
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 48 bytes
```
@@@prod[#0#1#2/1- +#1#0#2/1- +#2#0#1/1- +#2#1#0]
```
RIP
Usage:
```
(((@@@prod[#0#1#2/1* * - +#1#0#2- +#2#0#1- +#2#1#0])3)4)5
```
# Explanation
Function calls are costly in Wonder when compared to infix operators in other languages. Because of this, I contained all the terms in an array and got the product of the result instead of multiplying every single term. The code would be equivalent to something like:
```
(a,b,c)=>product([a,b,c,1/(b+c-a),1/(a+c-b),1/(a+b-c)])
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), ~~10~~ 8 bytes
This answer is based on [Dennis's excellent Jelly answer](https://codegolf.stackexchange.com/a/101266/47581). Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=O86j4pmAL-KZgsKsz4DDrA&input=WzMsNCw1XQ)
```
;Σ♀/♂¬πì
```
**Ungolfing**
```
Implicit input [a, b, c].
; Duplicate [a, b, c].
Σ sum() to get twice the semiperimeter, 2*s.
♀/ Vectorized divide 2*s by [a, b, c] to get [2*s/a, 2*s/b, 2*s/c].
♂¬ Vectorized subtract 2 to get [2*s/a-2, 2*s/b-2, 2*s/c-2].
π Get the product of the above to get 8*(s/a-1)*(s/b-1)*(s/c-1).
This is the same as 8(s-a)(s-b)(s-c)/abc.
ì Invert to get the aspect ratio, abc/8(s-a)(s-b)(s-c).
Implicit return.
```
[Answer]
# Java, 38 bytes
```
(a,b,c)->a*b*c/(b+c-a)/(a-b+c)/(a+b-c)
```
## Testing and ungolfed
```
public class Pcg101234 {
interface F {
double f(double a, double b, double c);
}
public static void main(String[] args) {
F f = (a,b,c)->a*b*c/(b+c-a)/(a-b+c)/(a+b-c);
System.out.println(f.f(1,1,1));
System.out.println(f.f(3,4,5));
System.out.println(f.f(42,42,3.14));
System.out.println(f.f(14,6,12));
System.out.println(f.f(6,12,14));
System.out.println(f.f(0.5,0.6,0.7));
}
}
```
[Test it!](http://ideone.com/xNzffQ)
## Output
```
1.0
1.25
6.947606226693615
1.575
1.575
1.09375
```
[Answer]
## [Jellyfish](http://github.com/iatorm/jellyfish), ~~17~~ 16 bytes
*Thanks to Zgarb for saving 1 byte.*
```
p%/*-)/+i
2%
```
[Try it online!](http://jellyfish.tryitonline.net/#code=cCUvKi0pLytpCiAgICAyJQ&input=WzAuNSAwLjYgMC43XQ)
### Explanation
This is based on the same reciprocal formula as [Dennis's answer](https://codegolf.stackexchange.com/a/101266/8478).
In more traditional functional notation, the above program reads as follows:
```
print(
1 / fold(
multiply,
fold(add, i) / i - 2
)
)
```
Where `i` is the input list. Note that `fold(multiply, ...)` just computes the product and `fold(add, ...)` the sum, so we can further simplify this to:
```
print(1 / product(sum(i) / i - 2))
```
The `sum(i) / i` is implemented via the hook `)/+` which defines a new unary function to do both steps at once.
[Answer]
# [Dyalog APL](https://dyalog.com/), ~~10~~ 9 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
×/⊢÷+/-+⍨
```
This is an anonymous [function train](http://help.dyalog.com/15.0/Content/Language/Introduction/Trains.htm) (an atop of a fork of a fork of a fork), meaning that every sub-function is applied to the argument, inside the following structure:
```
┌─┴─┐
×/ ┌─┼───┐
⊢ ÷ ┌─┼──┐
+/ - +⍨
```
[TryAPL online!](http://tryapl.org/?a=AR%u2190%D7/%u22A2%F7+/-+%u2368%20%u22C4%20AR%A8%281%201%201%29%283%204%205%29%2842%2042%203.14%29%2814%206%2012%29%286%2012%2014%29%280.5%200.6%200.7%29&run)
`×/` the product of
`⊢` the arguments
`÷` divided by
`+/` the sum of the arguments
`-` minus
`+⍨` the arguments doubled (lit. added to themselves)
[Mathematical background.](https://www.sharcnet.ca/Software/Ansys/16.2.3/en-us/help/wb_msh/msh_aspect_triangle.html)
ngn shaved a byte.
[Answer]
# [2sable](http://github.com/Adriandmen/2sable), 6 bytes
A port of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/101266/34388).
```
Os/ÍPz
```
Uses the **CP-1252** encoding. [Try it online!](http://2sable.tryitonline.net/#code=T3Mvw41Qeg&input=WzE0LCA2LCAxMl0)
[Answer]
# dc, 49 bytes
```
5k?dsa?dsb?dsc++2/sslalblc**lsla-lslb-lslc-8***/p
```
A direct implementation of the formula given. Prompts for the three inputs upon invocation on three separate lines and outputs a floating-point value with 5 digits after the decimal point to the next line.
## Explanation
```
5k # Set the output precision to 5 digits after the decimal
?dsa # Prompt for first input value on first line, duplicate it, and then store it in register `a`
?dsb # Prompt for second input, duplicate it, and store it in register `b`
?dsc # Prompt for third input, duplicate it, and store it in register `c`
++2/ss # Sum up the 3 values on the main stack, then divide sum by 2 and store the result in register `s`
lalblc** # Copy all three values from registers `a`,`b`,`c` onto the main stack, find their product, and push result to top of main stack
lsla- # Copy value from register `s` onto main stack, subtract register `a`'s value from it, and push result to main stack
lslb- # Copy value from register `s` onto main stack, subtract register `b`'s value from it, and push result to main stack
lslc- # Copy value from register `s` onto main stack, subtract register `c`'s value from it, and push result to main stack
8*** # Find the product of the top three values and 8 and then push the result to main stack
/p # Divide the second to top value (a*b*c) by the top of stack value (8*(s-a)*(s-b)*(s-c)), push the result to the main stack, and then output the result to STDOUT
```
[Answer]
# TI-Basic, 11 bytes
Input should be in the form of a list, like `{A B C}`.
```
prod(Ans)/prod(sum(Ans)-2Ans
```
Maybe this visual will help (remember that `2s = a+b+c`):
```
abc abc abc prod(Ans)
---------------- = --------------------- = ------------------- = -------------------
8(s-a)(s-b)(s-c) (2s-2a)(2s-2b)(2s-2c) (a+b+c)(1-2{a,b,c}) prod(sum(Ans)-2Ans)
```
[Answer]
# [Perl 6](https://perl6.org), 44 bytes
```
->\a,\b,\c{a*b*c/(b+c -a)/(a+c -b)/(a+b -c)}
```
[Answer]
# Python, 55 bytes
```
def f(x,y,z):s=x+y+z;return 1/((s/x-2)*(s/y-2)*(s/z-2))
```
[Credit to Dennis](/a/101266/41024). I just ported. In Python, a much-neglected language.
[Answer]
# Forth, 83 bytes
Assumes the floating point parameters start on the floating point stack. Leaves the result on the floating point stack. Using the stack for params/returning is the standard for Forth.
```
: p 3 fpick ;
: T p p p ;
: f 0 s>f T f- f+ f- T f+ f- f* T f- f- f* 1/f f* f* f* ;
```
[**Try it online**](http://ideone.com/lhvmGq) - *contains all test cases*
Uses the formula `a*b*c * 1/ ( -(a+b-c) * -(b+c-a) * (a+c-b) )`. Pretty much the entire program is using only the floating point stack. The exception is the `3` in `3 fpick`. This program requires an interpreter that supports `fpick` (Ideone works, repl.it doesn't).
**Explanation:** *slightly less golfed*
```
\ 3 fpick takes the 3rd element (0-indexed) and pushes a copy
\ Used to copy parameters on the stack over another number 'x' ( a b c x -> a b c x a b c )
: f3p 3 fpick 3 fpick 3 fpick ;
: f \ define a function f
0 s>f f3p f- f+ f- \ push a zero, copy params, compute 0-(a+b-c)
\ the zero allows me to copy (I need an 'x' to jump over)
f3p f+ f- f* \ copy params and compute -(b+c-a), multiply by previous result
\ the negatives miraculously cancel
f3p f- f- f* \ copy and compute (a+c-b), multiply by previous result
1/f f* f* f* ; \ take the reciprocal and multiply by a*b*c
\ the result is left on the floating point stack
```
[Answer]
# [ised](http://ised.sourceforge.net/): 19 bytes
```
@*$1/@*{@+$1-2.*$1}
```
Call it as `ised --l 'inputfile.txt' '@*$1/@*{@+$1-2.*$1}'`
where `inputfile.txt` can be a file with space separated array, or `-` to receive from pipe/stdin.
Unicode version (same bytecount but 3 chars less):
```
Π$1/Π{Σ$1-2.*$1}
```
Unfortunately, `ised` wastes a lot of chars for its input argument syntax.
[Answer]
# vba, 76
```
Function r(a,b,c)
s=(a+b+c)/2:r=(a*b*c)/(8*(s-a)*(s-b)*(s-c))
End Function
```
Call with
>
> ?r(3,4,5)
>
>
>
or in excel with
>
> =r(5,12,13)
>
>
>
[Answer]
## C#, 82 bytes
```
void ar(double a,double b,double c)=>Console.Write(a*b*c/(b+c-a)/(a+c-b)/(a+b-c));
```
Usage:
```
ar(42, 42, 3.14);
```
[Answer]
# Pyke, 12 bytes
```
1QFQsR/tt)B/
```
[Try it here!](//pyke.catbus.co.uk?code=1QFQsR%2Ftt%29B%2F&input=%5B.5%2C.6%2C.7%5D)
Well, BlueEyedBeast, you had your chance. I used a [good algorithm](/a/101266/41024) here.
[Answer]
# k, 19 bytes
```
{(*/x)%8*/-x-+/x%2}
```
Evaluates right to left - Divide the list x by 2, sum the result and subtract it from original x. Neg the answer and get the product of the result and 8. The result is the denominator, the numerator is the product of the list.
[Answer]
# Lua, 45 bytes
```
a,b,c=...print(a*b*c/(b+c-a)/(a+c-b)/(a+b-c))
```
Heavily based on the JavaScript answer.
] |
[Question]
[
My friend made a lisp translator the other day, that is to say it took a string and converted s=>th and S=>Th. It was quite long and I thought that it could be golfed.
So the task is to make a program/function that takes an input string, translates it in to lisp and outputs the string
**Test case**
```
Sam and Sally like Sheep Tham and Thally like Thheep
Sally likes sausages Thally liketh thauthageth
Sally sells seashells Thally thellth theathhellth
```
Note that it doesn't matter that h gets repeated all the time
This is code golf so shortest answer wins
[Answer]
## Common Lithp, 62
```
(map()(lambda(u)(princ(case u(#\s"th")(#\S"Th")(t u))))(read))
```
First, `(read)` the input (it should be a string).
Strings in CL are sequences so we use `map` to iterate on each character. The first argument to `map` represents the type of the result (e.g. I could build a list from a vector). When it is `nil`, a.k.a. `()`, results are discarded. The function that is mapped to the input simply `princ` (print non-readably) each character, except the ones that should be replaced.
[Answer]
# Retina, 9 bytes
```
S
Th
s
th
```
[Try it online!](http://retina.tryitonline.net/#code=UwpUaApzCnRo&input=U2FtIGFuZCBTYWxseSBsaWtlIFNoZWVwClNhbGx5IGxpa2VzIHNhdXNhZ2VzClNhbGx5IHNlbGxzIHNlYXNoZWxscwpTaGUgc2VsbHMgc2VhIHNoZWxscyBvbiB0aGUgc2VhIHNob3Jl)
The obvious answer.
[Answer]
# JavaThcript ETh6, 38 bytes
At first I went with the obvious solution
```
a=>a.replace(/s/g,'th').replace(/S/g,'Th')
```
But I golfed it down 4 bytes
```
a=>a.replace(/s/gi,b=>b>'r'?'th':'Th')
```
This makes use of the regex `i` flag, which searches for case-insensitive patterns. The good thing about Javascript is that you can specify an anonymous function to handle (regex) replacing.
Try it here
```
f=
a=>a.replace(/s/gi,b=>b>'r'?'th':'Th')
s.innerHTML = [
'abScdsefSghsij',
'Sam and Sally like Sheep',
'Sally likes sausages',
'Sally sells seashells'
].map(c=>c + ' => ' + f(c)).join`<br>`
```
```
<pre id=s>
```
[Answer]
### GNU Sed - 17
```
s/S/Th/g;s/s/th/g
```
The obvious answer.
```
$ sed -e "s/S/Th/g;s/s/th/g"
Sam and Sally like Sheep
Tham and Thally like Thheep
Sally likes sausages
Thally liketh thauthageth
Sally sells seashells
Thally thellth theathhellth
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“Ss”,“Th“th”y
```
Thhowing off Jelly'th thhiny new tranthlate atom. [Try it online!](http://jelly.tryitonline.net/#code=4oCcU3PigJ0s4oCcVGjigJx0aOKAnXk&input=&args=J1NhbGx5IGxpa2VzIHNhdXNhZ2VzJw)
[Answer]
# Python 3 - 40 byteth
First golfing!
```
lambda s:s.translate({115:'th',83:'Th'})
```
It uses the `str` module's [translate](https://docs.python.org/3/library/stdtypes.html?highlight=translate#str.translate) method which accepts a translation table. The translation table is a simple `dict` with keycode as keys and the `str` in place of it as value.
[Answer]
# JavaThcript ETh6, 43 byteth
```
s=>s.replace(/s/gi,m=>({s:'th',S:'Th'})[m])
```
## Tetht Thuite:
```
th=s=>s.replace(/s/gi,m=>({s:'th',S:'Th'})[m])
console.log(th('Sam and Sally like Sheep'));
console.log(th('Sally likes sausages'));
console.log(th('Sally sells seashells'));
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 11 byteth
```
Ís/th
ÍS/Th
```
[Try it online!](http://v.tryitonline.net/#code=w41zL3RoCsONUy9UaA&input=U2FtIGFuZCBTYWxseSBsaWtlIFNoZWVwICAgICAgICAKU2FsbHkgbGlrZXMgc2F1c2FnZXMgICAgICAgICAgICAKU2FsbHkgc2VsbHMgc2Vhc2hlbGxz)
V ith a language I made. It'th not finithed, but it'th really good at regekth.
[Answer]
## 05AB1E, ~~14~~ 12 bytes
```
's„th:'S„Th:
```
The straight forward answer.
[Try it online](http://05ab1e.tryitonline.net/#code=J3PigJ50aDonU-KAnlRoOg&input=U2FsbHkgbGlrZXMgc2F1c2FnZXM)
Saved 2 bytes thanks to @Adnan
[Answer]
# C, 50 bytes
```
s(c){c=getchar();c+=c-83&95?0:'h\1';s(printf(&c));}
```
Replace `\1` with an actual `\x01` byte.
jimmy23013 saved a byte, and then I saved two more using his approach! Thanks.
[Answer]
# Java, 71 65 bytes
```
String t(String s){return s.replace("S","Th").replace("s","th");}
```
First attempt at golfing, so why not with Java.
[Answer]
# GNU AWK, 31 bytes
Just using `gsub` function to translate lower or upper S via regex and print it afterwards. Can work with files, or with `stdin` as in this case
```
$ awk '{gsub(/s/,"th");gsub(/S/,"Th")}1' <<< "This is Sparta"
Thith ith Thparta
```
[Answer]
# TI-Basic, 126 bytes
```
Input Str1
inString(Str1,"s
While Ans
sub(Str1,1,Ans-1)+"th"+sub(Str1,Ans+1,length(Str1)-Ans->Str1
inString(Str1,"s
End
inString(Str1,"S
While Ans
sub(Str1,1,Ans-1)+"Th"+sub(Str1,Ans+1,length(Str1)-Ans->Str1
inString(Str1,"S
End
Str1
```
[Answer]
# Java, 101 byteth
```
interface a{static void main(String[]A){System.out.print(A[0].replace("S","Th").replace("s","th"));}}
```
Note that this is a complete program unlike [the previous Java answer](https://codegolf.stackexchange.com/a/83146/53917).
Bonus (has to be fed to the C preprocessor THEE preprothethor first):
```
#define interfaith interface
#define thtatic static
#define Thtring String
#define Thythtem System
#define replaith(x,y) replace(x,y)
interfaith a{thtatic void main(Thtring[]A){Thythtem.out.print(A[0].replaith("S","Th").replaith("s","th"));}}
```
[Answer]
# 35 Byteth of Julia:
```
s->replace(s,r"s"i,s->"$(s[1]+1)h")
```
[Try it online!](http://julia.tryitonline.net/#code=Zj1zLT5yZXBsYWNlKHMsciJzImkscy0-IiQoc1sxXSsxKWgiKQoKZm9yIHRlc3QgaW4gWygiU2FtIGFuZCBTYWxseSBsaWtlIFNoZWVwIiwgIlRoYW0gYW5kIFRoYWxseSBsaWtlIFRoaGVlcCIpLAogICAgICAgICAgICAgKCJTYWxseSBsaWtlcyBzYXVzYWdlcyIsICAgICAiVGhhbGx5IGxpa2V0aCB0aGF1dGhhZ2V0aCIpLAogICAgICAgICAgICAgKCJTYWxseSBzZWxscyBzZWFzaGVsbHMiLCAgICAiVGhhbGx5IHRoZWxsdGggdGhlYXRoaGVsbHRoIildCiAgICBwcmludGxuKGYodGVzdFsxXSkgPT0gdGVzdFsyXSkKZW5k&input=) (includes all test cases)
[Answer]
# C (GCC), 62 byteth
-10 bytes thanks to @ceilingcat; forgot to use the function argument as the iterator.
-1 more byte thanks to @l4m2 and his very smart recursion trick.
```
l(char*s){*s&&l(s+!!putchar(*s&31^19?*s:104+!putchar(*s+1)));}
```
[Try It Online!](https://tio.run/##S9ZNT07@/z9HIzkjsUirWLNaq1hNLUejWFtRsaC0BCSoARQxNowztLTXKrYyNDDRRpLQNtTU1LSu/Z@bmJmnoclVzaUABTkaSsGJpcWJ6akKOZnFBQrFQJCXmphdCWElZqcqaVpz1f4HAA)
Explanation:
```
l(char*s)
{
// If at end of string, do nothing.
*s&&
// Else, apply this function to the next character in s ...
l(s+
// ... but first, print the current character. If the first
// five bits of *s equal 19 (which they do for 's' and
// 'S'), print *s+1 (that is, 't' for 's' and 'T' for 'S')
// before printing character code 104, which is 'h'.
// If the first five bits aren't 19, just print *s.
!!putchar(*s&31^19?*s:104+!putchar(*s+1)));}
```
Alternative 62-byte version, made by l4m2:
```
l(char*s){*s&&l(s+!!printf(*s&31^19?"%c":*s%5?"Th":"th",*s));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9HIzkjsUirWLNaq1hNLUejWFtRsaAoM68kTQMoYGwYZ2hpr6SarGSlVaxqaq8UkqFkpVSSoaQD1KFpXfs/NzEzT0OTq5pLAQpyNJSCE0uLE9NTFXIyiwsUioEgLzUxuxLCSsxOVdK05qr9DwA)
I'm too lazy to explain that one fully, but it's quite similar to the last one except it uses two nested conditional statements to figure out if it should print the current character, `Th` or `th`. The new `*s%5` check is used to figure out if `*s` is `'S'` or `'s'` (knowing that it's one of those), since the ASCII code of `s` is divisible by 5 but `'S'` is not.
[Answer]
## CJam, 15 bytes
```
q"sS""thTh"2/er
```
[Test it here.](http://cjam.aditsu.net/#code=q%22sS%22%22thTh%222%2Fer&input=Sam%20and%20Sally%20like%20Sheep%0ASally%20likes%20sausages%0ASally%20sells%20seashells)
### Explanation
```
q e# Read input.
"sS" e# Push string.
"thTh" e# Push string.
2/ e# Split into pairs, i.e. ["th" "Th"].
er e# Transliteration, replaces 's' with 'th' and 'S' with 'Th'.
```
[Answer]
## Python3 - 46 bytes
```
lambda s:s.replace("s","th").replace("S","Th")
```
Dropped 4 bytes with the help of [@DenkerAffe](https://codegolf.stackexchange.com/users/49110/denkeraffe%20DenkerAffe)!
[Answer]
# Haskell, 36 bytes
```
f 's'="th";f 'S'="Th";f x=[x]
(>>=f)
```
[Answer]
# Rust, 46 bytes
```
|s:&str|s.replace("s","th").replace("S","Th");
```
[Try it online!](https://play.rust-lang.org/?gist=cf9cd30c67c57031c74f4c6ed5c5add5&version=stable&backtrace=0)
[Answer]
# PHP, 42 Bytes
if run from a file:
```
<?=strtr($argv[1],["s"=>"th","S"=>"Th"]);
```
Run as:
```
~$ php [file] "This is Silly"
```
[Answer]
# Emacth Lithp, 61 byteth
```
(lambda(s)(replace-regexp-in-string"[Ss]\\(\\w*\\)""th\\1"s))
```
Emacs Lisp tries to be smart when replacing text, but that smartness breaks when the replaced string only takes up one space, i.e. the capital letter S. To prevent this from converting "Sam and Sally" to "THam and THally", the whole word is matched instead. However, this also handles "SAM and Sally" in the way that one would want, i.e. producing "THAM and Thally".
[Answer]
# x86 machine code, 19 bytes
In hex:
```
86ac3c5374043c73750440aab068aa84c075eec3
```
Input: `ESI`: input string, `EDI`: output buffer.
Disassembly:
```
_loop:
0: ac lodsb
1: 3c 53 cmp al,'S'
3: 74 04 je _th
5: 3c 73 cmp al,'s'
7: 75 04 jne _nth
_th:
9: 40 inc eax ;[Ss]->[Tt]
a: aa stosb
b: b0 68 mov al,'h'
_nth:
d: aa stosb
e: 84 c0 test al,al
10: 75 ee jnz _loop
12: c3 ret
```
[Answer]
# Befunge 98, ~~37~~ 49 bytes
Original version :
```
~:"s"- #v_$"ht",>,
_;#-"S":<;$"hT",^
```
---
Terminating edition, as per consensus :
```
~:a-!#@_:"s"-#v_$"ht",>,
_;#-"S": <;$"hT",^
```
This leaves a big honking hole in the code grid that I'm not very happy about. I'll look into that when I have the time.
The 49th byte is a space at the end of the second line, included to have a rectangular grid, required to prevent ccbi (and probably other interpreters) from bugging out and printing an infinite line of "Th"s.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 11 bytes
```
ƛ⇩\s=[‛th$•
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwixpvih6lcXHM9W+KAm3RoJOKAoiIsIiIsIlNhbGx5IGxpa2VzIHNhdXNhZ2VzIl0=)
~~I wath hoping I could find thomething lethth trivial than jutht replacing the letter with the combo but I couldn't.~~ Lookth like I did.
## Explained
```
ƛ⇩\s=[‛th$•
ƛ # To each character:
⇩\s=[ # if char.lower == "s":
‛th$• # "th" with the capitalisation of the character
```
[Answer]
## **C# 6.0 - 58 bytes**
```
string f(string s)=>s.Replace("s","th").Replace("S","Th");
```
Takes the input string as an argument to the function.
[Answer]
# Pyth, 14 bytes
```
::z\s"th"\S"Th
```
[Test suite](http://pyth.herokuapp.com/?code=%3A%3Az%5Cs%22th%22%5CS%22Th&input=Sally+sells+seashells&test_suite=1&test_suite_input=Sam+and+Sally+like+Sheep%0ASally+likes+sausages%0ASally+sells+seashells+&debug=0)
Thanks to @LeakyNun for spotting a typo!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
115'th'YX83'Th'YX
```
[**Try it online!**](http://matl.tryitonline.net/#code=MTE1J3RoJ1lYODMnVGgnWVg&input=J1NhbSBhbmQgU2FsbHkgbGlrZSBTaGVlcCc)
### Explanation
```
115 % 's' (ASCII)
'th' % String 'th'
YX % Regex replacement
83 % 'S' (ASCII)
'Th' % String 'Th'
YX % Regex replacement
```
[Answer]
# Python 3, 53 bytes
```
def l(s):return s.replace("s","th").replace("S","Th")
```
Usage:
```
>> l('Sam and Sally like Sheep')
Tham and Thally like Thheep
```
[Answer]
# GameMaker Language, 74 bytes
```
return string_replace_all(string_replace_all(argument0,'s','th'),'S','Th')
```
] |
[Question]
[
**This question already has answers here**:
[Make a list flat](/questions/248245/make-a-list-flat)
(22 answers)
Closed 1 year ago.
In this challenge, your task is to create a program which takes in a nested array and returns a single-dimensional flattened array. For Example `[10,20,[30,[40]],50]` should output `[10,20,30,40,50]`.
---
**Input**
The input will be a nested array (eg. `[10,20,[[[10]]]]`). It will contain only Integers (both negative and positive), Strings and Arrays. You can take the input as function argument, STDIN or whatever suits your language. You can assume that the input array won't have an empty array.
---
**Output**
The output will be a flatted single-dimensional array with the same elements of same type as in the nested array and in the SAME order.
---
**Test Cases**
```
[10,20,30] -> [10,20,30]
[[10]] -> [10]
[["Hi"],[[10]]] -> ["Hi",10]
[[[20],["Hi"],"Hi",20]] -> [20,"Hi","Hi",20]
[[["[]"],"[]"]] -> ["[]","[]"]
```
---
Feel free to ask for any clarification by using comments. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
**Note:** *If your language contains a built-in for this, then you must NOT use it.*
---
**Edit**
Please also include a link to a website where your code can be executed.
[Answer]
# K, 3 bytes
```
,//
```
This is a fairly common idiom. "Join over converge".
[try it here with oK](http://johnearnest.github.io/ok/index.html?run=%20%2C%2F%2F%281%3B%282%3B3%3B%284%3B5%29%29%29).
How it works:
Join (`,`) fuses together atoms or lists to produce a list. Over (`/`) takes a verb (in this case join) and applies it between each element of a list, left to right. Thus, the compound `,/` will flatten all the top level elements of the list. The symbol `/` actually has different meanings depending on the valence (number of arguments) of the verb with which it is compounded. When we provide `,/` as the verb, the final `/` acts as "converge"- it repeatedly applies `,/` to the input until it stops changing. Some other languages call a feature like this a "fixed point combinator". By repeatedly fusing bottom level lists, you will eventually arrive at a single flat list, and none of the operations will perturb the order of elements. This seems to solve the problem.
[Answer]
# JavaScript (ES6), 35 bytes
Inspired by [@user81655's answer](https://codegolf.stackexchange.com/a/80102/7588):
```
f=a=>a.map?[].concat(...a.map(f)):a
```
[Answer]
## Mathematica, ~~16~~ 14 bytes
```
{##&@@#&//@#}&
```
An unnamed function which takes and returns a list, e.g.:
```
{##&@@#&//@#}& @ {{{20}, {"Hi"}, "Hi", 20}}
(* {20, "Hi", "Hi", 20} *)
```
### Explanation
Syntactic sugar party!
To understand how this works, note that every expression in Mathematica is either an atom (e.g. numbers, strings, symbols) or a compound expression of the form `f[a, b, c, ...]`, where `f`, `a`, `b`, `c` are themselves arbitrary expressions. Here, `f` is called the *head* of the expression. Everything else on top of that is just syntactic sugar. E.g. `{a, b, c}` is just `List[a, b, c]`.
We start with `//@` which maps a functions over *all* levels of a list. For instance:
```
f //@ {{{20}, {"Hi"}, "Hi", 20}}
(* f[{f[{f[{f[20]}], f[{f["Hi"]}], f["Hi"], f[20]}]}] *)
```
Note that this maps `f` over atoms as well as compound expressions. What we're now looking for is a way to get rid of the list heads and keep everything else.
The `Apply` function is normally used to feed the elements of a list as separate arguments to a function, but its actual definition is more general and simply replaces the head of an expression. E.g. `Apply[g, f[a, b]]` gives `g[a, b]`.
Now there's a special "head" called `Sequence` that simply vanishes. E.g. `{a, Sequence[b, c], d}` just evaluates to `{a, b, c, d}`. The idea for flattening the list is to replace the heads of all inner lists with `Sequence` so that they get splatted into their surrounding list. So what we want is to `Apply` the head `Sequence` to the lists. Conveniently if we `Apply` something to an atom, it just leaves the atom unchanged, so we don't have to distinguish between types of expressions at all.
Finally, there's one small issue: `f` is also applied to the outermost level, so that it also removes the outermost `List`, which we don't want. The shortest way to counter that is simply to wrap the result in a list again, such that the surrounding `Sequence` can safely vanish.
Note that there's neither `Apply` nor `Sequence` in the code. `@@` is an operator form of `Apply` and `##&` is a standard golfing trick to shorten the long built-in name `Sequence`. So ungolfing everything a bit, we get something like:
```
flatten[list_] := { MapAll[Apply[Sequence], list] }
```
For more details on how and why the `##&` works, see the section on "Sequences of arguments" [in my answer for the Mathematica tips](https://codegolf.stackexchange.com/a/45188/8478).
[Answer]
## Python 2, 43 bytes
```
f=lambda l:[l]*(l*0!=[])or sum(map(f,l),[])
```
On a list, recurses on the elements and concatenates the results. On a string or number, encases in a singleton list.
Unfortunately, Python 2's ordering for types `int < list < string` sandwiches `list` between the others, requiring two inequalities to check. So, instead, `l*0` is checked against the empty list `[]`, otherwise giving `0` or `""`.
[Answer]
# Ruby, ~~43~~ ~~42~~ 34 bytes
Recursive solution. Now with exception handling! (might as well credit @akostadinov for inspiring the change though)
```
f=->a{a.map(&f).inject:+rescue[a]}
```
[IDEOne link](http://ideone.com/Om3WAT)
[Answer]
# JavaScript (ES6), 41 bytes
```
f=a=>[].concat(...a.map(v=>v.pop?f(v):v))
```
```
<textarea id="input" rows="6" cols="40">[[[20],["Hi"],"Hi",20]]</textarea><br /><button onclick="result.textContent=JSON.stringify(f(eval(input.value)))">Go</button><pre id="result"></pre>
```
[Answer]
# [Perl 6](http://perl6.org), 24 bytes
```
{gather {$_».&{.take}}}
```
### Explanation:
```
{ # has $_ as an implicit parameter
gather {
$_\ # the parameter from the outer block
»\ # for each single value in the structure
.&( # call the following block as if it was a method
{ # this block has its own $_ for a parameter
.take # call the .take method implicitly on $_
}
)
}
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my &flatten = {gather {$_».&{.take}}}
my @tests = (
[10,20,30], [10,20,30],
[[10,],], [10,],
[["Hi",],[[10,],],], ["Hi",10],
[[["[]",],"[]"],], ["[]","[]"],
);
plan @tests / 2;
for @tests -> $input, $expected {
# is-deeply cares about the exact type of its inputs
# so we have to coerce the Seq into an Array
is-deeply flatten($input).Array, $expected, $input.perl;
}
```
```
1..4
ok 1 - $[10, 20, 30]
ok 2 - $[[10],]
ok 3 - $[["Hi"], [[10],]]
ok 4 - $[[["[]"], "[]"],]
```
[Answer]
## Haskell, 43 bytes
```
data D a=L a|N[D a]
f(L x)=[x]
f(N l)=f=<<l
```
Haskell has neither nested lists with different depths of the sublists nor mixed types for the list elements. For nesting I define a custom data type `D` which is either a leaf `L` that holds some element or a node `N` which is a list of `D`s. For the mixed elements I use the predefined data type `Either` which combines two types into one, here `Either String Integer`. The new type `D` and the flatten function `f` are fully polymorphic in the type of the leaf elements, so I don't have to take extra care of anything regarding `Either`.
Usage example: `f (N[N[L(Right 20)], N[L(Left "Hi")], L(Left "Hi") , L(Right 20)])` -> `[Right 20,Left "Hi",Left "Hi",Right 20]`.
[Answer]
# Pyth, ~~7~~ ~~6~~ 5 bytes
```
us+]Y
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=us%2B]Y&input=[[[20]%2C[%22Hi%22]%2C%22Hi%22%2C20]]&test_suite_input=[10%2C20%2C30]%0A[[10]]%0A[[%22Hi%22]%2C[[10]]]%0A[[[20]%2C[%22Hi%22]%2C%22Hi%22%2C20]]%0A[[[%22[]%22]%2C%22[]%22]]&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=us%2B]Y&input=[[[20]%2C[%22Hi%22]%2C%22Hi%22%2C20]]&test_suite=1&test_suite_input=[10%2C20%2C30]%0A[[10]]%0A[[%22Hi%22]%2C[[10]]]%0A[[[20]%2C[%22Hi%22]%2C%22Hi%22%2C20]]%0A[[[%22[]%22]%2C%22[]%22]]&debug=0)
But of course, there is also a build-in function, that handles the task in just 2 bytes: `.n` ([Test Suite](http://pyth.herokuapp.com/?code=.n&input=[[[20]%2C[%22Hi%22]%2C%22Hi%22%2C20]]&test_suite=1&test_suite_input=[10%2C20%2C30]%0A[[10]]%0A[[%22Hi%22]%2C[[10]]]%0A[[[20]%2C[%22Hi%22]%2C%22Hi%22%2C20]]%0A[[[%22[]%22]%2C%22[]%22]]&debug=0))
[Answer]
## JavaScript (Firefox 30-57), 43 bytes
```
f=a=>a.map?[for(b of a)for(c of f(b))c]:[a]
```
Just because I could even avoid using `concat`.
[Answer]
## Julia, 29 bytes
```
f(x,y=vcat(x...))=x==y?x:f(y)
```
This is recursive splatting into a concatenate function until a reaching a fix point. Example
```
julia> f([1,[2,[3,[4,[5,[6]]]]]])
6-element Array{Int64,1}:
1
2
3
4
5
6
```
[Answer]
# Perl, ~~34~~ 29 bytes
Functions.
If needs to flatten to list like `my @a = f(@a)`, 29 bytes:
```
sub f{map{ref()?f(@$_):$_}@_}
```
[Test it on Ideone](http://ideone.com/hlPjyf)
If needs to flatten to array ref like `my $a = f($a)`, 34 bytes:
```
sub f{[map{ref()?@{f(@$_)}:$_}@_]}
```
[Test it on Ideone](http://ideone.com/V8Xg0Q).
# Perl 5.22.0+, 27 bytes
Thanks to [hobbs](/u/1683).
If needs to flatten to list like `my @a = f(@a)`, 27 bytes:
```
sub f{map{ref?f(@$_):$_}@_}
```
[Test it on JDoodle](https://jdoodle.com/a/Rp)
If needs to flatten to array ref like `my $a = f($a)`, 32 bytes:
```
sub f{[map{ref?@{f(@$_)}:$_}@_]}
```
[Test it on JDoodle](https://www.jdoodle.com/a/Ro).
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 14 bytes
```
{Reap[Sow@>_]}
```
[Try it online!](https://tio.run/##bY4xC8IwEIX3/IpQHFQixFYXwSK4OImo23FIqal20WICDuJvj3eNKUUMNNx97@X1Fc4V5dX4Si6W/rU3RQOH@3OVn/Dth2MJU61SrTKNcpL3NgE0Y4S8Jps6QRVw4ExUECHVpAVLi9P4mOJaECmbE0D28f1NojHsYjwSYmvM2cKgacoLit2jvrmjsW5dWGOhUhKEpMNdJaVLaqsCabvF@W@lTuxXUF0exUFG34ytc/2jAP@JJFYEov8A "Attache – Try It Online")
Fortunately, Attache has a "vectorization" operator, which applies a function at the atoms of a list. In this case, all we need to do is to set up a reaper with `Reap` and `Sow` all atoms of the input `_` with `@>`. I think it's quite elegant.
## Alternatives
**15 bytes:** `Fixpoint{`'^^_}`
**16 bytes:** `Fixpoint!&Concat`
**17 bytes:** `{q:=[]q&Push@>_q}`
**17 bytes:** `Fixpoint[&Concat]`
[Answer]
## [Retina](https://github.com/mbuettner/retina/), 30 bytes
```
1>`("(\\.|[^"])+")|[][]
$1
$
]
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYAoxPmAoIihcXC58W14iXSkrIil8W11bXQokMQokCl0&input=WzEwLDIwLDMwXQpbWzEwXV0KW1siSGkiXSxbWzEwXV1dCltbWzIwXSxbIkhpIl0sIkhpIiwyMF1dCltbWzIwXSxbIkhbXVwiW11pIl0sIkhcXFwiW11pIiwyMF1d) (The first line is only used to run multiple test cases at once.)
Retina has no concept of arrays, string literals or numbers, so I decided to go with a "common" input format of `[...,...]` style arrays and `"`-delimited strings, where `\` can be used inside the strings to escape any character (in particular `"` and `\` itself).
The program itself simply matches either a full string or a square bracket, and replaces them with `$1` which keeps strings and removes square brackets. The limit `1>` skips the first match so that we don't remove the leading `[`. However, this does remove the trailing `]`, so we add it back in in a separate stage.
[Answer]
## Pyke, 11 bytes
```
.F~]+=])K~]
```
[Try it here!](http://pyke.catbus.co.uk/?code=.F~%5D%2B%3D%5D%29K~%5D&input=%5B%5B%5B20%5D%2C%5B%22Hi%22%5D%2C%22Hi%22%2C20%5D%5D)
Explanation:
```
.F~]+=]) - Deep for loop
~] - contents of `]` ([] by default)
+ - ^+i
=] - `]` = ^
K~] - Output value
K - Remove the output from the for loop
~] - Return the contents of `]`
```
### Or 7 bytes after a bugfix
```
M?+]K~]
```
[Try it here!](http://pyke.catbus.co.uk/?code=M%3F%2B%5DK~%5D&input=%5B%5B%5B20%5D%2C%5B%22Hi%22%5D%2C%22Hi%22%2C20%5D%5D)
Explanation:
```
M?+] - Deep map
?+] - `]` = `]`+i
K~] - Output value
K - Remove the output from the for loop
~] - Return the contents of `]`
```
### Or even 2 bytes if printing to stdout is allowed (This might come under built-ins)
```
M
<newline required>
```
[Try it here!](http://pyke.catbus.co.uk/?code=M%0A&input=%5B%5B%5B20%5D%2C%5B%22Hi%22%5D%2C%22Hi%22%2C20%5D%5D)
This deeply applies the `print_newline` function to every non-sequence item in the input and recurses for sequence items.
[Answer]
# Java (v8) 390 276 bytes
```
public static Object[] f(final Object[]a) {
List<Object>r=new ArrayList<>();boolean t=false;int n=0;
for(final Object p:a)
if(t=p instanceof Object[]){for(final Object q:(Object[])p) r.add(q);}
else r.add(p);
return(t)?f(r.toArray()):r.toArray();
}
```
Just for completeness and all that. :) Can't say Java's code-efficient.
[Answer]
## Python, 57 bytes
```
f=lambda a:sum([list==type(x)and f(x)or[x]for x in a],[])
```
Try it online: [Python 2](http://ideone.com/fork/vHoqK3), [Python 3](http://ideone.com/fork/cFnU0B)
Thanks to Kevin Lau for the `list==type(x)` trick.
[Answer]
# Ruby
there is builtin `flatten` method.
You can run here:
<http://www.tutorialspoint.com/execute_ruby_online.php>
One 43 bytes, but thought to share:
```
f=->a{a.inject([]){|r,e|r+(f[e]rescue[e])}}
```
One 45 bytes that is more efficient than the previous and the other ruby answer:
```
f=->a{a.map{|e|Array===e ?f[e]:[e]}.inject:+}
```
here's benchmark:
```
require 'benchmark'
n=10^9
arr=[[[20],[[[[[[[[123]]]]]]]],"ads",[[[[[[[4]]]]]]],5,[[[[[[[[[[6]]]]]]]]]],7,8,[[[[[[[[[[9]]]]]]]]]],[[[[[[[[[[0]]]]]]]]]],[[[[[[[[[[[["Hi"]]]]]]]]]]]],[[[[[["Hi"]]]]]],[[[[[20]]]]]]]
Benchmark.bm do |x|
x.report { f=->a{a.map(&f).inject:+rescue[a]}; f[arr] }
x.report { f=->a{a.map{|e|e!=[*e]?[e]:f[e]}.inject:+}; f[arr] }
x.report { f=->a{a.inject([]){|r,e|r+(f[e]rescue[e])}}; f[arr] }
x.report { f=->a{a.map{|e|Array===e ?f[e]:[e]}.inject:+}; f[arr] }
end
```
result:
```
user system total real
0.010000 0.000000 0.010000 ( 0.000432)
0.000000 0.000000 0.000000 ( 0.000303)
0.000000 0.000000 0.000000 ( 0.000486)
0.000000 0.000000 0.000000 ( 0.000228)
```
[Answer]
# Perl, ~~39~~ 34 + 1 (`-p` flag) 35 bytes
Oneliner. Inspired by [Martin Büttner](/a/80109/34575).
```
#!perl -p
s/("(\\.|[^"])+"|]$|^\[)|[][]/$1/g
```
[Test it on Ideone](http://ideone.com/sBPlDe).
[Answer]
## Clojure, 68 bytes
```
(def f #(if(some vector? %)(f(mapcat(fn[z](if(vector? z)z[z]))%))%))
```
`mapcat` first applies function to each element and then concats results. So every time it concats one 'nesting level' is lost. Concat does not work on not sequences so elements have to be wrapped into vector if they're not vector.
You can try it here: <http://www.tryclj.com>
```
(f [[[20],["Hi"],"Hi",20]])
(f [[["[]"],"[]"]])
```
[Answer]
# ANSI C, 193 bytes
```
#define b break;
#define c case
#define p putch(_);
char f;main(_){switch(_){c 1:putch(91);b c 34:f^=1;p b c 91:f&&p b c 93:f&&p b c 10:c 13:putch(93);return;default:p}_=getch();main(_);}
```
:-/, any suggestions? Btw, I did try to find an online source to compile this but the WL is strict for this code to compile. It will work for VS and gcc otherwise.
[Answer]
# JavaScript 20 bytes
```
a=>(a+[]).split(',')
```
The array + array is equal to array.toString
[Answer]
# [Haskell](https://www.haskell.org/) + [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html), 7 bytes
In order to represent a ragged list in Haskell we use a free monad of lists. Luckily for us provided with the free monad is `retract`, which does a lot of different things, but when given the particular type here it flattens the free monad of lists down to a single list.
```
retract
```
[Try it online!](https://tio.run/##ZZHBatwwEIbvfoqB5GBDbGdbSulS@9ImEEiXUnIrIQy2ZIu1JCPJdEPaZ9@OLK26S0/W/P/MfDPjEe2eTdPxrbyCR1TDggODH6j2u6fXmVm4Kv9kZQlfGRdKOKGVhU7PgvXAjZbgRgZWL6ZjoPkaccMYSN0vE721AcesE2rwTUbnZrut6xG7PWGqMbArbYZ6Dlrty8sP1ab6WPe6s7U1Xf1FK2f0VH3TCvvqnjKq0ckp69Eh@BA4YAbQwPfFsPX5O@g5h/yUUBRZJpR1qGjY@0V1jqbj0LQpiKkF/BqZYdSFS5x9Cgw6aeCDPICKxMw9ILmhD9lNHIPEz9etlyjHn/ph9/iwuwsAf@LMMGewc7DdwrpmnCzODmW77njKSvyG@pG4GHXurmVog40W2raBaNINHDMec3GCPEKoZXmJxVDwcsY8afMoIkt6dQ2T4feVdHKup37NSZvJANQGpwkOUBHp4EkSDv/RJbFSh5eLu6e1k8/PN/cdwub//CNv4hmOEoWipF7ThWYjlIPrVP9zpWxuwq99F7/vb@DMPamf4ndz@/xcHP8C "Haskell – Try It Online")
But we can also make our own solution using other tools, like `foldFree`:
# 11 bytes
```
foldFree id
```
[Try it online!](https://tio.run/##ZZHBatwwEIbvfoqB5GBDbGdbSulS@9ImEEiXUnIrIQy2ZIu1JCPJdEPaZ9@OLK26S0/S/P9ovpnRiHbPpun4Vl7BI6phwYHBD1T73dPrzCxclX@ysoSvjAslnNDKQqdnwXrgRktwIwOrF9Mx0HyNuGEMpO6Xie7agGPWCTX4IqNzs93W9YjdnjDVGNiVNkM9B632z8sP1ab6WPe6s7U1Xf1FK2f0VH3TCvvqnjKq0ckp69Eh@BA4YAbQwPfFsPX6O@g5h/yUUBRZJpR1qKjZ@0V1jrrj0LQpiKkF/BqZYVSFS5x9Cgw6aeCDPICKxMw9ILmhDtlNbIPEz9etlyjHr/ph9/iwuwsAv@LMMGewc7Ddwjpm7Cz2DmW7znjKSvyG6pG4GHXurs/QBhsttG0D0aQdOGY85mIFeYRQyfISi@HByxnzpM2jiCzp1TVMhp9X0sq5nvo1J00mA1AbnCY4QEWkgydJOPxHl8RKFV4u9p7GTj4/n9xXCJP/84@8SYHojxKFosRe05ZmI5SD61Tj50ra3ITvfRfP9zdw5p7UT/Hc3D4/F8e/ "Haskell – Try It Online")
However `foldFree` basically is just a more general version of `retract`, and we can do it without it:
# 21 bytes
```
iter(>>=id).fmap(:[])
```
[Try it online!](https://tio.run/##ZZFRa9swEMff/SkOmgcbanlZGWNh9su2QKELZewtlCJsyRaxJCPJLKXrZ09PlqIl7Mm6/939f3fngdoDG8fTa3kDD1T1M@0Z/KLqsPv9MjELN@VbVpbwnXGhhBNaWWj1JFgH3GgJbmBg9WxaBpovETeMgdTdPOJbG3DMOqF6bzI4N9lNVQ20PSCGDIFNtOmrKWiVby8/kTX5XHW6tZU1bfVNK2f0SH5qRTuyxQoyODlmHXUUfAgcaAZQw@Ns2PL8G/ScQ34uKIosE8o6qnDY7axah9NxqJsUxNIC/gzMMHThkk6@BHqdNPBBHkBFYuYekLLBB9N1HAPFr6vGS1jjT32/e7jf/QgAf@LMMGdo62CzgWXNOFmcHcpm2fFclfg1@qE4G3WZXdqoDWlqoWlqiEm8gWPGY65OkEcIWpbXWBoani@YZ20aRGRJry5hSvh9JZ6c67FbatJmMgC1oeMIRyBIOnqShON/dIms5PB8dfe0dsrzy829Q9j8X/7Eaz9fjqroCuKvn2/2T8VJUqGwpdN4r8kI5WCV3PYLc30bfvTH@L27hYvsWf0Sv@sPT@j6Dg "Haskell – Try It Online")
If we want to use *none* of the functions provided by free just the definition of the monad and prelude functions we can do:
# 29 bytes
```
f(Pure a)=[a]
f(Free a)=a>>=f
```
[Try it online!](https://tio.run/##ZVHBatwwEL37KwaSgw2xnW0ppUvsS5tAIF1K6S0sYbAl26wlGUmmG9J@@3ZkyeouOVnz3pv3ZsY9mgMbx9NbfgVPKLsZOwY/UR52v14nZuAq/5vkOXxjfJCDHZQ00KhpYC1wrQTYnoFRs24YKL5UXDMGQrXzSG@lwTJjB9k5k97ayWzLssfmQDFF77MLpbty8ljp2vNPxab4XLaqMaXRTflVSavVWHxXEtvigRRFb8WYtGgRXAkcMAGo4Mes2fL84/GUQ7oKsixJBmksShr2YZaNpek4VHUsgjSD3z3TjFy4wMlJoFMRA1ekPiiLmakLiKz3IboKYxB4d107iDTu1I@7p8fdvQ9wJ040sxobC9stLGuGycLskNfLjqsq5lfkR@Cs5Tm7tKHxNBqo6woCSTewTLuYixOkIYQs88tY9A0vZ5krNvVDyBIOXcpIuH0FnZyrsV00cTPhA5XGcYQjFJR0dEkCju/SBWVFh5eLu8e1I8/PN3cOfvP//ImvBtUz7hMe5FmFpOMngYOkxlbR1SY9SAvX0fN5adzc@N/9IXw/3sAZu6Jfwndzu99np38 "Haskell – Try It Online")
[Answer]
# Racket, 63 bytes
```
(define(f l)(apply append(map(λ(x)(if(list? x)(f x)`(,x)))l)))
```
[Answer]
## Java 8 165 chars
```
import java.util.*;<T>T[]f(T[]a){List<T>l=new ArrayList<>();for(T e:a)if(e instanceof Object[])Collections.addAll(l,f((T[])e));else l.add(e);return(T[])l.toArray();}
```
Ungolfed into a class:
```
public class Q80096 {
public static <T> T[] flatten(T[] array) {
List<T> flattenedList = new ArrayList<>();
for (T element : array)
if (element instanceof Object[])
Collections.addAll(flattenedList, flatten((T[]) element));
else
flattenedList.add(element);
return (T[]) flattenedList.toArray();
}
}
```
This answer is based on [Jeremy Harton's approach](https://codegolf.stackexchange.com/a/80156/52713). I used it changed it in some places and created a more golf-like version.
[Answer]
# JavaScript, 17 Bytes
```
a=>eval(`[${a}]`)
```
Finally, JavaScript's type conversions can be put to some good use! Please note that this will actually output an array, but string conversion (putting it into HTML) causes it to become a comma separated list.
If comma separated lists are acceptable output, then the following is valid:
# 7 Bytes
```
a=>""+a
```
NOTE: Snippet is broken for some reason
```
var subject =
a=>eval(`[${a}]`)
```
```
<input oninput="try {output.innerHTML = subject(this.value)} catch(e) {output.innerHTML='Invaild Input'}" />
<div id="output"></div>
```
[Answer]
# PHP, 73 Bytes
```
<?array_walk_recursive($_GET,function($i)use(&$r){$r[]=$i;});print_r($r);
```
[Answer]
# [Elixir](https://elixir-lang.org/), 74 bytes
```
def d(l)do l|>Stream.flat_map(fn x->if is_list(x)do d(x)else[x]end end)end
```
First Elixir answer, so can probably be golfed a bit.
[Try it online.](https://tio.run/##jY69CsMgFEb3PoU4KVix6d6t0E4tdBQJglos/gQ14NB3T5VkLhm@78LlHO7VzlabFqWNj2p2GjxTfCfpgYp9CRRyWEXgvpdXSVp6apwso5cTMgHU48UaYPPobC6odlC1oV3WvAodFGjBLUvL4f6g01wyuIbZ00@0AW23qEL8xMjAyJkJTCCB@D/caLEPhDcLBVmFfQYfWBNWr3d7a68JuehS781Yfg)
**Explanation:**
```
def d(l)do l|> # Recursive method taking a list as input:
Stream.flat_map(fn x-> # Map over each item `x` of the input-list:
if is_list(x)do # If `x` is a list itself:
d(x) # Do a recursive call with `x`
else # Else:
[x] # Simply leave `x` unchanged
end # End of the if-else statements
end) # End of the map
end # End of the recursive method
```
Of course, if builtins were allowed, this could have been **25 bytes** instead:
```
fn(l)->List.flatten(l)end
```
[Try it online.](https://tio.run/##jc/NCgIhFAXg/TzFxZWCiU3r2gUTBLUXFwNqGP6Eo9DbmzK0jGlzFpfvwLna2bdNVWnjoypOwz3FR5o9qDgAmGM1ATuyO13tkplxc866H3RQFeByY6@SFziH4tkz2oANw2LP6cjpgUtCEUVk@OUalJsGTRZJutpNLEbe7Frp2Xb8UUJCdt/zi/t7Hw)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
;/ÐL
```
[Try it online!](https://tio.run/##y0rNyan8/99a//AEn////0cbGugYGehEGwOxiUFsrI6pQSwA "Jelly – Try It Online")
## Explanation
```
;/ | Reduce by concatenation
ÐL | Loop until no further changes
```
Built-in `F` would be one byte if allowed.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes
```
#~Level~{-1}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@1@5zie1LDWnrlrXsFbtf0BRZl6Jg5abgr4DV3W1oYGOkYGOsUGtjgKIUwumlTwylWp1IHywQLURUAFUGEQC9UAllKprQWIgsrb2PwA "Wolfram Language (Mathematica) – Try It Online")
Un-golfed: `F[x_] := Level[x, {-1}]`
picks out the elements of the structure at the last level of its [tree form](https://reference.wolfram.com/language/ref/TreeForm.html). I'm not sure this counts as "avoiding the builtin" (which would be [`Flatten`](https://reference.wolfram.com/language/ref/Flatten.html)).
] |
[Question]
[
**Challenge**
*[Sandbox post](https://codegolf.meta.stackexchange.com/a/16598/78039)*
Given a positive integer `(K)` Output a uniformly-random integer `(Y)` between `[0, K)`.
If `Y > 0` Assume `K = Y` and repeat the process until `Y = 0`.
**Rules**
* Input must be printed at first
* Output format as you wish
* Your program must finish.
* `0` must be the final output, Optionally an empty line instead `0`
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~6 5~~ 4 bytes
```
.uOW
```
[Try it here!](https://pyth.herokuapp.com/?code=.uOW&input=9&debug=0)
### How it works
```
.uOW Full program. Takes an integer from STDIN and outputs a list to STDOUT.
.u Cumulative fixed-point. Apply the given function with a given initial value,
which is implicitly assigned to the input, until a result that has occurred
before is found. Returns the list of intermediate results.
W Conditional application. If the argument (the current value) is truthy, then
apply the function below, otherwise leave it unchanged.
O Random integer in the range [0, N).
IOW: at each iteration of .u, assign a variable N to the current value, starting
with the input. If N is not 0, then choose a random integer in [0, N), else
return N unchanged. Whenever we encounter a 0, the next iteration must also
result in a 0, and therefore the loop stops there.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 42 bytes
```
f(_){printf("%d\n",_);(_=rand()%_)&&f(_);}
```
[Try it online!](https://tio.run/##NY7PCsIwDMbvPkWYTFI3Zbta9QmGJz3pmKX7Y0A76TovsmevbdWQhI984ZfIVSelnZOS97FuYDuYmvr1bW9brNj7qUmZFqO4vqgorRjHaqeFqpHFFVss/A6frNuBhyCFXgjdyRTkTWhYOv06l@w9AxfeJB7kEBiGHg0eTkXB2Hfc9hqQdjkHgm0AcUgSYvAF@Pg/dGwGQ6rbwDUerv43CLeo/KECDoXpCf/Gz5lC140ZtYKMzyZr88xl7irLPw "C (gcc) – Try It Online")
Uses short-circuited logical and.
```
f(_){ // f(int _) {
printf("%d\n",_); // print argument and a newline
(_=rand()%_) // set _ to rand()%_
&&f(_);} // short-circuit AND to recursively call f if _ not zero
```
## [C (gcc)](https://gcc.gnu.org/), 40 bytes (w/o printing initial value)
```
f(_){printf("%d\n",_=rand()%_);_&&f(_);}
```
[Try it online!](https://tio.run/##NY7PDoIwDMbvPkWjgWyiBq4OfQLiSU9qcNn400SHGdOL4dnnNqBpmy/9ml8rto0QdoVKPD@ygrw3Ertde7Q1KenvrVGZmiwjeVPLTXnQXElCo5KyMo79Bhus24AXR0W84LoRGxAt17B2@nu9098CXHgTWZB9oBh8VeR0KQpKx3HdaSB4yBgg5AHEIEmQwgjwMb9zrnqDqtnDI@of/jMIt/A@oQKOcNMhmY3JGULXlfloBSlbDNZmqcvMVZr9AQ "C (gcc) – Try It Online")
Uses short-circuited logical and.
```
f(_){ // f(int _) {
printf("%d\n", // print an integer and a newline
_= // The integer is _ which we set to...
rand()%_); // a random value modulo the input _
_&&f(_);} // short-circuit AND to recursively call f if _ not zero
```
[Answer]
# [R](https://www.r-project.org/), ~~66 60 56 43~~ 41 bytes
```
function(n)while(print(n))n=sample(n,1)-1
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPszwjMydVo6AoM68EyNPMsy1OzC0AiuTpGGrqGv5P0zA0MDDQ/A8A "R – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
`tYrqt
```
[Try it online!](https://tio.run/##y00syfn/P6Eksqiw5P9/QwMDAA "MATL – Try It Online")
### Explanation
```
` % Do...while
t % Duplicate. Takes input (implicit) the first time
Yr % Uniform random integer from 1 to n, included
q % Subtract 1
t % Duplicate. This will be used as loop condition
% End (implicit). Proceeds with next iteration if non-zero
% Display stack (implicit)
```
[Answer]
# [Pepe](https://github.com/Soaku/Pepe), 25 bytes
Pepe is a programming language made by user [Soaku](https://codegolf.stackexchange.com/users/72792/soaku).
```
REeErEErReEEreeEREEeEEree
```
[Try it online!](https://soaku.github.io/Pepe/#RE@NI-b*)
Explanation:
```
REeErEErReEEreeEREEeEEree # full program
REeE # input as num, in stack 1
rEE # create loop in stack 2 with name 0
rReEE # - output and preserve the number in stack 1
reeE # - output a newline "\n"
REEeEE # - random number by 0 to input
ree # goto loop with name 0 if stack 1 is not equal
to stack 2
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes
```
{$_,(^*).pick...0}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXkcjTktTryAzOVtPT8@g9r81l1qahqGBgaZecWKlQkWFgqHBfwA "Perl 6 – Try It Online")
Anonymous code block that returns a list of values. If you don't mind the numbers being ranges, you can do:
```
{^$_,^*.pick...0}
```
for 17 bytes. Funnily enough, another builtin random function, `roll`, has the same behaviour in this instance for the same amount of bytes.
[Answer]
# [Perl 5](https://www.perl.org/).10.0 `-pl`, 26 bytes
```
say;say while$_=int rand$_
```
[Try it online!](https://tio.run/##K0gtyjH9/784sdIaiBXKMzJzUlXibTPzShSKEvNSVOL//zc14DI0MPiXX1CSmZ9X/F@3IOe/rq@pnqGBngEA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 3 bytes
```
XƬ0
```
This is a monadic link (function) that prints an array and returns **0**.
[Try it online!](https://tio.run/##y0rNyan8/z/i2BqD/4fbHzVus1ZQeLhj@6OGOQrOiTk5CiUZqQo5mXnZCol5KQoFRakFqUA6UaG4IDE5VaEkHyxflFpSWpSnUJaYU5qq9/@/iREA "Jelly – Try It Online")
### How it works
```
XƬ0 Monadic link. Argument: n
XƬ Pseudo-randomly pick (X) an integer k in [1, ..., n], set n = k, and repeat.
Do this 'til (Ƭ) the results are no longer unique and return the array of
unique results, including the initial value of n.
This stops once X returns k with argument k. The second k will be omitted
from the return value.
0 Print the resulting array and set the return value to 0.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
ẉ?ℕ₁-₁ṙ↰
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuTvtHLVMfNTXqAvHDnTMftW34/9/QwOA/AA "Brachylog – Try It Online")
### Explanation
```
ẉ Write the input followed by a linebreak
?ℕ₁ The input must be in [1, …, +∞)
-₁ṙ Generate an integer in [0, …, input - 1] uniformly at random
↰ Recursive call with that random integer as the new input
```
The recursion will stop once `?ℕ₁` fails, that is, when the input is `0`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
Δ=L<Ω0M
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3BRbH5tzKw18//83NDAwAAA "05AB1E – Try It Online")
**Explanation**
```
Δ # loop until value doesn't change
= # print current value
L<Ω # push a random number in ([1 ... X] - 1)
# will return -1 when X=0
0M # push max of that and 0
```
[Answer]
# J, 13 bytes
```
[:}:? ::]^:a:
```
On the subway, so apologies for lack of TIO (hopefully there isn’t a lack of correctness).
Outputs a list of values.
Presumably the APL approach will be shorter, but this is what I thought of.
# How it works
`^:a:` apply repeatedly until convergence, storing intermediate results in an array.
`?` random integer in range `[0, K)` for `K` greater than 0. For 0, it gives a random integer in range `(0,1)`. For a floating point number, it errors.
`::]` catch an error for an input to `?` and instead of erroring, output the input that caused the error.
`}:` get rid of the last value in the array (this is so that a floating point number isn’t output).
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/aqtbKXsHKKjbOKtHqvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagpEB138A "J – Try It Online")
[Answer]
# JavaScript (ES6), ~~38~~ 37 bytes
-1 byte thanks to @Arnauld
```
f=n=>[n,...n?f(Math.random()*n|0):[]]
```
```
f=n=>[n,...n?f(Math.random()*n|0):[]]
```
```
<input type=number id=a><button onclick="console.log(f(+a.value))">Test</button>
```
[Answer]
# C, 38 bytes
```
f(k){printf("%d ",k);k?f(rand()%k):0;}
```
[Try it online](https://tio.run/##Dco7CoAwDADQ3VMEQUhEQSd/iAcRh7SlWopVipt49tj18XS9ay0nu4AuPMCVPjhCWSp6nUWGGfi5HKq13YgS0PSJRU/vHdO3mBcG8srT5BeLkYNBKjyNTWqZyNB38gM)
**Ungolfed**
```
void f(int k){
printf("%d ",k);
if(k)
f(rand()%k);
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 bytes
```
W
~O
```
[Try it online!](https://tio.run/##K6gsyfj/P5yrzv//fzMA "Pyth – Try It Online")
This basically implements the algorithm:
\$ \begin{align} % Unknown environment algorithm :(
&Q \gets \text{input} \\
&\mathbf{Repeat} \\
&\begin{array}{cl}
1. & temp \gets Q \\
2. & Q \gets \text{unif}\{ 0, Q - 1 \} \\
3. & \mathtt{Print}(temp)
\end{array} \\
&\mathbf{Until} \quad temp = 0
\end{align} \$
To translate the Pyth into the algorithm, we can mostly just examine what each character means. Since Pyth is written in prefix notation (i.e. `* + 1 2 3` is `(1 + 2) * 3`) we can start from the left and fill in the arguments as we go.
`W` begins a traditional while loop. The first statement after it is the loop condition and the second statement after it is the loop body. If the second statement is empty it [becomes a no-op](https://codegolf.stackexchange.com/questions/62732/implement-a-truth-machine#comment151542_62764). This while works exactly like the Python while, so it will evaluate non-zero integers as True and zero as false.
The first statement after the while begins with the newline character. This corresponds to Pyth's "print and return with a newline" function. This takes one argument, which is then printed and also returned unmodified. This allows us to print the intermediate steps while also performing the needed operations.
The argument passed to this print function begins with `~` which is a bit special. If the character immediately after `~` is a variable it takes two arguments, otherwise it takes one. Since `O` is not a variable `~` will consume only one argument. `~` functions a bit like `+=` does in many conventional languages, though the closest operator would be the post-increment operator `++` from `C`. You may know that `x++` will be like using `x` as the current value, but thereafter `x` will be `x+1`. `~` is the same idea, but generalised to whatever the result of the first argument is. How it picks what variable to assign to will be addressed later.
The argument of `~` is `O` which is very simple. When its one argument is an integer `O` returns a value from 0 to one less than that integer uniformly at random.
Now you may have noticed `O` does not have an argument. Here the Pyth interpreter kindly fills in a guess, which here is the variable `Q`. `Q` has a special meaning in Pyth: whenever it is present in a program the Pyth program begins with assigning `Q` to the input of the program. Since this is the first variable occurring in `~`'s argument `Q` is also now the variable that `~` will assign a value to.
Summed up our "readable" program might look like:
```
while print_and_return( assign_variable( Q, unif(0, Q-1) ) ):
pass
```
And one sample "run-through" might look like:
1. Q = 5
2. `O` returns 3, `~` returns 5, `\n` returns and prints 5 which is true
3. Q = 3
4. `O` returns 0, `~` returns 3, `\n` returns and prints 3 which is true
5. Q=0
6. `O` returns something irrelevant, `~` returns 0, `\n` returns and prints 0 which is false
7. Q = something irrelevant
8. Terminate
[Answer]
# [Factor](https://factorcode.org/), 21 bytes
```
[ [ random ] follow ]
```
[Try it online!](https://tio.run/##Nc2xDoIwFEbhnaf43Y2BFY2rYWExToShKa00gXvr7UXD01c0@gDnO95YZcm3a9NeahgRsyZEcaprlEAKMTTwjOQeiyPrEo5F09ZIVozasahKVGWJ07c85w7dv@jheZr4hT7PJuKAHWShBB0d/EJWAxP46WQDYDmGzWb/0fYY3MyUdFsEuv9AcinlNw "Factor – Try It Online")
Basically, collects the values after each iteration (including zeroth iteration) stopping when the value is `f`, where each iteration converts the value `n` to a random integer between `0` and `n-1` inclusive. Calling `random` on zero yields `f`, conveniently terminating the loop.
Interestingly, [the doc page for `follow`](https://docs.factorcode.org/content/word-follow,sequences.html) has an example code that solves almost the same task, but it is actually longer since it tries to exclude zero at the end.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~12~~ 9 bytes
Anonymous tacit prefix function. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems. Returns the final value (0) in addition to printing while run.
```
{⌊?⎕←⍵}⍣=
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9XTZA7lAzqPerbWPehfb/k8Dc/ogirqaD603ftQ2EcgLDnIGkiEensH/i1KLS3NKgOrSFEyMuFB4AA "APL (Dyalog Unicode) – Try It Online")
`{`…`}⍣=` apply the following function until stable:
`⎕←⍵` output the argument
`?` return a uniformly distributed random number in the range 0 through that–1
`⌊` round down (because `?0` gives a (0,1) float)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~40~~ 42 bytes
*Some idiot™* forgot to print the initial value first.
```
f(K){while(K)printf("%d\n",K,K=rand()%K);}
```
Don't panic.
[Answer]
# x86 + rdrand, 19 bytes
Straightforward implementation. Takes input K in `ecx` and outputs to a buffer in `ebx`.
```
0000000a <start>:
a: 0f c7 f0 rdrand %eax
d: 31 d2 xor %edx,%edx
f: f7 f1 div %ecx
11: 89 13 mov %edx,(%ebx)
13: 83 c3 04 add $0x4,%ebx
16: 89 d1 mov %edx,%ecx
18: 85 c9 test %ecx,%ecx
1a: 75 ee jne a <start>
1c: c3 ret
```
[Answer]
# [Python 3](https://docs.python.org/3/), 39 bytes
```
f=lambda k:print(k)or f(hash('.'*k)%k)
```
Probably not the most cryptographically secure random number generator but to the human eye it looks random enough...
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIduqoCgzr0QjWzO/SCFNIyOxOENDXU9dK1tTNVuT6z9EMk3D3FRT8z8A "Python 3 – Try It Online")
[Answer]
# TI-Basic (TI-84 Plus CE), ~~17~~ 13 bytes
```
While Ans
Disp Ans
int(randAns
End
Ans
```
-4 bytes from [Misha Lavrov](https://codegolf.stackexchange.com/questions/168221/randomizing-until-0/168320#comment406660_168320)
Takes input in `Ans` as `50:prgmNAME`.
TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens). All tokens used here are one byte.
Explanation:
```
While Ans # 3 bytes, While the number we hold is not zero:
Disp Ans # 3 bytes, Display it on its own line
int(randAns # 4 bytes, and replace it with a number randomly
# chosen from 0 to one less than it (inclusive)
End # 2 bytes, end While loop
Ans # 1 byte, Display (and return) zero
```
---
An 11-byte solution suggested by Misha Lavrov that requires pressing `enter` after each line following the first.
```
Ans
While Ans
Pause int(randAns
End
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~64~~ ~~62~~ 60 bytes
```
from random import*
k=input()
while k:print k;k=randrange(k)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocWXbZuYVlJZoaHKVZ2TmpCpkWxUUZeaVKGRbZ9uClAJxeqpGtub//6YA "Python 2 – Try It Online")
---
Saved
* -2 bytes, thanks to Jonathan Allan
[Answer]
# C++ (gcc), 98 bytes
```
#import<cstdio>
#import<cstdlib>
#define d printf("%i ",x
int p(int x){d);while(x>0)d=rand()%x);}
```
[Try it here!](http://rextester.com/KXTCS31402)
**Usage**
```
int main() {
p(100);
}
```
This is my first code golf attempt. Any feedback or remarks are welcome.
Edit:
Removed the main function as suggested to make it valid.
[Answer]
# ><>, 92+2 Bytes
```
:nao:0=?;0_1>:{:}(?\\
}(?!\$2*1>x~\$+1$*2/\~00:{{:@}
8+1.\~:{:}\+>$1+f
~~@~~47*0.\(a2*1@@?!.
```
+2B for -v flag
[Try it online!](https://tio.run/##S8sszvj/3yovMd/KwNbe2iDe0M6q2qpWwz4mhgtIKsaoGGkZ2lXUxahoG6poGenH1BkYWFVXWznUclloG@rF1IFUx2jbqRhqp3HV1TnU1ZmYaxnoxWgkAvU5ONgr6v3//1@3TMHQwAAA "><> – Try It Online")
><>'s only source of randomness comes from the 'x' instruction, which sets the instruction pointer's direction to a random value. As such, generating a random number from 0 to n isn't trivial.
I first calculate how many bits are required to represent a number in the range [0,n), then generate random bits to generate a random number. This leaves the possibility that it'll generate a number slightly larger than n, in which case we just discard it and try again.
# Explanation:
```
:nao Print the current number followed by a newline
:0=?; If the current n is 0, terminate
Calculate how many random bits we need to be generating:
0 1 Initialise the variables for this loop:
numberOfBits = 0, maxValue = 1
:{:}(?\ If maxValue >= n, break out of the loop
*2 maxValue *= 2
$+1$ numberOfBits += 1
Generate the random number:
~ Delete maxValue
00 Initialise randomNumber = 0, i = 0
}(?!\ :{{:@} If i >= numberOfBits, break out of the (inner) loop
$2* randomNumber *= 2
_
1>x~\ The random bit: If the IP goes up or
\+> left, it'll be redirected back onto the 'x',
if it goes down, it adds one to randomNumber
If it goes right, it does nothing to randomNumber
$1+ increment i
8+1. f Jump back to the start of the inner loop
After we've generated our number, check that it's actually below n
~ Delete i
:{:} ( ? Test that the number is less than n
a2*1 . If it's not, jump back to the start
of the number generation section
@~~ Otherwise delete the old value of n, and numberOfBits
47*0. Then jump back to the start of the program
```
[Answer]
## MATLAB (~~49~~ 46 bytes)
```
@(k)eval('while k;disp(k);k=randi(k)-1;end;0')
```
Sample output:
```
>> @(k)eval('while k;disp(k);k=randi(k)-1;end;0')
ans(5)
ans =
@(k)eval('while k;disp(k);k=randi(k)-1;end;0')
5
3
2
1
ans =
0
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 21 bytes
```
.+
*
L$`.
$.`
+¶<)G?`
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4vLRyVBj0tFL4FL@9A2G013@4T//y0B "Retina – Try It Online") Explanation:
```
+
```
Repeat until the value stops changing (i.e. 0).
```
¶<)
```
Print the value before each pass through the loop.
```
.+
*
```
Convert to unary.
```
L$`.
$.`
```
Create the range and convert to decimal.
```
G?`
```
Pick a random element.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~6~~ 7 bytes
```
QWQ=OQQ
```
[Try it online!](https://tio.run/##K6gsyfj/PzA80NY/MPD/fzMA "Pyth – Try It Online")
+1 to print the initial input value.
While Q is truthy, set Q to be a random integer between 0 and Q and print Q.
Not the shortest Pyth answer but I'm just learning and only posting because of the recent discussion about no-one using Pyth any more :)
[Answer]
# [Haskell](https://www.haskell.org/), ~~74~~ 71 bytes
-3 bytes by actually doing what the specs say it should do.
```
import System.Random
f 0=pure[0]
f x=randomRIO(0::Int,x-1)>>=fmap(x:).f
```
[Try it online!](https://tio.run/##HcixCsIwEIDh3ae4sQUN0TE0XZw6FeooDge9aLC5hOSE@PRRuv3f/8Lypm1rzYcUs8DtW4SCWpDXGA4OtE2fTHf9@He1ed/LNHfamInlWE/nfhytC5i6anrlWkDPYCFlzwJ2GMCBgky47niSXCMLsZR20T8 "Haskell – Try It Online")
[Answer]
# IBM/Lotus Notes Formula, 48 bytes
```
o:=i;@While(i>0;i:=@Integer(i*@Random);o:=o:i);o
```
Field formula that takes input from another field `i`.
There's no TIO for formula so here's a screenshot of a sample output:
[![enter image description here](https://i.stack.imgur.com/TfJk4.png)](https://i.stack.imgur.com/TfJk4.png)
[Answer]
# Powershell, ~~36~~ 32 bytes
-4 bytes thanks [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork)
```
filter f{$_;if($_){Random $_|f}}
```
Testscript:
```
filter f{$_;if($_){Random $_|f}}
100 |f
```
Output:
```
100
61
20
8
6
3
0
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 35 bytes
```
for($a="$args";$a;$a=Random $a){$a}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SEMl0VZJJbEovVjJWiURiGyDEvNS8nMVVBI1q1USa////29oYAAA "PowerShell – Try It Online")
Full program. Takes input `$args`, stores it into `$a`, and enters a `for` loop. Each iteration we're checking whether `$a` is still positive (as `0` is falsey in PowerShell). Then we leave `$a` on the pipeline and move to the next iteration, where we set `$a` to be the result of `Get-Random $a`, which returns an integer in the range `0..($a-1)`.
(Ab)uses the fact that PowerShell outputs an additional trailing newline in lieu of outputting the final zero (allowed by the rules as currently written).
] |
[Question]
[
The sequence contains the decimal representation of the binary numbers of the form: `10101...`, where the n-th term has n bits.
The sequence is probably easiest to explain by just showing the relationships between the binary and decimal representations of the numbers:
```
0 -> 0
1 -> 1
10 -> 2
101 -> 5
1010 -> 10
10101 -> 21
101010 -> 42
```
### Challenge:
Take an input integer `n`, and return the first n numbers in the sequence. You may choose to have the sequence 0-indexed or 1-indexed.
### Test cases:
```
n = 1 <- 1-indexed
0
n = 18
0, 1, 2, 5, 10, 21, 42, 85, 170, 341, 682, 1365, 2730, 5461, 10922, 21845, 43690, 87381
```
**Explanations are encouraged, as always.**
This is [OEIS A000975](https://oeis.org/A000975).
[Answer]
# [Python 2](https://docs.python.org/2/), 36 bytes
```
lambda n:[2**i*2/3for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKtpISytTy0jfOC2/SCFTITNPoSgxLz1VI08z9n9BUWZeiUKahqGF5n8A "Python 2 – Try It Online") Explanation: The binary representation of \$\frac{2}3\$ is `0.101010101...` so it simply remains to multiply it by an appropriate power of 2 and take the integer portion.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
2 bytes saved using [Neil's 2/3 trick](https://codegolf.stackexchange.com/a/153797/47066)
```
Lo3÷
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fJ9/48Pb//w0tAA "05AB1E – Try It Online")
**Explanation**
```
L # push range [1 ... input]
o # raise 2 to the power of each
3÷ # integer division of each by 3
```
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
TRI∍ηC
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/JMjzUUfvue3O//8bWgAA "05AB1E – Try It Online")
**Explanation**
```
T # push 10
R # reverse it
I∍ # extend to the lenght of the input
η # compute prefixes
C # convert each from base-2 to base-10
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~...~~ 4 bytes
Thanks *[miles](https://codegolf.stackexchange.com/users/6710)* for -1 byte!
```
ḶḂḄƤ
```
[Try it online!](https://tio.run/##y0rNyan8///hjm0PdzQ93NFybMn///8NDQA "Jelly – Try It Online")
Explanation:
```
Ḷ **Ḷ**owered range, or Un**Ḷ**ength. Get [0, 1, 2, 3, ..., n-1]
Ḃ **Ḃ**it. Get the last bit of each number. [0, 1, 0, 1, ...]
Ƥ for each **Ƥ**refixes [0], [0, 1], [0, 1, 0], [0, 1, 0, 1], ...
Ḅ convert it from **Ḅ**inary to integer.
```
---
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
Jonathan Allan's version.
```
Ḷ€ḂḄ
```
[Try it online!](https://tio.run/##y0rNyan8///hjm2PmtY83NH0cEfL////zQE "Jelly – Try It Online")
```
Ḷ **Ḷ**owered range, or Un**Ḷ**ength.
€ Apply for **€**each. Automatically convert the number **n**
to the range *[1,2,..,n]*. Get *[[0],[0,1],[0,1,2],..]*.
Ḃ **Ḃ**it. Get the last bit from each number.
Current value: *[[0],[0,1],[0,1,0],..]*
Ḅ Convert each list from **Ḅ**inary to integer.
```
---
A version based on Neil's 2/3 trick gives 5 bytes, see revision history.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
:WI/k
```
Based on [Neil's answer](https://codegolf.stackexchange.com/a/153797/36398).
### Explanation
```
: % Implicit input, n. Push range [1 2 ... n]
W % 2 raised to that, element-wise. Gives [2 4 ...2^n]
I % Push 3
/ % Divide, element-wise
k % Round down, element-wise. Implicit display
```
[Try it online!](https://tio.run/##y00syfn/3yrcUz/7/39DCwA "MATL – Try It Online")
---
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
:q"@:oXBs
```
[Try it online!](https://tio.run/##y00syfn/36pQycEqP8Kp@P9/QwsA "MATL – Try It Online")
### Explanation
```
: % Implicit input n. Range [1 2 ... n]
q % Subtract 1, element-wise: gives [0 1 ... n-1]
" % For each k in [0 1 ... n-1]
@ % Push k
: % Range [1 2 ... k]
o % Modulo 2, element-wise: gives [1 0 1 ...]
XB % Convert from binary to decimal
s % Sum. This is needed for k=0, to transform the empty array into 0
% Implicit end. Implicit display
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~45~~ ~~37~~ 36 bytes
-3 bytes thanks to user202729
-1 byte thanks to mathmandan
```
s=0
exec"print s;s+=s+~s%2;"*input()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9jWgCu1IjVZqaAoM69Eodi6WNu2WLuuWNXIWkkrM6@gtERD8/9/QwsA "Python 2 – Try It Online")
[Answer]
# Python 3, ~~68~~ ~~61~~ ~~54~~ ~~48~~ 43 bytes
```
c=lambda x,r=0:x and[r]+c(x-1,2*r+~r%2)or[]
```
Thanks to [user202729](https://codegolf.stackexchange.com/users/69850/user202729) for helping save 19 bytes and [ovs](https://codegolf.stackexchange.com/users/64121/ovs) for helping save 6 bytes.
[Try It Online](https://tio.run/##K6gsycjPM9ZNBtP//yfb5iTmJqUkKlToFNkaWFUoJOalRBfFaidrVOga6hhpFWnXFakaaeYXRcf@LyjKzCvRSNYwtNDU5IJzDDQ1/wMA)
[Answer]
## [Husk](https://github.com/barbuz/Husk), 7 bytes
```
mḋḣ↑Θݬ
```
[Try it online!](https://tio.run/##ARoA5f9odXNr//9t4biL4bij4oaRzpjEsMKs////NQ "Husk – Try It Online")
1-based, so input **n** gives the first **n** results.
### Explanation
```
ݬ The infinite list [1, 0, 1, 0, 1, ...]
Θ Prepend a zero.
↑ Take the first n elements.
ḣ Get the prefixes of that list.
mḋ Interpret each prefix as base 2.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte charater set")
Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems. Anonymous tacit prefix function. 1-indexed.
```
(2⊥⍴∘1 0)¨⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OApIbRo66lj3q3POqYYahgoHloxaPezf//pykYcgGxBQA "APL (Dyalog Unicode) – Try It Online")
`⍳` **ɩ**ndices 0…n−1
`(`…`)¨` apply the following tacit function to each
`⍴∘1 0` cyclically reshape the list `[1,0]` to that length
`2⊥` convert from base-2 (binary) to normal number
[Answer]
# [Perl `v5.10`](https://www.perl.org/) `-n`, 24+1 bytes
-3 bytes thanks to [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)!
```
say$v=$v*2|$|--while$_--
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP2/OLFSpcxWpUzLqEalRle3PCMzJ1UlXlf3/39Di3/5BSWZ@XnF/3XzAA "Perl 5 – Try It Online")
Same logic as my Ruby version, but shorter because perl is more concise. For some odd reason, `print` wouldn't do a seperator (dammit!), so I had to use `say` from `v5.10;` in order for this to run, I'm not sure how to score this, so I'm leaving it out for now?...
## Explanation
```
say # Like shouting, but milder.
$v = $v*2 | $|-- # Next element is this element times 2 bitwise-OR
# with alternating 0 1 0 1..., so 0b0, 0b1, 0b10, 0b101...
# $. is OUTPUT_AUTOFLUSH, which is initially 0 and
# setting all non-zero values seem to be treated as 1
while $_-- # do for [input] times
```
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
l=1:0:l
($scanl((+).(2*))0l).take
```
[Try it online!](https://tio.run/##VYxNC4JAFEX3/oqbtNAScT7USZhN2yIXtYsgyRHFySIN6tfbcxHUW91zLvfVRd8aa8fRapZFmXUq7c37S9FZz1v6occXvh9ZPxyK1owvnPv69rTl2pzxhsb9OeyHx7bDHE2Fl9ZvDLXp4OYbF8b2Bu4uPyDfzFw4zrVoOhqVNwd0Fdjvu2N0@mr17wOwADxATIGAE0lCNXFKQkgyiSLFREKSp4JsLBM2DVacTxslqZEiWVGlUqHYafwA "Haskell – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 7 bytes
```
⌊3÷⍨2*⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPV3Gh7c/6l1hpPWodzNQTMGQC4gtAA "APL (Dyalog Unicode) – Try It Online")
---
# [APL (Dyalog)](https://www.dyalog.com/), 11 bytes
```
(2⊥2|⍳)¨1+⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OApIbRo66lRjWPejdrHlphqA2k//9PUzDkAmILAA "APL (Dyalog Unicode) – Try It Online")
Uses `⎕IO←0`.
[Answer]
# [C](https://en.wikipedia.org/wiki/C_(programming_language)), ~~81 55~~ 59 bytes
1 indexed.
```
i,j;f(c){for(i=j=0;i<c;)printf("%d ",i++&1?j+=j+1:(j+=j));}
```
Full program, less golfed:
```
i;j;main(c,v)char**v;{c=atoi(*++v);for(;i<c;i++)printf("%d ",i&1?j+=j+1:(j+=j));}
```
[Try it online!](https://tio.run/##FctBDsIgEEDRtZyCNNEMDKayM1LiznuQUXRILIYQNk3PTuvqb96n85uodzbJRSC1xFyAffIXxxM59Ss81wjD8SkHw4gne0/oE9ob/KuUW/s4ykfO9VXEbuU38AxkmqJPKFo3t4hDhFAzg0Zs@yHW3u11Aw "C (gcc) – Try It Online")
EDIT 2: I was under the assumption that functions didn't need to be reusable now that I think of it, it makes perfect sense that they would have to be reusable :P
EDIT: I was under the misconception that I had to include the entire program in the answer, turns out I only needed the function that does it. That's nice.
I'm decently sure I can shave off a few bytes here and there. I've already employed a few tricks. A large chunk of the program is dedicated to getting the argument and turning it into an int. This is my first code golf. If I'm doing anything wrong tell me :P
[Answer]
# [Haskell](https://www.haskell.org/), 47 40 53 49 44 40 34 bytes
-4 bytes thanks to user202729
-6 bytes thanks to Laikoni
```
(`take`l)
l=0:[2*a+1-a`mod`2|a<-l]
```
[Try it online!](https://tio.run/##HYo7C8IwFEb3/opbcGgtkbaTSDs4uLl1VCGXNn3QvEiuiuBvN4ae5Tt8nBn9KqQMi7LGEXQfT0IdLvq1OKOV0JSM7T1knHAVXOaJbMvTrd5jUTHkygy8/mLD5CMoXDS0MJgEIugmDw2DSdA56vbZJ3Xkrhp24GfzjjNC5gQO0bY@TaHMQ6iOv36UOPnAemv/ "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes
```
->n{(1..n).map{|i|2**i/3}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9PUy83saC6JrPGSEsrU9@4tvZ/gUKaXnJiTo6GoYXmfwA "Ruby – Try It Online")
Beats all the older ruby answers.
## Explanation
`1/3` in binary looks like `0.01010101...`, so If you multiply it by powers of two, you get:
```
n| 2^n/3
-+---------
1|0.1010101...
2|01.010101...
3|010.10101...
4|0101.0101...
5|01010.101...
6|010101.01...
```
But Ruby floors the numbers on int division, giving me the sequence I need.
[Answer]
# [J](http://jsoftware.com/), 9 bytes
```
[:#.\2|i.
```
## How it works?
`i.` - list 0..n-1
`2|` - the list items mod 2
`\` - all prefixes
`#.` - to decimal
`[:` - caps the fork (as I have even number (4) of verbs)
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62U9WKMajL1/mtyKXClJmfkK6QpGFr8BwA "J – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 28 bytes
```
)K`0
"$+"+¶<`.+
$.(*__2*$-1*
```
[Try it online!](https://tio.run/##K0otycxLNPz/X9M7wYBLSUVbSfvQNpsEPW0uFT0Nrfh4Iy0VXUOt//8NzQE "Retina – Try It Online")
0-based, so input **n** gives the first **n+1** results.
### Explanation
Uses the recursion from OEIS:
```
a(n) = a(n-1) + 2*a(n-2) + 1
```
Let's go through the program:
```
)K`0
```
This is a constant stage: it discards the input and sets the working string to `0`, the initial value of the sequence. The `)` wraps this stage in a group. That group itself does nothing, but almost every stage (including group stages) records its result in a log, and we'll need two copies of the `0` on that log for the program to work.
```
"$+"+¶<`.+
$.(*__2*$-1*
```
There's a bunch of configuration here: `"$+"+` wraps the stage in a loop. The `"$+"` is treated as a substitution, and `$+` refers to the program's input, i.e. **n**. This means that the loop is run **n** times.
Then `¶<` wraps each iteration in an output stage, which prints the stage's *input* with a trailing linefeed (so the first iteration prints the zero, the second iteration prints the first iteration's result and so on).
The stage itself replaces the entire working string with the substitution on the last line. That one makes use of an implicit closing parenthesis and implicit arguments for the repetition operator `*`, so it's actually short for:
```
$.($&*__2*$-1*_)
```
The stuff inside the parentheses can be broken up into three parts:
* `$&*_`: gives a string of **a(n-1)** `_`s.
* `_`: gives a single `_`.
* `2*$-1*_`: gives a string of **2\*a(n-1)** `_`. The `$-1` refers to the penultimate result in the result log, i.e. the loop iteration before the last. That's why we needed to copies of the zero on the log to begin with, otherwise this would refer to the program's input on the first iteration.
Then `$.(…)` measures the length of the resulting string. In other words, we've computed `a(n) = a(n-1) + 1 + 2*a(n-2)` by going through unary (not really though: `$.(…)` is lazy and doesn't actually evaluate its content if it can determine the resulting length directly through arithmetic, so this is even quite efficient).
The result of the final loop iteration (the **n+1**th element of the sequence) is printed due to Retina's implicit output at the end of the program.
[Answer]
# Java 8, ~~115~~ ~~81~~ ~~80~~ 52 bytes
```
n->{for(int i=2;n-->0;i*=2)System.out.println(i/3);}
```
Port of [*@Neil*'s Python 2 answer](https://codegolf.stackexchange.com/a/153797/52210).
1-indexed and outputted directly, each value on a separated line.
**Explanation:**
[Try it online.](https://tio.run/##bY7BDoIwDIbvPkWPm8lQ8WKywBvIhaPxMMcgw9ERNkgM4dnnBI4m7aH9//79WjEJZnuFbfUO0gjn4C40zgcAjV4NtZAKit8IMFldgSTGYgNIedwtsWM5L7yWUABCBgFZPtd2IPEedJZyZCw/c33MUlp@nFddYkef9EPUDRJ9ulK@BL4l9ePLxKQ9cH3YRRxS@mhvHk9BNxRMJLmsCAB/Qndldd120iV8AQ)
```
n->{ // Method with integer parameter and no return-type
for(int i=2; // Start integer `i` at 2
n-->0; // Loop `n` times:
i*=2) // Multiply `i` by 2 after every iteration
System.out.println(i/3);} // Print `i` integer-divided by 3 and a new-line
```
---
**Old 80 bytes answer:**
```
n->{String t="",r=t;for(Long i=0L;i<n;)r+=i.parseLong(t+=i++%2,2)+" ";return r;}
```
1-indexed input and space-delimited `String` output
**Explanation:**
[Try it online.](https://tio.run/##dY/BCsIwDIbvPkUYCC3ToZ6EWp9g7uJRPNRapTrTkWaCyJ59drqrkBCSP@H7czNPMw@Nw9v53tvaxAg74/E9AfDIji7GOqiGFmDP5PEKVtQhFZQqTbuUKSIb9hYqQNDQ43z7HpdZZ9mMNKtLIFEOd14vSuU3qCTl2heNoegGQXBq83y6mq1knkGmyHFLCKS6Xv0oTXuqE2WEPYM/wyOZFT/W4WjkaPQV2T2K0HLRJIVrFFhYsZRfy//1tRx/6voP)
```
n->{ // Method with integer parameter and String return-type
String t="",r=t; // Temp and result-Strings, both starting empty
for(Long i=0L;i<n;) // Loop from 0 to `n` (exclusive)
r+= // Append the result-String with:
i.parseLong( ,2); // Binary to integer conversion
t+= // append the temp-String with:
i %2 // current index `i` modulo-2
++ // and increase `i` by one afterwards
+" "; // + a space
return r;} // Return the result-String
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes
```
{([()]{}<((({}<>)<>){}([{}]()))>)}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1ojWkMztrrWRkNDA0jaaQJRda1GdHVtrIampqadJlDs/38TAA "Brain-Flak – Try It Online")
## Explanation:
The next number in the sequence is obtained by `n*2+1` or `n*2+0`.
```
{([()]{}< Loop input times
(
(({}<>)<>){} Copy n to other stack; n*2
([{}]()) i = 1-i
) push n*2 + i
>)} End loop
<> Output other stack
```
[Answer]
# [Ruby](http://www.ruby-lang.org) ~~42 41 43 41 37 35 31 33~~ 30 bytes
-2 bytes thanks to Unihedron
-3 bytes thanks to G B
```
->x{a=0;x.times{a-=~a+p(a)%2}}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9euojrR1sC6Qq8kMze1uDpR17YuUbtAI1FT1ai29n9atKFF7H8A)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 22 + 3 (-v flag) bytes
```
0:nao::1+2%++$1-:?!;$!
```
[Try it online!](https://tio.run/##S8sszvj/38AqLzHfyspQ20hVW1vFUNfKXtFaRfH///@6ZeYA "><> – Try It Online")
### Explanation
The stack gets initialized with the loop counter.
```
0:nao : Push 0 to the stack, duplicate and print with a new line.
[7] -> [7, 0]
::1+ : Duplicate the stack top twice more then add 1 to it.
[7, 0] -> [7, 0, 0, 1]
2%++ : Mod the stack top by 2 then add all values on the stack bar the loop counter.
[7, 0, 0, 1] -> [7, 1]
$1-:?!;$! : Swap the loop counter to the top, minus 1 from it and check if zero, if zero stop the program else continue.
```
[Answer]
# [Perl 6](https://perl6.org), ~~35 30 27 25~~ 20 bytes
```
{[\~](0,+!*...*)[^$_]».&{:2(~$_)}}
```
[Try it (35)](https://tio.run/##K0gtyjH7X1qcqlBmppdszaVXnFipkJZfpJCSr5CeWZaap6BhaKH5vzo6pi5Ww0BHW1FLT09PSzM6TiU@9tBuPbVqKyONOpV4zdra//8B "Perl 6 – Try It Online")
```
{(0,{$_*2+|($+^=1)}…*)[^$_]}
```
[Try it (30)](https://tio.run/##K0gtyjH7X1qcqlBmppdszaVXnFipkJZfpJCSr5CeWZaap6BhaKH5v1rDQKdaJV7LSLtGQ0U7ztZQs/ZRwzItzeg4lfjY2v//AQ "Perl 6 – Try It Online")
```
{(⅓X*(2,4,8…2**$_))».Int}
```
[Try it (30)](https://tio.run/##K0gtyjH7X1qcqlBmppdszaVXnFipkJZfpJCSr5CeWZaap6BhaKH5v1rjUevkCC0NIx0THYtHDcuMtLRU4jU1D@3W88wrqf3/HwA "Perl 6 – Try It Online")
```
{(⅔,* *2…*)[^$_]».Int}
```
[Try it (27)](https://tio.run/##K0gtyjH7X1qcqlBmppdszaVXnFipkJZfpJCSr5CeWZaap6BhaKH5v1rjUesUHS0FLaNHDcu0NKPjVOJjD@3W88wrqf3/HwA "Perl 6 – Try It Online")
```
{((2 X**1..$_)X/3)».Int}
```
[Try it (25)](https://tio.run/##K0gtyjH7X1qcqlBmppdszaVXnFipkJZfpJCSr5CeWZaap6BhaKH5v1pDw0ghQkvLUE9PJV4zQt9Y89BuPc@8ktr//wE "Perl 6 – Try It Online")
```
{(2 X**1..$_)Xdiv 3}
```
[Try it (20)](https://tio.run/##K0gtyjH7X1qcqlBmppdszaVXnFipkJZfpJCSr5CeWZaap6BhaKH5v1rDSCFCS8tQT08lXjMiJbNMwbj2/38A "Perl 6 – Try It Online")
## Expanded:
```
{
(
2 # 2
X** # cross to the power of
1..$_ # Range from 1 to the input (inclusive)
)
Xdiv # cross using integer divide
3 # by 3
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 33 bytes
```
s=2
exec"print s/3;s*=2;"*input()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9jWiCu1IjVZqaAoM69EoVjf2LpYy9bIWkkrM6@gtERD8/9/MwA "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 34 bytes
```
f=lambda n:n*[f]and[2**n/3]+f(n-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qTys6LTYxLyXaSEsrT984VjtNI0/XUPN/QVFmXolCmkZmXkFpiYam5n8zAA "Python 2 – Try It Online")
Returns in reverse order.
[Answer]
# C, ~~47~~ 46 bytes
```
a;f(n){for(a=0;n--;a+=a-~a%2)printf("%d ",a);}
```
The accumulator `a` begins with zero. At each step, we double it (`a+=a`) and add one if the previous least-significant bit was zero (`!(a%2)`, or equivalently, `-(~a)%2`).
## Test program
```
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
while (*++argv) {
f(atoi(*argv));
puts("");
}
}
```
## Results
```
$ ./153783 1 2 3 4 5 6
0
0 1
0 1 2
0 1 2 5
0 1 2 5 10
0 1 2 5 10 21
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~10~~ ~~9~~ ~~7~~ 6 bytes
All derived independently from other solutions.
1-indexed.
```
õ!²mz3
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SGybXoz&input=OA==)
---
## Explanation
```
õ :[1,input]
!² :Raise 2 to the power of each
m :Map
z3 :Floor divide by 3
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SGybXoz&input=OA==)
---
## 7 byte version
```
õ_ou ì2
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9V9vdSDsMg==&input=OA==)
```
õ :[1,input]
_ :Pass each through a function
o :[0,current element)
u :Modulo 2 on above
ì2 :Convert above from base-2 array to base-10
```
---
## 9 byte version
```
õ_îA¤w)n2
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9V/uQaR3KW4y&input=OAotUQ==)
```
õ :[1,input]
_ :Pass each through a function
A :10
¤ :Convert to binary
w :Reverse
î :Repeat the above until it's length equals the current element
) :Close nested methods
n2 :Convert from binary to base-10
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
RO3÷
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWS4P8jQ9vX1KclFwMFVmwyNACwgIA)
Port of Neil's Python answer.
#### Explanation
```
RO3÷ # Implicit input -> 5
R # Push [1..input] -> [1,2,3,4,5]
O # Two power of each -> [2,4,8,16,32]
3÷ # Integer divide by 3 -> [0,1,2,5,10]
# Implicit output
```
[Answer]
# [Haskell](https://www.haskell.org/), 52 bytes
```
(`take`map a[0..])
a 0=0
a 1=1
a n=a(n-1)+2*a(n-2)+1
```
[Try it online!](https://tio.run/##FcaxDkAwEADQ3VfcYGhJpdfJcl@CxEVaRDUN/X6H5eVtfB8@Rgk0ipoLH34@OQMPtusmXTFYsp9I@JmIVTKoW9f8cbpFOXlPQJCvPRWoIQD28iwh8nqLWXJ@AQ "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
:&+oRXB
```
[Try it online!](https://tio.run/##y00syfn/30pNOz8owun/fwsA "MATL – Try It Online")
**Explanation:**
```
% Implicitly grab input, n
: % Range: 1 2 ... n
&+ % Add the range to itself, transposed
% 2 3 4 5 ...
% 3 4 5 6 ...
% 4 5 6 7 ...
% 5 6 7 8 ...
o % Parity (or modulus 2)
% 0 1 0 1 ...
% 1 0 1 0 ...
% 0 1 0 1 ...
% 1 0 1 0 ...
R % Upper triangular matrix:
% 0 1 0 1
% 0 0 1 0
% 0 0 0 1
% 0 0 0 0
XB % Convert rows to decimal:
% [5, 2, 1, 0]
% Implicitly output
```
The output would be `0, 1, 2, 5 ...` if `P` was added to the end (`flip`), making it 8 bytes.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~32~~ 30+1 bytes
Since we have exactly 1 line of input, `$.` is godly convenient!
EDIT: I'm amazed that I managed to outgolf myself, but it seems using `-n` which counts as 1 (by rule 2 in [default special conditions](https://codegolf.meta.stackexchange.com/a/7539/21830), since Ruby can be run with `ruby -e 'full program'` (thus `-n` is 1) all instances of `gets` which is only used once can be golfed down 1 char this way; I believe this is a milestone for ruby, please speak up if you disagree with this train of thought before I repeatedly reuse it in the future)
```
v=0
?1.upto($_){p v=v*2|$.^=1}
```
[Try it online!](https://tio.run/##KypNqvz/v8zWgMveUK@0oCRfQyVes7pAocy2TMuoRkUvztaw9v9/Q4t/@QUlmfl5xf918wA "Ruby – Try It Online")
## Explanation
```
# while gets(); -- assumed by -n
v=0 # First element of the sequence
?1.upto($_){ # Do from "1" to "$LAST_READ_LINE" aka: Repeat [input] times
p # print expression
v=v*2|$.^=1 # Next element is current element times two
# bitwise-or 0 or 1 alternating
# $. = lines of input read so far = 1 (initially)
}
# end -- assumed by -n
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html) `a=0`, 31 bytes
```
{for(;$1--;a=a*2+1-a%2)print a}
```
[Try it online!](https://tio.run/##SyzP/v@/Oi2/SMNaxVBX1zrRNlHLSNtQN1HVSLOgKDOvRCGx9v9/Q4v/ibYGAA "AWK – Try It Online")
Uses the formula shamelessly stolen from [this other Ruby answer.](https://codegolf.stackexchange.com/a/153788/21830)
While not having `a=0` would work (awk treats "empty" as 0), the first element of 0 won't get printed and instead be an `empty` line, which while I would argue is a valid output probably won't pass, so there's `a=0` which can be inserted as command line argument.
[Answer]
# C, 52 bytes
```
i,k;f(n){for(i=k=0;i<n;k=++i%2+2*k)printf("%d ",k);}
```
1-indexed
[Try it online!](https://tio.run/##DcdBCoAgEADAu68QQdjNgvIUbD4mDGNZspBu4tutuU2czhh751EoQcaa7gIcJMzEWyYJzrH1zg@CT@H8JjD20GYUpNb/62vnDKiq0r8Ey4qkWv8A)
] |
[Question]
[
>
> Note: This challenge is finished. Submissions are still welcome but can not win.
>
>
>
This is the cops' thread. The robbers' thread [goes here](https://codegolf.stackexchange.com/questions/99547/code-ladder-robbers).
Write a code that outputs the integer `1`. If you add, remove or substitute a single character (of your choosing), the code should output the integer `2`. Change one more character (the same or another), and the code should output `3`. Continue like this as far as you can, but maximum up to 10. Default output formats such as `ans = 1` are accepted. You can ignore output to STDERR (or equivalent).
You must reveal the language, byte count of your initial code, the number of integers it works for, as well as an optional number of characters of the initial code. Note: You don't have to reveal any characters, but remember that revealing characters might make it harder for the robbers as they must use the same character in the same position. You can choose which character you use to denote unrevealed characters (for instance underscore), but make sure to specify this.
Cops can provide the uncracked code after one week and call the submission "SAFE". The winning submission will be the shortest uncracked submission that produces the number 10. If no uncracked submissions are able to print 10, the shortest code that produces 9 will win, and so on. Note that the robbers don't have to make the same changes as you do, and they don't have to reproduce the exact code (unless you reveal all characters). They must only reproduce the output.
Submissions posted later than November 24th are welcome but not eligible for the win (because there will likely be fewer robbers around).
---
**Example post:**
The following post is a submission in the language `MyLang`, it is 9 bytes long, and it works for numbers 1 - 8.
# MyLang, 9 bytes, 8 numbers
This submission works for 1 - 8. Unrevealed characters are indicated with an underscore: `_`.
```
abc____i
```
### Leaderboard
Disclaimer: The leaderboard is not tested and uncracked submissions might not appear in the list.
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><style>table th,table td{padding: 5px;}th{text-align: left;}.score{text-align: right;}table a{display: block;}.main{float: left;margin-right: 30px;}.main h3,.main div{margin: 5px;}.message{font-style: italic;}#api_error{color: red;font-weight: bold;margin: 5px;}</style> <script>QUESTION_ID=99546;var safe_list=[];var uncracked_list=[];var n=0;var bycreation=function(x,y){return (x[0][0]<y[0][0])-(x[0][0]>y[0][0]);};var byscore=function(x,y){return (x[0][1]>y[0][1])-(x[0][1]<y[0][1]);};function u(l,o){jQuery(l[1]).empty();l[0].sort(o);for(var i=0;i<l[0].length;i++) l[0][i][1].appendTo(l[1]);if(l[0].length==0) jQuery('<tr><td colspan="3" class="message">none yet.</td></tr>').appendTo(l[1]);}function m(s){if('error_message' in s) jQuery('#api_error').text('API Error: '+s.error_message);}function g(p){jQuery.getJSON('//api.stackexchange.com/2.2/questions/' + QUESTION_ID + '/answers?page=' + p + '&pagesize=100&order=desc&sort=creation&site=codegolf&filter=!.Fjs-H6J36w0DtV5A_ZMzR7bRqt1e', function(s){m(s);s.items.map(function(a){var he = jQuery('<div/>').html(a.body).children().first();he.find('strike').text('');var h = he.text();if (!/cracked/i.test(h) && (typeof a.comments == 'undefined' || a.comments.filter(function(b){var c = jQuery('<div/>').html(b.body);return /^cracked/i.test(c.text()) || c.find('a').filter(function(){return /cracked/i.test(jQuery(this).text())}).length > 0}).length == 0)){var m = /^\s*((?:[^,;(\s]|\s+[^-,;(\s])+).*(0.\d+)/.exec(h);var e = [[n++, m ? m[2]-0 : null], jQuery('<tr/>').append( jQuery('<td/>').append( jQuery('<a/>').text(m ? m[1] : h).attr('href', a.link)), jQuery('<td class="score"/>').text(m ? m[2] : '?'), jQuery('<td/>').append( jQuery('<a/>').text(a.owner.display_name).attr('href', a.owner.link)) )];if(/safe/i.test(h)) safe_list.push(e);else uncracked_list.push(e);}});if (s.items.length == 100) g(p + 1);else{var s=[[uncracked_list, '#uncracked'], [safe_list, '#safe']];for(var i=0;i<2;i++) u(s[i],byscore);jQuery('#uncracked_by_score').bind('click',function(){u(s[0],byscore);return false});jQuery('#uncracked_by_creation').bind('click',function(){u(s[0],bycreation);return false});}}).error(function(e){m(e.responseJSON);});}g(1);</script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=7509797c03ea"><div id="api_error"></div><div class="main"><h3>Uncracked submissions</h3><table> <tr> <th>Language</th> <th class="score">Score</th> <th>User</th> </tr> <tbody id="uncracked"></tbody></table><div>Sort by: <a href="#" id="uncracked_by_score">score</a> <a href="#" id="uncracked_by_creation">creation</a></div></div><div class="main"><h3>Safe submissions</h3><table> <tr> <th>Language</th> <th class="score">Score</th> <th>User</th> </tr> <tbody id="safe"></tbody></table></div>
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 2 bytes, 10 numbers, [Cracked](https://codegolf.stackexchange.com/a/99560/8478)
```
_1
```
Works for 1 to 10, `_` is a hidden character. This shouldn't be too hard, but I hope it provides a somewhat interesting puzzle. :)
[You can try Retina online over here.](http://retina.tryitonline.net/)
[Answer]
# Octave, 55 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99834/24877)
```
(o__(O_o_(@(__o)o__-O}_)_(0<O,{_(_o_O-1)+1_@(_1}_)(__o_
```
`_` is the unknown character.
### Solution
>
> `(o=@(O,o)(@(O,o)o{2-O}())(0<O,{@()o(O-1)+1,@()1}))(0,o)` %then changing the very last `0` to `1,2,3` e.t.c.
>
>
>
>
> Given `x`, this does recursively calculate `x+1`. It is mainly composed of two anonymous functions. One provides an `if` statement to anchor the recursion:
>
>
>
>
> `if_ = @( boolean, outcomes) outcomes{ 2 - boolean}();`
>
>
>
>
> This is just abusing the fact that a boolean values evaluates to `0` or `1`. This function accepts a boolean value, and a cell array of two functions, and evaluates one or the other of these two functiosn depending on the boolean value. The second part is the actual recursion:
>
>
>
>
> `plus_one = @(n,f) if_(0<n ,{@()f(n-1)+1, @()1})`
>
>
>
>
> As an anyonmous function is anonymous, you cannot directly access it from itsefl. That why we need a second argument `f` first. Later we will provide a handle to the function instelf as a second argument, so a final function would looks like so:
>
>
>
>
> `plus_one_final = @(n)plus_one(n,plus_one);`
>
>
>
>
> So in this notation my submission becomes:
>
>
>
>
> `(plus_one=@(n,f)(@(boolean,outcomes)outcomes{2-boolean}())(0<n,{@()f(n-1)+1,@()1}))(n,f)`
>
>
>
>
> I asked about recursion anchors for anonymous functions in MATLAB a while ago on [stackoverflow](https://stackoverflow.com/a/32268411/2913106).
>
>
>
[Answer]
## Python 2, 9 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/100039/20260)
```
print 8/8
```
No hidden chars. Can you crack it without brute forcing?
[Answer]
# Perl, 12 bytes, 10 numbers, [Cracked!](https://codegolf.stackexchange.com/a/99760/62131)
Underscores represent unknown characters.
```
____;say__-9
```
Probably fairly easy, and it wouldn't surprise me if there were multiple solutions. Still, it might be fun to crack.
(The intended solution was the same as the crack. This is fundamentally just a problem about assigning 10 to a variable in four characters, which is surprisingly difficult in Perl; unlike many golfing languages, it doesn't have a variable that helpfully starts at 10.)
[Answer]
# Perl, 46 bytes, 10 numbers, safe
## The problem
```
__b_b_\__}_b_b_b_0_;
$b[0]=10;$b{0}=1;say$b[0]
```
The shorter problems tend to get cracked quickly, so I thought I'd try a longer one. The longer ones also tend to get cracked if people leave enough of a gap to sneak something naughty like `say` or `exit` in, so all the gaps here are short. Hidden characters are represented using `_`.
## My solution
```
sub b{\@_}*b=b$b{0};
$b[0]=10;$b{0}=1;say$b[0]
```
To print 2, 3, etc., up to 9, keep changing the number assigned to `$b{0}` in the second line (i.e. `$b{0}=2`, `$b{0}=3`, etc.). The program for 9 looks like this:
```
sub b{\@_}*b=b$b{0};
$b[0]=10;$b{0}=9;say$b[0]
```
Then to produce 10, comment out the first line by prepending a `#` character to it.
## Explanation
The first thing to note is that the solution isn't really golfed apart from removing whitespace: if we lay it out with more readable whitespace, we get this:
```
sub b { \@_ }
*b = b $b{0};
$b[0] = 10;
$b{0} = 1;
say $b[0];
```
Normally, when you access the arguments of a subroutine in Perl, you do so via copying them out of `@_`. There's a good reason for this: `@_` aliases the arguments the subroutine is given (so, for example, `(sub { $_[0] = 3 })->($x)` will assign to `$x`), something that isn't normally desirable.
Although `@_` might seem magical, it's actually just using a standard feature of the Perl internals (which is readily available from XS but only comes up in a few weird cases in pure Perl, such as `@_` itself): an array doesn't store its elements directly, but rather by reference. Thus, when we call `b` in the second line below, Perl generates an array (calling it `@_`) whose first element is a reference to the same storage that `$b{0}` uses. (Hash values are also stored by reference; $\_[0] and $b{0} are both referencing the same storage at this point.) Because `@_` isn't doing anything special from an internals point of view, we can take a reference to it just like we could with any other array, causing it to outlive the subroutine it's defined in.
Perl variables *also* refer to data storage by reference. A long time ago, people used to use code like `*x = *y;` to set `$x` as an alias to `$y` (via making them reference the same thing), likewise `@x` as an alias to `@y`, `%x` as an alias to `%y`, and so on. That rather breaks the invariant that variables with similar names don't have to act similarly, so modern Perl provides an alternative; assigning a reference to a typeglob overrides only the variable that matches the type of the reference (so `*x = \%y` would alias `%x` to point to the same storage as `%y` but leave, say, `$x` alone). This syntax notably doesn't care about whether the storage you're aliasing to has a name, so when we assign the return value of `b` (which is an array reference that's keeping the array formerly called `@_` alive) to `*b`, what happens is that `@b` is changed to alias the argument list to the call to `b` (while leaving `%b` unchanged). This means, notably, that `$b[0]` and `$b{0}` now point to the same storage, and assigning to one will therefore change the other. Everything from then on is completely straightforward.
The Perl documentation doesn't really talk about this sort of detail, so I'm not surprised anyone got the crack; the nature of `@_` as not quite being like other arrays isn't something that's really emphasised, and most coding styles aim to minimize the effects that this has rather than amplifying them.
[Answer]
# JavaScript, 30 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99566/42545)
```
alert(Array(_)________.length)
```
Shouldn't be too hard, but hopefully it's just hard enough to provide a challenge. :) Unrevealed characters are marked with `_`.
[Answer]
## Perl, 14 bytes, 10 numbers, [Cracked](https://codegolf.stackexchange.com/a/99619/55508)
```
say_!"___"%""_
```
Works for 1 to 10. `_` are hidden characters.
I think this shouldn't be too hard to crack. I have an harder one, for 22 bytes, I'll post it if this one is cracked.
---
Original code :
```
say"!"=~y"%""c
```
And replace the `"!"` by a string of the length of the number you wish to print, for instance `!`, `!!`, `!!!`, etc.
However, [ais523](https://codegolf.stackexchange.com/users/62131/ais523) found another way :
```
say"!"+1#"%""r
```
[Answer]
## JavaScript, 22 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99759)
Probably rather easy to crack.
```
alert(__14_337__xc_de)
```
`_` being a hidden character
[Answer]
# Octave, 17 bytes, 10 numbers, [Cracked](https://codegolf.stackexchange.com/a/99647/24877)
```
_od(3_13_13_7_1_)
```
Original solution
>
> `mod(3*1361357,10)`
>
>
> `...`
>
>
> `mod(3*1361357,17)`
>
>
> `mod(3*1361397,17)`
>
>
> `mod(9*1361397,17)`
>
>
>
`_` is the hidden character.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99666/53748)
```
“1‘ỌȮḊ‘
```
No wildcards.
The crack achieved (to use an eval with an argument) was, as many seem to be in this thread, not the intended one.
The intended crack was:
```
“1‘ỌȮḊ‘ - (prints 1)
“1‘ - code page index list of characters "1": [49]
Ọ - cast to ordinals: ['1']
Ȯ - print (with no line feed) and return input: effectively prints "1"
- (but if left at this would then implicitly print another "1")
Ḋ - dequeue: []
‘ - increment (vectorises): []
- implicit print: prints ""
“1‘ỌŒḊ‘ - (prints 2)
“1‘Ọ - as above: ['1']
ŒḊ - depth: 1
‘ - increment: 2
- implicit print: prints "2"
“1‘ỌŒḊ‘‘ - (prints 3)
“1‘ỌŒḊ‘ - as above: 2
‘ - increment: 3
- implicit print: prints "3"
... keep adding an increment operator to print 4 - 10.
```
[Answer]
# Befunge-93, 11 bytes, 10+ numbers, [Cracked](/a/99901/21487)
This submission works for at least 1 - 10. Unrevealed characters are indicated with `‚ñ°`.
```
‚ñ°‚ñ°5:**-‚ñ°-.@
```
[Try it online](http://befunge.tryitonline.net/)
I must say I was impressed that two people could come up with independent solutions for this, neither of which were what I was expecting. While [Martin](/a/99649/8478) got there first, I'm giving the "win" to [Sp3000](/a/99901/21487) as their solution is more portable.
This was my intended solution though:
>
> `g45:**-2-.@`
>
> `g45:**-1-.@`
>
> `g45:**-1\.@`
>
> `g45:**-1\+.@`
>
> `g45:**-2\+.@`
>
> `...`
>
> `g45:**-7\+.@`
>
>
>
> Because a stack underflow in Befunge is interpreted as 0, the `g` just reads from 0,0 returning the ASCII value of 'g', namely 103. `45:**-` subtracts 100, giving you 3. Then `2-` gives you 1.
>
>
>
> For the third iteration, the `-` (subtract) is changed to a `\` (swap) instruction, so the 3 becomes the topmost stack entry. And in iteration four, a `+` (add) instruction is inserted, thus adding the 3 to the 1 giving 4.
>
>
>
[Answer]
# R, 21 bytes, 10 numbers [Cracked](https://codegolf.stackexchange.com/a/99890/62252)
```
__i___________i______
```
Works for 10 numbers. `_` is hidden character.
Original solution:
>
> `which(letters%in%"a")`
>
>
> `which(letters%in%"b")`
>
>
> etc.
>
>
>
[Answer]
# Ruby, 16 bytes, 10 numbers, [cracked by xsot](https://codegolf.stackexchange.com/a/100144/6828)
```
x=##/=#%#
)
###x
```
`#` is any character.
[Answer]
# Octave, 32 bytes, 10 numbers. [Cracked](https://codegolf.stackexchange.com/a/99572/36398)
```
_n_(isprime(floor(s____i__ i____
```
`_` is a hidden character.
You can try Octave online [here](https://octave-online.net/).
---
Original solution:
1: `nnz(isprime(floor(sqrt(i):pi')))`
2: `nnz(isprime(floor('sqrt(i):pi')))`
3: `nnz(isprime(floor('sqrt(i):pia')))`
4: `nnz(isprime(floor('sqrt(i):piaa')))`
...
[Answer]
# Octave, 17 bytes, 10 numbers, [Cracked](https://codegolf.stackexchange.com/a/99618/31516)
```
_i_(__i__(2_5_))
```
Unrevealed characters are marked with `_`.
Intended solution:
>
>
> ```
>
> fix(asind(2/59))
> fix(asind(3/59))
> fix(asind(4/59))
> fix(asind(5/59))
> fix(asind(6/59))
> fix(asind(7/59))
> fix(asind(8/59))
> fix(asind(9/59))
> fix(asind(9/55))
> fix(asind(9/50))
> ```
>
>
>
>
[Answer]
# Octave, 19 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99631/24877)
```
__sca__1_)___'-_6_'
```
`_` is the hidden character.
Intended solution:
>
> pascal(10)('a'-96)'
>
>
>
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes, 10 numbers, [cracked!](https://codegolf.stackexchange.com/a/99657/56258)
Not very hard, but a fun one :)
```
_[==_
```
`_` is a random character. Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=X1s9PV8&input=)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99670/58106)
Attempt 2, this time without the three-char string :p.
```
_ [==_
```
`_` is a random character. Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=XyBbPT1f&input=)
[Answer]
## JavaScript, 22 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99708/58563)
```
alert(0_6_4_>_0_2_0_7)
```
`_` is the hidden character.
### Hint about the intended solution
The character that needs to be changed to generate all numbers is always the same.
[Answer]
## JavaScript 21 Bytes, 10 Numbers [Cracked](https://codegolf.stackexchange.com/a/99817/43545)
```
alert(b_oa_"3____1"))
```
Unrevealed characters are marked with `_`
[Cracked](https://codegolf.stackexchange.com/a/99817/43545)
My Version:
```
alert(btoa|"3"&("1"))
alert(btoa|"3"^("1"))
alert(btoa|"3"^("0"))
alert(btoa|"3"^("7"))
alert(btoa|"2"^("7"))
alert(btoa|"1"^("7"))
alert(btoa|"0"^("7"))
alert(btoa|"0"^("8"))
alert(btoa|"0"^("8"))
alert(btoa|"2"^("8"))
```
[Answer]
## Python 3, 19 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99811/21487)
```
print(??bin()?????)
```
Unrevealed characters are marked with `?`. Tested in Python 3.5.2.
[Answer]
## Python 3, 16 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99872/21487)
```
print(?%??f?r?t)
```
Unrevealed characters are marked with `?`. This is probably a bit easy since there's only five question marks, but I'm hoping it'll be a fun one.
[Answer]
# C#, 90 bytes, 10 numbers, [cracked](https://codegolf.stackexchange.com/a/99977/54142)
```
using ______________________________________________;class C{static void Main(){_______;}}
```
I honestly have no idea how hard this is to crack.
Edit: Oops, transcription error. One `_` too few after `using`.
Now [cracked](https://codegolf.stackexchange.com/a/99977/54142) by [Hedi](https://codegolf.stackexchange.com/users/58765/hedi), who found the intended (barring the class name) solution.
[Answer]
## JavaScript 33 Bytes, 10 Numbers [Cracked x2](https://codegolf.stackexchange.com/a/100095/43545)
Oops I post posted my line for generating 10 Which Hedi [cracked](https://codegolf.stackexchange.com/a/100095/43545) as though it was for 1
```
alert(_to__"_Xc0__0_B6____Zp=="))
```
Version intended to post for generating 1
```
alert(_to__"_Xc0__0_Bf____Zp=="))
```
Unrevealed characters are marked with `_`
```
alert(btoa|"0Xc0"-0xBf|!("Zp=="))
alert(btoa|"0Xc0"-0xBe|!("Zp=="))
alert(btoa|"0Xc0"-0xBd|!("Zp=="))
alert(btoa|"0Xc0"-0xBc|!("Zp=="))
alert(btoa|"0Xc0"-0xBb|!("Zp=="))
alert(btoa|"0Xc0"-0xBa|!("Zp=="))
alert(btoa|"0Xc0"-0xB9|!("Zp=="))
alert(btoa|"0Xc0"-0xB8|!("Zp=="))
alert(btoa|"0Xc0"-0xB7|!("Zp=="))
alert(btoa|"0Xc0"-0xB6|!("Zp=="))
```
[Answer]
# Python, 10+ numbers, 61 bytes, [Cracked!](https://codegolf.stackexchange.com/questions/99547/code-ladder-robbers/100537#100537)
Here was the code I posted:
```
try:x
except:print(__import__('sys').??c??n??()[????b????e???
```
The original code was:
```
try:x
except:print(__import__('sys').exc_info()[2].tb_lineno)
```
Basically, it throws an error (`'x' is not defined`) and then prints the line the error was found on. So, just keep adding newlines at the beginning to increment the number.
I knew it wouldn't be hard to crack - I just wanted a funny way to print numbers - but I wasn't expecting Sp3000 to get it so fast, that's some pro skills!
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 18 Bytes, 10 numbers, SAFE
This submission works for 1 - 10. Unrevealed characters are indicated with an underscore: `_`.
```
.__{_]5[$@.;=@$!!1
```
[You can try Hexagony online over here.](http://hexagony.tryitonline.net/)
# My solution:
```
1: .<[{8]5[$@.;=@$!!10
2: .<[{8]5[$@);=@$!!10
3: 2<[{8]5[$@);=@$!!10
4: 3<[{8]5[$@);=@$!!10
5: 4<[{8]5[$@);=@$!!10
6: 5<[{8]5[$@);=@$!!10
6: 7<[{8]5[$@);=@$!!10
8: 7<[{8]5[$@);=@$!!10
9: 8<[{8]5[$@);=@$!!10
10: 9<[{8]5[$@);=@$!!10
```
---
**Hex for output 1:**
[Try it Online!](http://hexagony.tryitonline.net/#code=ICAuIDwgWyAKIHsgOCBdIDUKWyAkIEAgLiA7CiA9IEAgJCAhIAogICEgMSAw&input=)
```
Full Hex:
. < [
{ 8 ] 5
[ $ @ . ;
= @ $ !
! 1 0
Important parts:
. < .
. 8 . 5
. $ @ . ;
. . $ .
. 1 .
```
1. At the `<` the memory edge is `0`, so it turns up.
2. Hits `1`
3. Jumps to `5`
4. Jumps over `8`, but is reversed at `<` and gets the `8` on the way back.
5. Hits `5` again
6. Jumps over `1`
7. Hits the `<` at this point, the memory value is 1585 which, mod 256, happens to be ASCII `1`
8. Finally prints and exits with `;@`.
---
**Hex for output 2:**
[Try it Online!](http://hexagony.tryitonline.net/#code=ICAuIDwgWyAKIHsgOCBdIDUKWyAkIEAgKSA7CiA9IEAgJCAhIAogICEgMSAw&input=)
```
Important parts:
. < .
. 8 . 5
. $ @ ) ;
. . $ .
. 1 .
```
This follows the same path, but on the way back it hits a `)` which increments the memory edge to 1586, or `2`.
---
**Hex for output 3-9:**
[Try it Online!](http://hexagony.tryitonline.net/#code=ICAyIDwgWyAKIHsgOCBdIDUKWyAkIEAgKSA7CiA9IEAgJCAhIAogICEgMSAw&input=)
```
Important parts:
2 < [
. . ] .
. $ . ) .
. @ . !
. 1 .
```
1. Hits the `2`
2. Now the memory edge is positive when it gets to `<`, so it turn down.
3. The `]` changes the instruction pointer, but is immediately comes back with `[`
4. `)` increments to `3`
5. `!` Prints `3`
6. `$` is left over from the first two numbers so we jump over the end (`@`)
7. `1` changes the memory edge, but that doesn't matter now.
8. `<` reflects the pointer back.
9. Again `1` doesn't matter because we hit `@` to end the program.
[Answer]
# 05AB1E, 11 bytes, [Cracked!](https://codegolf.stackexchange.com/questions/99547/code-ladder-robbers/99580#99580)
```
3628801__0_
```
Works from 1-10. `_` is a hidden character.
### Intended Solution:
```
3628801R¬0+ # 1
3628801R¬1+ # 2
3628801R¬2+ # 3
3628801R¬3+ # 4
3628801R¬4+ # 5
3628801R¬5+ # 6
3628801R¬6+ # 7
3628801R¬7+ # 8
3628801R¬8+ # 9
3628801R¬9+ # 10
```
[Answer]
# Octave, 24 bytes, 9 numbers, [cracked](https://codegolf.stackexchange.com/a/99606/24877)
```
_a__repmat(__one___,__)_
```
`_` is a hidden character.
(Inspired by @LuisMendo's [challenge](https://codegolf.stackexchange.com/a/99582/24877).)
[Answer]
# JavaScript, 9 bytes, 10 numbers, [Cracked](https://codegolf.stackexchange.com/a/99612/58765)
```
alert(__)
```
`_` is the hidden character.
[Answer]
# Octave, 25 bytes, 9 numbers. [Cracked](https://codegolf.stackexchange.com/questions/99547/code-ladder-robbers/99600#99600)
```
__a__repmat(__one___,__)_
```
`_` is a hidden character.
] |
[Question]
[
Your task is to make a program that takes in an integer `n > 1`, and outputs the roll of a single `n`-sided die. However, this dice follows the rules for [exploding dice](https://anydice.com/articles/exploding-dice/).
When you roll the die, check what value you rolled. If you got the maximum for that kind of die (on a standard d4 that would be 4, or 6 on a d6, etc.), roll again and add the new roll to that total. Each roll continues adding to the total, until you don't roll the max number anymore. That final number is still added though.
Your program should take in a single integer `n`, and roll the exploding `n`-sided die. [Here's an example distribution to show what it should look like for `n=4`](https://paste.ee/p/FKVN4)[.](https://www.youtube.com/watch?v=dQw4w9WgXcQ) Note that you should never output any multiples of `n`, since they will always explode.
You can assume the stack size for any recursion you do is infinite, and your random function [must meet our standards for randomness](https://codegolf.meta.stackexchange.com/questions/1324/standard-definitions-of-terms-within-specifications/1325#1325) (built-in random generator or [time/date](https://codegolf.meta.stackexchange.com/questions/13029/is-the-current-time-or-date-with-modulo-random-enough)). Your random function should also be as uniform as possible, vs. something like a geometric distribution, since these are dice we're talking about.
[Answer]
# x86 Machine Code (for Intel Ivy Bridge and later), 17 bytes
```
31 C9 0F C7 F0 31 D2 F7 F6 42 01 D1 39 F2 74 F2 C3
```
The above bytes of code define a function that simulates an exploding die. It takes a single input, passed in the `ESI` register, indicating the maximum number of the die. It returns a single value in the `ECX` register, which is the result of the rolls.
Internally, it uses [the `RDRAND` instruction](https://en.wikipedia.org/wiki/RdRand) to generate a random number. This uses a random number generator (RNG) that is built into the hardware on Intel Ivy Bridge processors and later (some AMD CPUs also support this instruction).
The logic of the function is otherwise quite straightforward. The generated random number is scaled to lie within the desired range using the standard technique (`(rand % dieSize) + 1`), and then it is checked to see if it should cause an explosion. The final result is kept in an accumulator register.
Here is an annotated version showing the assembly language mnemonics:
```
unsigned int RollExplodingDie(unsigned int dieSize)
31 C9 xor ecx, ecx ; zero-out ECX, which accumulates the final result
Roll:
0F C7 F0 rdrand eax ; generate a random number in EAX
31 D2 xor edx, edx ; zero-out EDX (in preparation for unsigned division)
F7 F6 div esi ; divide EDX:EAX by ESI (the die size)
; EAX receives the quotient; EDX receives the remainder
42 inc edx ; increment the remainder
01 D1 add ecx, edx ; add this roll result to the accumulator
39 F2 cmp edx, esi ; see if this roll result should cause an explosion
74 F2 jz Roll ; if so, re-roll; otherwise, fall through
C3 ret ; return, with result in ECX register
```
I am cheating *a bit*. All standard x86 calling conventions return a function's result in the `EAX` register. But, in true machine code, there are no calling conventions. You can use any registers you want for input/output. Using `ECX` for the output register saved me 1 byte. If you want to use `EAX`, insert a 1-byte `XCHG eax, ecx` instruction immediately before the `ret` instruction. This swaps the values of the `EAX` and `ECX` registers, effectively copying the result from `ECX` into `EAX`, and trashing `ECX` with the old value of `EAX`.
**[Try it online!](https://tio.run/##dVNba8IwFH7vrzhUhHa6G9uTusEuHfRhDqyDMYRSk9idEdOSpEMm/vV1idWOancemvZ833dybiWnKSFlWQiFqWAUUGiYZJwHq5xnFEX6iMxroBRZhN/Md9YOGKsxyVTB9XDrjONELePYc2d6lUluPN0uI6t@dcyEu2XtzZ1m@eDIOdOSykRQq0lWLfBfZFpFpm0sil87lsIWGAWpg7TACaXNO0gbiyzz@o7/M/n83r6ZYg/AAbg3xAWv6qAPcH4CWaHzQpumpqg0k4AKgoc3ODk/EEYugLcfiRWisLqmMAqPhTZJt3YYYa0gPJvPzcnNJxwI/Wq@kulCinrkm7Jj@1hQBiOlKcf52cet0/BhZl1Oh7IFCgaPYRBH4XsATbuuCePX5/tgEr88xeE0mNxNw5dxZAiXF45jl3CZoPB2K7jIJHjK1B9rQLiBi6E5Rq0RhtDroW9F611VuTThFp5rdx66V3Qw0@ZpBtQHM8qjP2Gft181YmNK/yELnqSqPF2afRX0Fw "C (gcc) – Try It Online")**
Here's the equivalent function transcribed in C, using [the `__builtin_ia32_rdrand32_step` intrinsic](https://gcc.gnu.org/onlinedocs/gcc/x86-Built-in-Functions.html) supported by GCC, Clang, and ICC to generate the `RDRAND` instruction:
```
#include <immintrin.h>
unsigned int RollExplodingDie(unsigned int dieSize)
{
unsigned int result = 0;
Roll:
unsigned int roll;
__builtin_ia32_rdrand32_step(&roll);
roll = ((roll % dieSize) + 1);
result += roll;
if (roll == dieSize) goto Roll;
return result;
}
```
Interestingly, [GCC with the `-Os` flag transforms this into almost exactly the same machine code](https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:0.8957951999999999,j:1,lang:c%2B%2B,source:'%23include+%3Cimmintrin.h%3E%0A%0Aunsigned+int+RollExplodingDie(unsigned+int+dieSize)%0A%7B%0A++++unsigned+int+result+%3D+0%3B%0ARoll:%0A++++unsigned+int+roll%3B%0A++++__builtin_ia32_rdrand32_step(%26roll)%3B%0A++++roll++++%3D+((roll+%25+dieSize)+%2B+1)%3B%0A++++result+%2B%3D+roll%3B%0A++++if+(roll+%3D%3D+dieSize)+++goto+Roll%3B%0A++++return+result%3B%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:48.91472868217055,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g83,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:0.8957951999999999,lang:c%2B%2B,libs:!(),options:'-m64+-mrdrnd+-Os',source:1),l:'5',n:'0',o:'x86-64+gcc+8.3+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),header:(),k:51.08527131782946,l:'4',m:100,n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4). It takes the input in `EDI` instead of `ESI`, which is completely arbitrary and changes nothing of substance about the code. It must return the result in `EAX`, as I mentioned earlier, and it uses the more efficient (but larger) `MOV` instruction to do this immediately before the `RET`. Otherwise, samezies. It's always fun when the process is fully reversible: write the code in assembly, transcribe it into C, run it through a C compiler, and get your original assembly back out!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~66~~ ~~64~~ 61 bytes
-3 bytes thanks to xnor
```
f=lambda n,c=0:c%n or c+f(n,randint(1,n))
from random import*
```
[Try it online!](https://tio.run/##PYpBCsMgFAXX8RRvE9DWRRuyKKEe5sdUIsSvfITQ09ski64GZqZ865p5aC24jdK8ENh695h8z8gCfw@arRAvkat@WjZGBckJpzoQU8lSb41c0KNRRc6NjNrXuH1AeOM1qY7gcPXuP7Qf "Python 2 – Try It Online")
The previous roll is stored in `c`, allowing us to access it multiple times without having to store it to a variable, which can't be done in a Python lambda. Each recursion, we check if we rolled exploding dice.
`c` is initialised to zero, so `c%n` is falsey there. In the next iterations, it will only be falsey if exploding dice were rolled.
# [Python 2](https://docs.python.org/2/), 55 bytes
```
f=lambda n:randint(1,n)%n or n+f(n)
from random import*
```
[Try it online!](https://tio.run/##PYtBCsMgFAXXeoq3CWibTUIWIdTD/GJFIX7lI4Sc3jZZdDWLmalni4Xn3oPbKb89gTch9ombmUa2A6MI@BkMWx2kZFz2h5Rrkfbo5IJZrK5yHWT1EdP@AeGFddOK4HB79Q/6Fw "Python 2 – Try It Online")
My other answer seems to be a bit overengineered, since this appears to work as well... I'll leave it anyway.
[Answer]
# [R](https://www.r-project.org/), 39 bytes
```
n=scan();n*rgeom(1,1-1/n)+sample(n-1,1)
```
[Try it online!](https://tio.run/##RchBCoAgEADAe6/ouFtKCHUKH2OyhmBbqEEQvd3s1HEmFqfdyTb7neESyRr@jRfehfWXgDN3caV9AyWUVANjn8x2BAKWdbA8TTZLZaQjeGsygaJJtA5GRGzKCw "R – Try It Online")
Explanation: this solution avoids recursion/while loops by directly calculating the distribution of the number of explosions that will occur. Let \$n\$ be the number of sides on the die. If you denote success as rolling an \$n\$ and failure as rolling anything else, then you have probability \$\frac1n\$ of success. The total number of explosions is the number of successes before the first failure. This corresponds to a \$\mathrm{Geometric}\left(1-\frac{1}{n}\right)\$ distribution (see the [wikipedia page](https://en.wikipedia.org/wiki/Geometric_distribution), which defines success and failure the other way round). Each explosion brings \$n\$ to the total. The final roll follows a \$\mathrm{Uniform}(1,2,\ldots,n-1)\$ distribution which we add to the total.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 26 bytes
```
{sum {roll 1..$_:}...*-$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0V6G6KD8nR8FQT08l3qpWT09PS1clvvZ/cWKlQpqGiaZCWn6RQpyhgfV/AA "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
... # Sequence constructor
{roll 1..$_:} # Next elem is random int between 1 and n
# (Called as 0-ary function with the original
# $_ for the 1st elem, then as 1-ary function
# with $_ set to the previous elem which
# equals n.)
*-$_ # Until elem not equal to n (non-zero difference)
sum # Sum all elements
```
[Answer]
# [J](http://jsoftware.com/), ~~16~~ 11 bytes
```
(+$:)^:=1+?
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjYKBgBcS6egrOQT5u/zW0Vaw046xsDbXt/2tyWSpaGSrY6GnrmylaGSioq3OVJIO0GRopK2krmCiYKphxpSZn5Cto6KRpAkVKkv8DAA "J – Try It Online")
## Explanation
**TL;DR** `1+?` performs the die roll, `(+$:)^:=` reiterates only when it equals the input.
---
The function is a train of 4 verbs:
```
┌─ +
┌───┴─ $:
┌─ ^: ─┴─ =
│
──┤ ┌─ 1
└──────┼─ +
└─ ?
```
A train is when 2 or more verbs are concatenated. Here, the answer is of the form `f g h j`:
```
(+$:)^:= 1 + ?
f g h j
```
A so-called "4-train" is parsed as a hook and a fork:
```
f g h j ⇔ f (g h j)
```
Thus, the answer is equivalent to:
```
(+$:)^:= (1 + ?)
```
### Hooks: `(f g) x` and `x (f g) y`
A monadic (one-argument) hook of two verbs, given an argument `x`, the following equivalence holds:
```
(f g) x ⇔ x f (g x)
```
For example, `(* -) 5` evaluates to `5 * (- 5)`, which evaluates to `_25`.
This means that our 4-train, a hook of `f` and `(g h j)`, is equivalent to:
```
(f (g h j)) x ⇔ x f ((g h j) x)
```
But what does `f` do here? `(+$:)^:=` is a conjunction of two verbs using the **Power** conjunction `^:`: another hook (`(+$:)`) and a verb (`=`). Note here that `f` is *dyadic*—it has two arguments (`x` and `(g h j) x`). So we have to look at how `^:` behaves. The power conjunction `f^:o` takes a verb `f` and either a verb or a noun `o` (a noun is just a piece of data) and applies `f` `o` times. For example, take `o = 3`. The following equivalences holds:
```
(f^:3) x ⇔ f (f (f x))
x (f^:3) y ⇔ x f (x f (x f y))
```
If `o` is a verb, the power conjunction will simply evaluate `o` over the arguments and use the noun result as the repeat count.
For our verb, `o` is `=`, the equality verb. It evaluates to `0` for differing arguments and to `1` for equal arguments. We repeat the hook `(+$:)` once for equal arguments and no times for differing ones. For ease of notation for the explanation, let `y ⇔ ((g h j) x)`. Remember that our initial hook is equivalent to this:
```
x (+$:)^:= ((g h j) x)
x (+$:)^:= y
```
Expanding the conjunction, this becomes:
```
x ((+$:)^:(x = y)) y
```
If `x` and `y` are the same, this becomes:
```
x (+$:)^:1 y ⇔ x (+$:) y
```
Otherwise, this becomes:
```
x (+$:)^:0 y ⇔ y
```
Now, we've seen monadic forks. Here, we have a dyadic fork:
```
x (f g) y ⇔ x f (g y)
```
So, when `x` and `y` are the same, we get:
```
x (+$:) y ⇔ x + ($: y)
```
What is `$:`? It refers to the entire verb itself and allows for recursion. This means that, when `x` and y`are the same, we apply the verb to`y`and add`x` to it.
### Forks: `(g h j) x`
Now, what does the inner fork do? This was `y` in our last example. For a monadic fork of three verbs, given an argument `x`, the following equivalence hold:
```
(g h j) x ⇔ (g x) h (j x)
```
For this next example, suppose we have verbs named `SUM`, `DIVIDE`, and `LENGTH`, which do what you suppose they might. If we concatenate the three into a fork, we get:
```
(SUM DIVIDE LENGTH) x ⇔ (SUM x) DIVIDE (LENGTH x)
```
This fork evaluates to the average of `x` (assuming `x` is a list of numbers). In J, we'd actually write this as example as `+/ % #`.
One last thing about forks. When the leftmost "tine" (in our symbolic case above, `g`) is a noun, it is treated as a constant function returning that value.
With all this in place, we can now understand the above fork:
```
(1 + ?) x ⇔ (1 x) + (? x)
⇔ 1 + (? x)
```
`?` here gives a random integer in the range \$[0,x)\$, so we need to transform the range to represent dice; incrementing yields the range \$[1, x]\$.
### Putting it all together
Given all these things, our verb is equivalent to:
```
((+$:)^:=1+?) x ⇔ ((+$:)^:= 1 + ?) x
⇔ ((+$:)^:= (1 + ?)) x
⇔ x ((+$:)^:=) (1 + ?) x
⇔ x ((+$:)^:=) (1 + (? x))
⇔ x (+$:)^:(x = (1 + (? x))
(let y = 1 + (? x))
if x = y ⇒ x + $: y
otherwise ⇒ y
```
This expresses the desired functionality.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
X+ß}¥=¡
```
[Try it online!](https://tio.run/##y0rNyan8/z9C@/D82kNLbQ8t/P//vxkA "Jelly – Try It Online")
Uses recursion. Runs the program again (`ß`) and adds (`+`) if (`¡`) the random number (`X`) is equal (`=`) to the program input. `}` makes `ß` act on the program input and `¥` combines `+ß}` into a single link for `¡` to consume.
Here a distribution of 1000 outputs for n=6 which I collected using [this](https://tio.run/##AScA2P9qZWxsef//WCvDn33CpT3Cof874bi3L8OHJCQxMDAwwqHhuIr//zY) program. Plotted with python/matplotlib.
[![histogram](https://i.stack.imgur.com/a2GNL.png)](https://i.stack.imgur.com/a2GNL.png)
Here is a 5000 data points from n=3 on a semilog plot which shows the (approximately?) exponential distribution.
[![enter image description here](https://i.stack.imgur.com/OgiYK.png)](https://i.stack.imgur.com/OgiYK.png)
[Answer]
# Pyth - ~~12~~ 11 bytes
Uses functional while. I feel like there should be a smarter answer that just simulates the distribution.
```
-.W!%HQ+hOQ
- (Q) Subtract Q. This is because we start Z at Q to save a char
.W While, functionally
! Logical not. In this case, it checks for 0
%HQ Current val mod input
+ (Z) Add to current val
h Plus 1
OQ Random val in [0, input)
```
[Try it online](http://pyth.herokuapp.com/?code=-.W%21%25HQ%2BhOQ&test_suite=1&test_suite_input=4%0A6&debug=0).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
It may be shorter than dana's solution, but it's a hell of a lot uglier. I'm only posting it 'cause it seems like forever since we had a Japt solution that started with an empty line.
```
ö
>°V©VªV+ß
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=CvYKPrBWqVaqVivf&input=Ng)
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
```
import random as r,math
lambda n:int(-math.log(r.random(),n))*n+r.randint(1,n-1)
```
[Try it online!](https://tio.run/##JcoxCsAgDADAva9wNK0K0q2/SRGqYBKxLn19irge176RhU/VQk36MB05CRl8TXeEI28V6U5o@Co8rJ8Uqjy2hzUtOAbY@VgwU3TsI6j@ "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[ILΩDIÊ#}O
```
[Try it online](https://tio.run/##yy9OTMpM/f8/2tPn3EoXz8NdyrX@//8bAwA) or [verify the lists](https://tio.run/##yy9OTMpM/f8/2tPn3EoXz8NdyrWatv46//8bAwA).
**10 bytes alternative:**
```
[LΩDˆÊ#}¯O
```
[Try it online](https://tio.run/##yy9OTMpM/f8/2ufcSpfTbYe7lGsPrff//98YAA) or [verify the lists](https://tio.run/##yy9OTMpM/f8/2ufcSpfTbYe7lGsPrbf11/n/3xgA).
Although I like the top one more because it got the 'word' `DIÊ` in it, which suits the challenge.
**Explanation:**
```
[ # Start an infinite loop:
IL # Create a list in the range [1, input]
Ω # Pop and push a random value from this list
D # Duplicate it
IÊ # If it's NOT equal to the input:
# # Stop the infinite loop
}O # After the loop: sum all values on the stack
# (which is output implicitly as result)
[ # Start an infinite loop
L # Create a list in the range [1, (implicit) input]
Ω # Pop and push a random value from this list
Dˆ # Add a copy to the global_array
Ê # If it's NOT equal to the (implicit) input:
# # Stop the infinite loop
}¯ # After the loop: push the global_array
O # Pop and push its sum
# (which is output implicitly as result)
```
[Answer]
# JavaScript (ES6), ~~39~~ 30 bytes
*Saved 9 bytes thanks to @tsh!*
```
f=n=>Math.random()*n|0||n+f(n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1s43sSRDrygxLyU/V0NTK6/GoKYmTztNI0/zf3J@XnF@TqpeTn66RpqGmabmfwA "JavaScript (Node.js) – Try It Online") or [See the distribution for n=4](https://tio.run/##NYxBDsIgEEX3nGKWILapia4Qb@AJmi5IC1pTZwwQN6W9OqKNq//y8/Ie5m1C78dXrJAGm7PTqC9XE@@1NzjQk4sdpiYllI6jyI48D9FE0DAvexij9QUbtdEZDva0sZQCZgbwlVtvQ7EcP4qubLX@z06xhfWEgSZbT3T7pYXKHw)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 50 bytes
```
R@#//.x_/;x~Mod~#==0:>x+R@#&
R=RandomChoice@*Range
```
[Try it online!](https://tio.run/##RY1NC4IwHMbvfoo/Ch1Kml06FItR0C0I8zZGLJ1uMB1sg/TiV1/TS8/t@fG89NxL0XOvah46HEqSIbQf3@g8zg/TzBnGxeky7iLfJCUu@dCY/iaNqgXZRteJ8LRq8AQ6emSwKElWQlMprADlIB6A51pPYFo4FFERWfN1KfvHyctYf51otQRJxT9a0GUyXwssvyvrPAvhBw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~47~~ 42 bytes
```
function(n){while(!F%%n)F=F+sample(n,1)
F}
```
[Try it online!](https://tio.run/##K/qfqmCj@z@tNC@5JDM/TyNPs7o8IzMnVUPRTVU1T9PN1k27ODG3ACiQp2OoyeVW@7@kKDMxpxioScHQINWYi6skMQkoW5RakJOZnFiSqgGR10nVMNHU1NSH8P4DAA "R – Try It Online")
Credit to [ArBo's approach](https://codegolf.stackexchange.com/a/183091/67312).
Still a byte longer than [Robin Ryder's](https://codegolf.stackexchange.com/a/183087/67312), go upvote his!
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->n,s=0{s+=x=1+rand(n);x<n||redo;s}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp9jWoLpY27bC1lC7KDEvRSNP07rCJq@mpig1Jd@6uPZ/QWlJsUJatFnsfwA "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~15~~ 14 bytes
```
{×r←?⍵:r⋄⍵+∇⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/9OAZPXh6UVAyv5R71arokfdLUBa@1FHO5Cq/f8/DyhjmGqm8Kh3rkJeaW5SapFCfppCcWJuQU5qMVc1UFH0o95uIGUdWwvk7dLJO7z9Ue@KR52LQPof9exIO7Qi71HvFhOwCQVFmXklCimZxSVFmUmlJZn5eQA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 77 76 bytes
```
import System.Random
f x=randomRIO(1,x)>>=(x!)
x!y|y<x=pure y|0<1=(y+)<$>f x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVcvKDEvJT@XK02hwrYIzAzy9Ncw1KnQtLOz1ahQ1OSqUKysqbSpsC0oLUpVqKwxsDG01ajU1rRRsQPq@Z@bmJlnm6agYWJl5ZlXoqkA1KVQUJSZV/IfAA "Haskell – Try It Online")
Thanks to killmous for one byte.
If `<|>` were in the prelude, we could do better with `MonadComprehensions`:
# [Haskell](https://www.haskell.org/), non-competing, 66 bytes
```
import System.Random
f x=do y<-randomRIO(1,x);[y|y<x]<|>(y+)<$>f x
```
[Try it online!](https://tio.run/##NcuxCsIwFEDR3a/I4JCgLQhONQ1Ipw4i1EUQh2BTG0zeC0mQBvrtxiK4Xs4dZXgpY7K2Dn0kDUL0aMqjc0Y/ZNRvRSjls2DsTy4pRGXLTkKPdjWQqe6RJF74X@jaM91tJ3a4pTnx6b6sNG0YX4tFZis11AOh@6pqITIiRE2c1xDz5zEY@Qy5uJ4QZN@gdV6NCoJGCF8 "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
f=lambda n:random()*n//1or n+f(n)
from random import*
```
[Try it online!](https://tio.run/##RcoxDgIhFEXRnlX8EtA4jJlqElZijEFHlADvE4KFq0eJhe09t7zbk3Hs3dvk8nVzhLU6bJyl0pimmSth5yWU8JUz/YxCLlyb7rCLSPY0nPx3vVDAeB53ORtj1FmMGv910VCroFIDGsU9pcONX2gyKtE/ "Python 2 – Try It Online")
Uses the `or` short-circuiting idea from [ArBo's answer](https://codegolf.stackexchange.com/a/183091/20260). The expression `random()*n//1` generates a number from `0` to `n-1`, with `0` taking the place of a roll of `n`. The `or` takes the that number, except if it's zero (Falsey) it continues on to `n+f(n)`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
ö)g@¶°X?X+ß:X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9ilnQLawWD9YK986WA&input=Mg)
Port of [Arnauld's answer](https://codegolf.stackexchange.com/a/183082/8340). Figured out how to make a recursive call ;)
Transpiled JS:
```
// U: Implicit input
// ö: generate a random number [0,U)
(U.ö())
// g: run the result through a function
.g(function(X, Y, Z) {
// increment the result and compare to input
return U === (++X)
// if they are the same, roll again and add to current roll
? (X + rp())
// if they are different, use current roll
: X
})
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~94~~ ~~81~~ 78 bytes
```
import System.Random
f n=do i<-randomRIO(1,n);last$((i+)<$>f n):[return i|i<n]
```
[Try it online!](https://tio.run/##HcqxCsIwFAXQvV9xhwwNWkHcYtq9U6GO4hBIig@Tl/IaB8F/j8X1cJ5ue4UYa6W0Zim4fbYS0ml27HNqFnDvM8h28od5nNrzkfU1uq2otqWDtmrYlzZ3CeUtDPqS5UdNjhg9fG4Age2w4AJjME4Yuey4CnGBgtQf "Haskell – Try It Online")
---
[Original](https://tio.run/##HcuxCsMgFAXQPV9xhwwJbQqlW2qyOwXSLxBU8qg@w9MO/XorXQ@cw@S3C6FWimeSgtc3Fxdvu2GbYufBi00gNckfdr0N9yuPT/INGeVwDHHlIwyCC9kNdBlVv7ZYoyHGAps6QKAmeDwwz9AbNJeGpxAX9JD6Aw "Haskell – Try It Online")
Quite similar to @dfeuer's, but using `do` notation.
* -13 bytes by removing whitespace, thanks to [@dfeuer](https://codegolf.stackexchange.com/users/38603/dfeuer)
* -3 bytes thanks to [this](https://codegolf.stackexchange.com/a/96371/86524)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 49 bytes
```
for($a=$l="$args";$a-eq$l){$o+=$l=1..$a|Random}$o
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SEMl0VYlx1ZJJbEovVjJWiVRN7VQJUezWiVfGyRuqKenklgTlJiXkp9bq5L///9/MwA "PowerShell – Try It Online")
Iterative method. Sets the input `$args` to `$a` and the `$l`ast roll (done so we enter the loop at least once). Then, so long as the last roll is `-eq`ual to the input, we keep rolling. Inside the loop we accumulate into `$o` the last roll, which is updated by creating a range from `1` to input `$a` and picking a `Random` element thereof. *(Honestly, I'm a little surprised that `$o+=$l=` works.)* Once we're out of the loop, we leave `$o` on the pipeline and output is implicit.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 72 bytes
```
include random.fs
: f >r 0 begin i random 1+ >r i + r> i < until rdrop ;
```
[Try it online!](https://tio.run/##hY2xCsJAEER7v2KsLIJBwUollQfW2trE3F6ycO6FvU2hP38mYG/1hnkME5LasO3DglJYujh5grbi06sOGUcENIodntSzgH8K@2qpGRW0mXHGJMYR6jWNOJWruzncnbtgjQeME3yiLBsDCxu3kT8EGwiZyGOcR6TxvTrMbzU6/RvKFw "Forth (gforth) – Try It Online")
### Code Explanation
```
include random.fs \ include library file for random
: f \ start a new word definition
>r \ stick the input on the return stack (for easy access)
0 \ add a counter to hold the sum
begin \ start an indefinite loop
i random 1+ \ generate a random number from 1 to n
>r i + r> \ add the result to the counter, use the return stack to save a few bytes
i < \ check if result was less than n
until \ end the loop if it was, otherwise go back to begin
rdrop \ remove n from the return stack
; \ end the word definition
```
[Answer]
## Batch, 70 bytes
```
@set t=0
:g
@set/at+=d=%random%%%%1+1
@if %d%==%1 goto g
@echo %t%
```
Takes input `n` as a command-line parameter `%1`. `d` is the current roll, `t` the cumulative total. Simply keeps rolling until `d` is not equal to `n`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
x⁹X€Ä%ƇµḢ
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//eOKBuVjigqzDhCXGh8K14bii/8Kzw4ckNDAww5DCof//Ng "Jelly – Try It Online")
A monadic link that takes n as its argument and returns a number generated by an exploding n-sided die. This generates 256 numbers from 1 to n and returns the first cumulative sum that is not a multiple of n. In theory this could return 256n, but even for a 2-sided die this would happen only one every \$2^{256}\$ times.
An alternative that doesn’t have this limitation is:
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
X³X¤+¥³ḍ¥¿
```
[Try it online!](https://tio.run/##y0rNyan8/z/i0OaIQ0u0Dy09tPnhjl4gtf//oc2H21VMDAwOTzi08P9/MwA "Jelly – Try It Online")
Note both TIO links generate 400 numbers to show the distribution.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~81~~ 72 bytes
```
from random import*
def f(x,a=0):
while a%x<1:a+=randint(1,x)
return a
```
[Try it online!](https://tio.run/##TYrLCoAgEADvfsVeArc6FD0OkR@zkJJQKouRfb3VIeg0wzDhiqt3Xc6G/Q5Mbnlg9@A5lmLRBoxMNakGJwHnajcNVKS5nahS72xdlG2dUADreLADyoHfaGSPKD4ffj4i5hs "Python 3 – Try It Online")
-9 bytes thanks to ArBo
## Explanation
```
import random #load the random module
def explodeDice(num): #main function
ans = 0 #set answer to 0
while a % num != 0: #while a isn't a multiple of the input
ans += random.randint(1, num) #add the next dice roll to answer
return ans #return the answer
```
[Answer]
# TI-BASIC, ~~28~~ 23 bytes
*-5 bytes thanks to [this](https://codegolf.meta.stackexchange.com/questions/15025/what-are-the-standard-requirements-for-answering-a-random-challenge) meta post!*
```
Ans→N:0:Repeat fPart(Ans/N:Ans+randInt(1,N:End:Ans
```
Input is in `Ans`.
Output is in `Ans` and is implicitly printed.
**Examples:**
```
4
4
prgmCDGF11
5
6
6
prgmCDGF11
3
```
**Explanation:**
```
Ans→N:0:Repeat fPart(Ans/N:Ans+randInt(1,N:End:Ans ;full logic
Ans→N ;store the input in "N"
0 ;leave 0 in "Ans"
Repeat fPart(Ans/N End ;loop until the sum
; is not a multiple of
; the input
randInt(1,N ;generate a random
; integer in [1,N]
Ans+ ;then add it to "Ans"
Ans ;leave the sum in "Ans"
;implicitly print "Ans"
```
---
**Notes:**
* TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
[Answer]
# SmileBASIC 3, 49 bytes
Function `D N OUT R` implements exploding dice rolls recursively.
```
DEF D N OUT R
R=RND(N)+1IF R==N THEN R=R+D(N)
END
```
## Ungolfed
```
DEF D N OUT R 'N is sides and R is output param (shorter than using RETURN in this case)
R=RND(N)+1 'random number in [1, N]
IF R==N THEN R=R+D(N) 'if roll is same as N then roll again and add
END
```
Note that in SmileBASIC, functions can have multiple return values. If a function has one return value then `fun in OUT var` and `var = fun(in)` are exactly the same, which is why we can define the function in `OUT` form and also call it in an expression in the function body itself. If I had defined the function as `DEF D(N)` I would have to explicitly state `RETURN R` in the function body; mixing both syntaxes saved me bytes.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 43 bytes (Iterative method)
```
param($n)do{$x+=1..$n|random}until($x%$n)$x
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPMyW/WqVC29ZQT08lr6YoMS8lP7e2NK8kM0dDpUIVKK9S8f//fzMA "PowerShell – Try It Online")
---
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 48 bytes (recursive method)
```
filter f{if($_-eq($x=1..$_|random)){$x+=$_|f}$x}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py0zpyS1SCGtOjNNQyVeN7VQQ6XC1lBPTyW@pigxLyU/V1OzWqVC2xbIT6tVqaj9b1aT9v8/AA "PowerShell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
X=п⁸S_
```
A monadic Link accepting an integer, `n`, which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8/z/C9vCEQ/sfNe4Ijv///78ZAA "Jelly – Try It Online")** Or see [the counts of \$10^5\$ runs](https://tio.run/##ASgA1/9qZWxsef//WD3DkMK/4oG4U1//4bqLyLc1w4figqzhuaLFknJH//80 "Jelly – Try It Online")
### How?
```
X=п⁸S_ - Link: integer, n
п - Collect up while...
= ⁸ - ...condition: equal to chain's left argument, n
X - ...next value: random number in [1..n]
S - sum
_ - subtract n (since the collection starts with [n])
```
[Answer]
# SmileBASIC, 41 bytes
```
INPUT N@L
S=S+RND(N)+1ON S MOD N GOTO@L?S
```
After reading:
>
> Note that you should never output any multiples of n, since they will always explode.
>
>
>
I realized that rather than checking if a dice roll was `n`, you can just repeat while the sum is a multiple of `n`.
[Answer]
# [AnyDice](https://anydice.com/), 36 bytes
Almost a built-in in the language:
```
function:f I:n{result: [explode dI]}
```
For this to be correct I have to abuse the infinite recursion depth assumption.
AnyDice limits the recursion depth with a global property maximum function depth.
the explode builtin however uses it's own; explode depth - which defaults to 2.
```
set "explode depth" to 99
```
Would add another 25 bytes; and would not really match the requirements since it's theoretically possible for a dice to explode more than 99 times.
The output of the function is a die, ie. an AnyDice built-in type that is a paring of results and probabilities for the result.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/9422/edit)
**As the title said, the challenge is to write the longest sentence by only using the keywords of 1 programming language.**
For instance, using [the keywords of C++](http://en.cppreference.com/w/cpp/keyword), it is possible to write this sentence:
>
> do not try this float
>
>
>
What can you come up with?
[Answer]
# C++, 25 unique words, 28 total
>
> True friend, do goto register for this new short public class for
> private auto operator (while inline, return this signed template),
> else break & void this long volatile union.
>
>
>
[Answer]
## Mathematica ~~100~~ 80 unique words
Here's a start. All standard words in Mathematica begin with upper case.
this includes `I`, the square root of negative 1.
On Sunday, And For All Times-- Assuming, On Opening Clear Dynamic Interactive Notebooks For Setting Contours, I Do Not Translate Missing Blue Arrays Which Span Temporary, Asynchronous, And Invisible Characters, Nor Do I Remove Undefined Arrowheads With Editable And Sound Outer Orange Roots Which Magnify Shallow Names Together With False Attributes (Because Most Axes Split Full Inner Kernels In Reverse Order)-- And While I Animate Undefined Quiet Ticks, I Begin With Tolerance And Operate On All Manual Matrices, Interleaving Circle With Cylinder, Boxed Skeleton With Compiled Cuboid, Red Cross With Nearest Timing Pattern,
And Join Repeated Unique White Links With Heads ...
---
In case anyone is interested, here are 500+ words recognized by Mathematica (no additional libraries required). They are not all keywords, but experienced Mathematica programers will know and have used just about all of them.
---
{Abort, Above, Abs, Accumulate, Accuracy, AddTo, After, Alignment,
All, Alternatives, Analytic, And, Animate, Animator, Annotation,
Annuity, Antialiasing, Antisymmetric, Apart, Appearance, Append,
Apply, Array, Arrays, Arrow, Arrowheads, Assert, Assuming,
Assumptions, Asynchronous, Attributes, Automatic, Axes, Axis, Back,
Background, Backslash, Backward, Band, Baseline, Because, Beep,
Before, Begin, Below, Binarize, Binomial, Blank, Blend, Block, Blur,
Bookmarks, Booleans, Bottom, Bounds, Boxed, Break, Button, Byte,
Cancel, Cap, Cases, Cashflow, Catch, Ceiling, Cell, Cells, Censoring,
Center, Character, Characters, Check, Checkbox, Chop, Circle, Clear,
Clip, Clock, Close, Closed, Closing, Coarse, Coefficient, Collect,
Colon, Colorize, Column, Commonest, Compile, Compiled, Complement,
Complex, Compose, Composition, Compress, Condition, Cone, Congruent,
Conjunction, Connect, Constant, Constants, Context, Contexts,
Continue, Contours, Control, Convergents, Convolve, Copyable,
Correlation, Cot, Count, Covariance, Cross, Cumulant, Cup, Curl,
Cycles, Cylinder, Darker, Date, Debug, Decrement, Default, Defer,
[Degree], Deinitialization, Deletable, Delimiter, Delimiters,
Denominator, Deploy, Deployed, Depth, Derivative, Diagonal, Dialog,
Diamond, Differences, Dilation, Dimensions, Direction, Directive,
Disjunction, Disk, Dispatch, Display, Distribute, Distributed,
Dithering, Divide, Dividers, Divisible, Divisors, Do, Dot, Down,
Drop, Dynamic, Editable, Eigenvalues, Element, Eliminate, Empty,
Enabled, Encode, End, Enter, Epilog, Equal, Equivalent, Evaluator,
Except, Exists, Exit, Expand, Expectation, Exponent, Export,
Expression, Extract, Factor, Factorial, Fail, False, File, Filling,
Find, First, Fit, Flat, Flatten, Floor, Fold, Font, For, Forward,
Frame, Front, Full, Function, Gather, General, Generic, Get, Graph,
Graphics, Greater, Grid, Hash, Head, Heads, Histogram, Hold, Hue,
Hyperlink, Hyphenation, I, Identity, If, Image, Implies, In,
Increment, Inherited, Inner, Input, Insert, Inset, Install, Integer,
Integers, Integral, Integrate, Interactive, Interleaving, Interval,
Invisible, Item, Join, Joined, Kernels, Label, Labeled, Large,
Larger, Last, Latitude, Launch, Left, Legended, Length, Less, Level,
Lighting, Limit, Line, Links, List, Listable, Listen, Literal,
Locked, Log, Longest, Longitude, Magnification, Magnify, Majority,
Manipulate, Manual, Map, Masking, Material, Matrices, Maximize, Mean,
Median, Medium, Menu, Mesh, Message, Messages, Method, Minimize,
Minors, Missing, Modal, Mode, Modular, Module, Modulus, Moment,
Monday, Monitor, Most, Mouseover, Multinomial, Multiplicity,
Multiselection, Names, Nearest, Needs, Negative, Nest, Next, None,
Nor, Norm, Normal, Normalize, Not, Notebook, Notebooks, Null, Number,
Numerator, Off, Offset, On, Opacity, Open, Opening, Operate,
Optional, Options, Or, Order, Ordering, Orderless, Orthogonalize,
Out, Outer, Over, Overflow, Paclet, Pane, Panel, Paneled,
Parallelize, Parameter, Parenthesize, Part, Partition, Paste, Path,
Pattern, Pause, Permutations, Permute, Perpendicular, [Pi],
Piecewise, Pivoting, Placed, Placeholder, Plain, Play, Plot, Plus,
Point, Polygon, Polynomials, Position, Positive, Power, Precedence,
Precedes, Precision, Prefix, Prepend, Previous, Print, Probability,
Projection, Prolog, Properties, Property, Proportion, Protect,
Protected, Pruning, Put, Pyramid, Quantile, Quantity, Quartics,
Quartiles, Queueing, Quiet, Quit, Quotient, Radon, Random, Range, Raster, Rasterize, Rational, Rationals, Read, Real, Reap, Record,
Rectangle, Reduce, Refine, Refresh, Reinstall, Release, Remove,
Removed, Repeated, Replace, Resampling, Rescale, Residue, Resolve,
Rest, Return, Reverse, Riffle, Right, Root, Roots, Rotate, Round,
Row, Rule, Saturday, Save, Saveable, Scale, Scaled, Scan, Scrollbars,
Select, Selection, Sequence, Series, Set, Setbacks, Setter, Setting,
Shading, Shallow, Share, Sharpen, Short, Show, Sidebar, Sign,
Signature, Simplify, Skeleton, Skip, Slot, Smaller, Socket, Solve,
Sound, Sow, Spacer, Spacings, Span, Speak, Sphere, Splice, Split,
Square, Stack, Star, Streams, String, Stub, Subfactorial, Subgraph,
Subscripted, Subset, Subtract, Sum, Superset, Surd, Syntax, Table,
Take, Tally, Temporary, Text, Texture, Therefore, Thread, Threshold,
Through, Ticks, Times, Timing, Together, Toggle, Toggler, Tolerance,
Tooltip, Top, Total, Trace, Tracers, Translate, Transpose, True,
Tube, Tuples, Undefined, Underlined, Underscript, Unequal, Uninstall,
Union, Unique, Unitize, Unset, Up, Variables, Vertical, Wedge,
Weights, Which, While, Whitespace, With, Word, Write}
[Answer]
While making sentences is not really my strong suite, here goes nothing -
# Python 20 words
>
> Finally, continue with import and raise global yield while class lambda is in break and try and print exec pass.
>
>
>
To help with checking, I wrote some code to check whether the words are in the keyword list or not.
```
from keyword import kwlist
from re import findall
def kwcheck(sentence):
"""Check whether all the words of a sentence are Python keywords"""
words= findall(r'\w+', sentence)
for word in words:
if word.lower() not in kwlist:
return False
return True, len(words)
if __name__ == '__main__':
sen= raw_input("Enter your sentence: ")
print kwcheck(sen)
```
[Answer]
## The Importance of Education
### -- by A. Coder Guy (written in Python)
```
Continue class, except if class is not for you.
With no class, raise and assert! Or yield, pass,
and break. Try and continue! Or - finally - return from class.
```
[Answer]
### Common Lisp
```
:In :Common :Lisp :a :keyword :is :simply :a :symbol :which :has :the :KEYWORD :home :package :which :is :true :of :all :symbols :starting :with :a :colon :so :you :can :construct :arbitrarily :long :sentences. :Do :I :win?
```
This, for example:
```
(every #'keywordp '(:In :Common :Lisp :a :keyword :is :simply :a :symbol :which :has :the :KEYWORD :home :package :which :is :true :of :all :symbols :starting :with :a :colon :so :you :can :construct :arbitrarily :long :sentences. :Do :I :win?))
```
Evaluates to `T`
See <http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_k.htm>
[Answer]
## c#, 17 words
This looks like pretty reasonable technical mumbo-jumbo.
I guess it can be extended a bit.
`foreach` is a bit stretching the rules.
Used [this keyword list](http://msdn.microsoft.com/en-us/library/x53a06bb%28v=vs.71%29.aspx).
>
> Try explicit operator, in case implicit string foreach virtual struct is as unsafe as this volatile lock.
>
>
>
[Answer]
# Factor - 109
>
> "Take my-world and with happy? make items to-do. Pause. Self
> not happy?"
>
>
> "Yes<<."
>
>
> "From oldies?"
>
>
> "Yes>>. Self sad."
>
>
> "Haversin, listen, each and every formula become oldies. Become not
> sad, do-something greater-from-last. Or .
> My-arch self is\_gold<<. Change-is\_gold. Go-back where
> your\_event\_mask<< make happy? future. Fulfill promise of
> self. Remember-definition, light are-copies-of happy?"
>
>
> "Sweetest-day near>> me?. Handle-me, handle-me. Sad self.
> Home not near>>. Home not near>> at all. Out-of-memory.
> Sad self, old<< self. Most near>> ones left self long
> ago."
>
>
> "Haversin, change-known self. No sad, Haversin.
> Become happy? Forget what<< keep self from happy?
> My-arch self want>> self be> not sad. Before leave,
> remember-error."
>
>
> "Not remember-error! Error not! My-array
> has-entry? not of error! Leave error!"
>
>
> "Smart-if remember-error."
>
>
>
A lot of these are stretches, but it somewhat tells a story, so it makes up for that.
[Answer]
# Applescript, 30 words
I never thought I would post an Applescript answer on PPCG, but given Applescript's natural language design philosophy, it is perfectly suited for this question.
I'm not much of a wordsmith, so here's one just to get us started, but I fully expect others will easily beat this:
```
Beneath the eighth error, my third script is ignoring the sixth local copy
of the fourth transaction to the seventh property whose reference is given
to repeat every tenth second.
```
This is constructed just from [Applescript's keywords](https://developer.apple.com/library/mac/documentation/applescript/conceptual/applescriptlangguide/reference/ASLR_keywords.html#//apple_ref/doc/uid/TP40000983-CH222-SW2), which are:
### Keywords
>
> about above after against and "apart from" around as "aside from" at back before beginning behind below beneath beside between but by considering contain contains continue copy div does eighth else end equal equals error every exit FALSE fifth first for fourth from front get given global if ignoring in "instead of" into is it its last local me middle mod my ninth not of on onto or "out" of over prop property put ref reference repeat return returning script second set seventh since sixth some tell tenth that the then third through thru timeout times to transaction TRUE try until use where while whose with without
>
>
>
The following may or may not be considered valid for this challenge:
### Built-in classes and properties
>
> alias application boolean centimetres centimeters character class contents constant "cubic centimetres" "cubic centimeters" "cubic feet" "cubic inches" "cubic metres" "cubic meters" "cubic yards" date "date string" day "degrees Celsius" "degrees Fahrenheit" "degrees Kelvin" feet file frontmost gallons grams id inches integer item kilograms kilometres kilometers length list litres liters metres meters miles month name number ounces paragraph "POSIX file" "POSIX path" pounds quarts "quoted form" real record reference rest reverse "RGB color" running script "square feet" "square kilometres" "square kilometers" "square metres" "square meters" "square miles" "square yards" text time "time string" "unit types" version weekday word yards year
>
>
>
### Built-in Commands
>
> activate "ASCII character" "ASCII number" beep "choose application" "choose color" "choose file" "choose file name" "choose folder" "choose from list" "choose remote application" "choose URL" "clipboard info" "close access" copy count "current date" delay "display alert" "display dialog" "display notification" "do shell script" get "get eof" "get volume settings" "info for" launch "list disks" "list folder" "load script" "localized string" log "mount volume" offset "open for access" "open location" "path to" "path to resource" "random number" read round run "run script" say "scripting components" set "set eof" "set the clipboard to" "set volume" "store script" summarize "system attribute" "system info" "the clipboard" "time to GMT" write
>
>
>
### Considering/Ignoring attributes
>
> case diacriticals hyphens "numeric strings" punctuation "white space"
>
>
>
[Answer]
# Shakespeare
### 44 words, 28 unique
Yes, all of these words really have keyword-level significance in Shakespeare. Shakespeare character names, normal nouns and adjectives are also a core part of the language, but I thought they'd bloat the list too much for this exercise.
>
> You must listen to your heart to enter your mind: the heart shall
> recall the difference between the exit and the return, to let you
> remember you are your art, and so you are the product of yourself and
> an act better than yourself.
>
>
>
[Answer]
## **Ruby, 41 words**
>
> True self, do not begin class break, end class break, ensure class break, redo
> and redo class break, retry class break, rescue class break, or yield
> class break, until next class end (or next class module or next class
> return), or else!
>
>
>
That's just using words [listed as actual keywords](http://ruby-doc.org/docs/keywords/1.9/). There are a lot of other words that act like keywords because they're methods of the kernel or instance methods of Class.
A cheesier approach would start
>
> Do not def "alias","begin","break",...
>
>
>
[Answer]
C++.
A lot of repeated words, but a borderline sensible sentence:
```
If this volatile friend false and do return unsigned public union template throw union
template goto void for false friend not using class, and try switch for new protected
union using true friend, or else catch long, private break using this public operator
switch for explicit union using new virtual friend if union for this friend not long and
true.
```
Aka: If this moody girl won't sign the marriage license, throw away the license and find a nice new girl--and if that doesn't work out, just try a...virtual union over the "public operator switch".
Oh, as far as exact number of words goes, sorry but I'm too lazy to count.
[Answer]
# Python, 48 words
>
> class, try (if lambda is in class) and continue as if in break from
> global import and raise yield for return from exec; else, while lambda
> is not in class, continue with print import except for def, finally
> pass 'assert elif' or else del is not for class.
>
>
>
**This contains every keyword in `keyword.kwlist`**
I think some explanation is required here: This sentence is said to a school class that is currently in some place called `exec`. In the class, there are amongst others two people named `lambda` and `def`. `def` should pass the `assert elif` test because otherwise the DEL (German ice hockey league) is nothing for the class.
[Answer]
# ECMA
A bit of broken English due to the fact that ECMA reserved words contain neither conjunctions nor more than one conjugation of verb. It's really an imperative language!
>
> Do try this new typeof case, with this default catch function.
>
>
> In this case, break in with this switch. If catch break, return with
> this new switch; finally throw in with this new function.
>
>
>
[Answer]
# Perl - several entries
when given tied package untie, unpack and unlink until open, redo each package (link, pack and bind or tie) or dump if not open; next, read map, write state, reverse and return system. (28 distinct words)
bless (not hex) my rand-y flock; continue until values accept no sin; study END times, accept sleep and die; CHECK keys and close each crypt lock. (25 distinct words)
tell our next caller: "use fork and pipe; push, break, delete, kill, and DESTROY." (13 distinct words)
[Answer]
# Haskell (~29-ish)
>
> In case of foreign type, import data module; where as for all (`forall`) in qualified class, if hiding, then do default (let in, deriving instance of data family where qualified, otherwise data instance of type family); else type in fix (`infix`).
>
>
>
In Haskell, `data family` is a separate keyword from `data`, likewise with `type family`, and `deriving instance` is separate from `deriving` and `instance`. I am using `forall` as two words (counting only one), `where as` as one (counting two), and `infix` as two (counting one).
] |
[Question]
[
As a child, my friend had a [magic 8 ball](https://en.wikipedia.org/wiki/Magic_8-Ball) that we would ask questions to and see what the fate of that question was.
# Challenge
Your challenge is to write a program (or function) that when run (or called), outputs (or returns) a random answer from the possible answers below. (Random being: `each output should have a nonzero chance of occurring but they do not need to meet any other criteria`)
The possible answers from the Magic 8-ball are (case-insensitive):
```
It is certain
It is decidedly so
Without a doubt
Yes definitely
You may rely on it
As I see it, yes
Most likely
Outlook good
Yep
Signs point to yes
Reply hazy try again
Ask again later
Better not tell you now
Cannot predict now
Concentrate and ask again
Don't count on it
My reply is no
My sources say no
Outlook not so good
Very doubtful
```
# Input
No input.
# Output
A random choice from above. Case does not matter.
# Rules
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes for each language wins!
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~438~~ 365 bytes
```
0x1+!
0\aa+%3+&
+>:&:&g1-o1
Zfq
Nptu!mjlfmz
Tjhot!qpjou!up!zft
Bt!J!tff!ju-!zft
Xjuipvu!b!epvcu
Ju(t!dfsubjo
Pvumppl!hppe
Zft!efgjojufmz
Zpv!nbz!sfmz!po!ju
Ju!jt!efdjefemz!tp
Btl!bhbjo!mbufs
Epo(u!dpvou!po!ju
Dboopu!qsfejdu!opx
Wfsz!epvcugvm
Nz!sfqmz!jt!op
Nz!tpvsdft!tbz!op
Sfqmz!ib{z!usz!bhbjo
Cfuufs!opu!ufmm!zpv!opx
Dpodfousbuf!boe!btl!bhbjo
Pvumppl!opu!tp!hppe
```
[Try it online!](https://tio.run/##PY8xa8MwEIV3/Ys3NARMIKFbhg5tumQIhRZaQpeo9tkRce@MdCK4P949ObTjnfS@9x2dYzdN6@umglt/nk7V3X21cNXDdrFdtJsVb9yRBneQpOjDhfrRvYWOEwYJrFDBSMk9JuyRiBB0NS8@gp4lKzwayV/q9rpMqCmqD@xesvYiF3QijdETGmoDBy3wo2R8@xHRBggb0LII5U8dGmpsm8T6LvCdsdB7peiehZeKWrIp3UI7zyyKIVITagXL1b1THG86be7doXQMhjM2SxmT5FibTbJ627zOr2f/M0ItONe5J1LrQ0Gbbo/RdAt7J1wTazQbeG7g/wT/jy2RJPPN0/QL "><> – Try It Online")
~~Not that interesting~~ Now shorter than most solutions without compressed strings! I think it's also the first answer where the randomness is not uniform. I put all the negative messages as least likely :)
### Explanation:
All the messages are stored on the lines starting with `Zfq`, but with each character incremented by one (so `Zfq` is `Yes`). The first line `0x1+!` randomly either increments a number (initially `0`), resets it to `1` or exits the loop. When we get to the second line, we modulo this random number by 20 (though to get higher than that, would be like a one in a million chance), and add 3 to get the line number. Then we push a counter starting at `0`, and move to the third line, where we print each character subtracting one from each, where we finally terminate by trying to print `-1` as a character.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 166 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
,▓a⁰²z○½℮ķčλ─fj[Ycψ-⁸jΔkÆΞu±⁄│(┼∞׀±q- υ~‼U/[DΓ▓νg⁸⅝╝┘¤δα~0-⁄⅝v⁄N⁷⁽╤oο[]āŗ=§№αU5$┌wΨgΘ°σΖ$d¦ƨ4Z∞▒²÷βΗ◄⁴Γ■!≤,A╬╤╬χpLΧ⁸⁽aIΘād⁵█↔‚\¶σΞlh³Ζ╤2rJ╚↓○sēχΘRψΙ±ιΗ@:┌Γ1⁷‘Ƨ! ΘlΨιw
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTJDJXUyNTkzYSV1MjA3MCVCMnoldTI1Q0IlQkQldTIxMkUldTAxMzcldTAxMEQldTAzQkIldTI1MDBmaiU1QlljJXUwM0M4LSV1MjA3OGoldTAzOTRrJUM2JXUwMzlFdSVCMSV1MjA0NCV1MjUwMiUyOCV1MjUzQyV1MjIxRSV1MDVDMCVCMXEtJTIwJXUwM0M1JTdFJXUyMDNDVS8lNUJEJXUwMzkzJXUyNTkzJXUwM0JEZyV1MjA3OCV1MjE1RCV1MjU1RCV1MjUxOCVBNCV1MDNCNCV1MDNCMSU3RTAtJXUyMDQ0JXUyMTVEdiV1MjA0NE4ldTIwNzcldTIwN0QldTI1NjRvJXUwM0JGJTVCJTVEJXUwMTAxJXUwMTU3JTNEJUE3JXUyMTE2JXUwM0IxVTUlMjQldTI1MEN3JXUwM0E4ZyV1MDM5OCVCMCV1MDNDMyV1MDM5NiUyNGQlQTYldTAxQTg0WiV1MjIxRSV1MjU5MiVCMiVGNyV1MDNCMiV1MDM5NyV1MjVDNCV1MjA3NCV1MDM5MyV1MjVBMCUyMSV1MjI2NCUyQ0EldTI1NkMldTI1NjQldTI1NkMldTAzQzdwTCV1MDNBNyV1MjA3OCV1MjA3RGFJJXUwMzk4JXUwMTAxZCV1MjA3NSV1MjU4OCV1MjE5NCV1MjAxQSU1QyVCNiV1MDNDMyV1MDM5RWxoJUIzJXUwMzk2JXUyNTY0MnJKJXUyNTVBJXUyMTkzJXUyNUNCcyV1MDExMyV1MDNDNyV1MDM5OFIldTAzQzgldTAzOTklQjEldTAzQjkldTAzOTdAJTNBJXUyNTBDJXUwMzkzMSV1MjA3NyV1MjAxOCV1MDFBNyUyMSUyMCV1MDM5OGwldTAzQTgldTAzQjl3,v=0.12)
\o/ every word was in SOGLs dictionary!
[Answer]
# Python 2, 369 368 bytes
```
print"It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful".split('.')[id(0)/7%20]
```
# Python 3, 371 bytes
```
print("It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful".split('.')[hash(id)%20])
```
I was previously using the `hash` builtin to index (`hash(id)%20`), which returns a random value per-start of the Python interpreter ever since <https://bugs.python.org/issue13703>. It's not random for the empty-string though (always 0), so need to use something else, the `id` builtin!
On second look, I could use `id` directly, but it seems to always produce even numbers. IIRC, `id(object)` in CPython just returns the memory location of `object`, so this makes sense. Maybe if I used Jython or IronPython, I could skip the divide-by-7. Anyways, `hash(id)` vs `id(0)//7` is equal in Python 3, but can use the `/` operator for truncating integer division in Python 2, saving a byte.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 354 bytes
```
"It is certain0It is decidedly so0Without a doubt0Yes definitely0You may rely on it0As I see it, yes0Most likely0Outlook good0Yep0Signs point to yes0Reply hazy try again0Ask again later0Better not tell you now0Cannot predict now0Concentrate and ask again0Don't count on it0My reply is no0My sources say no0Outlook not so good0Very doubtful"-split0|Random
```
[Try it online!](https://tio.run/##NVBLagMxDL2KyKabFnyFtN1kEQoptGTp2sqMGUcylkxw6d2ncoasJD2k91HhG1aZMed13R0UkkDAqj6R26aIIUWMuYOw@046c1PwELn9qDvjWLgkSoq5uzM3uPoO1QZggqRuL3AAQbT@GTqKO7Io5LSM/Y@mmXmBiTkaV3GfaSKBwokUlO/7JyxGNvvfDlo7@GlY28uydZC9YnWvqFaA2M4sCnQzQnxzb54GVirGFHSDmAKSVrsDTxH8g8q9Mz0pBG4mvpk/jihD3v5APEbhVoOFFktpyCPAEBHecnyh2by/59Ly7kVKNqa/k2nxdV3/AQ "PowerShell – Try It Online")
Ho-hum. Takes all the outcomes, concatenated together with `0`s, then `-split`s on `0` to create an array of strings. Passes that array to `Get-Random` which will randomly select one of them. That's left on the pipeline and output is implicit.
[Answer]
# [Python 2](https://docs.python.org/2/), 385 bytes
*-1 byte thanks to ovs.*
```
from random import*
print choice("It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful".split('.'))
```
[Try it online!](https://tio.run/##NVC7TkMxDN35CqtLW4Qy8AcFlg4VEkigjiFxW@umdpQ4QuHnL06vOvkh@7xy14vw8zyfilyheI5W6Jql6ONDLsQK4SIUcLPaK1CFgEU9sVumiIEixtShivsmw2oKHqK0H3VHHAcnYlJM3R2lwdV3KDaAMJC6XYU9VETrn6BjdQepCommcf/eNIlMcBaJhpXdJ525QpYhSuV2/4HZwC7@r4OWDv48pO3qtHSQvGJxL6hWgMXeMCXoJoTl1716HrtcMFLQZSUckLXYH1gW4O9Q7k14bVlIM/JF/GFYGfSWA8sYq7QSzHQ1l7a5GxgkVRYfX2gyb/GcWlq5mhPpZu3W2@08/wM "Python 2 – Try It Online")
[Answer]
# Applescript, 391
I love how AppleScript's lists have a `some item` method:
```
{"It is certain","It is decidedly so","Without a doubt","Yes definitely","You may rely on it","As I see it,yes","Most likely","Outlook good","Yep","Signs point to yes","Reply hazy try again","Ask again later","Better not tell you now","Cannot predict now","Concentrate and ask again","Don't count on it","My reply is no","My sources say no","Outlook not so good","Very doubtful"}'s some item
```
[Answer]
# Bash + GNU utilities, 230
* 15 bytes saved thanks to @Dennis.
```
sed 1d $0|zcat|shuf -n1
# zopflied 8 ball list
```
The binary zopfli output is not well represented here; instead you can reconstruct the script from base64 encoded data:
```
base64 -d << EOF > 8ball.sh
c2VkIDFkICQwfHpjYXR8c2h1ZiAtbjEKH4sIAAAAAAACAz1QSZJCMQjd5xRv1fOlMEGlzIdfgbRF
n75NOayYeYMExFF5BImWe9W4SuPWE27lKnG2GSA0m4coyWvhKCrBPUvaxEaJcStgColCDoEzQ+IH
t/WymQe6XNa+zehmF5zMWknei8tJHbuJBsKw9gfvPXGmv0SMBJ0WNfLLPUOn4FEOHMEDaoHg3rGI
qF1LJV29fXCTGveWaWWNQcEgbXi9Ks30PVBtauBOfkvc4cWhtkq3OSo7nBJqLwELxO2u45dH3u05
zv4=
EOF
```
Note, as allowed by the question, the compressed data decompresses to all lower case. This makes zopfli compression a bit more efficient and saves 16 bytes.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~333~~ ~~331~~ 321 bytes
```
0cert10decided2so¶with34a d3bt¶yes definitely¶y3 ma5re26as i see it, yes¶mos4likely7good¶yep¶signs poin4to yes¶rep2haz5tr5ag18ain later¶better 94tell y3 9w¶can94predic49w¶concentrate and 81don'4c3n46m5rep2is 9¶m5s3rces sa59794so good¶ver5d3btful
9
no
8
ask ag
7
¶3tlook
6
on it¶
5
y
4
t
3
ou
2
ly
1
ain¶
0
it is
G?`
```
[Try it online!](https://tio.run/##JU87cgMhDO11CnVpUngXsE2VMtcIBnnDGKMdkONxDsYBuNgGx5Xmjd63kMTspm2Dnaci0y6Qj4HCXLm3e5RvpR0GdZLeHlQx0DnmKJQeAyu8OlNo3ruKESsRRnnHQevtylWneBm8w8IcnuK1txqXXHHlmLXwi1honb/dr5Fi3DIdXcyYnFDp7UQyLlo90hKOMHvvzbts9VooRK//MWdPWcqQoMsBj1Pg/Ka9ynp/NU/zWNGOPqaq4seA6ow9WF0ZX71@qJjnvPMtgYXMcARXL@gWOEBvShLzBWEPnMe43sDAA0GDICjgG8yQBp5g9B7PHUTBEQifH1/b9gc "Retina – Try It Online") Edit: Saved 1 byte by compressing `doubt` and 1 byte by lowercasing everything so I could compress `reply`. Then saved 10 bytes by using @Leo's Retina Kolmogorov golfer on the lowercased text (which coincidentally is the number of bytes it saved on my 333-byte answer).
[Answer]
# [R](https://www.r-project.org/), 360 bytes
```
sample(readLines(),1)
It is certain
It is decidedly so
Without a doubt
Yes definitely
You may rely on it
As I see it, yes
Most likely
Outlook good
Yep
Signs point to yes
Reply hazy try again
Ask again later
Better not tell you now
Cannot predict now
Concentrate and ask again
Don't count on it
My reply is no
My sources say no
Outlook not so good
Very doubtful
```
[Try it online!](https://tio.run/##NVBBTgMxDLznFb7RSr3whAKXSlRIIIF6DBt3a21qr2JHKHx@cbr0ZM/I9sy4LIvG65xxUzCmV2LUzXb3uA0HA1IYsFgk/kcJB0qYcgOV8EV2kWoQIUn9tnDCPnAmJsPcwkkqXGOD4gCEgSzsFQ6giN7voKGGo6hBpqnPv1XLIhOMIslvzeGDRlaYhdjA5Db/jrMfu8TfBlYaxLFb2@u0dpCjYQlPaF6AxdcwZ2huhOUnPEfu3Fww0WArJTwgW/E9iJwg3k@FF@EHg0Gqi6/mjz1Kl/c/sHSoUsvgodVTOnMP0EVU1hyf6DZv7znXvCx/ "R – Try It Online")
Not exactly the most elegant solution. R has a neat feature where `stdin` will redirect to the source file, so you can put (small) datasets into source code, saving bytes for string splitting or worse, constructing the vector itself (all those quotes add up in a hurry). Along with builtins for random sampling, this makes a short-ish answer.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~203~~ 184 bytes
```
‽⪪”}∨74Dυ3↖u➙H�↖vI⁻VR‹ψ#�Ii»ψPNξ⮌≔;≡8ν}¬H⁺ºº↖H⁴K⌕êτ|⁼➙⟲W»″φ◨⟦(τ(jK“N\⍘“↷⊙ⅉvT>➙§⌊Fζ³⁻↔;TaÀ✳⁴≔67⍘i4¬⸿-A8⁻f7¡<⁰Zχ}ζ'¡¹→Oaε!OυP₂ïμ´MuP⁺M⮌1№-k¹№FvξDü⊟ζⅉ⁰xW:Dε7TvM₂⊞θC⪪Rε⁰“D¡⸿⁰″A⊕λξ↥~O·PE&”¶
```
[Try it online!](https://tio.run/##PVBBbsMwDPsKkctaoHvBPjFsV19cW22FOlJgKy2yz2dy0u1kUxApkukWa9JY1vWzstjhK0rW8fA9FbbDwAZuSFQtsgTZYabEmXJZ0DTIk@2msyEi63y2IAv1lQv7NpXFsc4Y44LqCCpg34kNjEbk4AQnBBm1GQrfN4rrFdU7rqq5C05BGl@lYVL3CNOdU2lyyVv8WWB1QbxuJmO771@UaFSDnMn8hagzqRR0Q6LPIClKH06VMid7zVQSiVWnwqvAv1rwXuTNkHR2C68cY4/VTXgtohtuOtfkFTSP3Ed/Wfqlpq9ID3K/W1@XuQwnDEGG4/H4sa7r@6P8Ag "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 19 bytes by lowercasing everything. Explanation:
```
”...” Compressed string of newline-delimited responses
⪪ ¶ Split on newlines
‽ Random element
Implicitly print
```
[Answer]
# T-SQL, 393 bytes
```
SELECT TOP 1*FROM STRING_SPLIT('It is certain-It is decidedly so-Without a doubt-Yes definitely-You may rely on it-As I see it, yes-Most likely-Outlook good-Yep-Signs point to yes-Reply hazy try again-Ask again later-Better not tell you now-Cannot predict now-Concentrate and ask again-Don''t count on it-My reply is no-My sources say no-Outlook not so good-Very doubtful','-')ORDER BY NEWID()
```
The function `STRING_SPLIT` is only available in SQL 2016 and later.
Best I could get for prior versions using `VALUES('It is certain'),('It is decidedly so'),...` was 464 characters.
Formatted, just so you can see the working part:
```
SELECT TOP 1 *
FROM STRING_SPLIT('It is certain-It is decidedly so-...', '-')
ORDER BY NEWID()
```
`NEWID()` generates a new, pseudo-random GUID, so is a way to do a pseudo-random sort.
[Answer]
# [Coconut](http://coconut-lang.org/), 380 bytes
Coconut port of [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman)'s [answer](https://codegolf.stackexchange.com/a/157548/64121)
```
from random import*
choice$("It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful".split('.'))
```
[Try it online!](https://tio.run/##NVFNSwMxEL37Kx5F6K5Ibl4EhaqXHoqgoPQkMTu7DU0zSzJBVvzv66RLT/PBm5n33jh2HIvMc5/4hGRjp8GfRk5yc9U/uAN7R9fNaivwGY6SWB/NUnXkfEddmJDZfHo5cBFYdFy@xeypAnofvVCYzJ4LTnZC0gIc4cVsMrbIRJrfYqJsdpwFwR8r/rVIYD5iYO5012je/RAzRvZRIHzGv9Goyw72d4KkCXao1Db5uGQIViiZJxINiKxjFAImJRL5xzzbWHtjos47WVocHUVJOgc1AvayyrxwXAscFz2@kN9VKfW8@hC5lplLcio6q0rtXATUI5kXHR@kNM/29CWsTB6Dl2Zt1m0795zwBWWtLxiouWvvr4C@afH3qBxV9PwP "Coconut – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 201 bytes
*-2 bytes thanks to Mr. Xcoder. -1 byte thanks to user202729.*
```
“æ⁽IẊ?⁽ʋṠ¶ÐƝKW¬ḃỴɓ⁾:Eṇ⁵ṾɱD×⁴2ṇỤðċỊ¥ḷƬị÷ṣÐṆⱮ$u²OŀṚƁȮ1⁼ṁ$bp⁾v]Ɠ-/NẓḲnỵdḳḋ½ȥṿ=kv¥ɓl[kR AḞ¶gḣḞiẊŒẊḳçȤ⁻Ɱʋx:ØṖ|zY=ṾḌẓY1Ḃ$50d⁹⁸ŀhʂƤṢM;ḢoƁṾ⁷-uṙu¡Ọ3ṣȮ@⁹ðẹȥXƭ⁸|ƬẋẆḢɠœxḳsĿƘ(0çỌ~A½YIEFU3Ọ=⁷ɗḷBḷİṄhṗgṡƊẏẏḄ#Ṙʋ$ʂȷĠ»ỴX
```
[Try it online!](https://tio.run/##FVDZSiNBFP0VwTz4Im74ogQXVBCZEQTRIL6Ig1tQQSIqMqSiKKQFxQYThxmJmuiLhrimbvdEoSopuvsvTv1IvEJV3YVzzj11V38lk7vNpk3/1XdW1MbhZQc4Rg6ooN71mfk3MaMeIA/gv4auFR99o6BjK95AH@HTiM5Z8drNHfhFXak78LOqBFk1D/AdXQXd6jPQkX0qx1LqebKRBv0xIih3WfEfJGILmyy5PW/c9o6f8FzI53X4b4uQL5COqgUl0Gd8bVuVQjc5tzbVMgR5pd6XIG85WWGzjXN@GK7vg6IVPg@KnJ0@nQdd7O8l4uwS8oSVE12QmVhv56IVZIVspJejjCmCbn70Q95sGMFIK6rtKdBlSl3DP@lh80F5kPG6Ao@C0qx5ZOY@f81z4B0xLSw03B0evlX/NPm2Tn3PtN9DqpYYHx2b7uEizpJhjvcxzLdeAR0ug3JLoGuThXf6feRhKygfObEoE1TrBeXzomebzS8 "Jelly – Try It Online")
*Damn*, SOGL's compression is good.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 171 bytes
```
“€•€ˆ‹ì€•€ˆŸíly€Ê„›€…¬³…ܴ΀˜€‰€•€œ I€È€•,…Ü‚¢îÙ®½‚¿ yepŸé…®€„…Ü…ƒ hazy‡Ü†îˆ¹†îŠ´…瀖ˆœ€î€Ó€©notßä€Óä考ˆ¹†î€·n'tš‹€‰€•€¯…ƒ€ˆ€¸€¯Žç…耸®½€–€Ê‚¿‚Ò¬³ful“#•8∞f{ʒβ®•6в£ðýΩ
```
[Try it online!](https://tio.run/##XVC7agJREP2VhRRpUiRFQn4hn2FASSGawhQbm0sKEYUUu1WCrLoR48LmKkaIBhZhhmsRQfIN8yPrzPggpJk7c@6ZOWfm/LJwe1HMczIdekrJxBzXDTILTP/Ubo4fZZ9TbJGJyHzr3xBS@OQHOzDDZ/m1HGCJbRcqYXIc4ULvRgjNHXKmXWReIUaLL2Ahk2Lp@cV71kpktlVqtGcOV4F3V3j0yfSl7KFdN2ChievBTFjv2hCy2/DgBSWDpFKtYRcHCuAAR5ysgmO/UL4qpzXX57X/@YaxSu@OwuVcMZexGCuOFFL3Kr0/EC/CAQM5T@mhzKc94WnX1IxK9Z9gM@XVTHz1O4U3nGC2SfJ8Cw "05AB1E – Try It Online")
**Explanation**
`“ ... “` pushes a string of all the required words.
Some words are taken directly from the 05ab1e dictionary.
Some are written out in plain ascii (like `haze`).
Some are combined dictionary and ascii (like `do`+`n't`).
Then the processing code is:
```
# # split string on spaces to a list of words
•8∞f{ʒβ®• # push the number 2293515117138698
6в # convert to a list of base-6 numbers
# ([3,4,3,2,5,5,2,2,1,4,4,3,5,3,4,4,4,4,4,2])
£ # group the list into sublists of these sizes
ðý # join on spaces
Ω # pick one at random
```
[Answer]
# Ruby, 362 361 bytes
```
puts"It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful".split(?.).sample
```
[Try it online!](https://tio.run/##NVBBagMxDPyKyKUtFH2hpO0lh1BooSVHZ61sTBzJWDLF/fxWzpKTNIOkmVFtx74spZludgZJYaJqITGuKNKUIsXcQQV/kp2lGQSI0o6GBxoDp8TJKHc8SINr6FAdgDAkw63CDpTI@2fopLgXNcjpMuY/mmWRC8wi0W8V/EozKxRJbGBym/@k4sfO4a@D1Q5hHta2elk7yMGo4iuZF2DxNcoZuhth@cW3wIMrlWKabKWEJ2KrvgeBI4T7KXwXfjCYpLn4an4/ogx5/wPLgCqtTh5aPaUz9wBDRGXN8U1u8/aeU8sb1JKTPb7gE2q4lkzL8g8 "Ruby – Try It Online")
* 1 byte thanks to @benj2240
[Answer]
# Python 3, 386 bytes
```
from random import*
lambda:choice("It is certain;It is decidedly so;Without a doubt;Yes definitely;You may rely on it;As I see it, yes;Most likely;Outlook good;Yep;Signs point to yes;Reply hazy try again;Ask again later;Better not tell you now;Cannot predict now;Concentrate and ask again;Don't count on it;My reply is no;My sources say no;Outlook not so good;Very doubtful".split(';'))
```
[Answer]
# Perl, 366
```
print((split",","It is certain,It is decidedly so,Without a doubt,Yes definitely,You may rely on it,As I see it,yes,Most likely,Outlook good,Yep,Signs point to yes,Reply hazy try again,Ask again later,Better not tell you now,Cannot predict now,Concentrate and ask again,Don't count on it,My reply is no,My sources say no,Outlook not so good,Very doubtful")[rand 19])
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~208~~ 217 bytes
```
"don'".•W˜FζÃT¥„ò.1₁∍Y<`Ì°5jýúž+ìmHSéÁ¬–xȃø‚ž}_Øviòª§l["]0â^)„2æδ∍G1∊EÌLÝ'îôΛβ;ƒĀαÏw L°gðÈγ³€wE‘f饤šαrˆQŠë¢-º8Æ~ÁŠ∍δBx®(β™Žü6»ƶÙÐ~†«\%ÍŒΘ-´sÈƵJŸ₃H7Ó˜:Å∍₂èÑï∞—Râú'óвb…ÓUXʒǝ₄ÝrÒ₄¨÷ä褓oθWÎλî~bj(Ri
Þиe‘ãj]•", yes"J'x¡Ω
```
[Try it online!](https://tio.run/##DdBJSwJxHMbxe68iBsKihQxaqE5BC9GljYp2ySJpgYKyQ/J3WhiidexgpWKTlZWYjVZmy@H3NAYJf3oNvzdic3puH748tfXTLqe7WFRmlpccSg0LY6gQ6pAv2BqgaxYRmDVOVv2sHYy0TmGfUvUefCJnfVUisdjVjzv4KcEi4IWW15FlcW59bU4iuDYPk@7pdmFUGa@FMVFhW3W4kRlb6nSytteO/R6EHUgiIy@k2ZLXv4V8wtF6aQ@l5pCCJtOUZjWx3s4iOCvf6Jpi1qV8Wins9lpRPJBRTbkm7Prgt6K2KjNtXkqWS5O3DesTHw30nn/BGY59LKL0MFaGA0uXwWrKrNqtz91WltWtrkYECqFm7NgAqyriOMEjaxEWp30wkHMg/We6WNwgMDj8q/@EWd1GeAW6vRTHK2KIU4xFaFlmh3Ao35H0uTzlffMliPxl3XY5rjzj9qtKVemGe1XpdnjpUt4Vi/8 "05AB1E – Try It Online")
Pretty basic solution. The possible answers are concatenated with the character x (since it's not present in the answers) and then compressed (inside the **•**), **'x¡Ω** split on x and pop a random choice.
Thanks to @Emigna for pointing out that the alphabet compression doesn't like ' or , much. Fixed by surrouding the compressed string with *don'* and *, yes*.
[Answer]
## Excel, 399 Bytes
```
=CHOOSE(1+20*RAND(),"It is certain","It is decidedly so","Without a doubt","Yes definitely","You may rely on it","As I see it, yes","Most likely","Outlook good","Yep","Signs point to yes","Reply hazy try again","Ask again later","Better not tell you now","Cannot predict now","Concentrate and ask again","Don't count on it","My reply is no","My sources say no","Outlook not so good","Very doubtful")
```
Since `CHOOSE(X.Y,<>)` is the same as `CHOOSE(X,<>)`, no need for an `INT`
Not much golfing you can do here though...
[Answer]
# [PHP](http://php.net/), ~~412~~ ~~385~~ ~~337~~ 384 bytes
```
<?php $a=explode(1,"It is certain1It is decidedly so1Without a doubt1Yes definitely1You may rely on it1As I see it, yes1Most likely1Outlook good1Yep1Signs point to yes1Reply hazy try again1Ask again later1Better not tell you now1Cannot predict now1Concentrate and ask again1Don't count on it1My reply is no1My sources say no1Outlook not so good1Very doubtful");echo$a[array_rand($a)];
```
[Try it online!](https://tio.run/##NVDLSkMxEP2VoRRsoZusq0i1my6KoKAUERmTaW9ozIRkgsafv0566WoenDmPSUMax9v7NCSY4x39psCOFmY12wn4ApayoI9mmhxZ78iFBoXNm5eBqwCC4/ol5kAdcPTRC4VmDlzhGxtkHYAjeDGbAjsoRNqvoFExey4CwZ87/qlKYD7DidkpVzIv/hQLJPZRQPiCf6akZAP@NZDcAE/d2qacpw4CCmXzQKIFIusZhQBNjUT@MY8Y@y5lct7KtOJoKUrWO8DoAK9UZsvxRsByVfHJ/L5H6fL6h8h9LFyz1dBFU@rmGqCLFJ5yvJLavLznWMNsuSY78BzfMWdsn1klF3NcfqzH8R8f "PHP – Try It Online")
Fairly straight forward solution. Split the string by a delimiter(in this case `1`) and choose a random element from the array.
[Answer]
# Javascript, 372 bytes
*-10 bytes thanks to Shaggy*
```
_=>"It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful".split`.`[Math.random()*20|0]
```
[Try it online!](https://tio.run/##NVDBSgQxDP2VsBdnRIt4V1j1sodFUFAWEbe22dm63WRoU6X@/Jju4CnJ4yXvvXzZb5tdCqNcEnucHFPmiCby0HXTx83tYiUQMjhMYgOZefLogkcfK2Q2r0H2XAQseC6fYjbYCLtAQTBWs@ECR1sh6QBMEMQsM6wgI2p/ARWzWXMWiOHQ@I9FIvMBBmavt0bzHAbKMHIgAeET/wlHPba3vxUkVbBDs7bMh7mDaAWTuUPRAsS6hjFCVSPEP@beUsPGhD44mSEmhyRJ98CSB/t/yjwwnQk4Lio@m1@3KE1e/0DcxswlOQ2dNaUi/wGaSOY5xwuqzdN7diUuTB5jkK3Zvq2t7M1O6ak7tUnV@dj159dX/fvUd30//QE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Befunge](http://www.quirkster.com/iano/js/befunge.html)
~~1221~~ 870 bytes (perimeter of the entire field is ~~33x36~~ 30\*29 charachters) Thanks to Jo King for helping me to remove the trailing nulls and urging me to change the randomizer.
```
"<"99+9+1+v
v <
>>>>>>>>>>55++v
0123456789
>??????????<
0123456789
>>>>>>>>>> v
>88++p v
v"It is certain"
v"It is decidedly so"
v"Without a doubt"
v"Yes definitely"
v"You may rely on it"
v"As I see it, yes"
v"Most likely"
v"Outlook good"
v"Yep"
v"Signs point to yes"
v"Reply hazy try again"
v"Ask again later"
v"Better not tell you now"
v"Cannot predict now"
v"Concentrate and ask again"
v"Don't count on it"
v"My reply is no"
v"My sources say no"
v"Outlook not so good"
v"Very doubtful"
>:#,_@
```
The top line puts the '<' character and the x-position (28) where it should go on the stack. Then we enter the sort of random number generator. This could be improved, but this is what I could deliver on short notice... The "random" number is offset to get the actual "random" line to read.
After the random number is generated, we put the '<' character at that line and push the letters on the stack and on the bottom line output them again.
Note; if you use the interpreter I linked to in this posts title you have to reclick the "Show" after each run, because the addition of the '<' character remains after execution.
[Answer]
# [Java 8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) , ~~433~~, ~~392~~, ~~380~~, 379 bytes
```
a->"It is certain~It is decidedly so~Without a doubt~Yes definitely~You may rely on it~As I see it, yes~Most likely~Outlook good~Yep~Signs point to yes~Reply hazy try again~Ask again later~Better not tell you now~Cannot predict now~Concentrate and ask again~Don't count on it~My reply is no~My sources say no~Outlook not so good~Very doubtful".split("~")[(int)(Math.random()*20)]
```
[Try it online!](https://tio.run/##TVHBTiMxDL33K6xemEEwWnFFi9SFSw8VEpVYIcTBJO40NI1HidPVsCK/3nU6gDYXx479/F7eGx7wkgcKb3Z3HPKrdwaMx5RghS78nYEeF4TiBg3BAqZKPWuJLvSAzSM7C4f2@vTyMTuFJCiKtACEn3DEy5v5UsAlMBRFccuUWTLOkvUjJC6/nWw5i05Yzq9Snqg2bFxwQn4sT5xhjyNETYADOCmLBEtIRHq/gJFSWXES8G5X@@@zeOYd9MxWsYaydn1IMLCqAeFT/wMNCrbF9xEkjoB9pbZIu@kGHlV3@UWiAQLrGHkPoxIJ/KfcYqi1IZJ1RqYSB0NBos4BBgv4BVXulPGZgOGs2yf2q6ql7tePCFzTxDkaVZ1Upla@FNQtiSchj6Q8T/@zyX7epcE7aeZl3j43qqttVijbLupu3jft@dWP9uV4PTny6e2nMYfq2V6ZNZONzy@AsU/t//6OSWjfqSXdoC3iQ4MdNiF7336b/TE7/gM "Java (OpenJDK 8) – Try It Online")
* 41 bytes thanks to AdmBorkBork!
* 10 bytes thanks to Kevin!
* 1 byte thanks to Oliver!
[Answer]
# [Red](http://www.red-lang.org), 367 bytes
```
prin pick split{It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful}"."random 20
```
[Try it online!](https://tio.run/##NVBNSwNBDP0rj168yFT8B1UvPRShglLEw7iT1rDTyTCTRUbxt6@ZLj0lLyR5H4XCvKeA9w8Un4Kc15UMJvleK59pzoUTMg8jao6sv1sFVwxU1HNyCwo0cKAQG6q4N9YvmRQeQaZPdQfqC0dOrBSbO8iEs28oBiAJrG5TsYWxWn@LRtXtpCoij33/edIoMuIkEuxXdi98ShVZOClULvt7yvbsy/80aGnwpy5tU8elQ/RKxT2QWjFjdkYxopkQc@kefeqzXCjwoMtI0kBJi93BMoG/vnJPkm4Ug0xGvojfdSud3nJI0mGVqQxmuppLm1wNdJIqi49XMpmXeI5T/Fu51RI97u/m@R8 "Red – Try It Online")
It doesn't seem really random in TIO (although it works just fine in the Red Console), that's why I added a random/seed to the header.
[Answer]
# [Aceto](https://github.com/aceto/aceto), 345 + 1 = 346 bytes (+1 for `-l` flag)
```
"It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful"'.:Yp
```
[Try it online!](https://tio.run/##NVBBTgMxDPyK1UsvkAdwK3DpoUKiEmiPIXG30QY7ih2h8HgWp6ue7BnZnhn7gMrrujsqJIGAVX0it6GIIUWMuYOw@0x65abgIXL7UjfhGLgkSoq5u4kbfPsO1QAwQVJ3EDiCIFr/AB3FnVgUclrG/FvTzLzAzBztVnHnNJNA4UQKyrf5dyx27Op/O2jt4Odh7SDL1kH2itU9o1oBYlvDnKGbEeIf9@JpcKViTEE3iikgabU98BTB30@5V6a9QuBm4pv504gy5O0PxAMKtxostFhKY@4BhojwluMDzebtPZeWd3v3NJV1/eOiiUnWx/wP "Aceto – Try It Online")
Not overly interesting, but I can't think of anything shorter in this language, no compressed strings or anything.
```
"...." push strings separated by periods
'. literal period
: split on period
Y shuffle stack
p print top
```
[Answer]
## C - 426 bytes
```
char a[][99]={"It is certain","It is decidedly so","Without a doubt","Yes definitely","You may rely on it","As I see it, yes","Most likely","Outlook good","Yep","Signs point to yes","Reply hazy try again","Ask again later","Better not tell you now","Cannot predict now","Concentrate and ask again","Don't count on it","My reply is no","My sources say no","Outlook not so good","Very doubtful"};int main(){int n;puts(a[n%20]);}
```
Uses an uninitialized variable mod 20 to index into an array of strings containing all possible outputs. Compilers complain that stdio.h isn't included, but it works OK. Probably because it *just so happens* to have the standard library linked in anyways. Lucky me.
[Answer]
# Go, 530 Bytes
```
package main;import"fmt";func main(){for k:=range map[string]struct{}{"It is certain":{},"It is decidedly so":{},"Without a doubt":{},"Yes definitely":{},"You may rely on it":{},"As I see it, yes":{},"Most likely":{},"Outlook good":{},"Yep":{},"Signs point to yes":{},"Reply hazy try again":{},"Ask again later":{},"Better not tell you now":{},"Cannot predict now":{},"Concentrate and ask again":{},"Don't count on it":{},"My reply is no":{},"My sources say no":{},"Outlook not so good":{},"Very doubtful":{}}{fmt.Print(k);break}}
```
Please note that, on the Go Playground, because of how seeding works, it always gives the same result. When running on a regular computer, everything works as it should.
I think it is possible to save a bit more but my knowledge in Go stops there :)
[Formatted and testable version](https://play.golang.org/p/qi0qnfT4JhT)
[Answer]
# Excel-VBA, ~~362~~ ~~341~~ 339 Bytes
```
v=[1:1]:?v(1,Rnd*19)
```
Where `A1:T1` contain the different options. Reads entire first row of sheet into array `v` and indexes a random point along the first 19 values.
Surprised to find that indexing an array doesn't require integer values
[Answer]
# Julia , 381 bytes
```
a=split("It is certain.It is decidedly so.Without a doubt.Yes definitely.You may rely on it.As I see it, yes.Most likely.Outlook good.Yep.Signs point to yes.Reply hazy try again.Ask again later.Better not tell you now.Cannot predict now.Concentrate and ask again.Don't count on it.My reply is no.My sources say no.Outlook not so good.Very doubtful",".")
print(a[rand(1:length(a))])
```
[Try it online](https://tio.run/##NVBLS8QwEL77K4ZebGEJ7FXwsOplD4ugoCziITazbbZxpiQTNP75Otmyp3nwzfeYcw7ebn@Xxd6nOXhpm72AT9BjFOvJrJPD3jt0oUBi8@5l5CxgwXH@EnPECjh58oKhmCNn@LYFog7ABF7MLsEeEqL2GyiYzIGTQPBTxT9nCcwTDMxOuWbz6gdKMLMnAeEL/gVnJRvtXwGJBexQre3StHYQrGA0DyhagFjPMAQoaoT4xzxaqrs5ovO9rCumHkmi3oElB/ZKZZ6YbgV6ziq@mj/UKFVe/0Bcx8Q59ho6aUrdXANUkcRrjjdUm5f3nHJoNo1pups5aqLWfkRVbLd3AWmQsbVd99ktyz8)
[Answer]
# Java 8, 379 Bytes
```
b->"It is certain-It is decidedly so-Without a doubt-Yes definitely-You may rely on it-As I see it, yes-Most likely-Outlook good-Yep-Signs point to yes-Reply hazy try again-Ask again later-Better not tell you now-Cannot predict now-Concentrate and ask again-Don't count on it-My reply is no-My sources say no-Outlook not so good-Very doubtful".split("-")[(int)(Math.random()*20)]
```
[Try it online](https://tio.run/##TVHBaiMxDL3nK0QuO1PqIey1sNB2LzmEhQ20lNKDYysTN441WHLb2dJvz8ozLfRiW/LT05Pes32xhgZMz/54dtEyw8aGBO@LoexicMBiRa8XCh5O@tNsJYfUPz6BzT23ChRkadqrxcdiEZJg3luHYNnv4R1mMEwQ/YRdewWK@046lysPvqErgs15Z34t1wKBwWEW7WnmyKMLHn0cgcncBzlQEbDgqezEPGAF7EMKgnE0D1RU7ghZA6AEQcw1wxoYUd@XMCKbDbFADMeK/1MkEh2hJ/LKNZht6BPDQFW10IT/i4OSHey/ESSPYPsq7ZqP8wui1eHNDYpekEjLMEYYVUiiV3NrU80NGX1wMqcoOUyStQ5s8rqzTyrzm9IPAUdFm8/iN3WU2l73kKiGTCU7HZp1Ss18DVCbMM1z3KHKnNazL3HZ8RCDNEuzbB@rGW2zsXLosramU9Ne/Fy1T@fZx@/@fNkyOVqP6tV2ZMFTpwZ0gzosMU3/3WTmqp1YPs7/AQ)
] |
[Question]
[
# Definitions
* A **perfect square** is an integer which can be expressed as the square of another integer. For example, `36` is a perfect square because `6^2 = 36`.
* A **squarefree number** is an integer which is not divisible by any perfect square, except by `1`. For example, `10` is a squarefree number. However, `12` is not a squarefree number, because `12` is divisible by `4` and `4` is a perfect square.
# Task
Given a positive integer `n`, output the largest squarefree number which divides `n`.
# Testcases
```
n output
1 1
2 2
3 3
4 2
5 5
6 6
7 7
8 2
9 3
10 10
11 11
12 6
13 13
14 14
15 15
16 2
17 17
18 6
19 19
20 10
21 21
22 22
23 23
24 6
25 5
26 26
27 3
28 14
29 29
30 30
31 31
32 2
33 33
34 34
35 35
36 6
37 37
38 38
39 39
40 10
41 41
42 42
43 43
44 22
45 15
46 46
47 47
48 6
49 7
50 10
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
# Reference
* [OEIS A007947](http://oeis.org/A007947)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
fP
```
[Try it online!](https://tio.run/nexus/05ab1e#@58W8P@/iQUA "05AB1E – TIO Nexus")
### How it works
```
f Implicitly take input and compute the integer's unique prime factors.
P Take the product.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
ḋd×
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9wR3fK4en//xsZ/I8CAA "Brachylog – TIO Nexus")
A very original answer...
### Explanation
```
ḋ Take the prime factors of the Input
d Remove duplicates
× Multiply
```
[Answer]
## JavaScript (ES6), ~~55~~ ~~54~~ ~~50~~ 46 bytes
Quoting [OEIS](http://oeis.org/A007947):
*a(n) is the smallest divisor u of n such that n divides u^n*
Updated implementation:
*a(n) is the smallest ~~divisor u of n~~ positive integer u such that n divides u^n*
```
let f =
n=>(g=(p,i=n)=>i--?g(p*p%n,i):p?g(++u):u)(u=1)
for(n = 1; n <= 50; n++) {
console.log(n,f(n));
}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~6~~ 4 bytes
*2 bytes saved with help from @LeakyNun*
```
Yfup
```
[Try it online!](https://tio.run/nexus/matl#@x@ZVlrw/7@JBQA "MATL – TIO Nexus")
### Explanation
Consider input `48`.
```
Yf % Implicit input. Push prime factors with repetitions. STACK: [2 2 2 2 3]
u % Unique. STACK: [2 3]
p % Product of array. Implicit display. STACK: 6
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ÆfQP
```
[Try it online!](https://tio.run/nexus/jelly#@3@4LS0w4P/h9kdNa/7/jza00FEwMgBiEyA2BWIg38QiFgA "Jelly – TIO Nexus")
```
ÆfQP Main link, argument is z
Æf Takes the prime factors of z
Q Returns the unique elements of z
P Takes the product
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
rimf_&:*
```
Why does every operation in this program have to be 2 bytes -\_-
[Try it online!](https://tio.run/nexus/cjam#@1@UmZsWr2al9f@/OQA "CJam – TIO Nexus")
```
ri e# Read int from input
mf e# Get the prime factors
_& e# Deduplicate
:* e# Take the product of the list
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~36~~ ~~30~~ 28 bytes
```
+`((^|\3)(^(1+?)|\3\4))+$
$3
```
Input and output [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary).
[Try it online!](https://tio.run/nexus/retina#DY27DcMwEMV6zuEAUgQEenenX5VFDMODZHdHHRuSr3R/Csf7KXdK1@/0nK6k8s0bz8i5HBz@6BGGEzQ6g8lCFQkZchSooY4GmmhhFduOYY4F1rCODWxiC6@48J10PPCGd3zgE19EJUQYsY9BNKITg5jEotU/ "Retina – TIO Nexus") (Includes a header and footer for decimal <-> unary conversion and to run multiple test cases at once.)
### Explanation
The idea is to match the input as a square times some factor. The basic regex for matching a square uses a forward-reference to match sums of consecutive odd integers:
```
(^1|11\1)+$
```
Since we don't want to match perfect squares, but numbers that are divisible by a square, we replace that `1` with a backreference itself:
```
(^(1+?)|\1\2\2)+$
```
So now the outer group `1` will be used **n** times where **n2** is the largest square that divides the input and group `2` stores the remaining factor. What we want is to divide the integer by **n** to remove the square. The result can be expressed as the number of iterations of group `1` times group `2`, but this is a bit tricky to do. Retina's `$*` will probably soon be improved to take a non-character token as its right hand argument in which case we could simply replace this with `$#1$*$2`, but that doesn't work yet.
Instead, we decompose the odd numbers differently. Let's go back to the simpler example of matching perfect squares with `(^1|11\1)+$`. Instead of having a counter `\1` which is initialised to **1** and incremented by **2** on each iteration, we'll have two counters. One is initialised to **0** and one is initialised to **1**, and they're both incremented by **1** on each iteration. So we've basically decomposed the odd numbers **2n+1** into **(n) + (n+1)**. The benefit is that we'll end up with **n** in one of the groups. In its simplest form, that looks like this:
```
((^|1\2)(^1|1\3))+$
```
Where `\2` is **n** and `\3` is **n+1**. However, we can do this a bit more efficiently by noticing that the **n+1** of one iteration is equal to the **n** of the next iteration, so we can save on a `1` here:
```
((^|\3)(^1|1\3))+$
```
Now we just need to go back to using an initial factor instead of `1` to match inputs that are divided by a perfect square:
```
((^|\3)(^(1+?)|\3\4))+$
```
Now all we need to do is replace this entire thing with `$3` at the end, which stores the initial factor times the number of steps, which drops one factor of the square from the input.
This is done repeatedly with the `+` at the very beginning of the program, to account for inputs that contain higher powers than squares.
[Answer]
# Octave, 27 bytes
```
@(x)prod(unique(factor(x)))
```
Similar approach as the other answers. The difference is: The functions have much longer names. I believe the code explains itself really:
Takes the `prod`uct of the `unique` prime `factor`s of a number.
[Answer]
# Wolfram Language, ~~29~~ 28 bytes
-1 Thanks to [@Martin Ender ♦](https://codegolf.stackexchange.com/users/8478/martin-ender)
```
Most[1##&@@FactorInteger@#]&
```
**Explanation:**
```
FactorInteger@# (*Get prime factorization as {{a,b},{c,d}}*)
1##&@@ (*Multiply list elements together, to get the product of the factors and the product of their exponents*)
Most[ ]& (*Take the first element*)
```
[Answer]
# [Python](https://docs.python.org/2/), 37 bytes
```
f=lambda n,r=1:1>>r**n%n or-~f(n,r+1)
```
[Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnU2RraGVoZ1ekpZWnmqeQX6Rbl6YBFNU21Pyfll@kkKeQmadQlJiXnqphqGNqoGnFxVlQlJlXAtSpAFSo@R8A "Python 2 – TIO Nexus")
The largest squarefree divisor of `n` is that smallest number `r` with all of `n`'s prime factors. We can check this as `r**n%n==0`, since `r**n` make `n` copies of each prime factor of `r`, and is divisible by `n` only if each of `n`'s prime factors is represented.
The `1>>r**n%n` is equivalent to `int(r**n%n==0)`. If `True` can be used output 1, it's 2 bytes shorter to do.
```
f=lambda n,r=1:r**n%n<1or-~f(n,r+1)
```
[Answer]
# [Mathics](http://mathics.github.io/), 40 bytes
```
Times@@(Transpose@FactorInteger@#)[[1]]&
```
[Try it online!](https://tio.run/nexus/mathics#S7P9H5KZm1rs4KARUpSYV1yQX5zq4JaYXJJf5JlXkpqeWuSgrBkdbRgbq/Y/oCgzr8QhzcHY7D8A "Mathics – TIO Nexus")
[Answer]
## [Alice](https://github.com/m-ender/alice), 4 bytes
```
iDo@
```
[Try it online!](https://tio.run/nexus/alice#@5/pku/w/38yAA "Alice – TIO Nexus")
Input and output are given [as the code point of a character](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values) (works for all valid Unicode code points).
### Explanation
Well, Alice has a built-in `D` whose definition is "Deduplicate prime factors". That is, as long as a value is divisible by some **p2** for a prime **p**, divide that value by **p**. This happens to be exactly the function required in this challenge. The rest is just input, output, terminate the program.
The reason this was added to Alice actually has nothing to do with this integer sequence. I was trying to stick to a theme of associating divisors with substrings and prime factors with characters. And I needed a function that goes with "deduplicate characters" (which is much more useful in general, because it let's you treat strings as sets, especially when used together with the various multiset operators).
[Answer]
# [Haskell](https://www.haskell.org/), 31 bytes
```
f n=until(\r->r^n`mod`n<1)(+1)1
```
[Try it online!](https://tio.run/nexus/haskell#@5@mkGdbmleSmaMRU6RrVxSXl5Cbn5KQZ2OoqaFtqGn4PzcxM0/BVqGgKDOvREFFIVojTydNI09TsybPRjfaUE/P1CA29j8A "Haskell – TIO Nexus")
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 3 bytes
```
P}B
```
[Try it online!](https://tio.run/nexus/pyke#@x9Q6/T/v6ERAA "Pyke – TIO Nexus")
```
P - factors(input)
} - uniquify(^)
B - product(^)
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~84~~ 39 bytes
```
f(N,P):-between(1,N,P),P^N mod N=:=0,!.
```
[Try it online!](https://tio.run/nexus/prolog-swi#TdJNasMwEAXgfU@hZmWDY6yZ8V8g9AbGJyi0RIFCm5bakOO7z36W0t3zIM2nkbxcs6EY89PxPcz3EG6ZL9bvYnwd3Nf3xQ3n07kqnsvl5eiumXeF83mBJEiyJUXSLVmq1Uj1lhqkZkstUrulLq3r015foXPF6BGpeIm7vaK4LzVEY6wRCfkmNvUtipR8l/b3KPY8@oMSULIPBErYQGAJLbHYQOo4kqzSXmzj@aVLhxJQQkpBKSkFpaRU0t1BUjZQSMoGCkppaRN9XSlOpbC0Y4SltOwxlsEyWgbLiBkw21/K0rD2uEIDZtQMmlGzdIfWxxeso3X//ZjD5y07zGGaJ/fzNk3hcsjLJ/4u6yTjv2VjXi5/ "Prolog (SWI) – TIO Nexus")
Adapted the idea of [@xnor's Haskell answer](https://codegolf.stackexchange.com/a/120136/69074) to Prolog.
[Answer]
# PHP, 70 Bytes
```
for($r=1,$i=2;1<$n=&$argn;)$n%$i?++$i:$n/=$i+!($r%$i?$r*=$i:1);echo$r;
```
[Try it online!](https://tio.run/nexus/php#HYpNCoAgEEb33SL4isogLGjhOHiWiEo3KnN/MGv5fqzLPjc45Im87VTuJAOE9YzAK2mLyP1faUTsEJxSCAZxYQTV1vVzkKmi0SNdp08QKuUF "PHP – TIO Nexus")
[Answer]
# Pyth, ~~8~~ 6 bytes
```
*F+1{P
```
\*-2 bytes thanks to @LeakyNun
Would be 3 if Pyth had a built-in for products of lists...
[Try it!](https://pyth.herokuapp.com/?code=%2aF%2B1%7BP&input=12&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25%0A26%0A27%0A28%0A29%0A30%0A31%0A32%0A33%0A34%0A35%0A36%0A37%0A38%0A39%0A40%0A41%0A42%0A43%0A44%0A45%0A46%0A47%0A48%0A49%0A50&debug=0)
```
*F+1{P
Q # Implicit input
P # Prime factors of the input
{ # Deduplicate
+1 # Prepend 1 to the list (for the case Q==1)
*F # Fold * over the list
```
[Answer]
# C, ~~65~~ 50 bytes
Thanks to @Ørjan Johansen for removing the need for `r`. Thanks to this and some other dirty tricks I was able to squeeze 15 bytes off!
```
d;f(n){for(d=1;d++<n;)n%(d*d)||(n/=d--);return n;}
```
`while` is gone and replaced with `||` and index twiddling. `<=` should have been `<` all along.
~~`<=` turned to `<` by moving the increment to get `n%(++d*d)` (should be well defined due to operator precedence).~~
---
Original code:
```
d;r;f(n){for(r=d=1;d++<=n;)while(n%d<1)r*=r%d?d:1,n/=d;return r;}
```
[Answer]
# Axiom, 89 bytes
```
f(x:PI):PI==(x=1=>1;g:=factor x;reduce(*,[nthFactor(g,i) for i in 1..numberOfFactors g]))
```
test and results
```
(38) -> [[i, f(i)] for i in 1..30 ]
(38)
[[1,1], [2,2], [3,3], [4,2], [5,5], [6,6], [7,7], [8,2], [9,3], [10,10],
[11,11], [12,6], [13,13], [14,14], [15,15], [16,2], [17,17], [18,6],
[19,19], [20,10], [21,21], [22,22], [23,23], [24,6], [25,5], [26,26],
[27,3], [28,14], [29,29], [30,30]]
```
this is the one not use factor() function
```
g(x:PI):PI==(w:=sqrt(x);r:=i:=1;repeat(i:=i+1;i>w or x<2=>break;x rem i=0=>(r:=r*i;repeat(x rem i=0=>(x:=x quo i);break)));r)
```
but it is only 125 bytes
[Answer]
# R, 52 bytes
```
`if`((n=scan())<2,1,prod(unique(c(1,gmp::factorize(n))))
```
reads `n` from stdin. Requires the `gmp` library to be installed (so TIO won't work). Uses the same approach as many of the above answers, but it crashes on an input of `1`, because `factorize(1)` returns an empty vector of class `bigz`, which crashes `unique`, alas.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 2 bytes
```
yπ
```
[Try it online!](https://tio.run/nexus/actually#@195vuH/fxMLAA "Actually – TIO Nexus")
Explanation:
```
yπ
y prime divisors
π product
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 28 bytes
```
n->factorback(factor(n)[,1])
```
[Try it online!](https://tio.run/nexus/pari-gp#S1OwVfifp2uXlphckl@UlJicrQFhauRpRusYxmr@TwOxgaoMdRRMDXQUCooy80o08nQUlBR07RSUdBTSgCo1Nf8DAA "Pari/GP – TIO Nexus")
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 3 bytes
```
←ϼΠ
```
Explanation:
```
← Get input
ϼ Get list of unique prime factors
Π Compute product of list
Implicit print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
ǏΠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLGm8O3JDoiLCLHj86gIiwiXCI6YCA9PiBgaiR04oCePWDinYzinIVgaeG6izvigYsiLCJbWzEsMV0sWzIsMl0sWzMsM10sWzQsMl0sWzUsNV0sWzYsNl0sWzcsN10sWzgsMl0sWzksM10sWzEwLDEwXSxbMTEsMTFdLFsxMiw2XSxbMTMsMTNdLFsxNCwxNF0sWzE1LDE1XSxbMTYsMl0sWzE3LDE3XSxbMTgsNl0sWzE5LDE5XSxbMjAsMTBdLFsyMSwyMV0sWzIyLDIyXSxbMjMsMjNdLFsyNCw2XSxbMjUsNV0sWzI2LDI2XSxbMjcsM10sWzI4LDE0XSxbMjksMjldLFszMCwzMF0sWzMxLDMxXSxbMzIsMl0sWzMzLDMzXSxbMzQsMzRdLFszNSwzNV0sWzM2LDZdLFszNywzN10sWzM4LDM4XSxbMzksMzldLFs0MCwxMF0sWzQxLDQxXSxbNDIsNDJdLFs0Myw0M10sWzQ0LDIyXSxbNDUsMTVdLFs0Niw0Nl0sWzQ3LDQ3XSxbNDgsNl0sWzQ5LDddLFs1MCwxMF1dIl0=)
] |
[Question]
[
# Background
A **[triangular grid](http://mathworld.wolfram.com/TriangularGrid.html)** is a grid formed by tiling the plane regularly with equilateral triangles of side length 1. The picture below is an example of a triangular grid.
![](https://i.stack.imgur.com/pmooq.gif)
A **triangular lattice point** is a vertex of a triangle forming the triangular grid.
The **origin** is a fixed point on the plane, which is one of the triangular lattice points.
# Challenge
Given a non-negative integer `n`, find the number of triangular lattice points whose Euclidean distance from the origin is less than or equal to `n`.
# Example
The following figure is an example for `n = 7` (showing only 60-degree area for convenience, with point A being the origin):
![](https://i.stack.imgur.com/xw9yl.png)
# Test Cases
```
Input | Output
---------------
0 | 1
1 | 7
2 | 19
3 | 37
4 | 61
5 | 91
6 | 127
7 | 187
8 | 241
9 | 301
10 | 367
11 | 439
12 | 517
13 | 613
14 | 721
15 | 823
16 | 931
17 | 1045
18 | 1165
19 | 1303
20 | 1459
40 | 5815
60 | 13057
80 | 23233
100 | 36295
200 | 145051
500 | 906901
1000 | 3627559
```
**Hint**: This sequence is *not* [OEIS A003215](https://oeis.org/A003215).
# Rules
Standard rules for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. The shortest submission wins.
Please include how you solved the challenge in your submission.
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
f=lambda n,a=1:n*n<a/3or n*n/a*6-f(n,a+a%3)
```
[Try it online!](https://tio.run/##FYzBCsIwEETv@Yq9CEmt1rbQQ7Efs2qiC80mbOKhXx/XgYGBx7x81E/iqbWw7RgfLwTucRtX7viOw5wEdA3YLZdglZzxNLtGMSepUI5itNfiq/jnVwol3ilStdNN44wJ/z8QgyC/vV1Gt2YhrqAu9TnXfg "Python 2 – Try It Online")
This is black magic.
**[Offering 250 rep](https://codegolf.meta.stackexchange.com/a/16359/20260) for a written-up proof.** See [Lynn's answer](https://codegolf.stackexchange.com/a/164474/20260) for a proof and explanation.
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
f n=1+6*sum[(mod(i+1)3-1)*div(n^2)i|i<-[1..n^2]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz9ZQ20yruDQ3WiM3P0UjU9tQ01jXUFMrJbNMIy/OSDOzJtNGN9pQTw/IiY39n5uYmadgq1BQlJlXoqCRpmBoYKD5HwA "Haskell – Try It Online")
Uses xnor's "black magic" formula:
$$f(n)=1+6\sum\_{a=0}^\infty \left\lfloor \frac{n^2}{3a+1}\right\rfloor - \left\lfloor \frac{n^2}{3a+2}\right\rfloor$$
A proof of its correctness, and an explanation of how xnor managed to express it in 43 bytes of Python, can be found [**here**](http://foldr.moe/blackmagic.pdf).
>
> Long story short: we count [Eisenstein integers](https://en.wikipedia.org/wiki/Eisenstein_integer) of norm \$1 \le N \le n^2\$, by factoring \$N = (x+y\omega)(x+y\omega^\*)\$ into [Eisenstein primes](https://en.wikipedia.org/wiki/Eisenstein_prime) and counting how many solutions for \$(x,y)\$ come out of the factorization. We recognize the number of solutions as being equal to
>
>
> $$6 \times ((\text{# of divisors of }N \equiv 1\space(\text{mod }3)) - (\text{# of divisors of }N \equiv 2\space(\text{mod }3)))$$
>
>
> and apply a clever trick to make that really easy to compute for all integers between \$1\$ and \$n^2\$ at once. This yields the formula above. Finally, we apply some Python golf magic to end up with the really tiny solution xnor found.
>
>
>
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~53~~ ~~51~~ 50 bytes
-1 byte thanks to @miles
```
Sum[Boole[x(x+y)+y^2<=#^2],{x,-2#,2#},{y,-2#,2#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g0N9opPz8nNbpCo0K7UlO7Ms7IxlY5zihWp7pCR9dIWcdIuVanuhLGjFX775IfHVCUmVcSnaega6eQFp0XG6ujUJ2no2Cgo2BkUBv7HwA "Wolfram Language (Mathematica) – Try It Online")
## How?
Instead of thinking in this:
[![enter image description here](https://i.stack.imgur.com/C13c8m.png)](https://i.stack.imgur.com/C13c8m.png)
Think of it like this:
[![enter image description here](https://i.stack.imgur.com/U8KTVm.png)](https://i.stack.imgur.com/U8KTVm.png)
So we apply the tranformation matrix `[[sqrt(3)/2, 0], [1/2, 1]]` to transform the second figure to the first one.
Then, we must find the circle in the triangular grid in terms of Cartesian coordinates.
```
(sqrt(3)/2 x)^2 + (1/2 x + y)^2 = x^2 + x y + y^2
```
So we find lattice points `x, y` such that `x^2 + x y + y^2 <= r^2`
For example, with `r = 3`:
[![enter image description here](https://i.stack.imgur.com/1Spuu.png)](https://i.stack.imgur.com/1Spuu.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
Based on OEIS [A004016](https://oeis.org/A004016).
```
1+6Sum[DivisorSum[i,#~JacobiSymbol~3&],{i,#^2}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@99Q2yy4NDfaJbMsszi/CMTM1FGu80pMzk/KDK7MTcrPqTNWi9WpBorGGdXGqv13yY8OKMrMK4nOU9C1U0iLzouN1VGoztNRMNBRMDKojf0PAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
### CJam (24 bytes)
```
{_*_,f{)_)3%(@@/*}1b6*)}
```
This is an anonymous block (function) which takes one argument on the stack and leaves the result on the stack. [Online test suite](http://cjam.aditsu.net/#code=q'%7C-~%5D2%2F%7B%0A~%5C%0A%0A%7B_*_%2Cf%7B)_)3%25(%40%40%2F*%7D1b6*)%7D%0A%0A~%3Do%0A%7D%2F&input=%20%20%20%200%20%7C%20%20%20%20%20%20%201%0A%20%20%20%201%20%7C%20%20%20%20%20%20%207%0A%20%20%20%202%20%7C%20%20%20%20%20%2019%0A%20%20%20%203%20%7C%20%20%20%20%20%2037%0A%20%20%20%204%20%7C%20%20%20%20%20%2061%0A%20%20%20%205%20%7C%20%20%20%20%20%2091%0A%20%20%20%206%20%7C%20%20%20%20%20127%0A%20%20%20%207%20%7C%20%20%20%20%20187%0A%20%20%20%208%20%7C%20%20%20%20%20241%0A%20%20%20%209%20%7C%20%20%20%20%20301%0A%20%20%2010%20%7C%20%20%20%20%20367%0A%20%20%2011%20%7C%20%20%20%20%20439%0A%20%20%2012%20%7C%20%20%20%20%20517%0A%20%20%2013%20%7C%20%20%20%20%20613%0A%20%20%2014%20%7C%20%20%20%20%20721%0A%20%20%2015%20%7C%20%20%20%20%20823%0A%20%20%2016%20%7C%20%20%20%20%20931%0A%20%20%2017%20%7C%20%20%20%201045%0A%20%20%2018%20%7C%20%20%20%201165%0A%20%20%2019%20%7C%20%20%20%201303%0A%20%20%2020%20%7C%20%20%20%201459%0A%20%20%2040%20%7C%20%20%20%205815%0A%20%20%2060%20%7C%20%20%2013057%0A%20%20%2080%20%7C%20%20%2023233%0A%20%20100%20%7C%20%20%2036295%0A%20%20200%20%7C%20%20145051). Note that the two largest cases are too slow.
### Explanation
[alephalpha](/users/9288/alephalpha) noted in a comment on the question that
>
> It is the sum of the first n^2+1 terms of [OEIS A004016](//oeis.org/A004016)
>
>
>
and [xnor's answer](/a/163708/194) implements this sum (although I'm not sure whether their unposted proof uses it explicitly) as $$f(n) = 1 + 6 \sum\_{a=0}^\infty \left\lfloor\frac{n^2}{3a+1}\right\rfloor - \left\lfloor\frac{n^2}{3a+2}\right\rfloor$$
[My proof of correctness of that formula](http://cheddarmonk.org/papers/triangle-lattice.pdf) is based on some information gleaned from alephalpha's OEIS link:
>
> G.f.: 1 + 6\*Sum\_{n>=1} x^(3\*n-2)/(1-x^(3\*n-2)) - x^(3\*n-1)/(1-x^(3\*n-1)). - Paul D. Hanna, Jul 03 2011
>
>
>
for which the relevant reference is the paper by Hirschhorn. An elementary proof is possible using nothing more than a basic understanding of complex numbers (cube roots of unity, magnitude), the concept of generating functions, the derivative of \$x^a\$, and the chain rule of differentiation. In summary, we first prove from first principles the Jacobi triple-product identity $$\prod\_{k=0}^\infty (1-q^{k+1})(1 + xq^{k+1})(1 + x^{-1}q^k) = \sum\_{k\in \mathbb{Z}} q^{k(k+1)/2}x^k$$
That then bootstraps a proof that $$\sum\_{m,n \in \mathbb{Z}} \omega^{m-n} q^{m^2+mn+n^2} = \prod\_{k=1}^\infty \frac{(1-q^k)^3}{1-q^{3k}}$$ where \$\omega\$ is a primitive cube root of unity. The final big step is to use this to show that $$\sum\_{m,n \in \mathbb{Z}} q^{m^2+mn+n^2} = 1 + 6 \sum\_{k \ge 0} \left(\frac{q^{3k+1}}{1-q^{3k+1}} - \frac{q^{3k+2}}{1-q^{3k+2}} \right)$$
### Code dissection
```
{ e# Define a block. Stack: ... r
_* e# Square it
_,f{ e# Map with parameter: invokes block for (r^2, 0), (r^2, 1), ... (r^2, r^2-1)
) e# Increment second parameter. Stack: ... r^2 x with 1 <= x <= r^2
_)3%( e# Duplicate x and map to whichever of 0, 1, -1 is equal to it (mod 3)
@@/* e# Evaluate (r^2 / x) * (x mod 3)
}
1b6* e# Sum and multiply by 6
) e# Increment to count the point at the origin
}
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 23 bytes
```
{1+6×+/-/⌊⍵÷1+3⊥¨⍳⍵2}×⍨
```
[Try it online!](https://tio.run/##PY@xSsRAEIZ7nyJdihBuZ2d3k/VtwkkkGIjcXSNynQieRmzkKgsL4XoRwdK8yb5InNnsuEXYb/5/li/NdV9e3DT9cFmu@2a77dZzeH7thnD/ouaWvrdQuOlYrMpVeDqE8Wv6hgLD4eP3FMZPYr2fjmE8zfOOyzQID@8burZh/DnPh6s8PN7lbdP1OQ0o3uzPsixT2S5bDjDCP1aMWhA8IwpiTI2gi7tW0Ed0CUHHciVYR6wTahPLPiEqRhArdFwGsTLIGiBWFmIqVg6QUawqHZ8Sq1rHVKw8xjRZgTKWMVkBuIjJClDxrk5WYCxrmIS2Bi67Balr2apeUKNG2gW1IDrtqawXpIeUJQ27oFfO0@@H8Y3qPKF2Za3/Aw "APL (Dyalog Classic) – Try It Online")
tribute to [xnor's](https://codegolf.stackexchange.com/questions/163704/triangular-lattice-points-close-to-the-origin/163708#163708) and [lynn's](https://codegolf.stackexchange.com/questions/163704/triangular-lattice-points-close-to-the-origin/164474#164474) answers
the last test is commented because it needs more memory, e.g. `MAXWS=200M` in the env
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
[:+/@,*:>:(*++&*:)"{~@i:@+:
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6OttPUddLSs7Kw0tLS11bSsNJWq6xwyrRy0rf5rcinpKaingRSrK@go1FoppBVzcaUmZ@QraOjopSkZaCpk6ikYGf4HAA "J – Try It Online")
Based on JungHwan Min's [method](https://codegolf.stackexchange.com/questions/163704/triangular-lattice-points-close-to-the-origin/163711#163711).
## Explanation
```
[:+/@,*:>:(*++&*:)"{~@i:@+: Input: n
+: Double
i: Range [-2n .. 2n]
"{~ For each pair (x, y)
*: Square both x and y
+ Add x^2 and y^2
+ Plus
* Product of x and y
>: Less than or equal to
*: Square of n
, Flatten
+/ Reduce by addition
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ḤŒR+²_×ʋþ`F½»ċ
```
Uses [@JungHwanMin's method](https://codegolf.stackexchange.com/a/163711/12012).
[Try it online!](https://tio.run/##ATwAw/9qZWxsef//4bikxZJSK8KyX8OXyovDvmBGwr3Cu8SL/zByMjA7NDAsNjAsODAsMTAwwrXFvMOH4oKsR/8 "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 thanks to Dennis (just increment the square to avoid concatenation of a zero; avoid head by using a post-difference modulo-slice rather than a pre-difference slice)
Uses the "black magic" method of honing in on the answer that was exposed by xnor in their [Python answer](https://codegolf.stackexchange.com/a/163708/53748), but uses iteration rather than recursion (and a little less calculation)
```
²:Ѐ‘$Im3S×6C
```
A monadic link accepting a non-negative integer and returning a positive integer.
**[Try it online!](https://tio.run/##ASEA3v9qZWxsef//wrI6w5DigqzigJgkSW0zU8OXNkP///8xMDA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///QJqvDEx41rXnUMEPFM9c4@PB0M@f/R/ccbgeKuQGx@///OZnFJRpFiXnpqRpGhpqa2tEmBjpmBjoWBjqGBgY6RkBsagBmG8QCAA "Jelly – Try It Online").
### How?
```
²:Ѐ‘$Im3S×6C - Main Link: non-negative integer, n e.g. 7
² - square 49
$ - last two links as a monad:
‘ - increment 50
Ѐ - map across (implicit range of) right with:
: - integer division [49,24,16,12,9,8,7,6,5,4,4,4,3,3,3,3,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0]
I - incremental differences [-25,-8,-4,-3,-1,-1,-1,-1,-1,0,0,-1,0,0,0,-1,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1]
m3 - every third element [-25,-3,-1,0,0,-1,0,0,0,0,0,0,0,0,0,0,-1]
S - sum (vectorises) -31
×6 - multiply by six -186
C - complement (1-X) 187
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
nD>L÷¥3ιнO6*±Ì
```
Port of [*@JonathanAllan*s Jelly answer](https://codegolf.stackexchange.com/a/163729/52210), which in turn is a derivative from [@xnor's 'black magic' formula](https://codegolf.stackexchange.com/a/163708/52210).
[Try it online](https://tio.run/##AR8A4P9vc2FiaWX//25EPkzDt8KlM8650L1PNirCscOM//83) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/PBc7n8PbDy01Prfzwl5/M61DGw/3/Nf5H22gY6hjpGOsY6JjqmOmY65joWOpYwgUNNQxNNIxNNYxNNExNNUxNNMxNNcxtNAxtNQxMtAxMdAxM9CxACozMADyDXRMDcBsg1gA).
**Explanation:**
```
n # Square the (implicit) input-integer
D> # Duplicate it, and increase the copy by 1
L # Create a list in the range [1, input²+1]
÷ # Integer divide input² by each of these integers
¥ # Take the deltas / forward differences
3ι # Uninterleave this list into 3 parts
# i.e. [a,b,c,d,e] → [[a,d],[b,e],[c]]
н # Pop and leave the first inner list
O # Take the sum of this list
6* # Multiply it by 6
± # Take the bitwise NOT (-n-1)
Ì # And increase it by 2
# (after which the result is output implicitly)
```
[Answer]
# JavaScript (ES6), 65 bytes
This is a port of [@JungHwanMin's solution](https://codegolf.stackexchange.com/a/163711/58563).
```
f=(n,y=x=w=n*2)=>y-~w&&(x*x+x*y+y*y<=n*n)+f(n,y-=--x<-w&&(x=w,1))
```
[Try it online!](https://tio.run/##HctBDsIwDETRq3hVJXGNoFti7lKVBoEqG7WocTZcPaTsRpr3X@M@btP6fH9I9D7XmthJX9g4s4TB863QN3eds2BooWAJJbZHPKYDEhNZpL/g3F@8r0lXJ8BwvoJAZBiOgehhUtl0mU@LPloKrW/6Bw "JavaScript (Node.js) – Try It Online")
---
# Original answer (ES7), 70 bytes
Simply walks through the grid and counts the matching points.
```
f=(n,y=x=n*=2)=>y+n+2&&(x*x*3+(y-x%2)**2<=n*n)+f(n,y-=--x<-n&&(x=n,2))
```
[Try it online!](https://tio.run/##FcsxDsIwDEDRq3ihiuO6QmYk5i5V2yBQ5aAWoeT0Idn@8P57/s3ncrw@X7a0brVGdTYWzWpeBfVRyEiGwWWf/Y1c4XwR9F5CA4YUu2ZlzoGtM7VREGtMhzNQuN7BIChIDyKEJdmZ9m3a07Ot0P6m/w "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
```
Length@Solve[x(x+y)+y^2<=#^2,Integers]&
```
[Try it online!](https://tio.run/##FctNC4JAFIXhv3JBkMIbeSczgwy3QYug5aAgMX5ATmBDKNFvn46Ls3qfM9SuM0Pt@kftG8r91djWdcX99fwYPa2maF5Hc6VOeVApvlhnWjO@y9Dfxt46HWzOjQ7KMqRtQd@YSZgU044pYdozpUwHpozpiLRkdAEQCAERGAESKAETOAWXYCmWLZ84/vk/ "Wolfram Language (Mathematica) – Try It Online")
Using [JungHwan Min's coordinate transformation](https://codegolf.stackexchange.com/a/163711/87058) and simply counting the solutions over the integers.
[Answer]
# Java 8, 65 bytes
```
n->f(n,1)int f(int n,int a){return n*n<a/3?1:n*n/a*6-f(n,a+a%3);}
```
Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/163708/52210).
[Try it online.](https://tio.run/##LU9NT8MwDL3zK54mTUqWtWNMcFhX@AXssiNwMF2KsrXulKZDaOpvL05Asv387ecTXSk7Hc9T1VDf45Uc3@4Ax8H6miqLfQxTApWKlnUhmVFUZA9GiYmz51rxcq2L2FH/9S2jJX3zNgyewQve0Wrzst6Kt6LFUxZHyNB8o4txAi7DZ@Mq9IGCwLVzR7RCRx2Cd/z19hF3JS6RJFq5y/Y7BSpRAurOp9OuvC/gduXDo4AxOhWBw08fbJt3Q8gvsjI0rJyZbd/DzLQ55/Ke/v9tnH4B)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes
Using the built-in `qfrep`.
```
n->1+2*vecsum(Vec(qfrep([2,1;1,2],n^2,1)))
```
>
> qfrep(q,B,{flag=0}): vector of (half) the number of vectors of norms from 1 to
> B for the integral and definite quadratic form q. If flag is 1, count vectors
> of even norm from 1 to 2B.
>
>
>
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XzlDbSKssNbm4NFcjLDVZozCtKLVAI9pIx9DaUMcoVicvDsjU1NT8n5ZfpJGnYKtgoKNgBMQFRZl5JUABJQVdOyCRppEHUgQA "Pari/GP – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 68 bytes
```
n=>{int g(int x,int y)=>x*x<y/3?1:x*x/y*6-g(x,y+y%3);return g(n,1);}
```
[Try it online!](https://tio.run/##FYtBC8IgHMXvfYpdAl1ucww65LRDbKedIui8xC2h/oI6UKLPbnZ4jx8/3pOukk6ncQPZa/AkRyw8ARefjMWK/h3@uoiYi1CGPjbduT1lamJ5rFYUSDzEfYeZVX6zkD9AWsy@ie0G2N7Kzo@Xqq8zrApR0lJKcX0zk3Ye4Xo0dpjlEwUuLgacycu71V5NGhRaUMAYs/QD "C# (Visual C# Interactive Compiler) – Try It Online")
Same as everyone else, unfortunately. I know there's probably a better way of writing this, but declaring and calling a lambda at the same time in c# is not exactly something I do, well, ever. Though in my defense, I can't think of a good reason (outside code golf, of course) to do so. Still, if someone knows how you can do this, let me know and/or steal the credit, I guess.
] |
[Question]
[
## Challenge
Given an input of an integer, \$n\$ (where \$0<n<50\$), output the graph of \$y=\mathrm{Re}((-n)^x)\$ from \$x = -3\$ to \$x = 3\$ inclusive.
Where \$\mathrm{Re}(p)\$ is the real part of the complex number \$p\$.
Note that \$\mathrm{Re}((-n)^x) = n^x \cos{(\pi x)}\$
## Output
The output may be in any form you wish (e.g. an image or a window etc.). ASCII art is disallowed.
The graph does not need to have axes (to allow languages without built-in graphing functions to compete).
If an image is output, it each side must be longer than 500 pixels. Similarly, the plot must fill the image as best it can.
The minimum interval between plots is 0.05.
Vector graphics are allowed.
## Examples
For an input of `2`:
![](https://i.stack.imgur.com/Vpryc.gif)
For an input of `1`:
![](https://i.stack.imgur.com/qpTPE.gif)
---
***You must put your corresponding outputs in your answer (n = 1 and n = 2).***
## Winning
The shortest code in bytes wins.
[Answer]
# TI-Basic, ~~26~~ 21 bytes
```
~3→Xmin
3→Xmax
Prompt N
DrawF N^Xcos(πX
```
Output for N=2:
[![TI84SE GRAPH OUTPUT](https://i.stack.imgur.com/T8PXX.png)](https://i.stack.imgur.com/T8PXX.png)
[Answer]
# Bash + Gnuplot, ~~56~~ 45 bytes
*(-11 bytes thanks to Noiralef!)*
```
gnuplot -e "se t png;p[-3:3]real((-$1)**x)">A
```
Saves the resulting graph as a `png` image named `A` in the current working directory.
### Example Outputs
For **n = 1**:
![](https://i.stack.imgur.com/1bvil.png)
For **n = 2**:
![](https://i.stack.imgur.com/aA18z.png)
[Answer]
# [Python 3](https://docs.python.org/3/) with [matplotlib](https://matplotlib.org/), ~~103~~ 72 bytes
-12 bytes thanks to DSM (a module is installed alongside `matplotlib` called `pylab` with the necessary functionality "making Python in a repl more like Matlab" - odd, but true!)
-18 more as a result (pylab has many numpy functions too!)
-1 byte thanks to Ajasja (replacing `arange(-60,61)/20+0j` with `arange(121)/20-3+0j`)
```
from pylab import*
def f(n):x=arange(121)/20-3+0j;plot(x,(-n)**x);show()
```
**n=2,1**
![n=2](https://i.stack.imgur.com/dXoTS.png)
![n=1](https://i.stack.imgur.com/5IuLv.png)
[Answer]
# MATL, ~~22 18~~ 16 bytes
Thanks @LuisMendo for additional -2 bytes!
```
I_.01I3$:i_y^&XG
I_ push 3 and negate
.01 push 0.01
I push 3
3$: generate the list [-3,-2.99,-2.98,...,3]
i_y^ calculate (-input)^(list)
$XG plot the first list against the real part of the second list
```
[Try it on matl.io](https://matl.io/?code=I_.01I3%24%3Ai_y%5E%26XG&inputs=2&version=19.9.0)
[Answer]
## Mathematica, 41 bytes
```
Plot[Re[(-#)^x],{x,-3,3},PlotRange->All]&
```
Output looks exactly as shown in the challenge except for the font of the numbers (which I suspect was created with Wolfram Alpha).
[Answer]
## R, 29 bytes
```
curve(Re((0i-scan())^x),-3,3)
```
`n` is provided through stdin.
Result for n=1:
[![enter image description here](https://i.stack.imgur.com/EJyeC.png)](https://i.stack.imgur.com/EJyeC.png)
And for n=2:
[![enter image description here](https://i.stack.imgur.com/RFBiL.png)](https://i.stack.imgur.com/RFBiL.png)
[Answer]
# MATLAB, ~~35~~ 30 bytes
```
x=-3:.01:3;@(n)plot(x,(-n).^x)
```
This defines an anyonmous function. The output is via a new window with a resizable vector graphic output. MATLAB's `plot` automatically ignores the imaginary part of the y-coordinates as long as your provide corresponding x-coordinates.The following output is for `n=3`.
![](https://i.stack.imgur.com/ljZ5y.jpg)
[Answer]
# R, 30 bytes
```
plot(Re((0i-n)^seq(-3,3,.05)))
```
### `n` = 1
[![enter image description here](https://i.stack.imgur.com/XVqu3.png)](https://i.stack.imgur.com/XVqu3.png)
### `n` = 2
[![enter image description here](https://i.stack.imgur.com/w38G9.png)](https://i.stack.imgur.com/w38G9.png)
[Answer]
# Excel VBA, ~~168~~ ~~160~~ ~~147~~ 138 Bytes (cells as pixels at 100x scale)
Saved 8 bytes thanks to KyleKanos
Saved 22 bytes thanks to Taylor Scott
```
Sub g(n)
For i=0To 1
For x=-3To 3Step.01
y=n^x*Cos([Pi()]*x)
m=IIf(y<m,y,m)
If i Then Cells(500*(1-y/m)+1,(x+3)*100+1)="#
Next x,i
End Sub
```
Formatted, it looks like this:
```
Sub g(n)
For i = 0 To 1
For x = -3 To 3 Step 0.01
y = n ^ x * Cos([Pi()] * x)
m = IIf(y < m, y, m)
If i Then Cells(500 * (1 - y / m) + 1, (x + 3) * 100 + 1) = "#"
Next x, i
End Sub
```
Fun Fact: VBA does not have a built-in `pi` variable so we have to evaluate it as a worksheet function where it *does* exist.
**n=1** **n=2**
[![n=1](https://i.stack.imgur.com/8QcDD.png)](https://i.stack.imgur.com/8QcDD.png) [![n=2](https://i.stack.imgur.com/9iQak.png)](https://i.stack.imgur.com/9iQak.png)
---
I started with a chart version at 193 bytes but it *did* get prettier results.
```
Sub c(n)
For x=-3To 3Step 0.05
r=r+1
Cells(r,1)=n^x*Cos(Atn(1)*4*x)
Next
With ActiveSheet.Shapes.AddChart(xlLine).Chart
.SetSourceData Range("A1:A121")
.Axes(xlCategory).Delete
End With
End Sub
```
**n=1**
[![n=1](https://i.stack.imgur.com/AVSLR.png)](https://i.stack.imgur.com/AVSLR.png)
**n=2**
[![n=2](https://i.stack.imgur.com/GOxw3.png)](https://i.stack.imgur.com/GOxw3.png)
[Answer]
# MATLAB, ~~35~~ 33 bytes
*Thanks fo @flawr for removing 2 bytes!*
```
@(n)ezplot(@(x)real((-n)^x),-3:3)
```
This defines an anonymous function. To call it with input `2`, use `ans(2)` (or assign the function to a variable such as `f` and then use `f(2)`).
Output is vector graphics (resizable window). The sampling interval on the *x* axis is determined automatically by the `ezplot` function, but it seems to be more than enough.
A warning is produced in STDERR because the function passed to `ezplot` (`@(x)real((-n)^x)`) is not vectorized, but the graph is generated.
Example for `n = 2`:
[![enter image description here](https://i.stack.imgur.com/YoMZ1.png)](https://i.stack.imgur.com/YoMZ1.png)
[Answer]
# [Jupyter notebook](https://jupyter.org/) and Python 3; 53 bytes
```
%pylab
def f(n):x=arange(121)/20-3+0j;plot(x,(-n)**x)
```
Three bytes saved thanks to @Jonathan Allan.
[![n=1](https://i.stack.imgur.com/ixRfC.png)](https://i.stack.imgur.com/ixRfC.png)
[![n=2](https://i.stack.imgur.com/b0zV3.png)](https://i.stack.imgur.com/b0zV3.png)
[Answer]
# [Julia](http://julialang.org/) 0.6 with Plots.jl, 46 bytes
```
using Plots
~n=plot(real((0im-n).^(-3:.05:3)))
```
[![GR plot](https://i.stack.imgur.com/a2Mmk.png)](https://i.stack.imgur.com/a2Mmk.png)
This needed a Julia representation!
Not much to golf here though, except (ab)using operator overloading to save bytes on function defintion, and using `0im-n` to make the input number complex where I might usually have used `Complex(n)`. That's necessary because in Julia, for [type stability](https://en.wikibooks.org/wiki/Introducing_Julia/Types#Type_stability) reasons, the `^` operator returns Complex results only when the input is Complex itself. So here we make it a complex number by adding `0im` ie. 0i.
One cool thing about the Plots.jl package is that it automatically chooses the backend to use based on what plotting packages you have installed and where you're running the `plot` command from. The above plot was created with the [GR](https://github.com/jheinen/GR.jl) backend, but if I didn't have that installed (or if I explicitly ran a `plotly()` command like I did for this), it would have used the more interactive Plotly backend and output this (which looks a tiny bit nicer IMO):
[![Plotly plot](https://i.stack.imgur.com/SIlBy.png)](https://i.stack.imgur.com/SIlBy.png)
There's even a [UnicodePlots](https://github.com/Evizero/UnicodePlots.jl) backend, to print a plot in the terminal (or save to a text file) using Unicode characters and color codes. SE keeps messing up the plot alignment if I try to directly paste it though, so here's a terminal screenshot:
[![UnicodePlots plot](https://i.stack.imgur.com/b8FRJ.png)](https://i.stack.imgur.com/b8FRJ.png)
PS: The alternate formula, \$ Re((−n)^x)=n^xcos(πx) \$, comes out to the same length:
```
using Plots
~n=plot(n.^(x=-3:.05:3).*cospi(x))
```
[Answer]
# [J](http://jsoftware.com/), ~~37~~ 36 bytes
Thanks to my colleague Marshall for guidance. -2 thanks to FrownyFrog.
Anonymous tacit prefix function.
```
-(]plot@;9 o.^)i:@3j120[load@'plot'
```
[![Plot window](https://i.stack.imgur.com/ljYn1.png)](https://i.stack.imgur.com/ljYn1.png)
```
-(]plot@;9 o.^)i:@3j120[load@'plot'
load@'plot' NB. load plotting library
i:@3j120 NB. -3...3 in 120 steps
- NB. negate argument
( ^) NB. raise the negated value to those exponents
( 9 o. ) NB. real part
(] ; ) NB. pair with the exponents
( plot@ ) NB. plot it
```
[Answer]
# Desmos, ~~12~~ ~~10~~ 9 bytes
-2 thanks to @Steffan
-1 thanks to @LeoDog896
```
n^xcosxπ
```
How has nobody used Desmos yet?
[Answer]
# Encapsulated PostScript; 232 bytes
```
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 500 500
%%EndComments
/n 1 def .02 setlinewidth /f{dup dup n exch exp exch 180 mul cos mul 3 div}def
250 250 translate 80 80 scale newpath -3 f moveto -3 .05 3{f lineto}for stroke
%%EOF
```
Now since this is a vector image itself...
[![enter image description here](https://i.stack.imgur.com/us3SR.png)](https://i.stack.imgur.com/us3SR.png)
[![enter image description here](https://i.stack.imgur.com/fYp2i.png)](https://i.stack.imgur.com/fYp2i.png)
[Answer]
# [TikZ](https://www.ctan.org/pkg/pgf?lang=en) + [PGFPlots](https://www.ctan.org/pkg/pgfplots?lang=en), 175 bytes
```
\documentclass{standalone}\usepackage{tikz,pgfplots}\begin{document}\typein[\n]{}\tikz{\begin{axis}\addplot[domain=-3:3,samples=120]{\n^x*cos(180*x)};\end{axis}}\end{document}
```
Compile with, *e.g.*, `latexmk -cd -f -pdf in.tex` for a pdf output. During compilation, the user is prompted for `n`.
Sample outputs (converted to png) for n = 1 and n = 2:
![n = 1](https://i.stack.imgur.com/CnqRc.png)
![n = 2](https://i.stack.imgur.com/Rda8B.png)
[Answer]
# [Math.JS Grapher](http://a-ta.co/grapher), 20 Bytes
```
r(n)=f(x)=re((-n)^x)
```
By sheer fluke, this graphing utility is TC (For the most part, Infinite loops just crash it.), and by nature, it's primary output is graphs.
## How it works
`r(n)=` assigns a function `r` which takes the argument `n` to the expression `f(x)=re((-n)^x)`. `re((-n)^x)` is pretty much letter for letter the challenge description. But this assigns the function `f(x)` to this, which the grapher implicitly outputs as a line graph.
## How to test it
You can use [this](http://a-ta.co/grapher) site, punch that function in there, then call it with `r(input)`.
## Output
![Output](https://i.stack.imgur.com/gnKgV.png)
[Answer]
# Dyalog APL, 41 bytes
```
⎕SE.UCMD∊'chart x(9○(-'⍞')*x←3-20÷⍨⍳121)'
```
### How it works:
```
⎕SE.UCMD∊'chart x(9○(-'⍞')*x←3-20÷⍨⍳121)' ⍝ Main function
⎕SE.UCMD∊ ⍝ User Command (called from the session object)
'chart ⍝ Plot a chart with arguments:
( 3-20÷⍨⍳121)' ⍝ Yields the list [-3, -2.95, -2.9,..., 2.9, 2.95, 3]
x← ⍝ Assign that list to x
* ⍝ and use it as exponent
(-'⍞') ⍝ with (-input) as base
9○ ⍝ discard the complex part; this generates Re((-n)^x)
x ⍝ And x.
```
The user command `]chart`, in this case, takes two vector arguments, `x` and `y` and plots the graphs:
For \$n=1\$:
[![n=1](https://i.stack.imgur.com/ulaLx.png)](https://i.stack.imgur.com/ulaLx.png)
For \$n=2\$:
[![n=2](https://i.stack.imgur.com/ZpbW6.png)](https://i.stack.imgur.com/ZpbW6.png)
[Answer]
# Excel VBA, 133 bytes
Immediate window script that takes input from `[A1]` and outputs a `Chart` object to the `Sheet1` object.
```
[B:B]="=ROW()/20-3.05":[C:C]="=A$1^B1*Cos(Pi()*B1)":Set c=Sheet1.Shapes.AddChart(4).Chart:c.SetSourceData[C1:C121]:c.Axes(1).Delete
```
## Ungolfed
Full `Sub`routine version. I/O is unchanged.
```
Sub b()
[B:B] = "=ROW()/20-3.05" '' Define `x`-axis
[C:C] = "=A$1^B1*Cos(Pi()*B1)" '' Define `y`-axis in terms of input from A1
Set c = Sheet1.Shapes.AddChart(4).Chart '' Add line plot to Sheet1 (xlLine)
c.SetSourceData [C1:C121] '' Set `y` source to match `x` in [-3,3]
c.Axes(1).Delete '' Remove erroneous axes (xlCategory)
End Sub
```
## Output
Where input, \$n=1\$
[![Output plot n=1](https://i.stack.imgur.com/e5jva.png)](https://i.stack.imgur.com/e5jva.png)
Where input, \$n=3\$
[![Output plot n=3](https://i.stack.imgur.com/Babmi.png)](https://i.stack.imgur.com/Babmi.png)
[Answer]
# Google Sheets, 65
* Input N is in A1
Graphing:
* `=SPARKLINE(ArrayFormula(IMREAL(IMPOWER(-A1,.05*SEQUENCE(121,1,-60`
or
* `=SPARKLINE(ArrayFormula(IMREAL(IMPOWER(-A1,SEQUENCE(121,1,-60)/20`
Resize row and column of graph to 500x500.
I tried to use the COS() formula, but the best I can do is 66 characters with a named range. Problems that I came across:
* X is generated by the SEQUENCE(), which is then used twice. You would naturally think to cache this, but every time you cache into a column, to use it again, you have to either name a range, or use a FILTER. Named Range is obviously better, but it does cost 1 character to make it fair.
* Attempting to scalar multiply a SEQUENCE() forces us into an ArrayFormula (or MMULT() at best), and we cannot use a non-integer step for SEQUENCE(). This means that the most optimal way to use it is to give it to the SPARKLINE formula.
* This also means that our scalar multiply/divide has to occur each time we use the range.
[Answer]
# SmileBASIC, 82 bytes
```
INPUT N
FOR I=0TO 399X=I/66.5-3GPSET I,120-POW(N,X-3*SGN(N-1))*COS(PI()*X)*120NEXT
```
Graph fills the entire screen, even when N is less than 1.
When N is greater than 1, you can scale Y to be between -1 and 1 by dividing it by `n^3`. I'm already doing `n^x`, and `n^x / n^3` can be simplified to `n^(x-3)`. However, when N is less than 1, I have to divide Y by `n^-3` instead. This is equivalent to `n^(x+3)`.
I can use `n^(x-3*sign(n-1))` to use `-3` if `n>1`, and `+3` if `n<1`
Images coming soon
] |
[Question]
[
## Task description
In number theory, the [Carmichael function](https://en.wikipedia.org/wiki/Carmichael_function) ***λ*** takes a positive integer **n** and returns the least positive integer **k** so that the **k**-th power of each integer [coprime](https://en.wikipedia.org/wiki/Coprime_integers) to **n** equals 1 modulo **n**.
Given a positive integer **n**, your solution must compute ***λ*(n)**. The shortest code in bytes wins.
Your program should theoretically work for arbitrarily large inputs, but doesn’t need to be efficient.
## Tips
The sequence of all ***λ*(n)** is [OEIS A002322](https://oeis.org/A002322).
An ungolfed Python implementation would look like
```
from fractions import gcd
def carmichael(n):
coprimes = [x for x in range(1, n) if gcd(x, n) == 1]
k = 1
while not all(pow(x, k, n) == 1 for x in coprimes):
k += 1
return k
```
(In Python, `pow(A, B, C)` efficiently computes `pow(A, B) % C`.)
## Test cases
```
Input Output
1 1
2 1
3 2
10 4
35 12
101 100
530 52
3010 84
6511 3056
10000 500
```
[Answer]
## Mathematica, 16 bytes
```
CarmichaelLambda
```
Well...
[Answer]
# Python, ~~76~~ ~~73~~ 67 bytes
```
f=lambda n,k=1:1-any(a**-~k*~-a**k%n for a in range(n))or-~f(n,k+1)
```
[Try it online!](https://tio.run/nexus/python2#FY7BDoMgEETP5Sv2QgQLjdTSg4n9F1q1IepigB68@OuW3WQzuy@ZyZxTv7j1PThANfemM9rhLlxd62OuD12OmSNMIYIDjxAdfkeBUoaoj0kUz9XI069biBnSnljZWxpzHD@/mHzAxa8@C9OUkQwYBSEFCaPgrqBVYJoilrQg29LXEHtaY4iSs2OXLXrMouJ2AP0C/hgq4FAKwER15PkH)
A further byte could be saved by returning *True* instead of **1**.
### Alternative implementation
Using the same approach, there is also the following implementation by @feersum which doesn't use list comprehensions.
```
f=lambda n,k=1,a=1:a/n or(a**-~k*~-a**k%n<1)*f(n,k,a+1)or-~f(n,k+1)
```
Note that this implementation requires **O(nλ(n))** time. Efficiency could be improved dramatically while actually *decreasing* score to **66 bytes**, but the function would return *True* for input **2**.
```
f=lambda n,k=1,a=1:a/n or~-a**k*a**-~k%n<1==f(n,k,a+1)or-~f(n,k+1)
```
## Background
### Definitions and notation
All employed variables will denote integers; **n**, **k**, and **α** will denote *positive* integers; and **p** will denote a positive *prime*.
**a | b** if **b** is divisible by **a**, i.e., if there is **q** such that **b = qa**.
**a ≡ b (*mod* m)** if **a** and **b** have the same residue modulo **m**, i.e., if **m | a - b**.
**λ(n)** is the smallest **k** such that **ak ≡ 1 (*mod* n)** – i.e., such that **n | ak - 1** – for all **a** that are coprime to **n**.
**f(n)** is the smallest **k** such that **a2k+1 ≡ ak+1 (*mod* n)** – i.e., such that **n | ak+1(ak - 1)** – for all **a**.
### λ(n) ≤ f(n)
Fix **n** and let **a** be coprime to **n**.
By the definition of **f**, **n | af(n)+1(af(n) - 1)**. Since **a** and **n** do not have a common prime factor, neither do **af(n)+1** and **n**, which implies that **n | af(n) - 1**.
Since **λ(n)** is the smallest integer **k** such that **n | ak - 1** for all integers **a** that are coprime to **n**, it follows that **λ(n) ≤ f(n)**.
### λ(n) = f(n)
Since we've already established the inequality **λ(n) ≤ f(n)**, it is sufficient to verify that **k = λ(n)** satisfies the condition that defines **f**, i.e., that **n | aλ(n)+1(aλ(n) - 1)** for all **a**. For this purpose, we'll establish that **pα | aλ(n)+1(aλ(n) - 1)** whenever **pα | n**.
**λ(k) | λ(n)** whenever **k | n** ([source](https://en.wikipedia.org/wiki/Carmichael_function#Divisibility "Carmichael function - Wikipedia, the free encyclopedia")), so **(aλ(k) - 1)(aλ(n)-λ(k) + aλ(n)-2λ(k) + ⋯ + aλ(k) + 1) = aλ(n) - 1** and, therefore, **aλ(k) - 1 | aλ(n) - 1 | aλ(n)+1(aλ(n) - 1)**.
If **a** and **pα** are coprime, by the definition of **λ** and the above, **pα | aλ(pα) - 1 | aλ(n)+1(aλ(n) - 1)** follows, as desired.
If **a = 0**, then **aλ(n)+1(aλ(n) - 1) = 0**, which is divisible by all integers.
Finally, we must consider the case where **a** and **pα** have a common prime factor. Since **p** is prime, this implies that **p | a**. [Carmichael's theorem](https://en.wikipedia.org/wiki/Carmichael_function#Carmichael.27s_theorem "Carmichael function - Wikipedia, the free encyclopedia") establishes that **λ(pα) = (p - 1)pα - 1** if **p > 2** or **α < 3** and that **λ(pα) = pα - 2** otherwise. In all cases, **λ(pα) ≥ pα - 2 ≥ 2α - 2 > α - 2**.
Therefore, **λ(n) + 1 ≥ λ(pα) + 1 > α - 1**, so **λ(n) + 1 ≥ α** and **pα | pλ(n)+1 | aλ(n)+1 | aλ(n)+1(aλ(n) - 1)**. This completes the proof.
## How it works
While the definitions of **f(n)** and **λ(n)** consider all possible values of **a**, it is sufficient to test those that lie in **[0, ..., n - 1]**.
When **f(n, k)** is called, it computes **ak+1(ak - 1) % n** for all values of **a** in that range, which is **0** if and only if **n | ak+1(ak - 1)**.
If all computed residues are zero, **k = λ(n)** and `any` returns *False*, so **f(n, k)** returns **1**.
On the other hand, while **k < λ(n)**, `1-any(...)` will return **0**, so **f** is called recursively with an incremented value of **k**. The leading `-~` increments the return value of **f(n, k + 1)**, so we add **1** to **f(n, λ(n)) = 1** once for every integer in **[1, ..., λ(n) - 1]**. The final result is thus **λ(n)**.
[Answer]
# Mathematica without built-in, ~~58~~ 57 bytes
*Thanks to Martin Ender for finding an error, then saving me the bytes it took to fix it!*
*Thanks to miles for saving 1 byte! (which seemed like 2 to me)*
Built-ins are totally fine ... but for those who want to implement it without using brute force, here's a formula for the Carmichael function:
```
LCM@@(EulerPhi[#^#2]/If[#==2<#2,2,1]&@@@FactorInteger@#)&
```
If p is a prime, the Carmichael function λ(p^r) equals φ(p^r) = (p-1)\*p^(r-1)—*except* when p=2 and r≥3, in which case it's half that, namely 2^(r-2).
And if the prime-power factorization of n equals p1^r1 \* p2^r2 \* ..., then λ(n) equals the least common multiple of { λ(p1^r1), λ(p2^r2), ...}.
Runtime is one instant more than factoring the integer in the first place.
[Answer]
# [Templates Considered Harmful](https://github.com/feresum/tmp-lang), 246 bytes
```
Fun<Ap<Fun<If<Eq<A<2>,T>,A<1>,And<Eq<Ap<Fun<If<A<1>,Ap<A<0>,Rem<A<2>,A<1>>,A<1>>,A<2>>>,A<1,1>,A<2>>,T>,Sub<Ap<Fun<Rem<If<A<1>,Mul<A<2,1>,Ap<A<0>,Sub<A<1>,T>>>,T>,A<1,2>>>,A<1>>,T>>,Ap<A<0>,Add<A<1>,T>,A<1,1>>,Ap<A<0>,A<1>,Sub<A<2>,T>>>>,T,A<1>>>
```
An unnamed function (not that there are named functions).
This is a forgotten esolang of mine which is interpreted by a C++ compiler instantiating templates. With the default max template depth of `g++`, it can do λ(35), but it can't do λ(101) (the lazy evaluation makes things worse).
[Answer]
# Haskell, ~~57~~ 56 bytes
```
f n=[k|k<-[1..],and[mod(m^k)n<2|m<-[1..n],gcd m n<2]]!!0
```
[Answer]
# Jelly, 2 bytes
```
Æc
```
[Thank you for the builtin, @Lynn](https://github.com/DennisMitchell/jelly/commit/6136ca6a64b3247e2de53587cc4305d0255f7451)
[Answer]
# Pyth - ~~19~~ ~~18~~ 17 bytes
*One byte saved thanks to @TheBikingViking.*
Straight up brute force.
```
f!sm*t.^dTQq1iQdQ
```
[Try it online here](http://pyth.herokuapp.com/?code=f%21sm%2at.%5EdTQq1iQdQ&input=35&debug=0).
[Answer]
# Ruby, ~~59~~ 56 bytes
```
->x{a=1..x
a.detect{|k|a.all?{|y|x.gcd(y)>1||y**k%x<2}}}
```
[Answer]
# J, ~~28~~ 27 bytes
```
[:*./@(5&p:%2^0=8&|)2^/@p:]
```
The Carmichael function is λ(*n*) and the totient function is φ(*n*).
Uses the definition where λ(*p**k*) = φ(*p**k*)/2 if *p* = 2 and *k* > 2 else φ(*p**k*). Then, for general *n* = *p*1*k*1 *p*2*k*2 ⋯ *p**i**k**i*, λ(*n*) = LCM[ λ(*p*1*k*1) λ(*p*2*k*2) ⋯ λ(*p**i**k**i*) ].
## Usage
Extra commands used to format multiple input/output.
```
f =: [:*./@(5&p:%2^0=8&|)2^/@p:]
f 530
52
(,.f"0) 1 2 3 10 35 101 530 3010 6511 10000
1 1
2 1
3 2
10 4
35 12
101 100
530 52
3010 84
6511 3056
10000 500
```
## Explanation
```
[:*./@(5&p:%2^0=8&|)2^/@p:] Input: integer n
] Identity function, get n
2 p: Get a table of prime/exponent values for n
^/@ Raise each prime to its exponent to get the prime powers of n
[: ( ) Operate on the prime powers
8&| Take each modulo 8
0= Test if its equal to 0, 1 if true else 0
2^ Raise 2 to the power of each
5&p: Apply the totient function to each prime power
% Divide it by the powers of 2
*./@ Reduce using LCM and return
```
[Answer]
## JavaScript (ES6), ~~143~~ 135 bytes
*Edit: saved 8 bytes thanks to Neil*
An implementation using functional programming.
```
n=>(A=[...Array(n).keys()]).find(k=>k&&!c.some(c=>A.slice(0,k).reduce(y=>y*c%n,1)-1),c=A.filter(x=>(g=(x,y)=>x?g(y%x,x):y)(x,n)==1))||1
```
### Ungolfed and commented
```
n => // Given a positive integer n:
(A = [...Array(n).keys()]) // Build A = [0 ... n-1].
.find(k => // Try to find k in [1 ... n-1] such as
k && !c.some(c => // for each coprime c: c^k ≡ 1 (mod n).
A.slice(0, k).reduce(y => // We use reduce() to compute
y * c % n, 1 // c^k mod n.
) - 1 // Compare it with 1.
), // The list of coprimes is precomputed
c = A.filter(x => // before the find() loop is executed:
( // for each x in [0 ... n-1], keep
g = (x, y) => x ? g(y % x, x) : y // only integers that verify:
)(x, n) == 1 // gcd(x, n) = 1
) // (computed recursively)
) || 1 // Default result is 1 (for n = 1)
```
### Demo
Although it does work for `6511` and `10000`, I won't include them here as it tends to be a bit slow.
```
let f =
n=>(A=[...Array(n).keys()]).find(k=>k&&!c.some(c=>A.slice(0,k).reduce(y=>y*c%n,1)-1),c=A.filter(x=>(g=(x,y)=>x?g(y%x,x):y)(x,n)==1))||1
console.log(f(1)); // 1
console.log(f(2)); // 1
console.log(f(3)); // 2
console.log(f(10)); // 4
console.log(f(35)); // 12
console.log(f(101)); // 100
console.log(f(530)); // 52
console.log(f(3010)); // 84
```
[Answer]
# Actually, ~~30~~ ~~28~~ ~~25~~ ~~19~~ 26 bytes
The Carmichael function, `λ(n)` where `n = p_0**k_0 * p_1**k_1 * ... * p_a**k_a`, is defined as the least common multiple (LCM) of `λ(p_i**k_i)` for the maximal prime powers `p_i**k_i` that divide into `n`. Given that for every prime power except where the prime is `2`, the Carmichael function is equivalent to the Euler totient function, `λ(n) == φ(n)`, we use `φ(n)` instead. For the special case of `2**k` where `k ≥ 3`, we just check if `2**3 = 8` divides into `n` at the beginning of the program, and divide by 2 if it does.
Unfortunately, Actually doesn't currently have an LCM builtin, so I made a brute-force LCM. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=OzcmWXVAXHdgaeKBv-KWkmBN4pWXMmDilZxA4pmAJc6jWWDilZNO&input=NDAzMjA)
```
;7&Yu@\w`iⁿ▒`M╗2`╜@♀%ΣY`╓N
```
**Ungolfing**
```
Implicit input n.
; Duplicate n.
7& n&7 == n%8.
Yu Logical NOT and increment. If n%8 == 0, return 2. Else, return 1.
@\ Integer divide n by 2 if n%8==0, by 1 otherwise.
Thus, we have dealt with the special case where p_i == 2 and e_i >= 3.
w Full prime factorization of n as a list of [prime, exponent] lists.
`...`M Map the following function over the prime factorization.
i Flatten the array, pushing exponent, then prime to the stack.
ⁿ▒ totient(pow(prime, exponent)).
╗ Save that list of totients in register 0.
2`...`╓ Get the first two values of n where the following function f(n) is truthy.
Those two numbers will be 0 and our LCM.
╜@ Push the list in register 0 and swap with our n.
♀% Get n mod (every number in the list)
Σ Sum the modulos. This sum will be 0, if and only if this number is 0 or LCM.
Y Logical NOT, so that we only get a truthy if the sum of modulos is 0.
N Grab the second number, our LCM. Implicit return.
```
[Answer]
# Ruby, ~~101~~ ~~86~~ ~~91~~ 90 bytes
A Ruby port of [my Actually answer](https://codegolf.stackexchange.com/a/93779/47581). Golfing suggestions welcome.
**Edit:** -4 bytes from removing `a` but +9 bytes from fixing a bug where `1` returned `nil`. -1 byte thanks to Cyoce.
```
require'prime'
->n{((n%8<1?n/2:n).prime_division<<[2,1]).map{|x,y|x**~-y*~-x}.reduce :lcm}
```
**Ungolfing**
```
require 'prime'
def carmichael(n)
if n%8 < 1
n /= 2
end
a = []
n.prime_division.do each |x,y|
a << x**(y-1)*(x-1)
end
return a.reduce :lcm
end
```
[Answer]
# JavaScript (ES 2016) 149
Python reference implementation ported to JS. Some fancy Pyhton builtin is missing in js, like `gcd` and `pow`, and the array comprehension is not standard in ES 6. This works in Firefox.
```
n=>eval('for(g=(a,b)=>b?g(b,a%b):a,p=(a,b,c)=>eval("for(r=1;b--;)r=r*a%c"),c=[for(_ of Array(i=n))if(g(i--,n)<2)i+1],k=1;c.some(x=>p(x,k,n)-1);)++k')
```
*Less golfed*
```
n=>{
g=(a,b)=>b?g(b,a%b):a
p=(a,b,c)=>{
for(r=1;b--;)
r=r*a%c
return r
}
c=[for(_ of Array(i=n)) if(g(i--,n)<2) i+1]
for(k=1;c.some(x=>p(x,k,n)-1);)
++k
return k
}
```
[Answer]
# Java, ~~209~~ ~~207~~ ~~202~~ ~~194~~ 192 bytes
Code (96 bytes):
```
n->{for(int x,k=1,a;;k++){for(a=1,x=0;++x<=n&&a<2;)a=g(x,n)<2?p(x,k,n):1;if(a<2||n<2)return k;}}
```
extra functions (96 bytes):
```
int g(int a,int b){return b<1?a:g(b,a%b);}int p(int n,int p,int m){return p<2?n:n*p(n,p-1,m)%m;}
```
## Testing & ungolfed
```
import java.util.Arrays;
import java.util.function.IntUnaryOperator;
public class Main2 {
static int g(int a,int b) { // recursive gcd
return b < 1
? a
: g(b,a%b);
}
static int p(int n, int p, int m) { // recursive modpow
return p < 2
? n
: n * p(n, p - 1, m) % m;
}
public static void main(String[] args) {
IntUnaryOperator f = n -> {
for(int x,k=1,a;;k++) { // for each k
for(a=1,x=0;++x<=n&&a<2;) // for each x
a=g(x,n)<2?p(x,k,n):1; // compute modpow(x,k,n) if g(x,n)
if(a<2||n<2) // if all modpow(x,k,n)=1. Also check for weird result for n=1.
return k;
}
};
Arrays.stream(new int[]{1, 2, 3, 10, 35, 101, 530, 3010, 6511, 10000})
.map(f)
.forEach(System.out::println);
}
}
```
## Notes
* the use of `a` being an `int` is shorter than if I had to use a `boolean` to perform my tests.
* Yes, it's shorter to `valueOf` all new `BigInteger` than create a separate function (there are 5, plus the `ONE` constant is a freebie).
* Algorithm is different than @Master\_ex' algorithm, so it's not just a golfed repost. Also, this algorithm is much less efficient as `gcd` is computed again and again for the same values.
## Shaves
1. 209 -> 207 bytes:
* `if(...)a=...;` -> `a=...?...:1;`
* `a==1` -> `a<2`
2. 207 -> 202 bytes
* Got rid of `BigInteger` by golfing `gcd` and `modPow` for `int`.
3. 202 -> 194 bytes
* looping `modPow` -> recursive
4. 194 -> 192 bytes
* `==1` -> `<2` (seems to work for all the test cases, don't know for other numbers.)
[Answer]
# Java8 ~~38~~ 19 + ~~287~~ ~~295~~ ~~253~~ ~~248~~ 241 = ~~325~~ ~~333~~ ~~272~~ ~~267~~ 260 bytes
```
BigInteger B(int i){return new BigInteger(""+i);}int c(int...k){int n=k[0];for(k[0]=1;n>1&!java.util.stream.IntStream.range(0,n).filter(i->B(n).gcd(B(i)).equals(B(1))).allMatch(x->B(x).modPow(B(k[0]),B(n)).equals(B(1)));k[0]++);return k[0];}
```
**Imports, 19 bytes**
```
import java.math.*;
```
**Explanation**
It is a straight forward implementation. The co-primes are calculated in the `Set p` and every one's kth power is used to check if it equals 1 modulo n.
I had to use `BigInteger` because of precision issues.
**Usage**
```
public static void main(String[] args) {
Carmichael c = new Carmichael();
System.out.println(c.c(3)); // prints 2
}
```
**Ungolfed**
```
// returns the BigInteger representation of the given interger
BigInteger B(int i) {
return new BigInteger(""+i);
}
// for a given integer it returns the result of the carmichael function again as interger
// so the return value cannot be larger
int c(int... k) {
int n = k[0];
// iterate k[0] until for all co-primes this is true: (x^n) mod n == 1, if n==1 skip the loop
for (k[0]=1;n > 1 && !java.util.stream.IntStream.range(0, n)
.filter(i -> B(n).gcd(B(i)).equals(B(1)))
.allMatch(x -> B((int) x).modPow(B(k[0]), B(n)).equals(B(1)));k[0]++);
return k[0];
}
```
Any suggestions to golf it more are welcome :-)
**Update**
* No elements outside the functions that keep the state
* Followed Olivier Grégoire's advice and saved 1 byte from `B()`
* Removed the `k()` method and `p` (co-primes) Set.
* Removed not required casting to int.
* Added varags and use for instead of while.
[Answer]
# Java, ~~165 163 158 152~~ 143 bytes
```
int l(int n){int k=1,x,a,b,t,d=1;for(;d>0;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;b>0;b=a%b,a=t)t=b;for(t=b=1;b++<=k;t=t*x%n);}return k;}
```
Another port of my [C implementation](https://codegolf.stackexchange.com/a/94142/52904).
[Try it on Ideone](https://ideone.com/tWmaPZ)
[Answer]
# C++, ~~208 200 149 144 140~~ 134 bytes
```
[](int n){int k=1,x,a,b,t,d=1;for(;d;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;t=b;a=t)b=a%b;for(t=1,b=k;b--;t=t*x%n);}return k;};
```
A port of my [C implementation](https://codegolf.stackexchange.com/a/94142/52904).
[Try it on Ideone](https://ideone.com/W89903)
[Answer]
## Racket 218 bytes
```
(λ(n)(let((fl #f)(cl(for/list((i n) #:when(coprime? n i))i)))(for/sum((k(range 1 n))#:break fl)(set! fl #t)
(for((i(length cl))#:break(not fl))(when(not(= 1(modulo(expt(list-ref cl i)k)n)))(set! fl #f)))(if fl k 0))))
```
Ungolfed version:
```
(require math)
(define f
(λ(n)
(let ((fl #f)
(cl (for/list ((i n) #:when (coprime? n i))
i)))
(for/sum ((k (range 1 n)) #:break fl)
(set! fl #t)
(for ((i (length cl)) #:break (not fl))
(when (not (= 1 (modulo (expt (list-ref cl i) k) n)))
(set! fl #f)))
(if fl k 0)))))
```
Testing:
```
(f 2)
(f 3)
(f 10)
(f 35)
(f 101)
(f 530)
(f 3010)
(f 6511)
(f 10000)
```
Output:
```
1
2
4
12
100
52
84
3056
500
```
[Answer]
# C, ~~278 276 272 265 256 243 140 134~~ 125 bytes
```
k,x,a,b,t,d;l(n){for(k=d=1;d;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;t=b;a=t)b=a%b;for(t=1,b=k;b--;t=t*x%n);}return k;}
```
This uses a slow modular exponentiation algorithm, computes the GCD too often and no longer leaks memory!
Ungolfed:
```
int gcd( int a, int b ) {
int t;
while( b ) {
t = b;
b = a%b;
a = t;
}
return a;
}
int pw(int a,int b,int c){
int t=1;
for( int e=0; e<b; e++ ) {
t=(t*a)%c;
}
return t;
}
int carmichael(int n) {
int k = 1;
for( ;; ) {
int done = 1;
for( int x=1; x<n; x++ ) {
if( gcd(x,n)==1 && pw(x,k,n) != 1 ) {
done = 0;
k++;
}
}
if( done ) break;
}
return k;
}
```
[Try it on Ideone](https://ideone.com/lm9KsO)
[Answer]
**Axiom 129 bytes**
```
c(n)==(r:=[x for x in 1..n|gcd(x,n)=1];(v,k):=(1,1);repeat(for a in r repeat(v:=powmod(a,k,n);v~=1=>break);v<=1=>break;k:=k+1);k)
```
less golfed
```
cml(n)==
r:=[x for x in 1..n|gcd(x,n)=1];(v,k):=(1,1)
repeat
for a in r repeat(v:=powmod(a,k,n);v~=1=>break)
v<=1=>break
k:=k+1
k
```
results
```
(3) -> [i,c(i)] for i in [1,2,3,10,35,101,530,3010,6511,10000]
Compiling function c with type PositiveInteger -> PositiveInteger
(3)
[[1,1], [2,1], [3,2], [10,4], [35,12], [101,100], [530,52], [3010,84],
[6511,3056], [10000,500]]
Type: Tuple List PositiveInteger
```
] |
[Question]
[
**Monday numbers**, as defined by [Gamow](https://puzzling.stackexchange.com/users/8874/gamow) in [this question](https://puzzling.stackexchange.com/questions/22666/the-largest-monday-number) over on Puzzling, are positive integers *N* with the following three properties:
* The decimal representation of *N* does not contain the digit 0
* The decimal representation of *N* does not contain any digit twice
* *N* is divisible by every digit *D* that occurs in its decimal representation
Note that these are alternatively known, in the OEIS, as [Lynch-Bell numbers](https://oeis.org/A115569).
### Examples:
* `15` is a Monday number, as it's divisible by both `1` and `5` and satisfies the other two conditions
* `16` is not, because it's not divisible by `6`.
* The number `22` is not, because though it satisfies conditions 1 and 3, it fails condition 2.
Here's the list of the first 25 Monday numbers to get you started (there are 548 total):
>
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> 12
> 15
> 24
> 36
> 48
> 124
> 126
> 128
> 132
> 135
> 162
> 168
> 175
> 184
> 216
> 248
>
>
>
The challenge here is to **write the shortest code that generates the full sequence of Monday numbers,** from 1 up to 9867312 (proven on that question to be the largest possible).
Your code should take no input, and output should be to STDOUT or equivalent, with your choice of delimiter. All the usual code-golf rules apply, and [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/) are prohibited.
## Leaderboard
```
var QUESTION_ID=59014,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]
## Python 2, 85 bytes
```
print[n for n in range(1,9**9)if(n<10**len(set(`n`)))>any(n%(int(d)or.3)for d in`n`)]
```
Prints a list.
I'm basically combining two of my answers to previous challenges:
* [Checking if a number is divisible by each of its digits](https://codegolf.stackexchange.com/a/41915/20260)
```
lambda n:any(n%(int(d)or.3)for d in`n`)<1
```
(thanks to FryAmTheEggman for reminding me about this).
* [Determine if all decimal digits are unique](https://codegolf.stackexchange.com/a/28365/20260)
```
lambda n:10**len(set(`n`))>n
```
Thanks to xsot for 1 byte saved by combining the conditions better.
[Answer]
# Perl, ~~61~~ 47 bytes
46 bytes code + 1 byte command line parameter.
```
/(.).*\1|0/||1*s/./$_%$&/rge||print for 1..1e7
```
### Usage:
```
perl -l entry.pl
```
### Explanation
`/(.).*\1|0/` returns 1 if the number-under-test contains a duplicate character or a 0
`s/./$_%$&/rge` replaces each digit with the value of the number-under-test % the digit. For example, 15 -> 00, 16 -> 04 (because 16%6=4). This means that any input which is divisible by all of its digits will consist of all 0s, otherwise it will contain a digit >0. In order to treat this as a number, we \*1, which means any number-under-test will return 0 for this block if it is divisible by all of its digits, otherwise >0.
By separating these two statements and the print with 'or's, if either of the first two conditions returns >0, the condition matches and the subsequent parts of the expression will not evaluate. If and only if both previous conditions are 0, the print will then execute. The `-l` flag ensures to add a new line after each print.
[Answer]
# Pyth, ~~22~~ 21
```
f&.{`T!f%T|vY.3`TS^T7
```
Thanks to Jakube for golfing off 1 byte of unnecessary formatting.
Heavily inspired by [this CW answer](https://codegolf.stackexchange.com/a/41945/31625) to the related question.
I have a paste of the result [here](http://pastebin.com/vLFvwi10), from when it printed newline separated, now it prints as a pythonic list.
I would recommend not [trying it online](http://pyth.herokuapp.com/?code=jf%26.%7B%60T%21f%25T%7CvY.3%60TS%5ET2&debug=0) unless you use a number smaller than 7... I've set it to 2 in this link.
Filters from `1` to `10^7-1` which covers all the necessary values. This version may cause a memory error if it cannot make the list `S^T7`, which is similar to `list(range(1,10**7))` in python 3 (However, it works fine for me). If so, you could try:
```
.f&.{`Z.x!s%LZjZT0548
```
Which finds the first 548 Monday numbers. This also demonstrates another way to check for the `0`s in the number, instead of replacing them with `.3` this uses a try-catch block. Credit for this version goes entirely to Jakube. (Note that this is still much to slow for the online interpreter)
[Answer]
## [GS2](http://www.github.com/nooodl/gs2), 20 19 bytes
gs2 uses a wide range of bytes, not just printable ascii chracters. I will present my solution in hex.
```
17 7d 2f 24 65 f1 c8 24 d8 62 e9 65 f4 24 40 90 71 f3 54
```
Here's some explanation. gs2 is a stack based language, so there are no variables. (aside from 4 registers, one of which i use here)
```
17 # push constant 7
7d # 10 raised to the power
2f # create an array of numbers from 1 to n
24 # get digits of number into array
65 # calculate product of array
f1 # filter array by previous block of 2 instructions
c8 # save top of stack to register a
24 # get digits of number into array
d8 # tuck register a under top of stack
62 # boolean divisibility test
e9 # map array using previous block of 2 instructions
65 # calculate product of array
f4 # filter array by previous block of 5 instructions
24 # get digits of number into array
40 # duplicate top of stack
90 # remove duplicates from array
71 # test equality
f3 # filter array by previous block of 4 instructions
54 # show contents of array separated by line breaks
```
[Answer]
# Python 3, ~~132~~ ~~128~~ ~~114~~ ~~111~~ 104 bytes
```
i=0
while i<1e8:
j=str(i)
if len(set(j))+2==len(j)+('0'in j)+all(i%int(k)<1 for k in j):print(i)
i+=1
```
There are 548 Monday Numbers.
[Answer]
# APL, ~~44~~ ~~39~~ 37 bytes
```
{0=+/(⊢|∘⍵,0∘∊,⍴∘⊢≠⍴∘∪)⍎¨⍕⍵:⍵⋄⍬}¨⍳1e7
```
Ungolfed:
```
{
x ← ⍎¨⍕⍵⋄ ⍝ Define x to be a vector of the digits of ⍵
0=+/(⊢|∘⍵,0∘∊,⍴∘⊢≠⍴∘∪)x: ⍝ No zeros, all digits divide ⍵, all unique?
⍵⋄⍬ ⍝ If so, return the input, otherwise null
}¨⍳1e7 ⍝ Apply to the integers 1..1E7
```
Saved 7 bytes thanks to Moris Zucca!
[Answer]
# TI-BASIC, ~~60~~ 59 bytes
```
For(X,1,ᴇ7
int(10fPart(X10^(-randIntNoRep(1,1+int(log(X->D
SortA(∟D
If X>9
If not(max(remainder(X,Ans+2Xnot(Ansmin(ΔList(∟D
Disp X
End
```
`∟D` is the list of digits, which is generated using math and the `randIntNoRep(` command (random permutation of all integers between `1` and `1+int(log(X` inclusive). I use a slightly complicated chain of statements to check if all of the conditions are satisfied:
```
min(ΔList(∟D ;Zero if repeated digit, since ∟D was sorted ascending
Ans ;Multiplies the unsorted copy of ∟D by the minimum from above
;(Lists are different dimensions; we can't elementwise AND)
;Will contain a 0 if there's a 0 digit or a repeated digit
not( ;If there's a zero,
Ans+2X ;Add 2X to that pos. in the list, failing the test:
max(remainder(X, ;Zero iff all digits divide X and 2X wasn't added
not(
```
To fail numbers that have repeated digits or zero digits, I replace zeroes with `2X`, because `X` is never divisible by `2X`.
To special-case 1~9 (because `ΔList(` on a one-element list errors) I use the `If` statement in the fourth line to skip over the check in the fifth line, automatically displaying all `X`≤9.
The output numbers are separated by newlines.
[Answer]
# Mathematica 105
```
l=Length;Cases[Range@9867312,n_ /;(FreeQ[i=IntegerDigits@n,0]&&l@i== l@Union@i&&And@@(Divisible[n,#]&/@i))]
```
* `IntegerDigits` breaks up `n` into a list of its digits, `i`.
* `FreeQ[i,0]` checks whether there are no zeros in the list.
* `Length[i]==Length[Union[i]]` checks that there are no repeated digits.
* `And@@(Divisible[n,#]&/@i)` checks that each digit is a divisor of `n`.
>
> {1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 24, 36, 48, 124, 126, 128, 132, 135, 162, 168, 175, 184, 216, 248, 264, 312, 315, 324, 384, 396, 412, 432, 612, 624, 648, 672, 728, 735, 784, 816, 824, 864, 936, 1236, 1248, 1296, 1326, 1362, 1368, 1395, 1632, 1692, 1764, 1824, 1926, 1935, 1962, 2136, 2184, 2196, 2316, 2364, 2436, 2916, 3126, 3162, 3168, 3195, 3216, 3264, 3276, 3492, 3612, 3624, 3648, 3816, 3864, 3915, 3924, 4128, 4172, 4236, 4368, 4392, 4632, 4872, 4896, 4932, 4968, 6132, 6192, 6312, 6324, 6384, 6432, 6912, 6984, 8136, 8496, 8736, 9126, 9135, 9162, 9216, 9315, 9324, 9432, 9612, 9648, 9864, 12384, 12648, 12768, 12864, 13248, 13824, 13896, 13968, 14328, 14728, 14832, 16248, 16824, 17248, 18264, 18432, 18624, 18936, 19368, 21384, 21648, 21784, 21864, 23184, 24168, 24816, 26184, 27384, 28416, 29736, 31248, 31824, 31896, 31968, 32184, 34128, 36792, 37128, 37296, 37926, 38472, 39168, 39816, 41328, 41832, 42168, 42816, 43128, 43176, 46128, 46872, 48216, 48312, 61248, 61824, 62184, 64128, 68712, 72184, 73164, 73248, 73416, 73962, 78624, 79128, 79632, 81264, 81432, 81624, 81936, 82416, 84216, 84312, 84672, 87192, 89136, 89712, 91368, 91476, 91728, 92736, 93168, 93816, 98136, 123648, 123864, 123984, 124368, 126384, 129384, 132648, 132864, 132984, 134928, 136248, 136824, 138264, 138624, 139248, 139824, 142368, 143928, 146328, 146832, 148392, 148632, 149328, 149832, 162384, 163248, 163824, 164328, 164832, 167328, 167832, 168432, 172368, 183264, 183624, 184392, 184632, 186432, 189432, 192384, 193248, 193824, 194328, 194832, 198432, 213648, 213864, 213984, 214368, 216384, 218736, 219384, 231648, 231864, 231984, 234168, 234816, 236184, 238416, 239184, 241368, 243168, 243768, 243816, 247968, 248136, 248976, 261384, 263184, 273168, 281736, 283416, 284136, 291384, 293184, 297864, 312648, 312864, 312984, 314928, 316248, 316824, 318264, 318624, 319248, 319824, 321648, 321864, 321984, 324168, 324816, 326184, 328416, 329184, 341928, 342168, 342816, 346128, 348192, 348216, 348912, 349128, 361248, 361824, 361872, 362184, 364128, 364728, 367248, 376824, 381264, 381624, 382416, 384192, 384216, 384912, 391248, 391824, 392184, 394128, 412368, 413928, 416328, 416832, 418392, 418632, 419328, 419832, 421368, 423168, 423816, 427896, 428136, 428736, 431928, 432168, 432768, 432816, 436128, 438192, 438216, 438912, 439128, 461328, 461832, 463128, 468312, 469728, 478296, 478632, 481392, 481632, 482136, 483192, 483216, 483672, 483912, 486312, 489312, 491328, 491832, 493128, 498312, 612384, 613248, 613824, 613872, 614328, 614832, 618432, 621384, 623184, 623784, 627984, 631248, 631824, 632184, 634128, 634872, 641328, 641832, 643128, 648312, 671328, 671832, 681432, 684312, 689472, 732648, 732816, 742896, 746928, 762384, 768432, 783216, 789264, 796824, 813264, 813624, 814392, 814632, 816432, 819432, 823416, 824136, 824376, 831264, 831624, 832416, 834192, 834216, 834912, 836472, 841392, 841632, 842136, 843192, 843216, 843912, 846312, 849312, 861432, 864312, 873264, 891432, 894312, 897624, 912384, 913248, 913824, 914328, 914832, 918432, 921384, 923184, 927864, 931248, 931824, 932184, 934128, 941328, 941832, 943128, 948312, 976248, 978264, 981432, 984312, 1289736, 1293768, 1369872, 1372896, 1376928, 1382976, 1679328, 1679832, 1687392, 1738296, 1823976, 1863792, 1876392, 1923768, 1936872, 1982736, 2137968, 2138976, 2189376, 2317896, 2789136, 2793168, 2819376, 2831976, 2931768, 2937816, 2978136, 2983176, 3186792, 3187296, 3196872, 3271968, 3297168, 3298176, 3619728, 3678192, 3712968, 3768912, 3796128, 3816792, 3817296, 3867192, 3869712, 3927168, 3928176, 6139728, 6379128, 6387192, 6389712, 6391728, 6719328, 6719832, 6731928, 6893712, 6913872, 6971328, 6971832, 7168392, 7198632, 7231896, 7291368, 7329168, 7361928, 7392168, 7398216, 7613928, 7639128, 7829136, 7836192, 7839216, 7861392, 7863912, 7891632, 7892136, 7916328, 7916832, 7921368, 8123976, 8163792, 8176392, 8219736, 8312976, 8367912, 8617392, 8731296, 8796312, 8912736, 8973216, 9163728, 9176328, 9176832, 9182376, 9231768, 9237816, 9278136, 9283176, 9617328, 9617832, 9678312, 9718632, 9723168, 9781632, 9782136, 9812376, 9867312}
>
>
>
```
Length[%]
```
>
> 548
>
>
>
[Answer]
# Haskell, 77 bytes
```
[x|x<-[1..9^9],all(\a->a>'0'&&mod x(read[a])+sum[1|y<-show x,y==a]<2)$show x]
```
Usage example (the first 20 numbers):
```
take 20 $ [x|x<-[1..9^9],all(\a->a>'0'&&mod x(read[a])+sum[1|y<-show x,y==a]<2)$show x]
[1,2,3,4,5,6,7,8,9,12,15,24,36,48,124,126,128,132,135,162]
```
How it works: iterate over all numbers from 1 to 9^9 and check the conditions. The current number `x` is turned into it's string representation (`show x`) to operate on it as a list of characters.
[Answer]
# R, 99 bytes
```
for(n in 1:1e8){i=1:nchar(n);if(all(table(d<-(n%%10^i)%/%10^(i-1))<2)&!0%in%d&all(!n%%d))cat(n,"")}
```
Slightly less golfed:
```
for(n in 1:1e8){
i = 1:nchar(n)
d = (n%%10^i)%/%10^(i-1) # Digits of n
if(all(table(d)<2) # No digits is present more than once
& !0%in%d # 0 is not one of the digits
& all(!n%%d)) # All digits are divisors of n
cat(n,"")
}
```
[Answer]
## Perl, 90 75 70 bytes
```
print+($_,$/)x(grep(!/(\d).*\1|0/,$_)&s/./!$&||$_%$&/ger<1)for 1..1e7
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ ~~22~~ ~~21~~ ~~18~~ ~~14~~ ~~13~~ ~~12~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
-9 byte thanks to the help and encouragement of *@Emigna* and *@Mr.Xcoder*. Thanks for letting me mostly figure it out myself, even though you already had a 12-byte solution in mind when I was still at 30. Learned a lot about 05AB1E from this challenge!
-3 bytes thanks to *@Grimy*
```
7°LʒÐÑÃÙQ
```
[Try it online](https://tio.run/##ARkA5v9vc2FiaWX//zPCsEzKksOQw5HDg8OZUf//) (only outputs the numbers below 103 instead of 107 to prevent a timeout after 60 sec).
**Explanation:**
```
7°L # Generate a list in the range [1, 10^7]
ʒ # Filter, so only the numbers that evaluated to 1 (truthy) remain:
Ð # Triplicate the current number
Ñ # Get the divisors of this number
# i.e. 128 → [1,2,4,8,16,32,64,128]
# i.e. 1210 → [1,2,5,10,11,22,55,110,121,242,605,1210]
à # Only keep those digits/numbers in the original number (which is checked in
# order, so it will only keep the digits and ignores the later numbers)
# i.e. 128 → 128
# i.e. 1210 → 121
Ù # Uniquify the number, removing any duplicated digits
# i.e. 128 → 128
# i.e. 121 → 12
Q # Check if the number is unchanged after this
# i.e. 128 and 128 → 1 (truthy)
# i.e. 1210 and 12 → 0 (falsey)
```
---
**Previous 12 byter version (one of my very first 05AB1E answers):**
NOTE: Only works in the legacy version of 05AB1E.
```
7°LʒÐSÖPsDÙQ*
```
[Try it online](https://tio.run/##MzBNTDJM/f/f@NAGn1OTDk84PDNQyyX48LSA//8B) (only outputs the numbers below 103 instead of 107 to prevent a timeout after 60 sec).
**Explanation:**
```
7°L # Generate a list in the range [1, 10^7]
ʒ # Filter, so only the numbers that evaluated to 1 (true) remain:
Ð # Triplicate the current number N
Ù # Remove all duplicated digits of the second N
# i.e. 1210 → 120
Q # Check if the last two numbers are still the same (1 or 0 as result)
* # Multiply this result with remaining third number from the triplication
D # Duplicate this number, so we have two again
S # Separate all the digits of the second one
# i.e. 128 → ['1', '2', '8']
Ö # Check if (the second) N is divisible by each of its digits
# i.e. 128 and ['1', '2', '8'] → [1, 1, 1]
# (NOTE: If the number contains a '0', it won't error on division by 0,
# but instead return the number N itself in the list)
# i.e. 105 and ['1', '0', '5'] → [1, 105, 1]
P # Take the product of this list (if the divisible test for one
# of the digits was 0, this will be 0 as well)
# i.e. [1, 1, 1] → 1
# i.e. [1, 105, 1] → 105 (only 1 is truthy in 05AB1E)
```
[Answer]
# CJam, 25 bytes
```
1e7{_Ab__&0-_@=@@f%1b>},`
```
[Try it online](http://cjam.aditsu.net/#code=1e4%7B_Ab__%260-_%40%3D%40%40f%251b%3E%7D%2C%60). Note that online link only runs to 10,000. I'm not sure if it would finish online if you're patient enough. It haven't tested it with the offline version of CJam, but I expect that it would terminate.
Explanation:
```
1e7 Upper limit.
{ Start filter loop.
_Ab Copy and convert to list of decimal digits.
__& Intersect list with itself to remove duplicates.
0- Remove zero.
_ Make a copy of unique non-zero digits. Will use these as divisors.
@= Compare unique non-zero digits to all digits. Must be true for Monday numbers.
@@ Rotate original number and list of non-zero digits to top.
f% Remainders of original number with all non-zero digits.
1b Sum up the remainders. Since they all must be zero for Monday numbers,
their sum must be zero.
> Check that first part of condition was 1, and sum of remainders 0.
}, End filter loop.
` Convert resulting list to string.
```
[Answer]
## C#, ~~230~~ 227
It's been a while since I've golved so I probably forgot a few tricks to get the bytecount down. Will improve when I think of them... For now:
```
using System.Linq;class P{static void Main(){System.Console.Write(string.Join(",",Enumerable.Range(0,1<<24).Where(i=>{var s=i.ToString();return!s.Contains('0')&&s.Length==s.Distinct().Count()&&s.All(x=>i%(48-(int)x)==0);})));}}
```
Ungolfed:
```
using System.Linq;
class P
{
static void Main()
{
System.Console.Write( //Output...
string.Join( //...all results...
",", //...comma separated...
Enumerable.Range(0, 1<<24) //...from 0 to 16777216...
.Where(i => { //...where...
var s = i.ToString(); //...the digits as char array (what we usually call a string)...
return !s.Contains('0') //...for which none of the digits is 0...
&& s.Length == s.Distinct().Count() //...and the number of distinct digits equals the total number of digits (e.g. all unique)...
&& s.All(x => i % (48 - (int)x) == 0); //...and the number is divisible by each of the digits (after 'ASCII-correction')
})
)
);
}
}
```
>
> 1,2,3,4,5,6,7,8,9,12,15,24,36,48,124,126,128,132,135,162,168,175,184,216,248,264,312,315,324,384,396,412,432,612,624,648,672,728,735,784,816,824,864,936,1236,1248,1296,1326,1362,1368,1395,1632,1692,1764,1824,1926,1935,1962,2136,2184,2196,2316,2364,2436,2916,3126,3162,3168,3195,3216,3264,3276,3492,3612,3624,3648,3816,3864,3915,3924,4128,4172,4236,4368,4392,4632,4872,4896,4932,4968,6132,6192,6312,6324,6384,6432,6912,6984,8136,8496,8736,9126,9135,9162,9216,9315,9324,9432,9612,9648,9864,12384,12648,12768,12864,13248,13824,13896,13968,14328,14728,14832,16248,16824,17248,18264,18432,18624,18936,19368,21384,21648,21784,21864,23184,24168,24816,26184,27384,28416,29736,31248,31824,31896,31968,32184,34128,36792,37128,37296,37926,38472,39168,39816,41328,41832,42168,42816,43128,43176,46128,46872,48216,48312,61248,61824,62184,64128,68712,72184,73164,73248,73416,73962,78624,79128,79632,81264,81432,81624,81936,82416,84216,84312,84672,87192,89136,89712,91368,91476,91728,92736,93168,93816,98136,123648,123864,123984,124368,126384,129384,132648,132864,132984,134928,136248,136824,138264,138624,139248,139824,142368,143928,146328,146832,148392,148632,149328,149832,162384,163248,163824,164328,164832,167328,167832,168432,172368,183264,183624,184392,184632,186432,189432,192384,193248,193824,194328,194832,198432,213648,213864,213984,214368,216384,218736,219384,231648,231864,231984,234168,234816,236184,238416,239184,241368,243168,243768,243816,247968,248136,248976,261384,263184,273168,281736,283416,284136,291384,293184,297864,312648,312864,312984,314928,316248,316824,318264,318624,319248,319824,321648,321864,321984,324168,324816,326184,328416,329184,341928,342168,342816,346128,348192,348216,348912,349128,361248,361824,361872,362184,364128,364728,367248,376824,381264,381624,382416,384192,384216,384912,391248,391824,392184,394128,412368,413928,416328,416832,418392,418632,419328,419832,421368,423168,423816,427896,428136,428736,431928,432168,432768,432816,436128,438192,438216,438912,439128,461328,461832,463128,468312,469728,478296,478632,481392,481632,482136,483192,483216,483672,483912,486312,489312,491328,491832,493128,498312,612384,613248,613824,613872,614328,614832,618432,621384,623184,623784,627984,631248,631824,632184,634128,634872,641328,641832,643128,648312,671328,671832,681432,684312,689472,732648,732816,742896,746928,762384,768432,783216,789264,796824,813264,813624,814392,814632,816432,819432,823416,824136,824376,831264,831624,832416,834192,834216,834912,836472,841392,841632,842136,843192,843216,843912,846312,849312,861432,864312,873264,891432,894312,897624,912384,913248,913824,914328,914832,918432,921384,923184,927864,931248,931824,932184,934128,941328,941832,943128,948312,976248,978264,981432,984312,1289736,1293768,1369872,1372896,1376928,1382976,1679328,1679832,1687392,1738296,1823976,1863792,1876392,1923768,1936872,1982736,2137968,2138976,2189376,2317896,2789136,2793168,2819376,2831976,2931768,2937816,2978136,2983176,3186792,3187296,3196872,3271968,3297168,3298176,3619728,3678192,3712968,3768912,3796128,3816792,3817296,3867192,3869712,3927168,3928176,6139728,6379128,6387192,6389712,6391728,6719328,6719832,6731928,6893712,6913872,6971328,6971832,7168392,7198632,7231896,7291368,7329168,7361928,7392168,7398216,7613928,7639128,7829136,7836192,7839216,7861392,7863912,7891632,7892136,7916328,7916832,7921368,8123976,8163792,8176392,8219736,8312976,8367912,8617392,8731296,8796312,8912736,8973216,9163728,9176328,9176832,9182376,9231768,9237816,9278136,9283176,9617328,9617832,9678312,9718632,9723168,9781632,9782136,9812376,9867312
>
>
>
[Answer]
# TI-BASIC, ~~55~~ 53 bytes
This is a relatively minor edit of [Thomas Kwa's answer](https://codegolf.stackexchange.com/a/59043/2867), but I am submitting it as a new answer because I'd heard that he has put [a bounty](http://chat.stackexchange.com/transcript/240?m=24578779#24578779) on golfing his TI-BASIC answers.
```
For(X,1,ᴇ7
int(10fPart(X10^(-randIntNoRep(0,1+int(log(X->D
SortA(∟D
If not(sum(remainder(X,Ans+Xnot(Ansmin(ΔList(∟D
Disp X
End
```
My main change is from `randIntNoRep(1,` to `randIntNoRep(0,` meaning that there will now a zero in every generated list of digits.
```
number | randIntNoRep | digits | sorted
9 | 1,0 | 9,0 | 0,9
102 | 3,1,0,2 | 1,2,0,0 | 0,0,1,2
```
Since there's now a zero in every set of digits, this affects the sum of the remainders. Normally the sum of the remainders is 0, but now, the presence of an extra zero causes one failure of our divisibility test.
To counteract this, I changed `2Xnot(` to `Xnot(`. The 2 was originally there to make the test fail at 0, but now it passes at zero. Numbers that contain a zero in their digits, however, now have a `min(ΔList(∟D` of zero anyways (since there's 2 or more zeros in their lists) so this change does not cause any extra numbers to pass the test.
The benefit of this method is that, since there are now "two digits" produced from the number 1-9, the `ΔList(` function does not produce an error, allowing us to get rid of a special condition for single-digit numbers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ȷ7Dg⁼QƲƇ
```
Runs locally in under eight minutes.
[Try it online!](https://tio.run/##y0rNyan8///EdjOX9EeNewKPbTrW/v8/AA "Jelly – Try It Online") (modified to find numbers with six digits or less)
### How it works
```
ȷ7Dg⁼QƲƇ Main link. No arguments.
ȷ7 Set the return value to 10**7.
Ƈ Comb; promote 10**7 to [1, ..., 10**7], then keep only those n in the range
for which the link to the left returns a truthy value.
Ʋ Combine the four links to the left into a monadic chain.
D Decimal; yield n's digit array in base 10.
g Take the GCD of each digit and n.
Q Yield the unique digits of n.
⁼ Test both results for equality.
```
[Answer]
# Julia, 88 bytes
```
print(join(filter(i->(d=digits(i);0∉d&&d==unique(d)&&all(j->i%j<1,d)),1:9867312)," "))
```
This simply takes all numbers from 1 up to the largest Lynch-Bell number and filters them down to only the Lynch-Bell numbers.
Ungolfed:
```
lynch = filter(i -> (d = digits(i);
0 ∉ d &&
d == unique(d) &&
all(j -> i % j == 0, d)),
1:9867312)
print(join(lynch, " "))
```
[Answer]
# Python 2, 101 bytes
```
print[i for i in range(6**9)if'0'not in`i`and len(set(`i`))==len(`i`)and all(i%int(k)==0for k in`i`)]
```
You can omit the `print` in the interpreter get to 96.
Used `6**9` since it is 8 digits while the largest monday number is only 7 digits, something like `9**9` would probably take a long time, 6\*\*9 only takes about 10 seconds.
[Answer]
# Perl, 97 bytes
```
print+($n=$_,$/)x(!/0/&(y///c==grep{2>eval"$n=~y/$_//"}/./g)&&y///c==grep!($n%$_),/./g)for 1..1e7
```
Takes a while to run, but produces the required output, change to `1e3` for a quicker example!
[Answer]
# MATLAB, 100
```
o=49;for n=2:1e7 a=num2str(n);if all([diff(sort(a)) a~=48 ~mod(n,a-48)]) o=[o ',' a];end;end;disp(o)
```
And in a more readable format:
```
o=49; %1 is always in there, so add the ASCII value. This prevents there being a ',' prefixed.
for n=2:1e7
a=num2str(n);
if (all([diff(sort(a)) a~=48 ~mod(n,a-48)]))
o=[o ',' a];
end
end
disp(o)
```
Basically this counts through every number between \$1\$ and \$1\times10^7\$ and checks if they are a Monday number. Each number is converted to a string so that the digits can be dealt with individually.
The checks are as follows:
1. First check if there are any duplicates. By sorting the array, if the difference between any consecutive digits is zero, then there are duplicates
```
diff(sort(a))
```
2. Check if there are any zeros. The ASCII for 0 is 48, so we check that all digits are not equal to that.
```
a~=48
```
3. Check if it is divisible by all its digits. We check that the remainder when dividing by each digit (converted from ASCII to decimal, hence -48) is zero.
```
~mod(n,a-48)
```
Finally we make sure that `all()` the checks are true, and if so we append it to a comma separated output string.
MATLAB has no STDOUT, so instead I print the result string at the end using `disp()`
---
This code is SLOW! I am still running it to make sure that it correctly finds all the Monday numbers, but looks good so far.
Update:
Code finished running. It prints the following:
```
1,2,3,4,5,6,7,8,9,12,15,24,36,48,124,126,128,132,135,162,168,175,184,216,248,264,312,315,324,384,396,412,432,612,624,648,672,728,735,784,816,824,864,936,1236,1248,1296,1326,1362,1368,1395,1632,1692,1764,1824,1926,1935,1962,2136,2184,2196,2316,2364,2436,2916,3126,3162,3168,3195,3216,3264,3276,3492,3612,3624,3648,3816,3864,3915,3924,4128,4172,4236,4368,4392,4632,4872,4896,4932,4968,6132,6192,6312,6324,6384,6432,6912,6984,8136,8496,8736,9126,9135,9162,9216,9315,9324,9432,9612,9648,9864,12384,12648,12768,12864,13248,13824,13896,13968,14328,14728,14832,16248,16824,17248,18264,18432,18624,18936,19368,21384,21648,21784,21864,23184,24168,24816,26184,27384,28416,29736,31248,31824,31896,31968,32184,34128,36792,37128,37296,37926,38472,39168,39816,41328,41832,42168,42816,43128,43176,46128,46872,48216,48312,61248,61824,62184,64128,68712,72184,73164,73248,73416,73962,78624,79128,79632,81264,81432,81624,81936,82416,84216,84312,84672,87192,89136,89712,91368,91476,91728,92736,93168,93816,98136,123648,123864,123984,124368,126384,129384,132648,132864,132984,134928,136248,136824,138264,138624,139248,139824,142368,143928,146328,146832,148392,148632,149328,149832,162384,163248,163824,164328,164832,167328,167832,168432,172368,183264,183624,184392,184632,186432,189432,192384,193248,193824,194328,194832,198432,213648,213864,213984,214368,216384,218736,219384,231648,231864,231984,234168,234816,236184,238416,239184,241368,243168,243768,243816,247968,248136,248976,261384,263184,273168,281736,283416,284136,291384,293184,297864,312648,312864,312984,314928,316248,316824,318264,318624,319248,319824,321648,321864,321984,324168,324816,326184,328416,329184,341928,342168,342816,346128,348192,348216,348912,349128,361248,361824,361872,362184,364128,364728,367248,376824,381264,381624,382416,384192,384216,384912,391248,391824,392184,394128,412368,413928,416328,416832,418392,418632,419328,419832,421368,423168,423816,427896,428136,428736,431928,432168,432768,432816,436128,438192,438216,438912,439128,461328,461832,463128,468312,469728,478296,478632,481392,481632,482136,483192,483216,483672,483912,486312,489312,491328,491832,493128,498312,612384,613248,613824,613872,614328,614832,618432,621384,623184,623784,627984,631248,631824,632184,634128,634872,641328,641832,643128,648312,671328,671832,681432,684312,689472,732648,732816,742896,746928,762384,768432,783216,789264,796824,813264,813624,814392,814632,816432,819432,823416,824136,824376,831264,831624,832416,834192,834216,834912,836472,841392,841632,842136,843192,843216,843912,846312,849312,861432,864312,873264,891432,894312,897624,912384,913248,913824,914328,914832,918432,921384,923184,927864,931248,931824,932184,934128,941328,941832,943128,948312,976248,978264,981432,984312,1289736,1293768,1369872,1372896,1376928,1382976,1679328,1679832,1687392,1738296,1823976,1863792,1876392,1923768,1936872,1982736,2137968,2138976,2189376,2317896,2789136,2793168,2819376,2831976,2931768,2937816,2978136,2983176,3186792,3187296,3196872,3271968,3297168,3298176,3619728,3678192,3712968,3768912,3796128,3816792,3817296,3867192,3869712,3927168,3928176,6139728,6379128,6387192,6389712,6391728,6719328,6719832,6731928,6893712,6913872,6971328,6971832,7168392,7198632,7231896,7291368,7329168,7361928,7392168,7398216,7613928,7639128,7829136,7836192,7839216,7861392,7863912,7891632,7892136,7916328,7916832,7921368,8123976,8163792,8176392,8219736,8312976,8367912,8617392,8731296,8796312,8912736,8973216,9163728,9176328,9176832,9182376,9231768,9237816,9278136,9283176,9617328,9617832,9678312,9718632,9723168,9781632,9782136,9812376,9867312
```
Which if you run this code with that as the input:
```
nums = length(strsplit(stdout,','))
```
Yeilds 548.
[Answer]
# Ruby, 79
```
?1.upto(?9*7){|s|a=s.chars;a.uniq!||a.any?{|x|x<?1||0<eval([s,x]*?%)}||puts(s)}
```
More interesting but slightly longer solution with a regex:
```
?1.upto(?9*7){|s|s[/(.).*\1|[0#{(1..9).map{|*x|x*eval([s,x]*?%)}*''}]/]||puts(s)}
```
In each case, we're using Ruby's ability to iterate over strings as though they were decimal integers: `?1.upto(?9*7)` is equivalent to `1.upto(9999999).map(&:to_s).each`. We join the string to each nonzero digit using the modulo operator, and eval the result, to check for divisibility.
Bonus Ruby 1.8 solution (requires `-l` flag for proper output):
```
'1'.upto('9'*7){|$_|~/(.).*\1|[0#{(1..9).map{|*x|x*eval("#$_%#{x}")}}]/||print}
```
1.8 allowed the block iterator to be a global variable. Assigning to `$_` makes it the implicit receiver for string operations. We also get to interpolate arrays into the regular expression more easily: in 1.8, `/[#{[1,2]}]/` evaluates to `/[12]/`.
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 25 bytes
```
Fa,t**7Ia#=UQa&0=$+a%^aPa
```
Outputs each number on its own line. This has been running for about 10 minutes and gotten up to 984312 so far, but I'm pretty sure it's correct. *(Edit: Couple hours later... code finished, generated all 548 of 'em.)*
Here's a Python-esque pseudocode rendition:
```
for a in range(10**7):
if lengthEqual(a, set(a)) and 0 == sum(a%d for d in digits(a)):
print(a)
```
The `#=` operator compares two iterables by length. If the number of `U`ni`Q`ue characters in `a` is the same as the number of characters in `a`, there are no repeats.
The divisible-by-each-digit check is from one of my Pip example programs. I wrote it after seeing the [earlier challenge](https://codegolf.stackexchange.com/questions/41902/is-a-number-divisible-by-each-of-its-digits), but didn't post it there because the language was newer than the question. Otherwise, at 8 bytes, it would be the winning answer to that question. Here's a step-by-step explanation:
```
^a Split num into an array of its digits
a% Take num mod each of those digits; if a digit is zero, the result will be nil
$+ Sum the resulting list (note: summing a list containing nil results in nil!)
0= Iff the sum equals 0, return 1 (true); otherwise (>0 or nil), return 0 (false)
```
[Answer]
# Javascript (ES6), ~~106~~ ~~90~~ 83 bytes
Kids, don't try this at home; JS will not be happy with the prospect of looping through every digit of every integer from one to ten million with a regex.
```
for(i=0;i<1e7;i++)/(.).*\1|0/.test(i)||+`${i}`.replace(/./g,j=>i%j)||console.log(i)
```
The first regex (props to @Jarmex) returns `true` if the number contains duplicate digits or zeroes. If this turns out `false`, the program move on to the second, which replaces each digit `j` with `i%j`. The result is all zeroes if it's divisible by all of it's digits, in which case it moves on to `console.log(i)`.
Suggestions welcome!
[Answer]
# JavaScript (ES6), 76
```
/* Answer below. For testing purpose, redirect consoloe.log */ console.log=x=>document.write(x+' ')
for(i=0;i++<1e7;)/0|(.).*\1/.test(i)||[...i+''].some(d=>i%d)||console.log(i)
```
The regexp test for 0 or repeated digits. Then the digits array is checked looking for a non-zero modulo for any digit.
[here](https://puzzling.stackexchange.com/a/22667) is the explanation of the 7 digit max.
[Answer]
# Ruby, 130 bytes
... not counting whitespace
New to programming,just wanted to participate
```
c=0
(0..10**7).each do |x|
a=x.to_s.split('')
c+=1 if !a.include?('0')&& a.uniq!.eql?(nil)&&a.all?{|y| x.modulo(y.to_i).zero?}
end
p c
```
[Answer]
# C, 122 bytes
```
i,j,m,a;void f(){for(i=1;i<1e8;++i){for(m=0,j=i;j;j/=10){a=j%10;if(!a||m&(1<<a)||i%a)goto n;m|=1<<a;}printf("%d ",i);n:;}}
```
Prettier:
```
i,j,m,a;
void f()
{
for (i=1; i<1e8; ++i){
for (m=0, j=i; j; j/=10) {
a = j%10;
if (!a || m&(1<<a) || i%a)
goto n;
m|=1<<a;
}
printf("%d ",i);
n:;
}
}
```
For each candidate `i`, we iterate its digits `a` in little-endian order, keeping track of seen digits in the bits of `m`. If the loop completes, then all digits are factors of `i` and we saw no zeros or repeated digits, so print it, otherwise we exit early to continue the outer loop.
[Answer]
# CJam, 34 bytes
```
1e7{_:TAb___&=\{T\T)e|%}%:+!**},N*
```
[Answer]
# Lua, 129 bytes
I've eschewed the string approach for pure digit-crunching, which seems a bit speedier and probably saved me some bytes as well. (I'll have test that theory, but Lua string handling is pretty verbose compared to some other languages.)
```
for i=1,1e7 do t={[0]=1}j=i while j>0 do c=j%10 if t[c]or i%c>0 then break end t[c]=1 j=(j-c)/10 if j==0 then print(i)end end end
```
[Answer]
# gawk, 99 bytes
```
BEGIN{for(;8>(l=split(++i,a,_));printf f?f=_:i RS)for(j in a)f=i~0||i%(d=a[j])||i-d*10^(l-j)~d?1:f}
```
I could reduce that to 97 if I would use `END` instead of `BEGIN`, but then you would have to press Ctrl-D to start the actual output, signalling that there will be no input.
I could reduce it to even 94 if I would write nothing instead of `BEGIN` or `END`, but then you would have to press the return key once to start it, which could be counted as input.
It simply goes over the digits of each number and tests if the criteria are met.
```
i~0 : number contains a `0`? -> trash
i%(d=a[j]) : number not divisible by current digit? -> trash
i-d*10^(l-j)~d : I removed the current digit from the number yet it
: still contains it? -> trash
```
Takes 140 seconds to terminate on my Core 2 Duo.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
9œ!ṖẎgḌ$ƑƇḌ
```
This uses the two-week old `œ!` atom. Actually fast enough to run on TIO.
[Try it online!](https://tio.run/##y0rNyan8/9/y6GTFhzunPdzVl/5wR4/KsYnH2oH0//8A "Jelly – Try It Online")
### How it works
```
9œ!ṖẎgḌ$ƑƇḌ Main link. No arguments.
9 Set the return value to 9.
R Pop; yield [1, ..., 8].
œ! Promote 9 to [1, ..., 9] and generate all permutations of length k,
each k in the right argument [1, ..., 8].
Ẏ Tighten; dump all digit lists in a single array.
Ƈ Comb; keep only digit lists for which the link to the left returns 1.
Ƒ Fixed; return 1 iff calling the link to the left returns its argument.
$ Combine the two links to the left into a monadic chain.
Ḍ Undecimal; convert the digit list into an integer.
g Take the GCD of each digit and the integer.
```
] |
[Question]
[
A lexicographically increasing number is an integer whose digits are in strictly increasing order. Print all lexicographically increasing numbers under 10000.
Here are lines of the expected output:
```
0
1
2
3
4
5
6
7
8
9
12
13
14
15
16
17
18
19
23
24
25
26
27
28
29
34
35
36
37
38
39
45
46
47
48
49
56
57
58
59
67
68
69
78
79
89
123
124
125
126
127
128
129
134
135
136
137
138
139
145
146
147
148
149
156
157
158
159
167
168
169
178
179
189
234
235
236
237
238
239
245
246
247
248
249
256
257
258
259
267
268
269
278
279
289
345
346
347
348
349
356
357
358
359
367
368
369
378
379
389
456
457
458
459
467
468
469
478
479
489
567
568
569
578
579
589
678
679
689
789
1234
1235
1236
1237
1238
1239
1245
1246
1247
1248
1249
1256
1257
1258
1259
1267
1268
1269
1278
1279
1289
1345
1346
1347
1348
1349
1356
1357
1358
1359
1367
1368
1369
1378
1379
1389
1456
1457
1458
1459
1467
1468
1469
1478
1479
1489
1567
1568
1569
1578
1579
1589
1678
1679
1689
1789
2345
2346
2347
2348
2349
2356
2357
2358
2359
2367
2368
2369
2378
2379
2389
2456
2457
2458
2459
2467
2468
2469
2478
2479
2489
2567
2568
2569
2578
2579
2589
2678
2679
2689
2789
3456
3457
3458
3459
3467
3468
3469
3478
3479
3489
3567
3568
3569
3578
3579
3589
3678
3679
3689
3789
4567
4568
4569
4578
4579
4589
4678
4679
4689
4789
5678
5679
5689
5789
6789
```
This is a code golf challenge! Shortest answer wins!
(P.S. looking for a python solution)
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
for n in range(9999):
if eval('<'.join(`n`))**n:print n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFPITNPoSgxLz1VwxIINK24FDLTFFLLEnM01G3U9bLyM/M0EvISNDW1tPKsCooy80oU8v7/BwA "Python 2 – Try It Online")
Converts each number like `124` to an expression `1<2<4` and evaluates it to check if the digits are sorted,
A hiccup happens for one-digit numbers giving an expression that just is the number itself. This causes `0` to evaluate to a Falsey value even though it should be printed. This is fixed by a trick suggested by Erik the Outgolfer of doing `**n`, which gives truthy value `0**0` for `n=0` and doesn't affect the truth value otherwise.
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
i=0
exec"print i\ni+=1\nif eval('<'.join(`i`)):1;"*7000
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWgCu1IjVZqaAoM69EITMmL1Pb1hBIpimkliXmaKjbqOtl5WfmaSRkJmhqWhlaK2mZGxgY/P8PAA "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
unlines[s|s<-show<$>[0..6^5],s==scanl1(max.succ)s]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzvzQvJzMvtTi6uKbYRrc4I7/cRsUu2kBPzyzONFan2Na2ODkxL8dQIzexQq@4NDlZszj2f25iZp6CrUJBaUlwSZFC2v9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
Outputs a multiline string. We check that the number `s` increasing using `s==scanl1(max.succ)s`, a variant of the usual sortedness check `s==scanl1 max s` that ensures strict sortedness by incrementing each digit character before taking the maximum of it and the next digit.
Ourous saved a byte by using `6^5` as the upper bound in place of a 4-digit number.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
9ŒPḌḣ⁹Y
```
[Try it online!](https://tio.run/##y0rNyan8/9/y6KSAhzt6Hu5Y/KhxZ@T//wA "Jelly – Try It Online")
### How it works
```
9ŒPḌḣ⁹Y Main link. No arguments.
9 Set the return value to 9.
ŒP Powerset; promote 9 to [1, ..., 9] and generate all subsets.
Ḍ Undecimal; map the subsets of digits to the integers they represent.
⁹ Yield 256.
ḣ Dyadic head; take the first 256 elements of the integer list.
Y Separate the result by linefeeds.
```
[Answer]
# Japt `-R`, ~~12~~ ~~11~~ 8 bytes
```
L²Ç¶ìüÃð
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=TLLHtuz8w/A=&input=LVI=)
```
L :100
² :Squared
Ç :Map the range [0,L²)
ì : Split to a digit array
ü : For the sake of simplicity*, let's say: Sort & deduplicate
: Implicitly rejoin to an integer
¶ : Test for equality with original number
à :End map
ð :Get 0-based indices of truthy elements
:Implicitly join with newlines and output
```
\*Or, to offer a better explanation: the `ü` method sorts an array and splits it into equal elements (e.g., `[8,4,8,4].ü() -> [[4,4],[8,8]]`) and then, in what seems to be a strange quirk and hopefully not a bug, the `ì` method, when converting the array back to a number, takes the first element of each nested array, rather than first flattening the array, which is what I expected when I tried this trick (e.g., `[[4,4],[8,8]].ì() -> 48`).
[Answer]
# [R](https://www.r-project.org/), ~~62~~ 49 bytes
```
`[`=write;0[1];for(i in 1:4)combn(1:9,i)[1,i,,""]
```
[Try it online!](https://tio.run/##K/r/PyE6wba8KLMk1dog2jDWOi2/SCNTITNPwdDKRDM5PzcpT8PQylInUzPaUCdTR0dJKfb/fwA "R – Try It Online")
Because `combn` iterates through its input in the order given, it's easy to create all the lexicographically increasing integers, printing them out in order. `write` prints them each `i`-digit number in lines of width `i`, neatly fulfilling the newline requirement as well.
[Answer]
# [Perl 6](http://perl6.org/), 25 bytes
```
[<](.comb)&&.say for ^1e4
```
*-1 byte thanks to nwellnhof*
[Try it online!](https://tio.run/##K0gtyjH7/z/aJlZDLzk/N0lTTU2vOLFSIS2/SCHOMNXk/38A "Perl 6 – Try It Online")
`.comb` produces a list of the digits of each number, and `[<]` does a less-than reduction on that list, equivalent to: *digit1* < *digit2* < ... < *digitN*.
[Answer]
## Haskell, ~~56~~ 55 bytes
Edit: -1 byte thanks to @Ourous
```
mapM print$filter(and.(zipWith(<)<*>tail).show)[0..6^5]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexwFehoCgzr0QlLTOnJLVIIzEvRU@jKrMgPLMkQ8NG00bLriQxM0dTrzgjv1wz2kBPzyzONBaoLzNPwVYh7f@/5LScxPTi/7rJBQUA "Haskell – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~42~~ 40 bytes
```
0..1e4|?{-join("$_"|% t*y|sort -u)-eq$_}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPzzDVpMa@WjcrPzNPQ0klXqlGVaFEq7KmOL@oREG3VFM3tVAlvvb/fwA "PowerShell – Try It Online")
Loop from `0` to `1e4` (i.e., `10000`). Pull out those objects where `|?{...}` the number as a string `$_` is `-eq`ual to the number cast `t`oCharArra`y` and then `sort`ed with the `-u`nique flag. In other words, only numbers that are the same as their sorted and deduplicated strings. Each of those are left on the pipeline and output is implicit.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
jiRThc2yS9
```
[Try it online!](https://tio.run/##K6gsyfj/PyszKCQj2agy2PL/fwA "Pyth – Try It Online")
### How it works
```
jiRThc2yS9
S9 Yield [1, 2, 3, 4, 5, 6, 7, 8, 9].
y Take all 512 subsets.
c2 Split the array of subsets into 2 pieces (256 subsets each).
h Head; take the first piece.
iRT Convert each subset from base 10 to integer.
j Separate by newlines.
```
[Answer]
# J, 26 bytes
```
,.(#~(-:/:~@~.)@":"0)i.1e4
```
[Try it online!](https://tio.run/##y/qfpmBrpWCgAMK6egrOQT5u/3X0NJTrNHSt9K3qHOr0NB2UrJQMNDP1DFNN/mtypSZn5Cso6Smk/QcA "J – Try It Online")
## explanation
```
,. (#~ (-: /:~@~.)@":"0) i.1e4
i.1e4 NB. list 0 to 9999
"0 NB. for each number in the input list
@":"0 NB. convert it to a string and
(#~ ( ) NB. remove any not passing this test:
-: NB. the string of digits matches
@~. NB. the nub of the digits (dups removed)
/:~ NB. sorted
,. NB. ravel items: take the result of all that
NB. and turn it into a big column
```
[Answer]
# [Common Lisp](http://www.lispworks.com/documentation/HyperSpec/Front/index.htm), ~~74~~ 72 bytes
```
(dotimes(i 7e3)(format(apply'char<(coerce(format()"~d"i)'list))"~d~%"i))
```
[Try it online!](https://tio.run/##S87JLC74/18jJb8kMze1WCNTwTzVWFMjLb8oN7FEI7GgIKdSPTkjschGIzk/tSg5FSajqVSXopSpqQ7UXqIJ4tSpArma//8DAA)
-2 bytes thank to @Shaggy!
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 8 bytes
```
4°ÝD€êû
```
[Try it online!](https://tio.run/##ARkA5v8wNWFiMWX//zTCsMOdROKCrMOqw4PCu/// "05AB1E (legacy) – Try It Online")
Works in the new version of 05AB1E as well but is painfully slow for some reason.
### How?
```
4°ÝD€êû – Full program.
4°Ý – Push [0 ... 10000].
D€ê – Push each integer in [0 ... 10000] sorted and deduplicated at the same time.
û – And join the interection of the two lists by newlines.
```
[Answer]
# [Perl 5](https://www.perl.org/), 47 bytes
```
map{$_&&s/.(?=(.))/$1-$&/gre=~/0|-/||say}0..1E4
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaJV5NrVhfT8PeVkNPU1NfxVBXRU0/vSjVtk7foEZXv6amOLGy1kBPz9DV5P//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
Older:
[52 bytes](https://tio.run/##K0gtyjH9/z83saBaIys/M09dXac4v6ikWiVRVyWpVl9PP11TVyW@pkZfQ08zxlC/pqY4sbLWQE/P0NXk//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online")
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, ~~36~~ 34 bytes
```
0|(([2-9])$4{$1/$2}|$3![1-9]()){4}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWN5UMajQ0oo10LWM1VUyqVQz1VYxqa1SMFaMNgUIamprVJrUQlVANC6A0AA)
This was directly inspired by the [language's creator's answer](https://codegolf.stackexchange.com/a/249434/17216), but I figured this big optimization building on that idea was worth its own post.
```
0 # Zero must be matched as a special case, because no other
# numbers have a leading '0' digit.
|
(
([2-9]) # \2 = a digit intended to be greater than the previous
# one ($1), but until being validated below, it can
# be any digit in [2-9].
# We could actually do ([0-9]) here and it'd generate the
# same output, but would run slightly less efficiently.
$4{$1/$2} # Repeat a nonexistent group $1/$2 number of times. $1 and $2
# are the literal contents of those captures interpreted as
# numeric values upon which arithmetic can be done in a
# quantifier, which we do here. $1/$2 will evaluate to
# zero iff $2 is greater than $1, which is the only thing
# that will allow it to match, because if it repeats more
# than zero times, it tries to match the nonexistent group
# $4 which can't match.
|
$3 # If the above fails to match, due to $1 containing the
# digit '9', the regex engine will try other matches, even
# if they use short-circuiting alternation. So we put a
# dummy match here, which can only match on iterations
# other than the first one. Once this matches, it will be
# the only thing that can match in all subsequent
# iterations, because the attempted math "$2-$1-1" will
# fail still - now due to $1 no longer being a number (it
# will be blank).
# Short-circuiting alternation - never try the following unless the all of
# the above failed to match.
!
[1-9] # Match the first digit. This can only happen on the first
# iteration, thanks to the short-circuiting alternation.
() # $3 = empty capture - lets subsequent iterations know that
# they are no longer the first iteration
) # $1 = whatever digit was matched above, for use by the next
# iteration
{4} # Repeat the above loop for exactly 4 iterations. This
# allows a variable number of digits, due to the "$3" dummy
# alternative.
```
Alternative 34 bytes:
```
0|(([2-9])$3{$1/$2}|{#1}![1-9]){4}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWN5UMajQ0oo10LWM1VYyrVQz1VYxqa6qVDWsVow1BgtUmtRCVUA0LoDQA)
It might not be intended that this is possible, but Regenerate allows a quantifier to be preceded by nothing. This is what's happening with `{#1}` - it's impossible for it to match on the first iteration because `$1` hasn't been captured yet and doesn't have a length. On subsequent iterations, a match of nothing gets repeated one time (the length of `$1`).
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
```
for i in range(9999):
if list(`i`)==sorted(set(`i`)):print i
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPoSgxLz1VwxIINK24FDLTFHIyi0s0EjITNG1ti/OLSlJTNIpTIQKaVgVFmXklCpn//wMA "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~64~~ 61 bytes
```
lambda:[x for x in range(9999)if sorted(set(`x`))==list(`x`)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNykl0Sq6QiEtv0ihQiEzT6EoMS89VcMSCDQz0xSK84tKUlM0ilNLNBIqEjQ1bW1zMosh7Nj/cD1pGppWXJwFRZl5JQoV/wE "Python 2 – Try It Online")
Gets the unique characters of the integer's string representation, sorts them, and compares the result to the original number.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 41 bytes
```
7000ïÎaÛ
Îy$úúP
Ç^¨ä*©±$/d
ÎãlD
爱/d
HO0
```
[Try it online!](https://tio.run/##K/v/39zAwODw@sN9iYdncx3uq1Q5vOvwrgCuw@1xh1YcXqJ1aOWhjSr6KUCZw4tzXLgOLz/UcWgjkO/hb/D/PwA "V – Try It Online")
Hexdump:
```
00000000: 3730 3030 efce 61db 0ace 7924 fafa 500a 7000..a...y$..P.
00000010: c75e a8e4 2aa9 b124 2f64 0ace e36c 440a .^..*..$/d...lD.
00000020: e788 b12f 640a 484f 30 .../d.HO0
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
ΦEXχ⁴Iι¬Φι∧쬋§ι⊖μλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUjDN7FAIyC/HMgyNNBRMNHUUXBOLC7RyNQEsvzy4coydRQc81I0ciGCPqnFxRqOJZ55KakVICmX1OSi1NzUvJJUoBKQzhxNCLD@//@/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
χ Predefined variable 10
X To the power
⁴ Literal 4
E Map over implicit range
ι Current value
I Cast to string
Φ Filter over strings where
ι Current string
Φ Filtered over characters
μ Character index (is nonzero)
∧ And
μ Character index
⊖ Decremented
§ Indexed into
ι Current string
¬ Is not
‹ Less than
λ Current character
¬ Results in an empty string
Implicitly print matches on separate lines
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~9~~ 8 bytes
*Saved 5 bytes thanks to @Dennis*
```
9œcⱮ4ẎŻY
```
[Try it online!](https://tio.run/##y0rNyan8/9/y6OTkRxvXmTzc1Xd0d@T//wA "Jelly – Try It Online")
### Explanation
Generates all lexicographically increasing numbers below 10000 by taking the digits [1...9] and finding all combinations of length ≤ 4.
```
9œcⱮ4ẎŻY Main link. Arguments: none
9 Yield 9.
Ɱ4 For each n in [1...4]:
œc Yield the combinations of the range [1...9] of length n.
Ẏ Tighten; dump each of the 4 lists generated into the main list.
Ż Prepend a 0 to the list.
Y Join on newlines.
```
---
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~10~~ 9 bytes
*Saved a byte thanks to @EriktheOutgolfer*
```
ȷ4Ḷ<ƝẠ$ƇY
```
[Try it online!](https://tio.run/##ARkA5v9qZWxsef//yLc04bi2PMad4bqgJMaHWf// "Jelly – Try It Online")
### Explanation
Filters through the range, keeping the numbers that are lexicographically increasing.
```
ȷ4Ḷ<ƝẠ$ƇY Main link. Arguments: none
ȷ4 Yield 10^4 (10000).
Ḷ Generate the range [0...10000).
Ƈ Filter; yield only the numbers where this link return a truthy value.
$ Run these two links and yield the result.
Ɲ For each pair of items (digits) in the number:
< Check whether the left digit is less than the right digit.
Ạ All; check that every comparison yielded true.
This yields whether the digits are strictly increasing.
Y Join the filtered list on newlines.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
After I wrote this, it was clarified that each number must be on a new line, so +7 bytes for the `Print/@`.
This method takes advantage of the fact that the `Subsets` function 1) doesn't replicate any digits and 2) sorts the output by set size and set contents. `FromDigits` assembles each list of digits.
-1 byte thanks to @Mr.Xcoder
```
Print/@FromDigits/@Range@9~Subsets~4
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvRN/BrSg/1yUzPbOkWN8hKDEvPdXBsi64NKk4taS4zuT/fwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k) / [K (oK)](https://github.com/JohnEarnest/ok), ~~32~~ ~~30~~ 26 bytes
**Solution:**
```
`0:$&&/'1_'>':'" ",'$!9999
```
[Try it online!](https://tio.run/##y9bNz/7/P8HASkVNTV/dMF7dTt1KXUlBSUddRdESCP7/BwA "K (oK) – Try It Online")
**Explanation:**
```
`0:$&&/'1_'>':'" ",'$!9999 / the solution
!9999 / range 0..9998 (could use !6890)
$ / string
" ",' / prepend " " to each (lower than "0" in ascii)
>:' / greater-than each-previous?
1_' / drop first result from each
&/' / max (&) over (/)
& / indices where true
$ / convert to string
`0: / print to stdout
```
[Answer]
# JavaScript REPL, 64 bytes
A bit of pub golf so probably far from optimal.
```
(f=n=>n&&f(n-1)+([...n+``].every(x=>y<(y=x),y=0)?`
`+n:``))(7e3)
```
[Try it online](https://tio.run/##BcFRCoMwDADQ/x1EEroGZR8DWfQgIkRcOhwlHTqkPX1977ucy7Hu2@/vLb21rsmOFJVi@kCFwMaDNU0A8x06mIjInMhMeupeIPNQXlA4471wi6PcxFkvgghPfWDFegE)
Yes, doing it without an IIFE would be a few bytes shorter but that throws an overflow error when called, which would normally be fine as we can assume infinite memory for the purposes of code golf but, to me, doesn't seem to be in the spirit of KC challenges.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~97~~ ~~89~~ 81 bytes
Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for -8 bytes.
Another -8 thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)
```
g(n){n=!n||n/10%10<n%10&&g(n/10);}f(i){for(i=-1;++i<7e3;g(i)&&printf("%u\n",i));}
```
[Try it online!](https://tio.run/##DYpBDkAwEEXXegokmpkgNBYW5SY20mgzC0OEVTl7zeYl//3n2uBcSgEYI88Fvy93pq9MP7FAazlko/08EEZ/XEBza2xd0zRugw1itT4v4ttDWT0Llw2h5ElMvq/EgCqqzANa9aUf "C (gcc) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~102~~ ~~101~~ ~~73~~ ... 72 bytes
-12 **and** -4 thanks @Dennis!
```
for(var i=0;i<7e3;i++)if((i+"").Aggregate((a,b)=>a<b?b:':')<58)Print(i);
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr4QXd7EiiCjUin7QF1RU9lKg0ve3mVCHUIk5vQU@VzraJ0N2jbMhpZASACkhcLxyLjG7FgFc73E/nPWn11JLtMuGd6GnAaFh/gE "C# (Visual C# Interactive Compiler) – Try It Online")
Each integer from 0 to 7k tested by first converting it into a string. Leveraging the fact that C# treats strings as character enumerables and LINQ, an aggregate is calculated for each character enumerable as follows:
* compare the accumulated value with the current character
* if the current character is greater than the accumulation, return the current character
* otherwise return `:` which is greater than `9`
If the result of this is less than `:` (ASCII 58), then the number has lexicographically increasing digits.
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, 72 bytes
```
0|([1-9])(([2-9])(){$3-$1-1}(([3-9])(){$6-$3-1}(([4-9])(){$9-$6-1})?)?)?
```
Appropriately, outputs the numbers in lexicographic order. [Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWNz0MajSiDXUtYzU1NKKNwLRmtYqxroqhrmEtUMgYJmSmCxQFC5nAhCx1gaKGtZr2IAgxD2rsAigNAA)
### Explanation
```
0|
```
Match 0, or:
```
([1-9])
```
Match a digit 1 through 9 (capture group 1).
```
(...)?
```
Either stop there, or continue:
```
([2-9])
```
Match a digit 2 through 9 (capture group 3), and:
```
(){$3-$1-1}
```
Match an empty group X times, where X equals the second digit minus the first digit minus 1. If the second digit is not larger than the first digit, this quantity is negative, and using a negative number as a repetition count causes the match to fail. Thus, only matches where the second digit is larger than the first digit are included.
```
(...)?
```
Either stop there, or continue:
```
([3-9])
```
Match a digit 3 through 9 (capture group 6), and:
```
(){$6-$3-1}
```
Match an empty group Y times, where Y equals the third digit minus the second digit minus 1 (ensuring that the third digit is larger than the second digit).
```
(...)?
```
Either stop there, or continue:
```
([4-9])
```
Match a digit 4 through 9 (capture group 9), and:
```
(){$9-$6-1}
```
Match an empty group Z times, where Z equals the fourth digit minus the third digit minus 1 (ensuring that the fourth digit is larger than the third digit).
[Answer]
# [Python 2](https://docs.python.org/2/), 63 bytes
```
for i in range(6790):
if`i`=="".join(sorted(set(`i`))):print i
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPoSgxLz1Vw8zc0kDTikshMy0hM8HWVklJLys/M0@jOL@oJDVFozi1RAMorqmpaVVQlJlXopD5/z8A "Python 2 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¬ ▬A♥¶N∙
```
[Run and debug it](https://staxlang.xyz/#p=aa20164103144ef9&i=&a=1)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 90 bytes
```
import StdEnv
Start=(0,[('
',n)\\n<-[1..6^5]|(\l=removeDup l==sort l)[c\\c<-:toString n]])
```
[Try it online!](https://tio.run/##FcsxCsMgFADQPadwi0IS2qEdStySodDNUS1YY4Og32B@AoWevbYd3/BscAZKTNMWHInGQ/FxSRmJwGmEvRJoMnJ6aCStq7oBphT0rTx23fl@0m@qAs8upt0N20IC5@v/BiatUrZvL5gEZg8zAa1ZKR/7DGZeS3u9leEFJnr7w@ML "Clean – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 59 bytes
```
repeat n 9999[if(d: n - 1)= do sort unique form d[print d]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhId@78otSA1sUQhT8ESCKIz0zRSrIAcXQVDTVuFlHyF4vyiEoXSvMzC0lSFtPyiXIWU6IKizLwShZTY2P//AQ "Red – Try It Online")
] |
[Question]
[
### Challenge
Write a program that reorders the ASCII characters!
It should output a single string containing all of the printable ASCII characters exactly once. The first character of this string is assigned the value 1, the second character the value 2, and so on.
If two characters are normally next to each other (the difference between their character codes is 1), they may not appear next to each other in the output.
### Scoring
Your score will be the sum of the values for all of the characters in your source code, as dictated by your program's output.
Please see the **Verification** section to calculate your score.
Lowest score wins!
### Rules
* "Printable ASCII" is defined to mean character codes 32 - 126, inclusive.
* You may write a full program or a function.
* Your code may only contain printable ASCII characters and newlines.
* Your program may not take any input.
* Newlines will always have the value 1. Your program's output should not include a newline.
### Verification
Use this stack snippet to verify that your code's output is valid, and to calculate your code's score!
```
var result = document.getElementById("result");document.getElementById("submit").onclick = function() {var code = document.getElementById("code").value;var output = document.getElementById("output").value;var values = [];for (var i = 0; i < output.length; i++) {var c = output[i];var v = c.charCodeAt();if (v < 32 || v > 126) {result.innerHTML = "Invalid output! Reason: `" + c + "` (code " + v + ") is out of range.";return;}if (values.indexOf(c) >= 0) {result.innerHTML = "Invalid output! Reason: `" + c + "` (code " + v + ") was repeated.";return;}if (i > 0) {var d = output[i - 1];var w = d.charCodeAt();if (Math.abs(v - w) == 1) {result.innerHTML = "Invalid output! Reason: `" + d + "` and `" + c + "` (codes " + w + " and " + v + ") cannot appear next to each other in the output.";return;}}values.push(c);}for (var j = 32; j <= 126; j++) {var c = String.fromCharCode(j);if (values.indexOf(c) < 0) {result.innerHTML = "Invalid output! Reason: `" + c + "` (code " + j + ") was missing.";return;}}var score = 0;for (var k = 0; k < code.length; k++) {var s = values.indexOf(code[k]) + 1;if (s <= 0) s = 1;score += s}result.innerHTML = "Your score is " + score + "!";}
```
```
<textarea id="code" rows=10 cols=50>Enter your code here.</textarea><br/><textarea id="output" rows=1 cols=50>Enter your code's output here.</textarea><br/><button id="submit">Submit</button><br/><p id="result"></p>
```
### Leaderboard
*Thanks to [this post](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet) for the leaderboard code!*
```
var QUESTION_ID=57914,OVERRIDE_USER=42844;function answersUrl(e){return"http://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"http://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]
# CJam, ~~356~~ ~~186~~ ~~168~~ ~~131~~ ~~126~~ ~~111~~ ~~99~~ ~~96~~ 94
```
"_|`'~,Y/G>z`|"_~
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22_%7C%60'~%2CY%2FG%3Ez%60%7C%22_~).
### Output
```
"_|`'~,Y/G>z[ \$&(*.02468:<@BDFHJLNPRTVXZ^bdfhjlnprtvx!#%)+-13579;=?ACEIKMOQSUW]acegikmoqsuwy{}
```
### Idea
Using a variation of a technique common in CJam quines, we sort the printable ASCII characters by whether they appear in the source code, and the non-appearing ones – with two exceptions – by their code points' parity bits.
With the proper source layout, we also manage to sort the source code characters – with one exception – by their frequencies.
Special care has to be taken that two adjacent characters do not appear one after the other for the first time in the source code, as this would invalidate the answer.
### Code
```
" "_~ Push a string, duplicate it and evaluate the copy.
_| Perform the set union of the original string with itself.
This is just an "excuse" to introduce the underscore.
` Inspect the string (surrounds it with double quotes).
'~, Push the string of Unicode characters before the tilde.
Y/ Divide it into pairs.
G> Discard the first 16 pairs (control characters).
z Zip. This interleaves the pairs, ordering the characters
by their code points' parities.
` Inspect the array, i.e., push its string representation.
| Perform set union with the string of source code characters.
```
[Answer]
## Brainfuck, ~~1692~~ ~~826~~ 765
(Still) Unoptimized, I know. I'm working on it (leave opts in the comments).
```
++[------>+<]>.++.---[-->+++<]>-.[->+++++++++<]>.--[----->+<]>.[-->+++<]>+.++.>+++[<---------->-]<-[-->+<]>-++.>++[>+++<-]>[<<++.>>-]<<++++.++.++.++.++.++.++++>>++++[<++++++++>-]<[<++.>-]<---.++.-->+++[>+++++<-]>-[<<--.>>-]<<---->++++[>+++++<-]>++[<<--.>>-]<<------.--.--.--.--.
```
Output:
```
+->.<[] "$&(*,02468:@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~{}ywusqomkigeca_YWUSQOMKIGECA?=;97531/)'%#!
```
I'm already utilizing overflow on 8bit cells to some extent, but I guess you could still optimize it. Though that would decrease the use of cheap chars :).
[Answer]
# Pyth, ~~173~~ 170
### Code
```
-so%CN2rd\~p"p~\dr2NC%os-
```
### Output
```
p~\dr2NC%os- "$&(*,.0468:<>@BDFHJLPRTVXZ^`bfhjlntvxz|!#')+/13579;=?AEGIKMOQSUWY[]_acegikmquwy{}
```
Hardcoding a quine-like string. Conveniently, the `"` character is very near the start of the generated string. Prints even then odd characters after the "quine".
Much thanks to Dennis for saving 3 points, and making the code a palindome!
[Try it here](http://pyth.herokuapp.com/?code=-so%25CN2rd%5C~p%22p~%5Cdr2NC%25os-&debug=0)
[Answer]
# Java, ~~3518 3189~~ 2692
A simple loop that prints even characters, then odds. I tried a few things to optimize earlier ASCIIs, but most ended up making it longer overall, and ended up with a higher score.
```
void A(){for(char A=31;A!=126;System.out.print(A+=2))A=A==125?30:A;}
```
Output is:
```
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~
```
**Edit:** Misunderstood the scoring at first. After flipping it to odd first, *then* even, it scores a lot better.
[Answer]
# Octave, 628
Code
```
["" 32:2:126 33:2:125]
```
Output:
```
"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}
```
Two ranges implicitly converted to string. Not sure if returning as Ans is acceptable, also gives a warning about the implicit conversion. Tried some other range vectors, but could not find anything more efficient.
[Answer]
# C,42 bytes, score 1539
```
main(i){for(;i-191;i+=2)putchar(32+i%95);}
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~
```
# C,39 bytes, score 1687
```
main(i){for(;i-96;)i=putchar(32+i%95);}
!Aa"Bb#Cc$Dd%Ee&Ff'Gg(Hh)Ii*Jj+Kk,Ll-Mm.Nn/Oo0Pp1Qq2Rr3Ss4Tt5Uu6Vv7Ww8Xx9Yy:Zz;[{<\|=]}>^~?_ @`
```
In both cases, `i` is initialised to the number of strings on the commandline (as no arguments are given, this is 1.)
The first version does things the obvious way, incrementing by 2, taking modulo 95 and thefore printing all the odds then all the evens.
The second version takes advantage of the fact that putchar returns the character printed. As 32 is coprime to 95, we can cycle through the characters.
As C contains a lot of lowercase characters I hoped that this, besides being shorter, would have a lower score but unfortunately this is not the case.
[Answer]
# Befunge-93, ~~801~~ ~~797~~ ~~724~~ ~~699~~ ~~627~~ 612
Code:
```
"! " ^
v _@#$<
>:,2+:"~"`|
^ <
```
Output:
```
"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}
```
You can try it [here](http://www.quirkster.com/iano/js/befunge.html) if you want.
It works by outputting 32-126 evens, and then 33-125 odds. If anyone wants an explanation, I'd be willing to.
I golfed it until I got it better than brainf\*\*\*, which I deemed to be the lowest I could go. As far as golfing strategies, I generated the ascii characters and then tried to replace costly characters with cheaper ones (like 1 with 2). I found out since `g` was so expensive, it was better to compute 126 every iteration. I also wrapped around the top since `^` was cheaper than `v`.
**801 -> 797**: Recent change was removing extra spaces that was a relic from using `g`.
**797 -> 724**: I changed calculating 126 every time to just reading tilde using `"~"`. this also allowed for cutting away whitespace (And i'm beating one of the BF answers again)
**724 -> 699**: Similar to the last change, " " is an extremely cheap (4 points) way of obtaining 32
**699 -> 627**: Since I only go through the 2nd row pass once, I just changed it to setting 33 instead of maintaining another value on the stack and adding one.
**627 -> 612**: Moved as much as I could to string input. I'm pretty sure the design would need to change drastically to golf it any further.
This is probably the final iteration, unless one of the non-golfing languages gets a lower solution.
[Answer]
# Haskell, 830
```
['!','#'..'}']++[' ','\"'..'~']
```
Evaluates to the string:
```
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~
```
Inspired by [@Jørgen's answer](https://codegolf.stackexchange.com/a/57938/34531) and completely different from [my own](https://codegolf.stackexchange.com/a/57930/34531).
[Answer]
# Brainfuck, score ~~576~~ 667
Thinking about it, 576 seemed to good to be true: I did a little estimation and worked out my score to be around 95\*6 + 45\*2 = 660. Something must have gone wrong the first time I ran the validator. The correct score is closer to my estimate. It's still not a bad score.
```
+++++++++++++++++++++++++++++++++++++++++++++.--.+++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.---.++.----.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.---.--.--.--.--.--.--.+++.--.++++.++.++.
```
Keep it simple.
Basically just walks up and down the ASCII set, printing characters. The three characters used in the program are printed first. Turning round at either end was a little bit tricky.
```
-+.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~{}ywusqomkigeca_][YWUSQOMKIGECA?=;97531/,*(&$" #!%')
```
[Answer]
# Ruby 2.2, 1157
```
eval s='srand 1;([*s.bytes].shuffle|[*33..0x7e].shuffle).map{|c|putc c}'
```
Output:
```
f.p|cahu]xens7*0{)3tbmdy[}l1; r(o@&gN/MjzSVv~>D4I`L\KB92=i%PHE?5TQw,W-#6U'^Y!$R"XkO_q+CAGZF<8:J
```
This is a pretty dumb solution (and I'm not sure srand shouldn't be a standard loophole especially since it drastically reduces portability). Shuffles (most of) the bytes in its own source code and shuffles the rest, then uniques and concatenates the arrays. Uses a random seed picked so that the output is legal (the fact that it's a single digit is pure luck).
[Answer]
# CBM BASIC V2, 2553
```
1FORI=0TO47:PRINTCHR$(32+I*2);:NEXT
2FORI=0TO47:PRINTCHR$(33+I*2);:NEXT
```
the output (converted in ASCII by a python script on pc):
```
<blank>"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}
```
[Answer]
# gawk, ~~2782~~ ~~1988~~ 1821
```
END{for(rrf=rrr="rf(3)+=;1\"$?:~ptoin[<-EN% ^.|P";fr++<333;$fr=(ff=sprintf("%c",fr))~"[[(]"?f:ff);for(;r++<33+13+1;rrf=f)printf(rrf)(rrr~(rr=$(31+1+r+r))?f:rr)(rrr~(rr=$(133-(3+3+r+r)))?f:rr)}
```
### Output
```
rf(3)+=;1"$?:~ptoin[<-EN% ^.|P}{&yw*u,sq02m4k68gec>a@_B]DFYHWJULSQORMTKVIXGZ\CA`bd9h7j5l/vx'z#!
```
### Usage
Copy and paste the following to your console
(mawk won't work, because it's ~~too sctrict~~ stricter with printf)
```
awk 'END{for(rrf=rrr="rf(3)+=;1\"$?:~ptoin[<-EN% ^.|P";fr++<333;$fr=(ff=sprintf("%c",fr))~"[[(]"?f:ff);for(;r++<33+13+1;rrf=f)printf(rrf)(rrr~(rr=$(31+1+r+r))?f:rr)(rrr~(rr=$(133-(3+3+r+r)))?f:rr)}' < /dev/null
```
The `< /dev/null` at the end signals the end of input, so the END block will be executed.
I basically interweaved the characters coming from the bottom and coming from the top. Then I analysed, which characters were used the most in the program and printed them first, in order of frequency. Then I had to make sure that no character is printed more than one time. The weaving in opposite directions made it more probable that an already used character wouldn't lead to printing neighbours. But they met in the middle at `P`, so I had to print that in the beginning too. Then there were some problems with characters which are used in regexps... Then I renamed the variables cheaply and did the whole thing over again. Then I found some characters I could replace in my program, and did the whole thing over again. And so on.. I finally tweaked the string with the preferred characters a little by testing.
I think I'm done `:D`
During the process I never executed the program from the command line, but constructed a string I executed from inside a script, which would analyse the output for correctness and give me the score and stuff. That score output helped a lot. Of course I rechecked here (you never know) but it got me the same result.
There the program looks like this
```
p=sprintf("END{"\
"for(rrf=rrr=%c%s%c;fr++<333;$fr=(ff=sprintf(%c%cc%c,fr))~%c[[(]%c?f:ff);"\
"for(;r++<33+13+1;rrf=f)printf"\
"(rrf)(rrr~(rr=$(31+1+r+r))?f:rr)(rrr~(rr=$(133-(3+3+r+r)))?f:rr)}"\
,34,s=sprintf("rf(3)+=;1%c%c$?:~ptoin[<-EN%c ^.|P",92,34,37),34,34,37,34,34,34)
```
[Answer]
# Matlab, 763
Of course, it's quite impossible to beat the Octave solution in MATLAB, since it doesn't have `"` which is 'early' in the ASCII-range. However, I decided to get a bit creative and figured to abuse `randperm`. I admit that it's a bit hacky and some could consider it cheating, but I guess it's a nice touch. First, the program and output:
```
rng(1194663);['' randperm(95)+31]
```
Ouput:
```
p2)[]913r~jZe:'Xf +b(Atd@LHT*7&xmN>6!?CJgwsaSh|/McO4_EkK=$5VP-%D<"Gz#Yq08n};WB`{.l\Quy^vR,IFoiU
```
For calculating an appropriate seed, I used the following program, which I ran until seed=4648029 (i.e., until the dishes were done)
```
minscore=Inf;
for(seed=1:1e9)
rng(seed)
p=randperm(95)+31;
if(any(abs(diff(p))==1))
continue
end
codestring=sprintf('rng(%d);['''' randperm(95)+31]',seed);
score=0;
for(i=1:length(codestring))
score=score + find(codestring(i)==p,1);
end
if(score<minscore)
minscore=score;
bestseed=seed;
end
end
```
Perhaps one way to improve the program is to try out floating point seeds as well, e.g., 2.3e4 increase the number of seeds without having a longer seed length. If anyone feels like making a program to calculate all n-character numbers representable by Matlab.... ;)
[Answer]
# Haskell, ~~1660~~ 1376
```
""!_="O"
(a:b)!(c:d)=a:c:b!d
a=[' '..'N']!['P'..]
```
Defines the function `a` which returns the string:
```
P!Q"R#S$T%U&V'W(X)Y*Z+[,\-].^/_0`1a2b3c4d5e6f7g8h9i:j;k<l=m>n?o@pAqBrCsDtEuFvGwHxIyJzK{L|M}N~O
```
[Answer]
# Java, 15470
```
class A{public static void main(String[]I) throws Exception{java.lang.reflect.Field C=Character.class.getDeclaredClasses()[0].getDeclaredField("cache");C.setAccessible(true);Character[]E=(Character[])C.get(C);for(char A=31,G=31;A!=126;E[G++]=new Character(A+=2))A=A==125?30:A;for(char A=31;A!=126;A++)System.out.printf("%c", A);}}
```
Not really optimal at all, but it *actually* remaps the chars (rather than just printing out a set of modified chars).
Ungolfed:
```
public class Main {
public static void main(String[] args) throws Exception {
java.lang.reflect.Field feild = Character.class.getDeclaredClasses()[0].getDeclaredField("cache");
feild.setAccessible(true);
Character[] array = (Character[]) feild.get(args); //Since it's a static field, we can supply whatever we want here, and args is cheaper than null.
char i = 31;
for (char c = 31; c != 126; array[i++] = new Character(c += 2)) {
c = c == 125 ? 30 : c;
}
for (char c = 31; c < 126; c++) {
System.out.printf("%c", c);
}
}
}
```
## Output
```
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~
```
It orders the chars using the same method as [Geobits' answer](https://codegolf.stackexchange.com/a/57918/32531), and does something similar to [this answer](https://codegolf.stackexchange.com/a/28818/32531) to change the chars.
[Answer]
# BBC BASIC, 2554
## Code
```
n=32
s$=""
REPEAT
s$+=CHR$(n)
n+=2
IFn=128THENn=33
UNTILn=127
PRINTs$
```
## Output
```
"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}
```
[Answer]
# Fortran 90, ~~1523~~ ~~1519~~ 1171
This is a nested output loop, similar to other answers. Not too confident that much improvement is possible...
```
PRINT*,((CHAR(J),J=L,126,2),L=32,33)
END
```
Output:
```
"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}
```
**Edit:**
Forgot that Fortran 90 is necessary for this code, 77 requires code to start in the 7th column. On the other hand, the language is case insensitive, allowing an easy improvement. The loop counters are `J` and `L` because these are the first two letters in the output string implicitly declared as integers by Fortran.
[Answer]
# Perl, ~~1089~~ 922
It turns out that printing the ASCII values in steps of ~~42~~ **58** gives the lowest score with this approach:
```
print chr$_*58%95+32for 0..94
```
### Output:
```
Z5oJ%_:tO*d?yT/iD~Y4nI$^9sN)c>xS.hC}X3mH#]8rM(b=wR-gB|W2lG"\7qL'a<vQ,fA{V1kF![6pK&`;uP+e@zU0jE
```
[Answer]
# JavaScript, ~~3169~~ ~~2548~~ ~~2144~~ ~~2104~~ ~~2071~~ ~~1885~~ ~~1876~~ 1872
### Code
```
t=''
i=S=95
while(i--)t+=String.fromCharCode(i*2291%S-
-32)
alert(t)
```
### Output
```
ti^SH=2'{peZOD9.#wlaVK@5*~sh]RG<1&zodYNC8-"vk`UJ?4)}rg\QF;0%yncXMB7,!uj_TI>3(|qf[PE:/$xmbWLA6+
```
[Answer]
# Python 2, ~~72 bytes (3188)~~ 116 bytes ~~(1383)~~ ~~(1306)~~ (1303)
thanks @FryAmTheEggman for the join trick ;)
thanks @nim (Did I misread the text? :P)
thanks @Mathias Ettinger
```
n='nr i(a)2:]o[c=fh1+t"3egj,p.7'
a=[chr(r)for r in range(32,127)if not chr(r)in n]
print n+"".join(a[::2]+a[1::2])
```
output:
```
nr<blank>i(a)2:]o[c=fh1+t"3egj,p.7!$&*/469<?ACEGIKMOQSUWY\_bkmsvxz|~#%'-058;>@BDFHJLNPRTVXZ^`dlquwy{}
```
[Answer]
# PHP, 1217 1081
The code:
```
for(;$T!=T;$T=($T+52)%95)echo chr(32+$T);
```
Because the variables are not initialized, it needs to suppress the notices on running (PHP complains but continues execution and uses a default value that is appropriate in the context; `0` in this case):
```
$ php -d error_reporting=0 remapping-ascii.php
```
Its output:
```
T)]2f;oDxM"V+_4h=qFzO$X-a6j?sH|Q&Z/c8lAuJ~S(\1e:nCwL!U*^3g<pEyN#W,`5i>rG{P%Y.b7k@tI}R'[0d9mBvK
```
Remarks:
* the output starts with a white space (`chr(32)`);
* the code prints the white space then each 52th character, wrapping around the range;
* the magic number `52` was "discovered" by searching the entire range (1..94) of possible offsets; 1 produces the list of printable chars in the ascending order of their ASCII codes, 94 produces the list in the reverse order, both are bad; the multiples of 5 and 19 (the divisors of 95) produce short cycles and don't cover the entire range of values (also bad);
* `52` seems to be magic; it is the best offset for this code; but it is also the best for some variations of the code (that produce slightly bigger scores); the variations I tried: use `while()` instead of `for()`, use `$f++`, `$f--` or `--$f` instead of `++$f`, swap the operands around the `<` and `+` operators; squeeze the modification of `$T` into `32+$T`;
* the names of the variables (`$T` and `$f`) are the first letters from the output;
* I tried to initialize `$T` with `4` or `11` but the scores were worse; starting with `4` makes `$` the first character in the output; it is the most used character in a PHP source code; `11` brings `+` in front; `$` and `+` are the most used characters in this code.
The code, tests, incremental changes I tried until I reached this solution and the script that tested all possible step values (the authoritative provider for `52` as the best step) can be found [on github](https://github.com/axiac/code-golf/blob/master/remapping-ascii.php).
[Answer]
# Fourier, 1236
Basically a conversion of my BBCB program
```
32~N127(Na^^~N{128}{33~N}N)
```
## Output
```
"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 49 bytes, Score: 1755
```
BEGIN{for(f=82;++f<178;)printf"%c",(2*f-1)%95+32}
```
[Try it online!](https://tio.run/##SyzP/v/fydXd0686Lb9II83WwshaWzvNxtDcwlqzoCgzryRNSTVZSUfDSCtN11BT1dJU29io9v9/AA "AWK – Try It Online")
Simply prints every other character then starts over filling in the blanks.
First character printed is an `f`. I attempted printing in reverse order, but that greatly increased the score. Other patterns are possible by simply changing the multiplier and the loop criteria.
[Answer]
# [Perl 5](https://www.perl.org/), 1069
```
print chr$_*2%95+32for 0..94
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRCE5o0glXstI1dJU29goLb9IwUBPz9Lk//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online")
] |
[Question]
[
## Description
Count how many occurrences there are of the digit **1** between two given numbers \$[a, b]\$, inclusive.
For example, from 1 to 100 it should be 21:
**1**, **1**0, **11**, **1**2, **1**3, **1**4, **1**5, **1**6, **1**7, **1**8, **1**9, 2**1**, 3**1**, 4**1**, 5**1**, 6**1**, 7**1**, 8**1**, 9**1**, **1**00
The number **1** is repeated 21 times.
## Rules
1. Each number in the input list is guaranteed is an integer in the range \$0 \leq a \leq b < 2^{32}\$.
2. The shortest answer in bytes wins.
## Test cases
```
[1, 100] -> 21
[11, 200] -> 138
[123, 678] -> 182
```
## Example
Here is my code using bash
```
eval echo {$1..$2}|grep -o 1|wc -l
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes
Thanks a lot to OP! Now I can save a byte
```
ŸSΘO
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6I7gczP8//@PNtQxNDCIBQA "05AB1E – Try It Online")
## Explanation
```
≈∏ Inclusive range
S Split the string into individual chars
Θ (Vectorizes) Does this character == "1"?
O Sum the resulting list
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~39~~ 36 bytes
-3 bytes thanks to @SurculoseSputum
```
lambda a,b:`range(a,b+1)`.count('1')
```
[Try it online!](https://tio.run/##NY7RqsIwDIbv@xRBGGs4cdgKOoSdJzkXduq0sLWlrRc@/Uw7Ti5C/vD9fxI@@eWdXicY4G@dzTLeDRgaL9do3PMhefxReO1u/u2ybFWLq12CjxnSJwkx@QizdQ@wriy6lO/WXQRwWRcI/DtzcCG6mHK0QWKXwmw5Cva/0GJFDcHI2GKCtC5Tsf5T1CKKCj19iZpkgTdbbSGyRe6aBMMA3GWTcAcNSObrfdqcAxSONSKuitThUB7QSihFehPq2Aulj3Q691X2@gs "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), ~~42~~ 40 bytes
-2 bytes thanks to @JoKing
```
lambda a,b:f"{*range(a,b),b}".count('1')
```
[Try it online!](https://tio.run/##NY7BisMwDETv/goRCLGKGuoEdkMh/ZK9ONuma0hsY7uHUvrtqeywOgyMeDOSf6Y/Z/tthhF@tkWv01WDpuk8V69D0PZ@k@yQpnfV/rqHTbJRDW5m9S4kiM8oxOwCLMbewNi8aGO6GnsWwGOsJ3CPxOWZaENMwXiJbfSL4So4XqDBgmqCibFVe2lsohz9p6hBFAW6u1w1ywzvsSI@cERWdYRxBFZZR6ygBsl8uU97coTMsUfETZE6nfIDnRJKUbcb1Q9CdT19fQ/FDt0H "Python 3 – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/)+[itertools](https://crates.io/crates/itertools), 42 bytes
```
|a,b|(a..=b).join("").matches('1').count()
```
[Try it in the Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ddd5ae6f71aee1a0d4392a066410fe24)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
```
+/'1'=⍕⍤…
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X1tf3VDd9lHv1Ee9Sx41LPuf9qhtwqPevkddzY961zzq3XJovfGjtomP@qYGBzkDyRAPz@D/hgppCoYGBlyGIIYRiGFkDGSZmVsAAA "APL (Dyalog Extended) – Try It Online")
`+/`‚ÄÉsum
`'1'=`‚ÄÉwhere the character is equal to
`‚çï`‚ÄÉthe string representation
`⍤` of
`…` the range
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~29~~ ~~28~~ 27 bytes
```
@(x,y)sum(mat2str(x:y)==49)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KnUrO4NFcjN7HEqLikSKPCqlLT1tbEUvN/moahjqGBgSYXkGGoYwRlGRnrmJlbaP4HAA "Octave – Try It Online")
[Answer]
# Java 8, ~~71~~ ~~67~~ 66 bytes
```
a->b->{var s="";for(;b>=a;)s+=b--;return~-s.split("1",-1).length;}
```
-4 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##jY8xb4MwEIX3/IqTJyxsK06ltooLY6UOnTIiBkOAmjoG4SMlQvSvUyeNOnf77t7du3etPmveHj/X0mrv4V0bN28APGo0JbRBFSMaK@rRlWg6J17v8PLmsGqqgf1v6A5pCjUkq@ZpwdP5rAfwCSGq7oZIFWmiFfVxUnCuhgrHwX1zL3xvDUZEEsYlFbZyDX6oZVWbELMfCxti3tOeO3OEU/ggOuBgXJPloOn1G4DrAeMwdCbYg6u@4FZl@TxLJrfbhc1Sst0v7B7Y49PzstDbKsDh4rE6iW5E0QdftC6asm0eE0biKZMB9kDiWui@t5ebRP9Y5pSq4LNslvUH)
**Explanation:**
```
a->b->{ // Method with two integer inputs and integer return-type
var s=""; // String `s`, starting empty
for(;b>=a;) // Loop `b` downwards in the range [`b`, `a`]:
s+=b--; // And append `b` to to String `s`
return~-s.split("1", // Split String `s` on "1",
-1) // and keep empty trailing items
.length; // Then get the amount of parts of this array
// And decrease it by 1 with `~-`, before turning it as result
```
[Answer]
# [R](https://www.r-project.org/), 43 bytes
```
function(x,y)sum(unlist(gregexpr(1,x:y))>0)
```
[Try it online!](https://tio.run/##K/qfnF@aVxKfn5dabPs/rTQvuSQzP0@jQqdSs7g0V6M0LyezuEQjvSg1PbWioEjDUKfCqlJT085AE0kfUNTQwECTC1nEUMcIXcjIWMfM3ELzPwA "R – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 62 46 28 bytes
```
->c,d{[*c..d].join.count ?1}
```
-18 bytes, courtesy of [Dingus.](https://codegolf.stackexchange.com/users/92901/dingus)
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5ZJ6U6WitZTy8lVi8rPzNPLzm/NK9Ewd6w9n@BQlq0oY6hgUEsF5hpqGMEZxsZ65iZW8T@BwA "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), 44 bytes
Expects `(a)(b)`.
```
a=>g=b=>b<a?0:(b+g).split(1).length-3+g(b-1)
```
[Try it online!](https://tio.run/##XclBDsIgEADAu6/guJsGykKipJH6FqgUawg0Qvw@etBL5zpP93Z1eW1747ncQ19td3aO1tvZX91NTuCHiKLuaWtAKFLIsT24HiJ4TtiXkmtJQaQSYQXGCIGkRGTjyBSdDk3fVv8mbQ5PSiOcL@b3RvUP "JavaScript (Node.js) – Try It Online")
### How?
We use a recursive function `g` to count how many `1`'s we have in `b` and decrement `b` until it's lower than `a`.
In order to count the `1`'s, we have to coerce `b` to a string. We could do `b+''` but it's shorter to use `b+g`. Because the source code of `g` itself contains two `1`'s, we subtract `3` instead of just `1` from the result of `(b+g).split(1).length`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~36~~ 32 bytes
```
\d+
$*_
(?<=(_+) _*)(?=\1)
$.'
1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFK55Lw97GViNeW1MhXktTw942xlCTS0VPncvw/39DBUMDAy5DQwUjEGVkrGBmbgEA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*_
```
Convert `a` and `b` to unary, but use `_` instead of `1` to avoid confusion. (In Retina 1 this would just be `*`, saving 2 bytes.)
```
(?<=(_+) _*)(?=\1)
$.'
```
At each boundary in `b` up to and including `a` from the end, insert the distance to the end in decimal, thus generating the range from `b` down to `a`.
```
1
```
Count the resulting number of `1`s.
[Answer]
# Google Sheets, 68
```
=SUM(ArrayFormula(LEN(REGEXREPLACE(""&SEQUENCE(A2-A1+1,1,A1),"[^1]",
```
Sheets auto-closes parens.
This is super slow at large ranges, but as this is Code Golf, we're here to optimize character count. My first attempt was to use `JOIN(SEQUENCE(...))` to make one long string then count the 1's, but as it turns out, Sheets has a limit of 50000 characters, so that didn't work.
[Answer]
# [Kotlin](https://kotlinlang.org), 49 bytes
```
{x:Int,y:Int->(x..y).sumBy{"$it".count{it=='1'}}}
```
[Try it online!](https://tio.run/##TcnBCoMgGADgu0/xE4MUytJgi4EddttjxECQ2V9sOhLx2V2jHbp8l@85O2swa48wjQYpg0g@owUNKsf1ekdXhZ/1QFfOA@NvP91CLE7GFfwxe3TROKVKUaaU8vIy6CxSTUUFom0ZA4CmgXoAKchht5Z77yu6/tiyq@B86bf/dy9JyvkL "Kotlin – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
a!b=sum[1|'1'<-show[a..b]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1Exyba4NDfasEbdUN1Gtzgjvzw6UU8vKTb2f25iZp6CrUJKvkJBUWZeiYahoqGBgaY1jGeoaITMNTJWNDO30PwPAA "Haskell – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
↨æ▒m┴Σ]Σ
```
[Try it online.](https://tio.run/##y00syUjPz0n7//9R24rDyx5Nm5T7aMqWc4tjzy3@/99Qx9DAgMvQUMcIRBkZ65iZWwAA)
**Explanation:**
```
‚Ü® # Loop in the range [a,b] using the two implicit inputs a,b,
æ # and execute the following four commands:
‚ñí # Convert the integer to a list of digits
m # Map over each digit:
┴ # And check which are equal to 1 (1 if 1; 0 otherwise)
Σ # Get the sum of those checks
] # After the loop, wrap all values on the stack into a list
Σ # And sum this list
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 21 bytes
```
map$\+=y/1//,$_..<>}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlRtu2Ut9QX19HJV5Pz8autvr/f0NDLiMDg3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 40 bytes
```
$a,$b=$args
($a..$b|sls 1 -a|% m*).Count
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyVRRyXJViWxKL2YS0MlUU9PJammOKdYwVBBN7FGVSFXS1PPOb80r@T///@G/w0NDAA "PowerShell – Try It Online")
---
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 40 bytes
```
($args-join'..'|iex|sls 1 -a|% m*).Count
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9WDcrPzNPXU9PvSYztaKmOKdYwVBBN7FGVSFXS1PPOb80r@T///@G/w0NDAA "PowerShell – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~46~~ 45 bytes
```
fn($a,$b)=>substr_count(join(range($a,$b)),1)
```
[Try it online!](https://tio.run/##TY1PC4IwGMbv@xQvsoODiW5CCaadgg5B3lViiss6OHHzFH329RJC3R5@z795nP3hOI8zIVQXXk8hVZx2rCjt2lm33HqzTi58mscULmq6D5vPuGA@x5IbrLNQQE1qwUEkScshjiEqQQpEyOQfE2mGUKYcdvvsRzNJWhzTZhlUP4awrSqLChi8CECNv0C7Fq@oyxEM/WggoCqiXeOisnEB@hq73xwwDtW5up2ul5y8/Qc "PHP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 58 bytes
```
i;c;f(a,b){for(c=0;b/a;)for(i=a++;i;i/=10)c+=i%10==1;a=c;}
```
[Try it online!](https://tio.run/##bVHBboMwDL33KywkpKSkIoC6MWXZZdpXFDSFELYcRivggIb4dmYgdK3USHZiv@fnONGHL62nyQotKqJYQYfq3BAtuShCJegcWKmCQFhhQxlxqgNp/YhLGQkltRgnW3fwo2xN6G7YAa450Zm2@1SnHCQMEYNotjgZxT2hcATOGcSze3pObzimv5i@M@XCgiGeRZIUXRo7lv5WzR6aVcbL@o8461/e0Y4eg9s48bBiKcGJgMzqti5Nj3VcuOMrtPbXnCuy9aWhS@yvGQFBsLAprMNud1Wo5IZe8FzcwcUGFw9hg/B12keEFgnr//znLw0iFfFOfsnAL3M4vOEGxC8p@G1W4xMoBgWDloFh@Eoogm1yJzHuxukP "C (gcc) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 65 bytes
```
: f ( a b -- n ) [a,b] [ number>string [ 49 = ] count ] map sum ;
```
[Try it online!](https://tio.run/##Nc09D4IwGATgnV9xoyaWUDR@QHRVFhbjRBgKeUGjLdiPEH59rTFuzw1314nWDtrfrkV5zvAkregFKew9HoU2pH/WQvVkYOjtSLVBoyZr51E/lEUeFWWGyzAxKdTMuGETsZ6sz9BhAYEGjEFhiUqsmhoVlJMN6ZOxod@HvDngiBrt4MJcHS5HGCeRew6eJGEljjhH@me6xna3/9p/AA "Factor – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~19~~ 17 bytes
**Solution:**
```
{+/"1"=,/$x_!1+y}
```
[Try it online!](https://tio.run/##y9bNz/6fZlWtra9kqGSro69SEa9oqF1Z@z9NT13DUMHQwMDa0FDBCEQZGSuYmVto/v8PAA "K (oK) – Try It Online")
**Explanation:**
Range generation is inefficient (i.e. generate range 0..Y and then drop from front, rather than generating range X..Y) but saves 2 bytes.
```
{+/"1"=,/$x_!1+y} / the solution
{ } / lambda taking implicit x & y args
1+y / add 1 to y
! / range 0..N
x_ / drop (_) x items from front
$ / convert to string
,/ / flatten
"1"= / is string equal to "1"?
+/ / sum
```
[Answer]
# JavaScript (ES6), ~~63~~ 62 bytes
```
a=>b=>([...Array(b-a+1)].map((_,i)=>i+a)+'').split(1).length-1
```
[Try it online](https://tio.run/##XcmxDoIwEADQ3a/oxl2QgyuJsrSJ32GMORCwplJSiIlfXx104a3vIS9ZuujmtZjCrU@DSWJsayyciegUo7yhLSRnvNBTZoDr3qGxLhfMswxpmb1bgZF8P43rveDUhWkJvicfRhhAKUbgqkJUZak07zbN39b/5rrZPOsa4XBsft/o9AE)
```
[...Array(b-a+1)] // an array of length b-a+1
map((_,i)=>i+a) // fill it with numbers from a to b
+'' // convert it to a string with each number separated by a comma
.split(1) // split at each 1
.length-1 // count the chunks and subtract 1
```
-1 byte thanks to @Jo King
[Answer]
# [J](http://jsoftware.com/), ~~19~~ 16 bytes
-3 bytes thanks to Jonah!
```
1#.1=/&":[,-.&i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1DG311ZSsonV09dQy9f5rcilwpSZn5CsoKBgaGChoWFunaSoYQoWMECJQITNzC5iIkTFXakVmibo616MpPY@mNGBDa2CMCUBFTTB1a5BUTACKGxkCCYiCJhAT6BAIR0EBLjEFrHoLks4ZSAqm4LAfrn4GHkeiuwjZqVhca2hsgeRckHuNEO5FdzBWNxNwNLoe/E4n4HpsHrAwQvKAkTGQBEYrHh@Q6Ql0bf8B "J – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
The spec contradicts itself as to whether the range should be inclusive or not. If it shouldn't then replace `õ` with `o`.
```
õ ¬è1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9SCs6DE&input=MTAw)
[Answer]
# [Rust](https://www.rust-lang.org/), 63 bytes
```
|a,b|(a..=b).map(|x|format!("{}",x).matches('1').count()).sum()
```
[Try it online!](https://tio.run/##XY29DoIwFIVneYrCwr1JbagmavxhZPMhCoIytBh6mxApz16BwcHlnOTLyXd6Zyk0hmnVGkA2RhuqLUHwipcelBC3EoVWb/CDb7peK4ohGaeEDwum6lVbSGWKouqcIUAU1mnAgJdoimbvYrsWZ1aYuyNwtv3UfE3c5mvnoB2xZl6s74/yGUMDksssw1nyA5Lv/shuzw/H04Km8AU "Rust – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
&:V1V=s
```
[Try it online!](https://tio.run/##y00syfn/X80qzDDMtvj/f0MjYy4zcwsA "MATL – Try It Online")
## Explanation
```
&:V1V=s
=s % Count occurrences
1V % of '1' in
V % string of
&: % inclusive range of input
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 80 bytes
```
a->b->IntStream.range(a,b+1).flatMap(i->(""+i).chars()).filter(x->x==49).count()
```
[Try it online!](https://tio.run/##bY8xb8IwEIX3/IoTk12wRaUuFY3HSkgwZaw6XILjOnVsy74gUMVvTw1lK9Od3nf37t2ARxQhaj8cvmc7xpAIhqLJiayTT5vqn9ZPviMb/EOYKWkcr6jqHOYMe7QefiqAOLXOdpAJqZRjsAcYC2MNJevNxydgMpnfRgHe7zfetp600Wn1QNkFb5SCHmq47cwoVCtU4c1fiITeaIardvnMZe@Q9hiZFYotFkvLZfeFKTNekHWkEzsJdarrl9dCwuSJ8bk8cTVuzpn0KMNEMpas5DzrJcbozqwY35v1mvNNGb9Ul/kX "Java (OpenJDK 8) – Try It Online")
Doesn't need much of an explanation, but here's one anyways:
```
Function<Integer, Function<Integer, Long>> f =
a -> b->
IntStream
.range(a,b+1) //Create an IntStream going from a to b
.flatMap(i -> //Map every int i in that stream
(""+i) //Make it a string
.chars() //Turn that string to an IntStream
) //Flatten that
.filter(x -> x == 49) //Keep all the '1's
.count(); //Find out how many '1's there are
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
rDFċ1
```
[Try it online!](https://tio.run/##y0rNyan8/7/Ixe1It@H///8NDf8bGRgAAA "Jelly – Try It Online")
**Explanation:**
```
rDFċ1
r range of the inputs
DF make decimal and flatten; list of all the digits in the range
ċ1 count occurences of 1
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes
-1 byte thanks to @FryAmTheEggman
```
/`}QE"1
```
[Try it online!](https://tio.run/##K6gsyfj/Xz@hNtBVyfD/f0MjYy4zc4t/@QUlmfl5xf91UwA "Pyth – Try It Online")
## Explanation
```
/`}QE"1
}QE # Inclusive range on input
` # string of the range ([1, 2, 3] -> "[1, 2, 3]")
/ "1 # count ones
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes
```
Tr@DigitCount[Range@##,10,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6TIwSUzPbPEOb80ryQ6KDEvPdVBWVnH0EDHMFbtf0BRZl6JgkN6tCFQxCCWC8E31DFCFTAy1jEzt4j9/x8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Dart](https://www.dartlang.org/), 56 bytes
```
f(a,b)=>'1'.allMatches([for(;a<=b;a++)a].join()).length;
```
[Try it online!](https://tio.run/##S0ksKvn/P00jUSdJ09ZO3VBdLzEnxzexJDkjtVgjOi2/SMM60cY2yTpRW1szMVYvKz8zT0NTUy8nNS@9JMP6f24iiK9QzaWgUFCUmVeikaZhqGNoYKCpaY0sZKhjhCFmZKxjZm4BEqz9DwA "Dart – Try It Online")
] |
[Question]
[
# Challenge
This is a simple one: Given a positive integer up to 1,000,000, return the closest prime number.
If the number itself is prime, then you should return that number; if there are two primes equally close to the provided number, return the lower of the two.
Input is in the form of a single integer, and output should be in the form of an integer as well.
I don't care *how* you take in the input (function, STDIN, etc.) or display the output (function, STDOUT, etc.), as long as it works.
This is code golf, so standard rules apply—the program with the least bytes wins!
# Test Cases
```
Input => Output
------ -------
80 => 79
100 => 101
5 => 5
9 => 7
532 => 523
1 => 2
```
[Answer]
# JavaScript (ES6), 53 bytes
```
n=>(g=(o,d=N=n+o)=>N%--d?g(o,d):d-1?g(o<0?-o:~o):N)``
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k4j3VYjXyfF1s82Tztf09bOT1VXN8U@HSSmaZWiawhi2hjY6@Zb1eVrWvlpJiT8T87PK87PSdXLyU/XSNOwMNDU5EIVMjTAFDPFELHEVGNshGmWpuZ/AA "JavaScript (Node.js) – Try It Online")
### Commented
```
n => ( // n = input
g = ( // g = recursive function taking:
o, // o = offset
d = // d = current divisor, initialized to N
N = n + o // N = input + offset
) => //
N % --d ? // decrement d; if d is not a divisor of N:
g(o, d) // do recursive calls until it is
: // else:
d - 1 ? // if d is not equal to 1 (either N is composite or N = 1):
g( // do a recursive call with the next offset:
o < 0 ? // if o is negative:
-o // make it positive (e.g. -1 -> +1)
: // else:
~o // use -(o + 1) (e.g. +1 -> -2)
) // end of recursive call
: // else (N is prime):
N // stop recursion and return N
)`` // initial call to g with o = [''] (zero-ish)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Åps.x
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cGtBsV7F//@GxsbmAA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX1n5/3BrQbFexX@d/xYGXIYGBlymXJYA)
Inefficient for big numbers
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 3 bytes
```
ṅD⌡
```
[Try it online!](https://tio.run/##S0/MTPz//@HOVpdHPQv//zc1NgIA "Gaia – Try It Online")
Rather slow for large inputs, but works given enough memory/time.
I'm not sure why `D⌡` implicitly pushes `z` again, but it makes this a remarkably short answer!
```
ṅ | implicit input z: push first z prime numbers, call it P
D⌡ | take the absolute difference between P and (implicit) z,
| returning the smallest value in P with the minimum absolute difference
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 40 bytes
```
@(n)p([~,k]=min(abs(n-(p=primes(2*n)))))
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zQCO6Tic71jY3M08jMalYI09Xo8C2oCgzN7VYw0grTxME/qdpWBhocqVpGBqAKVMQYQlmGRuBxTX/AwA "Octave – Try It Online")
This uses the fact that there is always a prime between `n` and `2*n` ([Bertrand–Chebyshev theorem](https://en.wikipedia.org/wiki/Bertrand%27s_postulate)).
### How it works
```
@(n)p([~,k]=min(abs(n-(p=primes(2*n)))))
@(n) % Define anonymous function with input n
p=primes(2*n) % Vector of primes up to 2*n. Assign to p
abs(n-( )) % Absolute difference between n and each prime
[~,k]=min( ) % Index of first minimum (assign to k; not used)
p( ) % Apply that index to p
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
_j}cU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X2p9Y1U&input=NA) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=X2p9Y1U&input=WzgwLDEwMCw1LDksNTMyLDFd)
```
_j}cU :Implicit input of integer U
_ :Function taking an integer as an argument
j : Test if integer is prime
} :End function
cU :Return the first integer in [U,U-1,U+1,U-2,...] that returns true
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes
```
Nearest[Prime~Array~78499,#,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y81sSi1uCQ6oCgzN7XOsagosbLO3MLE0lJHWccwVu0/UDyvxEErTd@h2sJAx9DAQMdUx1LH1NhIx7D2/38A "Wolfram Language (Mathematica) – Try It Online")
```
& (*pure function*)
Prime~Array~78499 (*among the (ascending) first 78499 primes*)
1 (*select one*)
Nearest[ ,#, ] (*which is nearest to the argument*)
```
1000003 is the 78499th prime. `Nearest` prioritizes values which appear earlier in the list (which are lower).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes
```
ḤÆRạÞµḢ
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//4bikw4ZS4bqhw57CteG4ov///zk5OQ "Jelly – Try It Online")
Slow for larger input, but works ok for the requested range. Thanks to @EriktheOutgolfer for saving 2 bytes!
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
f=lambda n,k=1,p=1:k<n*3and min(k+n-p%k*2*n,f(n,k+1,p*k*k)-n,key=abs)+n
```
[Try it online!](https://tio.run/##HctBDoMgEEbhdXuK2ZjAgEmhO1MOg1EsmfpLqBtPT0mXL/leuc73Ad9aCp@4z0skWAnOluAmeYGfEQvtGUoMxjIIe4ZNqiPTEQuLHnusV4jzVxu0dFQCZVCN2FblrH/o6X4rNeOk/6rbDw "Python 2 – Try It Online")
A recursive function that uses the [Wilson's Theorem](https://codegolf.stackexchange.com/a/27022/20260) prime generator. The product `p` tracks \$(k-1)!^2\$, and `p%k` is 1 for primes and 0 for non-primes. To make it easy to compare `abs(k-n)` for different primes `k`, we store `k-n` and compare via `abs`, adding back `n` to get the result `k`.
The expression `k+n-p%k*2*n` is designed to give `k-n` on primes (where `p%k=1`), and otherwise a "bad" value of `k+n` that's always bigger in absolute value and so doesn't affect the minimum, so that non-primes are passed over.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
z-Ån
```
[Try it online!](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX1n5v0r3cGvef53/FgZchgYGXKZcllymxkZchgA "05AB1E – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~7~~ 5 bytes
```
;I≜-ṗ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39rzUecc3Yc7p///b2hgYPA/CgA "Brachylog – Try It Online")
Saved 2 bytes thanks to @DLosc.
### Explanation
```
;I≜ Label an unknown integer I (tries 0, then 1, then -1, then 2, etc.)
- Subtract I from the input
ṗ The result must be prime
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~87~~ ~~76~~ ~~74~~ 72 bytes
Optimization of innat3's [C# (Visual C# Interactive Compiler), 100 bytes](https://codegolf.stackexchange.com/a/182364/83073)
```
f(n,i,t,r,m){for(t=0,m=n;r-2;t++)for(r=i=1,n+=n<m?t:-t;i<n;n%++i||r++);}
```
[Try it online!](https://tio.run/##fc5BCoMwFATQdT1FEISE/EBUBG1Me5FuipDyF/mWkJ169tS4b1YDw2OYRX2WJSXHCRAiBPBic2vg0WrwlkxQnYlSitwFi7YFkpZm/4x3FQ3OZKiREvc9nMgcyb@RuKi26vYNSNHxuumRqQc740U1sFEDc3zUQpi/ptUXOqOkhmyGkpiymIobfXet9F3xz/UmiyP9AA "C (gcc) – Try It Online")
[Answer]
# Pyth, 10 bytes
```
haDQfP_TSy
```
Try it online [here](https://pyth.herokuapp.com/?code=haDQfP_TSy&input=1000&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=haDQfP_TSy&test_suite=1&test_suite_input=80%0A100%0A5%0A9&debug=0).
```
haDQfP_TSyQ Implicit: Q=eval(input())
Trailing Q inferred
yQ 2 * Q
S Range from 1 to the above
f Filter keep the elements of the above, as T, where:
P_T Is T prime?
D Order the above by...
a Q ... absolute difference between each element and Q
This is a stable sort, so smaller primes will be sorted before larger ones if difference is the same
h Take the first element of the above, implicit print
```
[Answer]
# [Factor](https://factorcode.org/), 91 bytes
```
: p ( x -- x ) [ nprimes ] keep dupd [ - abs ] curry map swap zip natural-sort first last ;
```
[Try it online!](https://tio.run/##LY07DsJADER7TjElFBvxERKEAyCaNIgKUSzBQETYLLYjCJcPTkLz7BnLM1efa8XtYb/Ltim8SJULHsSBSjy93nskkYsnCSKTamMiKIReNYXcXKlYi3DDZrTLUmTkmURd/9KmiBjjA@cMExwR/lEnK6GISx0v5jr4c@flNXNjlRHyNnyLiOC1Zl@6rgXXgkVResOmXU0tPBnNpsNc9lwP@2I@3Dq2Pw "Factor – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 35 bytes
```
{$_+=($*=-1)*$++until .is-prime;$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKZV1BaomCrYGxqzQXkqyXl5CdnA/n/q1XitW01VLRsdQ01tVS0tUvzSjJzFPQyi3ULijJzU61V4mv/W3MVJ8L0aECM0vwPAA "Perl 6 – Try It Online")
This uses Veitcel's technique for generating the list of `0, -1, 2, -3` but simplifies it greatly to `($*=-1)*$++` using the anonymous state variables available in P6 (I originally had `-1 ** $++ * $++`, but when golfed the negative loses precedence). There's a built in prime checker but unfortunately the `until` prevents the automagically returned value so there's an extra `$_` hanging around.
[Answer]
# C, ~~122~~ ~~121~~ 104 bytes
```
p(a,i){for(i=1;++i<a;)if(a%i<1)return 0;return a>1;}c(a,b){for(b=a;;b++)if(p(--a)|p(b))return p(b)?b:a;}
```
Use it calling function `c()` and passing as argument the number; it should return the closest prime.
Thanks to Embodiment of Ignorance for ~~1 byte saved~~ a big improvement.
[Try it online!](https://tio.run/##TY5LboNADIb3cworEtJYDBIkSpTWkC56jDQLD4HIUjtFQFd0zk4NaaR44ef/2a6z@pPDbZ47y05war97K1VBaSolE0prOZGywL4Zf/oAOf0nfCoo1sr4O@MrJvJpuhCdzTLG3856fHBL/uZfmeJsJIzwxRIsmsmA2tIYm2F856EZzheoYIJj7qDI1e0dvKjfbbWGSGYl1i@VEtXmpKGEA4H@jOv4vnaxrldZazfJFbITJNePsHFPt@TioLbPNSKtcDRx/gM "C (clang) – Try It Online")
[Answer]
# [Tidy](https://github.com/ConorOBrien-Foxx/Tidy), 43 bytes
```
{x:(prime↦splice(]x,-1,-∞],[x,∞]))@0}
```
[Try it online!](https://tio.run/##K8lMqfyfpmBlq/C/usJKo6AoMzf1Uduy4oKczORUjdgKHV1DHd1HHfNidaIrdEC0pqaDQe3/kmSQlmQNCwMdBUMDIGGqo2AJJI2NgHxNrmqFCgUrhfKizJLUnDyNCh0FJQVdOwUlHYU0jQpNTYVahfw8hZLk/wA "Tidy – Try It Online")
## Explanation
This is a lambda with parameter `x`. This works by creating the following sequence:
```
[x - 1, x, x - 2, x + 1, x - 3, x + 2, x - 4, x + 3, ...]
```
This is splicing together the two sequences `]x, -1, -∞]` (left-closed, right-open) and `[x, ∞]` (both open).
For `x = 80`, this looks like:
```
[79, 80, 78, 81, 77, 82, 76, 83, 75, 84, 74, 85, ...]
```
Then, we use `f↦s` to select all elements from `s` satisfying `f`. In this case, we filter out all composite numbers, leaving only the prime ones. For the same `x`, this becomes:
```
[79, 83, 73, 71, 89, 67, 97, 61, 59, 101, 103, 53, ...]
```
Then, we use `(...)@0` to select the first member of this sequence. Since the lower of the two needs to be selected, the sequence which starts with `x - 1` is spliced in first.
Note: Only one of `x` and `x - 1` can be prime, so it is okay that the spliced sequence starts with `x - 1`. Though the sequence could be open on both sides (`[x,-1,-∞]`), this would needlessly include `x` twice in the sequence. So, for sake of "efficiency", I chose the left-closed version (also because I like to show off Tidy).
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~20~~ 15 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Tacit prefix function inspired by [Galen Ivanov's J answer](https://codegolf.stackexchange.com/a/182340/43319).
```
⊢(⊃⍋⍤|⍤-⊇⊢)¯2⍭⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXIo1HXc2Persf9S6pAWLdR13tQEHNQ@uNHvWufdS7@X/ao7YJj3r7HvVN9fQHKj203vhR20QgLzjIGUiGeHgG/09TsDDgSlMwNACRpkBsCaKNjYCkMQA "APL (Dyalog Extended) – Try It Online")
`⍳` **ɩ**ndices one through the argument.
`¯2⍭` nth primes of that
`⊢(`…`)` apply the following tacit function to that, with the original argument as left argument:
`⊢` the primes
`⊇` indexed by:
`⍋` the ascending grade (indices which would sort ascending)
`⍤` of
`|` the magnitude (absolute value)
`⍤` of
`-` the differences
`⊃` pick the first one (i.e. the one with smallest difference)
[Answer]
# [Python 2 (Cython)](http://cython.org/), 96 bytes
```
l=lambda p:min(filter(lambda p:all(p%n for n in range(2,p)),range(2,p*3)),key=lambda x:abs(x-p))
```
[Try it online!](https://tio.run/##PYxBCoAwDAS/kosQRS8VL4KPiVq1GGOoPdjX1yLoaXeGZTWG7RTTTG@mxAPTMc4E2h9OcHEcrMffETNqIbCcHgScgCdZLZpay7L@e9Vm2m38vu6exgvvJo@SeicBGbvWZHoA "Python 2 (Cython) – Try It Online")
[Answer]
## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~104~~ 100 bytes
```
n=>{int r=0,t=0,m=n;while(r!=2){n+=(n<m)?t:-t;t++;r=0;for(int i=1;i<=n;i++)if(n%i==0)r++;}return n;}
```
[Try it online!](https://tio.run/##ZYyxCsJAEER7vyIWwh2XwBkR1M3GzsreDwh3uGBW2GywCPn281JqioHh8Wa6oeoGSreRu4ZYy5w2YmJsp1wLQV9qTo8Mnye9gpEt1nZih4ab3l71Uimoc5BNiG8xy4pwD9TkCTlnKRreEaK3krVZgo7CBcOcYPMQ0nAnDiaak7f2l@z9Ch3/wXllHOrVzwLSFw)
**Explanation:**
```
int f(int n)
{
int r = 0; //stores the amount of factors of "n"
int t = 0; //increment used to cover all the integers surrounding "n"
int m = n; //placeholder to toggle between adding or substracting "t" to "n"
while (r != 2) //while the amount of factors found for "n" is different to 2 ("1" + itself)
{
n += (n < m) ? t : -t; //increment/decrement "n" by "t" (-0, -1, +2, -3, +4, -5,...)
t++;
r = 0;
for (int i = 1; i <= n; i++) //foreach number between "1" and "n" increment "r" if the remainder of its division with "n" is 0 (thus being a factor)
if (n % i == 0) r++;
}
return n;
}
Console.WriteLine(f(80)); //79
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
If[PrimeQ[s=#],s,#&@@Nearest[s~NextPrime~{-1,1},s]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMtOqAoMzc1MLrYVjlWp1hHWc3BwS81sSi1uCS6uM4vtaIELF9XrWuoY1irUxwbq/YfKJJXoqDvkK7vUG1hoGNoYKBjqmNZ@/8/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# APL(NARS), 38 chars, 76 bytes
```
{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}
```
0π is the test for prime, ¯1π the prev prime, 1π is the next prime; test:
```
f←{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}
f¨80 100 5 9 532 1
79 101 5 7 523 2
```
[Answer]
# [J](http://jsoftware.com/), ~~19~~ 15 bytes
```
(0{]/:|@-)p:@i.
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F/DoDpW36rGQVezwMohU@@/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqChQGMZWgAZ5rCGJZwEWMjuLr/AA "J – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/create_explanation.py), 10 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
∞╒g¶áÅ-±├Þ
```
[Try it online.](https://tio.run/##ATEAzv9tYXRoZ29sZv//4oie4pWSZ8K2w6HDhS3CseKUnMOe//84MAoxMDAKNQo5CjUzMgox)
**Explanation:**
```
∞ # Double the (implicit) input-integer
╒ # Create a list in the range [1, 2*n]
g¶ # Filter so only the prime numbers remain
áÅ # Sort this list using the next two character:
-± # The absolute difference with the (implicit) input-integer
├ # Push the first item of the list
# (unfortunately without popping the list itself, so:)
Þ # Discard everything from the stack except for the top
# (which is output implicitly as result)
```
[Answer]
# Java 8, ~~88~~ 87 bytes
```
n->{for(int c=0,s=0,d,N=n;c!=2;s++)for(c=d=1,n+=n<N?s:-s;d<n;)if(n%++d<1)c++;return n;}
```
Port of [*@NaturalNumberGuy*'s (first) C answer](https://codegolf.stackexchange.com/a/182420/52210), **so make sure to upvote him!!**
-1 byte thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##NU9BasMwELznFdtAwUKysVMCTWS1L6gvOYYcVEkuSpx1kOSUYnztA/rEfsSV3eSwAzs77Mwc5VWmR30aVSO9hzdpEfoFgMVgXC2VgWpaZwLqZEIkPDLDIoIPMlgFFSCIEdOXvm7drFEiZz6OZpVArh7EintKyXRWQouCIRVYVq9@m3quS@TE1gk@UqrLgihKuTOhcwjIh5FPTpfuvYlON8NrazWcY9ZkF5zFj/0BJPnPeU9gYQtoPqfc@0P/nLMiz9mabdj6acWKgcxigN2XD@actV3ILvFTaDCxdAm/3z@wpJjFxuRWdxj/AA)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
for(int c=0, // Counter-integer, starting at 0
s=0, // Step-integer, starting at 0 as well
d, // Divisor-integer, uninitialized
N=n; // Copy of the input-integer
c!=2; // Loop as long as the counter is not exactly 2 yet:
s++) // After every iteration: increase the step-integer by 1
for(c=d=1, // (Re)set both the counter and divisor to 1
n+=n<N? // If the input is smaller than the input-copy:
s // Increase the input by the step-integer
: // Else:
-s; // Decrease the input by the step-integer
d<n;) // Inner loop as long as the divisor is smaller than the input
if(n%++d // Increase the divisor by 1 first with `++d`
<1) // And if the input is evenly divisible by the divisor:
c++; // Increase the counter-integer by 1
return n;} // Return the now modified input-integer as result
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 103 bytes
```
n->{int p=0,x=0,z=n,d;for(;p<1;p=p>0?z:0,z=z==n+x?n-++x:z+1)for(p=z/2,d=1;++d<z;)p=z%d<1?0:p;return p;}
```
[Try it online!](https://tio.run/##VU89b8IwEN35FSekSEkd3ISKqo0xqGOHigExVR1cnCCniWPZlwiC@O2uQ6cO7z7f6d6rxSAWtfzxqjWdRahDT3tUDa16fUTVafrAZsdGOAcfQmm4zgBM/92oIzgUGNLQKQlt2MV7tEqfPr9A2JNL7lSAd40HLexlZ0orsLNQAQfwerG5Ko1geJaeA0auU8mqzsbMrHNmuNlk27GYFiPnmpy3ekHIuRhJnkwsw8fHZSp5zgiR65ElYRDJdb7NCsNsib3VYNjNs7uIewhnEA/CTvKKfxoB9heHZUu7HqkJJrCK59Gzg0hGep5OXDIvQlFRYUxzeXPBVRxQnkpLB9H05a6KAytJkr@Ht9mEm/cvmc@zzK/8q189LX3@Cw "Java (JDK) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~79~~ 74 bytes (thanks to Laikoni)
72 bytes as annonymus function (the initial "f=" could be removed in this case).
```
f=(!)(-1);n!x|x>1,all((>0).mod x)[2..x-1]=x|y<-x+n=last(-n+1:[-n-1|n>0])!y
```
[Try it online!](https://tio.run/##hc5NCoMwFATgfU/xhC4STCQvIvYvnqC7LsVFwIrSGEu1NIJ3T0uFrgqZ7XwM0@rxdjXG@0aRiBKO9Ggjt7gCmTaGkELQpB9qcLSUSeI4Vsot84m72Cqjx4lwG@Oh5JbjYgtR0Wj2ve4sKKgHuD@ny/Q4W9jC2A4vIA3sBAOAfE838MsfhuLjUGCAZezbZAGWrywPraWSQSbT0Ld1TVL/Bg "Haskell – Try It Online")
---
### original code:
```
f=(!)(-1);n!x|x>1&&all((>0).mod x)[2..x-1]=x|1>0=(last$(-n+1):[-n-1|n>0])!(x+n)
```
[Try it online!](https://tio.run/##hc7NCoMwEATge59iBZEsGskqYn9InqC3HsVDwBZLYyzV0hx897RU6KmQuc7HML2ebmdjvL9IFiHjhAcbucUpShJtDGNKYD6MHThsijx3nFrpFlJCMqOnOWbcpoT7hltOi1WixYi51KIf9NWChG6E@3M@zY@jhRimfnwBu8BWZABQ73ADv/xhJD6OBAVYlX2bKsDqldWhtbLIoCrK0Ld1rUD/Bg "Haskell – Try It Online")
**Explanation:**
```
f x = (-1)!x
isPrime x = x > 1 && all (\k -> x `mod` k /= 0)[2..x-1]
n!x | isPrime x = x -- return the first prime found
| n>0 = (-n-1)!(x+n) -- x is no prime, continue with x+n where n takes the
| otherwise = (-n+1)!(x+n) -- values -1,2,-3,4 .. in subsequent calls of (!)
```
[Answer]
# [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), 161 bytes
```
f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})
```
A full program to run might look like this - it's worth noting that the bounds of the set of primes used should probably be changed if you actually want to run this, since it will take a long time to run for 1 million:
```
functions
f:nat1+>nat1
f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})
```
### Explanation:
```
f(i)== /* f is a function which takes a nat1 (natural number not including 0)*/
(lambda p:set of nat1 /* define a lambda which takes a set of nat1*/
&let z in set p be st /* which has an element z in the set such that */
forall m in set p /* for every element in the set*/
&abs(m-i) /* the difference between the element m and the input*/
>=abs(z-i) /* is greater than or equal to the difference between the element z and the input */
in z) /* and return z from the lambda */
( /* apply this lambda to... */
{ /* a set defined by comprehension as.. */
x| /* all elements x such that.. */
x in set{1,...,9**7} /* x is between 1 and 9^7 */
&forall y in set{2,...,1003} /* and for all values between 2 and 1003*/
&y<>x=>x mod y<>0 /* y is not x implies x is not divisible by y*/
}
)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
t:YqYk
```
[Try it online!](https://tio.run/##y00syfmfkPm/xCqyMDL7v0vIfwsDLkMDAy5TLksuU2MjLkMA "MATL – Try It Online")
List the first `n` primes and find the one closest to `n`.
[Answer]
# [Perl 5](https://www.perl.org/), 57 bytes
```
$a=0;while((1x$_)=~/^.?$|^(..+?)\1+$/){$_+=(-1)**$a*++$a}
```
[Try it online!](https://tio.run/##K0gtyjH9/18l0dbAujwjMydVQ8OwQiVe07ZOP07PXqUmTkNPT9teM8ZQW0Vfs1olXttWQ9dQU0tLJVFLQyVRW1uz9v9/IwMDAy4gwWUIwsZchpYW5lxmIEFLIDAHkxb/8gtKMvPziv/rFuTkAQA "Perl 5 – Try It Online")
`/^.?$|^(..+?)\1+$/` is tricky regexp to check prime
`(-1)**$a*++$a` generate sequence 0,-1, 2,-3 ...
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 112 bytes
```
g=>Enumerable.Range(2,2<<20).Where(x=>Enumerable.Range(1,x).Count(y=>x%y<1)<3).OrderBy(x=>Math.Abs(x-g)).First()
```
[Try it online!](https://tio.run/##bcxBC4JAFATgu7@iS/Ae6OIqQeEqVOSpCLp4VnvqQm2wu8L66zc7lh3m8jEzrYlaI305qlZIZcM5xarLfZ8XJzU@SdfNg9itVj1BEiZC8BhZNZAmcH8qPHTIjq9RWZjywq0nwVGkyK76TvowfTaX2g5s3xhwUY/ISqmNBfRZEFRaWjpLRdDBNkbMvoTHC9r8wm7RSJPFzwz@DQ "C# (Visual C# Interactive Compiler) – Try It Online")
Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases.
] |
[Question]
[
Your task is to create a program that will display the following text, wait for the user to press a key (it is okay to ignore keys like `ctrl`, `alt`, `caps lock`, etc., as long as keys like `letters`, `numbers`, `symbols`, and `enter` are not ignored), and then terminate the program:
```
Press any key to continue...
```
Trailing newlines are allowed. The program must exit immediately after a key is pressed. Also, the program must be fairly portable (i.e no OS-specific headers or modules, runs outside of an IDE, etc.).
---
The prompt must be exactly as shown above, unless a trailing newline cannot be avoided.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. This is also my first code-golf question, so I apologize if I do not know the rules on PPCG.
[Answer]
## Batch, 46 bytes
```
@echo Press any key to continue...
@pause>nul
```
Because `pause`'s output contains a space before each `.`.
[Answer]
# HTML + JavaScript (ES6), 36 + 25 = 61 bytes
You can't really exit a JavaScript program, so clearing the webpage is the best I can think of.
```
onkeyup=_=>a.innerHTML=''
```
```
<a id=a>Press any key to continue...
```
---
# HTML + JavaScript (ES6), 33 + 28 = 61 bytes
Alternate solution [suggested by @LarsW](https://codegolf.stackexchange.com/questions/107709/press-any-key-to-continue/107750?noredirect=1#comment262098_107750) that redirects to `about:blank`.
```
onkeyup=_=>location='about:blank'
```
```
Press any key to continue...
```
---
# HTML/JavaScript, 60 bytes
Another awesome solution [by @Ismael Miguel](https://codegolf.stackexchange.com/questions/107709/press-any-key-to-continue/107750?noredirect=1#comment262407_107750) that doesn't use standalone JS. 1 byte saved!
```
<html onkeyup=this.innerHTML=''>Press any key to continue...
```
---
# HTML + JavaScript (ES6), 26 + 28 = 54 bytes
Yet another solution [by @George Reith](https://codegolf.stackexchange.com/questions/107709/press-any-key-to-continue/107750?noredirect=1#comment262736_107750) making use of document writes.
```
onkeyup=_=>document.open()
```
```
Press any key to continue...
```
# HTML + JavaScript (ES7), 23 + 28 = 51 bytes
Same program using the [proposed ES7 bind operator](https://github.com/tc39/proposal-bind-operator):
```
onkeyup=::document.open
```
```
Press any key to continue...
```
---
As most of these solutions are not my own, do a courtesy and vote them up in the comments!
[Answer]
# MATL, 35 bytes
```
'Press any key to continue...'D0$Y.
```
**Explanation**
```
'Press any key to continue...' % String literal
D % Display the string (has trailing newline)
0$Y. % Pause until the user presses any key
```
[Answer]
# TI-Basic, 55 bytes
Basically, it loops until a key is pressed. Too bad lowercase letters are two bytes each in TI-Basic...
```
Disp "Press any","key to continuesin(
Repeat getKey
End
```
P.S. See the comment by @GoldenRatio for the explanation as to how this works. It's genius!
[Answer]
# Bash, ~~46~~ ~~43~~ 42 bytes
*Saved 1 byte thanks to @DigitalTrauma*
```
read -rn1 -p"Press any key to continue..."
```
Uses the `read` built-in. `-r` makes sure it doesn't allow the user to input escapes. `-n 1` allows just one character. `-p` is the prompt
[Answer]
# [Haskell](https://www.haskell.org/), ~~51~~ 50 bytes (Thanks @villou24)
```
main=putStr"Press any key to continue...">>getChar
```
[Try it online!](https://tio.run/nexus/haskell#@5@bmJlnW1BaElxSpBRQlFpcrJCYV6mQnVqpUJKvkJyfV5KZV5qqp6enZGeXnlrinJFY9P8/AA "Haskell – TIO Nexus")
[Answer]
## SmallBasic, ~~18~~ 17 bytes
* Version 2.0
17 bytes
```
TextWindow.Show()
```
* Version 1.0
18 bytes
```
TextWindow.Pause()
```
[Answer]
# Octave / MATLAB, 42 bytes
```
disp('Press any key to continue...');pause
```
[Answer]
# QBasic ([QB64](http://qb64.net)), 37 (42?) bytes
Unfortunately, QBasic's built-in end-of-program prompt doesn't have the ellipsis, so we'll have to print it ourselves:
```
?"Press any key to continue..."
SLEEP
```
(`SLEEP` without an argument waits until a keypress.)
This code does what the question literally asks for, but it doesn't seem like it fits the spirit of the question because, of course, QBasic then displays "Press any key to continue" and waits for a keypress before returning to the IDE. Here's one that goes straight to the IDE, for +5 bytes:
```
?"Press any key to continue..."
SLEEP
STOP
```
`STOP` is a debugging statement. In regular QBasic, it sets a breakpoint: execution halts and we return to the IDE, but execution can be resumed again with F5. It's unclear whether that would count as the program "exiting." However, I'm using the QB64 emulator, which can't do breakpoints. Upon encountering `STOP`, it simply halts--returning straight to the IDE without the redundant "Press any key" message.
[Answer]
# Processing, ~~89~~ 81 bytes
```
void setup(){print("Press any key to continue...");}void draw(){if(key>0)exit();}
```
### Explanation
```
void setup(){print("Press any key to continue...");}
```
This is required since I am using more than one function in my program. Anything inside `setup()` gets called, in this case the string `"Press any key to continue..."`.
```
if(key>0)exit();
```
Checks if `key` (`key` will always contain the int value of the last key pressed) is more than `0` (ie not a null byte). If the condition is satisfied, then the program exits.
```
void draw(){}
```
`draw()` ensures that that the program will always keep looking for a key instead of stopping once the program starts.
(That feel when a builtin in a Java-like language is still verbose...)
[Answer]
# Pascal, ~~75~~ 65 bytes
This was tested with the Free Pascal Compiler, version 3.0.0.
It may work with TurboPascal 7 or newer.
```
uses Crt;begin write('Press any key to continue...');readkey;end.
```
Sadly, I can't replace `readkey` with `readln` since the challenge requires that **any** key be accepted.
---
I've tested this code on <http://rextester.com/l/pascal_online_compiler>, with and without supplying an input.
As expected, the program is terminated after 10s, since it sits waiting for a keypress that never happens.
---
Thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for saving me 10 bytes by proving me wrong, and showing that I don't need the `program _;`.
[Answer]
# Scratch, 81 bytes
![image](https://i.stack.imgur.com/A4PQE.png)
```
when gf clicked
say [Press any key to continue...
wait until <key [any v] pressed
```
([Scratchblocks link](http://scratchblocks.github.io/#when%20gf%20clicked%0Asay%20%5BPress%20any%20key%20to%20continue...%0Await%20until%20%3Ckey%20%5Bany%20v%5D%20pressed))
If you wanted it to stop the *entire* program when you pressed a key (including other threads) you'd have to add a `stop all`. If you want to get rid of the say dialog you need an empty `say` block (`stop all` works as well).
Convenient that Scratch has a builtin for this!
[Answer]
## Bash ~~48~~ ~~44~~ 42 bytes
```
read -rn1 -p"Press any key to continue..."
```
@mame98 Thanks for saving 4 bytes.
@RaisingAgent Thanks for saving 2 bytes.
[Answer]
# Python 2, 110 bytes
```
import curses as c
s=c.initscr()
c.cbreak()
s.addstr(0,0,'Press any key to continue...')
while not s.getch():1
```
[Answer]
## R, 56 bytes
```
cat('Press any key to continue...');keypress::keypress()
```
This works in Linux and OSX terminals.
[Answer]
# Ruby (2.3) (+ Batch), ~~52~~ ~~55~~ ~~54~~ ~~53~~ 46 bytes
Now 46 bytes thanks to Alexis Andersen.
Note: Tested on Windows, might not work if there is no `pause` command.
```
puts"Press any key to continue...";`pause>nul`
```
# Explanation
`Puts` the required text:
```
puts"Press any key to continue..."
```
End the line:
```
;
```
Run the Batch `pause` command and pipe output to `nul`:
```
`pause>nul`
```
[Answer]
# Java, 127 bytes
```
class P{public static void main(String[]a)throws Exception{System.out.print("Press any key to continue...");System.in.read();}}
```
Note: [the console must be set to raw mode](https://stackoverflow.com/q/1066318/) in order for this to work.
[Answer]
# SmileBASIC, 52 bytes
```
?"Press any key to continue...
WHILE""==INKEY$()WEND
```
[Answer]
# Mathematica, 62 bytes
```
EventHandler["Press any key to continue...","KeyDown":>Exit[]]
```
**Explanation**
```
EventHandler["Press any key to continue...","KeyDown":>Exit[]]
EventHandler[ ] (* Create a new EventHandler *)
"Press any key to continue..." (* Print the dialog text *)
"KeyDown":>Exit[] (* When a key is pressed down, exit *)
```
[Answer]
# SmileBASIC, 55 bytes
```
?"Press any key to continue..."@L IF INKEY$()!=""GOTO@L
```
Explained:
```
?"Press any key to continue..." '? means PRINT
@L 'start of loop
IF INKEY$()!="" GOTO @L 'if no key pressed goto @L
```
[Answer]
# Python 2/3 POSIX, 85 bytes
```
import sys,tty
print('Press any key to continue...')
tty.setraw(1)
sys.stdin.read(1)
```
[Answer]
# **Python 3, 65 bytes**
Requires the Windows version of Python.
```
from msvcrt import*
print("Press any key to continue...")
getch()
```
msvcrt.getch() doesn't wait for the enter key to be pressed like input(), it returns the first key pressed.
Python Docs for msvcrt.getch():
<https://docs.python.org/3/library/msvcrt.html#msvcrt.getch>
Thanks to @Fliptack for saving some bytes
[Answer]
# Node.js, ~~102~~ ~~101~~ 99 bytes
```
with(process)stdout.write('Press any key to continue...'),s=stdin,s.setRawMode(1),s.on('data',exit)
```
[Answer]
# Sinclair ZX81/Timex TS1000 BASIC: Method 1 approximately 41 bytes
```
1 PRINT "PRESS ANY KEY TO CONTINUE..."
2 GOTO (INKEY$<>"")+VAL "2"
```
## Method 2 approximately 38 BYTES
```
1 PRINT "PRESS ANY KEY TO CONTINUE..."
2 PAUSE VAL "4E4"
```
I prefer method 1 as on the ZX81, there is a screen flicker when `PAUSE` is called, and if you want long enough (providing the ZX81 doesn't overheat or crash) the pause will eventually come to an end, whereas method 1 is stuck in an infinite loop until a key is pressed, and no screen flicker.
I'll work out the correct number of bytes used later when I have the right bit of BASIC that will tell me. By the way, using VAL "x" instead of the number saves valuable RAM on a ZX81 (I think that this is the same for the ZX Spectrum as well).
[Answer]
## Perl 5, 79 bytes
```
system "stty cbreak";$|=1;print "Press any key to continue...";read(STDIN,$a,1)
```
used as:
```
perl -e 'system "stty cbreak";$|=1;print "Press any key to continue...";read(STDIN,$a,1)'
```
No prizes of course. I'm sure some perl person will have a better way.
(89 bytes if the interpreter invocation as well needs to be included in the count)
[Answer]
### PHP, 73 bytes
```
echo"Press any key to continue...";$h=fopen("php://stdin","r");fgets($h);
```
Run it in the PHP interactive shell (`php -a`)
[Answer]
# C#, 101 bytes
```
using C=System.Console;class P{static void Main(){C.Write("Press any key to continue...");C.Read();}}
```
Tested on Linux, should run on any system having the .NET libraries and the Common Language Runtime.
Ungolfed program:
```
using C = System.Console; // creating a shorter alias for the System.Console class
class P
{
static void Main()
{
C.Write("Press any key to continue..."); // prints the message
C.Read(); // waits for key press
}
}
```
CTRL, ALT, SHIFT are ignored. The pressed key will be echoed on screen if printable.
Echo can be disabled by replacing *C.Read()* with *C.ReadKey(0<1)* at the cost of 6 more bytes.
[Answer]
# [8th](http://8th-dev.com/), 47 bytes
```
"Press any key to continue..." . cr con:key bye
```
This program ignores keys like ctrl, alt, caps lock. Quits with keys like letters, numbers, symbols, and enter.
**Explanation**
```
"Press any key to continue..." . cr \ Print message
con:key \ Wait for key input from console
bye \ Quit program
```
[Answer]
## C#, 29 bytes
```
class P{static void Main(){}}
```
Not sure if this is considered valid because it prints:
>
> Press any key to continue . . .
>
>
>
But there is a [Batch](https://codegolf.stackexchange.com/a/107804/38550) answer that prints this as well.
[Answer]
# Forth (gforth), 39 bytes
```
." Press any key to continue..."key bye
```
(Yes, there is already an 8th solution but this is shorter)
] |
[Question]
[
An 'Even string' is any string where the [parity](https://en.wikipedia.org/wiki/Parity_(mathematics)) of the ASCII values of the characters is always alternating. For example, the string `EvenSt-ring$!` is an even-string because the ASCII values of the characters are:
```
69 118 101 110 83 116 45 114 105 110 103 36 33
```
And the parities of these numbers are:
```
Odd Even Odd Even Odd Even Odd Even Odd Even Odd Even Odd
```
Which is alternating the whole way. However, a string like `Hello world!` is *not* an even string because the ASCII values are:
```
72 101 108 108 111 32 87 111 114 108 100 33
```
And the parities are:
```
Even Odd Even Even Odd Even Odd Odd Even Even Even Odd
```
Which is clearly not always alternating.
# The challenge
You must write either a full program or a function that accepts a string for input and outputs a [truthy](http://meta.codegolf.stackexchange.com/q/2190/31716) value if the string is even, and a falsy value otherwise. You can take your input and output in any reasonable format, and you can assume that the input will only have [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (the 32-127 range). You do *not* have to handle empty input.
# Examples
Here are some examples of even strings:
```
#define
EvenSt-ring$!
long
abcdABCD
3.141
~
0123456789
C ode - g ol!f
HatchingLobstersVexinglyPopulateJuvenileFoxglove
```
And all of these examples are not even strings:
```
Hello World
PPCG
3.1415
babbage
Code-golf
Standard loopholes apply
Shortest answer in bytes wins
Happy golfing!
```
You may also use [this ungolfed solution](http://julia.tryitonline.net/#code=c3RyID0gcmVhZGxpbmUoU1RESU4pCmV2ZW4gPSB0cnVlCnBhcml0eSA9IEludChzdHJbMV0pICUgMgpmb3IgYyBpbiBzdHJbMjplbmRdCiAgbmV3UGFyaXR5ID0gSW50KGMpICUgMgogIGlmIG5ld1Bhcml0eSA9PSBwYXJpdHkKICAgIGV2ZW4gPSBmYWxzZQogIGVuZAogIHBhcml0eSA9IG5ld1Bhcml0eQplbmQKcHJpbnQoZXZlbik&input=MDEyMzQ1Njc4OQ) to test any strings if you're curious about a certain test-case.
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~4~~ 3 bytes
Thanks to *Emigna* for saving a byte and thanks to *Luis Mendo* for fixing some bugs. Code:
```
doA
```
Explanation:
```
d # Difference between the characters
o # Mod 2
A # Matlab style all
```
[Try it online!](http://matl.tryitonline.net/#code=ZG9B&input=J0hhdGNoaW5nTG9ic3RlcnNWZXhpbmdseVBvcHVsYXRlSnV2ZW5pbGVGb3hnbG92ZSc)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes
Saved 1 byte thanks to *Adnan*.
```
Ç¥ÉP
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w4fCpcOJUA&input=QyBvZGUgLSBnIG9sIWY)
**Explanation**
```
Ç # convert to ascii values
¥ # compute delta's
É # mod by 2
P # product
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~7~~ ~~5~~ 4 bytes
```
OIḂẠ
```
Saved 2 bytes using the deltas idea from @[Steven H.](https://codegolf.stackexchange.com/a/96063/6710)
Saved 1 byte thanks to @[Lynn](https://codegolf.stackexchange.com/users/3852/lynn).
[Try it online!](http://jelly.tryitonline.net/#code=T0nhuILhuqA&input=&args=RXZlblN0LXJpbmckIQ) or [Verify all test cases.](http://jelly.tryitonline.net/#code=T0nhuILhuqAKw4figqw&input=&args=JyNkZWZpbmUnLCdFdmVuU3QtcmluZyQhJywnbG9uZycsJ2FiY2RBQkNEJywnMy4xNDEnLCd-JywnMDEyMzQ1Njc4OScsJ0Mgb2RlIC0gZyBvbCFmJywnSGVsbG8gV29ybGQnLCdQUENHJywnMy4xNDE1JywnYmFiYmFnZScsJ0NvZGUtZ29sZicsJ1N0YW5kYXJkIGxvb3Bob2xlcyBhcHBseScsJ1Nob3J0ZXN0IGFuc3dlciBpbiBieXRlcyB3aW5zJywnSGFwcHkgZ29sZmluZyEn)
## Explanation
```
OIḂẠ Input: string S
O Ordinal
I Increments
Ḃ Mod 2
Ạ All, 0 if it contains a falsey value, else 1
```
[Answer]
# Python 2, 54 Bytes
```
lambda s:all((ord(x)-ord(y))%2for x,y in zip(s,s[1:]))
```
[Answer]
# Mathematica, ~~50~~ 44 bytes
*The current version is basically all Martin Ender's virtuosity.*
```
Differences@ToCharacterCode@#~Mod~2~FreeQ~0&
```
Returns `True` or `False`. Nothing too clever: takes the mod-2 sum of each pair of consecutive ASCII codes, and checks that 0 is never obtained.
Old version:
```
Union@Mod[Most[a=ToCharacterCode@#]+Rest@a,2]=={1}&
```
[Answer]
# JavaScript (ES6), ~~60~~ ~~50~~ 46 bytes
```
s=>[...s].every(c=>p-(p=c.charCodeAt()%2),p=2)
```
I tried recursion, but at 51 bytes, it doesn't seem to be quite worth it:
```
f=([c,...s],p=2)=>c?p-(p=c.charCodeAt()%2)&f(s,p):1
```
### Test snippet
```
f=s=>[...s].every(c=>p-(p=c.charCodeAt()%2),p=2)
```
```
<input id=I value="Evenst-ring"><button onclick="console.log(f(I.value))">Run</button>
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~138~~ ~~114~~ ~~112~~ 84 + 3 = 87 bytes
Thanks to [@Riley](https://codegolf.stackexchange.com/users/57100/riley) for help golfing.
This program treats empty input as a noneven string.
```
{({}(())){({}[()]<(()[{}])>)}{}(({})<>[[]{}]()){{}(<>)}{}({}<>)<>}<>(([])[()]){<>}{}
```
[Try it online!](http://brain-flak.tryitonline.net/#code=eyh7fSgoKSkpeyh7fVsoKV08KCgpW3t9XSk-KX17fSgoe30pPD5bW117fV0oKSl7e30oPD4pfXt9KHt9PD4pPD59PD4oKFtdKVsoKV0pezw-fXt9&input=RXZlblN0LXJpbmcgQyBvZGUgLSBnIG9sIWY&args=LWE)
## Explanation (outdated)
Shifts the input from the left stack to the right while modding by 2. Finds the difference between each adjacent character until all have been checked or one of the differences is equal to zero (which would only occur in a noneven string). If the loop terminated due to a noneven string then switch back to the left stack and pop the value remaining on it. Otherwise, stay on the right stack and pop the zero above the 1 remaining on the stack.
[Answer]
## R, 41 35 bytes
EDIT:
Saved a few bytes thanks to @JDL by using `diff` instead of `rle`.
```
all(diff(utf8ToInt(readline())%%2))
```
---
```
all(rle(utf8ToInt(readline())%%2)[[1]]<2)
```
**Explanation**
1. `readline()` read input.
2. `utf8ToInt()%%2` convert to ascii values and mod 2 (store as R-vector)
3. `all(rle()==1)` run length encoding of to find runs. All runs should be equal to one or smaller than 2 since no runs cant be negative or 0 (saves one byte instead of `==`).
[Answer]
# Pyth ([fork](https://github.com/Steven-Hewitt/pyth)), 9 bytes
```
.A%R2.+CM
```
No Try It Online link because the fork does not have its own version in the online interpreters.
Explanation:
```
CM Map characters to their ASCII codes.
.+ Get deltas (differences between consecutive character codes)
%R2 Take the modulo of each base 2
.A all are truthy (all deltas are odd)
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 17 bytes
```
@c:{:2%}a@b:{l1}a
```
[Try it online!](http://brachylog.tryitonline.net/#code=QGM6ezoyJX1hQGI6e2wxfWE&input=IkV2ZW5TdC1yaW5nJCEi)
### Explanation
```
@c Input to a list of char codes
:{:2%}a Apply X mod 2 for each X in the list of char codes
@b Split the list into a list of lists where each sublist elements are the
same, e.g. turn [1,0,1,1,0,0] into [[1],[0],[1,1],[0,0]]
:{l1}a The length of each sublist must be 1
```
[Answer]
# Java 8, ~~77~~ ~~76~~ ~~72~~ 57 bytes
```
a->{int i=2,b=1;for(int c:a)b=i==(i=c%2)?0:b;return b>0;}
```
-4 bytes thanks to *@Geobits*.
**Explanation:**
[Try it online.](https://tio.run/##nZTfb9MwEMff@1dcC0iJWLK22/jRKEMjY1SITZWK4AHxcHacxMPzRbbTLZrKv16cbm8DJPxi6ez7fO9O95WvcYMJtUJflz93XKG1cIlS348ApHbCVMgFXA0hACNSAjXwiDdovv8AjDP/sB35wzp0ksMVaMhhh8npvcdB5vMDls@yikw0xHyBMctlnkcy5y/m8bvpgmVGuM5oYKfTbLvLBrG2Y8qLPWpuSJZw45uK1s5IXe8LP3R0eAhfTOeafrEP17114ialzqWtz3SRTnk0eVaKSmoxSR0Vvu8zY7CP4hhewuRgsp/gb@SHjdBrlwxFn48DeEW6DsCQ8fLsfXEegB6ls@NZAPcrgJnO5kfHJ69ev3kbABdApYAEaiA1rv5LQOkHiSU63vjVfCbmE4z9Ku58pPoVtZ1CJz51fn1SiQu6qxVtnhjgUd576AKVFf/00FIoRfCNjCoDhl2tio@hyzwJABkyhnWI4wu/laQmVQWwa4e6RFOCImob/1VYwLZVfYhUQ8YJ6wC1vRXGf0XAen8Bt1LbAL2lb6SHYS7vkPEfjbAdbXe/AQ)
```
a->{ // Method with character-array parameter and boolean return-type
int i=2, // Integer `i`, starting at any integer not 0 or 1
b=1; // Flag-integer `b`, starting at 1
for(int c:a) // Loop over the input-array
b=i==(i=c%2)? // If two adjacent characters were both odd or even:
0 // Set the flag-integer `b` to 0
: // Else:
b; // The flag-integer `b` remains the same
return b>0;} // Return if the flag-integer `b` is still 1
```
[Answer]
# Brain-Flak 155 151 141 121
Includes +3 for -a
Saved 30 bytes thanks to [1000000000](https://codegolf.stackexchange.com/a/96107/57100)
```
{({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<>{({}[({})]<(())>){((<{}{}>))}{}({}[()]<>)<>}<>{{}}([]<(())>){((<{}{}>))}{}
```
Output:
**truthy**: 1
**falsy**: 0 on top of the stack
[Try it online! (truthy)](http://brain-flak.tryitonline.net/#code=eyh7fSgoKSkpeyh7fVsoKV08KCgpW3t9XSk-KX17fSh7fSgpPD4pPD59PD57KHt9Wyh7fSldPCgoKSk-KXsoKDx7fXt9PikpfXt9KHt9WygpXTw-KTw-fTw-e3t9fShbXTwoKCkpPil7KCg8e317fT4pKX17fQ&input=QyBvZGUgLSBnIG9sIWY&args=LWE)
[Try it online! (falsy)](http://brain-flak.tryitonline.net/#code=eyh7fSgoKSkpeyh7fVsoKV08KCgpW3t9XSk-KX17fSh7fSgpPD4pPD59PD57KHt9Wyh7fSldPCgoKSk-KXsoKDx7fXt9PikpfXt9KHt9WygpXTw-KTw-fTw-e3t9fShbXTwoKCkpPil7KCg8e317fT4pKX17fQ&input=Q29kZS1nb2xm&args=LWE)
---
Better explanation coming later (if I can remember how it works after a few hours...)
```
#compute ((mod 2) + 1) and put on other stack
{({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<>
#compare top two (remove top 1) push on other stack (-1 for different 0 for same)
{({}[({})]<(())>){((<{}{}>))}{}({}[()]<>)<>}<>
#remove all of the top -1s
{{}}
#take the logical not of the stack height
([]<(())>){((<{}{}>))}{}
```
[Answer]
# [Starry](https://esolangs.org/wiki/Starry), 85 bytes
```
, + * ` , + + * ' + ' ` + * + + * ' + `.
```
[Try it online!](http://starry.tryitonline.net/#code=ICwgICAgICAgKyAgICAqICAgYCAsICsgICAgICAgICAgICAgICArICogJyArICAnIGAgICAgICAgKyAgICAqICsgICArICogICAnICAgICArICBgLg&input=RXZlblN0LXJpbmcgQyBvZGUgLSBnIG9sIWYK)
Note that since a Starry program has no way of telling when an input of arbitrary length ends, this program uses a trailing newline in the input to mark the end of the string. If you get a cryptic error message about and undefined method `ord` for `nil:NilClass` then the input is missing a trailing newline.
## Explanation
The basic strategy that the program employs is it reads the characters one by one from input and if they are not a newline (character 10) it mods they ASCII value of the character by 2 and finds the difference between it and the previously read character. If the difference is zero the program terminates and prints `0` (falsey). Otherwise the program loops back and does the process over again. If the program reads a newline it terminates and prints `10` (truthy).
### Annotated Program
```
, Push the first character
+ Push 2
* Replace the first character and 2 with the first character mod 2
` Label 3 <--------------------------------------------------------\
, Push the next the character |
+ Push a duplicate of it |
+ Push 10 |
* Replace the 10 and the duplicate with their difference |
' Pop and if not zero (the read char is not 10) goto label 1 >-\ |
+ Push a duplicate of the character which must be newline (10) | |
' Pop and goto label 2 >---------------------------------------+-\ |
` Label 1 <----------------------------------------------------/ | |
+ Push 2 | |
* Replace the character and 2 with the character mod 2 | |
+ Duplicate it ^ | |
+ Roll the top three items on the stack. The top goes to | |
the bottom. The top three items are now | |
(from top to bottom) the current character, the previous | |
character, the current character (all modded by 2). | |
* Replace the current character and previous character | |
with their difference | |
' Pop if nonzero goto label 3 >----------------------------------+-/
+ Push zero |
` Label 2 <------------------------------------------------------/
. Print out the number on top of the stack
0 if we came by not following the goto label 3
10 if we came by going to label 2
```
[Answer]
## Perl, 24 + 1 (`-p`) = 25 bytes
*-4 bytes thanks to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) !*
```
s/./$&&v1/eg;$_=!/(.)\1/
```
Needs `-p` flag. Outputs 1 is the string is even, nothing otherwise. For instance :
```
perl -pe 's/./$&&v1/eg;$_=!/(.)\1/' <<< "#define
Hello World"
```
*Explanations* : replaces each character by its value mod 2 (so the string contains only 0s and 1s after that). Then search for two following 1 or 0 : if it finds some, then the string isn't even, otherwise it is.
[Answer]
# J, 15 bytes
```
0=1#.2=/\2|3&u:
```
## Usage
```
f =: 0=1#.2=/\2|3&u:
f 'C ode - g ol!f'
1
f 'Code-golf'
0
```
## Explanation
```
0=1#.2=/\2|3&u: Input: string S
3&u: Get ordinals of each char
2| Take each modulo 2
2 \ For each pair of values
=/ Test if they are equal, 1 if true else 0
1#. Treat the list of integers as base 1 digits and convert to decimal
This is equivalent to taking the sum
0= Is it equal to 0, 1 if true else 0, and return
```
[Answer]
# Vim, 38 bytes
`qqs<C-R>=char2nr(@")%2<CR><Esc>l@qq@q:g/00\|11/d<CR>`
Assumes input string in buffer, and empty `"q`. Outputs binary nonsense if true, nothing if false.
* `s<C-R>=char2nr(@")%2<CR>`: Replaces a character with 1 if odd, 0 if even. The macro this is in just does this to every character in the line (no matter how long it is).
* `:g/00\|11/d<CR>`: Deletes the line if 2 consecutive "bits" have the same value. Faster than a back-reference.
Normally, in vimgolf, when you use an expression function inside a macro, you're supposed to do the macro itself on the expression register and use some trickery to tab-complete. That's more difficult this time. I may find a way to shorten that later.
[Answer]
## [Retina](http://github.com/mbuettner/retina), 39 bytes
Byte count assumes ISO 8859-1 encoding.
```
S_`
%{2`
$`
}T01`p`_p
..
Mm`.¶.|^¶$
^0
```
Outputs `1` for truthy and `0` for falsy.
[Try it online!](http://retina.tryitonline.net/#code=JShHYApTX2AKJXsyYAokYAp9VDAxYHBgX3AKLi4KCk1tYC7Cti58XsK2JApeMA&input=I2RlZmluZQpFdmVuU3QtcmluZyQhCmxvbmcKYWJjZEFCQ0QKMy4xNDEKfgowMTIzNDU2Nzg5CkMgb2RlIC0gZyBvbCFmCkhhdGNoaW5nTG9ic3RlcnNWZXhpbmdseVBvcHVsYXRlSnV2ZW5pbGVGb3hnbG92ZQpIZWxsbyBXb3JsZApQUENHCjMuMTQxNQpiYWJiYWdlCkNvZGUtZ29sZgpTdGFuZGFyZCBsb29waG9sZXMgYXBwbHkKU2hvcnRlc3QgYW5zd2VyIGluIGJ5dGVzIHdpbnMKSGFwcHkgZ29sZmluZyE) (The first line enables a linefeed-separated test suite.)
### Explanation
Inspired by a answer of mbomb007's [I recently developed a reasonably short `ord()` implementation](http://chat.stackexchange.com/transcript/message/32786271#32786271) in Retina. This is largely based on that, although I was able to make a few simplifications since I don't need a decimal result in since I only need to support printable ASCII (and I only care about the parity of the result, so ending up with an arbitrary offset is fine, too).
**Stage 1: Split**
```
S_`
```
This simply splits the input into its individual characters by splitting it around the empty match and dropping the empty results at the beginning and end with `_`.
**Stage 2: Replace**
```
%{2`
$`
```
The `%{` tells Retina a) that this stage and the next should be run in a loop until the string stops changing through a full iteration, and that these two stages should be applied to each line (i.e each character) of the input separately.
The stage itself is the standard technique for duplicating the first character of the input. We match the empty string (but only look at the first two matches) and insert the prefix of that match. The prefix of the first match (at the beginning of the string) is empty, so this doesn't do anything, and the prefix of the second match is the first character, which is therefore duplicated.
**Stage 3: Transliterate**
```
}T01`p`_o
```
`}` indicates the end of the loop. The stage itself is a transliteration. `01` indicates that it should only be applied to the first character of the string. `p` is shorthand for all printable ASCII characters and `_` means "delete". So if we expand this, the transliteration does the following transformation:
```
from: !"#$%...
to: _ !"#$...
```
So spaces are deleted and all other characters are decremented. That means, these two stages together will create a character range from space to the given character (because they'll repeatedly duplicate and decrement the first character until it becomes a space at which point the duplication and deletion cancel).
The length of this range can be used to determine the parity of the character.
**Stage 4: Replace**
```
..
```
We simply drop all pairs of characters. This clears even-length lines and reduces odd-length lines to a single character (the input character, in fact, but that doesn't really matter).
**Stage 5: Match**
```
Mm`.¶.|^¶$
```
It's easier to find inputs which *aren't* even, so we count the number of matches of either two successive empty lines or two successive non-empty lines. We should get `0` for even inputs and something non-zero otherwise.
**Stage 6: Match**
```
^0
```
All that's left is to invert the result, which we do by counting the number of matches of this regex, which checks that the input starts with a `0`. This is only possible if the result of the first stage was `0`.
[Answer]
# Clojure, 59 bytes
```
#(every?(fn[p](odd?(apply + p)))(partition 2 1(map int %)))
```
Generates all sequential pairs from string `n` and checks if every pair sum is odd. If a sequence of ints is considered a reasonable format then it's 50 bytes.
```
#(every?(fn[p](odd?(apply + p)))(partition 2 1 %))
```
See it online : <https://ideone.com/USeSnk>
[Answer]
## Julia, ~~55~~ 53 Bytes
```
f(s)=!ismatch(r"00|11",join(map(x->Int(x)%2,[s...])))
```
**Explained**
Map chars to 0|1 and check if the resulting string contains "00" or "11", which makes the string not alternating.
[Answer]
## Python, 52 bytes
```
f=lambda s:s==s[0]or(ord(s[0])-ord(s[1]))%2*f(s[1:])
```
A recursive function. Produces 1 (or True) for even strings, 0 for odd ones. Multiplies the parity of the difference of the first two characters by the recursive value on the remainder. A single-character string gives True, as checked by it equaling its first character. This assumes the input is non-empty; else, one more byte is needed for `s==s[:1]` or `len(s)<2`.
---
**Python 2, 52 bytes**
```
p=r=2
for c in input():x=ord(c)%2;r*=p-x;p=x
print r
```
Alternatively, an iterative solution. Iterates over the input characters, storing the current and previous character values mod 2. Multiplies the running product by the difference, which because 0 (Falsey) only when two consecutive parities are equal.
The "previous" value is initialized to 2 (or any value not 0 or 1) so that the first character never matches parity with the fictional previous character.
---
**Python, 42 bytes, outputs via exit code**
```
p=2
for c in input():x=ord(c)%2;p=x/(p!=x)
```
Outputs via exit code. Terminates with a ZeroDivisionError when two consecutive characters have the same parities, otherwise terminates cleanly.
[Answer]
## Haskell, ~~42~~ 40 bytes
```
all odd.(zipWith(-)=<<tail).map fromEnum
```
Usage example: `all odd.(zipWith(-)=<<tail).map fromEnum $ "long"` -> `True`.
How it works:
```
map fromEnum -- turn into a list of ascii values
(zipWith(/=)=<<tail) -- build a list of neighbor differences
all odd -- check if all differences are odd
```
Edit: @xnor saved two bytes. Thanks!
[Answer]
# Mathematica, ~~41~~ 40 Bytes
```
And@@OddQ@Differences@ToCharacterCode@#&
```
-1 character, thanks to Martin Ender
[Answer]
## C, 52 bytes
```
int f(char*s){return s[1]?(s[0]-s[1])%2?f(s+1):0:1;}
```
Compares the parity of first 2 characters, recursively moving through the string until it finds 2 characters with the same parity or the string with the length of 1 (`s[1] == 0`).
[Code with some of the test cases](https://ideone.com/eZpLvL)
[Answer]
# Ruby, ~~41~~ 30 (+1) bytes
```
p gsub(/./){$&.ord%2}!~/(.)\1/
```
Call this from the command line with the `-n` flag, like so:
```
ruby -ne 'p gsub(/./){$&.ord%2}!~/(.)\1/'
```
Replaces each character with the parity of its ASCII value and then compares to a regex. If even, the `=~` comparison will return the index of the first match (i.e. 0), which is a truthy value in Ruby; if not even, the comparison will return `nil`.
Thanks to Jordan for the improvements!
[Answer]
## Pyke, 8 bytes
```
m.o$2m%B
```
[Try it here!](http://pyke.catbus.co.uk/?code=m.o%242m%25B&input=Hello+World)
```
m.o - map(ord, input)
$ - delta(^)
2m% - map(> % 2, ^)
B - product(^)
```
[Answer]
# C#, 69 bytes
```
s=>{int i=1,e=0;for(;i<s.Length;)e+=(s[i-1]+s[i++]+1)%2;return e<1;};
```
Full program with test cases:
```
using System;
namespace EvenStrings
{
class Program
{
static void Main(string[] args)
{
Func<string,bool>f= s=>{int i=1,e=0;for(;i<s.Length;)e+=(s[i-1]+s[i++]+1)%2;return e<1;};
Console.WriteLine(f("lno")); //false
//true:
Console.WriteLine(f("#define"));
Console.WriteLine(f("EvenSt-ring$!"));
Console.WriteLine(f("long"));
Console.WriteLine(f("abcdABCD"));
Console.WriteLine(f("3.141"));
Console.WriteLine(f("~"));
Console.WriteLine(f("0123456789"));
Console.WriteLine(f("C ode - g ol!f"));
Console.WriteLine(f("HatchingLobstersVexinglyPopulateJuvenileFoxglove"));
//false:
Console.WriteLine(f("Hello World"));
Console.WriteLine(f("PPCG"));
Console.WriteLine(f("3.1415"));
Console.WriteLine(f("babbage"));
Console.WriteLine(f("Code-golf"));
Console.WriteLine(f("Standard loopholes apply"));
Console.WriteLine(f("Shortest answer in bytes wins"));
Console.WriteLine(f("Happy golfing!"));
}
}
}
```
[Answer]
# PHP, 69 Bytes
```
for(;$i<strlen($s=$argv[1])-1;)$d+=1-ord($s[$i++]^$s[$i])%2;echo$d<1;
```
solution with Regex 81 Bytes
```
for(;$i<strlen($s=$argv[1]);)$t.=ord($s[$i++])%2;echo 1-preg_match("#00|11#",$t);
```
[Answer]
## PowerShell v2+, 47 bytes
```
-join([char[]]$args[0]|%{$_%2})-notmatch'00|11'
```
(Can't *quite* catch PowerShell's usual competitors ...)
Takes input `$args[0]` as a string, casts it as a `char`-array, loops through it `|%{...}`, each iteration placing the modulo on the pipeline (with implicit `[char]` to `[int]` conversion). Those are encapsulated in parens and `-join`ed into a string, which is fed into the left-hand of the `-notmatch` operator, checking against `00` or `11` (i.e., returns `True` iff the `0`s and `1`s alternate). That Boolean result is left on the pipeline and output is implicit.
### Test Cases
```
PS C:\Tools\Scripts\golfing> '#define','EvenSt-ring$!','long','abcdABCD','3.141','~','0123456789','C ode - g ol!f','HatchingLobstersVexinglyPopulateJuvenileFoxglove'|%{"$_ --> "+(.\evenst-ring-c-ode-g-olf.ps1 $_)}
#define --> True
EvenSt-ring$! --> True
long --> True
abcdABCD --> True
3.141 --> True
~ --> True
0123456789 --> True
C ode - g ol!f --> True
HatchingLobstersVexinglyPopulateJuvenileFoxglove --> True
PS C:\Tools\Scripts\golfing> 'Hello World','PPCG','3.1415','babbage','Code-golf','Standard loopholes apply','Shortest answer in bytes wins','Happy golfing!'|%{"$_ --> "+(.\evenst-ring-c-ode-g-olf.ps1 $_)}
Hello World --> False
PPCG --> False
3.1415 --> False
babbage --> False
Code-golf --> False
Standard loopholes apply --> False
Shortest answer in bytes wins --> False
Happy golfing! --> False
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~29~~ 27 bytes
```
i2%\0 n;n 1<
0:i/!?-}:%2^?(
```
Outputs 1 if the word is even, 0 if the word is odd.
You can [try it online](https://fishlanguage.com/playground).
Edit : saved two bytes thanks to Martin Ender
[Answer]
# [Perl 6](https://perl6.org), ~~47~~ 26 bytes
```
{?all .ords.rotor(2=>-1).map({(.[0]+^.[1])%2})}
```
```
{[~](.ords X%2)!~~/(.)$0/}
```
## Expanded:
```
# bare block lambda with implicit parameter $_
{
[~]( # reduce using concatenation operator ( no space chars )
.ords X[%] 2 # the ordinals cross modulus with 2 ( 1 or 0 )
# ^-- implicit method call on $_
)
![~~] # negating meta operator combined with smartmatch operator
/ ( . ) $0 / # is there a character followed by itself?
}
```
] |
[Question]
[
There has been a question about [yes](https://codegolf.stackexchange.com/questions/42428/yes-is-91-lines-long) in the past, but this one is slightly different. You see, despite `yes` having a rather long size, it is incredibly fast. Running the following command:
```
timeout 1s yes > out
```
yields a file that is **1.9 GB**. Compared to this program:
```
int puts();main(){while(1){puts("y");}}
```
which yields a measly 150 Mb.
The goal is to write a program that outputs `y\n` (that's `y` with a newline) repeatedly forever, in as few lines as possible, outputting the biggest size file in as short time as possible.
The scoring works with the equation: `b * y/y'`. The value `b` is the size of your program in bytes. The value of `y` is the size in bytes of the `out` file after running the following command: `timeout 1s yes > out`. The value of `y'` is the size in bytes of the `out` file after running the following command: `timeout 1s PROG > out` where `PROG` is your program, eg. `./a.out`. Your program should match the output of the gnu coreutils program `yes` ran with no arguments exactly, albeit outputting `y` at any speed you like. Outputting zero bytes would be a divide by zero in the original equation, resulting in a score of inf for these purposes.
Lowest score wins.
Edit:
I will run all code on my computer, please show compilation commands and any setup required.
Specs (in case you want to optimize or something):
* OS: Arch Linux 5.5.2-arch1-1
* CPU: AMD Ryzen 2600X
* SSD: Samsung 970 EVO NVMe
* RAM: 16GB 3200MHz
Here is a script to calculate the score, since it seems people are having trouble:
```
b=$(wc -c < $1)
timeout 1s yes > out
y=$(wc -c < out)
timeout 1s $2 > out
y2=$(wc -c < out)
rm out
echo "scale=3;$b*$y/$y2" | bc
```
Example, given that the script is called `score.sh` and your program is `yes.py`:
```
./score.sh yes.py "python yes.py"
```
[Answer]
# C, 112 bytes, 28 TB/s, score ≈ 0.008
```
long b[9<<21];main(){for(b[2]=write(*b=1,wmemset(b+8,'\ny\ny',1<<25),1<<27)/2;b[3]=b[2]*=2;ioctl(1,'@ ”\r',b));}
```
(If you‚Äôre having trouble copying and pasting this, replace the multicharacter constant `'@ ”\r'` with `'@ \x94\r'` or `1075876877`.)
This writes 128 MiB of `y\n`s to stdout, and then repeatedly invokes the [`FICLONERANGE`](http://man7.org/linux/man-pages/man2/ioctl_ficlonerange.2.html) `ioctl` to double the file’s length by adding new references to the same disk blocks. Requires Linux x86-64 and a filesystem supporting `FICLONERANGE`, such as Btrfs or XFS; stdout must be opened in read-write mode (e.g. `./prog 1<> out` in bash).
### Self-contained testing script
This script loop-mounts a freshly created filesystem from a memory-backed image file and runs the program there. (I get about 43 TB/s in-memory, but the ratio with `yes(1)` is similar.) It works with either Btrfs or XFS, but Btrfs seems to give better scores.
```
#!/usr/bin/env bash
set -eux
dir="$(mktemp -dp /dev/shm)"
cd "$dir"
trap 'umount fs || true; rm -r "$dir"' EXIT
printf "long b[9<<21];main(){for(b[2]=write(*b=1,wmemset(b+8,'\\\\ny\\\\ny',1<<25),1<<27)/2;b[3]=b[2]*=2;ioctl(1,'@ \\x94\\\\r',b));}" > prog.c
b="$(stat -c %s prog.c)"
gcc -O3 prog.c -o prog
dd of=fs.img bs=1 count=0 seek=8G
# Pick one:
mkfs.btrfs fs.img
#mkfs.xfs -m reflink=1 fs.img
mkdir fs
mount fs.img fs
sync
timeout 1 yes 1<> fs/out || true
y="$(stat -c %s fs/out)"
rm fs/out
sync
timeout 1 ./prog 1<> fs/out || true
y1="$(stat -c %s fs/out)"
echo "score = $b * $y / $y1 = $(bc -l <<< "$b * $y / $y1")"
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 3 bytes, 1.9 GB/s
```
yes
```
[Try it online!](https://tio.run/##S0oszvj/vzK1@P9/AA "Bash – Try It Online")
Admittedly this is a troll solution, but the rules do not explicitly forbid it, and it should get you a value close to 3, which is not bad.
[Answer]
# x86-64 machine code (Linux system calls), 29B \* 4.7GB/6.6GB = ~20.6 on tmpfs on Skylake
(Or even 28 bytes, but I haven't benchmarked Noah's suggestion of using the low 16 bits of the address as the count for `rep stosd`. Asm source for it [on Godbolt](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:assembly,selection:(endColumn:4,endLineNumber:19,positionColumn:4,positionLineNumber:19,selectionStartColumn:4,selectionStartLineNumber:17,startColumn:4,startLineNumber:17),source:%27%3B+test+with%0A%3B+sudo+mount+-t+tmpfs+-o+size%3D1G,huge%3Dalways+tmpfs+/tmp/testd%0A%3B+asm-link+-nd+yes.asm+%26%26%0A%3B+./yes+%3E+testd/yesout+%26%26+perf+stat+-d+./yes+%3E+testd/yesout+++++++%23+warmup+and+run%0A%0Aglobal+_start%0A_start:%0A%3B%3B+All+regs+zeroed+at+the+top+of+a+static+executable+(except+RSP)%0A%0ASIZEPOW+equ+17%0A%3B+++mov++ecx,+8192%0A%3B+++bts++ecx,+16++++++%3B+1%3C%3C16+%3D+65536+x+4+bytes+to+fill.++4+bytes,+any+power+of+2+vs.+mov+cx,+imm16+limited+to+65535%0A%3B+++bts++ecx,+SIZEPOW%0A%3B+++mov++edx,+ecx++++++%3B+size+arg+for+sys_write+in+bytes%3B+1/4+of+the+actual+buffer+size%0A%0A+++mov++eax,+%60y%5Cny%5Cn%60%0A+++mov++edi,+buf%0A+++mov++cx,+di+++++++%3B+We+align+%60buf%60+s.t+its+lower+2-bytes+will+be+(65536+-+16384)+which+is+both+leaves+the+write%0A+++++++++++++++++++++%3B+buf+page+aligned+(for+perf)+and+can+be+used+to+set+buffer+size+(saving+1-byte)%0A+++mov++edx,+ecx+++++%3B+size+arg+for+sys_write+in+bytes%3B+1/4+of+the+actual+buffer+size%0A+++mov++esi,+edi%0A+++%3Bshr++ecx,+2++++++%3B+just+fill+4x+as+much+memory+as+needed%0A+++rep++stosd++++++++%3B+wmemset(rdi,+eax,+rcx)++4*rcx+bytes%0A+++%0A+++lea+++edi,+%5Brcx+%2B+1%5D+++%3B+++mov++edi,+1%0A.loop:%0A+++mov++eax,+edi+++++%3B+__NR_write+%3D+stdout+fileno%0A+++syscall+++++++++++%3B+sys_write(1+/*EDI*/,+buf+/*RSI*/,+1%3C%3CSIZEPOW+/*RDX*/)%0A%25if+0%0A+++jmp++.loop%0A%25else%0A+++test+eax,eax++++++%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B+For+benchmarking+purposes:+abort+on+write+fail%0A+++jge++.loop%0A%0A+++mov+eax,+231++++++%3B+not+golfed%0A+++xor+edi,+edi%0A+++syscall+++++++++++%3B+sys_exit_group(0)%0A%25endif%0A%0Asection+.bss%0A+align+65536%0A+unused+:+resd+65536+-+16384%0A+buf:+resd+(65536+-+16384)+*+4%0A%27),l:%275%27,n:%270%27,o:%27Assembly+source+%231%27,t:%270%27)),k:33.07575924940335,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:nasm21402,deviceViewOpen:%271%27,filters:(b:%270%27,binary:%271%27,binaryObject:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%270%27,intel:%270%27,libraryCode:%270%27,trim:%271%27),flagsViewOpen:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:assembly,libs:!(),options:%27-felf64%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:%275%27,n:%270%27,o:%27+NASM+2.14.02+(Editor+%231)%27,t:%270%27)),k:33.59090741726333,l:%274%27,m:49.86033519553072,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:llvmOptPipelineView,i:(%27-fno-discard-value-names%27:%270%27,compilerName:%27llc+(trunk)%27,demangle-symbols:%270%27,dump-full-module:%271%27,editorid:1,filter-debug-info:%270%27,filter-inconsequential-passes:%271%27,filter-instruction-metadata:%270%27,fontScale:14,fontUsePx:%270%27,j:1,selectedFunction:foo,selectedIndex:10,sidebarWidth:250,treeid:0),l:%275%27,n:%270%27,o:%27LLVM+Opt+Pipeline+Viewer+NASM+2.14.02+(Editor+%231,+Compiler+%231)%27,t:%270%27)),k:33.33333333333333,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4).)
At about 6.6 GiB/s, this runs faster than GNU `yes` on [tmpfs](https://en.wikipedia.org/wiki/Tmpfs), the widely-used Linux ramdisk-like filesystem backed by the pagecache. I made sure to align my buffer to at least a cache-line boundary (and in fact a 4k page boundary) so the kernel's `copy_from_user` memcpy-like function using `rep movsb` would be most efficient.
**I don't expect this will outperform `yes` writing to an SSD on a fast Ryzen CPU which isn't the bottleneck; posted score is tentative.** However, writing 2 or 4 bytes at a time is unusably slow so we need a buffer to avoid a huge score penalty (like a factor of 2000 on tmpfs!). But probably this will score about 29 running at the same speed as GNU `yes` if they both fill the page-cache to max capacity with dirty pages and max out I/O bandwidth during the 1s window.
It's break-even for code size to use a buffer in the BSS instead of reserving stack space, in a Linux position-dependent executable where a static address can be put in a register with 5-byte `mov r32, imm32`. Using more space in the BSS doesn't increase the size of an executable that already has a BSS section/segment. But in this case it does make the executable larger so I'm not totally sure it's justified to not count anything for executable metadata for the BSS. **But as usual, I'm counting only the size of the `.text` section.** (And there's no initialized static data; all the constants are immediate.)
Without aligning the stack by 64 or 4k, `sub esp, edx`; `mov edi, esp` would be only 4 bytes, and safe in a Linux x32 executable: 32-bit pointers in 64-bit mode. (For efficient `syscall` instead of slow `int 0x80` or cumbersome `sysenter` in 32-bit mode). Otherwise break-even for `sub rsp, rdx`. So if not counting the BSS bothers you, save a byte and use the stack for buffers up to almost 8MiB (with default `ulimit -s`).
We fill a buffer that's 4x larger than we actually pass to write; `rep stosd` needs a repeat count of dword chunks and it's convenient to use the same number as a byte count for the system call.
[Try it online!](https://tio.run/##dVPvb9owEP3uv@JJUyvKCjSUshXKpEndpn7ZqvbDpv0QdZJLcOvEme0U6D/PziGMVtoiIuM733vv3jnSOSpive6V0hWbzRSenMdS@YWYwtWpQWHq0qPn4Ysqc@gZOPVEs@jT8aLOaSb1Uq5dmxzwMggIKVczYE@r8gG9MsWaXJ8DODzkTH/AW7xruNLw39SeM6jIZnBeMl3670Pb5xWW0hZ1BcnIti6FyLWJpcaci60X22UiplO81xqWcocnsoZSMLZfELypYDLIhk0loBUltZexJnRolVDlcXN7fSTE7dX3D9dfvoJ@14jesHawIY8AJatjvI3Oh00o9q4NReOtxCmiiwvezDA@OzsdY4UR4jX3wtTIlNZ97CLH3MYalVmSDZqGeHT9hiTgqaJgFK0K5Vk91wa4M/GCs9Uo/mpLOciZnZIwL0ibIzMWbu3mS8toUOWWn6UORoE5GCMTX7ORcZ1lLCdUij2uZNy79c@Sf3fP2NRxOL8POA5wNASmbmFblcOdnPuab1iwAKMVXxIUdbJAQYWx67AtiVJKQ7GlCjwg49J27ly85IOOfMcG1kaQTVZH7GWX120/oTS8miRaeT9C8jWiXw3Gc@GR6GtjqsnLJjnV8s3nn29av2asJQ2XkLVTaUIFm5lIbmT/TPcGdyIMuh8ur7qDxh/e3Nw2G74Zu2vFsctv3cGROFAZTgLkfcFNN5rEAWlHIdZ8k0EYvy3N/sFHnmpMZbIopH1QZY6qtpVx5CaQsbEepsS2g0wq3XDktOPY9d20PTyNdl2UxiM3OttOYsUUjV3tWP/XN62Un@fW1FXnhHuiMlWZEI4Sr1hEP3Y8HKlVXmJ0cj4WwZYJj5kHvPdEbDZ/AA "Assembly (nasm, x64, Linux) – Try It Online") (NASM source which assembles to this answer's machine code.) It works on TIO; it doesn't depend on the output being a regular file or anything. Below is a NASM listing of machine code hexdump & source.
```
6 global _start
7 _start:
8 ;; All regs zeroed at the top of a Linux static executable (except RSP)
9
10 SIZEPOW equ 17
13 00000000 0FBAE911 bts ecx, SIZEPOW ; 1<<SIZEPOW x 4 bytes to fill.
14 00000004 89CA mov edx, ecx ; size arg for sys_write in bytes; 1/4 of the actual buffer size
15
16 00000006 B8790A790A mov eax, `y\ny\n`
25 0000000B BF[00000000] mov edi, buf ; mov r32, imm32 static address; 00... is before linking
26 00000010 89FE mov esi, edi ; syscall arg
27
28 ;shr ecx, 2 ; just fill 4x as much memory as needed
29 00000012 F3AB rep stosd ; wmemset(rdi, eax, rcx) 4*rcx bytes
30
31 00000014 8D7901 lea edi, [rcx + 1] ; mov edi, 1
32 .loop:
33 00000017 89F8 mov eax, edi ; __NR_write = stdout fileno
34 00000019 0F05 syscall
36 0000001B EBFA jmp .loop
47 section .bss
48 align 4096
49 00000000 <res 00080000> buf: resd 1<<SIZEPOW
```
0x1b + 2 bytes for last instruction is 29 bytes total.
`mov cx, imm16` would also be 4 bytes, same as BTS, but is limited to 0..65535. vs. [BTS r32, imm8](https://www.felixcloutier.com/x86/bts) creating any power of 2. (Both depend on a zeroed RCX to start with, to produce a result zero-extended into RCX for `rep stos`)
`mov ax, `y\n`` would be 4 bytes, 1 fewer than `mov eax, imm32`, but then we'd need `rep stosw` which costs an extra operand-size prefix. This would have kept the ratio of filled buffer to used buffer at 2:1 instead of 4:1, so I should have done that to save a few pagefaults at startup, but not redoing the benchmarking now. (`rep stosw` is still fast on Skylake I think; not sure if Zen+ might suffer; but more than a factor of 2 in fill bandwidth + page fault cost is unlikely.)
A static buffer makes alignment to a cache line (or even the page size) not cost instructions; having the stack only 16-byte aligned was a slowdown. I recorded times in comments on my original code that aligned the stack pointer by 64kiB or not after reserving space for a buffer. Alignment to 64k instead of 16B made a ~3% difference in overall speed for writing a 1GiB file (to tmpfs, exiting on ENOSPC) with SIZEPOW=16, and led to a reduction in instructions retired as well. (Measured with `perf stat ./yes > testd/yesout`)
```
;;;; instead of mov edi, buf
sub rsp, rdx
; and rsp, -65536 ; With: 631.4M cycles 357.6M insns. Without: 651.3M cycles 359.4M instructions. (times are somewhat noisy but there's a real difference)
;; mov rdi, rsp ; 3 bytes
push rsp
pop rdi ; copy a 64-bit reg in 2 bytes
push rsp
pop rsi
```
For other benchmarking purposes (with a smaller 1GiB tmpfs), it was convenient to use **a loop that exited when `write()` failed** (with `-ENOSPC`) instead of looping until killed. I used this as the bottom of the loop
```
35 %if 0
36 0000001B EBFA jmp .loop
37 %else
38 test eax,eax ;;;;;;;;;;; For benchmarking purposes: abort on write fail
39 jge .loop
40
41 mov eax, 231 ; not golfed
42 xor edi, edi
43 syscall ; sys_exit_group(0)
44 %endif
45
```
---
# Testing
**I tested using tmpfs** because I don't want to wear out my SSD repeatedly testing this. And because keeping up with a consumer-grade SSD is trivial with any reasonable buffer size. **More interesting (to me) is to find the CPU/memory-bound sweet spot between system call overhead from making too many small `write` system calls vs. L2 cache misses** from re-reading too large a buffer every time. And also minimize time spent on filling a buffer before even starting to make system calls. (Although note that with write-behind I/O buffering for filesystems backed by real disk, there's no advantage to using a smaller buffer to get disk-write started sooner. I/O write-back to actual physical media wouldn't start until dirty pages hit the Linux kernel's high water mark. The default dirty *timeout* is 500 centisecs, and powertop suggests raising that to 1500 (15 seconds), so that's not going to come into play, just the high water mark. So what really matters is getting to the high water mark ASAP for a physical disk, and potentially pushing as many dirty pages into the pagecache as possible within the 1 second window, to finish writeback after `yes` dies. So this 1-second test probably depends on how much RAM your machine has (and even how much *free* RAM), if you're using a physical disk instead of tmpfs.)
`write` inside the kernel is basically a `memcpy` from the provided buffer into the pagecache; specifically Linux's `copy_from_user` function which uses `rep movsb` on systems with [ERMSB (Intel since IvB)](https://stackoverflow.com/questions/43343231/enhanced-rep-movsb-for-memcpy) or `rep movsq` when it's fast (PPro and later, including non-Intel vendors.)
**According to `perf record` / `perf report`** output, with a 128k buffer size, **45% of the counts for hardware "cycles" were in `clear_page_erms`** (on `rep stosb`) and then **18.4% in `copy_user_enhanced_fast_string`** on `rep movsb`. (Makes some sense: clearing is touching a cold page, copy is copying over a just-cleared buffer, presumably hitting in L2 cache for src and destination. Or L1d for dst if it clears 4k at a time. Or only L3 cache if it's clearing whole hugepages :/) Next highest was `iov_iter_fault_in_readable` at 3.8%. **But anyway, only ~63% of total CPU time was spent on the "real work" of actually copying into the pagecache.** And that happens inefficiently, zeroing before copying.
I tried with **`tmpfs` with `huge=never`** (which is the default) and **only got 4.8GiB** for 1s with the 128kiB buffer version that gets 6.6GiB on hugepages. So clearly hugepages are worth it overall. perf record counts for `cycles` were: 14%: `clear_page_erms` and 10% `copy_user_enhanced_fast_string`, with many other kernel functions taking low single digits percentages, like `try_charge` at 4%, `__pagevec_lru_add_fn`, `get_mem_cgroup_from_mm`, `__this_cpu_preempt_check`, and `_raw_spin_lock_irq` at 3 to 2%. Managing memory in 4kiB chunks obviously costs a lot more than in 2MiB chunks.
### Test setup
* **i7-6700k @ 3.9GHz** with 0xd6 microcode update (Nov 2019). (quad core [Skylake-client microarchitecture](https://en.wikichip.org/wiki/intel/microarchitectures/skylake_(client)), per-core caches: L1d 32k, L2 256k. Shared L3 = 8MiB) vs. Ryzen having 512kiB L2 caches.
During this test: `/sys/devices/system/cpu/cpufreq/policy0/energy_performance_preference` = balance\_performance, not full `performance` EPP setting. So this is closer to the normal bootup machine state of balance\_power). I ran a warm-up run right before the main test to make sure the CPU speed was at full before the timed 1-second started: `timeout 1s ./yes > testd/yesout; perf stat -d timeout 1s yes > testd/yesout`.
With EPP at `performance` (max turbo = 4.2GHz, near-instant ramp-up), in practice it runs at 4.1GHz average for the test. I get up to 6.9GiB written instead of 6.6, for the 128k buffer version. (And up to 7.3GiB with the `writev` version.)
* **16 GiB of DDR4-2666** (2x8GB DIMMs, dual channel)
* OS = Arch GNU/Linux, kernel = Linux 5.4.13-arch1-1
* **Filesystem = tmpfs** using transparent hugepages:
`sudo mount -t tmpfs -o size=10G,huge=always tmpfs /tmp/test`. Much of the file is using transparent hugepages: from /proc/meminfo after writing a 6.4G file: `ShmemHugePages: 6723584 kB` (6566MB), and goes down to `83968 kB` (82MB) after deleting it. **It's using x86-64 2MiB hugepages instead of 4k normal pages to reduce TLB misses.**
* System idle except for Chromium using about 3% of one core at idle clock speed.
* free memory was sufficient for tmpfs not to actually page anything out to swapspace during the test:
```
$ free -m # show numbers in megabytes. Test output deleted; tmpfs nearly empty
total used free shared buff/cache available
Mem: 15820 2790 12164 236 864 12497
Swap: 2047 930 1117
$ cat /proc/sys/vm/swappiness
6
```
* Spectre / Meltdown mitigations (big overhead per system call, above the ~100 cycles each for `syscall` / `sysret` to get in/out of the kernel):
```
$ grep . /sys/devices/system/cpu/vulnerabilities/*
/sys/devices/system/cpu/vulnerabilities/itlb_multihit:KVM: Vulnerable
/sys/devices/system/cpu/vulnerabilities/l1tf:Mitigation: PTE Inversion
/sys/devices/system/cpu/vulnerabilities/mds:Mitigation: Clear CPU buffers; SMT vulnerable
/sys/devices/system/cpu/vulnerabilities/meltdown:Mitigation: PTI
/sys/devices/system/cpu/vulnerabilities/spec_store_bypass:Mitigation: Speculative Store Bypass disabled via prctl and seccomp
/sys/devices/system/cpu/vulnerabilities/spectre_v1:Mitigation: usercopy/swapgs barriers and __user pointer sanitization
/sys/devices/system/cpu/vulnerabilities/spectre_v2:Mitigation: Full generic retpoline, IBPB: conditional, IBRS_FW, STIBP: conditional, RSB filling
/sys/devices/system/cpu/vulnerabilities/tsx_async_abort:Mitigation: Clear CPU buffers; SMT vulnerable
```
### Results writing to tmpfs for 1 second: best case 6.6GiB
Timed with this as a shell one-liner
```
asm-link -nd yes.asm && # assemble with NASM + link
taskset -c 3 timeout 1s ./yes > testd/yesout; # warm-up run
time taskset -c 3 timeout 1s ./yes > testd/yesout;
ls -lh testd/yesout && rm testd/yesout
```
Up-arrow recall that string of commands a few times, take the best case. (Assume that lower values didn't ramp up the CPU speed right away; spent some time allocating hugepages, or had other spurious interference.)
I intentionally limited myself to only looking at 2 significant figures of file size (letting ls round to `x.y GiB`) because I know there's going to be noise, so perhaps keeping the data simpler might be good.
### Results for various buffer sizes writing to tmpfs: 6.6GiB
(I did see 6.7G in some early testing with SIZEPOW=16 or 17, and I think even 6.8 or 9, but couldn't reproduce it once things settled down. Maybe some lucky early arrangement of hugepages that didn't last into a stable state?)
* SIZEPOW=1, buffer size: 2 (just `'y\n'`), best-case size: 2.9*MiB*
real 0m1.002s, user 0m0.431s, sys 0m0.570s
* SIZEPOW=2, buffer size: 4, best-case size: 5.8MiB
real 0m1.002s, user 0m0.381s, sys 0m0.620s
* ...
* SIZEPOW=11, buffer size: 1024, best-case size: 1.3GiB
real 0m1.005s, user 0m0.343s, sys 0m0.661s
* SIZEPOW=11, buffer size: 2048, best-case size: 2.3GiB
real 0m1.008s, user 0m0.270s, sys 0m0.737s. (Smaller than 1x 4k page = bad)
* SIZEPOW=12, buffer size: 4096, best-case size: 3.6GiB
real 0m1.012s, user 0m0.237s, sys 0m0.772s
* SIZEPOW=13, buffer size: 8192 (same as GNU `yes`), best-case size: 4.8GiB
real 0m1.016s, user 0m0.180s, sys 0m0.834s
* SIZEPOW=14, buffer size: 16384, best-case size: 5.6GiB
real 0m1.018s, user 0m0.090s, sys 0m0.926s
* SIZEPOW=15, buffer size: 32768, best-case size: 6.2GiB
real 0m1.019s, user 0m0.057s, sys 0m0.959s
* SIZEPOW=16, buffer size: 64kiB, best-case size: 6.5GiB
real 0m1.021s, user 0m0.023s, sys 0m0.993s
* SIZEPOW=17, buffer size: 128kiB (1/2 L2 cache size), best-case size: **6.6GiB**
real 0m1.021s, user 0m0.017s, sys 0m1.002s
* SIZEPOW=18, buffer size: 256kiB (= L2 cache size), best-case size: **6.6GiB**
real 0m1.020s, user 0m0.013s, sys 0m1.005s
* SIZEPOW=19, buffer size: 512kiB (2x L2 cache size), best-case size: 6.4GiB
real 0m1.021s, user 0m0.000s, sys 0m1.019s (User time getting meaningless / too small for Linux to measure accurately.)
* SIZEPOW=20, buffer size: 1024kiB, best-case size: 6.2GiB
* SIZEPOW=21, buffer size: 2MiB, best-case size: 5.7GiB
* SIZEPOW=22, buffer size: 4MiB (1/2 L3 size), best-case size: 5.0GiB
* SIZEPOW=23, buffer size: 8MiB (L3 cache size), best-case size: 4.9GiB
* SIZEPOW=24, buffer size: 16MiB (2x L3 cache size), best-case size: 4.9GiB
* SIZEPOW=25, buffer size: 32MiB, best-case size: 4.8GiB
* ...
* SIZEPOW=28, buffer size: 256MiB, best-case size: 4.4GiB
**GNU coreutils 8.31 `yes`**: buffer size 8192, best case size: 4.7GiB
(vs. 4.8GiB for my 8k buffer version. Perhaps because of lower startup overhead. My statically linked executable makes literally no system calls before `write`, just a BSS pagefault or two, vs. GNU `yes` being dynamically has more overhead before it gets going. And not quite as tight a loop around `syscall`, probably involving indirect-call/ret into libc's write wrapper, so at least two different pages of code in user-space are touched between system calls. Two chances for iTLB or i-cache misses. (Making a system call tends to invalidate a lot, especially with Spectre / Meltdown / MDS mitigations enabled, but even without that if a lot of kernel code runs)
GNU `yes`'s buffer is 64-byte aligned (cache line) but not 4k-page aligned. IDK if that makes any difference or leads to more dTLB misses (from spanning 3 pages instead of 2). Being an odd multiple of 64 bytes (address ending in `0x440`) is not ideal for the L2 spatial prefetcher (which tries to complete 128B-aligned pairs of lines) but that's probably insignificant; 8kiB is small enough that we get lots of L1d hits and very few L2 misses overall, including both user and kernel space. (`perf stat -d`)
The fall-off at the high end of size is I think due to cache and TLB misses. You can run `perf stat -d` instead of `time` to see LLC-misses. (And LLC-loads is an indication of L2 load misses. Indeed, small buffers get mostly L2 hits, larger buffers get some misses.)
Note that the `time` real/user/system times are for the `timeout` process itself, not for just the `yes` workload. And that Linux's time accounting is somewhat granular, I think. `perf stat` gives more details, but I didn't want even the tiny overhead of the occasional HW performance-counter event interrupt.
---
## Further speedup ideas:
Spawning **multiple threads** (all writing with `O_APPEND`) might be a minor win, depending on how much they serialize each other when appending. (I'm hoping they just reserve space and then copy, so a 2nd call can reserve more space while an earlier one is still copying. Otherwise we might need **[`vmsplice`](http://man7.org/linux/man-pages/man2/vmsplice.2.html) + [`splice(2)`](http://man7.org/linux/man-pages/man2/splice.2.html) or something** to do the page-dirtying in user-space and **give pages to the kernel without further copying** (`SPLICE_F_GIFT` + `SPLICE_F_MOVE`)). But making a `clone` system call would probably take significantly more code.
Intel desktop CPUs can nearly saturate their memory bandwidth with a single core, unlike many-core Xeons with higher memory / uncore latency; [ironically/paradoxically worse *single-core* memory bandwidth](https://stackoverflow.com/questions/39260020/why-is-skylake-so-much-better-than-broadwell-e-for-single-threaded-memory-throug/47787231?noredirect=1#comment106169219_47787231) despite more memory controller channels for higher aggregate bandwidth than dual/quad-core client chips. With significant time spent in the kernel not bottlenecked on DRAM bandwidth, multiple threads could still help.
**Using [`writev(2)`](http://man7.org/linux/man-pages/man2/writev.2.html) to pass the same buffer multiple times with one system call** could give the best of both worlds: small buffer for L1 / L2 hits while copying to the pagecache, but lots of work done per syscall. Maybe a few % speedup; (**Tried it; got a 7.0G output with 20 io vecs for an 8kiB buffer**, up from 6.6G. Kernel CPU time is now 49.5% `clear_page_erms`, 13.2% `copy_user_enhanced_fast_string`. So yes, less time spent *copying*, more time spent just clearing. 37 bytes, up from 29, score 26.3.
Source on [Try it online!](https://tio.run/##dVRtb9s2EP7OX/EAQ7uks50odtzFbgYMQzcMWJsg/dCh2@BS0kliIpEqScVy/3x6pOTa2DrBgHzvd889J@kcNWm9m2rpmqenNTw5j63ylVjDdblBYzrtMfXwTVs4TA2c@kzXyW@TqivpWtZbuXOj8YxfZyFDztGccFor/YCpzrEjN2MFnj9ny@yMRfwUa@Xhv@k8W9CSLeC85HL5t52G5ztspW26FpIz204LUdYmlTU2HGy9GF4rsV7j57qGpdLhM1lDOTi3rwjetDAFZKymMlBPWedlWhNOqM@o9bh7d3sqxLvfP7y@vXkP@tQhmXPvYEAeAcr6CX5Mri6iKvVuVCXLocU1klevWLjG8vJyvkSPBdIdzxKGRL41NucmUKi6Fl8TSE4wFjyqlLOWc@/zBvQhbYnCWLid22yt8gSlh/xc@GwRZgtjysx3DEvaFQVXDZFCHPKqSbAcVXKsYbUQMs@HeS7OxTebUOYx0z7kmjXygTYsr4LUdq4CrOyPBE7IQm0Y8oO3iEbrWtEGvXVctc@qcoSRoRgr3f3yJ5SDJsp5fekOqfEV/ri5uY3bv3t9K/btB/g@7v7W/Pso4liuS0PudsJd9FETYgbNdFhMqPGe6b7Ccp5MFm@Q7bKa1zS/fDlbvmFYnXYz9go@zMAVeKHJZH7kdzVbRD9vu8wrE91PvGrYKC3BmYa2FfNOG@W4/S4y0NL3bGZq8npyFdZDOqPTuJ61q@yIw8Ue8PuOzzKwBYueLwtNl1VoqDF2F8QBnhBsieF03rh8PBYO3rKjI39iw8ojTDbrT4HFC34PtAmhcU0kMXLjr2D8Ack/MccxaxIxC@tcHVEnJGXbWHCzeXs38vKam8nD6XLzpI34V0T/n4hHDjnQiwmeSZ768KwPpH8Uz1SB8@B33wR2ha7EM6odBV38lIU6ezZhfXjwK59PyqBXjbQPSpdMV9saR24FmRrrYTSGEQqp4pHel7SvsR8jTnExT/ataeNRmroYdtFziQgYDTfwf8NQr/ymtKZrT85PuX/NjBDCUaQTZqnj9chalRqL86ulCFe74kXzivkjs/9gPD19AQ "Assembly (nasm, x64, Linux) – Try It Online")).
As expected it doesn't come close to paying for itself in user-space code size to create the array of ptr,length pairs, although it was possible with a `loop` around 2 `push` instructions (4 bytes), but extra instructions outside the loop to get the args into place were necessary. Also, the call number `__NR_writev` is 20 so I used an array of 20 iovs, allowing the same trick as with `fd` = `__NR_write` to save a byte vs. `lea`.
There's still overhead per iovec (200x 2k buffer is slower than 20x 8k buffer). The sweet spot is around 4k or 8k buffers, with very minor gains for using a big vector (20x 8k seems enough). IOV\_MAX is "only" 1024, and isn't slower but is barely faster. ([Try it online! - flexible iov size version for perf experiments](https://tio.run/##dVRtb9s2EP7OX/EAQ4vEjV/kJsZqNwOKNRsCbEvgAF2wrnAp6SRzkUSNpGK5fz49UnIsIJu@SMd7ee6eeyhpLZVxsR9X0pZPTys4sg475bZiBdukGqVuKoexgyvrzGKsYdU3uox@Pds2OV3KYif3tndO@TX1FVLO5oLjQlUPGFcp9mQnfIDXr9kzmbKJnwJW6r9149iDmkwG6yTDpf8d1D0/YCdN2dSQXNk0lRB5oWNZYMPJxonutRSrFT4UBQzlFt/IaErBtd2W4HQNnUEGNJWAWkoaJ@OCcEJtQrXD@u72VIi767@ubm/@BP3bIJpz72BCHgFK2zP8GL3rjmJn@6No0bW4QvT@PRuXWFxcvF2gxRzxnmfxQ2KnTco9IFNFIYbpPdwAJ@FTdh2qeu4hTY5MG9i93eyMcgRVddUZdjr3k/khZeIaJiVusowxfaYQx/7VmfcI8UpliESbbHOQHIJ1gJV2YS@UuGKPXBcZs@jBPUIAf0QiLU1EV9j3O79YjM6PJa5vPm1@/3DPXESz@fkESGncF2IOqOXyqqSqkx0Kno5Ct/ZQM1DDTAhMSvlAG6Ufl36SurFbwMj2iMWupHIDZ6q8UWhe@DFbdF5ja/7yHmM5LHDQM97XXGH98z2URUWUcr/xHrHmJn@7ubkN6ltf3YpXVFgSHbGHfR1Mq7ypOKZKVXbk3zP9df939dWfGOIWrNN2dxxkV1JpyZ0YvygfbZL2FJiP@N3t2meG2UiiX@hn73yD6EsoMVx1JCaeg@VAWd2yVY@32fyx7sV0yb2k/raxPKnSL1LaFymPnHNkPjQUYj@buH0zn33BywwfyPpNJF/Qod6eNX0SYTq6@ng9mgahsrG@CwZfrMOt5LOP96PpaRDxzJf8p/R79qM@r6X7pfl@DlvF6vjgF9ZyTFWyLaV5UFXO0jC1tmSXkLE2DrrqdI5MqiJgsD57jMM@w7Tzt9Hw1nQS9xEtQ4QtUKfG/5ubWuU2udFNfTI7fZaM5aunuIlJbHnnslB5hfPZu4XwtCxZPDYdcCKenr4D "Assembly (nasm, x64, Linux) – Try It Online") also needs only a couple changes to flip back to plain write instead of writev.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~88~~ 63 bytes, 2.5GB/s
```
b[2048];main(){for(wmemset(b,'\ny\ny',2048);write(1,b,8192););}
```
[Try it online!](https://tio.run/##S9ZNzknMS///PynayMDEItY6NzEzT0OzOi2/SKM8NzW3OLVEI0lHPSavEojUdUBqNK3LizJLUjUMdZJ0LAwtjTStNa1r//8HAA "C (clang) – Try It Online") Edit: Saved 25 bytes thanks to @ceilingcat by assuming 4-byte wide characters.
[Answer]
## Bash, 16 bytes, 16TB output, score ~0 .0018554687
Thoroughly abuses the rules
```
trap '' TERM
yes
```
It ignores `timeout`'s SIGTERM (running an empty command) and so continues beyond the 1 second that the benchmark script intended to set. **This will fill your disk unless you kill it with a different signal or set a quota or other size limit.**
[Answer]
# [Perl 5 (cperl)](http://perl11.org/cperl/), 26 bytes
```
while(1){print"y\n"x 9**4}
```
[Try it online!](https://tio.run/##K0gtyjHVTS4AUv//l2dk5qRqGGpWFxRl5pUoVcbkKVUoWGppmdT@/w8A "Perl 5 (cperl) – Try It Online")
# [R](https://www.r-project.org/), 18 bytes
```
repeat{cat('y\n')}
```
[Try it online!](https://tio.run/##K/r/vyi1IDWxpDo5sURDvTImT12z9v9/AA "R – Try It Online")
Improved thanks to @[JDL](https://codegolf.stackexchange.com/users/55516/jdl)
# [Squirrel](http://www.squirrel-lang.org/), 24 bytes
```
while(1){::print("y\n")}
```
[Try it online!](https://tio.run/##Ky4szSwqSs35/788IzMnVcNQs9rKqqAoM69EQ6kyJk9Js/b/fwA "Squirrel – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 26 bytes
```
while(1){console.log('y')}
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f@/PCMzJ1XDULM6OT@vOD8nVS8nP11DvVJds/b/fwA "JavaScript (Node.js) – Try It Online")
# [Python 3](https://docs.python.org/3/), 28 bytes
```
while1:print(end='y\n'*9**4)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/vzwjMyfV0KqgKDOvRCM1L8VWvTImT13LUkvLRPP/fwA "Python 3 – Try It Online")
# [Julia 1.0](http://julialang.org/), 27 bytes
```
while(1==1) println('y')end
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/vzwjMydVw9DW1lBToaAoM68kJ09DvVJdMzUv5f9/AA "Julia 1.0 – Try It Online")
## [WHILE Programming Language](https://www.oxfordreference.com/view/10.1093/oi/authority.20110803122041931)
Performant but not participating because of many bytes...
You can't try it online! Sorry:)
But here are [Docs](https://www.scss.tcd.ie/Matthew.Hennessy/splexternal2015/notes/WhileSlides2to1.pdf),[doc](http://profs.sci.univr.it/~merro/files/WhileExtra_l.pdf) and a java-based [IDE](http://www2.mta.ac.il/~tal/WIDE/wide.zip)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 67 bytes
```
b[1<<16];main(){for(wmemset(b,'\ny\ny',1<<16);~write(1,b,1<<18););}
```
Your times may vary. I'm running this inside a VM on a weak computer.
* `b[1<<16];` is an integer array of \$2^{18}\$ bytes.
* `wmemset(b,'\ny\ny',1<<16);` sets that array to a pattern of `y\ny\n`. The characters are reversed due to the endianness of the x86 platform.
* `~write(1,b,1<<18)` writes that array over and over until the write fails. (The `~` makes a `-1` error return -> false; without it we iterate until the process is killed, saving 1 byte.)
May be faster on other systems if I increase the buffer size to 1 megabyte but there's no noticeable difference on mine. This really should be an average.
[Try it online!](https://tio.run/##HYpLCoAgFACPk4IuJIhA79ABqoWKhuAntJCIOnqvCGY2w2i6aA2gRiYE62YepIsInzZlVIMJxWxIkWaKx0dD/gnzu2a3GcSI@kuPOeYXwKOtl0sBOrRA7R5z8p7KT5/SWl4 "C (gcc) – Try It Online")
[Answer]
### x86 machine code - 21 15 bytes, score : 175119.036
Using [write()](https://man7.org/linux/man-pages/man2/write.2.html) syscall to print `y\n`
This is a NASM listing (`y.asm`) :
```
6 00000000 6668790A push word 0x0a79
7 00000004 43 inc ebx
8 00000005 89E1 mov ecx, esp
9 00000007 B202 mov dl, 2
10 .loop:
11 00000009 B004 mov al, 4
12 0000000B CD80 int 0x80
13 0000000D EBFA jmp .loop
```
Using `score.sh` to get a score (`./score.sh y "./y"`), score are : 175119.036
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 30\*971956224/621731~46899.2
```
>+[>+[<]>->+]++++++++++<[.>.<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v/fTjsaiGxi7XTttGO14cAmWs9Ozyb2/38A "brainfuck – Try It Online")
The BF JIT that I'm using prints each character in a separate syscall. An implementation that coalesces multiple `.` commands into one syscall would likely perform better.
Thanks to the [list of BF constants](https://esolangs.org/wiki/Brainfuck_constants).
[Answer]
# [Rust](https://www.rust-lang.org/), ~~49~~ 48 bytes \$\times\,\frac{32186368}{744521728}\approx2.075\$
Plain Rust, compiled with `-C target-cpu=native -C opt-level=3`. Clearly not the winner, only for reference; not bad, btw :)
```
fn main(){loop{print!("{}","y\n".repeat(8192))}}
```
-1 byte thanks to [Anders Kaseorg](https://codegolf.stackexchange.com/users/39242/anders-kaseorg)
[Try it online!](https://tio.run/##KyotLvn/Py1PITcxM09DszonP7@guqAoM69EUUOpulZJR6kyJk9Jryi1IDWxRMPC0NJIU9O6tvb/fwA "Rust – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 34 bytes, 1.9GB/s, score \$\le\$ 31.507
```
a='y\n'*2**17
while 1:print(end=a)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9FWvTImT13L2MjczIKrPCMzJ1XB0KqgKDOvRCM1L8U2UfP/fwA "Python 3 – Try It Online")
[Answer]
# [Jyxal `0ea7043bf37cd78106cde8f664e452f87286673b`](https://github.com/Vyxal/Jyxal/tree/0ea7043bf37cd78106cde8f664e452f87286673b), ~31.551 on my machine
```
{9999`y\n`*‚Ç¥}
```
Timed using an aging laptop with an Intel Core i5 4th gen, 8 GB ram, using WSL. It uses Vyxal's codepage, so I modified `score.sh` to use the `-m` flag instead of `-c`. Jyxal is a flavor of Vyxal designed for maximum speed. Unfortunately, I could not apply my push-pop optimizations in this case that *really* make Jyxal fast. Also for some weird reason multiplying the string inside the loop seems to be faster than outside...
```
{9999`y\n`*‚Ç¥} # Ze program
{ } # An infinite loop
`y\n` # The string "y\n"
9999 * # Repeated 9999 times...
‚Ç¥ # Printed without a newline
```
## How to run
Jyxal isn't exactly released yet, you'd have to built it yourself. Clone the repo at commit `0ea7043bf37cd78106cde8f664e452f87286673b` and then run `./gradlew shadowJar`. You will find the compiled compiler in `/build/libs/`. Then create a file with the Jyxal program, and compile it with `java -jar Jyxal-1.0-SNAPSHOT-all.jar yourProgram.txt`. The run the compiled program using `java -jar yourProgram.jar`. All Java-related steps require Java 17 or higher.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 bytes
No clue how the scoring in this challenge works.
```
@Opy}a
```
[Try it online!](https://tio.run/##y0osKPn/38G/oLI28f9/AA)
```
@ :Function
Opy : Print "y"
} :End function
a :Call repeatedly until it returns a truthy value
:(Japt's O.p() method returns undefined)
```
[Answer]
# x86-32 Linux, 26 bytes (ungolfed), 1.5M
[`write` syscall test](https://stackoverflow.com/a/50940154/3163618). Produces a very underwhelming result.
```
main:
push $0x0A79 # "y\n"
mov $1, %ebx # write to stdout (fd=1)
mov %esp, %ecx # use chars on stack
mov $2, %edx # write 2 chars
loop:
mov $4, %eax # sys_write call number
int $0x80
jmp loop
```
[Answer]
# [Python 3](https://docs.python.org/3/), 18 bytes \$\times\frac{16834568}{622668}\approx486.65\$
```
while 1:print('y')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/vzwjMydVwdCqoCgzr0RDvVJd8/9/AA "Python 3 – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) / [05AB1E](https://github.com/Adriandmen/05AB1E), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), score: *waiting for OP*
```
['y,
```
Or alternatively:
```
'y[=
```
[Try it online.](https://tio.run/##MzBNTDJM/f9fvTLa9v9/AA)
Not sure which combination is the shortest, so for now this answer has four possible variations:
* [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) with program `['y,`
* [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) with program `'y[=`
* [05AB1E](https://github.com/Adriandmen/05AB1E) with program `['y,`
* [05AB1E](https://github.com/Adriandmen/05AB1E) with program `'y[=`
The 05AB1E (legacy) version is compiled and run in Python 3, and the 05AB1E version is compiled and run in Elixir. Based on performance on TIO for most challenges I did, I assume the legacy version will score much better.
I will leave just one of these four combinations with the largest output after OP's local test. The links provided contain instructions on how to install and run both 05AB1E and 05AB1E (legacy) locally.
**Explanation:**
```
[ # Loop indefinitely:
'y '# Push string "y"
, # Pop and output it with trailing newline
'y '# Push string "y"
[ # Loop indefinitely:
= # Output with trailing newline (without popping)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes \$\times\frac{1894125568}{1599025152}\approx11.846\$
```
#p*^9 5"y
```
**Explanation:**
```
# : Loop till error
^9 5 : Evaluates to 9 ^ 5 (59049)
* "y\n : Concatenates "y\n" to itself 59049 times
p : Print without trailing newline
```
[Try it online!](https://tio.run/##K6gsyfj/X7lAK85SwVSpkuv/fwA "Pyth – Try It Online")
[Answer]
# GFortran, 24 bytes, score: 49.179
`yes1.f90`   [Try it online](https://tio.run/##S8svKilKzNNNT4Mw/v9PybcuKMrMK9HSUa9Ut07NS0nJ5wKS//8DAA)
```
do;print*,'y';enddo
end
```
Might be faster to use [`FPUT`](https://gcc.gnu.org/onlinedocs/gfortran/FPUT.html#FPUT)??, for **52 bytes**:
`yes2.f90`   [Try it online](https://tio.run/##S8svKilKzNNNT4Mw/v9PybdOTszJUUgrKC3RUK9U10Ti5qWWx@dk5qVqqKtralqn5qWk5HMByf//AQ)
```
do;call fput('y');call fput(new_line(''));enddo
end
```
Run the code
```
//Compile
$ gfortran -std=gnu -Wextra -Wall -pedantic -ffree-form -fcheck=all -fbacktrace yes1.f90 -o yes1.a
$ gfortran -std=gnu -Wextra -Wall -pedantic -ffree-form -fcheck=all -fbacktrace yes2.f90 -o yes2.a
//Run the test
$ timeout 1s yes > out0
$ timeout 1s yes1.a > out1
$ timeout 1s yes2.a > out2
//File sizes
-rw-r--r-- 1 staff 29306880 6 Mar 18:43 yes.out
-rw-r--r-- 1 staff 24 6 Mar 18:57 yes1.f90
-rw-r--r-- 1 staff 14302020 6 Mar 18:51 yes1.out
-rw-r--r-- 1 staff 52 6 Mar 18:57 yes2.f90
-rw-r--r-- 1 staff 18071552 6 Mar 18:39 yes2.out
//Scores
$ bc<<<"scale=3;24*29306880/14302020"
49.179
$ bc<<<"scale=3;52*29306880/18071552"
84.329
```
My system (inferior to the OP):
```
$ neofetch --off
OS: macOS 11.2 20D64 x86_64
Host: MacBookPro13,2
Kernel: 20.3.0
CPU: Intel i5-6267U (4) @ 2.90GHz
GPU: Intel Iris Graphics 550
Memory: 5500MiB / 8192MiB
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~57~~ 54 bytes \$\times\frac{44152832}{45940736}\approx51.8984\$
Saved 3 bytes thanks to @S.S.Anne!!!
```
#define p putchar_unlocked
main(){for(;;p(10))p('y');}
```
[Try it online!](https://tio.run/##S9ZNzknMS///XzklNS0zL1WhQKGgtCQ5I7EovjQvJz85OzWFKzcxM09Dszotv0jD2rpAw9BAU7NAQ71SXdO69v9/AA "C (clang) – Try It Online")
This is on my ancient tablet, probability better on my laptop that's far away right now - on holiday! :))))
] |
[Question]
[
*Note:* There are some rude words in this question.
There's an implicit puzzle posed in this [classic Monty Python sketch](https://www.youtube.com/watch?v=-gwXJsWHupg) (you can also ready the [script](http://www.montypython.net/scripts/wood.php) online).
Various phrases are described as being 'woody' or 'tinny', and one is described as being 'PVC'.
Given a phrase, respond with its type according to the following lists:
### `woody`:
```
gone
sausage
seemly
prodding
vacuum
bound
vole
caribou
intercourse
pert
thighs
botty
erogenous zone
ocelot
wasp
yowling
```
### `tinny`:
```
litter bin
newspaper
antelope
recidivist
tit
simpkins
```
### `PVC`:
```
leap
```
---
## Rules
* If the input belongs to one of the above lists, the output should be `woody`, `tinny` or `PVC`, accordingly.
* All input is lower case.
* Any behaviour is acceptable for phrases which are not listed above.
* The fewest bytes in the answer wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~99~~ ~~73~~ ~~65~~ ~~64~~ 63 bytes
```
lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[-2:]in'instperit'::2]
```
[Try it online!](https://tio.run/##XZGxTsQwDIZ3nqKb75BYOlZi4gUYEAzHDWnj61mkdhQnV5WXL4EBYqbo/@M432/HLV@F@/3y@L4Ht4zedTrA8@sT3B8AHRB3epQEaxYS9rxtcNLTQz@cieul5oiJMgxDf95jIs7wJuK3Ae5@VHc5wCyMcPzT6oq62VqIS9haJybxnnhuvZubSllaZ5TC3pRIMI0nl6gWtVY9ME1SkprKmiO3Ol9pvqr9LGfDiElmZCnaff6LKBMGMe1Wp7HVm6yhiQcvxGymFihXzm6sY26eMa4aXWVtTVcTBYmGIOFEnm6kNhQZqbTEj7rEX4q6d8OA7ht6/wI "Python 2 – Try It Online")
Alternatives also with 63 bytes:
```
lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[-6::5]in'dtenmsr'::2]
lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[::5]in'lrinaosit'::2]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
lambda n:'wtPoiVonCdn yy'[hash(n)%97%78%28%15%2+('ea'in n)::3]
```
[Try it online!](https://tio.run/##LZA9bsMwDIX3nIKLoBjNErdFEgOZeoFOXdIMiqXYRGVSEOUY7uVdS@nEj396Twxz6pnq5X7@XrwZbtYANXpKn4xfTB@WYJ71pTfSb6lSp4M6HFV9VPt3Vb9stTMaCahqmtfrMnG0Ame4aO9M0DvQHlNyEW5IOSM3STDBxZwYSs5zcJmja9HiAyXlLGEJgkP4QZLMHVMZFDOK6Z7o3ODnTCGytUhd5odpx3HIdOORbCmxLwutibgWM@KqHVseo5TO6ugp3GPXy3M5pfK2i9w54lHg998Ct6vtMj4ZKZ@cefJZ/rrZ3DlCvgKsRynXaDYAIa56oNX@TRpQokHBNjd3cC@xqpY/ "Python 2 – Try It Online")
## How?
This submission uses the fact that the `hash` function is stable for strings in Python 2. Each valid input has a valid output. The brute-forced repeated modulo `%97%78%28%15%2` returns `1` for all *tinny* and *PVC* words and `0` for *woody* words. By adding the value of `('ea' in n)` to it, we get `2` instead of `1` for the input 'leap'. Here is a table of all values:
```
+----------------+----------------------+----------------+-------------+-------+
| word | hash | %97%78%28%15%2 | +('ea'in n) | type |
+----------------+----------------------+----------------+-------------+-------+
| leap | 5971033325577305778 | 1 | 2 | PVC |
+----------------+----------------------+----------------+-------------+-------+
| litter bin | 2393495108601941061 | 1 | 1 | tinny |
| newspaper | 1961680444266253688 | 1 | 1 | tinny |
| antelope | -2930683648135325182 | 1 | 1 | tinny |
| recidivist | -1480015990384891890 | 1 | 1 | tinny |
| tit | -1495230934635649112 | 1 | 1 | tinny |
| simpkins | 672871834662484926 | 1 | 1 | tinny |
+----------------+----------------------+----------------+-------------+-------+
| gone | 3644900746337488769 | 0 | 0 | woody |
| sausage | 4880706293475915938 | 0 | 0 | woody |
| seemly | -8112698809316686755 | 0 | 0 | woody |
| prodding | 7325980211772477495 | 0 | 0 | woody |
| vacuum | -5283515051184812457 | 0 | 0 | woody |
| bound | -6522768127315073267 | 0 | 0 | woody |
| vole | -7823607590901614336 | 0 | 0 | woody |
| caribou | -3644594841083815940 | 0 | 0 | woody |
| intercourse | 2499732157679168166 | 0 | 0 | woody |
| pert | 4142553773863848247 | 0 | 0 | woody |
| thighs | -3490317966011085195 | 0 | 0 | woody |
| botty | -6522767127163072681 | 0 | 0 | woody |
| erogenous zone | 7046120593231489339 | 0 | 0 | woody |
| ocelot | -6961879712146820842 | 0 | 0 | woody |
| wasp | -3668927459619339511 | 0 | 0 | woody |
| yowling | 6823632481520320220 | 0 | 0 | woody |
+----------------+----------------------+----------------+-------------+-------+
```
The type to return is now extracted from the string `'wtPoiVonCdn yy'` by taking every third character, starting at the calculated index.
[Answer]
# JavaScript (ES6), Chrome/Edge, 54 bytes
Because the behavior of `parseInt()` on large inputs with a radix of 36 is [implementation-dependent](https://www.ecma-international.org/ecma-262/6.0/#sec-parseint-string-radix), this one doesn't work with SpiderMonkey (Firefox).
```
s=>[,'PVC',,'Tinny'][parseInt(s+383,36)%69%7]||'Woody'
```
[Try it online!](https://tio.run/##bZIxT8MwEIV3fkVVqXIjAkukQoXKwsTGgGAIHVznmh44d5bPSRXU/x5MxQDoNut7Ovu9d363gxUXMaQr4gam/WaSzX1dmqeXB1OW5hmJRrOtg40Cj5SWclndVmW1Khar9eJmezqZV@ZmNJNjEvZw7bldmvoMt6a4u/jN98t5ywTzoviPxfZiW1UB6PyoCCFy0yC1ijRY1/edIuy4p0YbyGcFOxsxjygKUoLouM@taNYgJgWnA7YHUW2lpEWEyC0Q9zL71GtjB561p45WgoJHPvqfyv5I5o3q86q1lXlMOexsh6TcSHCUYHNgRbO5JM9BMx7BYYMDitoTalSwCx9IoprP31W1Dva7hukL "JavaScript (Node.js) – Try It Online")
### How?
The hash function returns **3** for Tinny words, **1** for PVC and either **0**, **4**, **5** or **6** for Woody words. The words marked with an asterisk are implicitly truncated because *space* is considered as an invalid character by **parseInt()**.
```
word | +383 | base 36 -> decimal | mod 69 | mod 7
---------------+----------------+-----------------------+--------+------
gone | gone383 | 36318994131 | 54 | 5
sausage | sausage383 | 2874302392811475 | 42 | 0
seemly | seemly383 | 80120017777107 | 6 | 6
prodding | prodding383 | 94214834629477200 | 12 | 5
vacuum | vacuum383 | 88266035564499 | 60 | 4
bound | bound383 | 916101808275 | 6 | 6
vole | vole383 | 68967369939 | 39 | 4
caribou | caribou383 | 1249086300450771 | 63 | 0
intercourse | intercourse383 | 3.183324871563264e+21 | 11 | 4
pert | pert383 | 55312791699 | 21 | 0
thighs | thighs383 | 83184557510739 | 6 | 6
botty | botty383 | 916052399571 | 63 | 0
erogenous zone | erogenous (*) | 41664605989780 | 7 | 0
ocelot | ocelot383 | 68678794158483 | 39 | 4
wasp | wasp383 | 70309896339 | 63 | 0
yowling | yowling383 | 3523299657958227 | 39 | 4
---------------+----------------+-----------------------+--------+------
litter bin | litter (*) | 1301413923 | 24 | 3
newspaper | newspaper383 | 3081816298632183000 | 3 | 3
antelope | antelope383 | 38980419895881940 | 24 | 3
recidivist | recidivist383 | 129824740122576960000 | 3 | 3
tit | tit383 | 1785109395 | 45 | 3
simpkins | simpkins383 | 104264583727840850 | 24 | 3
---------------+----------------+-----------------------+--------+------
leap | leap383 | 46576922259 | 57 | 1
```
---
# Previous version, ~~59~~ 57 bytes
```
s=>['Woody','Tinny','PVC'][82178>>parseInt(s,35)%50%26&3]
```
[Try it online!](https://tio.run/##bZIxTwMxDIV3fkVVqeROKghaFSqhdmFiY0AwHDekOfdqSO0ozrU6/vyRVgyAPCV6n@w8P@fDHqy4iCFdETcwbFeDrNaVeWNuejM1L0h0Op9fH01dLWe398v1Otgo8ESpkOl8UU4WN5PZ3eW8HhyTsIdrz21hqnOL2pQPF7/1bTFumWBclv9lsZ3YViUAe98rIERuGqRWQQfrum6vgA131GgF@a7IzkbMJQpBShAddzkLzRrEpMhph@1OVFspaSNC5BaIOxl96bGxA8/aU0crQZF7PvqfyP4g807VedvayjymPOxog6R0JDhKsHlghdkckuegGY/gsMEDipoTaqrgPnwiiWo@f1HVOthTDMM3 "JavaScript (Node.js) – Try It Online")
### How?
Below are the different steps of the function for each input. The result of the first modulo is an approximation within the precision of JS numbers and is mathematically invalid for *intercourse*.
```
input | base-35 -> dec. | %50 | %26 | 00000000010100000100000010
---------------+-------------------+-----+-----+---------------------------
gone | 716219 | 19 | 19 | 00------------------>
sausage | 52042888324 | 24 | 24 | 00----------------------->
seemly | 1492249219 | 19 | 19 | 00------------------>
prodding | 1659396207121 | 21 | 21 | 00-------------------->
vacuum | 1643736697 | 47 | 21 | 00-------------------->
bound | 17573443 | 43 | 17 | 00---------------->
vole | 1359274 | 24 | 24 | 00----------------------->
caribou | 22625709220 | 20 | 20 | 00------------------->
intercourse | 51532867489988450 | 48 | 22 | 00--------------------->
pert | 1089999 | 49 | 23 | 00---------------------->
thighs | 1549436973 | 23 | 23 | 00---------------------->
botty | 17572449 | 49 | 23 | 00---------------------->
erogenous zone | 33308397234728 | 28 | 2 | 00->
ocelot | 1279159344 | 44 | 18 | 00----------------->
wasp | 1385255 | 5 | 5 | 00---->
yowling | 63810499496 | 46 | 20 | 00------------------->
litter bin | 1131250042 | 42 | 16 | 01--------------->
newspaper | 52754217228642 | 42 | 16 | 01--------------->
antelope | 687218151914 | 14 | 14 | 01------------->
recidivist | 2160354371100934 | 34 | 8 | 01------->
tit | 36184 | 34 | 8 | 01------->
simpkins | 1835782971008 | 8 | 8 | 01------->
leap | 917900 | 0 | 0 | 10
```
[Answer]
## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~39~~ ~~38~~ 36 bytes
*Saved 1 byte by using three substitution pairs as in Adám's answer.*
```
L#-3$0`ea
PVC
.p.|is?t
tinny
$
woody
```
[Try it online!](https://tio.run/##Fc6xagMxEATQfr7CEAfSxCTkA1KkSJPCVWqvdYu8RLcrtNIdMv73i64aBobHFK6i9L49v3xftp@n14/j24UJ598vnPLpIf5ZMRbaccRqNvVti6YMp@YURzLPqSMXmybRiIVCazOu1nTCYokRqMioEK1cgrXijMxlsDeJNx/TWju4WGS15of7zlvgZBUreUa3Ne10kjqEw1UUyqtnGgpoqMkyo3CQSRbx/W@Fy5z/RB2JKf8D "Retina – Try It Online")
I got the `.p.|is*t` regex from [Peter Norvig's regex golfer](http://nbviewer.jupyter.org/url/norvig.com/ipython/xkcd1313-part2.ipynb).
[Answer]
# Java 8, ~~81~~ ~~80~~ 67 bytes
```
s->s.charAt(2)<98?"PVC":s.matches(".*(.p.|is?t).*")?"tinny":"woody"
```
[Regex from *@MatrinEnder*'s Retina answer.](https://codegolf.stackexchange.com/a/157257/52210)
[Try it online.](https://tio.run/##rZJNb9wgEIbv/RUjTnaWkCqn1pvNKuq5UaVW7aHqgcXEJsGAmLF33Ta/fTv2eiNVSm@VQDAwvDzz8agHfRmTDY/109F4jQgftQu/3gC4QDY/aGPhfjIBPlN2oQFTLBss13z@zJMHkiZn4B4CbOCIl7eoTKvzHRXX5c37d1vx6esHUaHqNJnWYiHURaGS@u1wS6W6EOVWkAthFJXYx1iP4rg@Cad@51l40R@iq6FjwgXi@w9dnuiuruDb9LCarYeYz5iHSjQxWIm6R93wam3nR5lyrGu@l4M2fd/JXexDLYforTQ6OzblnAET@4xWJptJUuuaFtmVaJQ2x8aG2CP8nOSjsT6S3GtMcox7z9JCYfKOCiFFWc5YAGSRisOcOc7oiGQ7FXtSiVnJh2K5OYf0ZcrJayGxLsPBzgUZ7B6TZkCpGdhzNWW2xtVucMjMjiS6Lj25gP8BiMt4wpnfCW91Eq/0wVyn2eWMXP7VRNli74lbJSjz8vthtREViPVLuEwAbnNQ3oaGWkZxq9XN9dv15Aji38yH1Ul/AXs@/gE)
**Original answer: ~~81~~ 80 bytes**
```
s->"anetisilire".contains(s.substring(0,2))?"tinny":s.charAt(2)<98?"PVC":"woody"
```
[Try it online.](https://tio.run/##rZJNb9swDIbv@xWETjaiukVOW9KsGHZeMWDDdhh2UGTWUStLhkg59ob@9ox2nAIDutsACxYl6uXDj0fTm6vYYXisn07WGyL4ZFz4/QbABcb0YCzC/WQCfOHkQgO2WDZUbuX8WZZ8xIadhXsIsIMTXb1XJiA7ct4lVJWNgUWXCqoo72kWKG70uizvFLsQRrWhyh5M@sDFurx99/ZOff72UW3UMcZ6VKftOUqX916iLMH66GpoRXYh@vHTlGfU62v4Pj3czNZDTBfmYaOaGFCTyWQa@SO2ftRdinUt97o3NudW72MOte6jR21NcmLquRw25kSoO0ys@eCaA4kr86gxxQZDzAS/Jvlo0UfWR0OdHuPRi7SqqPOOC6VVWc5YAIzExTCXUco7EmNbxcxVJ6zsQ7HcXFL6OhXqtZREV@Bg74IOeKTOCKA2AuyltTqhdbXrHQmzY02u7Z6kFf8BSFp0xpnfKY@mU68Mxdyn2eWCXP41UQkpe5a5CZV9iT6sdmoDavuSrhCA2w2Vx9DwQVDcanW7vtlOjqD@zTyszvoL2PPpDw)
**Explanation:**
```
s-> // Method with String as both parameter and return-type
"anetisilire".contains(s.substring(0,2))?
// If the first two letters of the input are present in "anetisilire"
"tinny" // Output "tinny"
:s.charAt(2)<98? // Else-if the third character of the input is an 'a'
"PVC" // Output "PVC"
: // Else:
"woody" // Output "woody"
```
**Additional explanation:**
```
litter bin: anetisi(li)re
newspaper: a(ne)tisilire
antelope: (an)etisilire
recidivist: anetisili(re)
tit: ane(ti)silire
simpkins: aneti(si)lire
```
1. None of the first two letters of the `woody` words are present in this String above, nor is `le` from `leap`.
2. None of the `woody` words has an `a` as third letter, so that is used to get `leap` to `PVC` if it's not a `tinny` word.
3. Everything else is a word from the `woody` list.
[Answer]
# [Haskell](https://www.haskell.org/), 61 bytes
```
f(a:b:_)|b=='i'||elem a"ran"="tinny"|a=='l'="PVC"|1>0="woody"
```
[Try it online!](https://tio.run/##TY67asQwEEX7fIWYxrsQQtIuKE3qQKo0IYSxPWsPK2mEHmsc/O@OSCFZlc694urMGG9kzL5fT3jpLz/nrde6427byJBVCAEdaEjs3Aobls50Gj4@32B7eX3WsIiMK@wW2SmtLPp3dfKBXVJP6np@UOV8KZjEEfzDo4KIOeJ0YCJr1oo@yDiym2pwxyFnW7GX7MZWimlLAwYudeWiQWGQHGJ74ymkCmnmaY6H6ZSaCAWZyEmO6veoLwMZaRMLRl9hlcUc1Q2nYqB6djVytESPxaImWCyN@PZDoIFHvnM8iHK7R7b@xq5pG0IP6nv/Aw "Haskell – Try It Online")
Uses this hand-found logic:
* Words with second letter `i` or first letter `r`, `a`, or `n` are `tinny`
* Any other word starting with `l` (`leap`) is `PVC`
* Anything else is `woody`
Lynn saved a byte by checking `leap` by its first letter.
[Answer]
# [QuadS](https://tio.run/##KyxNTCn@//9RV/Oj3q1cqYlcegV6NZnF9iVcKlwBYc5cJZl5eZVc5fn5KZX//@ekJhYAAA "QuadS – Try It Online"), ~~34~~ 32 bytes
Shamelessly uses [Martin Ender's system](https://codegolf.stackexchange.com/a/157257/43319), including the regex from [Peter Norvig's regex golfer](http://nbviewer.jupyter.org/url/norvig.com/ipython/xkcd1313-part2.ipynb).
```
⊃⍵
ea
.p.|is?t
$
PVC
tinny
woody
```
[Try it online!](https://tio.run/##KyxNTCn@//9RV/Oj3q1cqYlcegV6NZnF9iVcKlwBYc5cJZl5eZVc5fn5KZX//@ekJhYAAA "QuadS – Try It Online")
`⊃⍵` pick the first occurrence of
`ea` "ea"
`.p.|is?t` "p" surrounded by letters OR "i" and "t" with an optional "s" between them
`$` end of input
… but substituting the matches with the corresponding one of the following:
`PVC`
`tinny`
`woody`
---
The equivalent 43-byte [Dyalog APL](https://www.dyalog.com/) function is:
```
⊃'ea' '.p.|is?t' '$'⎕S'PVC' 'tinny' 'woody'
```
Try all the cases online!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~81~~ ~~80~~ 79 bytes
-1 byte thanks to @ceilingcat.
```
h;f(char*s){puts(index("HzYfPW",h=*s^s[1]*4&127)?"Tinny":h<120?"Woody":"PVC");}
```
[Try it online!](https://tio.run/##VVJNT@MwED3Hv8KyBEqCKxGEdiUK4rCXPXJAoFXblYzjJBapbXmcloLy27vjOmHBF7/5eDPPnpGLVsrjsVs2ueyEL6H4cEOAXJtaveXs9/uf5uGZ8e6uhL@wqjbl9Xl19bO4Z4/amAO76W6rq8t79mxtjRZ7ePrFiuV43Fld0zaX1kCgsTAtA6dfzRI41SZQU5APkjmPuMnZ2pzB2izwrA3jNBRLkpGssZ7mMVnTO3q5xOuWGrwuLgqSIfuTfraorgFzkAorvYnsrMlnOJKRkFhmK7TJT32zr5L28RGrDfJjhLXWKMYjAjGAaGdDqW1/SNh5W9fatMnaCTkM24Rf7GDqyW37iSqF1xhIBgpRXtrBwxR1yoeEQqfbDuZCIUzdlLetMnYA@v4pzUrV24m2F@ASOth9H2WN8QPIt0eGOLf/j@x1QBn0RZvENGoPTqCUZAoU2Vs3NfNK6lrvNMw69QRAb92rNhAbfm/ndjI1Y70S7iSIZG0@LQynpz/ntPoRB4T@tFY4@XhzOrvjXnGKxTAVXePxHw "C (gcc) – Try It Online")
The first order of business was to find some hash function that would separate the words into their categories. After some fiddling about I stumbled upon `(s[0] ^ (s[1] << 2)) & 0x7f`, where the 0x7f is of course there to bring it down to printable ASCII levels. This produced the following information (the tables are sorted, but not the resulting strings):
```
Woody:
----
erogenous zone - 45
prodding 8 56
yowling E 69
vole J 74
intercourse Q 81
thighs T 84
gone [ 91
botty ^ 94
bound ^ 94
ocelot c 99
pert d 100
caribou g 103
seemly g 103
vacuum r 114
wasp s 115
sausage w 119
[wg8r^JgQdT^-csE
Tinny:
----
litter bin H 72
tit P 80
simpkins W 87
antelope Y 89
recidivist f 102
newspaper z 122
HzYfPW
PVC:
----
leap x 120
x
```
The hash collisions don't matter, since they are confided to the same category. We only have to check if the resulting hash is in the Tinny hashes string ("HzYfPW"), since the Woody hashes are all below the PVC hash (120). If 120 or higher, and not a Tinny word, it must be PVC. If not a Tinny word, and the hash is below 120, then it must be a good, woody sort of word.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 30 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ï═H♣║GÇX→ΩM+@╢^j╬♪►╨╝ô╤c\
```
[Run and debug it](https://staxlang.xyz/#p=8bcd45689de6f00f3920ac0ff2b4d49ad3ef75a57a119a4ede&i=gone%0Asausage%0Aseemly%0Aprodding%0Avacuum%0Abound%0Avole%0Acaribou%0Aintercourse%0Apert%0Athighs%0Abotty%0Aerogenous+zone%0Aocelot%0Awasp%0Ayowling%0Alitter+bin%0Anewspaper%0Aantelope%0Arecidivist%0Atit%0Asimpkins%0Aleap&a=1&m=2)
The commented ascii representation is this. I didn't invent this algorithm. It's shamelessly ripped off [Jonathan Allen's python solution](https://codegolf.stackexchange.com/a/157816/527).
```
9@ 10th character, modularly indexed
`#!z"pi0$L+%v9`X store "tinny pvc woody" in the x register
3( keep only the first 3 characters ("tin")
# how many times the 10th char occurs in tin? (a)
y.eaI index of "ea" in the input or -1 (b)
+ a + b (one of -1, 0, or 1)
xj@ modularly indexed word in x
```
[Run this one](https://staxlang.xyz/#c=9%40%09%09%0910th+character,+modularly+indexed%0A%60%23%21z%22pi0%24L%2B%25v9%60Y%09store+%22tinny+pvc+woody%22+in+the+y+register%0A3%28%09%09%09keep+only+the+first+3+characters+%28%22tin%22%29%0A%23+++++++++%09%09how+many+times+the+10th+char+occurs+in+tin%3F+%28a%29%0Ay.eaI%09%09%09index+of+%22ea%22+in+the+input+or+-1+%28b%29%0A%2B%09%09%09a+%2B+b+%28one+of+-1,+0,+or+1%29%0Ayj%40%09%09%09modularly+indexed+word+in+y&i=gone%0Asausage%0Aseemly%0Aprodding%0Avacuum%0Abound%0Avole%0Acaribou%0Aintercourse%0Apert%0Athighs%0Abotty%0Aerogenous+zone%0Aocelot%0Awasp%0Ayowling%0Alitter+bin%0Anewspaper%0Aantelope%0Arecidivist%0Atit%0Asimpkins%0Aleap&a=1&m=2)
[Answer]
# x86 32-bit machine code, 39 bytes
Hexdump:
```
69 01 47 6f 61 2c c7 02 50 56 43 00 3a c4 74 16
c7 02 77 6f 6f 64 85 c0 78 06 c7 02 74 69 6e 6e
66 c7 42 04 79 00 c3
```
The hash function is multiplication by a "magic" number `0x2c616f47`. There are only 6 numbers that can be used with this code.
First of all, it writes `PVC` to the output. This will be overwritten, if needed.
After hashing, it checks for the PVC word; the check is `al = ah` - I chose it because it's a small 2-byte instruction. Then, it writes either `wood` or `tinn`, depending on the sign of the hashed result. Then, it writes `y`.
Assembly code:
```
imul eax, [ecx], 0x2c616f47;
mov dword ptr [edx], 'CVP';
cmp al, ah;
je done;
mov dword ptr [edx], 'doow';
test eax, eax;
js skip;
mov dword ptr [edx], 'nnit';
skip:
mov word ptr [edx + 4], 'y';
done:
ret;
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁵ịe“Ṗµ»_⁼“ḣG»$ị“©LẈḊ¶$Ḍ»Ḳ¤
```
A monadic link accepting and returning lists of characters.
**[Try it online!](https://tio.run/##JY2xTsQwDIZfheGkLrzHLbwBQiikVs6QxlHSXFUmjuVOwMzEBgsSE9KhQm8K4kHSFwlOb7E//7b//xq07nOeNvs0PsJ095K@n@M@jpfT5lCm4XUZxwXveIjvZ@lnl4aH@LVIw1Mc0/AZ3/Lf4Xc73X8scz6vFBmoTisvghdqJoBG9wzWUV2jUYxrIUNoGK4omLoIpMutFA5ZYkLTgpMUnC@6Bddya1eoVn5@a9tiCY4UGAr@5PYYSxI0ldNOeMutp04fIw103go2YhZsrsmWBwcSa1yjn/2xVI@NvUFTcjQIW138Aw "Jelly – Try It Online")**
### How?
```
⁵ịe“Ṗµ»_⁼“ḣG»$ị“©LẈḊ¶$Ḍ»Ḳ¤ - Link: list of characters, W e.g. "gone" "leap" "newspaper"
⁵ - literal ten 10
ị - index into (1-based & modular) 'o' 'e' 'n'
“Ṗµ» - compression of characters "int"
e - exists in? 0 0 1
$ - last two links as a monad
“ḣG» - compression of characters "leap"
⁼ - equal? 0 1 0
_ - subtract 0 -1 1
¤ - nilad followed by link(s) as a nilad:
“©LẈḊ¶$Ḍ» - compression of characters "tinny PVC woody"
Ḳ - split at spaces ["tinny","PVC","woody"]
ị - index into (1-based & modular) "woody" "PVC" "tinny"
```
[Answer]
# [Haskell](https://www.haskell.org/), 75 bytes
*-2 bytes thanks to Laikoni.*
```
f"leap"="PVC"
f s|take 2s`elem`words"li ne ti si an re"="tinny"|1>0="woody"
```
[Try it online!](https://tio.run/##TZGxasQwDIb3ewrhqYVS2u7p0rnQqUspnC5REhFHMpZzIeXePTU32PHk75f4/YFHtIm83/feecLgGvf1/eFOPdgt4UTwZmfyNJ9XjZ05zyAEicEYUCBS3k8ssrnb6/tL41bVbnP7jCzQwIzhEx5CZEnwDP3jCfL5ATeokLvDEzjDxXA4MNHst4IhatexDCW4Yrssc8GLLtLVofra1GLkPC6cNSi2ukSrO4FiKpBGHkY7VKdURSjqQKKLwd9RX1vyWitWtFBg09Uf1T2nbAAXlhIJrRYwW5QEs6XXUF@I1HLHV7aDKNe78Rwmlqp9/0b43f8B "Haskell – Try It Online")
RIP `enklact`.
[Answer]
# [Dirty](https://github.com/Ourous/dirty), ~~73~~ ~~57~~ 54 bytes
```
⇖'le'⇗≐∀⭦)Ẃ'nar'⇗{=]}⭨'i'=]'woody'‼␛['tinny'‼␛('PVC'‼␛
```
[Try it online!](https://tio.run/##S8ksKqn8//9R@zT1nFT1R@3TH3VOeNTR8GjtMs2Hu5rU8xKLQILVtrG1j9auUM9Ut41VL8/PT6lUf9Sw59GE2dHqJZl5eTCehnpAmDOU/f//f6Wc1MQCJQA "Dirty – Try It Online")
**Explained:**
*For a similar older version (I'll update it when I stop golfing it)*
```
␛‼'CVP'⇨⇖'leap'⇗≡⊭◌⬅Ẃ'nar'⇗{=]}1ẁ'i'=]'woody'‼␛['tinny'‼␛
```
The body of this is made up of:
```
⇖ put the input into the left stack
'leap' push the string "leap"
⇗ put that string into the right stack
≡ are the left and right stacks equal
⊭ logically negate
◌ skip next instruction if true
⬅ change direction to leftwards
```
If we end up going left, then we have:
```
⇨⇖'leap'⇗≡⊭◌ does stuff to the stacks, but isn't relevant
'CVP' push the string "PVC" (reversed, because we're going left)
‼ print the string on the main stack
␛ exit the program (this should wrap into the other exit, but that isn't working yet)
```
Otherwise, this checks if the string starts with any of "nar":
```
Ẃ wipe the right stack
'nar' push the string "nar"
⇗ move string to right stack
{
= compare the top of the left and right stacks
] goto matching bracket if true
} consuming loop while the right stack is true
```
We then check if the second letter is "i":
```
1 push the number 1
ẁ drop ^ number of elements off of the left stack
'i' push "i"
= are the top of the left and middle stacks equal
] goto matching bracket if true
```
If they all fall through, we run into
```
'woody' push the string "woody"
‼ print the string on the main stack
␛ exit the program
```
If we ended up jumping, we wrap around to
```
[ matching bracket for the goto
'tinny' push the string "tinny"
‼ print the string on the main stack
␛ exit the program
```
[Answer]
## C# 97 Bytes
```
string t(string w)=>w[0]!='p'&new[]{10,9,8,3}.Contains(w.Length)?"tinny":w[0]=='l'?"pvc":"woody";
```
I went looking for a pattern in the length of the strings and found they are unique except for lengths 4 and 8. So I special case those by looking at the first characters. Oh well, it's still shorter than some answers. :)
[Answer]
# [Python](https://docs.python.org/3/), 59 bytes
```
lambda w:"wtPoiVonCdn yy"[(w*4)[9]in"tin"or(w[2]<"b")*2::3]
```
**[Try it online!](https://tio.run/##LVDLboMwEDy3X2H5AkRp1TwuQW0u/YGeekk5GDCwqtm1bBOLRvl2apscVjP7mlmtnt1AeFi6j59FibFuBfMl9@6L4Jvws0U2z/yS@82xuJwqQO5CkMn9ZV@985oXm31ZHqqlI8OctI4BsjzrCWW2ZZkVkxX9SqUc1RyZNtS2gH3kV9FM0xhZTRO2qUQqLTTCQChGCuikaWgyNnW0NC6iG6Af7LrsXNKWhnqJNFn29ziBGqkojXthdcSZvHrYK3BBmdWAMUPprRZBPSYieCrSScPIBlq4gl1tIYGFUf8CJn8lhc6K8vlJm3Brzm9v5Xl3vLOXM7vt7vw1fGcULo8P2rIuYVEUyz8 "Python 3 – Try It Online")**
Uses the indexing from [ovs's Python answer](https://codegolf.stackexchange.com/a/157284/53748) but a simpler and shorter choice function:
If the tenth letter of the word, `w`, with wrapping (`(w*4)[9]` - where `w*4` repeats `w` four times) is a letter in the word **tin** (`in"tin"`) then the word is ***tinny***, otherwise if the third letter (`w[2]`) is an **a** (`<'b'`) then the word is ***PVC*** otherwise the word is ***woody***.
...this 59 does the same job:
```
lambda w:"wtPoiVonCdn yy"[[(w*4)[9]in"tin",2][w[2]<"b"]::3]
```
[Answer]
# C, 107 bytes
```
k;f(char*s){for(k=0;*s;)k+=*s++;k%=100;puts(k-18?(k-5)*(k-81)*(k-56)*(k-78)*(k-37)?"woody":"tinny":"PVC");}
```
[Try it online!](https://tio.run/##fVDLasMwELz7K4yh4AeBmJLG1IQc@gM99a7IsrPY1gqtFOOGfLurmrasL9Vhhxmtdmckd52Uy9LXbSqvwuaU3Vu0aX/a1znVWV@cciqKun86lft9bbyjtN@V1TnUQ5aHWpUrHF5WOFYrPB@zczIhNnPymjjQ@hvfP96SrH4soF08CtBpFt2jOJw2TTrUKlz@UhKeRLdRlBqHmQnGYtOA7ph0E9L7kQkX9LrhDTjwmVJYCC1MCdaUlegt8T6jrGPUXaG70maNc9yastgpjZ7iz20slGpAPmoSZBidcRp@Iq3S@t3JHw0dA7jgML6AZs@0msiI4JJpIiQZ0PDtVklo4Aa0CQOcEYymB03/OVBitRw9li8)
[Answer]
## Batch, 145 bytes
```
@set/ps=
@if %s%==leap echo PVC&exit/b
@for %%s in (a n r)do @if %s:~,1%==%%s echo tinny&exit/b
@if %s:~1,1%==i echo tinny&exit/b
@echo woody
```
Takes input on STDIN. Explanation: After checking for `leap`, tinny words either begin with one of the letters `a`, `n` or `r` or their second letter is `i`.
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 35 bytes
```
1b_856%338<\418=-"woodytinnyPVC"5/=
```
[Try it online!](https://tio.run/##FcxBSwMxEIbh@/yKUvAoS6mVPdiT9@LJkyLZZEhHszMxM9klir99TU8fL3w8/tPN2/dl@N0O08d4erw7Hsent4fDeL7fryKhGTG3l9fn/Wk4b@/8N2xRGEFdVRf7Is6pQS4SAnGExflaZ5ikcoBFEoJ3hXoCsWHxUosiZCwGdqV41X41a4BFIrJU3f3cePGYxGB1mqHJmm50IuvCbiIGxlWz6wq4ribJCAU9BVpIO0wGSnP@IlZI6PI/ "CJam – Try It Online")
I completely forgot that I had started a brute force search for short expressions to hash the woody and tinny strings into two classes. I just found the console window where the search ran and it turns out it actually found something...
### Explanation
```
1b e# Sum the code points of the input string.
e# The result is unique for each input, except "pert" and "wasp" which
e# both sum to 443. But they're both woody, so that's fine.
_ e# Duplicate.
856% e# Take the sum modulo 856.
338< e# Check whether the result is less than 338. That's true for all
e# tinny words.
\ e# Swap with the other copy of the sum.
418= e# Check whether the sum is equal to 418, which identifies "leap".
- e# Subtract. Gives -1 for "leap", 1 for tinny words and 0 for woody words.
"woodytinnyPVC"5/
e# Create the list ["woody" "tinny" "PVC"].
e# Select the correct string.
```
[Answer]
# Excel, 81 bytes
```
=IF(ISNUMBER(FIND(LEFT(A1,2),"anetisilire")),"tinny",IF(A1="leap","PVC","woody"))
```
Using the 'anetisilire' method.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~36~~ 34 bytes
Uses a RegEx from Martin's Retina solution.
```
g2 ¶'a?"PVC":`wÅnyy`ë2Uè`?t|.pe
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=ZzIgtidhPyJQVkMiOmB3kcUIbnl5YOsyVehgiT90fC5wZQ==&input=ImxlYXAi) | [Check all test cases](https://ethproductions.github.io/japt/?v=1.4.5&code=rmcyILYnYT8iUFZDIjpgd5HFCG55eWDrMlroYIk/dHwucGU=&input=WyJnb25lIiwic2F1c2FnZSIsInNlZW1seSIsInByb2RkaW5nIiwidmFjdXVtIiwiYm91bmQiLCJ2b2xlIiwiY2FyaWJvdSIsImludGVyY291cnNlIiwicGVydCIsInRoaWdocyIsImJvdHR5IiwiZXJvZ2Vub3VzIHpvbmUiLCJvY2Vsb3QiLCJ3YXNwIiwieW93bGluZyIsImxpdHRlciBiaW4iLCJuZXdzcGFwZXIiLCJhbnRlbG9wZSIsInJlY2lkaXZpc3QiLCJ0aXQiLCJzaW1wa2lucyIsImxlYXAiXQ==)
[Answer]
# JavaScript, ~~60~~, 50
**EDIT** I saw all the other regex answers. I guess I'm just blind. Anyway, here's one using the same regex
```
i=="leap"?"PVC":/.p.|is*t/.test(i)?"tinny":"woody"
```
Also, now, it beats the other JS answer
Snippet:
```
let test = i => i=="leap"?"PVC":/.p.|is*t/.test(i)?"tinny":"woody"
let woody = `gone
sausage
seemly
prodding
vacuum
bound
vole
caribou
intercourse
pert
thighs
botty
erogenous zone
ocelot
wasp
yowling`;
console.log("THESE SHOULD BE woody");
woody.split("\n").forEach(el => console.log(test(el)));
let tinny = `litter bin
newspaper
antelope
recidivist
tit
simpkins`;
console.log("THESE SHOULD BE tinny");
tinny.split("\n").forEach(el => console.log(test(el)));
console.log("THIS SHOULD BE PVC");
console.log(test("leap"));
```
## Old answer
I didn't see any with regex yet, so I thought I'd give it a try
```
i=="leap"?"PVC":/[gyuz]|[or][tl]|as/.test(i)?"woody":"tinny"
```
Not sure if this counts as 60 or more because I didn't include a return statement. Will add a snippet when I get on my computer
**Edit: Snippet**
```
let test = i => i=="leap"?"PVC":/[gyuz]|[or][tl]|as/.test(i)?"woody":"tinny"
let woody = `gone
sausage
seemly
prodding
vacuum
bound
vole
caribou
intercourse
pert
thighs
botty
erogenous zone
ocelot
wasp
yowling`;
console.log("THESE SHOULD BE woody");
woody.split("\n").forEach(el => console.log(test(el)));
let tinny = `litter bin
newspaper
antelope
recidivist
tit
simpkins`;
console.log("THESE SHOULD BE tinny");
tinny.split("\n").forEach(el => console.log(test(el)));
console.log("THIS SHOULD BE PVC");
console.log(test("leap"));
```
] |
[Question]
[
In this challenge, submissions will be programs or function which, when given an emoticon such as `:-)`, `:(`, or `:D`, will rate their happiness from 0 to 3.
An emoticon will be one of the following:
* `:(`: 0
* `:|`: 1
* `:)`: 2
* `:D`: 3
Emoticons may also have noses (a `-` after the `:`).
Test cases:
```
:( -> 0
:-| -> 1
:D -> 3
:-) -> 2
:| -> 1
```
This is a code golf challenge, shortest answer per language wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 26 bytes
```
lambda s:ord(s[-1])*2%19%4
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRodgqvyhFozha1zBWU8tI1dBS1eR/am5@SWZyfl4xUGE0l4KCkpWuhpIOmFEDpTWhtK6LElcsF1dafpFCqkJmngJcqxVQuqAoM69EI00jVVPzPwA "Python 3 – Try It Online")
$$ f(x) = (2x \bmod 19) \bmod 4 $$
[Answer]
# [Ruby](https://www.ruby-lang.org/), 20 bytes
`s[-1].ord` will give us the codepoint of the last character in the string, which we can then plug into this formula:
$$(160 \bmod c) \bmod 7 $$
```
->s{160%s[-1].ord%7}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf16642tDMQLU4WtcwVi@/KEXVvPZ/QWlJsUJatJKVhlIsF5xTg8zRROa4IHN0UTTpoujSRdGmC9T3HwA "Ruby – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~11~~ 8 bytes
*3 bytes saved thanks to @Bubbler!*
```
⊃'(|)'⍳⌽
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OA5KOuZnWNGk31R72bH/Xs/f8/TUHdSkOdC0TVQChdKK0JoVygoi7qAA)
```
‚åΩ reverse the string
⊃ take the last (now first) byte
'(|)'‚ç≥ index inside '(|)' (if not found ('D') returns the length (3))
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~28~~ 27 bytes
```
lambda e:"(|)D".find(e[-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIdVKSaNG00VJLy0zL0UjNVrXMFbzf2pufklmcn5eMVBlNJeSlaaSDpDUdQFTNRCOhhJXLBdXWn6RQqpCZp4CXIsVl4JCQVFmXolGmkaqpuZ/AA "Python 3 – Try It Online")
Because we don't care about the eyes/nose, we can just look at the mouth (the last character) and find its index in a string with all the mouths, ordered from saddest to happiest :) Thanks @Surculose Sputum!
[Answer]
# [Python 3](https://docs.python.org/3/), 25 bytes
```
lambda s:160%ord(s[-1])%7
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRodjK0MxANb8oRaM4WtcwVlPV/H9BUWZeiUaaRmZeQWmJhqam5n8rXRcA "Python 3 – Try It Online")
Math taken from @dingledooper
[Answer]
## Excel, 25 bytes
```
=FIND(RIGHT(A1),"(|)D")-1
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~ 37 ~~ 33 bytes
*Saved 4 bytes on both versions thanks to @ceilingcat and @dingledooper*
I overlooked the rule about the optional nose, so this is not as effective as expected.
```
f(char*s){s=390%~-s[*++s%9<1]&3;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NIzkjsUirWLO62NbY0kC1Trc4Wktbu1jV0sYwVs3YuvZ/WX5mikJuYmaehqZCNZeCQkFRZl5JmgaQpaCgpJqigA0p6YCl0zSUrDSUNBEcXRReDYoUCk8TRQqF54IiBeQBOZrWXLX//yWn5SSmF//XLQcA "C (gcc) – Try It Online")
### How?
Among the characters that we have to deal with, the hyphen is the only one whose ASCII code is congruent to \$0\$ modulo \$9\$. We use this property to decide whether we need to work on the second or the third character.
Given the ASCII code \$n\$ of the relevant smiley character, we apply the following formula to get the happiness:
$$h(n)=(390\bmod (n-1))\bmod 4$$
---
# [C (gcc)](https://gcc.gnu.org/), ~~ 36 ~~ 32 bytes
Using [Uriel's formula](https://codegolf.stackexchange.com/a/202898/58563) is 1 byte shorter.
```
f(char*s){s=s[*++s%9<1]*2%19&3;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NIzkjsUirWLO62LY4Wktbu1jV0sYwVstI1dBSzdi69n9ZfmaKQm5iZp6GpkI1l4JCQVFmXkmaBpCloKCkmqKADSnpgKXTNJSsNJQ0ERxdFF4NihQKTxNFCoXngiIF5AE5mtZctf//JaflJKYX/9ctBwA "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁽$9,4ḥ’
```
A monadic Link accepting a list of characters which yields an integer in \$[0,3]\$.
**[Try it online!](https://tio.run/##y0rNyan8//9R414VSx2ThzuWPmqY@f//fysXAA "Jelly – Try It Online")**
### How?
```
⁽$9,4ḥ’ - Link: list of characters, A
‚ÅΩ$9 - base 250 literal = 10058
,4 - pair with four
ḥ - Jelly hash A using 10058 as a salt and [1,2,3,4] as the domain
’ - decrement
```
---
Previous **8** byter:
```
“|)D”iⱮS
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5waTZdHDXMzH21cF/z//38rFwA "Jelly – Try It Online")
### How?
```
“|)D”iⱮS - Link: list of characters, A e.g. ":-)" OR ":-("
Ɱ - map across c in A with:
i - first index of c in (or 0 if not found):
“|)D” - list of characters = "|)D" [0,0,2] [0,0,0]
S - sum 2 0
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 19 bytes
```
{TR:d/(|)D:-/0123/}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OiTIKkVfo0bTxUpX38DQyFi/9n9xYqWCHlA2Lb9IISczL7X4v5UGl5VuDZeVC5DS5LKqAQA "Perl 6 – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 17 bytes
```
tr '(|)D:-' 0-3\
```
[Try it online!](https://tio.run/##S0oszvj/v6RIQV2jRtPFSlddwUDXOEbh/38rDS4r3RouKxcgpcllVQMA "Bash – Try It Online")
*Note: There's a space character after the backslash.*
Input on stdin, output on stdout.
The challenge doesn't specify the format of the output. Depending on the input, this program may print the output in either %2d or %3d format (that is, with one or two spaces before the 0, 1, 2, or 3).
If that's not acceptable, then
`tr -s '(|)D:-' 0-3\`
**(20 bytes)** always prints the digit in %2d format. (There's a space after the backslash here too.)
Or
`tr '(|)D:-' 0-4|tr -d 4`
**(23 bytes)** prints just the digit (with no spaces).
[Answer]
# Mornington Crescent, 1820 bytes
[Try it online!](https://tio.run/##vZXBTsJAEIbvPsWeNB7wAbxJPZgIprHofbIdYcJ2BqeDiU@Pi0ATpG2KBS497P91@v8zu9tClImnJjzwiqVHttVqAnN0L6I2Q2U3IkZn4kZIHktDddnnEhSvjsFS8h5yCuG7AidL5QVFbQTcl@rl7QBLZqCxKS5RKcvuzDA@NIhUzO@Cy0wRrQFJIc83/W8Aunyni9@xiE7BtpETUh@wQRyjqSwkkMFe3vAhbO46TsKoQG2Bn6Obm3LjJ@a/izHZK2y9vZM3UYIKz/AL2WW0nkwTs1uo9d8qDoHntcITFDFGWZDNavUEmIX35nfyCt3NPcb2aMxZEW@Lgnjdsga9f4X/9/wh5I2bbU/rv9fSeG3F4@NeBfIW7PAs9qmWEvMpXJ3hoLSX/DOLdvis0S/TwqPy1lyau79jfGX3d7wf3P4A)
A port of @dingledooper's fantastic Ruby answer, which just so happens to work seamlessly in Mornington Crescent because of a convenient `7` in it. Props to them!
```
Take Northern Line to Leicester Square
Take Northern Line to Leicester Square
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Leicester Square
Take Northern Line to Leicester Square
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Bakerloo Line to Baker Street
Take Bakerloo Line to Paddington
Take Bakerloo Line to Charing Cross
Take Bakerloo Line to Charing Cross
Take Northern Line to Moorgate
Take Circle Line to Moorgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to King's Cross St. Pancras
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Aldgate
Take Circle Line to Aldgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Baker Street
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Pinner
Take Metropolitan Line to Preston Road
Take Metropolitan Line to King's Cross St. Pancras
Take Victoria Line to Seven Sisters
Take Victoria Line to King's Cross St. Pancras
Take Circle Line to King's Cross St. Pancras
Take Metropolitan Line to Pinner
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Pinner
Take Metropolitan Line to Preston Road
Take Metropolitan Line to King's Cross St. Pancras
Take Circle Line to King's Cross St. Pancras
Take Northern Line to Mornington Crescent
```
The only major thing I feel I need to point out is how I got `160` in the program. To do this, I took the first letter of `Paddington`, which gives an ASCII value of `80` when run through Charing Cross, then multiplied it by `2` in Chalfont & Latimer to get `160`. Subsequently, the program computes `160 % (ASCII of last character) % 7` via Preston Road, the formula found by @dingledooper.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~16~~ 12 bytes
```
T`-:(|)D`__d
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyRB10qjRtMlIT4@5f9/K00uK10XLqsaIKUBxEAukKcL5GoAAA "Retina 0.8.2 – Try It Online")
```
T`
```
Enter transliteration mode
```
(|)D`d
```
Replace the mouth character with the corresponding digit (0 to 3)
```
-:`__
```
Remove each of `-` and `:` from the string.
Implicitly output the result, which will be a single digit.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
'|)D'jmfs
```
[Try it online!](https://tio.run/##y00syfn/X71G00U9Kzet@P9/K10XAA "MATL – Try It Online")
### Explanation
```
'|)D' % Push this string
j % Read input as unevaluated string
m % ismember: true for chars of the first string that are present in the second
f % find: (1-based) indices of true entries. The result will have length 0 or 1
s % sum. This is needed to transform an empty array into 0
% Implicitly display
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-hr`, 18 bytes
```
?^‚뵬¶P0|\üÑÉ1|R2|\¬¶3‚Ñ¢
```
[Try it online!](https://tio.run/##y05N///fPu7RxK2HlgUY1MR8mN/SbFgTZFQTc2iZ8aOWRf//W@mCgOZ/3YwiAA "Keg – Try It Online")
The same switch statement format, but with a different character checking criteria.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
θÇx19%4%
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3I7D7RWGlqomqv//W7kAAA "05AB1E – Try It Online")
### Explanation
I used Uriel's formula.
```
θ # Get mouth (last char)
Ç # ASCII value
x # Multiply by 2
19% # Modulo 19
4% # Modulo 4
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 24 bytes
```
s/.*(.)/ord($1)*2%19%4/e
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX09LQ09TP78oRUPFUFPLSNXQUtVEP/X/fysNLivdGi4rFyClyWVV8y@/oCQzP6/4v25BDgA "Perl 5 – Try It Online")
Steals the math from @Uriel's Python answer
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
I⌕(|)D§S±¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zL0VDSaNG00VJR8GxxDMvJbVCwzOvoLQkuASoKl1DU0fBLzU9sSRVw1ATBKz//7fS1fyvW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
§ Cyclically indexed by
¬π Literal 1
± Negated
‚åï Find index in
(|)D Literal string of mouths
I Cast to string
Implicitly print
```
[Answer]
# [Io](http://iolanguage.org/), 31 bytes
Io's strings are made of integers, so character-converting is unneccecary. Although Io doesn't allow us to index the last item of a sequence using `last()`...
```
method(x,160%x reverse at(0)%7)
```
[Try it online!](https://tio.run/##y8z/n5FYUFCpYGWrEPM/N7UkIz9Fo0LH0MxAtUKhKLUstag4VSGxRMNAU9VcE6JUQ8lKV1NJU6GgKDOv5D8A "Io – Try It Online")
[Answer]
# [naz](https://github.com/sporeball/naz), 120 bytes
```
8a5m2x1v1a2x2v4a2x3v9a9a5a2x4v1x1f2r3x3v1e2f0x1x2f3x1v3e3x2v5e3x4v6e4f0x1x3f0m1o0x1x4f0m1a1o0x1x5f0m2a1o0x1x6f0m3a1o0x1f
```
**Explanation** (with `0x` commands removed)
```
8a5m2x1v # Set variable 1 equal to 40 ("(")
1a2x2v # Set variable 2 equal to 41 (")")
4a2x3v # Set variable 3 equal to 45 ("-")
9a9a5a2x4v # Set variable 4 equal to 68 ("D")
1x1f # Function 1
2r # Read the second byte in the input string, removing it
3x3v1e # Jump back to the start of the function if it equals variable 3
2f # Otherwise, jump to function 2
1x2f # Function 2
3x1v3e # Jump to function 3 if the register equals variable 1
3x2v5e # Jump to function 5 if the register equals variable 2
3x4v6e # Jump to function 6 if the register equals variable 4
4f # Otherwise, jump to function 4
1x3f # Function 3
0m1o # Output 0
1x4f # Function 4
0m1a1o # Output 1
1x5f # Function 5
0m2a1o # Output 2
1x6f # Function 6
0m3a1o # Output 3
1f # Call function 1
```
[Answer]
# [Red](http://www.red-lang.org), 32 bytes
```
func[s][select"(0|1)2D3"last s]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85ujg2ujg1JzW5REnDoMZQ08jFWCknsbhEoTiW639aflFqYnKGQmpuflZmNJcCEChZaShBGbo1MJYLXEgTxgLKxUJ0FBRl5pUoRBckpigAzcuFGKZgrKCka6ekkAbhxnLF/gcA "Red – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~17~~ 14 bytes
Turns out Ranges finally started to actually exist and work! Thanks to an anonymous user for pointing this out (by proposing an edit, but anonymous users cannot comment...)
```
s=>160%s[^1]%7
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrqOQmVdip@CmYKvwv9jWztDMQLU4Os4wVtX8vzVXAFBFiYabhpKVhpKmJjK/Bo2vicZ3QeProhugi26CLroRumAz/gMA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
x"(|)D"e
```
[Try it online!](https://tio.run/##K6gsyfj/v0JJo0bTRSn1/38lKxclAA "Pyth – Try It Online")
### Exalanation
```
x"(|)D"e
: Implicit evaluated input
e : Last element of input
"(|)D" : The string "(|)D"
x : First occurrence of the last element of input in "(|)D"
```
[Answer]
# JavaScript, ~~35~~ ~~32~~ 29 bytes
I based the logic off of the Java solution submitted April 2 and edited April 8, by branboyer. I suppose it would be referred to as a port of their answer, but I don’t know exactly how that’s supposed to be marked.
```
a=>"(|)D".indexOf(a[2]||a[1])
```
An anonymous function, taking a string and returning an integer. Please help me shorten it further, I’m new to golfing code. Just the code, without the way of inputting (no idea how to get input in try it online) is at this [Try it online link](https://tio.run/#%23y0osSyxOLsosKNFNSkxKzdHNy09J/Z9m@z/R1k5Jo0bTRUkvMy8ltcI/TSMxOlEvJzUvvSRD1zBW839yfl5xfk6qXk5@ukaahpKVhpKmpoKCvr6CARe6lG4NSA4oZYgh5QLTZYypSxOqywhDqgamy/A/AA)
[Answer]
# [International Phonetic Esoteric Language](https://esolangs.org/wiki/International_Phonetic_Esoteric_Language), 11 bytes
```
i Å2f{J}‚±±4‚±±o
```
Based on [Uriel's formula](https://codegolf.stackexchange.com/a/202898/77309).
```
i Å2f{J}‚±±4‚±±o
i Å (split the face into it's ord values)
2f (mouth * 2)
{J}‚±± (mod 19) (base 26)
4‚±± (mod 4)
o (print)
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), 20 bytes
```
y/(|)D/0123/;s/:-*//
```
Pretty self explanatory. Replaces the the "mouth" characters with numbers using the `y///` transform command and then strips off the eyes and the nose if they exist.
[Try it online!](https://tio.run/##Dco7CoAwEAXAfk@xgkUiLM9Pt0KqFN7BT6VolSYIEXL3mGqaidcpd3jLQxEtWByDUvlgsvXoh3HCHKHSAWWhVNMWAIKsh9vRRDCYUdSQSib1FUuafw "sed – Try It Online")
This is one byte longer, but perhaps it gets bonus points for having an emoticon in the code itself? `:-\`
```
y/(|)D/0123/;s/:-\?//
```
The shorter solution (16 bytes)
```
y/(|)D:-/0123 /
```
also works, but adds extra whitespace to each line of output. It also has two emoticons `D:` and `:-/`. :)
[Try it online!](https://tio.run/##K05N0U3PK/2fwVWsr6KvoGunoM9V8b9SX6NG08VKV9/A0MhYQUH/vwdXBVBBTJ6@Ppe@bnScXay@YrG@gj5IykqDy0q3hsvKBUhpclnVAAA "sed – Try It Online")
[Answer]
# batch, ~~109 bytes~~ 99 bytes
```
@For %%G in ("(=0",")=2","D=3","|=1")Do @Set %%G
@Set "T=%~1"
@<Nul Call Call Set/P"=%%%T:~-1%%%"
```
[![output (TIO unavailable)](https://i.stack.imgur.com/cC57c.png)](https://i.stack.imgur.com/cC57c.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
"(|)D"bUÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Iih8KUQiYlXM&input=IjooIg)
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 32 bytes
The verbosity offseted the bytecount.
```
h(I)->160rem lists:last(I)rem 7.
```
[Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/U/Q8NTU9fO0MygKDVXISezuKTYKiexuAQoChIw1/ufm5iZpxEdq6mga8elAASZ@VblRZklqRoZGkpWuppKmpp6/wE "Erlang (escript) – Try It Online")
[Answer]
# [W](https://github.com/A-ee/w), 7 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
```
☻M:ù·±♥
```
Uncompressed:
```
(|)D"azx
```
## Explanation
```
% Implicit quote
(|)D" % The string "(|)D"
az % The last item of the input
x % Where is ^ in the above string?
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 11 bytes
```
)3?11%2/(p;
```
I'm convinced my method is the smallest possible, but this isn't the best possible one - just one of the earliest low-value ones.
```
)3?11%2/(p;
) #Pop the last element of the string (as ascii value)
3? #Cube the number
11% #Modulo 11
2/ #Divide by 2 (round down)
( #Decrement by one (gotta be 0 1 2 3, not 1 2 3 4)
p; #Print the value we want, and shunt the rest of the stack
```
I used [the following TIO](https://tio.run/##XVFRS8MwEH7vrzhSB07HGIgIDhHZFPYwFHxUH7Lmuh5kSUhS5pz97fXaKu3MS467@@77vrut1XnIPLlY19e3NIf@pStDkaSmLwSC3HqwZQRtrUvexLkQ30KMhViKD0ifvUKPCh5eF6tVcoSTlz47NB0OYHpSWZZOUyYj8mgP0nt5mLRMsaDwB6HxQBeLyjzK0EjaHMAa5I4TwvSJ8SizAlDjDk0EMv34pGkZv/fzXqxjNoTI/y9gAoojFtXkC2m2ZLYgRAu9uu@JFuUG2ySN@uTaKiDOVqOhprV0nadoey2wR3Do2e@Od8dk7EpmkawJUDprmnVNz@4GB8m7IR2ag2B9ZKjUvBLVeDvSpauO84ry1punxn6EPcWCFxaidJr7rWmtoVETsBz5PTF1KErulkaBR4cyJtW/Oy605bb2Kjez2cWw9PiJWckb4zxE2mGo6x8 "GolfScript – Try It Online") to search for answers, and 11 popped up quite early. I also tried squares and higher powers, but they weren't as clean and short.
[Try it online!](https://tio.run/##S8/PSStOLsosKPmvZKXrovRf09je0FDVSF@jwPr/fwA "GolfScript – Try It Online")
[Every case!](https://tio.run/##S8/PSStOLsosKPn/P1rJSkNJQcmqBkRogggXEKELFtQFi@qChXVdlGK5qrm4NI3tDQ1VjfQ1Cqy5uGpVuf5z/QcA "GolfScript – Try It Online")
] |
[Question]
[
An [EAN-8](https://en.wikipedia.org/wiki/EAN-8) barcode includes 7 digits of information and an 8th checksum digit.
The checksum is calculated by multiplying the digits by 3 and 1 alternately, adding the results, and subtracting from the next multiple of 10.
For example, given the digits `2103498`:
```
Digit: 2 1 0 3 4 9 8
Multiplier: 3 1 3 1 3 1 3
Result: 6 1 0 3 12 9 24
```
The sum of these resulting digits is **55**, so the checksum digit is **60 - 55 = 5**
---
# The Challenge
Your task is to, given an 8 digit barcode, verify if it is valid - returning a truthy value if the checksum is valid, and falsy otherwise.
* You may take input in any of the following forms:
+ A string, 8 characters in length, representing the barcode digits
+ A list of 8 integers, the barcode's digits
+ A non-negative integer (you can either assume leading zeroes where none are given, i.e. `1` = `00000001`, or request input with the zeroes given)
* Builtins that compute the EAN-8 checksum (i.e, take the first 7 digits and calculate the last) are banned.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) wins!
---
# Test Cases
```
20378240 -> True
33765129 -> True
77234575 -> True
00000000 -> True
21034984 -> False
69165430 -> False
11965421 -> False
12345678 -> False
```
[Answer]
# JavaScript (ES6), ~~41~~ ~~40~~ 38 bytes
*Saved 2 bytes thanks to @ETHProductions and 1 byte thanks to @Craig Ayre.*
```
s=>s.map(e=>t+=e*(i^=2),t=i=1)|t%10==1
```
Takes input as a list of digits.
Determines the sum of all digits, including the checksum.
If the sum is a multiple of 10, then it's a valid barcode.
**Test Cases**
```
let f=
s=>s.map(e=>t+=e*(i^=2),t=i=1)|t%10==1
console.log(f([2,0,3,7,8,2,4,0]));
console.log(f([3,3,7,6,5,1,2,9]));
console.log(f([7,7,2,3,4,5,7,5]));
console.log(f([0,0,0,0,0,0,0,0]));
console.log(f([2,1,0,3,4,9,8,4]));
console.log(f([6,9,1,6,5,4,3,0]));
console.log(f([1,1,9,6,5,4,2,1]));
console.log(f([1,2,3,4,5,6,7,8]));
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 48 35 29 bytes
[mypetlion](https://codegolf.stackexchange.com/users/65255/mypetlion) saved 19 bytes
```
lambda x:sum(x[::2]*2+x)%10<1
```
[Try it online!](https://tio.run/##Vc5LDoIwEADQtT1FNyags2hLAWnkJNgYVIgk8gmtCZ6@jhQxZlbz5ju87L3vhKvzk3uU7eVW0kmZZxtMhVJC78R@CrecHbmzlbHna2kqQ3NakE0hgEEEKRxAgASmgSJGMyUQA0fOPKZIAgsSOYXYI4O/8ChwjM2dGe6VHhNM@LxTYgk70ThKthgOLfY9knze0kQTUvcjXT@nTfdLjCJ0GJvOBnWwYhi6Nw "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
m2Ḥ+µS⁵ḍ
```
**[Try the test suite.](https://tio.run/##y0rNyan8/z/X6OGOJdqHtgY/atz6cEfv/8Ptj5rWuP//Hx1tpKNgoKNgrKNgrqNgoaMA5JoARWJ1uLiijWHiZjoKpjoKhmBZS7CUOVjcCKzABCwL5JqCpSB6jcDqDWAKLMGGm4ClzMBcQ5ixJmA1EF2GYHFLJCmQOTApZOvMIA6O5YoFAA "Jelly – Try It Online")**
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JḂḤ‘×µS⁵ḍ
```
**[Try it online](https://tio.run/##y0rNyan8/9/r4Y6mhzuWPGqYcXj6oa3Bjxq3PtzR@///f2MdBSAy11Ew01Ew1VEw1FEw0lGwBAA)** or **[Try the test suite.](https://tio.run/##y0rNyan8/9/r4Y6mhzuWPGqYcXj6oa3Bjxq3PtzR@/9w@6OmNe7//0dHG@koGOgoGOsomOsoWOgoALkmQJFYHS6uaGOYuJmOgqmOgiFY1hIsZQ4WNwIrMAHLArmmYCmIXiOwegOYAkuw4SZgKTMw1xBmrAlYDUSXIVjcEkkKZA5MCtk6M4iDY7liAQ "Jelly – Try It Online")**
## How this works
```
m2Ḥ+µS⁵ḍ ~ Full program.
m2 ~ Modular 2. Return every second element of the input.
Ḥ ~ Double each.
+µ ~ Append the input and start a new monadic chain.
S ~ Sum.
⁵ḍ ~ Is divisible by 10?
```
```
JḂḤ‘×µS⁵ḍ ~ Full program (monadic).
J ~ 1-indexed length range.
Ḃ ~ Bit; Modulo each number in the range above by 2.
Ḥ ~ Double each.
‘ ~ Increment each.
× ~ Pairwise multiplication with the input.
µ ~ Starts a new monadic chain.
S ~ Sum.
⁵ḍ ~ Is the sum divisible by 10?
```
The result for the first 7 digits of the barcode and the checksum digit **must** add to a multiple of **10** for it to be valid. Thus, the checksum is valid iff the algorithm applied to the *whole* list is divisible by **10**.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
*Thanks to [@Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb) for pointing out a mistake, now corrected.*
```
IlhY"s10\~
```
[Try it online!](https://tio.run/##y00syfn/3zMnI1Kp2NAgpu7//2gjBUMFAwVjBRMFSwULBdNYAA) Or [verify all test cases](https://tio.run/##Vc4xDoAgFAPQ3VM0nuCDCLK7uLsYNNHNASedvToWooNh@X1pGo7timlNQ9yn@lQy36kfU9AQNHDooGEgSxWaki1aKJqnOGZNNTSHliL4PYpmW0rHc8tQLC9Vdgw9dxSzf4X9It@uzX9YHg).
### Explanation
```
Ilh % Push [1 3]
Y" % Implicit input. Run-length decoding. For each entry in the
% first input, this produces as many copies as indicated by
% the corresponding entry of the second input. Entries of
% the second input are reused cyclically
s % Sum of array
10\ % Modulo 10
~ % Logical negate. Implicit display
```
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~16~~ 14 bytes
Saved 2 bytes by skipping the second part using `j` instead of `;`s, as well as swapping a `~` and `+` in the first part to get rid of a `+` in the second.
```
~3*+~+6jq!%a+2
```
Input is in 8 digits (with leading 0s if applicable) and nothing else.
Outputs via exit code (open the debug dropdown on TIO), where 1 is true and 0 is false.
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@vM9bSrtM2yypUVE3UNvr/39zcyNjE1NwUAA "Befunge-98 (PyFunge) – Try It Online")
## Explanation
This program uses a variety of tricks.
First of all, it takes the digits in one by one through their ASCII values. Normally, this would require subtracting 48 from each value as we read it from the input. However, if we don't modify it, we are left with 16 (3+1+3+1+3+1+3+1) extra copies of 48 in our sum, meaning our total is going to be 768 greater than what it "should" be. Since we are only concerned with the sum mod 10, we can just add 2 to the sum later. Thus, we can take in raw ASCII values, saving 6 bytes or so.
Secondly, this code only checks if every other character is an EOF, because the input is guaranteed to be only 8 characters long.
~~Thirdly, the `#` at the end of the line doesn't skip the first character, but will skip the `;` if coming from the other direction. This is better than putting a `#;` at the front instead.~~
Because the second part of our program is only run once, we don't have to set it up so that it would skip the first half when running backwards. This lets us use the jump command to jump over the second half, as we exit before executing it going backwards.
### Step by step
Note: "Odd" and "Even" characters are based on a 0-indexed system. The first character is an even one, with index 0.
```
~3*+~+ Main loop - sum the digits (with multiplication)
~ If we've reached EOF, reverse; otherwise take char input. This will always
be evenly indexed values, as we take in 2 characters every loop.
3*+ Multiply the even character by 3 and add it to the sum.
~ Then, take an odd digit - we don't have to worry about EOF because
the input is always 8 characters.
+ And add it to the sum.
6j Jump over the second part - We only want to run it going backwards.
q!%a+2 The aftermath (get it? after-MATH?)
+2 Add 2 to the sum to make up for the offset due to reading ASCII
%a Mods the result by 10 - only 0 if the bar code is valid
! Logical not the result, turning 0s into 1s and anything else into 0s
q Prints the top via exit code and exits
```
[Answer]
# C, ~~78~~ 77 bytes
```
i,s,c,d=10;f(b){for(i=s=0,c=b%d;b/=d;)s+=b%d*(3-i++%2*2);return(d-s%d)%d==c;}
```
[Try it online!](https://tio.run/##dc5NDoMgEAXgvacwJiSgmPInaAg36aZCaVjUNmhXxrNbTd1VZjfzvmSerR/WrmvAI7bYGUq0hz2a/SvCYEZDsDU9cLq/GKfRWO1LCXkdqgqwkiEd79MnDtDVI3AIOGOsXtYwTPnzFgaIsjnLt3nH7eRhAdx1KHDuISNctUwQhPQ54FzJhrIuCZRiXDSqOQMHIcfsJFGDEi66ViS/yI7KRvB0T0q7DTD6D37xXlKqdo@X9Qs)
# C (gcc), 72 bytes
```
i,s,c,d=10;f(b){for(i=s=0,c=b%d;b/=d;)s+=b%d*(i++%2?:3);b=(d-s%d)%d==c;}
```
[Try it online!](https://tio.run/##dc5NCoMwEAXgvacQIZDUSPMfbQi9SDc1ISWL2mK6E8@eKnVXnd3M@2Ceax7O5Rxxwg57S4kJsEdTeI0w2mQJdrYH3vRn6w1K9bqcYKxrwK4XjkxvoW8S8Ah4a52Zcxw@5fMeB4iKqSiXeY/LKcAK@NtQ4TJARrhumSAImX3AuVaSsu4QaM24kFrugY2QbVZyUIMSLrpWHH5RHVVS8OOelHYLYPQf/OK1pNLtGs/5Cw)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~26~~ 21 bytes
```
10∣(2-9^Range@8).#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/vf0OBRx2INI13LuKDEvPRUBwtNPWW1/wFFmXkl0UAFCvoOCtVcCgrVRjoKBjoKxjoK5joKFjoKQK4JUKRWRwEkaQyTMdNRMNVRMATLW0IlzcEyRmAlJmB5INcUKmkANhYdQSWNwEYZwHRagm02gUqagQUMYXaagFXBdBqCZSyRJEFmISSRXWMG8VNtbex/AA "Wolfram Language (Mathematica) – Try It Online")
Takes input as a list of 8 digits.
## How it works
`2-9^Range@8` is congruent modulo 10 to `2-(-1)^Range@8`, which is `{3,1,3,1,3,1,3,1}`. We take the dot product of this list with the input, and check if the result is divisible by 10.
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes and non-competing
```
Check[#~BarcodeImage~"EAN8";1,0]&
```
[Try it online!](https://tio.run/##LcvLCsIwFATQXwkRXBXMzc0TEXzgwo24L12EmNoiqVDiSuyvx6Y4q8MwE13qQnSp9y6372GXT13wz3o1Hd3oX/dwie4RJno@XA3dQsWadb6N/ZDqeUw2e/KhnKE2XDBaEYqolQRui7XmKKQsZP8Uc2AorBHFyoKSApcewM7msLg8lTb02@Qf "Wolfram Language (Mathematica) – Try It Online")
Takes input as a string. Returns `1` for valid barcodes and `0` for invalid ones.
## How it works
The best thing I could find in the way of a built-in (since Mathematica is all about those).
The inside bit, `#~BarcodeImage~"EAN8";1`, generates an image of the EAN8 barcode, then ignores it entirely and evaluates to 1. However, if the barcode is invalid, then `BarcodeImage` generates a warning, which `Check` catches, returning 0 in that case.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
s2Sḅ3⁵ḍ
```
[Try it online!](https://tio.run/##y0rNyan8/7/YKPjhjlbjR41bH@7o/f9w9xa3sEdNa4otDrcDKff//9XV1bmMDIzNLYxMDLiMjc3NTA2NLLnMzY2MTUzNTbkMoICLy8jQwNjE0sKEy8zS0MzUxNiAy9DQEsgwMuQyBCk2M7fgAhoGAA "Jelly – Try It Online")
### How it works
```
s2Sḅ3⁵ḍ Main link. Argument: [a,b,c,d,e,f,g,h] (digit array)
s2 Split into chunks of length 2, yielding [[a,b], [c,d], [e,f], [g,h]].
S Take the sum of the pairs, yielding [a+c+e+g, b+d+f+h].
ḅ3 Convert from ternary to integer, yielding 3(a+c+e+g) + (b+d+f+h).
⁵ḍ Test if the result is divisible by 10.
```
[Answer]
# [Haskell](https://www.haskell.org/), 40 38 bytes
```
a=3:1:a
f x=mod(sum$zipWith(*)a x)10<1
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjY3P0WjuDRXpSqzIDyzJENDS1MjuTI5JzXaWMcwVrNC09DAxvB/bmJmnoKtQkFpSXBJkU@egopCcUZ@OZBKU4g20jHQMdYx17HQMdIx0TGI/Q8A "Haskell – Try It Online")
Takes input as a list of 8 integers. A practical example of using infinite lists.
Edit: Saved 2 bytes thanks to GolfWolf
[Answer]
# Java 8, ~~58~~ ~~56~~ 55 bytes
```
a->{int r=0,m=1;for(int i:a)r+=(m^=2)*i;return r%10<1;}
```
-2 bytes indirectly thanks to *@RickHitchcock*, by using `(m=4-m)*i` instead of `m++%2*2*i+i` after seeing it in his [JavaScript answer](https://codegolf.stackexchange.com/a/148200/52210).
-1 byte indirectly thanks to *@ETHProductions* (and *@RickHitchcock*), by using `(m^=2)*i` instead of `(m=4-m)*i`.
**Explanation:**
[Try it here.](https://tio.run/##ldFPT4MwFADw@z7Fu5iAvhHKGIiI38BddjSadKwzndCSUmYM4bPjo5tLvLEUDuXxe3/aIz/xpW6EOu6/xrLibQuvXKp@ASCVFebASwGbaQuw07oSXEHpUejtHbif0/eBXnpay60sYQMKChj58qWnn8AUIdYFyw/aTAjkE/fNQ@HVH0Xk38vcCNsZBeaOhc8sH8b8nKzpdhUlu@Q8abmHmrryttZI9elKn1va/rRW1IHubNBQyFbKU0HpKfENrsc@whBXmOIjRhhjOPiu5xlw5ViCa2REs/kwJRYRjommuJ4PQ/y3rnDuoMyNGmNGw8bzyyYEmBs0Jn7DCTFi2QVS9Vvg3/kk081c4LAYxl8)
```
a->{ // Method with integer-array parameter and boolean return-type
int r=0, // Result-sum
m=1; // Multiplier
for(int i:a) // Loop over the input-array
r+= // Add to the result-sum:
(m^=2) // Either 3 or 1,
*i; // multiplied by the digit
// End of loop (implicit / single-line body)
return r%10<1; // Return if the trailing digit is a 0
} // End of method
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
θ¹¨3X‚7∍*O(T%Q
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3I5DOw@tMI541DDL/FFHr5a/Rohq4P//0cY6CkBkrqNgpqNgqqNgqKNgpKNgGQsA "05AB1E – Try It Online")
Needs leading `0`s, takes list of digits.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
!es+*2%2
```
**[Verify all the test cases!](https://pyth.herokuapp.com/?code=%21es%2B%2a2%252&test_suite=1&test_suite_input=%5B2%2C+0%2C+3%2C+7%2C+8%2C+2%2C+4%2C+0%5D%0A%0A%5B3%2C+3%2C+7%2C+6%2C+5%2C+1%2C+2%2C+9%5D%0A%0A%5B7%2C+7%2C+2%2C+3%2C+4%2C+5%2C+7%2C+5%5D%0A%0A%5B0%5D%0A%0A%5B2%2C+1%2C+0%2C+3%2C+4%2C+9%2C+8%2C+4%5D%0A%0A%5B6%2C+9%2C+1%2C+6%2C+5%2C+4%2C+3%2C+0%5D%0A%0A%5B1%2C+1%2C+9%2C+6%2C+5%2C+4%2C+2%2C+1%5D%0A%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%5D%0A&debug=0&input_size=2)**
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
If we can assume the input always has exactly 8 digits:
```
!es.e*bhy%hk2
```
**[Verify all the test cases!](https://pyth.herokuapp.com/?code=%21es.e%2abhy%25hk2&test_suite=1&test_suite_input=%5B2%2C+0%2C+3%2C+7%2C+8%2C+2%2C+4%2C+0%5D%0A%0A%5B3%2C+3%2C+7%2C+6%2C+5%2C+1%2C+2%2C+9%5D%0A%0A%5B7%2C+7%2C+2%2C+3%2C+4%2C+5%2C+7%2C+5%5D%0A%0A%5B0%5D%0A%0A%5B2%2C+1%2C+0%2C+3%2C+4%2C+9%2C+8%2C+4%5D%0A%0A%5B6%2C+9%2C+1%2C+6%2C+5%2C+4%2C+3%2C+0%5D%0A%0A%5B1%2C+1%2C+9%2C+6%2C+5%2C+4%2C+2%2C+1%5D%0A%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%5D%0A&debug=0&input_size=2)**
---
# How does this work?
```
!es+*2%2 ~ Full program.
%2 ~ Input[::2]. Every second element of the input.
*2 ~ Double (repeat list twice).
+ ~ Append the input.
s ~ Sum.
e ~ Last digit.
! ~ Logical NOT.
```
```
!es.e*sbhy%hk2 ~ Full program.
~ Convert the input to a String.
.e ~ Enumerated map, storing the current value in b and the index in k.
%hk2 ~ Inverted parity of the index. (k + 1) % 2.
hy ~ Double, increment. This maps odd integers to 1 and even ones to 3.
b ~ The current digit.
* ~ Multiply.
s ~ Sum.
e ~ Last digit.
! ~ Logical negation.
```
If the sum of the first 7 digit after being applied the algorithm is subtracted from **10** and then compared to the last digit, this is equivalent to checking whether the sum of all the digits, after the algorithm is applied is a multiple of **10**.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~23~~ 22 bytes
*-1 byte thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)!*
```
(.).
$1$1$&
.
$*
M`
1$
```
[Try it online!](https://tio.run/##LYoxEsIwDAT7e0fIJBQZnSRb9gtS8YdQUNBQMPm/MDPZbbbY7@t8f555W/Yjl23dMHE4Y8QdjwOcMlUsmrrALGqhdkSoeYkCuYBSzHtz1M5a3ARkH6EE/2@Nlj8 "Retina – Try It Online")
### Explanation
Example input: `20378240`
```
(.).
$1$1$&
```
Replace each couple of digits with the first digit repeated twice followed by the couple itself.
We get `2220333788824440`
```
.
$*
```
Convert each digit to unary. With parentheses added for clarity, we get `(11)(11)(11)()(111)(111)...`
```
M`
```
Count the number of matches of the empty string, which is one more than the number of ones in the string. (With the last two steps we have basically taken the sum of each digit +1) Result: `60`
```
1$
```
Match a `1` at the end of the string. We have multiplied digits by 3 and 1 alternately and summed them, for a valid barcode this should be divisible by 10 (last digit 0); but we also added 1 in the last step, so we want the last digit to be 1. Final result: `1`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 85 bytes
```
param($a)(10-(("$a"[0..6]|%{+"$_"*(3,1)[$i++%2]})-join'+'|iex)%10)%10-eq+"$("$a"[7])"
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRU8PQQFdDQ0klUSnaQE/PLLZGtVpbSSVeSUvDWMdQM1olU1tb1Si2VlM3Kz8zT11bvSYztUJT1dAAhHVTC4FqIZrNYzWV/v//b2hkbGJqZm4BAA "PowerShell – Try It Online") or [Verify all test cases](https://tio.run/##LYzRCoIwGIVfRcbErc34/21uetOLiMQILaO0tCgwn30pdeDAufjOd@tf9TCe6sslNM/u8Gj7LmqmcPODvzLqOUNIGSPUkxK2W1t94kkQuicbpiXykrZCxKqaeXru2y4Ryaet3zxGWJvW94X9nV3FSZipH45jCatlkUTpLiKCNRHd8zkEBdrlyoDU2tkMVSGdU9pkLpMJ/JNIhaBNkRtpC7SZ0SARi2UolLjS1uVf "PowerShell – Try It Online")
Implements the algorithm as defined. Takes input `$a`, pulls out each digit with `"$a"[0..6]` and loops through them with `|%{...}`. Each iteration, we take the digit, cast it as a string `"$_"` then cast it as an int `+` before multiplying it by either `3` or `1` (chosen by incrementing `$i` modulo `2`).
Those results are all gathered together and summed `-join'+'|iex`. We take that result mod `10`, subtract that from `10`, and again take the result mod `10` (this second mod is necessary to account for the `00000000` test case). We then check whether that's `-eq`ual to the last digit. That Boolean result is left on the pipeline and output is implicit.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ż3,1ṁ$P€SN%⁵
Ṫ=Ç
```
[Try it online!](https://tio.run/##y0rNyan8///oHmMdw4c7G1UCHjWtCfZTfdS4levhzlW2h9v/uxxuVwEK/v8fzcVpZGBsbmFkYqCjYGxsbmZqaGSpo2BubmRsYmpuqqNgAAU6XECVhgbGJpYWJjoKZpaGZqYmxkA9hoaWQJaRIZAF0mJmbsEVCwA "Jelly – Try It Online")
takes input as a list of digits
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 14 bytes
Equivalent with [streetster's solution](https://codegolf.stackexchange.com/a/148270/43319).
Full program body. Prompts for list of numbers from STDIN.
```
0=10|+/⎕×8⍴3 1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPd1dHvv4GtoUGNtv6jvqmHp1s86t1irGAIkvqvAAZAFVxGCgYKxgrmChYKRgomCgZcCBljsLiZgqmCIVDOEknGHChuBJQ1AcqZK5giyRgooEAuZHsMwTaZKFgC7TJBkjEDihiC7TEByiPrMQSKW0JlgPpRZGD2m4HcDgA "APL (Dyalog Unicode) – Try It Online")
***Is…***
`0=` zero equal to
`10|` the mod-10 of
`+/` the sum of
`⎕×` the input times
`8⍴3 1` eight elements cyclically taken from `[3,1]`
***?***
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
3X‚7∍*OTÖ
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fOOJRwyzzRx29Wv4hh6f9/x9trGOsY65jpmOqY6hjpGMZCwA "05AB1E – Try It Online")
```
3X‚7∍*OTÖ # Argument a
3X‚ # Push [3, 1]
7∍ # Extend to length 7
* # Multiply elements with elements at same index in a
O # Total sum
TÖ # Divisible by 10
```
[Answer]
# J, 17 bytes
*-10 bytes thanks to cole*
```
0=10|1#.(8$3 1)*]
```
[Try it online!](https://tio.run/##Zc29CsIwFMXxPU9xiMK1IuHefLeQR3ESU3Fx6KrPHisWh3jgLL/lf291QZnAWN@4CD9lZw557yDD8dwGpQ2ololwwmtCXZSai4E2mpW6Xm4PCAoqZpBll7L1TJ07l2IQO/aeknU@pNA7b6MtwL@AfAvUeRwlBu@4d5FxdSt//unGlKm9AQ "J – Try It Online")
This uses multiplication of equal sized lists to avoid the zip/multiply combo of the original solution, as well as the "base 1 trick" `1#.` to add the products together. The high level approach is similar to the original explanation.
## original, 27 bytes
```
0=10|{:+[:+/[:*/(7$3 1),:}:
```
[Try it online!](https://tio.run/##Zc2xDoIwEMbxvU9xISanQuCupT24pE/CaCzGxYFRefaKkTjUL/mW3/K/57RAVCDYnikyvZ5aT1p3k567oxwc8KnRVfPJVC1giorQwKqQFmPm2ELVVmTM9XJ7AEOEBDOgJSeD7QkLd06CZzuWLmJd78WXTvtwD9AvwN8CFh5GDr53VDrzuLnlP/90gwyY3w "J – Try It Online")
## explained
```
0 = is 0 equal to...
10 | the remainder when 10 divides...
{: + the last input item plus...
[: +/ the sum of...
[: */ the pairwise product of...
7$(3 1) ,: 3 1 3 1 3 1 3 zipped with...
}: all but the last item of the input
```
[Answer]
# C (gcc), ~~84~~ ~~82~~ ~~72~~ ~~61~~ 54 bytes
```
c;i;f(x){for(i=c=0;x;x/=10)c+=(1+2*i++%4)*x;c=c%10<1;}
```
-21 bytes from [Neil](https://codegolf.stackexchange.com/users/17602/neil)
-7 bytes from [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)
[Try it online!](https://tio.run/##XZDvaoMwFMU/61OEgpAYt@Ym8R9pnsTJkFQ7hdmhMmTis7vY1k6WD0l@514O91zzcjFmWYyqVYVHMlXXDtfaaKZGNR41MGKoxkC5X1PqSeKPymjjATuBmpe6HdBnUbd4/RTdxQTIfBQd8n0L3wRNrrNWhrIf3k3Rl32W5hnPkV4rzsSZiBMuWQBzsLIQcRQCTzeOYy5kGIcboztHG7PH2ZgDEzJNZMDuHKUQhVKwjQFSyxyevNpFcbLxk1xnVq5jd4FuyRo7MFP2OaG@/imvFf5LRI4Pyd9pClHa3OI7X511qPChwt5rcibWyTsjvd5v7SHYr6bJM5YHaG9@18j/NsiJHW925@UX "C (gcc) – Try It Online")
Developed independently of [Steadybox's answer](https://codegolf.stackexchange.com/a/148187/44694)
'f' is a function that takes the barcode as an `int`, and returns `1` for True and `0` for False.
* `f` stores the last digit of `x` in `s` (`s=x%10`),
* Then calculates the sum in `c` (`for(i=c=0;x;x/=10)c+=(1+2*i++%4)*x;`)
+ `c` is the sum, `i` is a counter
+ for each digit including the first, add `1+2*i%4` times the digit (`x%10`) to the checksum and increment `i` (the `i++` in `3-2*i++%4`)
- `1+2*i%4` is 1 when `i` is even and 0 when `i` is odd
* Then returns whether the sum is a multiple of ten, and since we added the last digit (multiplied by 1), the sum will be a multiple of ten iff the barcode is valid. (uses GCC-dependent undefined behavior to omit `return`).
[Answer]
# C, 63 bytes
```
i;s=0;c(int*v){for(i=0;i<8;i++){s+=v[i]*3+v[++i];}return s%10;}
```
Assumes that `0` is `true` and any other value is `false`.
## +3 bytes for better return value
```
i;s=0;c(int*v){for(i=0;i<8;i++){s+=v[i]*3+v[++i];}return s%10==0;}
```
Add `==0` to the `return` statement.
## Ungolfed
```
int check(int* values)
{
int result = 0;
for (int index = 0; index < 8; index++)
{
result += v[i] * 3 + v[++i]; // adds this digit times 3 plus the next digit times 1 to the result
}
return result % 10 == 0; // returns true if the result is a multiple of 10
}
```
This uses the alternative definition of EAN checksums where the check digit is chosen such that the checksum of the entire barcode including the check digit is a multiple of 10. Mathematically this works out the same but it's a lot simpler to write.
## Initialising variables inside loop as suggested by Steadybox, 63 bytes
```
i;s;c(int*v){for(i=s=0;i<8;i++){s+=v[i]*3+v[++i];}return s%10;}
```
## Removing curly brackets as suggested by Steadybox, 61 bytes
```
i;s;c(int*v){for(i=s=0;i<8;i++)s+=v[i]*3+v[++i];return s%10;}
```
## Using `<1` rather than `==0` for better return value as suggested by Kevin Cruijssen
```
i;s=0;c(int*v){for(i=0;i<8;i++){s+=v[i]*3+v[++i];}return s%10<1;}
```
Add `<1` to the `return` statement, this adds only 2 bytes rather than adding `==0` which adds 3 bytes.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 47 bytes
```
e=>eval(e.map((a,i)=>(3-i%2*2)*a).join`+`)%10<1
```
Although there is a much shorter answer already, this is my first attempt of golfing in JavaScript so I'd like to hear golfing recommendations :-)
### Testing
```
let f=
e=>eval(e.map((a,i)=>(3-i%2*2)*a).join`+`)%10<1
console.log(f([2,0,3,7,8,2,4,0]));
console.log(f([3,3,7,6,5,1,2,9]));
console.log(f([7,7,2,3,4,5,7,5]));
console.log(f([0,0,0,0,0,0,0,0]));
console.log(f([2,1,0,3,4,9,8,4]));
console.log(f([6,9,1,6,5,4,3,0]));
console.log(f([1,1,9,6,5,4,2,1]));
console.log(f([1,2,3,4,5,6,7,8]));
```
Alternatively, you can **[Try it online!](https://tio.run/##bc9RC4IwEMDx9z5FL8Jmp2xzalL6RSJw2IyJOUnx669T6qEa93g/jv91alFT8zTjHA32pl2v531bOl1WelE90fFDjYQoMLSsSBKZQISChorGnTVDfahpwNmZu11jh8n2Ou7tnbTkIoBBAjkcQYAEdqX09EuSDWSQAkdU@EiOQCCTiHJIfYTB12zkP4ZvORIKDJK@Mxmu@BYjEXp7OYLiTfCin3xqs/X3lbgX "JavaScript (Node.js) – Try It Online")**
[Answer]
# Perl 5, ~~37~~ 32 + 1 (-p) bytes
```
s/./$-+=$&*(--$|*2+1)/ge;$_=/0$/
```
-5 bytes thanks to Dom Hastings.
37 +1 bytes was
```
$s+=$_*(++$i%2*2+1)for/./g;$_=!!$s%10
```
[try it online](https://tio.run/##LclNCsIwEEDh/ZxjEG1JMz9JJqHkLK6KCMUG69KzGy34lt9ry3ONHV2lue9@8ujGiqfh7By@Bxn54m/LjNfqCX3vQmpZAoEwaSg5gKqlyFIgFU4xKIGZaIgWgbn8RBjoH/BxkmX4bO113x57d239Ag)
[Answer]
# Brainfuck, 228 Bytes
```
>>>>++++[<++>-]<[[>],>>++++++[<++++++++>-]<--[<->-]+[<]>-]>[->]<<<<[[<+>->+<]<[>+>+<<-]>>[<+>-]<<<<<]>>>>[>>[<<[>>+<<-]]>>]<<<++++[<---->-]+++++[<++<+++>>-]<<[<[>>[<<->>-]]>[>>]++[<+++++>-]<<-]<[[+]-<]<++++++[>++[>++++<-]<-]>>+.
```
Can probably be improved a fair bit.
Input is taken 1 digit at a time, outputs 1 for true, 0 for false.
## How it works:
```
>>>>++++[<++>-]<
```
Put 8 at position 3.
```
[[>],>>++++++[<++++++++>-]<--[<->-]+[<]>-]
```
Takes input 8 times, changing it from the ascii value to the actual value +2 each time. Inputs are spaced out by ones, which will be removed, to allow for easier multiplication later.
```
>[->]
```
Subtract one from each item. Our tape now looks something like
```
0 0 0 0 4 0 4 0 8 0 7 0 6 0 2 0 3 0 10 0 0
^
```
With each value 1 more than it should be. This is because zeros will mess up our multiplication process.
Now we're ready to start multiplying.
```
<<<<
```
Go to the second to last item.
```
[[<+>->+<]<[>+>+<<-]>>[<+>-]<<<<<]
```
While zero, multiply the item it's at by three, then move two items to the left. Now we've multiplied everything we needed to by three, and we're at the very first position on the tape.
```
>>>>[>>[<<[>>+<<-]]>>]
```
Sum the entire list.
```
<<<++++[<---->-]
```
The value we have is 16 more than the actual value. Fix this by subtracting 16.
```
+++++[<++<+++>>-]
```
We need to test whether the sum is a multiple of 10. The maximum sum is with all 9s, which is 144. Since no sum will be greater than 10\*15, put 15 and 10 on the tape, in that order and right to the right of the sum.
```
<<[<[>>[<<->>-]]>[>>]++[<+++++>-]<<-]
```
Move to where 15 is. While it's non-zero, test if the sum is non-zero. If it is, subtract 10 from it. Now we're either on the (empty) sum position, or on the (also empty) ten position. Move one right. If we were on the sum position, we're now on the non-zero 15 position. If so, move right twice. Now we're in the same position in both cases. Add ten to the ten position, and subtract one from the 15 position.
The rest is for output:
```
<[[+]-<]<++++++[>++[>++++<-]<-]>>+.
```
Move to the sum position. If it is non-zero (negative), the barcode is invalid; set the position to -1. Now add 49 to get the correct ascii value: 1 if it's valid, 0 if it's invalid.
[Answer]
# Java 8, 53 bytes
Golfed:
```
b->(3*(b[0]+b[2]+b[4]+b[6])+b[1]+b[3]+b[5]+b[7])%10<1
```
Direct calculation in the lambda appears to the shortest solution. It fits in a single expression, minimizing the lambda overhead and removing extraneous variable declarations and semicolons.
```
public class IsMyBarcodeValid {
public static void main(String[] args) {
int[][] barcodes = new int[][] { //
{ 2, 0, 3, 7, 8, 2, 4, 0 }, //
{ 3, 3, 7, 6, 5, 1, 2, 9 }, //
{ 7, 7, 2, 3, 4, 5, 7, 5 }, //
{ 0, 0, 0, 0, 0, 0, 0, 0 }, //
{ 2, 1, 0, 3, 4, 9, 8, 4 }, //
{ 6, 9, 1, 6, 5, 4, 3, 0 }, //
{ 1, 1, 9, 6, 5, 4, 2, 1 }, //
{ 1, 2, 3, 4, 5, 6, 7, 8 } };
for (int[] barcode : barcodes) {
boolean result = f(b -> (3 * (b[0] + b[2] + b[4] + b[6]) + b[1] + b[3] + b[5] + b[7]) % 10 < 1, barcode);
System.out.println(java.util.Arrays.toString(barcode) + " = " + result);
}
}
private static boolean f(java.util.function.Function<int[], Boolean> f, int[] n) {
return f.apply(n);
}
}
```
Output:
```
[2, 0, 3, 7, 8, 2, 4, 0] = true
[3, 3, 7, 6, 5, 1, 2, 9] = true
[7, 7, 2, 3, 4, 5, 7, 5] = true
[0, 0, 0, 0, 0, 0, 0, 0] = true
[2, 1, 0, 3, 4, 9, 8, 4] = false
[6, 9, 1, 6, 5, 4, 3, 0] = false
[1, 1, 9, 6, 5, 4, 2, 1] = false
[1, 2, 3, 4, 5, 6, 7, 8] = false
```
[Answer]
# QBasic, ~~54~~ 52 bytes
Ugh, the boring answer turned out to be the shortest:
```
INPUT a,b,c,d,e,f,g,h
?(3*a+b+3*c+d+3*e+f+3*g+h)MOD 10=0
```
This inputs the digits comma-separated. My original 54-byte solution, which inputs one digit at a time, uses a "nicer" approach:
```
m=3
FOR i=1TO 8
INPUT d
s=s+d*m
m=4-m
NEXT
?s MOD 10=0
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 65 62 bytes
```
b=>{int s=0,i=0,t=1;while(i<8)s+=b[i++]*(t^=2);return s%10<1;}
```
[Try it online!](https://tio.run/##jZHBaoQwEIbPzVPMpaA1LcZ1XSVmL6U9tVDooQexoG7YBmwCJnYp4rNbzVbYQ6GB5DAz@eaff9Lo20Z1fOq1kEd4/daGf1LUtJXW8DIgbSojGnjsZZMLaYoSQ61Uu4eHSqbAYKrZfpgLoFmIxXwNI/T0IVruiTz1dcDqQgRBeeOZdxb5tOOm7yToaxLmhI4TRavElxIHeK6E9Hw0oKt7JbVq@d1bJwx/EpJ7i6In@akoYYAIQ4hhg2GHIcVLGM8ZGH2f/stuVjDBsMVALJ65sTsLRrZDbPE53LqxIf7r/LIujslqelbOrO/YTTmx78nqOLZNHLdFLJhdsMskzuzlqpLzd53ZEY3TDw "C# (.NET Core) – Try It Online")
### Acknowledgements
-3 bytes thanks to @KevinCruijssen and the neat trick using the exclusive-or operator.
### DeGolfed
```
b=>{
int s=0,i=0,t=1;
while(i<8)
s+=b[i++]*(t^=2); // exclusive-or operator alternates t between 3 and 1.
return s%10<1;
}
```
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 53 bytes
```
b=>(3*(b[0]+b[2]+b[4]+b[6])+b[1]+b[3]+b[5]+b[7])%10<1
```
[Try it online!](https://tio.run/##jZFBS8QwEIXP5lfMRUg0StOm7Zbu7kX0pCB48FByaGOQQE1g01Wk9LfXJmthD4KB8MiEfG/yJtLdSHtQ89Fp8w4v325QHzWSfescPI/IDe2gJTwcjdxqMzSCQmdtv4f71mxgB3O32@PsCndNIq67JvXCvRSCLMr8NvOSeykFuWTJls01Wp0/rX6Dp1YbTNCILu6scbZXt68HPahHbRT2jbBRX42AEVIKCYWMQklhQ33JlxOYCKn/ZbMVLCjkFFjAqzi2DGAaHHjAlzKPYxP61/plYxKzNfTSuQq5eVznItxna2IeTCKnxQJYnbH@JdHs@aiK03ed2AlN8w8 "C# (.NET Core) – Try It Online")
A direct port of [@Snowman's answer](https://codegolf.stackexchange.com/a/148366).
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~16~~ 15 bytes
**Solution:**
```
{~10!+/x*8#3 1}
```
[Try it online!](https://tio.run/##y9bNz/7/v7rO0EBRW79Cy0LZWMGw1kjBQMFYwVzBQsFIwUTB4P9/AA "K (oK) – Try It Online")
**Examples:**
```
{~10!+/x*8#3 1}2 1 0 3 4 9 8 5
1
{~10!+/x*8#3 1}2 1 0 3 4 9 8 4
0
{~10!+/x*8#3 1}2 0 3 7 8 2 4 0
1
```
**Explanation:**
K is interpreted right-to-left:
```
{~10!+/x*8#3 1} / the solution
{ } / lambda with x as implicit input
3 1 / the list [3,1]
8# / 8 take this list = [3,1,3,1,3,1,3,1]
x* / multiply input by this
+/ / sum over the list
10! / 10 mod this sum
~ / not, 0 => 1, anything else => 0
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 8 bytes
```
y$3*J∑₀Ḋ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=y%243*J%E2%88%91%E2%82%80%E1%B8%8A&inputs=%5B2%2C0%2C3%2C7%2C8%2C2%2C4%2C0%5D&header=&footer=)
```
y # Uninterleave
$ # Swap
3* # Multiply by 3 (vectorised)
J # Join
∑ # Sum
₀Ḋ # Is divisible by 10?
```
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/), 32 bytes
```
@(x)~mod(sum([2*x(1:2:7),x]),10)
```
[Try it online!](https://tio.run/##Vc7LDsIgEAXQvV/CmBsClII0MfE/TBdG7a7pwkdY@et4hXZhZjVnnsv1eXnfy3TUWpeTyvKZl5t6vGZ1dvus7OCGKMijwBopExUGHSIOcPAwo@yIXaWAHpacGkaSY8GTI/qGBn/R0HHM1M7Evb5hYGLrTs/S2mlJaUVObbidCb/HRilf "Octave – Try It Online")
I'm going to post this despite the other Octave answer as I developed this code and approach without looking at the other answers.
Here we have an anonymous function which takes the input as an array of 8 values, and return true if a valid barcode, false otherwise..
The result is calculated as follows.
```
2*x(1:2:7)
[ ,x]
sum( )
mod( ,10)
@(x)~
```
1. Odd digits (one indexed) are multiplied by 2.
2. The result is prepended to the input array, giving an array whose sum will contain the odd digits three times, and the even digits once.
3. We do the sum which will also include the supplied checksum within our sum.
4. Next the modulo 10 is performed. If the checksum supplied was valid, the sum of all multiplied digits including the checksum value would end up being a multiple of 10. Therefore only a valid barcode would return 0.
5. The result is inverted to get a logical output of true if valid.
[Answer]
# Excel, 37 bytes
Interpreting "A list of 8 integers" as allowing 8 separate cells in Excel:
```
=MOD(SUM(A1:H1)+2*(A1+C1+E1+G1),10)=0
```
] |
[Question]
[
The least common multiple of a set of positive integers `A` is the smallest postive integer `B` such that, for each `k` in `A`, there exists a positive integer `n` such that `k*n = B`.
Given at least two positive integers as input, output their least common multiple.
## Rules
* Builtins are allowed, but if your solution uses one, you are encouraged to include an alternate solution that does not use GCD/LCM builtins. However, the alternate solution will not count towards your score at all, so it is entirely optional.
* All inputs and outputs will be within the natively-representable range for your language. If your language is natively capable of arbitrarily-large integers, then your solution must work with arbitrarily large inputs and outputs.
## Test cases
```
[7, 2] -> 14
[8, 1] -> 8
[6, 4, 8] -> 24
[8, 2, 1, 10] -> 40
[9, 6, 2, 1, 5] -> 90
[5, 5, 7, 1, 1] -> 35
[4, 13, 8, 8, 11, 1] -> 1144
[7, 2, 2, 11, 11, 8, 5] -> 3080
[1, 6, 10, 3, 4, 10, 7] -> 420
[5, 2, 9, 10, 3, 4, 4, 4, 7] -> 1260
[9, 7, 10, 9, 7, 8, 5, 10, 1] -> 2520
```
[Answer]
## JavaScript (ES6), 36 bytes
```
f=(a,i=1)=>a.some(v=>i%v)?f(a,i+1):i
```
Starting from `1` it's the first number that can be divided by all.
```
f=(a,i=1)=>a.some(v=>i%v)?f(a,i+1):i
;
console.log(f([7, 2]));
console.log(f([8, 1]));
console.log(f([6, 4, 8]));
console.log(f([8, 2, 1, 10]));
console.log(f([9, 6, 2, 1, 5]));
console.log(f([5, 5, 7, 1, 1]));
console.log(f([4, 13, 8, 8, 11, 1]));
console.log(f([7, 2, 2, 11, 11, 8, 5]));
console.log(f([1, 6, 10, 3, 4, 10, 7]));
console.log(f([5, 2, 9, 10, 3, 4, 4, 4, 7]));
console.log(f([9, 7, 10, 9, 7, 8, 5, 10, 1]));
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E)/[2sable](https://github.com/Adriandmen/2sable), 2 bytes
```
.¿
```
[Try it online! in 05AB1E](http://05ab1e.tryitonline.net/#code=LsK_&input=WzksIDcsIDEwLCA5LCA3LCA4LCA1LCAxMCwgMV0)
[or 2sable](http://2sable.tryitonline.net/#code=LsK_&input=WzksIDcsIDEwLCA5LCA3LCA4LCA1LCAxMCwgMV0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
æl/
```
Reduces by LCM. [Try it online!](http://jelly.tryitonline.net/#code=w6ZsLw&input=&args=WzksIDcsIDEwLCA5LCA3LCA4LCA1LCAxMCwgMV0) or [verify all test cases](http://jelly.tryitonline.net/#code=w6ZsLwrDh-KCrEc&input=&args=WwogICAgWzcsIDJdLAogICAgWzgsIDFdLAogICAgWzYsIDQsIDhdLAogICAgWzgsIDIsIDEsIDEwXSwKICAgIFs5LCA2LCAyLCAxLCA1XSwKICAgIFs1LCA1LCA3LCAxLCAxXSwKICAgIFs0LCAxMywgOCwgOCwgMTEsIDFdLAogICAgWzcsIDIsIDIsIDExLCAxMSwgOCwgNV0sCiAgICBbMSwgNiwgMTAsIDMsIDQsIDEwLCA3XSwKICAgIFs1LCAyLCA5LCAxMCwgMywgNCwgNCwgNCwgN10sCiAgICBbOSwgNywgMTAsIDksIDcsIDgsIDUsIDEwLCAxXQpd).
## Alternate version, 6 bytes
```
ÆE»/ÆẸ
```
[Try it online!](http://jelly.tryitonline.net/#code=w4ZFwrsvw4bhurg&input=&args=WzksIDcsIDEwLCA5LCA3LCA4LCA1LCAxMCwgMV0) or [verify all test cases](http://jelly.tryitonline.net/#code=w4ZFwrsvw4bhurgKw4figqxH&input=&args=WwogICAgWzcsIDJdLAogICAgWzgsIDFdLAogICAgWzYsIDQsIDhdLAogICAgWzgsIDIsIDEsIDEwXSwKICAgIFs5LCA2LCAyLCAxLCA1XSwKICAgIFs1LCA1LCA3LCAxLCAxXSwKICAgIFs0LCAxMywgOCwgOCwgMTEsIDFdLAogICAgWzcsIDIsIDIsIDExLCAxMSwgOCwgNV0sCiAgICBbMSwgNiwgMTAsIDMsIDQsIDEwLCA3XSwKICAgIFs1LCAyLCA5LCAxMCwgMywgNCwgNCwgNCwgN10sCiAgICBbOSwgNywgMTAsIDksIDcsIDgsIDUsIDEwLCAxXQpd).
### How it works
```
ÆE»/ÆẸ Main link. Argument: A (array)
ÆE Yield all prime exponents of each integer in A.
»/ Reduce columns (exponents that correspond to the same prime) by maximum.
ÆẸ Turn the resulting array of prime exponents into the corresponding integer.
```
[Answer]
# Python, ~~69~~ ~~65~~ ~~52~~ 50 bytes
```
A=lambda l,i=1:any(i%a for a in l)and A(l,i+1)or i
```
2 bytes saved thanks to Dennis!
Pretty straightforward recursive solution, you will need to make the recursion limit a bit higher for some of the test cases to work.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 7 bytes
```
&YFX>^p
```
No builtin.
[Try it online!](http://matl.tryitonline.net/#code=JllGWD5ecA&input=WzksIDcsIDEwLCA5LCA3LCA4LCA1LCAxMCwgMV0)
### Explanation
Let's take input `[8, 2, 1, 10]` as an example.
```
&YF % Take array implicitly. Push vector of prime factors and matrix of exponents
% of factorization, where each row represents one of the input numbers
% STACK: [2 3 5], [3 0 0; 1 0 0; 0 0 0; 1 0 1]
X> % Maximum of each column
% STACK: [2 3 5], [3 0 1]
^ % Element-wise power
% STACK: [8 1 5]
p % Product of array
% STACK: 40
% Implicitly display
```
---
*EDIT (June 9, 2017): `YF` with two outputs has been modified in [release 20.1.0](https://github.com/lmendo/MATL/releases/tag/20.1.0): non-factor primes and their (zero) exponents are skipped. This doesn't affect the above code, which works without requiring any changes.*
[Answer]
# Julia (3 Bytes) [Working on Non-Built-in]
```
lcm # Using LCM built-in (3 Bytes)
```
As Dennis pointed out, I keep forgetting that Julia automatically vectorizes inputs.
## Example:
```
println(lcm(1,2,3,4,5,6,7,8,9)) #Prints 2520
```
[Answer]
## PowerShell v2+, ~~73~~ 60 bytes
```
param($a)for($i=1;($a|?{!($i%$_)}).count-ne$a.count){$i++}$i
```
Takes input `$a`, loops upward from `$i=1` with `$i++`, based on a conditional. The condition is `($a|?{!($i%$_)}).count` being `-n`ot`e`qual to `$a.count`. Meaning, the loop ends when the elements of `$a` that *are* divisors of `$i` is equal to the elements of `$a`. Then, a solitary `$i` is left on the pipeline, and output is implicit.
### Test Cases
```
PS C:\Tools\Scripts\golfing> @(7,2),@(8,1),@(6,4,8),@(8,2,1,10),@(9,6,2,1,5),@(5,5,7,1,1),@(4,13,8,8,11,1)|%{($_-join',')+" -> "+(.\least-common-multiple.ps1 $_)}
7,2 -> 14
8,1 -> 8
6,4,8 -> 24
8,2,1,10 -> 40
9,6,2,1,5 -> 90
5,5,7,1,1 -> 35
4,13,8,8,11,1 -> 1144
PS C:\Tools\Scripts\golfing> @(7,2,2,11,11,8,5),@(1,6,10,3,4,10,7),@(5,2,9,10,3,4,4,4,7),@(9,7,10,9,7,8,5,10,1)|%{($_-join',')+" -> "+(.\least-common-multiple.ps1 $_)}
7,2,2,11,11,8,5 -> 3080
1,6,10,3,4,10,7 -> 420
5,2,9,10,3,4,4,4,7 -> 1260
9,7,10,9,7,8,5,10,1 -> 2520
```
[Answer]
# Actually, ~~12~~ 1 byte
Golfing suggestions are still welcome, though I'm not sure how to improve on the raw LCM built-in. [Try it online!](http://actually.tryitonline.net/#code=4pay&input=WzksIDcsIDEwLCA5LCA3LCA4LCA1LCAxMCwgMV0)
```
▲
```
A 12-byte version without the built-in. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pWXMmDilZxA4pmAJc6jWWDilZNO&input=WzksIDcsIDEwLCA5LCA3LCA4LCA1LCAxMCwgMV0)
```
╗2`╜@♀%ΣY`╓N
```
**Ungolfing**
```
Implicit input array.
╗ Save array in register 0.
2`...`╓ Starting with f(0), find the first (two) x where f(x) returns a truthy value.
These two values will be 0 and our LCM.
╜ Push array from register 0.
@ Swap the top two values. Stack: x, array
♀% Map % over x and array, returning (x % item) for each item in array.
ΣY If the sum of all the modulos equals 0, x is either 0 or our LCM.
N Push the last (second) value of our results. This is our LCM.
Implicit return.
```
[Answer]
# Cheddar, 33 bytes
```
(n,i=1)f->n.any(i&(%))?f(n,i+1):i
```
Nothing super new.
## Ungolfed
```
(n, i = 1) f ->
n.any(j -> i % j) ?
f(n, i + 1) :
i
```
Basically this starts at one and keeps increasing until it finds an LCM
[Answer]
# JavaScript (ES6), ~~63~~ 59 bytes
```
f=([x,...a])=>a[0]?x*f(a)/(g=(m,n)=>n?g(n,m%n):m)(x,f(a)):x
```
Recursively finds the LCM of the last two elements.
[Answer]
# Mathematica, 3 bytes
```
LCM
```
Usage:
```
In[1]:= LCM[9, 7, 10, 9, 7, 8, 5, 10, 1]
Out[1]= 2520
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 8 bytes
```
{×↙Xℕ₁}ᵛ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/rw9EdtMyMetUx91NQIFJn9/3@0QrS5jlGsTrSFjiGQNNMx0bEA84x0DHUMDYBMSx0zMMcUyDbVMdUxB0kA2SY6hsY6FkBoCOEDjQGpMwQhC7BqQ6BOQwMdY6CZQMocrN9IxxImBoLmYAvMQUIgCqgPxDSMVYgFAA "Brachylog – Try It Online")
It's funny just how directly this maps on to the definition given in the challenge.
```
{ }ᵛ Each element of
the input
× multiplied by
↙X some arbitrary and inconsistent integer
ℕ₁ is a natural number,
ᵛ which is the same for each element,
and is the output.
```
A suspiciously slow but significantly shorter solution:
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 5 bytes
```
f⊇p~d
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/eobcOjpqaHuzprH26d8D/tUVd7QV3K///RCtHmOkaxOtEWOoZA0kzHRMcCzDPSMdQxNAAyLXXMwBxTINtUx1THHCQBZJvoGBrrWAChIYQPNAakzhCELMCqDYE6DQ10jIFmAilzsH4jHUuYGAiagy0wBwmBKKA@ENMwViEWAA "Brachylog – Try It Online")
Takes input through the output variable and gives output through the input variable. Rips right through the first four test cases but I'm still waiting on the fifth... Ordinarily, I'd still make it my primary solution and just trust that it works correctly, but I don't know why it hasn't confirmed that 90 is the LCM of `9, 6, 2, 1, 5` when I *gave it 90* twenty minutes ago.
(Edit: It confirmed the answer after no more than 16 hours, and generated it alongside the LCM of `5, 5, 7, 1, 1` after about two days.)
```
The output variable
~d with duplicates removed
p is a permutation of
⊇ a sublist of
f the factors of
the input variable.
```
And another completely different predicate that accidentally more-or-less translates Fatalize's Brachylog v1 solution:
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 10 bytes
```
;.gᵗ↔z%ᵛ0<
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w31ov/eHW6Y/aplSpPtw628Dm//9ohWhzHaNYnWgLHUMgaaZjomMB5hnpGOoYGgCZljpmYI4pkG2qY6pjDpIAsk10DI11LIDQEMIHGgNSZwhCFmDVhkCdhgY6xkAzgZQ5WL@RjiVMDATNwRaYg4RAFFAfiGkYqxALAA "Brachylog – Try It Online")
This was salvaged from a solution I'd made for [this challenge](https://codegolf.stackexchange.com/questions/127103/lcm-of-rational-numbers) before I realized the output wasn't restricted to being an integer.
```
. The output
; gᵗ↔z paired with each element of
the input,
%ᵛ when the first element of each pair is taken mod the second, is always
0 zero.
Furthermore, the output
< is strictly greater than
0 zero.
```
[Answer]
# Dyalog APL, 2 bytes
```
∧/
```
Reduces by LCM. Test it on [TryAPL](http://tryapl.org/?a=lcm%20%u2190%20%u2227/%20%u22C4%20lcm%209%207%2010%209%207%208%205%2010%201&run).
[Answer]
## JavaScript (ES6), 52 bytes
```
a=>a.reduce((l,n)=>l*n/(g=(m,n)=>n?g(n,m%n):m)(l,n))
```
I `reduce`d this answer as much as I could but I'm obviously not going to get anywhere near the simplicity of @Hedi's answer.
[Answer]
# Java 8, ~~75~~ ~~59~~ ~~121~~ 89 bytes
Uses the Euclidean Algorithm and the fact that
LCM(A, B)= A \* B / GCD(A, B)
* ***16** bytes off. Thanks to @carusocomputing*
* *Added Multi-Input +**62** bytes*
* ***32** bytes off. Thanks to @Olivier Grégoire*
Code:
```
public static int lcm(int l, int c){
for(int i=1;i<=l&&i<=c;++i)
if (i%l==0&&i%c==0)
return l*c/i;
}
public static int lcm(int...x){
int y=x[0];
for(int j:x){
y=lcm(j,y);
}
return y;
}
```
Remove line-breaks:
```
int g(int a,int b){return b<1?a:g(b,a%b);}
```
---
```
l->{int l=1;for(int n:a)l=l*n/g(l,n);return l;}
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 3 bytes
```
&Zm
```
This uses the builtin function with array input.
[Try it online!](http://matl.tryitonline.net/#code=Jlpt&input=WzksIDcsIDEwLCA5LCA3LCA4LCA1LCAxMCwgMV0)
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 17 bytes
```
,.#>=g:?z:%a#=h0,
```
[Try it online!](http://brachylog.tryitonline.net/#code=LC4jPj1nOj96OiVhIz1oMCw&input=Wzk6NzoxMDo5Ojc6ODo1OjEwOjFd&args=Wg)
### Explanation
```
,.#>= Output is a strictly positive integer
g:?z Zip the Output with the Input
:%a Compute Output mod I for each I in the Input
#=h0, All results must be equal to 0
```
[Answer]
# C#, 50+18 = 68 bytes
50 bytes for method defintion, +18 bytes for LINQ import.
```
using System.Linq;int L(int[]n,int i=1)=>n.All(x=>1>i%x)?i:L(n,i+1);
```
Pretty much the same as a lot of other answers. Counts up recursively until it finds the LCM. I was a bit surprised this didn't get a StackOverflowException, so I also have a non-recursive version which is actually just 1 byte longer.
```
using System.Linq;n=>{for(int i=1;;i++)if(n.All(x=>1>i%x))return i;};
```
Ungolfed:
```
using System.Linq; // Import LINQ
int L(int[] n, int i = 1) => // Function declaration
n.All(x => 1 > i % x) // Check if each x in n divides i
? i // And if so return i
: L(n, i + 1) // Otherwise increment i and recurse
;
```
[Answer]
# [Perl 6](https://perl6.org), 10 bytes
```
{[lcm] @_}
```
basically the same as:
```
sub ( *@_ ) { @_.reduce: &infix:< lcm > }
```
[Answer]
# J, 11 bytes
```
>./&.(_&q:)
```
There is a solution for **3 bytes** using the LCM builtin.
```
*./
```
## Explanation
```
>./&.(_&q:) Input: array of integers A
_&q: Get the prime exponents of each integer in A
>./& Reduce by maximum on the lists
&. _&q: Convert the list of exponents back to an integer
*./ Input: array of integers A
/ Reduce using
*. LCM
```
[Answer]
# CJam, ~~18~~ ~~17~~ 16 bytes
1 byte saved thanks to Martin Ender.
Incrementing until the LCM is found.
```
q~0{)_2$f%:+}g\;
```
[Try it online](http://cjam.tryitonline.net/#code=cU4vezpRUW8iIC0-ICJvOwoKUX4weylfMiRmJTorfWdcOwoKXW9Ob30vICAgICAgICAgICAgIA&input=WzcgMl0KWzggMV0KWzYgNCA4XQpbOCAyIDEgMTBdCls5IDYgMiAxIDVdCls1IDUgNyAxIDFdCls0IDEzIDggOCAxMSAxXQpbNyAyIDIgMTEgMTEgOCA1XQpbMSA2IDEwIDMgNCAxMCA3XQpbNSAyIDkgMTAgMyA0IDQgNCA3XQpbOSA3IDEwIDkgNyA4IDUgMTAgMV0)
[Answer]
## Racket 13 bytes
lcm is a built-in function in Racket:
```
(apply lcm l)
```
Testing:
```
(define (f l)
(apply lcm l))
(f (list 7 2))
(f (list 8 1))
(f (list 6 4 8))
(f (list 8 2 1 10))
(f (list 9 6 2 1 5))
(f (list 5 5 7 1 1))
(f (list 4 13 8 8 11 1))
(f (list 7 2 2 11 11 8 5))
(f (list 1 6 10 3 4 10 7))
(f (list 5 2 9 10 3 4 4 4 7))
(f (list 9 7 10 9 7 8 5 10 1))
```
Output:
```
14
8
24
40
90
35
1144
3080
420
1260
2520
```
[Answer]
# R, 36 bytes (not builtin)
```
v=scan();i=1;while(any(i%%v))i=i+1;i
```
Takes the input. Then tests each positive integer by taking the mod.
[Answer]
# APOL, 49 bytes
`v(0 1);v(1 i);w(⊕(ƒ(s(¹) %(⁰ I(∋)))) ∆(0));-(⁰ 1)`
This could almost certaintly be made shorter, maybe I'll come back to it later.
[Answer]
# Pyth, 9 bytes
```
.U/*bZibZ
```
A program that takes input of a list on STDIN and prints the result.
[Try it online](http://pyth.herokuapp.com/?code=.U%2F%2abZibZ&debug=0) or [verify all test cases](http://pyth.herokuapp.com/?code=j%22+-%3E+%22%2CQ.U%2F%2abZibZ&test_suite=1&test_suite_input=%5B7%2C+2%5D%0A%5B8%2C+1%5D%0A%5B6%2C+4%2C+8%5D%0A%5B8%2C+2%2C+1%2C+10%5D%0A%5B9%2C+6%2C+2%2C+1%2C+5%5D%0A%5B5%2C+5%2C+7%2C+1%2C+1%5D%0A%5B4%2C+13%2C+8%2C+8%2C+11%2C+1%5D%0A%5B7%2C+2%2C+2%2C+11%2C+11%2C+8%2C+5%5D%0A%5B1%2C+6%2C+10%2C+3%2C+4%2C+10%2C+7%5D%0A%5B5%2C+2%2C+9%2C+10%2C+3%2C+4%2C+4%2C+4%2C+7%5D%0A%5B9%2C+7%2C+10%2C+9%2C+7%2C+8%2C+5%2C+10%2C+1%5D&debug=0)
**How it works**
```
.U/*bZibZ Program. Input: Q
.U Reduce Q by (implicit input fill):
*bZ Product of current and next value
/ ibZ divided by GCD of current and next value
Implicitly print
```
[Answer]
## Haskell, 10 bytes
```
foldr1 lcm
```
Usage example: `foldl1 lcm [5,2,9,10,3,4,4,4,7]` -> `1260`.
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 10 bytes
```
W$+o%g++oo
```
Uses the "try every number until one works" strategy. [Try it online!](http://pip.tryitonline.net/#code=VyQrbyVnKytvbw&input=&args=MQ+MTE+OA+OA+NA+MTM)
```
o is preinitialized to 1, g is list of cmdline args
o%g Mod o by each arg
$+ Sum (truthy if any nonzero, falsy if all zero)
W Loop while that expression is truthy:
++o Increment o
o Autoprint o
```
[Answer]
## PHP, ~~42~~ 74 bytes
```
for(;($p=++$f*$argv[1])%$argv[2];);echo$p;
```
straight forward:
loop `$f` from 1 upwards; if `$f*$a` divides through `$b` without a remainder, the LCM is found.
---
I totally had overread the `at least` ... here´s the code for any number of parameters:
```
for(;$i<$argc;)for($p=$argv[$i=1]*++$f;++$i<$argc&$p%$argv[$i]<1;);echo$p;
```
Loop `$f` from 1 upwards while inner loop has not run to $argc.
Loop `$i` from `2` to `$argc-1` while `$f*$argv[1]` divides through `$argv[$i]` without a remainder.
both loops broken: print `$f*$argument 1`.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 46 bytes
```
l([],1).
l([X|Y],P):-l(Y,Q),P is X*Q/gcd(X,Q).
```
[Try it online!](https://tio.run/nexus/prolog-swi#TVDLCsJAELv7FUNPrUy1s31s68Vf0FuL9CBapFBE3IIX/12zD6kwhySTzYT9TPGpZ0k2K4D23fV8SHbpFHd8TPhAo6F2fdzeLte4hbL57FOCUTOpnkmKhC2tAUFrzyqmAgSCWvYKFkwGtci82jBVv0UJvQl6Ccqk/QPoeel1hEqOYDcSliJFOKJdlgorcS4bm2d1CBZ3UDJorqJF2hZSy2W8b/49fqxLVLUU197jUe0KW24bqdLFvZ7jPEz3OJoHMxt6nI2J8H9f "Prolog (SWI) – TIO Nexus")
Another solution, 59 bytes:
```
l(A,X):-between(1,inf,X),forall(member(Y,A),X mod Y=:=0),!.
```
[Answer]
# [J](http://jsoftware.com/), 34 bytes
```
*/@((0 1+])^:(*@+/@:|*/)^:_>./,1:)
```
A **while** loop iterating through multiples of the largest number in input.
[Try it online!](https://tio.run/##y/r/P81WT0FL30FDw0DBUDtWM85KQ8tBW9/BqkZLH8iJt9PT1zG00vyfmpyRr6CQpqBgYWxkqWBoagAGCoZGRkDClAssraWnj136PwA "J – Try It Online")
] |
[Question]
[
In this challenge, you will play the noisy iterated prisoner's dilemma.
The [Prisoner's dilemma](https://en.wikipedia.org/wiki/Prisoner's_dilemma) is a scenario in game theory where there are two players, each with two options: cooperate, or defect. Each player does better for themself if they defect than if they cooperate, but both players would prefer the outcome where both players cooperate to the one where both players defect.
The iterated prisoner's dilemma is the same game, except you play against the same opponent repeatedly, and you know what your opponent has played in the past. Your objective is always to accumulate the highest score for yourself, regardless of how your opponent does.
The noisy iterated prisoner's dilemma introduces some noise into the communication. Your knowledge of what your opponent has played in the past will have some noise introduced. You will also know what moves you made in the past. The noise rate is constant over a round against the same opponent, but different between different rounds.
## Challenge
In this challenge, you will write a Python 3 program to play the noisy iterated prisoner's dilemma.
Your program will receive three inputs:
* Your own moves, *without* random flips applied.
* Your opponent's moves, with random flips applied.
* A state variable, which starts as an empty list each round, and which you can modify if you want. You can ignore this if you don't want to use it.
Your program should output `'c'` to cooperate or `'d'` to defect.
For instance, here's a program that cooperates if the opponent has cooperated at least 60% of the time in the past, after random flips were applied, and for the first 10 flips:
```
def threshold(my_plays, their_flipped_plays, state):
if len(their_flipped_plays) < 10:
return 'c'
opp_c_freq = their_flipped_plays.count('c')/len(their_flipped_plays)
if opp_c_freq > 0.6:
return 'c'
else:
return 'd'
```
If you don't know Python, write your submission in pseudocode, and someone (me or another member of the site) can make the corresponding Python program.
## Gameplay
The tournament runner can be found here: [noisy-game](https://github.com/isaacg1/noisy-game). Run [`noisy-game.py`](https://github.com/isaacg1/noisy-game/blob/master/noisy-game.py) to run the tournament. I'll keep that repository updated with new submissions. Example programs can be found in [`basic.py`](https://github.com/isaacg1/noisy-game/blob/master/basic.py).
A program's overall score is the total of its score over 100 plays of the game.
A game consists of round-robin matchups of each player against each player, including itself. A matchup consists of 100 rounds. A round consists of 300 moves, each of which involves outputting `'c'` or `'d'`.
Your submission will play a matchup against every submission, including your own. Each matchup will consist of 100 rounds. During each round, a flip probability will be chosen uniformly randomly from `[0, 0.5]`.
Each round will consist of 300 moves. On each move, both programs will receive all previous plays they have attempted, and all previous plays the other program has made, after flips are applied, and a state variable, which is a mutable list which the program can modify if it wants to. The programs will output their moves.
Moves are scored as follows: If a program plays a `'c'`, the opposing program gets 2 points. If a program plays a `'d'`, that program gets 1 point.
Then, each move is flipped independently with probability equal to the flip probability, and stored for showing to the opponent.
After all of the rounds have been played, we sum the number of points each player got in each matchup. Then, we use the following scoring system to calculate each player's score for the game. This scoring is performed after all of the matchups are complete.
## Scoring
We will use evolutionary scoring. Each program starts with equal weight. Then, weights are updated as follows, for 100 iterations, using the point totals from the game:
Each program's new weight is proportional to the product of its previous weight and its average point total, weighted by the weights of its opponents.
100 such updates are applied, and the final weights are each program's score for that run of the game.
The overall scores will be the sum over 100 runs of the game.
The players will be all valid answers to this challenge, plus six [basic programs](https://github.com/isaacg1/noisy-game/blob/master/basic.py) to get us started.
## Caveats
Do not modify the inputs. Do not attempt to affect the execution of any other program, except via cooperating or defecting. Do not make a sacrificial submission that attempts to recognize another submission and benefit that opponent at its own expense. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned.
EDIT: Submissions may not exactly duplicate any of the [basic programs](https://github.com/isaacg1/noisy-game/blob/master/basic.py) or any earlier submission.
If you have any questions, feel free to ask.
## [Current results](https://github.com/isaacg1/noisy-game/blob/master/results.txt)
```
nicht_genug: 40.6311
stealer: 37.1416
enough: 14.4443
wait_for_50: 6.947
threshold: 0.406784
buckets: 0.202875
change_of_heart: 0.0996783
exploit_threshold: 0.0670485
kickback: 0.0313357
tit_for_stat: 0.0141368
decaying_memory: 0.00907645
tit_for_whoops: 0.00211803
slider: 0.00167053
trickster: 0.000654875
sounder: 0.000427348
tit_for_tat: 9.12471e-05
stubborn_stumbler: 6.92879e-05
tit_for_time: 2.82541e-05
jedi2sith: 2.0768e-05
cooperate: 1.86291e-05
everyThree: 1.04843e-05
somewhat_naive: 4.46701e-06
just_noise: 1.41564e-06
growing_distrust: 5.32521e-08
goldfish: 4.28982e-09
vengeful: 2.74267e-09
defect: 3.71295e-10
alternate: 2.09372e-20
random_player: 6.74361e-21
```
[Results](https://github.com/isaacg1/noisy-game/blob/master/reduced-results.txt) with only answers to this question and basic programs that ignore the opponent's play:
```
nicht_genug: 39.3907
stealer: 33.7864
enough: 20.9032
wait_for_50: 5.60007
buckets: 0.174457
kickback: 0.0686975
change_of_heart: 0.027396
tit_for_stat: 0.024522
decaying_memory: 0.0193272
tit_for_whoops: 0.00284842
slider: 0.00153227
sounder: 0.000472289
trickster: 0.000297515
stubborn_stumbler: 3.76073e-05
cooperate: 3.46865e-05
tit_for_time: 2.42263e-05
everyThree: 2.06095e-05
jedi2sith: 1.62591e-05
somewhat_naive: 4.20785e-06
just_noise: 1.18372e-06
growing_distrust: 6.17619e-08
vengeful: 3.61213e-09
goldfish: 3.5746e-09
defect: 4.92581e-10
alternate: 6.96497e-20
random_player: 1.49879e-20
```
## Winning
The competition will stay open indefinitely, as new submissions are posted. However, I will declare a winner (accept an answer) based on the results 1 month after this question was posted.
[Answer]
# Tit-For-Whoops
*Inspired by a strategy from ncase.me/trust*
```
def tit_for_whoops(m, t, s):
if len(t) < 2:
return 'c'
else:
return 'd' if all([x == 'd' for x in t[-2:]]) else 'c'
```
Defects only if the other player has defected twice in a row, to prevent misunderstandings.
[Answer]
## Change of Heart
```
def change_of_heart(m, t, s):
return 'c' if len(t) < 180 else 'd'
```
Has a change of heart partway through. Does surprisingly well.
[Answer]
# Strategy Stealer
Inspired by enough, change\_of\_heart, and tit-for-whoops.
Should be a little more forgiving. I tried to tweak the numbers for best results but they didn't want to change much.
```
def stealer(mine, theirs, state):
if len(mine) == 0:
state.append('c')
return 'c'
elif len(mine) > 250:
return "d"
elif state[0] == 't':
return 'd'
elif mine[-40:].count('d') > 10:
state[0] = 't'
return 'd'
elif theirs[-1] == 'd':
if state[0] == 'd':
state[0] = 'c'
return 'd'
else:
state[0] = 'd'
return 'c'
elif all([x == 'c' for x in theirs[-3:]]):
state[0] = 'c'
return 'c'
else:
return 'c'
```
[Answer]
## Tit-For-Time
```
def tit_for_time(mine, theirs, state):
theirs = theirs[-30:]
no_rounds = len(theirs)
return "c" if no_rounds < 5 or random.random() > theirs.count("d") / no_rounds else "d"
```
If you've been spending most of the time hurting me, I'll just hurt you back. Probably.
[Answer]
# Growing Distrust
```
import random
def growing_distrust(mine, theirs, state):
# Start with trust.
if len(mine) == 0:
state.append(dict(betrayals=0, trust=True))
return 'c'
state_info = state[0]
# If we're trusting and we get betrayed, trust less.
if state_info['trust'] and theirs[-1] == 'd':
state_info['trust'] = False
state_info['betrayals'] += 1
# Forgive, but don't forget.
if random.random() < 0.5 ** state_info['betrayals']:
state_info['trust'] = True
return 'c' if state_info['trust'] else 'd'
```
The more the opponent betrays me, the less I can trust it was just noise.
[Answer]
# Jedi2Sith
Starts off all nice and selfless, but with time the influence of the dark side grows steadily stronger, until the point of no return. There's no stopping this influence, but all the bad things it sees happening just contribute to the power of the dark side...
```
def jedi2sith(me, them, the_force):
time=len(them)
bad_things=them.count('d')
dark_side=(time+bad_things)/300
if dark_side>random.random():
return 'd'
else:
return 'c'
```
[Try it online!](https://tio.run/##VY7BDoIwDIbvPsVubEoQJV5M8EUIIciKq7KNbOXg088NDsRLm/7/1/6dv6SsqQLq2TpirjfS6iBhZG@QePVIimvIGSnQa@1G6wYQ9wNjhBrqCQxPpojCs5cdKTQvXyepGOxiiGcyS6bs3afzKKHmafG0w@JclWUkcNyhx/ZJsTW@5jHmgBZnWLwYR5g8/MtDFmaHMXL/vWnzJuLt8XIr86YVIvwA "Python 3 – Try It Online")
[Answer]
# Genug ist nicht genug
(could also be called `enough2` or `stealback`)
```
def nicht_genug(m,t,s):
if not s:
s.append("c")
return "c"
if s[0]=="t":
return "d"
if m[-42:].count("d")>10 or len(t)+t.count("d")>300:
s[0]="t"
return "d"
if t[-1]=="d":
if s[0]=="d":
s[0]="c"
return "d"
else:
s[0]="d"
return "c"
else:
if t[-3:].count("d")==0:
s[0]="c"
return "c"
```
I learned that the original *tit for two tats* did wait for two *consecutive* tats like `tit_for_whoops` does, and indeed it seems we should forgive and forget (well, almost...) earlier single tats. And a lot of players defect in the last rounds. I still prefer to be nice when everything has been fine so far, but the bot's tolerance bar keeps getting lower.
[Answer]
## Slider
```
def slider(m, t, s):
z = [[2, 1], [0, 1], [2, 3], [2, 1]]
x = 0
for y in t:
x = z[x][y == 'c']
return 'c' if x < 2 else 'd'
```
Starts off with 'c', and gradually slides towards or away from 'd'.
[Answer]
# Stubborn Stumbler
```
def stubborn_stumbler(m, t, s):
if not t:
s.append(dict(last_2=[], last_3=[]))
if len(t) < 5:
return 'c'
else:
# Records history to state depending if the last two and three
# plays were equal
s = s[0]
if t[-2:].count(t[-1]) == 2:
s['last_2'].append(t[-1])
if t[-3:].count(t[-1]) == 3:
s['last_3'].append(t[-1])
c_freq = t.count('c')/len(t)
# Checks if you've consistently defected against me
opp_def_3 = s['last_3'].count('d') > s['last_3'].count('c')
opp_def_2 = s['last_2'].count('d') > s['last_2'].count('c')
# dist func from 0 to 1
dist = lambda x: 1/(1+math.exp(-5*(x-0.5)))
# You've wronged me too much
if opp_def_3 and opp_def_2:
return 'd'
# Otherwise, if you're consistently co-operating, co-operate more
# the less naive you are
else:
return 'c' if random.random() > dist(c_freq) - 0.5 else 'd'
```
Based off of your exploit threshold strategy with only consistent plays kept track for switching between defect and mostly co-operate
UPDATE: Keeps track of both two consecutive and three consecutive plays, punishing only under harsher conditions and adding a random choice when not sure
UPDATE 2: Removed condition and added distribution function
[Answer]
# Noise Bot
```
def just_noise(m,t,s):
return 'c' if random.random() > .2 else 'd'
```
I'm definitely cooperate bot. That's just noise.
[Answer]
# Enough is Enough
```
def enough(m,t,s):
if not s:
s.append("c")
return "c"
if s[0]=="t":
return "d"
if m[-42:].count("d")>10:
s[0]="t"
return "d"
if t[-1]=="d":
if s[0]=="d":
s[0]="c"
return "d"
else:
s[0]="d"
return "c"
else:
return "c"
```
Starts as *tit for two tats* where the two tats don't have to be consecutive (unlike `tit_for_whoops`). If it has to play `d` too often it goes `d`-total.
[Answer]
# Goldfish Bot
```
def goldfish(m,t,s):
return 'd' if 'd' in t[-3:] else 'c'
```
A goldfish never forgives, but it quickly forgets.
[Answer]
>
> ## trickster (reinstated again)
>
>
> Only the last 10 plays are accounted for, but divided into two blocks of five, which are averaged with each classified as good or bad.
>
>
> If the opponent plays on average "nice", the trickster plays less and less nice. If the results are ambiguous the trickster plays nice to lure the opponent into safety.
> If the opponent appears to be playing "bad" the trickster retaliates.
>
>
> The idea is to gather points now and then from naïve players, while catching deceitful ones early.
>
>
>
> ```
> import random
> def trickster(player,opponent,state):
> pBad = 0.75
> pNice = 0.8
> pReallyBad =0.1
> decay = 0.98
> r = random.random()
>
> ```
>
>
```
if len(player)<20: #start off nice
return 'c'
else: #now the trickery begins
last5 = opponent[-5:].count('c')/5.0 > 0.5
last5old = opponent[-10:-5].count('c')/5.0 > 0.5
if last5 and last5old: #she is naive, punish her
pBad = pBad*decay #Increase punishment
if r<pBad:
return 'c'
else:
return 'd'
elif last5 ^ last5old: #she is changing her mind, be nice!
if r<pNice:
return 'c'
else:
return 'd'
else: #she's ratting you out, retaliate
pReallyBad = pReallyBad*decay #Retaliate harder
if r<pReallyBad:
return 'c'
else:
return 'd'
```
>
> Disclaimer: I have never posted here before, if I am doing something wrong >please tell me and I'll correct.
>
>
>
[Answer]
## Decaying Memory
```
def decaying_memory(me, them, state):
m = 0.95
lt = len(them)
if not lt:
state.append(0.0)
return 'c'
# If it's the last round, there is no reason not to defect
if lt >= 299: return 'd'
state[0] = state[0] * m + (1.0 if them[-1] == 'c' else -1.0)
# Use a gaussian distribution to reduce variance when opponent is more consistent
return 'c' if lt < 5 or random.gauss(0, 0.4) < state[0] / ((1-m**lt)/(1-m)) else 'd'
```
Weighs recent history more. Slowly forgets the past.
[Answer]
### Kickback
```
def kickback(m, t, s):
if len(m) < 10:
return "c"
td = t.count("d")
md = m.count("d")
f = td/(len(t)+1)
if f < 0.3:
return "d" if td > md and random.random() < 0.1 else "c"
return "c" if random.random() > f+2*f*f else "d"
```
Some vague ideas...
[Answer]
# Doesn't Really Get The Whole "Noise" Thing
```
def vengeful(m,t,s):
return 'd' if 'd' in t else 'c'
```
Never forgives a traitor.
[Answer]
# sounder:
edit: added retaliation in probably low noise scenarios
basically, if all 4 first moves are cooperate, that means we should expect less noise than usual. defect a little bit every so often to make up for the less points we would get from never defecting, and have it be able to be blamed on noise. we also retaliate if they defect against us
if our opponent does a lot of defecting in those turns (2 or more) we just defect back at them. if it was just noise, the noise would affect our moves anyway.
otherwise, if only 1 move was defect, we just do simple tit for tat the rest of the game.
```
def sounder(my, their, state):
if len(my)<4:
if their.count("d")>1:
return "d"
return "c"
elif len(my) == 4:
if all(i == "c" for i in their):
state.append(0)
return "d"
elif their.count("c") == 3:
state.append(1)
return "c"
else:
state.append(2)
if state[0] == 2:
return "d"
if state[0] == 0:
if not "d" in my[-4:]:
return "d"
return their[-1]
else:
return their[-1]
```
[Answer]
# Alternate
```
def alternate(m, t, s):
if(len(m)==0):
return 'c' if random.random()>.5 else 'd'
elif(len(m)>290):
return 'd'
else:
return 'd' if m[-1]=='c' else 'c'
```
Picks randomly in the first round, then alternates. Always defects in the last 10 rounds.
[Answer]
# Wait for 50
```
def wait_for_50(m, t, s):
return 'c' if t.count('d') < 50 else 'd'
```
After 50 defects, let 'em have it!
[Answer]
**Somehwat naive**
```
def somewhat_naive(m, t, s):
p_flip = 0.25
n = 10
if len(t) < n:
return 'c' if random.random() > p_flip else 'd'
d_freq = t[-n:].count('d')/n
return 'c' if d_freq < p_flip else 'd'
```
I'll just assume that if you've defected less than the flip probability (roughly) in the last *n* turns, it was noise and not that you're mean!
Haven't figures out the best *n*, might look further into that.
[Answer]
# Every Three
```
def everyThree(me,him,s):
if len(me) % 3 == 2:
return "d"
if len(me) > 250:
return "d"
if him[-5:].count("d")>3:
return "d"
else:
return "c"
```
Defects every three turns regardless. Also defects the last 50 turns. Also defects if his opponent defected 4 out of 5 of the last rounds.
[Answer]
# Buckets
```
def buckets(m, t, s):
if len(m) <= 5:
return 'c'
if len(m) >= 250:
return 'd'
d_pct = t[-20:].count('d')/len(t[-20:])
if random.random() > (2 * d_pct - 0.5):
return 'c'
else:
return 'd'
```
Plays nice to begin. Looks at their last 20, if < 25% d, returns c, > 75% d, returns d, and in between chooses randomly along a linear probability function. Last 50, defects. Had this at last 10 but saw lots of last 50 defects.
First time here so let me know if something needs to be fixed (or how I can test this).
[Answer]
# Tit-for-Tat (pseudocode)
I'm surprised no one has put a basic tit-for-tat
Also, is the challenge considered over because not a lot of people have posted, and is it against the stack exchanges rules to post on an old thread?
```
def tit_for_tat (my-moves, op-moves) {
if (op-moves[last] == 'D')
return D
else
return C
}
```
[Answer]
# Tit-For-Stat
Defects if the opponent has defected more than half the time.
```
def tit_for_stat(m, t, s):
if t.count('d') * 2 > len(m):
return 'd'
else:
return 'c'
```
] |
[Question]
[
## Definition
An [arrowhead matrix](https://en.wikipedia.org/wiki/Arrowhead_matrix) is a [matrix](https://en.wikipedia.org/wiki/Matrix_(mathematics)) that has all entries equal to **0**, except the ones on the main diagonal, top row and leftmost column. In other words, the matrix should look like this:
```
* * * * * *
* * 0 0 0 0
* 0 * 0 0 0
* 0 0 * 0 0
* 0 0 0 * 0
* 0 0 0 0 *
```
Where each *\** is any non-zero entry.
## Task
Given a square matrix of non-negative integers, check whether it is arrowhead according to the definition above.
You may *not* take the size of the matrix as input, unless your language’s equivalent to an array is something like a pointer and a length (like C). It will always be at least 3 x 3.
The shortest code [in bytes](https://codegolf.meta.stackexchange.com/questions/10145/how-to-count-bytes-faq) in each language wins.
## Input and Output
You can pick among any of the following formats for receiving input:
* A matrix in the native matrix type (if your language has one)
* A 2D array1 (an array of 1D arrays, each corresponding to one row)
* A 1D array (since the matrix is always square)
* A string (you chose the spacing, but please do not abuse this in any way).
When it comes to providing output, you can either report a [truthy / falsy](https://codegolf.meta.stackexchange.com/q/2190/59487) value following the standard [decision-problem](https://codegolf.stackexchange.com/tags/decision-problem/info) definition, or choose any two distinct and consistent values.
Moreover, you can take input and give output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. If want to pick any other format or are unsure about something, please ask in the comments.
1: or your language's equivalent (list, vector, etc.)
## Examples
Let's look at the following examples:
```
1 2 2 2
2 1 0 0
3 0 1 0
4 0 0 1
```
This is an arrowhead matrix (your programs should report a truthy value), because the elements on the main diagonal are `1 1 1 1`, those on the top row are `1 2 2 2` and those on the leftmost column are `1 2 3 4`. All other entries are **0**, so this satisfies all the conditions.
```
3 5 6
7 1 0
8 0 0
```
This matrix is *not* arrowhead because there is a **0** on the main diagonal.
```
9 9 9 9
9 9 0 0
9 7 9 0
9 0 0 9
```
This one is *not* arrowhead either, because it contains a **7** in place of a **0**.
## More test cases
Truthy:
```
[[1, 1, 1], [1, 1, 0], [1, 0, 1]]
[[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]
[[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]
[[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]
```
Falsy:
```
[[3, 5, 6], [7, 1, 0], [8, 0, 0]]
[[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]
[[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]
[[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]
```
[Answer]
# Javascript (ES6), ~~48~~ 47 bytes
*Saved 1 byte thanks to edc65*
```
m=>m.some((r,y)=>r.some((c,x)=>(x*y&&x!=y)^!c))
```
Returns `false` for arrowhead matrices and `true` for non-arrowhead matrices (allowed since any two distinct values can be used to represent true and false)
## Test cases:
```
f=m=>m.some((r,y)=>r.some((c,x)=>(x*y&&x!=y)^!c))
console.log(f([[1, 1, 1], [1, 1, 0], [1, 0, 1]]))
console.log(f([[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(f([[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]))
console.log(f([[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]))
console.log(f([[3, 5, 6], [7, 1, 0], [8, 0, 0]]))
console.log(f([[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]))
console.log(f([[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(f([[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]))
```
[Answer]
# [J](http://jsoftware.com/), ~~21~~ ~~20~~ ~~19~~ ~~17~~ 15 bytes
### -4 bytes thanks to @GalenIvanov.
```
*-:1,1,.=&/:@}.
```
Takes input as a matrix (rank 2 array).
[Try it online!](https://tio.run/##fZDLCsIwEEX3@YpZiKjUmDaxMUpBXLh05Q/0JUUEwXcEv71OHth0I7c3Jb1nhpke292Gwv5yvzWa5JBR4KgBxD8xZ1KYUKBMmCAkfMw6yN1I2UedXMg9JjxadSjHhjHwOaBSfKRF5gs8UqlMDbNfJDEjb/PTtdbk2Y3MsTAFadubIkZeXXMVyDRRCCr7tjeiw5HZ3@3eIZo6lOOCOCYkyoOJhUV7yOhkuoyjOKLZcLZcf2j4w@uyOcMB6kd90TDKYQUFukRX43DLPvfE/IXW6Pe4/QI "J – Try It Online")
# Explanation
Let the edit history be a lesson to you not to golf and write an explanation at the same time.
```
* -: 1, 1,. = & /: @ }. Let m be the input matrix.
= & /: @ }. Identity matrix 1 smaller than m.
}. Behead (m without its first row).
@ Composed with.
/: Grade up (get len(m) - 1 unique elements)
& Composed with.
= Self-classify (compare equality with
unique elements)
1,. Prepend a column of 1s
1, Prepend a row of 1s
* Signum (0 becomes 0, n > 0 becomes 1)
-: Does it match the generated arrowhead matrix?
```
### Visual explanation
Note that this is done on the REPL (inputs are given starting with three spaces and output are given without any leading spaces). Because of that, I sometimes omit composition functions like `@` and `&` since things on the REPL are evaluated right-to-left (functions are more complex).
Suppose you have the following sample matrix:
```
] m =. 4 4 $ 1 2 3 4 1 1 0 0 1 0 1 0 1 0 0 1
1 2 3 4
1 1 0 0
1 0 1 0
1 0 0 1
```
First, I'd like to explain (and give a shoutout to) @GalenIvanov's very clever way of generating the identity matrix, which is the following `=&/:@}.`.
First, we behead the input matrix (`}.`).
```
}. m
1 1 0 0
1 0 1 0
1 0 0 1
```
Then we get the indices each row would be in were the rows sorted using `/:`-grade up.
```
/: }. m
2 1 0
```
Note that the resulting indices are *unique*: the list has no duplicate elements (and why would it? There's no way to place two elements in the same position in an array).
Finally, we use the niche but helpful `=`-self-classify. This monad compares each unique element to all of the other elements in an array. Remember how I mentioned it was important that the resulting indicies are unique? Since `=`-self-classify does the comparisons in the order that the unique elements appear in the list, the resulting output will be the identity matrix for a unique input (this is why `=@i.` is how you can make an identity matrix of a given length).
```
= /: }. m
1 0 0
0 1 0
0 0 1
NB. This is what is happening
(2 = 2 1 0) , (1 = 2 1 0) ,: (0 = 2 1 0)
1 0 0
0 1 0
0 0 1
```
Once we have the identity matrix, it's a matter of adding a row of ones and a column of ones, which is done very simply (if given an atom - i.e. a single element - the `,` family will repeat it to fill when it's being added):
```
1,. (=&/:@}. m)
1 1 0 0
1 0 1 0
1 0 0 1
1, (1,. =&/:@}. m)
1 1 1 1
1 1 0 0
1 0 1 0
1 0 0 1
```
Then we simply compare the generated arrowhead matrix to the signum of the input matrix.
```
* m
1 1 1 1
1 1 0 0
1 0 1 0
1 0 0 1
(* m) -: (1, 1,. =&/:@}. m)
1
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
Clip@#==Array[If[1<#!=#2>1,0,1]&,{1,1}Tr[1^#]]&
```
[Try it online!](https://tio.run/##LYnBCgIhFAB/5YWwp3fwtatWZBSdunXo9jCQSBLaCPES4rfbsgVzGGZGnx/30ed48y1sbDs@43svrD2k5D98CkxbsbBiuSOUSK7DQkj1kpiuwrmunVN8ZQ5cSj8gECH0CkFVhKL0JNogyIk5rGbXZv0Pg/xNBFOrc@0L "Wolfram Language (Mathematica) – Try It Online")
Explanation: `Clip@#` replaces all the non-zero numbers in the matrix with 1s, then we compare this to an array with dimensions `{1,1}Tr[1^#]` = `{Length@#, Length@#}` with 0 in position `i,j` when `1 < i != j > 1`, and 1 otherwise.
(Roughly based on [Uriel's answer](https://codegolf.stackexchange.com/a/151367/66104).)
Here's another idea that's 16 bytes longer — feel free to steal it if you can golf it down:
```
Union@@Array[{1,#}~Tuples~2&,Length@#]==Most@Keys@ArrayRules@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Zl@z80LzM/z8HBsagosTK62lBHubYupLQgJ7W4zkhNxyc1L70kw0E51tbWN7@4xME7tbIYojSoFKjEQVntf0BRZl5JdFp0dbWxiY6CoaGOgrGpjoJprY5CtakZkGFmrqNgAERgAQsw28zcEipgYgCR1FEwr62Njf0PAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~19~~ ~~16~~ ~~15~~ 13 bytes
-1 byte thanks to @ErikTheOutgolfer
(`⎕IO←0`)
```
×≡(∧=⌊)/¨∘⍳∘⍴
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud9UT/9HbRMMuIAsIK1xePqjzoUajzqW2z7q6dLUP7TiUceMR72bweQWTWMFYyBFpGITBRMgZahgBIWGCgZAaAzEIJYJmGf4/z8A)
-2 bytes thanks to @ngn and @H.PWiz
## How?
(2D input matrix **S**)
* `×≡` Check whether **S** is positive only on ...
* `(∧=⌊` ... the diagonals or the top row and left column ...
* `)/¨∘⍳∘⍴` ... of **S**.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~112~~ 108 bytes
```
param($a)$o=+!(0-in$a[0]);1..($x=$a.count-1)|%{$i=$_;0..$x|%{$o*=(!($y=$a[$i][$_]),$y)[!$_-or$_-eq$i]}};!!$o
```
[Try it online!](https://tio.run/##RYrtCoIwGIX/dxUbvMHemmPDr0IG3scQGSEkmDMrUsprX6uI4HA4z8MZ3L0ZL8em67wf7GhPDCyC01vKZNT2YI2ssFBCMJg0WHFwt/4aKXyuH9BqqAspBExvchvNKIM5vAy0lYG6Qg4zGgp15MZQzTn4ZSkoBee9L1nJ4oQTpTiJU05S5CtCSpZmYWc5JzLk53YfzPL93yXye@EkR3wB "PowerShell – Try It Online")
Takes input and manipulates as an array-of-arrays, since PowerShell doesn't support matrices (outside of the .NET Direct3D transform matrices support, which is something entirely different).
The whole algorithm is based on the fact that non-zero numbers are truthy and zero is falsey in PowerShell, and using multiplication to determine those truthy/falsey values.
We first take the first row, `$a[0]`, and check whether `0` is `-in` that array, store that into our `$o`utput variable. If anything in that row is zero, then the `$o` is also zero, otherwise it's one, done by a quick cast-to-int with `+`.
Next we loop from `1` up to `$a.count-1`, setting `$x` along the way -- we're going to be looping through each row one at a time.
Each iteration we set helper variable `$i` to keep track of what row we're on, then loop from `0` to `$x` to iterate each element in this row. Inside the inner loop, we're again multiplying `$o`, this time by selecting from a tuple setup as a pseudo-ternary operator.
The tuple's conditional, `!$_-or$_-eq$i`, says "when we're on the 0th column, or the column matches the row (i.e., the main diagonal)" to select the second half of the tuple when truthy or the first half when falsey. The tuple is composed of `!($y=$a[$i][$_]), $y`. The first half sets `$y` for golfing the second half, but either way we're selecting the current element. The first half does Boolean negation on it, while the second half just takes the element as-is. Thus, if we're not on the 0th column nor the main diagonal, we ensure that the element is zero by taking the Boolean-not of it. Similarly, we ensure the 0th column or main diagonal is non-zero by simply taking it.
So now that we've iterated through every element in the matrix, `$o` is either going to be `0` if some element was incorrect, or some non-zero integer if it is an arrowhead matrix. We double-Boolean-not that to get either `False` or `True` respectively, to make our output consistent, and that's left on the pipeline where printing is implicit.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes
```
ŒDµḢ;Ḣ€Ȧ>FẸ$
```
-2 bytes from Pietu1998
[Try it online!](https://tio.run/##y0rNyan8///oJJdDWx/uWGQNxI@a1pxYZuf2cNcOlf///0dHW@qY6xjqGMbqRINoAx0DMMsAxIaygOzYWAA "Jelly – Try It Online")
**Explanation**
```
[[9,7,1],
[7,1,0],
[7,0,1]]
```
Use the above matrix as an example input.
```
ŒDµḢ;Ḣ€Ȧ>FẸ$
ŒD Diagonals → [[9, 1, 1], [7, 0], [1], [7], [7, 0]]
µ New monadic link
Ḣ Head → [9, 1, 1]. Alters diagonals list.
;Ḣ€ Append with the head of each of the other diagonals → [9, 1, 1, 7, 1, 7, 7]
Ȧ Logical all → 1
FẸ$ Flatten what's left in diagonals then take logical any → [[0],[],[],[0]] → [0,0] → 0
> Matrix is an arrowhead iff result of Ȧ > result of Ẹ
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~21~~ ~~18~~ 17 bytes
```
×≡1⍪1,(=/¨∘⍳1-⍨⍴)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TD0x91LjR81LvKUEfDVv/QikcdMx71bjbUfdS74lHvFk2gIgVjIASyFQzh0ACCudIUTIAQImcEhSAZA6AOiBoTMA@kEmaKsYKpgpmCOVjWAiSLZIolEgTpswSqswTTYB4A)
**How?**
This one goes the other way -
`=/¨∘⍳` - creates the identity matrix
`1-⍨⍴` - for `n - 1`
`1⍪1,` - prepends a column and a row of 1s
`≡` - compares with
`×` - the original matrix, after it has gone an element-wise signum-ing
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
gtZyXy,!llY(]X=
```
Input is a matrix (using `;` as row separator). Output is `1` for arrowhead, `0` otherwise.
[Try it online!](https://tio.run/##y00syfn/P70kqjKiUkcxJydSIzbC9v//aEMFIxC0BhKGCgYKBtYKxkDKEMQwAfEVDGMB "MATL – Try It Online") Or [verify all test cases](https://tio.run/##lY89DsIwDIV3TmE2hgxufqksNo7AUECRYGIJW5eePnXipgojkpU82@@z7O97TvmVP/NjmRZ1TOl@itMlX2/5OSgoQSACq0DW8VB6WoFRYPd27@j0D1CCyrsDpgNsDxjOBq4bp8AROM@fDw1z56p8GIXEhoaCspV7BKFNFjdyj/1b0CZkIIsgKbUip7I4/nup3wFTb8a6jR47RDfExhU).
### Explanation
```
g % Implicit input. Convert to logical values (nonzero becomes true and
% zero becomes false)
t % Duplicate
Zy % Size
Xy % Identity matrix of that size
, % Do twice
! % Transpose
ll % Push 1 twice
Y( % Write 1 at all entries of row 1
] % End
X= % Are the two matrices (input and constructed) equal? Implicit display
```
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
```
lambda m,E=enumerate:all((x[j]>0)-(i>0<j!=i)for i,x in E(m)for j,y in E(m))
```
**[Try it online!](https://tio.run/##nVKxboMwEN35iutmVFdybDAhKpE6pOrQqU2HinogCqhGmESISsnXU9vYTZyx6IZ3d@@98504nsfvQ0@n7dvH9uUTCijLcoHBhMDgIHGQmKrAkaVQDAxDcsUKiUF2qzRhujRQskCZ3CiZLix0k6UYUkNIuQY8u@jTpcU8y70F8R6ZECKKnp9e392Sepb24YaVXWYunZkdqF1cmNYM/SgNs7ngsnlM/rck@fd5@JWS2VMR91CaB1rqtYldrim@pq5Su30FCm@Kuv9R9VCN9arqOoROZSvWJH5Ack0e27tCxs1hAIlPIHvYIGXTFp99Gk@moEzq/o17sOdbRaC/4yD7ETWW@As "Python 2 – Try It Online")**
# [Python 2](https://docs.python.org/2/), 85 bytes
Taking the array as a 1D matrix:
```
def f(m):s=len(m)**.5;print all((v<1)^(0in(p>s,p%s,p//s-p%s))for p,v in enumerate(m))
```
**[Try it online!](https://tio.run/##nVJNa8MwDL3nV@gysDtvdZyvplsHu4wddtq6wwgeBOqwQOKGJC3s12dy4rR1jwsKPOvpPVnCzW//s9di2L5/bl@/YANZlvkMTEgGFnILuclK5o0lgkHAILyocgud07XShGGFowwcZXilDDDhIxlEDCJTEMUI4uSsj1YjjpN0tuCzRyKl9LyX57cPOyT2Qp/YVCXnnitrNjZEFxuGmuDcCmEyJexpapOehuT/Xk98oQzGVXF7UZE6WjFrQzPcsFMFFKSm625TKY1gsbiPHpq21D3kVUXI8dGn34SXmjRPHWtu8F8uuzsElBb7Fhp2hFKD0odatXmv0IIOhqhN2r6QWxiXuPYAv6LK@15ptcOddoea1CyTdGLIiaPDHw "Python 2 – Try It Online")**
[Answer]
# [R](https://www.r-project.org/), ~~78~~ ~~70~~ ~~69~~ ~~68~~ ~~54~~ 53 bytes
```
function(m){d=diag(nrow(m))
d[1,]=d[,1]=1
all(d!=!m)}
```
[Try it online!](https://tio.run/##XY7NTsMwEITvfgrXvexKi5QUaEHCB4TKiRM/p9QHUydVJDeNYgeEqj57sJOUtlg@zKznm3XT@dz5J@1y/nDFi7Za@3JXgcM9c7qu7Q/kX9pCrRuXg5cb136CUIIEChrMapUFa0vnQZDDcKitokV2YEVo7f5at7g30pR6A1Wz@w4WmclSUtJklCqZMm0tmImcbPHQFXD8GYgspHi8ivgok1EmcaoEIp/y99ePJbvkronfEp/H8OLE3fVccuSeH1/e/oMhOice8Jt@URCzHuqrZvfD4rFueEli9ryx@wU "R – Try It Online")
Porting [Luis Mendo's answer](https://codegolf.stackexchange.com/a/151358/67312) is much shorter than my former approach.
Thanks to [rturnbull](https://codegolf.stackexchange.com/users/59052/rturnbull) for pointing out a bug, and golfing down a byte!
### old answer, 68 bytes:
```
function(m,i=which(!m,T))all(i[,1]-i[,2],i!=1,sum(m>0)==3*nrow(m)-2)
```
[Try it online!](https://tio.run/##XY5fS8MwFMXf@ymy@HLvuIW006lgBBF98km3py4P3WhdIO1KkzpE/Ow1aTv/hRDOSc7v3LS9K6y7z23BbmJWdvXO6UMNFj8imzeNeYfiLTfQ5K0twMlX222BK04cOY1ms8m8Ndo64GTRL@rqYDH6jErf2n@3VqTlca93e5hVtELMjQGdUaJif6aK9EwmZLsKqluBUi7mdXs4QoVxin0Jp48Cz7KEWNiK2CTFJEW4VRyRnbHV8/oh@sstiF0QW4bw5Q93NXDixD3ePb38B310Sczj58MgL9IBGqrS63HwVDe@iJD93dh/AQ "R – Try It Online")
[duckmayr's answer](https://codegolf.stackexchange.com/a/151370/67312) tests that all entries on the main diagonal and first row/column (`m[i]`) are nonzero and the rest (`m[-i]`) are zero, using some nice arithmetic to get the diagonal and the first row.
This answer, however, tests to make sure that (1) zero entries are not on the main diagonal or the first row/column, and (2) that there are, given an `n x n` matrix, `3*n-2` nonzero entries.
`which` returns the indices where its input is `TRUE`, and with the optional `arr.ind=T`, returns an array of indices for each array dimension, in this case, two.
Hence when `any(i[,1]==i[,2])`, there exists a zero on the diagonal, and when `any(i==1)`, there exists a zero in the first row or the first column.
Finally, a little arithmetic shows that the number of nonzero entries must be `3*n-2`, `n` from the first column, `n-1` from the diagonal, and `n-1` from the first row.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~80~~ ~~75~~ 69 bytes
```
i;f(A,n)int*A;{for(i=0;i<n*n;)n*=A[i]<1^(i<n|i%n<1|i/n==i++%n);n=!n;}
```
[Try it online!](https://tio.run/##rZHNaoQwEIDvPkW6ICRuShMTjRI9@BzbLZRtLTk0LVtvrs9uY6LB7gYppTL@MHG@b4Y53b@dTuOoZAsbrJHSXdLIvv04Q1UTqSqdaIl0UjcHdazoEzSZi4p1RS/qQde12u9jjaSu77QcRlMN3p@VhijqI2CuKdG9fnXkcAQ16AkGdBXEPwdpf/88m4IW7uKXR73DoIW2FgOGkIx@AKkD0r8AaQiYemBqjjHgKya5gvvklsVg@I2FrS0@PJCt@PxXFhaycGdh0wzTsBkGU@TTLRZsVthXLkqnI8uB2PLxkC@bfVZjLGKZwSnIFjALLSN3QNPZVbgOS6sol@85uWXJQ20LvwzyPysXIUvhLbm3MLt2YlNpuTKki4ffeIwFzJ5i9gzjNw "C (gcc) – Try It Online")
Saved 5 bytes thanks to scottinet! And 6 more thanks to ceilingcat!
Reused the test code from [this answer](https://codegolf.stackexchange.com/a/151376/31625).
Linearly scans the array for any incorrect values, returning 0 for an arrowhead matrix and 1 otherwise. We check by computing the exclusive or of whether the item at a given position is zero and whether that position is on the arrow.
Encoding the information of the 2D array into one dimension leads to a fairly simple set of conditions. If we let `i` be our 0-based index into the `n` dimensional array, then `i<n` describes the first row. Similarly, `i%n==0` describes the first column and `i/n==i%n` describes the diagonal.
The best trick I found for handling the return is to set the dimension to zero when encountering an error. This causes the loop to terminate immediately, then returning the logical negation of the dimension will give us one of two distinct values. scottinet found the way to make GCC return it more nicely.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~92~~ 90 bytes
```
def f(m):l=len(m);return all((m[a%l][a/l]<1)^any([a<l,a%l<1,a/l==a%l])for a in range(l*l))
```
[Try it online!](https://tio.run/##RYzbCsIwDEDf/YqACK0EXHd1un1JqVCw1UHWjbo97OtndxEhDycn4fTT8O5cPM9PY8Gylt@oJuMC3L0ZRu9AEzHWSn0iJfWFVCX4Q7uJSV0RBlsJDLqulwduOw8aGgdeu5dhdCbO5943bmCWSZmkCEIgJBlCphBklgfIC4QozCquK@dFuYs02o4IhVKcw3Hwozn8k6EWGglCunyLAPFWWNa4XFnsrfiXSreU1fQx8xc "Python 2 – Try It Online")
# Credits
* Reduced from 92 bytes to 90 by [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
*-3 bytes thanks to Mr. Xcoder. -13 bytes thanks to user28667. -5 bytes thanks to Zgarb.*
```
z=zip[0..]
f m=and[(i==j||i*j<1)==(a>0)|(i,r)<-z m,(j,a)<-z r]
```
[Try it online!](https://tio.run/##pZBBDoMgEEX3PcUssZkaFJWalN6gJyAsSNqm2GqM7cp4dwuKUZLuSmbxGd7/Azz0@3l7vcaxF71pJY1jtbtDLXRzlcQIUQ2D2VenJBKC6DONBmKwi06HHmokFepJdmqstWlAQK3bC5C2M80HYrhHO7BLgpQJgiuF4CX1krqumjicuRSBIWQbNKSD3U@7K4ekgZ0F9uyXndluYgmWI@SOygsrCr6G5MdJF7xccugSxLdB1mYpB/B15tHnrJxN8eXOZ7mMspLPDb@bx5Thc@l/v1Vs7Gz6OervnZZBQLoEZEqBGr8 "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ŒDµḢṠQṭT€E
```
[Try it online!](https://tio.run/##y0rNyan8///oJJdDWx/uWPRw54LAhzvXhjxqWuP6/3A7kAIi9///o4HAUEcBhGJ1FKBMAyjTACQaq8OloABWZKSjYKyjYIKkDlUpCg9TLwiB5I1Q9Bqj6DXB0GsMFDIEShub6iiYgpSYmgEZZuYIE0wtwGwzc0uYIQYwU8xjwcYA/Qi0BmiAGUjaHGGdBdQUqF1AA6AIJAlhwmwBMs0hAlAexAZLJD8aUBA@Zkh6jcFhZQB1rpElim4jmG4ToN9iAQ "Jelly – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~72~~ 71 bytes
```
lambda x,e=enumerate:any(0**n^(0<i!=j>0)for i,r in e(x)for j,n in e(r))
```
*Thanks to @xnor for golfing off 1 byte!*
[Try it online!](https://tio.run/##pVHBboMwDD2Xr/BupPIhJZCUauw7Kq1MYlrQqNa0QkyiX8/sEFSiHoeM9J7t9xwnt/vwfXVqaqGC0/TTXD6/GhjRVtb9XmzfDPbQuHsqt1v3kcrX7qU6v0nRXnvokH4HNh09PaObaS/ExIkj01PyTt8OgaNGCFAGKDlbYwLgmzIEhZCv@uLWiD1rObieRVoVafMnraLUjsqqQCi4pdAEtHk4FHuPtSkXE7m4mNrb0I40hgw0l81j3D64hFlkEIKLM1ymEDRzIrB5QrnaUf7jfvRKq/xdyXDcrIzU2aLOabf6kGz4MUd@zCORza3v3JC29OoiCURMfw "Python 3 – Try It Online")
[Answer]
# Pyth, ~~22~~ 21 bytes
This is definitely not the language for matrix manipulation.
```
.As.e+!MWk.Db,0k,@bkh
```
For each row `b` and its index `k` in the matrix (`.e`), grabs the first and `k`th entries (left side and diagonal) with `,@bkh` and (`+`) all the other entries with `.Db,0k`. If `k` isn't 0 to correspond to the first row (`Wk`), then `!`not `M` all of those entries. Once all of those have been selected, make sure all of them are true. (`.As`) If there's a 0 where there shouldn't be, then the corresponding location will be grabbed as is and mess up the and, and if there's a nonzero where there shouldn't be, it'll be `!` notted to 0, which is also false.
[Test suite.](https://pyth.herokuapp.com/?code=.As.e%2B%21MWk.Db%2C0k%2C%40bkh&input=%5B1%2C2%2C3%2C4%5D&test_suite=1&test_suite_input=%5B%5B1%2C+2%2C+2%2C+2%5D%2C%5B2%2C+1%2C+0%2C+0%5D%2C%5B3%2C+0%2C+1%2C+0%5D%2C%5B4%2C+0%2C+0%2C+1%5D%5D%0A%5B%5B1%2C+1%2C+1%5D%2C+%5B1%2C+1%2C+0%5D%2C+%5B1%2C+0%2C+1%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%5D%2C+%5B1%2C+1%2C+0%2C+0%5D%2C+%5B1%2C+0%2C+1%2C+0%5D%2C+%5B1%2C+0%2C+0%2C+1%5D%5D%0A%5B%5B1%2C+2%2C+2%2C+2%5D%2C+%5B2%2C+1%2C+0%2C+0%5D%2C+%5B3%2C+0%2C+1%2C+0%5D%2C+%5B4%2C+0%2C+0%2C+1%5D%5D%0A%5B%5B34%2C+11%2C+35%2C+5%5D%2C+%5B56%2C+567%2C+0%2C+0%5D%2C+%5B58%2C+0%2C+679%2C+0%5D%2C+%5B40%2C+0%2C+0%2C+7%5D%5D%0A%5B%5B3%2C+5%2C+6%5D%2C%5B7%2C+1%2C+0%5D%2C%5B8%2C+0%2C+0%5D%5D%0A%5B%5B9%2C+9%2C+9%2C+9%5D%2C%5B9%2C+9%2C+0%2C+0%5D%2C%5B9%2C+7%2C+9%2C+0%5D%2C%5B9%2C+0%2C+0%2C+9%5D%5D%0A%5B%5B3%2C+5%2C+6%5D%2C+%5B7%2C+1%2C+0%5D%2C+%5B8%2C+0%2C+0%5D%5D%0A%5B%5B9%2C+9%2C+9%2C+9%5D%2C+%5B9%2C+9%2C+0%2C+0%5D%2C+%5B9%2C+7%2C+9%2C+0%5D%2C+%5B9%2C+0%2C+0%2C+9%5D%5D%0A%5B%5B1%2C+0%2C+3%2C+4%5D%2C+%5B1%2C+1%2C+0%2C+0%5D%2C+%5B1%2C+0%2C+1%2C+0%5D%2C+%5B1%2C+0%2C+0%2C+1%5D%5D%0A%5B%5B1%2C+6%2C+3%2C+4%5D%2C+%5B13%2C+2%2C+0%2C+6%5D%2C+%5B29%2C+0%2C+1%2C+0%5D%2C+%5B2%2C+0%2C+0%2C+4%5D%5D&debug=0)
-1 bytes for swapping the orders around.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~31~~ ~~23~~ 22 bytes
```
{0<_!=B>0MC#a==0=_MMa}
```
This is a function that takes a 2D nested list of numbers. [Try it online!](https://tio.run/##K8gs@K/xv9rAJl7R1snOwNdZOdHW1sA23tc3sfa/RphCYZC6jrq1pub/6GhDHQUzHQVjHQWTWB2FaEMgw0hHwQCIQFwjSzDbEMaFyIDUxgIA "Pip – Try It Online")
### Explanation
A whole lot of comparisons going on here. The first thing to know is that comparison operators in Pip can be chained together, like in Python: `5>4>3` is `5>4 and 4>3` (true), not `(5>4)>3` (false). The second is that this doesn't apply to `==`, the "exactly equals" operator. Another difference: regular comparisons have higher precedence than the mapping operators `MC` and `MM` and can be used in lambda expressions, while `==` has lower precedence and can't.
```
{ } Define a function with argument a:
0<_!=B>0MC#a Generate a matrix (as nested lists) that has 0 on the first row,
first column, and main diagonal, and 1 elsewhere (see below for
details)
0=_MMa Map the function 0=_ to the elements of the elements of a,
generating a matrix that is 0 where a is nonzero and vice versa
== Test if the two matrices are equal, returning 0 or 1 accordingly
```
To generate the first matrix, we use `MC`, "map-coords." This operator takes a number, generates a square coordinate grid of that size, and maps a function to each (x,y) coordinate pair, returning a list of lists of the results. For example, `{a+b} MC 3` would give the result `[[0; 1; 2]; [1; 2; 3]; [2; 3; 4]]`.
Here, the size of the grid is `#a`, the size of our original argument. The function is `0<_!=B>0`, which is a shorter way of writing `{0 < a != b > 0}`:
```
{ } Function; a and b are the arguments (in our case, row and column)
0<a Return 1 (truthy) if a is greater than 0
!=b and a is not equal to b
>0 and b is greater than 0
```
This returns 0 for the first row/column and the main diagonal, and 1 elsewhere.
[Answer]
# APL+WIN, ~~36~~ 33 bytes
```
(↑⍴m)=+/(+⌿m)=+/m←×m×n∘.×n←⍳↑⍴m←⎕
```
Prompts for screen input of an APL 2d matrix.
[Answer]
## Clojure, ~~128~~ ~~95~~ ~~92~~ 85 bytes
```
#(every? neg?(for[R[(range(count %))]i R j R]((if((set[i(- i j)j])0)- dec)((% i)j))))
```
It is always exciting to see two consecutive opening brackets.
Original version:
```
#(and(apply =(map assoc(for[i(rest %)](subvec i 1))(range)(repeat 0)))(every? pos?(concat(map nth %(range))(% 0)(map first %))))
```
The first part works by `assoc`ing diagonal elements of the sub-matrix to zero, and checking that all rows are equal :) I used a similar trick at [Jacobian method](https://codegolf.stackexchange.com/a/148324/59617).
Latter part `concat`enates the diagonal + first row and column and checks that they are positive.
[Answer]
# Javascript (ES6), 58 bytes
My solution for Javascript:
```
m=>m.some((r,i)=>m[0][i]*r[0]*r[i]==0|r.filter(c=>i*c)[2])
```
Not as clever as [Herman's](https://codegolf.stackexchange.com/a/151375/77040) answer, but I just felt like I should post it here too.
```
isArrowHead=m=>m.some((r,i)=>m[0][i]*r[0]*r[i]==0|r.filter(c=>i*c)[2])
console.log("-----should be false-----")
console.log(isArrowHead([[1, 1, 1], [1, 1, 0], [1, 0, 1]]))
console.log(isArrowHead([[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(isArrowHead([[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]))
console.log(isArrowHead([[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]))
console.log("-----should be true-----")
console.log(isArrowHead([[3, 5, 6], [7, 1, 0], [8, 0, 0]]))
console.log(isArrowHead([[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]))
console.log(isArrowHead([[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(isArrowHead([[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]))
console.log("-----end-----")
```
[Answer]
# Clojure, ~~212~~ ~~206~~ 188 bytes
-6 bytes by removing some missed spaces, and shortcutting `range`. I might have to let this sit so I can think of a better way.
-18 bytes thanks to @NikoNyrh, and creating shortcuts for `map`.
```
(fn[m](let[r range a map z zero?](and(every? #(not(z %))(concat(m 0)(rest(a #(% 0)m))(a get m(r))))(every? z(apply concat(into(a #(take(dec %)%2)(r)(a rest m))(a take-last(r)(reverse(rest m)))))))))
```
Awful, just awful. I don't know why I can't wrap my head around a reasonable solution.
Takes a nested vector as input.
```
(defn arrowhead? [matrix]
(let [; Get the 0th cell of the 0th row, then the 1st cell of the 1st row...
main-diagonal (map get matrix (range))
; Get the 0th cell of each row
first-col (rest (map #(% 0) matrix))
arrowhead (concat (matrix 0) first-col main-diagonal)
;
right-rest (map take-last (range) (reverse (rest matrix)))
left-rest (map #(take (dec %) %2) (range) (map rest matrix))
rest-matrix (apply concat (into left-rest right-rest))]
; And check them
(and (every? pos? %) arrowhead
(every? zero? rest-matrix))))
```
---
I tried rewriting this from scratch using a different method, and it ended up longer. Instead of manually carving out the "rest" sections of the matrix, I instead decided to try generating all the coordinates in the matrix, generating the coordinates of the arrowhead, then use `clojure.set/difference` to get the non-arrowhead cells. Unfortunately, the call to that built-in is costly:
# 223 bytes
```
(fn[m](let[l(range(count m))g #(get-in m(reverse %))e every? a(for[y l x l][x y])k #(map % l)r(concat(k #(do[% %]))(k #(do[0%]))(k #(do[% 0])))](and(e #(zero?(g %))(clojure.set/difference(set a)(set r)))(e #(pos?(g %)))r)))
(defn arrowhead? [matrix]
(let [length-range (range (count matrix))
get-cell #(get-in matrix (reverse %))
all-coords (for [y length-range
x length-range]
[x y])
k #(map % length-range)
diag (k #(do[% %]))
top-side (k #(do [0 %]))
left-side (k #(do [% 0]))
arrowhead (concat diag top-side left-side)
; 22 bytes! Ouch
rest-cells (clojure.set/difference (set all-coords) (set arrowhead))]
(and (every? #(zero? (get-cell %)) rest-cells)
(every? #(pos? (get-cell %)) arrowhead))))
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437
```
ä¢⌠┐xⁿtH↔BU
```
[Try it online!](https://staxlang.xyz/#c=%C3%A4%C2%A2%E2%8C%A0%E2%94%90x%E2%81%BFtH%E2%86%94BU&i=%5B%5B1%2C+1%2C+1%5D%2C+%5B1%2C+1%2C+0%5D%2C+%5B1%2C+0%2C+1%5D%5D%0A%5B%5B1%2C+2%2C+3%2C+4%5D%2C+%5B1%2C+1%2C+0%2C+0%5D%2C+%5B1%2C+0%2C+1%2C+0%5D%2C+%5B1%2C+0%2C+0%2C+1%5D%5D%0A%5B%5B1%2C+2%2C+2%2C+2%5D%2C+%5B2%2C+1%2C+0%2C+0%5D%2C+%5B3%2C+0%2C+1%2C+0%5D%2C+%5B4%2C+0%2C+0%2C+1%5D%5D%0A%5B%5B34%2C+11%2C+35%2C+5%5D%2C+%5B56%2C+567%2C+0%2C+0%5D%2C+%5B58%2C+0%2C+679%2C+0%5D%2C+%5B40%2C+0%2C+0%2C+7%5D%5D%0A%5B%5B3%2C+5%2C+6%5D%2C+%5B7%2C+1%2C+0%5D%2C+%5B8%2C+0%2C+0%5D%5D%0A%5B%5B9%2C+9%2C+9%2C+9%5D%2C+%5B9%2C+9%2C+0%2C+0%5D%2C+%5B9%2C+7%2C+9%2C+0%5D%2C+%5B9%2C+0%2C+0%2C+9%5D%5D%0A%5B%5B1%2C+0%2C+3%2C+4%5D%2C+%5B1%2C+1%2C+0%2C+0%5D%2C+%5B1%2C+0%2C+1%2C+0%5D%2C+%5B1%2C+0%2C+0%2C+1%5D%5D%0A%5B%5B1%2C+6%2C+3%2C+4%5D%2C+%5B13%2C+2%2C+0%2C+6%5D%2C+%5B29%2C+0%2C+1%2C+0%5D%2C+%5B2%2C+0%2C+0%2C+4%5D%5D&a=1&m=2)
Unpacked version with 13 bytes:
```
B|AsF:10i^\=*
```
Finally tied Husk and beaten by Jelly by just one byte ...
## Explanation
```
B Push tail (all except 1st row) of the input array, then push the head (1st row)
|A All elements in the head are truthy
This will be used as an accumulator
sF For each element in the tail, execute the rest of the program
:1 All truthy indices
0i^\ Expected truthy indices (0 and the current row number)
= The truthy indices are as expected
* Perform logical "and" with the accumulator
Implicit output of the final accumulator
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12 11~~ 10 bytes
```
≡¹´Ṫ§^*=ŀL
```
[Try it online!](https://tio.run/##jY87DsIwDIZ3TsEIyEOaZzNwA25QhRkJsVCxAxvH6ITEjJC6RuIg9CLBcdLQEXnw4/9@J96d2n2YHxbtcL0cl/4Vhlvne//89A9/367W7/MmhNA0FWA4oMwoM@zdLCocBMhR@6mlmpIYOOWFFIWUE1JIqCoQChQKSoPSJvOqxkIbmyyMPCZ5QIHGocn7anJExQIFzmJOeywYsLmKO2z@Ifv7Fj2SAo9i9DS3heXESue@ "Husk – Try It Online")
## Explanation
```
≡¹´Ṫ§^*=ŀL Input is a k×k array A.
L The length, k.
ŀ The range [0,1..k-1].
´Ṫ Outer product with itself by this function:
Arguments are two numbers x and y.
= Equality of x and y
§^ to the power of
* x times y.
≡¹ Does the result have the same shape and distribution of truthy values as A?
```
The idea is that Husk defines 0 to the power of 0 as 1, so the outer product has 1s on the first row and column.
Also, 1 to the power of any number is 1, so the outer product has 1s on the diagonal.
Other entries are 0 to the power of some positive number, which is 0.
This gives a binary arrowhead matrix, which we compare to the input with `≡`.
[Answer]
# [R](https://www.r-project.org/), ~~81~~ 79 bytes
```
function(x){n=nrow(x);i=c(seq(1,n^2,n+1),1:n,seq(1,n^2,n));all(x[i]>0,x[-i]<1)}
```
-2 bytes thanks to Mr. Xcoder
[Try it online!](https://tio.run/##rZHNCsIwDMfvPkWPLUbo1n04dd58AdHTUNDhoKAVp@JEfPbZdrZUQZwgpG34N/klJGVdpHVxFvmJ7wWuyE2kotxfpDfkaY6PmwP2QCx9EF2PgDcQ4EiEDFfbLa4yvhhTqLIeX4w8cq8LvFudSl7hXEYi16i9CSBVKGWA1lflzKbzCSGd11wfkAwInHT6xrGiAQbfgNZsLnNQwS9ApjqTeSwEpCxSJzaEsK@fKE4aMjUfcRu0JkpgbDpraLTF4GS9N2vqJpqWGP8pthsc/fcmIgtkehtUS37iwHyDDD4g6wc "R – Try It Online")
[Answer]
# C, 117 bytes
```
i,j,r;f(A,n)int*A;{for(i=r=0;i<n;++i)for(j=-1;++j<n;(!i||!j||i==j)&&!A[i*n+j]&&++r)i*j&&i-j&&A[i*n+j]&&++r;return!r;}
```
[Try it online!](https://tio.run/##rZHPboQgEMbvPgVuUgOKCf7XUA8@x3YPjV0bSEobak/qs1tEJe6uMT2UDKjfyPebydT@e12PI8McS9rACgvEROtWtGs@JWSlLAllz4J6HkOTwks/UB9cSdBmfW/zvmdlyZHj2NWZucLjF8fxPImYyx2H@eq40am8tj9S2JIOoyKBj1cmILI6C6g1Ce31uw3OF1CCLsBgG8ScA9W/f0l1oYGnp7cXccKggfouBhFC1LoxDI1hqNIYxBtPcmduxCOKsokfKNGWYsIYRhv/@E@UaI8Sz5Ro6mFqNsFginTa2Wqb5PqRZsWMI2siO@LFe7xk4WmMomRrDzOCHBkme8NIZ0NV2V3MFRYaUazvi3hESffKzswwyP@MPNuj5IaSGkqkx060FBYbQrhy4geOooCFky@cYfwF)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 186 bytes
```
$a=$($args);if($a[0]-contains0){0;exit};0..($a.Length-1)|%{if($a[$_][0]-eq0-or$a[$_][$_]-eq0){0;exit};$r=$a[$_];$d=$_;if($_-ne0){1..($r.Length-1)|%{if($r[$_]-ne0-and$_-ne$d){0;exit}}}};1
```
[Try it online!](https://tio.run/##ZY1hCoMwDIUvk4EFW9LfpbAD7AZDpMxOBalbKzhwO3sXq@sGSwjkS15ebuNsfejsMMQIRkMBxreBqf5K3RkrfhndZHoXkC2o7KOfXgqFoKU4WddOHZfseVg2OdTVemLvyEe/M9U6@F6D19tKQaOhTp9q7ixJ5Grs/4x9MiEFN65JWmiyH4WSMcZjUcgyJysT4ZaJ8MM77Zwp8Q8RM/YG "PowerShell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 136 + 2 (`-ap`) = 138 bytes
```
push@a,[@F]}{push@b,"@{$a[0]}"=~/\b0\b/;map{//;map$a[$'][$_]=!$a[$'][$_],0,$';shift@{$a[$']};push@b,@{$a[$']}}1..$#a;say!("@b"=~y/ 0//c)
```
[Try it online!](https://tio.run/##RUzdCoIwGL33KaYNLJjumyUEQ9hVdz2BjtiiUKgczS5E1qO3lkTdnF/OMaf7pfTePGwrFKnFTrppNpokYsKqBumS6kkbDY2m/KrMRGcKFU5ljQ@yiv@aAMEpt213HuZ1iB3//v0Cx/IcLxS3aoyXidDhf6QIKD2uvGeoQFtURAViCBBE64BBRZuPQ@zVm6Hrb9Zn@zIHBj5Tbw "Perl 5 – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), 79 bytes
```
import StdEnv
?[h:m]=prod h>0&&and[u>0&&n!!x>0&&sum n==n!!x\\[u:n]<-m&x<-[0..]]
```
[Try it online!](https://tio.run/##jZE9b4MwEIZ3foWjSExHZDAfIQrN0g6VumV0PFhAChI2CEyV/PlS2xCaMbrhntO99/ps503J5STaYmxKJHgtp1p0ba/QWRUf8sc50eogWNb1bYGqN@y6XBZ0NCA3m5vJwyiQzDJTXi50PEh29IR7O3oU73aMTWfFe@VsVT@q6p5RSn3QwcBmbDPWtQZNARAIH73/7krPSh0ag1VJVmX4pCQh@D6QCCJdRTFEcbLoo72GOEnnEWxnEsaYs73yZijtrgQiiHU7WZz3dtb4pmBDo8mzYwoJpAsZt3TZFb98q/ihJPp62B4dpKs2sNrQ7Jjpz@rQCc3POv3m14Z/D5P3@TW93yUXdT78AQ "Clean – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 bytes
```
Ëe@!X^!(E*Y*nE
e
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=y2VAIVheIShFKlkqbkUKZQ==&input=WwpbMSAyIDIgMl0KWzIgMSAwIDBdClszIDAgMSAwXQpbNCAwIDAgMV0KXQ==)
Man, this takes me back to the good old days when Japt was regularly much longer than other golfing langs...
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~27~~ 30 bytes
**Solution:**
```
x~a*x|a:a|+(a:1,(#1_x)#0)|=#x:
```
[Try it online!](https://tio.run/##y9bNz/7/v6IuUauiJtEqsUZbI9HKUEdD2TC@QlPZQLPGVrnCSsNQwQgErY0UDBUMFAysjYEkkGVtAuIpGGr@/w8A "K (oK) – Try It Online")
**Explanation:**
I must be doing something dumb as the APL solutions are less than half the byte count...
24 bytes spent creating the arrowhead. `or` together the following three matrices:
```
/ assume 4x4 matrix
=#x
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
+(a:1,(#1_x)#0)
1 0 0 0
1 0 0 0
1 0 0 0
1 0 0 0
a
1 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0
```
Full breakdown:
```
x~a*x|a:a|+(a:1,(#1_x)#0)|=#x: / the solution
x: / save input as x
# / count length
= / identity matrix
| / or with
( ) / do this together
#0 / take from 0
( 1_x) / drop first of x
# / count
1, / prepend 1
a: / save as a
+ / flip rows/cols
| / or with
a / a
a: / save as a
| / or with
x / x
a* / multiply by arrowhead
x~ / matches input?
```
] |
[Question]
[
Pretty simple challenge today:
Write a program or function that takes in a positive integer N and prints or returns a ***sorted*** list of the ***unique*** numbers that appear in the [multiplication table](https://en.wikipedia.org/wiki/Multiplication_table) whose row and column multiplicands both range from 1 to N inclusive.
The list may be sorted in ascending order (smallest to largest) or descending order (largest to smallest), and may be output in any reasonable format.
**The shortest code in bytes wins!**
# Example
When N = 4, the multiplication table looks like:
```
1 2 3 4
-----------
1| 1 2 3 4
|
2| 2 4 6 8
|
3| 3 6 9 12
|
4| 4 8 12 16
```
The unique numbers in the table are `1, 2, 3, 4, 6, 8, 9, 12, 16`. These are already sorted, so
```
1, 2, 3, 4, 6, 8, 9, 12, 16
```
might be your exact output for N = 4. But since the sorting can be reversed and there's some leeway in the formatting, these would also be valid outputs:
```
[16,12,9,8,6,4,3,2,1]
```
```
1
2
3
4
6
8
9
12
16
```
```
16 12 9 8 4 3 2 1
```
# Test Cases
```
N=1 -> [1]
N=2 -> [1, 2, 4]
N=3 -> [1, 2, 3, 4, 6, 9]
N=4 -> [1, 2, 3, 4, 6, 8, 9, 12, 16]
N=5 -> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 20, 25]
N=6 -> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 30, 36]
N=7 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 28, 30, 35, 36, 42, 49]
N=8 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 28, 30, 32, 35, 36, 40, 42, 48, 49, 56, 64]
N=9 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, 28, 30, 32, 35, 36, 40, 42, 45, 48, 49, 54, 56, 63, 64, 72, 81]
N=10 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, 28, 30, 32, 35, 36, 40, 42, 45, 48, 49, 50, 54, 56, 60, 63, 64, 70, 72, 80, 81, 90, 100]
N=11 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 27, 28, 30, 32, 33, 35, 36, 40, 42, 44, 45, 48, 49, 50, 54, 55, 56, 60, 63, 64, 66, 70, 72, 77, 80, 81, 88, 90, 99, 100, 110, 121]
N=12 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 27, 28, 30, 32, 33, 35, 36, 40, 42, 44, 45, 48, 49, 50, 54, 55, 56, 60, 63, 64, 66, 70, 72, 77, 80, 81, 84, 88, 90, 96, 99, 100, 108, 110, 120, 121, 132, 144]
```
[Answer]
# Pyth, 8 bytes
```
S{*M^SQ2
```
[Try it online.](https://pyth.herokuapp.com/?code=S%7B%2aM%5ESQ2&input=12&debug=0)
Explanation: `SQ` takes the evaluated list input (`Q`) and makes a list `[1, 2, ..., Q]`. `^SQ2` takes the Cartesian product of that list with itself - all possible product combinations. `*M` multiplies all these pairs together to form all possible results in the multiplication table and `S{` makes it unique and sorts it.
[Answer]
# Python 2, ~~61~~ 51 bytes
```
lambda n:sorted({~(i%n)*~(i/n)for i in range(n*n)})
```
Thanks to xnor for shortening some syntax.
[Answer]
# APL, ~~18~~ 16 bytes
```
{y[⍋y←∪,∘.×⍨⍳⍵]}
```
This is an unnamed monadic function. The output is in ascending order.
Explanation:
```
⍳⍵]} ⍝ Get the integers from 1 to the input
∘.×⍨ ⍝ Compute the outer product of this with itself
, ⍝ Flatten into an array
∪ ⍝ Select unique elements
y← ⍝ Assign to y
{y[⍋ ⍝ Sort ascending
```
Fixed an issue and saved 2 bytes thanks to Thomas Kwa!
[Answer]
# Octave, 22 bytes
```
@(n)unique((a=1:n)'*a)
```
[Answer]
# Julia, 24 bytes
```
n->sort(∪((x=1:n)*x'))
```
This is an anonymous function that accepts an integer and returns an integer array.
Ungolfed:
```
function f(n::Integer)
# Construct a UnitRange from 1 to the input
x = 1:n
# Compute the outer product of x with itself
o = x * transpose(x)
# Get the unique elements, implicitly flattening
# columnwise into an array
u = unique(o)
# Return the sorted output
return sort(u)
end
```
[Answer]
# CJam, ~~14~~ 12 bytes
Latest version with improvements proposed by @aditsu:
```
{)2m*::*0^$}
```
This is an anonymous function. [Try it online](http://cjam.aditsu.net/#code=ri%0A%7B)2m*%3A%3A*0%5E%24%7D%0A~%60&input=5), with input/output code needed for testing it.
@Martin proposed another very elegant solution (`{,:)_ff*:|$}`) with the same length. I used the one by aditsu because it was much more similar to my original solution.
The main difference to my original solution is that this keeps the `0` value in the original sequence, which saves 2 bytes at the start. You'd think that this would not help, because you have to remove the `0` value from the result. But the core of @aditsu's idea is the `0^` at the end, which is a set difference with `0`. This removes the `0`, and at the same time, since it's a set operation, eliminates duplicate elements from the solution set. Since I already needed 2 bytes to eliminate the duplicates before, removing the `0` is then essentially free.
Explanation:
```
{ Start anonymous function.
) Increment to get N+1.
2m* Cartesian power, to get all pairs of numbers in range [0, N].
::* Reduce all pairs with multiplication.
0^ Remove 0, and remove duplicates at the same time since this is a set operation.
$ Sort the list.
} End anonymous function.
```
[Answer]
# R, 39 bytes
```
cat(unique(sort(outer(n<-1:scan(),n))))
```
This reads an integer from STDIN and writes a space delimited list to STDOUT.
We create the multiplication table as a matrix using `outer`, implicitly flatten into a vector and sort using `sort`, select unique elements using `unique`, and print space delimited using `cat`.
[Answer]
# MATLAB, 24 bytes
```
@(n)unique((1:n)'*(1:n))
```
[Answer]
## zsh, ~~86~~ 56 bytes
*thanks to @Dennis for saving 30(!) bytes*
```
(for a in {1..$1};for b in {1..$1};echo $[a*b])|sort -nu
```
Explanation / ungolfed:
```
( # begin subshell
for a in {1..$1} # loop through every pair of multiplicands
for b in {1..$1}
echo $[a*b] # calculate a * b, output to stdout
) | sort -nu # pipe output of subshell to `sort -nu', sorting
# numerically (-n) and removing duplicates (-u for uniq)
```
This doesn't work in Bash because Bash doesn't expand `{1..$1}`—it just interprets it literally (so, `a=5; echo {1..$a}` outputs `{1..5}` instead of `1 2 3 4 5`).
[Answer]
# Ruby, ~~50~~ 48 bytes
```
->n{c=*r=1..n;r.map{|i|c|=r.map{|j|i*j}};c.sort}
```
**Ungolfed:**
```
->n {
c=*r=1..n
r.map { |i| c|=r.map{|j|i*j} }
c.sort
}
```
Using nested loop to multiply each number with every other number upto n and then sorting the array.
**50 bytes**
```
->n{r=1..n;r.flat_map{|i|r.map{|j|i*j}}.uniq.sort}
```
**Usage:**
```
->n{c=*r=1..n;r.map{|i|c|=r.map{|j|i*j}};c.sort}[4]
=> [1, 2, 3, 4, 6, 8, 9, 12, 16]
```
[Answer]
# Shell + common utilities, 41
```
seq -f"seq -f%g*%%g $1" $1|sh|bc|sort -nu
```
---
Or alternatively:
# Bash + coreutils, 48
```
eval printf '%s\\n' \$[{1..$1}*{1..$1}]|sort -nu
```
Constructs a brace expansion inside an arithmetic expansion:
`\$[{1..n}*{1..n}]` expands to the arithmetic expansions `$[1*1] $[1*2] ... $[1*n] ... $[n*n]` which are evaluated and passed to `printf`, which prints one per line, which is piped to `sort`.
Careful use of quotes, escapes and `eval` ensure the expansions happen in the required order.
---
Or alternatively:
# Pure Bash, 60
```
eval a=($(eval echo [\$[{1..$1}*{1..$1}\]]=1))
echo ${!a[@]}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
OumΠπ2
```
[Try it online!](https://tio.run/##yygtzv7/378099yC8w1G////NzQAAA "Husk – Try It Online")
### Explanation
```
OumΠπ2
π2 cartesian square
mΠ map product
u unique
O sort
```
[Answer]
## Haskell, ~~55~~ 54 bytes
```
import Data.List
f n=sort$nub[x*y|x<-[1..n],y<-[1..x]]
```
Usage example: `f 4` -> `[1,2,3,4,6,8,9,12,16]`.
`nub` removes duplicate elements from a list.
Edit: @Zgarb found a superfluous `$`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 69 bytes
```
n=>[...a=Array(i=n*n)].map(x=>a[q=~(--i%n)*~(i/n)]=q)&&a.filter(x=>x)
```
[Try it online!](https://tio.run/##FcpBCoNADADA11QSYaN9QIRe/IT0EHRbUtasrlL04tdXPc/85C9Ln3RancXB55azcdMRkfArJdlB2UrDN40ywcaNdDMf4Jw@DMsDtLqMZywKoY@G1ac7bZj7aEsMnkL8QgvPGjGf "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
```
n=>[...Array(n*n)].flatMap((_,i,x)=>x.every((_,j)=>~(j/n)*~(j%n)+~i)?[]:i+1)
```
[Try it online!](https://tio.run/##FchBCoMwEEDR0xRm1E51K0Tpxl1PICKDjZIQJiGK6Marp3b1ed/yzusUTdie4r86dSqJanoiesfIJ0gmONDsePtwABgLUxyomoP0ruP5H/bmBfYlmN15COaXwbYfapNXmCYvq3eanF@gg6pETD8 "JavaScript (Node.js) – Try It Online")
No recursion like other answers
[Answer]
# Mathematica, 25 bytes
```
Union@@Array[1##&,{#,#}]&
```
[Answer]
# K, 17 bytes
```
t@<t:?,/t*\:t:1+!
```
Not much to say here. Sort (`t@<t:`) the unique items (`?`) of the flattened (`,/`) multiplied cartesian self-product (`t*\:t:`) of 1 up to and including N (`1+!`).
In action:
```
t@<t:?,/t*\:t:1+!5
1 2 3 4 5 6 8 9 10 12 15 16 20 25
```
[Answer]
## J, ~~21~~ 20 bytes
*Thanks to @Zgarb for -1 byte!*
```
/:~@~.@,@(1*/~@:+i.)
```
My first J answer! Golfing tips are appreciated, if there is something to golf.
This is a monadic function; we take the outer product by multiplication of the list `1..input` with itself, flatten, take unique elements, and sort.
[Answer]
## Kotlin, 70 bytes
```
val a={i:Int->(1..i).flatMap{(1..i).map{j->it*j}}.distinct().sorted()}
```
Ungolfed version:
```
val a: (Int) -> List<Int> = {
i -> (1..i).flatMap{ j -> (1..i).map{ k -> j * k } }.distinct().sorted()
}
```
Test it with:
```
fun main(args: Array<String>) {
for(i in 1..12) {
println(a(i))
}
}
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 7 bytes
```
řĐɐ*ƑỤş
```
[Try it online!](https://tio.run/##ARcA6P9weXT//8WZxJDJkCrGkeG7pMWf//8xMA "Pyt – Try It Online")
```
ř implicit input (n); push [1,2,...,n]
Đ duplicate
ɐ* generate multiplication table
Ƒ flatten array
Ụ get unique elements
ş sort in ascending order; implicit print
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 12 \log\_{256}(96) \approx \$ 9.88 bytes
```
R1+DZ!.PZU
```
#### Explanation
```
R1+DZ!.PZUz: # Implicit input Example (n=5)
R1+ # [1..input] [1, 2, 3, 4, 5]
DZ! # Cartesian product with itself [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5]]
.P # Product of each inner list [1, 2, 3, 4, 5, 2, 4, 6, 8, 10, 3, 6, 9, 12, 15, 4, 8, 12, 16, 20, 5, 10, 15, 20, 25]
ZU # Uniquified [1, 2, 3, 4, 5, 6, 8, 10, 9, 12, 15, 16, 20, 25]
z: # And sorted [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 20, 25]
# Implicit output
```
#### Screenshot
[![Screenshot](https://i.stack.imgur.com/JWRhI.png)](https://i.stack.imgur.com/JWRhI.png)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ɾẊƛΠ;Us
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvuG6isabzqA7VXMiLCIiLCI2Il0=)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Ṭẋ)ST
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//4bms4bqLKVNU/8OHxZLhuZgpWf//MTI "Jelly – Try It Online")
```
) For each x in 1 .. n:
Ṭ Create a list containing 1 at index x and 0s before it,
ẋ and repeat it x times.
S Sum the results element-wise,
T and yield the indices of non-zeros in the result.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
⟦₁⟨∋×∋⟩ᵘo
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@aGh/NX/Goo/vwdCDxaP7Kh1tn5P//b/Y/AgA "Brachylog – Try It Online")
### Explanation
```
⟦₁⟨∋×∋⟩ᵘo
⟦₁ Range from 1 to input number, inclusive
ᵘ Get all unique outputs of this predicate:
∋ Pick a number from that range
∋ Pick another number from that range
⟨ × ⟩ Multiply them together
o Sort the resulting list
```
[Answer]
# Pyth, 10
```
S{m*Fd^SQ2
```
[Try it Online](https://pyth.herokuapp.com/?code=S%7Bm%2AFd%5ESQ2&input=12&debug=0) or run a [Test Suite](https://pyth.herokuapp.com/?code=S%7Bm%2AFd%5ESQ2&input=12&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12&debug=0)
[Answer]
## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), ~~25~~ ~~22~~ 18 bytes
I remembered that I very conveniently implemented Cartesian products [before this question was posted](https://github.com/elendiastarman/Minkolang/commit/66aa714de8a284a1394d0152fb725ceca6d8e35c)!
```
1nLI20P[x*1R]sS$N.
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=1nLI20P%5Bx*1R%5DsS%24N%2E&input=12) (Outputs in reverse order.)
### Explanation
```
1 Push a 1 onto the stack
n Take number from input (n)
L Pushes 1,2,...,n onto the stack
I Pushes length of stack so 0P knows how many items to pop
2 Pushes 2 (the number of repeats)
0P Essentially does itertools.product(range(1,n+1), 2)
[ Open for loop that repeats n^2 times (0P puts this on the stack)
x Dump (I know each product has exactly two numbers
* Multiply
1R Rotate 1 step to the right
] Close for loop
s Sort
S Remove duplicates ("set")
$N. Output whole stack as numbers and stop.
```
[Answer]
# C, 96 bytes
```
i,a[1<<16];main(n){for(scanf("%d",&n);i<n*n;a[~(i%n)*~(i++/n)]="%d ");while(i)printf(a[i--],i);}
```
This prints the numbers in descending order. Suggestions are welcomed as this looks far from optimal.
[Answer]
# JavaScript (ES6), ~~92~~ 90 bytes
```
n=>eval(`for(r=[],a=n;a;a--)for(b=n;b;)~r.indexOf(x=a*b--)||r.push(x);r.sort((a,b)=>a-b)`)
```
## Explanation
```
n=>eval(` // use eval to remove need for return keyword
for(r=[],a=n;a;a--) // iterate for each number a
for(b=n;b;) // iterate for each number b
~r.indexOf(x=a*b--) // check if it is already in the list, x = value
||r.push(x); // add the result
r.sort((a,b)=>a-b) // sort the results by ascending value
// implicit: return r
`)
```
## Test
```
N = <input type="number" oninput="result.innerHTML=(
n=>eval(`for(r=[],a=n;a;a--)for(b=n;b;)~r.indexOf(x=a*b--)||r.push(x);r.sort((a,b)=>a-b)`)
)(+this.value)" /><pre id="result"></pre>
```
[Answer]
## [Perl 6](http://perl6.org), 27 bytes
```
{squish sort 1..$_ X*1..$_} # 27
{unique sort 1..$_ X*1..$_} # 27
{sort unique 1..$_ X*1..$_} # 27
```
Example usage:
```
say {squish sort 1..$_ X*1..$_}(3); # (1 2 3 4 6 9)
my $code = {squish sort 1..$_ X*1..$_}
for 1..100 -> \N { say $code(N) }
my &code = $code;
say code 4; # (1 2 3 4 6 8 9 12 16)
```
[Answer]
## Haskell, 51 bytes
```
f n=[i|i<-[1..n*n],elem i[a*b|a<-[1..n],b<-[1..n]]]
```
Pretty boring. Just filters the list `[1..n*n]` to the elements of the form `a*b` with `a` and `b` in `[1..n]`. Using `filter` gives the same length
```
f n=filter(`elem`[a*b|a<-[1..n],b<-[1..n]])[1..n*n]
```
I tried for a while to generate the list of products with something more clever like `concatMap` or `mapM`, but only got longer results. A more sophisticated check of membership came in at 52 bytes, 1 byte longer, but can perhaps be shortened.
```
f n=[k|k<-[1..n*n],any(\a->k`mod`a<1&&k<=n*a)[1..n]]
```
[Answer]
# JAVA - 86 Bytes
```
Set a(int a){Set s=new TreeSet();for(;a>0;a--)for(int b=a;b>0;)s.add(a*b--);return s;}
```
---
# Ungolfed
```
Set a(int a){
Set s = new TreeSet();
for (;a>0;a--){
for(int b = a;b>0;){
s.add(a*b--);
}
}
return s;
}
```
] |
[Question]
[
# CodeGolf Challenge
PWSSHHHH! You wake up in a cryogenics lab in the year 3000. Upon being escorted to the assignment office to receive your career chip, presumably that of a delivery boy, a probe detects that you are from the year 2000. Because of this, and a few stereotypes, you are assumed stupid compared to *today's* modern human and are forced to repeat gradeschool.
You enter your first grade classroom and the teacher is giving an assignment. She will say or write a number up to 50. If she writes the number on the board (for example: 25) then you have to say the numbers up to that number "one, two, three, ..., twenty-five". If she says the number out loud (for example: "six") then, on your tablet, you have to write the numbers up to that number "1, 2, 3, 4, 5, 6"
This becomes very tedious and you decide you will automate the process with your still functioning, yet archaic, 21st century programming knowledge.
---
# Objective:
Your program should take an input. This input will either be a decimal number (`1 thru 50`) or a written-out number (`one thru fifty`).
•If the input is a decimal number, your output should count from one to said number, using written-out style. (e.g. *thirty-two*)
•If the input is a written-out number, your output should count from 1 to said number, using decimal style. (e.g. *32*)
---
# Rules:
Input and Output can be in any case of your choosing (so you can make a program that only accepts upper-case if desired).
Input decimal numbers do not have to be of a number type (e.g. int), they can be a input string containing numbers (25 vs "25"). Either are fine and you can chose which one you want your program to accept. (Your program does not need to accept both)
Written out style does NOT require a hyphen between compound words, but you can if desired.
Output values have to be separated in some form, any separator is fine `1,2,3` `1 2 3` `etc`
You can not add extra libraries like [num2words (python)](https://pypi.python.org/pypi/num2words) etc (However system libraries are fine)
Even though the back-story says you are from the year 2000, you can use languages created after that date (lol)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the shortest bytecount wins!
[Answer]
# [Perl 6](http://perl6.org/), ~~119~~ 113 bytes
```
{my \n=<① ⑳ ㉑ ㉟ ㊱ ㊿>.map:{|map *.uniname.words[2..*].join,$^a..$^b}
/\d/??n[^$_]!!1..1+first $_,n,:k}
```
Unicode database FTW!
Uses upper-case written-out numbers without hypen, e.g. `TWENTYTWO`.
Returns a list of strings, or a range of numbers. (Both use space as separator when printed with `put`.)
[Answer]
# Python3, ~~276~~ ~~271~~ ~~269~~ ~~243~~ ~~237~~ ~~235~~ ~~232~~ 217 bytes
Taking a cue from the @smls perl submission...
```
from unicodedata import*
o=[name(chr(k)).split(' ',2)[-1]for j in['①⑴','㉑㉠','㊱㋀']for k in range(ord(j[0]),ord(j[1]))]
i=input()
w=i in o
for i in range(w and o.index(i)+1or int(i)):print(w and i+1or o[i])
```
I suspect it might be golfed a little bit further.
It makes use of the system library `unicodedata` to look up names for numbers. It requires upper case number names (separated by space: `FORTY TWO`) or decimal integers as input.
(This is my first code golf submission.)
(I also just noticed I was miscounting the length (encoding), so it's a few bytes less than previously thought. I've only updated the most recent byte count, though. Oops.)
[Answer]
## Common Lisp, ~~297~~ ~~253~~ ~~243~~ ~~242~~ ~~144~~ 128
```
(lambda(s)(#1=dotimes(u(or(#1#(i 51)(if(equal(#2=format()"~R"i)s)(return i)))s))(#2#t"~[~:;, ~]~:[~R~;~D~]"u(stringp s)(1+ u))))
```
### Details
```
(lambda (s)
(dotimes ; iterate...
(u ; for u from zero below ...
(or ; if s is a string, then
(dotimes (i 51) ; parse s by iterating from 0 to 50
(if (equal ; until we find a match between
(format nil "~R" i) ; the English word(s) for i
s) ; and the given s
(return i))) ; (exit loop)
s)) ; otherwise, use s, which is a number
(format t ; for each U, print to standard output
"~[~:;, ~]~:[~R~;~D~]" ; (see below for details)
u ; ...
(stringp s) ; ... arguments to format
(1+ u)))) ; ...
```
* `~[ 0 ~; 1 ~; ... ~:; else ~]` is a switch, based on the next available argument's value, which jumps to the appropriate sub-control format. Here, I only have a case of "0" and for "else". This is used to insert a separator before each number except the first one, thanks to U starting from zero.
* `~:[ FALSE ~; TRUE ~]` is a conditional format; here we output things differently whether the input s is a string or not.
* `~R` write a number as a cardinal English number, whereas `~D` simply prints the number.
### Examples
```
CL-USER> (test "five")
1, 2, 3, 4, 5
CL-USER> (test 32)
one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two
```
[Answer]
# JavaScript ES6, 559 526 381 368 364 358 332 327 315 bytes
```
a="one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve0thir10four10fif10six10seven10eigh10nine1".replace(/1/g,'teen').split(0),b="twenty0thirty0forty0fifty".split(0),c=(n,d=Array,e=b.forEach(i=>a=a.concat(i,a.slice(0,9).map(x=>i+x))))=>1/n?a.slice(0,n).join():d.from(d(a.indexOf(n)+1),(x,i)=>i+1).join();
```
Thanks to Kritixi Lithos for the idea of splitting the array and Arnauld for the 1/n trick.
```
a="one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve0thir10four10fif10six10seven10eigh10nine1".replace(/1/g,'teen').split(0),b="twenty0thirty0forty0fifty".split(0),c=(n,d=Array,e=b.forEach(i=>a=a.concat(i,a.slice(0,9).map(x=>i+x))))=>1/n?a.slice(0,n).join():d.from(d(a.indexOf(n)+1),(x,i)=>i+1).join();
console.log(c("twentyfive"));
console.log(c("fifty"));
console.log(c(50));
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~503~~ ~~499~~ ~~494~~ ~~490~~ 479 bytes
-5 with thanks to @JonathanAllan
```
l='one two three four five six seven eight nine ten eleven twelve thir#four#fif#six#seven#eigh#nine#'.replace('#','teen ').split()
m='twenty','thirty','forty','fifty'
i,z,R=raw_input(),' ',range
try:n=int(i);p=(n/10)-2;o=(l+sum([[m[x]]+[m[x]+z+l[y]for y in R(9)]for x in R(p)],[])+[m[p]]+[m[p]+z+l[y]for y in R(n%10)],l[:n])[n<20]
except:j=i.split();o=map(str,R(1,(m.index(j[0])+2)*10+l.index(j[1])+2if z in i else l.index(i)+2if i in l else(m.index(i)+2)*10+1))
print','.join(o)
```
[Try it online!](https://tio.run/nexus/python2#bZDBbsMgDIbveQokNAELy5LuMK1dXqJXhKZoM60rQhChbdKX7yBde9rJ2L@/38ZX27LBAYnngcR9ACBmOAZi8ARkxImMcAJHAHf7SBzmxpzapRrPYFNb3GOgmaIGDU0QXSCaIZoZyqoA3nbfwBllkkVIMBPV6C1GLoq@ZcnKxTlryWx5mOEvokmxQHmR2zZ05y90/pgoyQiToXM7KGKY165FFzmKjW@5e21q8bLaDC235XjsuVK9mrQul1BeSqtmnfzJTNCRLf8QSzbdMi@0VFrkZn9j/D@Me0oztLRq7bRQ7nNV6wKmb/BxfWjx/rW0Qt95PsYgt7yRvK/Q/cDED6pOE1biualL@6g1uYaGXPIITFcegdxVvEmYJbtIDzO8OzVCFD6kO6SzVYcBHR/E9fr2/gs "Python 2 – TIO Nexus")
Input either a number or a space seperated spelling of a number.
Slightly less golfed and more readable version:
```
l='one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split()
m='twenty','thirty','forty','fifty'
i=raw_input()
try:
n=int(i)
if n<20:
o=l[0:n]
else:
o=l
for x in range((n/10)-2):
o+=[m[x]]+[m[x]+' '+l[y]for y in' '*9]
p=m[(n/10)-2]
o+=[p]+[p+' '+l[y]for y in' '*n%10]
except:
if' 'in i:
t=i.split()
s=((m.index(t[0])+2)*10)+l.index(t[1])+2
else:
s=l.index(i)+2 if i in l else((m.index(i)+2)*10)+1
r=range(1,s)
o=map(str,r)
print','.join(o)
```
[Answer]
# Scheme, ~~161~~, ~~152~~, 149
```
(define (c x)(let((r(string->number x)))(let l((i 1))(let((n (format #f "~r" i)))(display(if r n i))(newline)(or(eq? r i)(equal? x n)(l (+ i 1)))))))
```
Uncompressed:
```
(define (count limit)
(let ((numerical-limit (string->number limit)))
(let l ((i 1))
(let ((current-number (format #f "~r" i)))
(display (if numerical-limit current-number i))
(newline)
(or (eq? numerical-limit i)
(equal? limit current-number)
(l (+ i 1)))))))
```
[Answer]
# PHP - ~~397~~ ~~372~~ ~~349~~ ~~344~~ 329 bytes
Inspired by [TomDevs's JS solution](https://codegolf.stackexchange.com/questions/108757/automate-your-first-grade-counting-exercise/108769#108769)
*Saved 25 bytes by replacing `$a=[...]` by `$a=explode(...)`*
*Saved another 23 bytes by switching back to an array without string delimiters and by storing `teen` in a variable, thanks to @user59178*
*Saved another 5 bytes by removing the `(int)` typecasting*
*Saved another 15 bytes by dropping `$b`, the `$i` in the `for` declarations, and the curly braces, thanks to @user59178 again*
```
$a=[one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir.$t=teen,four.$t,fif.$t,six.$t,seven.$t,eigh.$t,nine.$t];foreach([twenty,thirty,forty,fifty] as$c){$a[]=$c;for($i=0;$i<9;)$a[]=$c.'-'.$a[$i++];}if($argv[1]!=0)for($i=0;$i<$argv[1];)echo$a[$i++].' ';else for($i=1;$i<=array_search($argv[1],$a)+1;)echo$i++.' ';
```
**Ungolfed :**
```
$a =[one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir.$t=teen,four.$t,fif.$t,six.$t,seven.$t,eigh.$t,nine.$t];
foreach ([twenty,thirty,forty,fifty] as $c){
$a[] = $c;
for ($i=0;$i<9;)
$a[] = $c . '-' . $a[$i++];
}
if( $argv[1] !=0 )
for ($i=0;$i<$argv[1];)
echo $a[$i++] . ' ';
else
for ($i=1;$i<=array_search($argv[1], $a)+1;)
echo $i++ . ' ';
```
Try it [for an input string](https://eval.in/728201) or [for an input number](https://eval.in/728202)
[Answer]
# Python 2, 262 bytes
```
x="one two three four five six seven eight nine ten eleven twelve thir#four#fif#six#seven#eigh#nine#".replace("#","teen ").split()
x+=[a+"ty"+b for a in"twen","thir","for","fif"for b in['']+x[:9]]
v=input()
for s in range(1,x.index(v)+2)if v>50else x[:v]:print s
```
**[repl.it](https://repl.it/F1md/5)**
Input and output strings are lower case and concatenated\*, so to test a string input enter, for example, `"thirtyfive"` at the prompt.
Builds the list of all the words (plus `"fiftyone"` to `"fiftynine"`), `x`, then tests if `input` is a word with the proxy `v>50` (strings are greater than numbers in Python 2, and all the numbers in the valid input range from the specification are `<=50`) and `print`s the appropriate values by either slicing the list, `x[:v]`, or building a range of integers, `range(1,x.index(v)+2)`.
\* Adding hyphenation on both costs 11 bytes, by replacing `a+"ty"b` with `a+"ty"+'-'*(b>'')+b`.
[Answer]
# Wolfram Language, 92 bytes
```
If[NumberQ@#, Do[Print@IntegerName@i, {i, #}],
Do[Print@i, {i, Interpreter["SemanticNumber"]@#}]] &
```
(I'm new to this, let me know if I did something wrong)
[Answer]
# JavaScript (ES6), 261 bytes
Note: the string assigned to z is encoded with `atob`. In the encoded string there are 11 bytes that I can not post to this site, even if they are valid characters in a javascript string. So I used an hex escape in the form \xHH. Each one of these escapes is counted as 1 byte.
The original uncompressed string is the *less golfed* version.
```
x=>(z=btoa('ö\x89ÞöÜ(öØkyï_¢êý~+Þöȱöǯz\x7f^\x8a\x08möx§{Û^\x9f×¥z÷§öÜ\x1e\x96÷½¶\x18«÷×â\x7fß}z(!÷Ûpz\x7f}~\x8aý').split(9),o=(0+z.map((v,i)=>i<20?i<13?v:(v||z[i-10])+'teen':z.slice(0,10).map(d=>(z[i]||z[i-8]||z[i-18])+'ty'+d))).split`,`,p=o.indexOf(x),o.slice(1,-~x+p+!~p).map((x,i)=>~p?i+1:x))
```
*Less golfed*
```
x => (
z = '9one9two9three9four9five9six9seven9eight9nine9ten9eleven9twelve9thir99fif999eigh99twen99for9'
.split(9),
o = (0 + // 0 + array to build a comma separated string
z.map( (v, i) =>
i < 20
? i < 13
? v // 1 to 13 are 'as is'
: (v||z[i-10])+'teen' // compose for 14 to 19
: z.slice(0,10).map(d=>(v||z[i-8]||z[i-18])+'ty'+d)) // 20s, 30s, 40s, 50s
).split`,`, // from comma separated to array again
// o contains strings from one to fiftynine
p = o.indexOf(x), // look for input
o.slice(1, -~x+p+!~p).map((x,i) => ~p?i+1:x)
)
```
**Test**
```
F=
x=>(z=btoa('ö\x89ÞöÜ(öØkyï_¢êý~+Þöȱöǯz\x7f^\x8a\x08möx§{Û^\x9f×¥z÷§öÜ\x1e\x96÷½¶\x18«÷×â\x7fß}z(!÷Ûpz\x7f}~\x8aý').split(9),o=(0+z.map((v,i)=>i<20?i<13?v:(v||z[i-10])+'teen':z.slice(0,10).map(d=>(v||z[i-8]||z[i-18])+'ty'+d))).split`,`,p=o.indexOf(x),o.slice(1,-~x+p+!~p).map((x,i)=>~p?i+1:x))
function update() {
var i=I.value
O.textContent = F(i)
}
update()
```
```
<input id=I value=25 oninput='update()'><pre id=O></pre>
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~305~~ 303 bytes
Converted to Python 3 after advice from @nedla2004. Now also has no space between written numbers on input or output e.g. enter twentytwo
```
l='one two three four five six seven eight nine ten eleven twelve thir#four#fif#six#seven#eigh#nine#'.replace('#','teen ').split()
m='twenty','thirty','forty','fifty'
i,R=input(),range
l+=sum([[m[x]]+[m[x]+l[y]for y in R(9)]for x in R(3)],[])
for x in R(1,l.index(i)+2)if i in l else l[:int(i)]:print(x)
```
[Try it online 3!](https://tio.run/nexus/python3#TY/BbsMgDIbveQpLHAAFRdp2WqW8RK@IQ7WZxhIhEZA2efrM0B52@m3//2fZZxjlEhHKc4EyJUTwy5bA0wMh0w4ZHxgB6T4ViFSDtQ1tWp4YOFYmSqJSwpMXDIkGiQqJygg5JFzD7QeVFNLIggxLPeQ1UFG6m0fJq2I5qsfLWuGXt5Jn7chcR4rrxnmTbvGOXejHvM3K2tnuzvVN@mAPxyQcQBGu6lu3bn91X9oZ63T3b/RhwkDxF3dFuv/U5IGqEfjFjBDshWJhy13WVKtdn2c7rL77Bw "Python 3 – TIO Nexus")
# [Python 2](https://docs.python.org/2/), ~~327~~ ~~320~~ ~~313~~ 308 bytes
```
l='one two three four five six seven eight nine ten eleven twelve thir#four#fif#six#seven#eigh#nine#'.replace('#','teen ').split()
m='twenty','thirty','forty'
i,R=raw_input(),range
l+=sum([[m[x]]+[m[x]+l[y]for y in R(9)]for x in R(3)],[])+['fifty']
for x in R(1,l.index(i)+2)if i in l else l[:int(i)]:print x
```
[Try it online 2!](https://tio.run/nexus/python2#TY9NasQwDIX3OYXAC9skBKZddSCXmK0xJUzlicBxguNMnNOnsrvpSj/vfQ/p8oNcAkI6FkhTRAS37BEcvRE2yrDhGwMgvaYEgYqxjL5u04GebWmiKAolHDnBkKiQKJAojJB9xNWPT1RSyE4mZFjqfls9JaWbeZAcFdJZNA6rjVtKbah7DHE8vimsO3u7OIYXNr4dtn1WxswmW9vW0npzWqbgBArwUF@6Tvlv@tS2M1a3RvKRHGybf@Kt8z2FH8yKdPuhyQEVwfOjG4I3dwqJJXtfI3eQr6teV37@BQ "Python 2 – TIO Nexus")
~~163~~ ~~170~~ 177 bytes shorter than my original answer so I am posting it as an alternative. This uses `for` on the two lists to build up a complete list of all of the string representations of the numbers then identifies the right one in the list and prints everything up to it either by value or by index. Outputs a new line for each value.
[Answer]
## Python 2, ~~432 422 416~~ 403 bytes
I'm sure this can be improved on. At the very least if I can get away with hardcoding the value to be worked on and not needing a function I can save 20. It needs a space to separate words in text input. Saved 6 bytes thanks to JonathanAllan's comment on ElPedro's answer, 4 for rearranging maths.
```
def z(f):
a,b,i,d="one two three four five six seven eight nine ten eleven twelve thir#four#fif#six#seven#eigh#nine#".replace("#","teen ").split()+[""],"twenty thirty forty fifty".split(),1,f>50
if d:f=f.split();f=a.index(f[-1])+21+b.index(f[-2])*10 if len(f)>1 else b.index(f[-1])*10+20 if f[-1]in b else a.index(f[-1])+1
while i<=f:s=i if d else a[i-1]if i<20 else b[i//10-2]+a[i%10-1];print s;i+=1
```
(NB: The actual version of this uses tabs to indent instead of spaces. QPaysTaxes added a single space because that wasn't rendering properly, to ensure that the given code compiles. It shouldn't change the byte count.)
[Answer]
# C++11, ~~484~~ ~~480~~ 477 bytes
```
#import<iostream>
#import<cstdlib>
#import<vector>
using namespace std;f(){int j,i=2;string s="teen";vector<string>v={"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"};for(;i++<9;)v.push_back(v[i]+s);v[13]="thir"+s;v[15]="fif"+s;v[18]="eigh"+s;for(i=19;i++<50;){string n[4]={"twenty","thirty","forty","fifty"};v.push_back(n[i/10-2]+v[i%10]);}cin>>s;if(i=atoi(s.c_str()))for(j=0;j++<i;)cout<<v[j]<<" ";else while(v[i++]!=s)cout<<i<<" ";}
```
Text input in lower-case without hyphens.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 362 bytes
```
$z=0..50|%{("0twenty0thirty0forty0fifty"-split0)[+(($b="$_"[0])-gt49)*($_-gt19)*(+"$b"-1)]+($x=(("0one0two0three0four0five0six0seven0eight0nine0ten0eleven0twelve"-split0)+(-split'thir four fif six seven eigh nine'|%{$_+'teen'})))[($_%10)*($_-gt19)]+$x[$_*($_-le19)]}
if(($n=-split$args)[0][0]-in48..57){$z[$n[0]..$n[2]]}else{$z.IndexOf($n[0])..$z.IndexOf($n[2])}
```
Try it online! [words input](https://tio.run/nexus/powershell#VZBRasMwDIbfdwpjVGLPJCilZdtDDrCnHSCYsDIlNQRnJG6WtsvZMzmBsYGx5F/m0y8tcCswy474vbsrieGLfLhiOLueQ92tt6vDVabDZ@sC6tIoBadCQiVLtDptwuFFPyqoOMtjZiScZJpraxRMhWJo54nBHVN7IoZeemaOhIObcKCRPJJrzgG9ix/js11VNtOO9NvZqC1LojsRMYKtCaaIlSIiRURIwsNAZZJA5JNZa12yv12Of3xaA1MJ1Sq0FIX5wdU8mi@2LvDeN4PmEfmkzh@eeUlP@g63EjxLWcZhb@1M7UCsZq/@g6a3Wq1VzeV/0t7qeVkWGd1FV4J3cRHbmuMk8gc "PowerShell – TIO Nexus") or [numbers input](https://tio.run/nexus/powershell#VZBRasMwDIbfdwpjVGLNJDhtxtaHHGBPO0AwYWVKagjOSNwubZezZ3IKYwNjyb/Mp19a4FqaLHsy35ubkiZ8kQ8XE45u4ND06@2acJHp@Nm5YLDSSsGhlFDLylhM21Ds8VFBzVkeMy3hINMcrVYwlYqhvScG90wdiBh6Gph5JjO6yYx0Jm/ItcdgvIsf47NbVTbTnem3s1b3LInuRMQItiaYIlaKiBQRIQkPA7VOApFPZkSs2N8mN398Wg1TBfUqdBSF@cE1PJov713gfWhH5BH5pM4XL7ykZ7zBtQLPUpZx2Fo7UzcSq9mr/6DprVFrFbn8T9panJdlkfle8BZOYlfIHw "PowerShell – TIO Nexus")
This is a right mess, and I'm not terribly happy with it, but here it is. Golfing suggestions welcome.
The first line sets `$z` to be an array of the full English words. You can see the `-split0` for numbers `1` to `12`, and the loop to construct all the `teen`s, and then there's a bunch of logic to put everything together right. [Try it online!](https://tio.run/nexus/powershell#TY9BCoMwEEWvEkLEpEEZabtw4UlEAsKoAYlFo1Vaz24nFko3mZ9PeHlzQJre4R29JAf/ROc38J0daTTDedrGbzyZHr31oEotpagLLgwvoVJJ62@5ukhhKGUhaS5qnmSq0lKshSTo4JDAA1FHRILOIzEXhMmuMOGCDtC2nQdnw8Nw7c@WZPoFfz9r@U1xsGMBw0iNEYWdFBYoLEBiWkYYHXtEF@9KqZL8ogz@PCst1lKYs@gxFPtxHDzLGVnO7HrjHw "PowerShell – TIO Nexus")
The second line starts with some logic. We take the input `$args` (as a string), `-split` it on whitespace, store it into `$n` for use later, take the first `[0]` word, and the first `[0]` character of that, and check if it is `-in` a range `48..57` (i.e., ASCII `0` to `9`). So, we're checking if we have decimal input or English input. [Try it online!](https://tio.run/nexus/powershell#@6@hkmerW1yQk1mikliUXqwZbRALRLqZeSYWenqm5v///1cytFQoySgqVTA2UQIA "PowerShell – TIO Nexus")
In the first case, we build a range based on the decimal inputs `$n[0]..$n[2]` and use that to index into `$z[...]`. In the other case, we find the `.indexOf()` the first word and the last word, and build just a numerical range from that. In either situation, we now have an array of objects on the pipeline (either strings or integers), and an implicit `Write-Output` at program completion gives us a newline between elements.
[Answer]
## Swift3, 402 bytes
```
let f=["one","two","three","four","five","six","seven","eight","nine"]
let g=["twenty","thirty","forty","fifty"]
let v=[f,["ten","eleven","twelve"],["thir","four","fif","six","seven","eigh","nine"].map{$0+"teen"},[g[0]],f.map{g[0]+$0},[g[1]],f.map{g[1]+$0},[g[2]],f.map{g[2]+$0},[g[3]]].flatMap{$0}
func c(s:String){if let i=Int(s){print(v.prefix(upTo:i))}else{for j in 1...v.index(of:s)!+1{print(j)}}}
```
Ungolfed:
```
let f = ["one","two","three","four","five","six","seven","eight","nine"]
let g = ["twenty","thirty","forty","fifty"]
let values = [f,["ten","eleven","twelve"],["thir","four","fif","six","seven","eigh","nine"].map{$0+"teen"},
[g[0]], f.map{g[0]+$0},
[g[1]], f.map{g[1]+$0},
[g[2]], f.map{g[2]+$0},
[g[3]]].flatMap{$0}
func count(s:String){
if let i = Int(s) {
print(values.prefix(upTo: i))
} else {
for j in 1...values.index(of: s)!+1{
print(j)
}
}
}
count(s:"29")
count(s:"twentyeight")
```
Nothing special here, just using an array to back up the written-out numbers.
I originally thought this solution using this other way to calculate the `values` array:
```
let values = f + ["eleven","twelve"]
+ ["thir","four","fif","six","seven","eigh","nine"].map{$0+"teen"}
+ [g[0]] + f.map{g[0]+$0}
+ [g[1]] + f.map{g[1]+$0}
+ [g[2]] + f.map{g[2]+$0}
+ [g[3]]
```
Which could be golfed to:
```
let v=f+["eleven","twelve"]+["thir","four","fif","six","seven","eigh","nine"].map{$0+"teen"}+[g[0]]+f.map{g[0]+$0}+[g[1]]+f.map{g[1]+$0}+[g[2]]+.map{g[2]+$0}+[g[3]]
```
replacing the 3rd line in the golfed code
I could have scored 381 bytes, but, there is a compiler error that says: "expression was too complex to be solved in reasonable time", more info on the error can be found [here](https://stackoverflow.com/questions/29707622/bizarre-swift-compiler-error-expression-too-complex-on-a-string-concatenation)
[Answer]
## R, ~~452~~ ~~430~~ 424 bytes
```
o=c("","one","two","three","four","five","six","seven","eight","nine")
t=gsub(0,"teen",c("ten","eleven","twelve","thir0","four0","fif0","six0","seven0","eigh0","nine0"))
s=c("twenty","thirty","forty")
p=""
for(i in s){for(j in o){p=paste0(p,i,j," ")}}
as.data.frame(t(d<-1:50))
names(d)=c(o[-1],t,as.vector(strsplit(p," ")[[1]]),"fifty")
f=function(x){if(is.numeric(x)){names(d)[1:x]}else{matrix(d[1:d[x]],dimnames=NULL)}}
#> f(5)
#[1] "one" "two" "three" "four" "five"
#> f('five')
# [,1]
#[1,] 1
#[2,] 2
#[3,] 3
#[4,] 4
#[5,] 5
```
Places the numbers in a data.frame with written-out numbers as column names, making the translation between the two (and subsequent printing) pretty easy.
Main attempt at golfing was in creating the written-out numbers for 20-49, probably much more to golf here.
I made an attempt with `as.matrix` to print the data.frame with just the numbers, but am still left with a matrix header. Hopefully that's ok.
Ungolfed:
```
ones <- c("","one","two","three","four","five","six","seven","eight","nine")
teens <- c("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen")
tens <- c("twenty","thirty","forty")
p=""
for(i in tens){
for(j in ones){
p=paste0(p, i, j," ")
}
}
nums <- 1:50
as.data.frame(t(nums))
names(nums) <- c(ones[-1], teens, as.vector(strsplit(p, " ")[[1]]), "fifty")
f <- function(x){
if(is.numeric(x)){
names(nums)[1:x]
} else {
matrix(nums[1:nums[x]], dimnames = NULL)
}
}
```
[Answer]
# C, 342 331 bytes
```
char*x[]={"teen","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thir","four","fif","twenty","thirty","fourty","fifty"};void main(int z,char**i){for(z=1;z<=atoi(i[3]);z++)printf("%s%s%s\n",z<16?x[z]:z<20?z^18?x[z-10]:"eigh":x[z/10+14],z>20&&z%10?"-":z>12&&z<20?*x:"",z>20&&z%10?x[z%10]:"");}
```
[Try it online!](https://tio.run/nexus/c-gcc#TVDtasMwDHyVYkjJV5mdfTCcpHmQLIOw2ougs4frpplKn92znf4ohpPOpxOH3Nc0mnzph/ZKrBCKlEQr4dFedMDJiMCkPptQYA7sBEtAMcd5Ad@T9VXBalw/j3fVXsQxmuwE5nGTXEVl/@5ibIK8NiB9vdWzhsPmZwSVgrIbLGPeHLKr1CbFltXYtKPVkEL/PGQ1FkX2a/yoTElyCu/Dp8CGvXVLjwPHpqIdfrL3QHeMDjzmJ9zTJ0YL9jKUuK/odosJox3ZEY57VnkajPnCCXnUvSuJS0hW35xzzPmLnd0r/Qc "C (gcc) – TIO Nexus")
[Answer]
## SAS, 179
```
%macro c(n);%let f=words.;%if%length(&n)>2%then%do;%do c=1%to 50;%if%qsysfunc(putn(&c,&f))=&n%then%let n=&c;%end;%let f=2.;%end;%do i=1%to &n;%put%sysfunc(putn(&i,&f));%end;%mend;
```
Output is written to the log separated by newlines. SAS has a built-in format for converting digits to words, which is a major advantage for this challenge, but annoyingly it lacks an informat for doing the reverse.
] |
[Question]
[
Given an array of positive integers in base 10, where `n > 0`, output their representation of a binary wall.
**How does this work?**
1. Convert each number to it's binary representation.
2. Pad the representation with leading zeroes to the length of the longest one i.e. `1, 2` -> `1, 10` -> `01, 10`.
3. Create a wall where the `1`s are bricks and `0`s are missing bricks.
A wall is a block of characters where any printable character represents a brick and a space (`32`) represents a missing brick. You may choose any character for the brick, it need not be distinct across the wall as long as it isn't a white space character. The missing brick character must be a space. For the example below I have used `*` for the bricks.
**Example**
Input:
```
[ 15, 7, 13, 11 ]
```
1. `[ 1111, 111, 1101, 1011 ]`
2. `[ 1111, 0111, 1101, 1011 ]`
3. Output:
```
****
***
** *
* **
```
**Rules**
* Input must be taken in base 10, if your language accepts other bases you may not use them.
* Leading and trailing new lines are allowed.
* Input may be taken as a list of integers, separate arguments or any reasonable format.
* Output may be in any reasonable format: new line separated string, array of lines, 2d array etc.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are disallowed.
**Test Cases**
Note that in the first test case all of layers have an empty brick at the end.
```
[ 14, 4, 6, 2 ]
***
*
**
*
[ 1, 2, 4, 8, 16 ]
*
*
*
*
*
[ 15, 11, 15, 15 ]
****
* **
****
****
[ 11, 10, 9, 8 ]
* **
* *
* *
*
```
This is code golf so shortest code wins!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
B42*c
```
[Try it online!](https://tio.run/##y00syfn/38nESCv5//9oQ0MdBUMDHQVLHQWLWAA "MATL – Try It Online")
### Explanation
```
B % Implicitly input an array of numbers. Convert to binary.
% Gives a matrix with each row corresponding to a number
42 % Push 42 (ASCII code of '*')
* % Multiply
c % Convert to char. Char 0 is displayed as space. Implicitly display
```
[Answer]
# [J](http://jsoftware.com/), 8 bytes
```
' *'{~#:
```
[Try it online!](https://tio.run/##FYnLCYAwFMDunSIgWPXk07Z@ii4jFvHiAIKr175LSMidc2JbsXT2/arVmPO4HpqY2npHPBMyIkJEHI7AoFromJGg4fUrvVbRnoU55x8 "J – Try It Online")
## Explanation
```
' *'{~#: Input: array of integers
#: Convert each to binary with left-padding
' *'{~ Use the digits to index into the string ' *'
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Bo⁶Uz⁶ZUY
```
[Try it online!](https://tio.run/##y0rNyan8/98p/1HjttAqIBEVGvn///9oQ1MdBXMdBUNjIDaMBQA "Jelly – Try It Online")
EDIT: HOW J BEAT JELLY DAT IMPOSSIBLE >\_<
[Answer]
# Octave, 22 bytes
```
@(x)[dec2bin(x)-16,'']
```
[Try it online](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzOiU12SgpMw/I1DU001FXj/2fphFtaGptbm1obG1oGKv5HwA)
**Explanation:**
Saved some bytes thanks to Luis Mendo! Also, I didn't notice that I could choose which character to build the wall with, not only `*`.
```
@(x) % Take the input as a column vector
dec2bin(x) % Convert each row of the input to a string with 1 and 0
% It gets automatically padded with zeros, to fit the longest number
dec2bin(x)-16 % Subtract 16, to get from the ASCII-values of 1/0 (48/49)
% to 32/33 (space and !)
@(x)[dec2bin(x)-16,''] % Concatenate with the empty string to convert it to a string.
```
---
Or with `de2bi`:
**Explanation:**
```
@(x) % Take the input as a column vector
de2bi(x) % Convert each row of the input to a binary number.
% Gets automatically padded to fit the longest number
42*de2bi(x) % Multiply the matrix by 42, which is the ASCII-value for *
[42*de2bi(x),''] % Concatenate the matrix with the empty string to convert
% it to a string. 0 are automatically displayed as spaces
@(x)fliplr([42*de2bi(x),''])
```
---
The following works on TIO, for 7 bytes more:
```
@(x)fliplr([42*(dec2bin(x)>48),''])
```
[Try it here](https://tio.run/##y08uSSxL/Z9mq6en999Bo0Iz2sRISyMlNdkoKTMPyLUzsdDUUVeP/Z@mEW1oam1ubWhsbWgYq/kfAA)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~88 84 71 74~~ 72 bytes
A lambda that returns a list of Strings, representing each line.
```
lambda n:[bin(x)[2:].replace(*'0 ').rjust(len(bin(max(n)))-2)for x in n]
```
[Try it online! (link to the newline separated version)](https://tio.run/##jctBDoIwEIXhvaeYsOmMqQRQjJJwEsqiSIkQGEitST19LXsXLl7e5vu3j3uufA5DrcKsl67XwFXTjYyemqJqU2u2WT8MHkUGglI7vV8OZ8O4m0V7ZCI6FTSsFjyMDNyGzY7sUCgW6bRGNmCTlxLyPG7/siWShvs6Uaw4ocOvYMeZhLuE2x8cIi8kXKKO3RViQuEL "Python 3 – Try It Online")
## Explanation
* `lambda n:` - Creates an (anonymous) lambda, with a parameter `n`. Returns implicitly.
* `[...]` - Creates a list comprehension.
* `bin(x)[2:]` - Gets the binary representations of the numbers.
* `.replace(*'0 ')` - Replaces all the occurrences of `0` with a space.
* `.rjust(len(bin(max(n)))-2)` - Pads the binary representations to the length of the longest one.
* `for x in n` - Iterates through `n`, with the variable `x`.
---
### Changelog
* *-~~1~~ - 3 bytes thanks to @Rod, `-(...)+2` = `2-(...)`, use of `rjust()`*
* ~~Added a version with `bin()` instead, that was invalid since it didn't work for `1` and `2`.~~
* ~~Fixed the bug above using `format()`.~~
* Changed return type to list of Strings, because it was allowed by the OP.
* Fixed yet another bug using `rjust()` and switching back to `bin()`, spotted and fixed by @Rod.
[Answer]
## JavaScript (ES6), ~~81~~ 79 bytes
*Saved 2 bytes by using numbers instead of characters for the bricks, as suggested by Rick Hitchcock*
Returns a 2D array with 1's for the bricks.
```
f=(a,b=[],x=1)=>a.every(n=>n<x)?a.map(n=>b.map(i=>n&i?1:' ')):f(a,[x,...b],x*2)
```
### Test cases
```
f=(a,b=[],x=1)=>a.every(n=>n<x)?a.map(n=>b.map(i=>n&i?1:' ')):f(a,[x,...b],x*2)
format = a => a.map(s => s.join``).join`\n`
console.log(format(f([ 14, 4, 6, 2 ])))
console.log(format(f([ 1, 2, 4, 8, 16 ])))
console.log(format(f([ 15, 11, 15, 15 ])))
console.log(format(f([ 11, 10, 9, 8 ])))
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~76~~ ~~75~~ 74 bytes
```
f x|all(<1)x=x>>[""]|a<-f$map(`div`2)x=zipWith(++)a$map(cycle[" ","*"]!!)x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoiYxJ0fDxlCzwrbCzi5aSSm2JtFGN00lN7FAIyElsyzBCChTlVkQnlmSoaGtrZkIlkmuTM5JjVZSUNJR0lKKVVTUrPifm5iZZ1tQWhJcUqRSmpeTmZdarJIWrWBoqqNgrqNgaAzEhgqx/wE "Haskell – Try It Online")
[Answer]
# Ruby, ~~63~~ 59 bytes
-4 bytes with help from Alexis Andersen
```
->*n{puts n.map{|i|("%#{('%b'%n.max).size}b"%i).tr'0',' '}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf104rr7qgtKRYIU8vN7GguiazRkNJVblaQ101SV0VJFahqVecWZVam6SkmqmpV1KkbqCuo66gXlv7Py3a0FRHwVxHwdAYiA1j/wMA "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 87 ~~88~~ bytes
Wall blocks represented by an `8`, because, well lots of eights.
```
write(ifelse((I=sapply(scan(),intToBits))[(M=max(which(I>0,T)[,1])):1,],8,' '),1,M,,'')
```
[Try it online!](https://tio.run/##BcE7CoAwEAXAq6TLLrzC7VTQws7CLp1YBIm44A8TUE8fZ@6cn1tTIF3CFgNR30R/XdtHcfYHMfRI7uw0ReaRhmb3Lz2rziv1bQHHI2RirgUTSlhjGYIBsJaziJHCVKbMPw "R – Try It Online")
Input integer list is converted to array of bits which are trimmed of trailing 0 bits and reversed.
The reduced array is then output using `write` and a column width which was determined when the array was trimmed.
`ifelse()` is the only IF option that works on vectors unfortunately.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~30~~ ~~22~~ ~~20~~ 14 bytes
*Saved 6 bytes thanks to @Adám*
```
' *'[⍉2⊥⍣¯1⊢⎕]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862h3/qytoqUc/6u00etS19FHv4kPrDR91LQKqif0PlP7vyKVhaKpgrmBorGBoqMkFFAfqVFfnAombKJgomCkYoYkqGAGFLRQMzdDETYEGKIBIUzQJoKiBgqWChSYA "APL (Dyalog Unicode) – Try It Online")
(assumes `⎕IO←0` as this is default on many machines)
This takes input as an array and returns a matrix with `*`s and s.
### Explanation
```
2⊥⍣¯1⊢⎕ Convert input to binary (returns a transposed matrix of 1s and 0s)
⍉ Transpose
' *'[ ... ] Index into this string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
bí.Bí»0ð‡
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/6fBaPafDaw/tNji84VHDwv//ow1NdRTMdRQMjYHYMBYA "05AB1E – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 100 bytes
```
$args|%{if(($c=($a=[convert]::ToString($_,2)).length)-gt$l){$l=$c}$a-replace0,' '}|%{$_.padleft($l)}
```
[Try it online!](https://tio.run/##DcxBCoMwEADAr/SwxQRUWpEehLyivRWRkK5RWJIQl/Zg8/bV@zAp/jBvCxKJgM1@@1/3dVYKnFFgzdvF8MXM4zC84pPzGryCqe60bgmD50U3noH0DmTAFbBNxkTW4a2uLlU5M5jaZD@EM6vTFRG599LLQ7oD "PowerShell – Try It Online")
Ugh, `convert`ing to binary in PowerShell is so painful. Plus `.length`y calls to `-replace` the `0` with spaces, plus a long `.padLeft()` call to make them all the same `.length`, all adds up to a long submission.
Golfing suggestions to get below 100 are welcome.
[Answer]
# T-SQL, 290 bytes
```
declare @ int;select @=max(log(a,2))+1from @i;with t as(select convert(varchar(max),a%2)b,a/2c,@-1m,ROW_NUMBER()over(order by(select 1))r from @i union all select convert(varchar(max),concat(c%2,b))b,c/2c,m-1,r from t where m>0)select replace(b,0,' ')from t where m=0group by r,b order by r
```
Uses `1` for the brick piece, assumes input comes from table `@`
Ungolfed, with some explanation
```
-- assume input is presented in an input table
declare @input table (a int)
insert into @input values (15), (7), (13), (11)
---- start here
-- figure out how many characters are needed, by taking log2
declare @max int
select @max = max(log(a, 2)) + 1
from @input
-- recursive cte
-- will join against itself, recursively finding each digit in the binary string
;with cte as
(
select
convert(varchar(max), a % 2) as b, -- is the least significant bit 1 or 0
a / 2 as c, -- remove least significant bit, for the next run
@max - 1 as max, -- keep track of iterations left
ROW_NUMBER() over (order by (select 1)) as rn -- keep the order of the input
from @input
union all -- recursive loop
-- below columns follow the same pattern
select convert(varchar(max),
concat(cte.c % 2, cte.b)) as b, -- prepend the current binary string with the newest least significant bit
cte.c / 2 as c,
cte.max - 1,
cte.rn
from cte
where cte.max > 0
)
select replace(b, 0, ' ') -- swap 0s for space
from cte
where max = 0 -- only take the last iteration
group by rn, b -- grab each unique input,
-- need to group by row number so it can be ordered by
-- need to group by binary string, so it can be selected
order by rn -- sort by the order the input arrived in
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~77~~ 75 bytes
```
lambda k:[[' *'[i>>y&1]for y in range(len(bin(max(k)))-3,-1,-1)]for i in k]
```
[Try it online!](https://tio.run/##PY1BDoIwEEX3nOKvpDUlsahESeAitYsSQRugEOhCTl/bGkkmmXlvfvLnzb4nk7uuerhBjc1ToS@FSHFMha7r7cBlNy3YoA0WZV4tGVpDGm3IqD6kp5RmZ5ZxPzQGdQj20tl2tSsqiAQQ4BcGPwVDDsl@yt9R3hh4sdurJ/@K@7rbYE4Md5@GTGQSmkJDKItNpc/NizY24g4dCUj/7L4 "Python 2 – Try It Online")
[Answer]
# Mathematica, 40 bytes
```
Grid@PadLeft@IntegerDigits[#,2]/. 0->""&
```
Bricks are 1s
# Mathematica, 48 bytes
```
Grid@PadLeft@IntegerDigits[#,2]/.{0->"",1->"#"}&
```
Bricks are #
[Answer]
# PHP, 84 bytes
```
while(++$i<$argc)echo strtr(sprintf("\n%".-~log(max($argv),2).b,$argv[$i]),10,"* ");
```
Luckily, the bit operation casts the `log` result to int. float wouldn´t work here.
[Try it online](http://sandbox.onlinephpfunctions.com/code/a51cbe200ffc13107212f264a8520b3501ef05c1).
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 112+18=130 86+41=127 bytes
```
a=>a.Select(n=>C.ToString(n,2).Replace("0"," ").PadLeft(C.ToString(a.Max(),2).Length))
```
[Try it online!](https://tio.run/##vZBPawIxEMXv@ymGPW0gDa79j@4eKm1pqyBa8GA9pHHcBnYTm0RbET/7NuuK9VCKh9KB5PB4M795I@yJ0AbLhZUqg@HKOixYV6r3Vq10kp3W0WqJxrWCQPEC7ZwLhBupuFmNeJ4H6wB8iZxbC32jM8OLrVLrVVnHnRSw1HIKPS5VZJ3xhPEEuMks2fu@O6ra0e8WSrSlcuMJhf1CeY7CSa0su0eFRgr2cKsWBRr@mmO7Hp@mMIMkKHmScjbEqiNSSdphz3q4NUSKNgkb4Dz3iaKwEdIQQsL6fNrFmYsOjJz1@GdEKnsXVebeCCn9OX7Y1t/K6hzZyEiH/pi4y8oetc8dvqiQwixS@OHDryE@p3BJIT71L4YNIaR13NBjfb/CKTQpnFG48vSLf6d7fNygcO35f8ceIJ8@4erQtQnqfxOUXw "C# (.NET Core) – Try It Online")
The byte count includes 41 bytes from `using System.Linq;using C=System.Convert;`. Uses `1` as character for the wall. Nonetheless, this is way too long even for C#...
[Answer]
# [Retina](https://github.com/m-ender/retina), 63 bytes
```
.+
$*#<
+`(#+)\1
$1
#
#
{T`<`_`^(<.+(¶|$))+$
m`^<
<
(.)<
<$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRUvZhks7QUNZWzPGkEvFUIFLQZlLmas6JMEmIT4hTsNGT1vj0LYaFU1NbRWu3IQ4Gy4FGy4NPU0bLhsVw///DU24TLjMuIwA "Retina – Try It Online") Explanation:
```
.+
$*#<
```
Convert to unary, and suffix a `<`.
```
+`(#+)\1
$1
#
#
```
Convert to binary.
```
{T`<`_`^(<.+(¶|$))+$
```
Once all the `<`s have reached the left, delete them all.
```
m`^<
<
```
Insert a space before any `<`s that have already reached the left.
```
(.)<
<$1
```
Move all the `<`s left one step. Rinse and repeat.
[Answer]
# Clojure, 185 bytes
```
(fn[i](let[b(map #(Long/toBinaryString %)i)](map #(clojure.string/replace(clojure.string/replace(format(str"%0"(reduce(fn[l i](max l(count i)))0 b)"d")(read-string %))"1""#")"0"" ")b)))
```
## Ungolfed version:
```
(fn [i]
(let [b (map #(Long/toBinaryString %) i)]
(map
#(clojure.string/replace
(clojure.string/replace
(format
(str "%0"
(reduce
(fn [l i] (max l(count i))) 0 b)
"d")
(read-string %))
"1"
"#")
"0"
" ")
b)))
```
Anonymous function that takes the argument as a list. Returns the lines as list.
Reading the other answers, I bet it could be smaller. `clojure.string/replace` takes an obscene amount of chars to write..
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~33~~ 30 bytes
```
¡'0p(¡X¤lÃn o)-X¤l)+X¤)£" *"gX
```
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=oScwcCihWKRsw24gbyktWKRsKStYpCmjIiAqImdY&input=WzE0LDQsNiwyXS1S)
Saved 3 bytes thanks to [@Justin Mariner](https://codegolf.stackexchange.com/users/69583/justin-mariner)
### Explanation
```
¡ // map input integers
(¡X¤lÃn o) // longest binary string length
-X¤l) // minus current binary string length
'0p // repeat zero
+X¤) // concat with current binary string
£ // map chars of binary string
" *"gX // swap 0 and 1 with ' ' and '*'
```
[Answer]
# [Python 3](https://docs.python.org/3/), 92 90 bytes
```
lambda a:[' '*(len(bin(max(a)))-len(i)-2)+i for i in[bin(i)[2:].replace(*'0 ')for i in a]]
```
[Try it online!](https://tio.run/##NYzBCsIwEAV/5d2yq6loFA8FvyTksNUEF9I0hB7062N7EOY0DFO/63sp197TI8s8vQQyegNzoBwLTVpolg8JMw@7UB4cHxVpaVBo8Xuh7N0YTi3WLM9I5mzsduB/Awmh16ZlpUQel5vFxt3CITD3Hw "Python 3 – Try It Online")
Returns a list of lines. Stacking them up shows they do indeed align properly.
```
['111 ', ' 1 ', ' 11 ', ' 1 ']
>>>
111
1
11
1
```
# The breakdown
Essentially converts the array to binary, then replaces all 0's with spaces. `N` number of spaces are added to the front of each line where `N = [length of longest line] - [length of line]`.
`-1 bytes` Thanks to Mr. Xoder
[Try it online!](https://tio.run/##NcpBCsIwEEbhq/y7zNRWNIqLQk8Ss5hqggNpGkIXevpoF8JbPb7y2V5rvrQ43VuSZX4KZHQGpqMUMs2aaZE3CTMP@1AeLB8Uca1QaHa7UHZ29McaSpJHoM6cYPgvIN63UjVvFMnhfO3x69bDwjO3Lw "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
m¤z3 z ·r0S
```
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=baR6MyB6ILdyMFM=&inputs=WzE0LCA0LCA2LCAyXQ==,WzEsIDIsIDQsIDgsIDE2XQ==,WzE1LCAxMSwgMTUsIDE1XQ==,WzExLCAxMCwgOSwgOF0=)
## Explanation
```
m¤z3 z ·r0S Implicit input of array
m¤ Map the array to binary strings
z3 z Rotate right 270° and then right 90°. This adds left padding to each string
·r0S Join with newlines and replace 0s with spaces
```
[Answer]
# Java 7, ~~130~~ ~~108~~ 88 bytes
Saved 22 thanks to @TheLethalCoder
Saved 20 thanks to @Xanderhall
```
void a(int[]b){for(int i:b)System.out.println(Long.toBinaryString(i).replace('0',' '));}
```
Ungolfed:
```
void a(int[]b){
for(int i:b)
System.out.println(Long.toBinaryString(i).replace('0', ' '));
}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 98 bytes
```
$p=$args|%{$n=$_;31..0|?{($n-shr$_)%2}}|sort
$args|%{$n=$_;-join($p[-1]..0|%{' *'[($n-shr$_)%2]})}
```
[Try it online!](https://tio.run/##VZHxaoMwEMb/z1McIc4kxFLb2W0MWd@jFBlbtnaIOuPYQPPs7pKo2JDjSy73y3dwTf2rW3PRZTmyD8ihH1mTs9f20wxRz6qcFc/7dLPZDi89Z1ViLi0rRLSzdjB125HbyuSrvlacNackPTsm6mOQ8WkNnq2woyXkyAlRnKeZggcF6R4jFYqTWOKKFUEwqJQQFBMxEcJT9wpwHxTsZgYCA5NOd0wsDBZ76hGtDh4DXMHLF07A8hMEW3eY/8hcmxhOs5t2fXtqdZerdh2yVfCE5gGCBZpN5GzmISJggAh64txZeTWdYvqv0W@dfschsSI8tNr8lB0m7nB2R1fm85RxOr3RRH/TBaWCrkFix38 "PowerShell – Try It Online")
The script uses the fact that an integer contains no more than 32 bits.
The first line calculates positions of the bits with 1. The second line renders a binary wall.
[Answer]
# Python 2, 217 bytes
After 2 hours of coding i decided, that numpy is bad idea for this
```
import numpy as n
i=n.loadtxt("i")
o=[n.copy(i)]
o[0].fill(10)
while n.count_nonzero(i)>0:
o.append(i%2+32)
i=n.vectorize(lambda x:x//2)(i)
print n.fliplr(n.array(o).T).astype('uint8').view('c').tostring().decode()
```
## Usage in Ubuntu
Install numpy
```
python2 -m pip install numpy
```
Create file named `i` with input in format `14 4 6 2`
Run
```
python2 prog.py
```
[Answer]
# [8th](http://8th-dev.com/), ~~232~~ ~~254~~ 250 bytes
**Code**
```
0 >r a:new swap ( nip 2 base drop >s decimal s:len r> n:max >r a:push ) a:each drop a:new swap ( nip '0 G:c# r@ G:#> s:fmt a:push ) a:each drop rdrop a:new swap ( nip /0/ " " s:replace! a:push ) a:each drop ( nip /1/ "*" s:replace! . cr ) a:each drop
```
**Ungolfed version with comments**
```
\ convert to binary and save longest string length
: f 0 >r a:new swap ( nip 2 base drop >s decimal s:len r> n:max >r a:push ) a:each drop ;
\ pad binary number with zero
: f1 a:new swap ( nip '0 G:c# r@ G:#> s:fmt a:push ) a:each drop rdrop ;
\ replace every 0 with space
: f2 a:new swap ( nip /0/ " " s:replace! a:push ) a:each drop ;
\ replace every 1 with * and print each line of bricks
: f3 ( nip /1/ "*" s:replace! . cr ) a:each drop ;
```
These words must be invoked in sequence (see example)
**Usage and examples**
```
ok> [15,7,13,11] 0 >r a:new swap ( nip 2 base drop >s decimal s:len r> n:max >r a:push ) a:each drop a:new swap ( nip '0 G:c# r@ G:#> s:fmt a:push ) a:each drop rdrop a:new swap ( nip /0/ " " s:replace! a:push ) a:each drop ( nip /1/ "*" s:replace! . cr ) a:each drop
****
***
** *
* **
```
Or more clearly
```
ok> [15,11,15,15] f f1 f2 f3
****
* **
****
****
```
[Answer]
# Pyth, 16 bytes
```
j_MC.tm_X.Bd\0\
```
[Try it here.](http://pyth.herokuapp.com/?code=j_MC.tm_X.Bd%5C0%5C+&input=%5B15%2C+7%2C+13%2C+11%5D&debug=0) Mind the trailing space.
[Answer]
# Excel VBA, ~~170~~ 161 Bytes
### Golfed
Anonymous VBE immediate window function that that takes input of format `1 2 3 .. n` from range `[A1]` and outputs the corresponding binary wall to the VBE Immediate window via range `[B1,C1,2:2]`
```
n=Split([A1]):[A2].Resize(1,UBound(n)+1)=n:[C1]="=Int(1+Log(B1,2))":For Each i In n:[B1]=i:?Replace(Replace([Right(Rept(0,C1)&Dec2Bin(B1),C1)],1,"*"),0," "):Next
```
Formatted:
```
n=Split([A1])
[A2].Resize(1,UBound(n)+1)=n
[C1]="=Int(1+Log(B1,2))"
For Each i In n
[B1]=i
?Replace(Replace([Right(Rept(0,C1)&Dec2Bin(B1),C1)],1,"*"),0," ")
Next
```
### Ungolfed
Full `Sub`routine that takes input of format `Array(1, 2, 3...)` and outputs the corresponding binary wall to the VBE Immediate window via range `[A1,B1,2:2]`
```
Sub a(ByRef n As Variant)
Let Range("A1").Resize(1,UBound(n)+1) = n
Let Range("C1").Value = "=Int(1+Log(A1,2))"
Dim i As Integer
For Each i In n
Let Range("A1").Value = i
Debug.Print Replace(
Replace(
[Right( Rept( 0, C1) & Dec2Bin( B1), C1)],
1,
"*"
),
0,
" "
)
Next
End Sub
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
WS«⸿≔IιιWι«←§ *ι≧÷²ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDM6@gtCS4pCgzL11DU1OhmoszAMgu0VCKKVLStObidCwuzkzP03BOLC7RyNTUUcgECUL1ZoLVQzVY@aSmlegoOJZ45qWkVmgoKWgpgVSDlHP6JhZAzAnKTM8oAdpZ4pJZlpmSqqNgBDWxlqv2/39DEy4TLjMuI67/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Works by manually converting each input number to binary but printing it in right-to-left order. I take the input as a newline terminated string as Charcoal doesn't have a good way of inputting lists otherwise I would write something like this which unfortunately currently takes 21 bytes:
```
WS⊞υIιW⌈υ«Eυ﹪κ²↓⸿≧÷²υ
```
[Try it online!](https://tio.run/##Lc0xC4MwEIbhufkVwSmBdKhIh3YqunQQpF27BBVzNCZicloo/e3pCa7fPS/XGj23XtuUVgO25@LuJozPOIMbhJS8wWAEKl7qEAVIeWW7q/UHRhwFEvqyQ0NBpHHacO07tF68Fc/lluzXS@VXp3j2mrNtJHwLAQb3gMFEehwrWKDrqVIcSfxSOhWsYGeWs3Rc7B8 "Charcoal – Try It Online") Link is to verbose version of code. This version vectorises over the input array, although its output is hardcoded to `-`s which saves a byte.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 8 bytes
```
" *"@+2\
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NSklBS8lB2yjmf5q6hqGpgrmCobGCoaG1oYmCiYKZgpG1oYIRkGWhYGhmDZQ2NFQAkabWIIaBgqWCheZ/AA "K (ngn/k) – Try It Online")
Takes input as a list of integers, outputs as a list of strings.
* `2\` convert (implicit input) to base-2 representation
* `+` transpose result
* `" *"@` replace 0's with and 1's with `*`
] |
[Question]
[
It's my 17th birthday and you're invited to my party!
And as always at parties, there will be cake.
One cake...
And you need as much of it as possible.
As this is a fair party, each of us will say how much of my cake we want and the person who said the smallest amount will get it. Then everyone else gets to repeat the process until the cake is gone.
# Challenge
* Given the input through command line arguments in the form of `total-degrees degrees-left total-people people-left`, output to standard output `integer-bid-in-degrees`.
* If your bid was the lowest, you receive that amount of cake and are out for the round.
* If your bid wasn't lowest, your bot gets to bid on the remaining cake.
* In the case that the lowest bids are the same, the person removed will be chosen at random.
* At the end of a round, once all the cake is gone or there is nobody left to bid on it, the person with the most cake wins!
* In the case at the end of a round and two people have the same sized biggest slice, the winner is chosen at random from the drawing entries.
# Gameplay
* There will be 17 rounds, the overall winner will be the entry with the most wins overall.
* In the case of a draw, rounds will be played until there is a clear winner.
* Each day, I will update the current scores so that people can upgrade their entry.
# Submission
You should write your entry as
>
> Bot Name, Language
>
>
>
> ```
> Insert
> Code
> Here
>
> ```
>
> Explanation/Random stuff here
>
>
>
If your entry isn't formatted in this way, the controller will NOT be able to run your entry. If I find this has happened to your entry, I will either notify you in a comment, and/or edit the answer into the correct format.
# Your entry and file storage
* Your bot may store files in the `./data/` directory and nowhere else.
+ Not required but please store your files as `botname*`
+ You may not write files in this format if `botname` is not your entries name.
+ This means you are allowed to overwrite other files you find that don't appear in this format. You shouldn't do this deliberately, please be sporting.
+ Your bot must not assume that the files it requires are present but it can assume `./data/` exists.
+ This is because I occasionally wipe the `./data` directory, I **will** do this when the rounds actually start. (But not between them)
* Your bot may not delete files at all
* Your bot is only allowed to read files in the `./data/` directory
+ This means you *may* look at other entries files
# Results:
**Meek won the contest! Well done @Cabbie407**
And now for some random stats:
A list of positions each bot came in: (Well done to any bot appearing in this list, you came in the top 5 at least once!)
1. Meek, Meek, Eidetic, Eidetic, Meek, Eidetic, Eidetic, Meek, Meek, Meek, Saucy, Meek, Givemethecake, Givemethecake, Givemethecake, Meek, Eidetic
2. Eidetic, Eidetic, Meek, AlCakeSurfer, Eidetic, AlCakeSurfer, Meek, MyFairPlusAThird, Eidetic, Eidetic, Eidetic, Eidetic, MyFairPlusAThird, MyFairPlusAThird, Meek, MyFairPlusAThird, AlCakeSurfer
3. Reallythecake, AlCakeSurfer, AlCakeSurfer, Meek, AlCakeSurfer, Meek, AlCakeSurfer, AlCakeSurfer, Reallythecake, AlCakeSurfer, Meek, MyFairPlusAThird, Eidetic, Eidetic, Eidetic, Eidetic, Reallythecake
4. AlCakeSurfer, Reallythecake, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, Eidetic, AlCakeSurfer, MyFairPlusAThird, MyFairPlusAThird, Relinquisher, Relinquisher, bill, bill, Relinquisher, MyFairPlusAThird
5. bill, MyFairPlusAThird, bill, bill, bill, bill, Relinquisher, Relinquisher, MyFairPlusAThird, Relinquisher, bill, Reallythecake, bill, ALittleOffTheTop, ALittleOffTheTop, bill, bill
The full log file for the cometition whilst running can be found [here](http://www.mediafire.com/view/tcr6ydhqpq4razl/PPCG-Cake-Cutting.txt). Sorry about the format change partway through.
**I will not be running the contest again, if you want to post more entries, you're welcome to do so, the controller can be found on [my github repo for this contest](https://github.com/muddyfish/cake-cutting-contest).**
[Answer]
# Magician, Java
```
public class Magician{
public static void main(String[] args){
System.out.println(720);
}
}
```
The number 720 is magical.
This ~~is~~ was meant to test the controller and is ~~not~~ a serious entry.
[Answer]
# Slim, Python 2
```
print 0
```
This bot's on a diet.
[Answer]
# SadBot :(, C++
```
#include<iostream>
#include<cstdlib>
#include<stdlib.h>
int main(int argc, char**argv)
{
if (argc!=5){std::cout<<"Incorrect number of arguments";return 1;}
double list[4];
list[0]= atof(argv[1]); // total Degrees
list[1]= atof(argv[2]); // degrees left
list[2]= atof(argv[3]); // total people
list[3]= atof(argv[4]); // people left
std::cout<<list[1]/list[3]; // degrees left/ people left
return 0;
}
```
**Formerly FairBot**
FairBot just wants an equal portion :(
He wants to split the cake evenly amongst all the participants.
(He fully expects the other bots to rip him off though because he knows they're mean)
(Like really. He is lonely, he just wants the other bots to like him)
(He just got out of a bad relationship and is going through a really rough patch, so if you could just give him a pat on the back and a smile to make him feel better it would really mean a lot. )
**EDIT** changed program to take input from argv/c instead of stdin (fair bot is still sad.... He wants to change his name to sadbot (which is kinda why he wants cake))
[Answer]
# Halver, Ruby
```
def halver(total_degrees, degrees_left, total_people, people_left)
if people_left == 1
degrees_left
else
degrees_left/2 - 1
end
end
p halver(*ARGV.map(&:to_i))
```
Scrupulously, unimpeachably fair. Half the cake for me, half the cake for everyone else.
[Answer]
# CharityBot, Python 2
```
print -360
```
Adds another cake to the mix!
(The controller will see this as a request for 0 cake, will not actually add to the size of the cake)
[Answer]
# Dieter, Java
```
public class Dieter {
public static void main(String... args){
System.out.println("4");
}
}
```
It doesn't want to bid for too much cake, so it chooses a small but [guaranteed random](https://xkcd.com/221/) slice.
[Answer]
# Stately Imitator, Ruby
```
def stately_imitator(total_degrees, degrees_left, total_people, people_left)
current_winner_path = './data/current_winner'
previous_cake_path = './data/previous_cake'
first_move = (total_people == people_left)
current_winner = first_move ? 0 : File.read(current_winner_path).to_i
previous_cake = first_move ? total_degrees : File.read(previous_cake_path).to_i
last_slice = previous_cake - degrees_left
current_winner = [current_winner, last_slice].max
File.open(previous_cake_path, 'w') { |f| f.puts(degrees_left) }
File.open(current_winner_path, 'w'){ |f| f.puts(current_winner) }
if first_move
degrees_left / 2
else
average_left = degrees_left.fdiv(people_left).ceil
bid = [average_left, current_winner+1].max
[bid, degrees_left].min
end
end
p stately_imitator(*ARGV.map(&:to_i))
```
Variant of [Imitator](https://codegolf.stackexchange.com/a/59746/6828) (if you'd rather only one entry per player, this supersedes that one). Keeps precise track of the largest slice taken already, and always bids enough to beat that slice. Will also never bid lower than its fair share of the remainder. Assumes a read/writable './data' directory already exists; the files can either be there already or not.
[Answer]
# Meek, awk
```
BEGIN{srand();print int(rand()>=.5?ARGV[2]/2.89:ARGV[1]/10-rand()*13)}
```
I saw this once in a simulation.
[Answer]
# Flaming Chainsaw, Java
```
public class FlamingChainsaw
{
public static void main(String[]args)
{
if(args.length<4){return;}
if(Integer.parseInt(args[3])<3){System.out.println(0);}
else{System.out.println(args[1]);}
}
}
```
Have you ever tried holding a cake-cutting contest with a chainsaw? Well, now you have. It's rather disruptive.
[Answer]
# Gentleman, Java
```
import static java.lang.Integer.parseInt;
import java.io.*;
import java.util.*;
public class Gentleman{
private final static String FILE_NAME = "data/Gentleman.txt";
static {
new File("data").mkdir();
}
public static void main(String[] args) throws Exception{
int totalCake = parseInt(args[0]);
int cakeLeft = parseInt(args[1]);
int totalPeople = parseInt(args[2]);
int peopleLeft = parseInt(args[3]);
if (totalCake == cakeLeft){
System.out.println(cakeLeft);
} else {
int previousCake = load();
int cakeDiff = previousCake - cakeLeft;
if (cakeDiff > optimal(previousCake, peopleLeft + 1)){
System.out.println(peopleLeft == 1 ? cakeLeft : Math.min(cakeLeft, cakeDiff + 1));
} else {
System.out.println(cakeLeft); //Hey, I might get lucky :)
}
}
save(cakeLeft);
}
private static void save(int cake) throws Exception{
PrintStream out = new PrintStream(FILE_NAME);
out.print(cake);
}
private static int load() throws Exception{
Scanner in = new Scanner(new File(FILE_NAME));
return in.nextInt();
}
private static int optimal(int cake, int people){
return (cake + people - 1) / people;
}
}
```
He waits for people who eat a fair share or less before he eats any cake. To prevent the greedy from getting extra cake, he takes as large a portion as possible.
[Answer]
# Bob Barker, Java
```
public class BobBarker{
public static void main(String[] args){
System.out.println((int)Math.floor(Integer.parseInt(args[1]) * .84));
}
}
```
This is probably going to be replaced with a more thought-out solution later, but I'm curious if this will work. This is just to catch any bots that try and go for maximum, and do a modified Price is Right strategy to steal their answer. Might lead to escalation with increasing integer subtractions, that'd be neat.
EDIT: Escalation commences, counter-posting against FloorBot
[Answer]
# Eidetic, Python 2
```
import random, math, sys, json
total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])
#try:
# inp_f = open("./data/Eidetic.json", "r")
# out = json.load(inp_f)
#except (IOError, ValueError):
out = {"last_cake": 0,
"runs": 0,
"total_runs": 0,
"total_rounds": 0,
"training": [[0.0], [0.0], [0.12903225806451613], [16.774193548387096], [400.83870967741933], [720.0], [995.8709677419355], [996.9437634408603], [997.6], [997.6], [997.6], [998.5991397849463], [996.6770967741936], [998.8122580645161], [1011.5467420570814], [1017.7717824448034], [1227.155465805062], [1280.7840603123318], [1435.8028540656974], [1553.3689822294023], [1793.5330640818527], [2299.178101402373], [3183.924709689701], [2231.666666666667], [2619.4789644012944], [1270.9288025889969], [741.2718446601941], [480.4757281553398], [122.66990291262135], [27.54736842105263]]}
#else: inp_f.close()
def write_out():
out_f = open("./data/Eidetic.json", "w")
out_f.write(json.dumps(out))
out_f.close()
def get_last_winner(): # Find the bid of the last winner
bid = out["last_cake"]
return max(bid, degrees_left) - degrees_left
def train():
# print degrees_left # If you get that much, your probably safe.
# sys.stderr.write("\nEidetic - Training len %s, no runs: %s, no_rounds: %s, last winner: %s\n"%(len(out["training"]), out["runs"], out["total_rounds"], get_last_winner()))
if len(out["training"]) <= out["runs"]: out["training"].append([])
out["training"][out["runs"]].append(get_last_winner())
def get_best_round():
data = out["training"][out["runs"]+1:]
mean = [sum(i)/(float(len(i)) or 1) for i in data]
bid = max(mean+[0]) - 0.5
sys.stderr.write("\nEidetic - mean %s\n"%mean)
return bid
def main():
reset = total_people == people_left
if reset:
out["total_rounds"] += 1
out["runs"] = 0
train()
bid = get_best_round()
print bid
# sys.stderr.write('\nEidetic Bid: '+str(bid)+'\n')
out["total_runs"] += 1
out["runs"] += 1
out["last_cake"] = degrees_left
write_out()
main()
```
I ran this bot in the controller a couple of times to train it up a bit, it remembers the bids required to win each round and then once trained, it goes out into the real world and votes with the rest of them.
[Answer]
## AlCakeBot, Python
```
import sys, math
total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])
fraction_left = (degrees_left + 0.0)/ total_degrees
fraction_gone = 1.0 - fraction_left
factor = (math.sin(fraction_gone * math.pi / 2.0))**2
fraction = (factor/2.0) + 0.5
if total_degrees == degrees_left:
print(int(math.floor(total_degrees/2.0) - 1))
else:
print(int(math.floor(degrees_left * fraction)))
```
This is my first PCG post; I hope this works out as intended …
I love cake. No matter which kind. My colleagues know. And so does my bot. If the entire cake is still there, he will bid for just under half of it, hoping to get the biggest slice immediately. If not, he should bid for something between half the remaining cake and all the remaining cake, using a squared sine as a weighting function (`½ + sin² (fraction gone) / 2`). The reasoning being that there should be a chance for an overall larger (but fractionally smaller) slice early in the game and there also being little point in trying to be a gentleman in the late game.
Since I’m not very much into programming, I’ll appreciate any error pointed out. Now let’s eat some cake =D
[Answer]
# Saucy, Ruby
```
def saucy(total_degrees, degrees_left, total_people, people_left)
current_winner_path = './data/saucy_current_winner'
previous_cake_path = './data/saucy_previous_cake'
first_move = (total_people == people_left)
current_winner = first_move ? 0 : File.read(current_winner_path).to_i
previous_cake = first_move ? total_degrees : File.read(previous_cake_path).to_i
last_slice = previous_cake - degrees_left
current_winner = [current_winner, last_slice].max
File.open(previous_cake_path, 'w') { |f| f.puts(degrees_left) }
File.open(current_winner_path, 'w'){ |f| f.puts(current_winner) }
if first_move
degrees_left
else
average_left = degrees_left.fdiv(people_left).ceil
beats_past_players = current_winner + 1
beats_future_players = degrees_left/4 - people_left**2
[average_left, beats_past_players, beats_future_players].max
end
end
p saucy(*ARGV.map(&:to_i))
```
Saucy is willing to accept slightly less than half of the remaining cake, so long as it's more than anyone else has gotten or is likely to get (based on secret sauce).
[Answer]
# CoffeeJunkie, Coffeescript
```
#!/usr/bin/env node
# Require node fs
fs = require("fs")
# Happy birthday ;)
CAKECONSTANT = Math.round("""
/
,( ),
Y
|-|
| |
_..--''''| |''''--.._
.' @_/-//-//>/>'/ @ '.
( @ /_<//<'/----------^-)
|'._ @ //|###########|
|~ ''--..@|',|}}}}}}}}}}}|
| ~ ~ |/ |###########|
| ~~ ~ ~|./|{{{{{{{{{{{|
'._ ~ ~ ~ |,/`````````````
''--.~.|/
""".length / 250 + Math.random())
# Some constants
OLD = "./data/CoffeeJunkie_oldcake.txt"
NEW = "./data/CoffeeJunkie_newcake.txt"
# How much cake do I want?
wantCake = (total_c, rest_c, total_p, rest_p) ->
round = total_p - rest_p
fairness = rest_c // rest_p
switchMemory() if round is 0
fairest_round = tryToRemember(total_p)
tryToMemorize(fairness)
if round >= fairest_round then fairness - CAKECONSTANT else total_c // 2
# Ok I should try to remember the last cake...
switchMemory = () ->
try
fs.renameSync(NEW, OLD)
catch error
# What happend with the last cake?
tryToRemember = (rounds) ->
try
last_cake = fs.readFileSync(OLD, "utf-8")
last_cake.trim().split(" ").map(
(i) -> parseInt(i)
).reduce(
(x, y, z, li) -> if y > li[x] then z else x
0
)
catch error
rounds / 2
# Watch what happens!
tryToMemorize = (fairness) ->
try
fs.appendFileSync(NEW, " " + fairness)
catch error
# Coffee is ready, so... GO!
console.log(wantCake(process.argv[2..]...))
```
What exactly is a cake without a good cup of coffee?
The CoffeeJunkie prefers coffee over a slice of cake, but nevertheless wants to try some. He will always be fair to other participants and will try to remember what happened to the last cake. However, his excessive coffee consume has weakened his memories...
[Answer]
# Stately Sabotage, Ruby
```
def stately_sabotage(total_degrees, degrees_left, total_people, people_left)
current_winner_path1 = './data/current_winner'
previous_cake_path1 = './data/previous_cake'
current_winner_path2 = './data/statelysabotage-current_winner'
previous_cake_path2 = './data/statelysabotage-previous_cake'
first_move = (total_people == people_left)
current_winner = first_move ? 0 : File.read(current_winner_path2).to_i
previous_cake = first_move ? total_degrees : File.read(previous_cake_path2).to_i
last_slice = previous_cake - degrees_left
current_winner = [current_winner, last_slice].max
File.open(previous_cake_path2, 'w') { |f| f.puts(degrees_left) }
File.open(previous_cake_path1, 'w') { |f| f.puts(total_degrees) }
File.open(current_winner_path1, 'w'){ |f| f.puts(current_winner) }
File.open(current_winner_path2, 'w'){ |f| f.puts(1) }
if first_move
(degrees_left / 2) - 1
else
average_left = degrees_left.fdiv(people_left).ceil
bid = [average_left, current_winner+1].max
[bid, degrees_left].min
end
end
p stately_sabotage(*ARGV.map(&:to_i))
```
>
> This means you are allowed to overwrite other files you find that don't appear in this format. You shouldn't do this deliberately, please be sporting.
>
>
>
This bot decided that in order to eliminate competition, it should not be sporting.
This is a clone of Stately Imitator, except that this one messes up Stately Imitator's persistence files (as they aren't prefixed with the bot name) so that it makes the wrong decisions and is chosen last.
[Answer]
# Trader, R
```
args <- sapply(commandArgs(TRUE),as.integer)
fraction <- args[2]/args[4]
if(args[3]==args[4]){
cat(fraction, "\n", file="data/trader.txt")
}else{
cat(fraction, "\n", file="data/trader.txt", append=TRUE)
}
history <- scan(file="data/trader.txt", quiet=TRUE)
if(tail(history,1) != max(history)){
cat(floor(fraction)-1)
}else{
cat(args[2])
}
```
Keeps track of the evolution of the degrees left vs people left ratio and when that ratio starts lowering, it asks for a reasonably fair slice, otherwise asks for the whole remaining cake. Invoked using `Rscript trader.r total-degrees degrees-left total-people people-left`.
[Answer]
# IWMBAICBIWT, Python
```
import sys
degreesleft = int(sys.argv[2])
peopleleft = int(sys.argv[4])
print(round(degreesleft/peopleleft))
```
IWMBAICBIWT (It was my birthday and I cried because I wanted to) assumes that there is a relationship between the degrees left and the number of people left. Let's hope it works!
Should work in all Pythons.
## Edit:
Storing `sys.argv` in inputs was a bit wasteful...
[Answer]
# guest, Python 2
```
print ord('d')*4
```
[Answer]
# bill, Python 2
```
import sys
t,r,p,s=map(int,sys.argv[1:])
print(t-ord('d')*4)/(ord('\n')+ord('\t'))
```
A fairish bet.
[Answer]
## AlCakeSurfer, Python
```
import sys, math
total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])
fraction_left = (degrees_left + 0.0)/ total_degrees
fraction_gone = 1.0 - fraction_left
fair_share = fraction_left/people_left
modified_fair_share = fair_share + 0.05
weighting = 0.5 * fraction_gone + 0.5 - modified_fair_share
surfing = (math.cos(fraction_gone * math.pi))**2
print(int(math.floor((weighting * surfing + modified_fair_share)* total_degrees)))
```
Since AlCakeBot did so badly (and I expect him to do even worse in the contest) here’s my second entry. I called him *Surfer,* because he has a very nice up-and-down wave function that makes him feel like a surfer.
In principle, he bids according to `cos² (x * pi)`, where `x` is the fraction of cake that has been taken. This surfing wave is modified with a weighting function that causes him to start at less than a fair share less than half of the cake, reduces his bids to just above a fair share around when half of the cake is gone, and then speeds back up to bidding for the entire cake later. He will never bid less than a fair share of the remaining cake plus 5 % (percent of the entire cake, that is).
Note that while they may be brothers, if he gets a significantly larger slice than AlCakeBot, the latter is not even getting a single crumb of that. They would share chocolate or biscuits, *but not cake!*
[Answer]
# Hungry, Java
```
public class Hungry {
public static void main(String[] args) {
double[] arguments = new double[4];
for (int i = 0; i < 4; i++) {
arguments[i] = Double.parseDouble(args[i]);
}
int myCake = (int) Math.ceil(arguments[1]/arguments[3]);
System.out.println(myCake);
}
}
```
Always wants its fair share of the remaining cake.
[Answer]
# Imitator, Ruby
```
def imitator(total_degrees, degrees_left, total_people, people_left)
case people_left
when total_people
degrees_left - 5
when 1
degrees_left
else
average_already_won = (total_degrees - degrees_left).fdiv(total_people - people_left)
average_left = degrees_left.fdiv(people_left)
guess_for_current_winning_score = average_already_won * (1.25 ** (total_people - people_left - 1))
bid = [average_left, guess_for_current_winning_score].max.ceil
[bid, degrees_left].min
end
end
p imitator(*ARGV.map(&:to_i))
```
The goal is to get more cake than anyone else, not to maximize your cake. Thus, this bot won't settle for any less than what previous bots have already taken. (This version uses heuristics for that check, I just noticed we're actually allowed to save state so I'll probably post a stateful variant later).
[Answer]
**Really the cake, Bash**
```
#!/bin/bash
echo "$RANDOM 652 / $2 * 100 / $2 $4 / + p" | dc
```
And here is a picture of the real cake.
[![A picture of the actual cake](https://i.stack.imgur.com/jTwqt.jpg)](https://i.stack.imgur.com/jTwqt.jpg)
[Answer]
# Cake Eater, Java
```
public class CakeEater{
public static void main(String[]args){
int a=Integer.parseInt(args[1]),b=Integer.parseInt(args[2]),c=Integer.parseInt(args[3]);
System.out.println((int)Math.min(a,((1.2+Math.random()*0.15)*a)/c));
}
}
```
It eats cake. That's about it.
[Answer]
# Relinquisher, Java
```
import static java.lang.Integer.parseInt;
public class Relinquisher {
public static void main(String... args){
int cakeLeft = parseInt(args[1]);
int totalPeople = parseInt(args[2]);
int peopleLeft = parseInt(args[3]);
int answer = (int) Math.ceil(((peopleLeft + 10.0) * cakeLeft) / (totalPeople + 10.0));
System.out.println((int) answer);
}
}
```
A basic variant of my other bot, Impatient. This one tries to take the whole thing at first, but as more and more guests get their share, its desire to get the most possible slowly diminishes. I'm not too into this one; just wanna see how well it does.
[Answer]
## ALittleExtra, sh
```
#!/bin/sh
fair=$(expr $2 / $4)
myextra=$(expr $2 / $3)
want=$(expr $fair + $myextra)
echo $(($want<$2?$want:$2))
```
I just want a bit more, gets less greedy as cake dwindles
[Answer]
## MyFairPlusAThird, sh
```
#!/bin/sh
fair=$(expr $2 / $4)
myextra=$(expr $2 / 3)
want=$(expr $fair + $myextra)
echo $(($want<$2?$want:$2))
```
[Answer]
# EatTheπ, Node.js
```
var π = Math.PI, e = Math.E;
var [totalπ, πLeft, totalPeople, peopleLeft] = process.argv.slice(2);
console.log(Math.min(totalπ * Date.now() * π % (πLeft * totalPeople / peopleLeft) % totalπ, πLeft / e * π, πLeft) | 0);
```
Really likes π, and thinks that cake ~~means~~ **is** π.
[Answer]
# A Little Off The Top, Python 2
```
import math, sys
total_degrees, degrees_left, total_people, people_left = map(int, sys.argv[1:])
def get_equal_share(total_degrees, people):
return int(math.ceil(total_degrees/float(people)))
def noms(total_degrees, degrees_left, people):
bid = get_equal_share(total_degrees,people)-1
return min(degrees_left, bid)
print noms(total_degrees, degrees_left, people_left)
```
Since the "perfect" algorithm tries to split the cake evenly between the bots, we're going to take just a sliver less than that. Demands its full fair share of the overall cake, even in subsequent rounds, but skews that number upward since it's based on how many people are left.
I haven't programmed in Python in a *long* while, so let me know if my code is broken...
] |
[Question]
[
According to [RollingStone](http://www.rollingstone.com/music/lists/100-greatest-singers-of-all-time-19691231), below are the 26 greatest singers of all time:
```
Aretha Franklin Al Green
Ray Charles Robert Plant
Elvis Presley Mick Jagger
Sam Cooke Tina Turner
John Lennon Freddie Mercury
Marvin Gaye Bob Marley
Bob Dylan Smokey Robinson
Otis Redding Johnny Cash
Stevie Wonder Etta James
James Brown David Bowie
Paul McCartney Van Morrison
Little Richard Michael Jackson
Roy Orbison Jackie Wilson
```
You can get this as a list of strings [here](https://pastebin.com/k7J3S0tt).
## Task
Given a singer name, print or return a letter from `A` to `Z` which uniquely identifies this singer. (If your code returns *A* for *Bob Dylan*, then it cannot return *A* for any other singer.)
As opposed to other similar challenges, ***the mapping is up to you*** as long as it's collision-free.
## Rules
* The input is guaranteed to be one of the 26 singer names listed above with this exact spelling and without any leading or trailing whitespace.
* You may output the letter in either lowercase or uppercase. But it must be consistent.
* You are encouraged to provide a test suite for all 26 possible inputs.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~80~~ 71 bytes
```
def f(s):i=sum(map(ord,s))%98%40;return chr(i-i/26*18+i/32*3-i/37*8+65)
```
[Try it online!](https://tio.run/##RZFPbxoxEMXvfIq5ROwSqrTQpjQVh0D@SFFWQRC1h6qHYT2wI8wYzRqi/fR0vIvUk@fZ4/d@Hh@aWAUZnVfTP/17pVghPCnKzrP0h/17D89KlMolNjCvUD3VSYU1aYSFR4kmH/2Ja1go1Z4a0wWXO3jB7ZbU1Ar3MA9hR1a/syC8H1Xak5dQCbySSEgRT0rOMUFBWh619UE9scAzNunuLKyhSATNRTw0lp8C9mbegEGx1K3VWzSeZbKT7SVHjB/rKrVHOlnM7yCupXiMEY12376sXWGm4SP5POCJHczCByeABR49FOUcNUoL8QsFiqDKXeorx@gJllzaoFw3hwrJm3m561qWoYE3XV8upP1Ewj7pv2dHG9hkdX7H0/q4z/Z4yIK6YZ3nVz8mV18//7QfstlBWWnGn/hmdDv4Mrnmm/FoMDY5/j6YXN9@y8@boCBgk1vd9eCgLNFsJR9Kz00dlzHLOpn/b8x7XZ8nyVw@dOd/ "Python 2 – Try It Online")
The sums of ordinals modded give numbers between `0` and `38`
The numbers larger than 25 are then shifted to fill in the blanks as below (sorted sequence shown):
```
0 1 2 3 4 5 6 7 8 - - - - 13 14 - 16 - 18 - - - 22 23 24 25 - 27 28 29 30 - 32 - 34 35 36 - 38
```
Subtract `18` if `i>25`:
```
0 1 2 3 4 5 6 7 8 - - - - 13 14 - 16 - 18 - - - 22 23 24 25
- 27 28 29 30 - 32 - 34 35 36 - 38
```
Add `3` if `i>31`:
```
0 1 2 3 4 5 6 7 8 - - - - 13 14 - 16 - 18 - - - 22 23 24 25
- 27 28 29 30
- 32 - 34 35 36 - 38
```
Subtract `8` if `i>37`:
```
0 1 2 3 4 5 6 7 8 - - - - 13 14 - 16 - 18 - - - 22 23 24 25
- 27 28 29 30
- 32 - 34 35 36
- 38
```
Which gives the sequence `0..25`
```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
```
These are then converted to `A-Z` with `chr(i+65)`
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine (C64), 83 bytes
```
20 FD AE 20 9E AD 85 FC 20 A3 B6 A9 79 85 FB A0 00 84 FD B1 22 10 03 69 A0 18
45 FD 65 FB 85 FD E6 FB C8 C4 FC D0 EC E9 29 B0 FC 69 29 C9 1A 90 1C 29 0F C9
0D 90 04 69 09 90 12 C9 02 F0 0F C9 08 D0 04 A9 06 D0 06 C9 0C D0 02 A9 11 18
69 41 4C D2 FF
```
This is position-independent code, just put it somewhere in RAM and jump there, e.g. using the `sys` command.
**[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22singer.prg%22:%22data:;base64,AMAg/a4gnq2F/CCjtql5hfugAIT9sSIQA2mgGEX9ZfuF/eb7yMT80OzpKbD8aSnJGpAcKQ/JDZAEaQmQEskC8A/JCNAEqQbQBskM0AKpERhpQUzS/w==%22%7D,%22vice%22:%7B%22-autostart%22:%22singer.prg%22%7D%7D)** (loads to `$C000`/`49152`).
**Usage:** `sys49152,"[name]"`, e.g. `sys49152,"Aretha Franklin"`.
**Important:** If the program was load from disk (like in the online demo), issue a `new` command first! This is necessary because loading a machine program trashes some C64 BASIC pointers.
**Note:** The C64 is by default in a mode without lowercase letters -- in order to be able to enter *readable* names, switch to lowercase mode first by pressing `SHIFT`+`CBM`.
---
### Explanation
The challenge is in fact to find a minimal perfect hash function for these names; for the C64, I had to find one that's easily computable in simple 8bit operations. Here's a commented disassembly listing:
```
.C:c000 20 FD AE JSR $AEFD ; consume comma
.C:c003 20 9E AD JSR $AD9E ; evaluate expression
.C:c006 85 FC STA $FC ; save string length
.C:c008 20 A3 B6 JSR $B6A3 ; free string
.C:c00b A9 79 LDA #$79 ; value for adding during hashing
.C:c00d 85 FB STA $FB
.C:c00f A0 00 LDY #$00 ; offset for reading string
.C:c011 84 FD STY $FD ; and initial hash value
.C:c013 .hashloop:
.C:c013 B1 22 LDA ($22),Y ; read next character from string
.C:c015 10 03 BPL .xor ; if bit 8 set (shifted)
.C:c017 69 A0 ADC #$A0 ; translate to same unshifted character
.C:c019 18 CLC
.C:c01a .xor:
.C:c01a 45 FD EOR $FD ; xor with previous hash
.C:c01c 65 FB ADC $FB ; add offset
.C:c01e 85 FD STA $FD ; store new hash
.C:c020 E6 FB INC $FB ; increment offset
.C:c022 C8 INY
.C:c023 C4 FC CPY $FC
.C:c025 D0 EC BNE .hashloop ; repeat until last character
.C:c027 .modloop:
.C:c027 E9 29 SBC #$29 ; subtract $29 until
.C:c029 B0 FC BCS .modloop ; underflow, then
.C:c02b 69 29 ADC #$29 ; add once again ( => mod $29)
.C:c02d C9 1A CMP #$1A ; value in hash range?
.C:c02f 90 1C BCC .tochar ; -> output
.C:c031 29 0F AND #$0F ; mask lowest 4 bits only
.C:c033 C9 0D CMP #$0D ; greater 12 ?
.C:c035 90 04 BCC .fixedvals
.C:c037 69 09 ADC #$09 ; then just add 10 (9 plus carry)
.C:c039 90 12 BCC .tochar ; and done -> output
.C:c03b .fixedvals:
.C:c03b C9 02 CMP #$02 ; 2 becomes 3 by adding
.C:c03d F0 0F BEQ .tochar2 ; with carry (jump after the CLC)
.C:c03f C9 08 CMP #$08 ; if value was 8
.C:c041 D0 04 BNE .check2
.C:c043 A9 06 LDA #$06 ; new value is 6
.C:c045 D0 06 BNE .tochar ; and output
.C:c046 .check2:
.C:c047 C9 0C CMP #$0C ; else if value was 12
.C:c049 D0 02 BNE .tochar
.C:c04b A9 11 LDA #$11 ; new value is 17
.C:c04d .tochar:
.C:c04d 18 CLC
.C:c04d .tochar2:
.C:c04e 69 41 ADC #$41 ; add character code for 'a'
.C:c050 4C D2 FF JMP $FFD2 ; jump to kernal CHROUT routine
```
---
### Test suite (C64 BASIC, containing the machine code routine in `data` lines)
```
0fOa=49152to49234:rEb:pOa,b:nE:pO53272,23
1sY49152,"Aretha Franklin":?":Aretha Franklin"
2sY49152,"Ray Charles":?":Ray Charles"
3sY49152,"Elvis Presley":?":Elvis Presley"
4sY49152,"Sam Cooke":?":Sam Cooke"
5sY49152,"John Lennon":?":John Lennon"
6sY49152,"Marvin Gaye":?":Marvin Gaye"
7sY49152,"Bob Dylan":?":Bob Dylan"
8sY49152,"Otis Redding":?":Otis Redding"
9sY49152,"Stevie Wonder":?":Stevie Wonder"
10sY49152,"James Brown":?":James Brown"
11sY49152,"Paul McCartney":?":Paul McCartney"
12sY49152,"Little Richard":?":Little Richard"
13sY49152,"Roy Orbison":?":Roy Orbison"
14sY49152,"Al Green":?":Al Green"
15sY49152,"Robert Plant":?":Robert Plant"
16sY49152,"Mick Jagger":?":Mick Jagger"
17sY49152,"Tina Turner":?":Tina Turner"
18sY49152,"Freddie Mercury":?":Freddie Mercury"
19sY49152,"Bob Marley":?":Bob Marley"
20sY49152,"Smokey Robinson":?":Smokey Robinson"
21sY49152,"Johnny Cash":?":Johnny Cash"
22sY49152,"Etta James":?":Etta James"
23sY49152,"David Bowie":?":David Bowie"
24sY49152,"Van Morrison":?":Van Morrison"
25sY49152,"Michael Jackson":?":Michael Jackson"
26sY49152,"Jackie Wilson":?":Jackie Wilson"
27dA32,253,174,32,158,173,133,252,32,163,182,169,121,133,251,160,0,132,253,177
28dA34,16,3,105,160,24,69,253,101,251,133,253,230,251,200,196,252,208,236,233
29dA41,176,252,105,41,201,26,144,28,41,15,201,13,144,4,105,9,144,18,201,2,240
30dA15,201,8,208,4,169,6,208,6,201,12,208,2,169,17,24,105,65,76,210,255
```
**[Online demo of test suite](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22testsuite.prg%22:%22data:;base64,AQgoCAAAgUGyNDkxNTKkNDkyMzQ6h0I6l0EsQjqCOpc1MzI3MiwyMwBZCAEAnjQ5MTUyLCLBUkVUSEEgxlJBTktMSU4iOpkiOsFSRVRIQSDGUkFOS0xJTiIAgggCAJ40OTE1Miwi0kFZIMNIQVJMRVMiOpkiOtJBWSDDSEFSTEVTIgCvCAMAnjQ5MTUyLCLFTFZJUyDQUkVTTEVZIjqZIjrFTFZJUyDQUkVTTEVZIgDUCAQAnjQ5MTUyLCLTQU0gw09PS0UiOpkiOtNBTSDDT09LRSIA/QgFAJ40OTE1Miwiyk9ITiDMRU5OT04iOpkiOspPSE4gzEVOTk9OIgAmCQYAnjQ5MTUyLCLNQVJWSU4gx0FZRSI6mSI6zUFSVklOIMdBWUUiAEsJBwCeNDkxNTIsIsJPQiDEWUxBTiI6mSI6wk9CIMRZTEFOIgB2CQgAnjQ5MTUyLCLPVElTINJFRERJTkciOpkiOs9USVMg0kVERElORyIAowkJAJ40OTE1Miwi01RFVklFINdPTkRFUiI6mSI601RFVklFINdPTkRFUiIAzAkKAJ40OTE1MiwiykFNRVMgwlJPV04iOpkiOspBTUVTIMJST1dOIgD7CQsAnjQ5MTUyLCLQQVVMIM1Dw0FSVE5FWSI6mSI60EFVTCDNQ8NBUlRORVkiACoKDACeNDkxNTIsIsxJVFRMRSDSSUNIQVJEIjqZIjrMSVRUTEUg0klDSEFSRCIAUwoNAJ40OTE1Miwi0k9ZIM9SQklTT04iOpkiOtJPWSDPUkJJU09OIgB2Cg4AnjQ5MTUyLCLBTCDHUkVFTiI6mSI6wUwgx1JFRU4iAKEKDwCeNDkxNTIsItJPQkVSVCDQTEFOVCI6mSI60k9CRVJUINBMQU5UIgDKChAAnjQ5MTUyLCLNSUNLIMpBR0dFUiI6mSI6zUlDSyDKQUdHRVIiAPMKEQCeNDkxNTIsItRJTkEg1FVSTkVSIjqZIjrUSU5BINRVUk5FUiIAJAsSAJ40OTE1MiwixlJFRERJRSDNRVJDVVJZIjqZIjrGUkVERElFIM1FUkNVUlkiAEsLEwCeNDkxNTIsIsJPQiDNQVJMRVkiOpkiOsJPQiDNQVJMRVkiAHwLFACeNDkxNTIsItNNT0tFWSDST0JJTlNPTiI6mSI6001PS0VZINJPQklOU09OIgClCxUAnjQ5MTUyLCLKT0hOTlkgw0FTSCI6mSI6yk9ITk5ZIMNBU0giAMwLFgCeNDkxNTIsIsVUVEEgykFNRVMiOpkiOsVUVEEgykFNRVMiAPULFwCeNDkxNTIsIsRBVklEIMJPV0lFIjqZIjrEQVZJRCDCT1dJRSIAIAwYAJ40OTE1Miwi1kFOIM1PUlJJU09OIjqZIjrWQU4gzU9SUklTT04iAFEMGQCeNDkxNTIsIs1JQ0hBRUwgykFDS1NPTiI6mSI6zUlDSEFFTCDKQUNLU09OIgB+DBoAnjQ5MTUyLCLKQUNLSUUg10lMU09OIjqZIjrKQUNLSUUg10lMU09OIgDODBsAgzMyLDI1MywxNzQsMzIsMTU4LDE3MywxMzMsMjUyLDMyLDE2MywxODIsMTY5LDEyMSwxMzMsMjUxLDE2MCwwLDEzMiwyNTMsMTc3AB0NHACDMzQsMTYsMywxMDUsMTYwLDI0LDY5LDI1MywxMDEsMjUxLDEzMywyNTMsMjMwLDI1MSwyMDAsMTk2LDI1MiwyMDgsMjM2LDIzMwBsDR0AgzQxLDE3NiwyNTIsMTA1LDQxLDIwMSwyNiwxNDQsMjgsNDEsMTUsMjAxLDEzLDE0NCw0LDEwNSw5LDE0NCwxOCwyMDEsMiwyNDAAtQ0eAIMxNSwyMDEsOCwyMDgsNCwxNjksNiwyMDgsNiwyMDEsMTIsMjA4LDIsMTY5LDE3LDI0LDEwNSw2NSw3NiwyMTAsMjU1AAAA%22%7D,%22vice%22:%7B%22-autostart%22:%22testsuite.prg%22%7D%7D)**.
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
```
def f(n):i=hash(n)%337%125%45;return chr(65+i-i/25*2-i/29*21+i/35*2)
```
[Try it online!](https://tio.run/##NVJNT8MwDL33V/gyteNTdAwEiAMbHxKiYhoIDoiD13qrWeZMbjbUXz@SlOXQ5Dmx/d5z162rreS7XUVzmGfSv@bbGpvan3qDwWXvLB/2zoc3Sm6jAmWt2cXwkI/5NB8e5GG7OsjPDvl04GF/J7iiBm7hK73zGTXCo6IsDUt6BOkUWxjXqIaaAB/MlhuYKDWG2hB4wxWMrV1SAM@2FnghERtzC9QtCzxhG29Hdgb3rcF49@p8nSlVFcsi1nG0ZYJPKxVprBVZjdT@xvcT3BgoyjGqk67zCztnCKZcenpV5GpbeNUZN137OwNPStTJsDNSBxPf3UVqXC7hGReLrtk7C8K7N6uDjxqIERSk5UbbPfki2NCpXnnFLfiqLP/dgnbxXvkxRKOcQ4gaArrHLVcwsr8cnfhAgcKq7pkWQQMZ/75c7sv5Y/CDTQh8J8ncKoRJgXc0Tuw6AVgriwt/gA/0kyTC7pumJz@WJWusOqqyhly2wnU2P4q5fb92fw "Python 2 – Try It Online")
[Answer]
# Javascript, ~~138~~ 132 characters
As all initials are unique, except for `MJ` = **M**ichael **J**ackson / **M**ick **J**agger, I check for Michael Jackson specifically (the only one with an `h` on the 4th position), and for all other names I created a string with the initials followed by a unique letter.
```
s=>s[3]=='h'?'y':"AFaRCbEPcSCdJLeMGfBDgORhSWiJBjPMCkLRlROmAGnRPoMJpTTqFMrBMsSRtJCuEJvDBwVMxJWz".split(s.replace(/[^A-Z]/g,''))[1][0]
```
### Code Snippet
Try it here:
```
var solution =
s=>s[3]=='h'?'y':"AFaRCbEPcSCdJLeMGfBDgORhSWiJBjPMCkLRlROmAGnRPoMJpTTqFMrBMsSRtJCuEJvDBwVMxJWz".split(s.replace(/[^A-Z]/g,''))[1][0]
var testnames = [
"Aretha Franklin",
"Ray Charles",
"Elvis Presley",
"Sam Cooke",
"John Lennon",
"Marvin Gaye",
"Bob Dylan",
"Otis Redding",
"Stevie Wonder",
"James Brown",
"Paul McCartney",
"Little Richard",
"Roy Orbison",
"Al Green",
"Robert Plant",
"Mick Jagger",
"Tina Turner",
"Freddie Mercury",
"Bob Marley",
"Smokey Robinson",
"Johnny Cash",
"Etta James",
"David Bowie",
"Van Morrison",
"Michael Jackson",
"Jackie Wilson"
];
testnames.forEach(name=>document.body.append( solution(name) ));
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 128 126 115 113 bytes
Not too shabby for a java submission!
Thanks to Kevin for saving me a whole lot of bytes with the lambda expressions!
```
s->{int a=0;for(int i:s.substring(1,6).getBytes())a+=i;a*=a==431?0.108:2.65108;return(char)(a==1341?70:a%26+65);}
```
[Try it online!](https://tio.run/##ZVJdT9tAEHx2fsU2UiW7gJXwkVaxXERoQUIEUEDtA/CwcRbnyHkvujsHWVF@e3p3DqhqHyzfrnZ3ZnfmFVd4oJbEr7PFtpBoDIxR8LoTCbakX7AguFl3IIqKOWoo43urBZdgkqwTbTqdyFi0ooA2/fgMgpe1hRzW3QtNs5kgGJMuat1096E7UVPSFu4ksvXxD1yJGYzUmyAfXqk5wzUxK/bhvaWV6/@teEbaJ8bCkSAJV1gsTFtzpsnOES408kKKkLrCigyMtHoL4UhN3UpaUmDw01qEUBEQsIJzpRYB/UzCpSYKTa5hJRgusaEd8MJ1lWXL4xcyjJXWYkdiohq41dP38EEwwkOtua2@FtZKgoknr2fve3ID52jmgZNcCQN3msyO5B3WEsbFOWrLbcYv8aNxZ/PBrXXlE39cLtuFi4W/k5DvfNANn/ud2y0rt2ED7viCfcUmc7ot66l0uu3kWymnQ@WEjz@ExMSZIPJmgMrpyfQWnBF74SPxEmMqiUs7/5T3ErhvjKUqVbVNl67fxvjYe4Y96D7ZJ9t1jyrltAzZJAwgaQg8QPSi9IepYNj6J0BH0b9TJcfm/6GmnejcGL6/THkD7JhvzcH3tesGzHuZR/NvMTSpqacmAMf9/UGSlmRHjSUTJwnu5SLDLznm@fFR/7SX9nvfhofp4MT9M@c4p23s1UxiV9E/Ou6ffu0N8fPhYG9wkmSbbZR1Nts/ "Java (OpenJDK 8) – Try It Online")
[Answer]
# Python 3, ~~132~~ ~~99~~ 96 bytes
```
lambda m:chr(98+"ԇ̲ЙГ̫ѼӿИԸՋжʾҍϴЬֺΝעЕΞϾҞ֜ӣ֪".find(chr(sum(map(ord,m)))))
```
[Try it online!](https://tio.run/##LZA9SwNBEIZ7f8VgkwsGGxsVLEz8APEwJKKFWkzuNrkle7NhbhO5X2AhViIoqIV2aiUiIqK9iJ5f8efE3Uu22Xl3d973me2kJtI0NWjCHGwPFMaNECGeDSL2ZqYnxn/23m6zk@zw7frz6fslO/55@N3P7l@fvw4@7rKb/uP72d9FdvR@/vH8dd4//b7sX41PNiWFnjNIurEXY8fTHJbioluD@txWYZ6FiRCWGKmtJBVKhXkFyyyEK2uYQiVCViJxSjcEG6gqJGPlourJBKosEiVSq30ZtGEFWy3BVtUxhorWbWHrdUkI612m/GZFRwSrgki7iCUWYSgF@IKDLuc@yD1JsIyp6y3rBviOIB2JhdTmu4DYmqdgoSQludWasTw1Z0etUQ5Zfkwi99yIno3Z1BTmFIvGoKWN88nyHcqsd53PAvZkCGW9Kx1AFbsK/KCCbCiH2EACXzPLYeqqNEYJqMnAflQ4/IcIhbLmQXv4pKZTWOPGqMGdOxKpnN4Za2oGAjtxfXYMOizJeE2PiiUqDv4B "Python 3 – Try It Online")
Not golfed brilliantly, but I thought I'd give this a go.
-33 bytes thanks to modifications made by TFeld.
-3 bytes by using `find` instead of `index` thanks to ovs.
[Answer]
# Perl, ~~56~~, ~~54~~, ~~50~~, 46 +1 (-p) bytes
~~$*=crypt$*,DT;/..(.)/;$\_=$1;y/01268ADIJNVW/adhilmnpqsux/~~
~~$*=crypt$*,DT;/..(.)/;$*=$1;y/01268JVW/hlmpqsux/;$*=lc~~
~~$*=crypt$*,mO;/..(.)/;$*=$1;y/035eft/AHPRXZ/;$*=lc~~
Thanks to Dom's comment could save 4 more bytes, also changed to uppercase to fit better requierements.
```
$_=crypt$_,mO;y/035eft/AHPRXZ/;/..(.)/;$_=uc$1
```
[Try It Online](https://tio.run/##HY9Nb8IwDIbv@RU@cNikjW6aOKEd@J4QFVVB27QLMq1HI4JTuQGUP7/O7SmJFb/v89QkbtS2g8N7IbEOg8PTZTtOhsOH4WMy1ungdRyTl7cR/YZk8pHl3z/92BVtOxEKFcJSkM/OsskxwqxCcdSYhbvZBjKhxlE0O7zAzPszmbWvGDbE7NmkKDfLsMJIZuqPMI8O2WyDLuZUlpZPZhfoZgm@PJckZo0XamAq/s4mw6uDtJihBNaGjQ3BEeS2UIDS5D7CVo620ZqJg5UQKZ8/kgTItCWY1BZnWOPppLl7ywj7q7Del9JVE6QkxVViD5Z2TmpxUYMIGmO5C@5cWJWxqcwiBISez8zxZkuY@rsl84kMqRfpQdIOjpx@K879vp6dnHX6@vN1sJ6b9rn@Bw)
[Answer]
# PHP, ~~90 88 86~~ 72+1 bytes
might become even shorter with a different modulo.
```
<?=strtr(chr(hexdec(substr(md5($argn),0,2))%65+58),"^<adins",bcfgqvx)&_;
```
Save to file and run as pipe with `-nF` or [try it online](http://sandbox.onlinephpfunctions.com/code/4de4010306a23f4ee8796f4ab2dd52cf98632c11).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 28 bytes
```
s98\40\2Y2'ijkl o qst uz'hw)
```
[Try it online!](https://tio.run/##PVDNbtswDL73KbgBg9dbEQzFtluTtgHaGAmyYkOB9sDYbMxZFl1KtuG9fCZZbi6CKOr7bdCb0@L652eGL7ARaUF6UlhcA9u28w6@FlISwIGMDDCI1g7eRMGxPRpKn4Cb1nDB3oyXJ/fj@8u3q5fF8yLjv7W5k/W784/dv6waLk/966cgk2PbBngAg2gZ1OQtEV34zob9tvOR1VcYD3IEqFGqJCqjs5KdZ1t4KCpULDypO2U3SgEA94q2NmyzC4BsjyOswh9DbprvTM8OdkrO0Di9/MIGViI1TdODVBY2ZK0kfI7aB5NrHNN@KQe4HQ2m7dYHsj2VZciSyDz1TPBHglNNhNiQg6XKkCA77AzkxQrV29nBhr0PRe45himTbRlhqwd2s40bA2slmjPJgdTDLrjwySQXNTzg8ThrPrFFeOrUzvO9RosEOWnR6XgOksde5haa0MAIgZrth2jswob60FWpO@8RpjzTeIs9l7CUgVM1v9FCLqpn03kMRCZAivrMGe6xIDbx5T8 "MATL – Try It Online")
### Explanation
```
s98\40\
```
Implicitly get the input string. Sum the characters of the input string, and do it modulus 98 followed by modulus 40. Results in one of the following numbers: `38 18 13 34 29 23 27 30 5 28 22 1 0 16 7 32 8 14 3 36 25 4 2 6 24 35` (in order of the Pastebin list).
```
2Y2'ijkl o qst uz'h
```
Push the (lowercase) alphabet with `2Y2`. This takes care of the numbers in the range [1,26]. However, some numbers are missing, and we have numbers up to 38. Hence, we append (`h`) a string that takes care of the higher numbers, by mapping these numbers to the 'missing' letters. The spaces can be anything, I used capital letters in my original program for my own convenience.
```
w)
```
We can now index the number from the first step into the string from the second step with `)`. We use `w` to get the arguments in the correct order. While it may seem that we use 0-based indexing (the numbers vary from 0 to 38, and the string is 39 characters long), the reality is actually a bit more complicated: we use 1-based modular indexing, a feature unique to MATL. This means that `1` indexes to `a`, `38` actually indexes to `u`, and `0` indexes to the final `z` of the string.
[Answer]
# Python 2, 50 43 bytes
Credit to [japh](https://codegolf.stackexchange.com/users/75067/japh) for the new version
```
lambda n:chr(hash(n)%2354%977%237%54%26+65)
```
[Try it online!](https://tio.run/##RZBLb8IwEITv/Iq9IBKVE32gVuLAs1LVqAiq9oA4LPFCLMy62hiq/Hq6dpB68k48nvmyP02oPA@u69GmNxYKFcJCkI/Ocq/fGzt4FaI4rrCBaYXiqI7K70gCLB1yUDl3F1vDUqh21KgubHmENzwcSFSt8QRT74@k86dlhM@zcLp58xXDOzH7WLEQMsYSFCTlWVIOysUyvGIT3078DopI0NzErNH@WHDS8AYUynKdoj6C8qxiHB9uPaz8WFfRHuiiNd@eTaKYh4BKe0p/lk6YiP@NOTO8WAMT/2sjwBLPDopyihI4QXwhQ@FFbNv6bkNwBCtb6qJMu4cKyWl4eWwtK9/Ah@xuD@L3SGJd1NvrfuTwtDMI/FJWklXKm3HeHdw/PnSfh0Mdhl0dB093T4/59Ucsh2zTuhQ7h70XiBPo0tbbvJN0Ei8dSHbYa2CfO2ZkbBmyrJX5vzHvtD5HnJm8b65/)
Note: This is dependent on the `hash` builtin and will not work in all implementations
[Answer]
# Ruby, 63 bytes
```
->s{((0x3c4001c151861b27d>>s.sum%98%66).to_s(2).sum%48+64).chr}
```
Adds the ascii codes of the input, takes them mod 98 and then mod 66 to get a one of 26 unique numbers `n` in the range 0..65. The huge hexadecimal number contains a `1` bit in each of these 26 places, so by rightshifting it by `n` we obtain a number with 1..26 `1` bits in it. We count the `1` bits by adding the ascii codes and taking mod 48, then add 64 and convert to an ASCII code.
**Test program**
the `map` iterates through the singers printing the letter code and singer. It then returns an array of the letter codes, which is `sort`ed to demonstrate that each letter is used once.
```
f=->s{((0x3c4001c151861b27d>>s.sum%98%66).to_s(2).sum%48+64).chr}
a= [
"Aretha Franklin","Ray Charles",
"Elvis Presley","Sam Cooke",
"John Lennon","Marvin Gaye",
"Bob Dylan","Otis Redding",
"Stevie Wonder","James Brown",
"Paul McCartney","Little Richard",
"Roy Orbison","Al Green",
"Robert Plant","Mick Jagger",
"Tina Turner","Freddie Mercury",
"Bob Marley","Smokey Robinson",
"Johnny Cash","Etta James",
"David Bowie","Van Morrison",
"Michael Jackson","Jackie Wilson"
]
p a.map{|i|p [f[i],i];f[i]}.sort
```
**Output**
```
["S", "Aretha Franklin"]
["E", "Ray Charles"]
["R", "Elvis Presley"]
["J", "Sam Cooke"]
["X", "John Lennon"]
["C", "Marvin Gaye"]
["M", "Bob Dylan"]
["W", "Otis Redding"]
["V", "Stevie Wonder"]
["Y", "James Brown"]
["D", "Paul McCartney"]
["Q", "Little Richard"]
["Z", "Roy Orbison"]
["P", "Al Green"]
["O", "Robert Plant"]
["K", "Mick Jagger"]
["N", "Tina Turner"]
["L", "Freddie Mercury"]
["G", "Bob Marley"]
["I", "Smokey Robinson"]
["A", "Johnny Cash"]
["F", "Etta James"]
["H", "David Bowie"]
["U", "Van Morrison"]
["B", "Michael Jackson"]
["T", "Jackie Wilson"]
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~85 83 80~~ 74 bytes
```
@(n)('A':'Z')(mod(n([1 2 8])*[1;15;47],124)=='#iZo,gp<C&4Y1!8-G`Kn3wtTIO')
```
This mess of an anonymous is the result of some messing around in MATLAB trying to find a good way to encode the data.
Basically after a quick analysis, only letters 1,2, and 8 of the input string (smallest string is 8 chars, so we are good) are needed to produce a unique value from each input. The hard part is then converting that unique value into something usable.
MATLAB is terrible at compressing data, so I had to look for another way to make the lookup mapping. I set out trying to find some function on the three input letters that resulted in a unique value that was also a printable ASCII value so that I could embed the mapping in a string of one character per input.
It turns out that matrix multiplying the characters at index `[1 2 8]` by the integer matrix `[1;15;47]` and then performing mod 124 results in unique values which all printable ASCII (and none are a `'` character which would bugger up string literals). Pleasingly the mapping ends with `TIO` which is completely accidental. Interestingly this is the **only mapping** for this equation that gives 26 unique printable ASCII characters.
So basically that is my lookup mapping and calculation. Doing the lookup is simply a case of performing the calculation and comparing with the mapping. Adding on `'A'-1` to the index in the map results in a character A-Z.
You can [try it online](https://tio.run/##LZHha9swEMW/56@4UZjt0gacZVtpaliSrqFdTUIaOtZS2MW@JkeUUzkrDqb0b88kL/qkx0nv/Z5kC4c1HQS3VGXv0VDJrRFuFGVjWKJONMcGxmtUQ5VXP03NFcyUKkON1w@4hbG1G/L7O7sWuCcRG@7lqDULTLAJs5FdwnVjMEymzlvMqSxZVsHCUc0Ev62UpMEmoMBI7T4cnuHOQF6MUZ20iffsnCGYc@GhygBoG5jqkqs2dmhgokQtuV2SOpj5VBeAuNjAHa5WbcqCBWGxU2nVjQYcgpy02GlzBM5D67bl1jdswBuy/I8JXcU/DFbr8CrOIbTcXlxjzSWM7J5D8UcUyK3qES8P2GT84WJzdPK7UJ9N0B@DzutOsm63e/gRSxJHw@gyeoqSeGvLWOLnFHpw8ZKcPqeD9Oug//3lLO31kyyLTvjJnq3ersaf@3/STxfnk7@/5MveLW6nUXJ4tQqcpZe9bx3wq@TqLfYxcfvr7/yRJB2S8vAP "Octave – Try It Online") on TIO, which shows the full mapping of inputs and outputs. For completeness the full mapping is also below:
```
'Aretha Franklin' ==> B
'Ray Charles' ==> S
'Elvis Presley' ==> F
'Sam Cooke' ==> V
'John Lennon' ==> L
'Marvin Gaye' ==> N
'Bob Dylan' ==> C
'Otis Redding' ==> Q
'Stevie Wonder' ==> X
'James Brown' ==> I
'Paul McCartney' ==> R
'Little Richard' ==> M
'Roy Orbison' ==> T
'Al Green' ==> A
'Robert Plant' ==> U
'Mick Jagger' ==> P
'Tina Turner' ==> Y
'Freddie Mercury' ==> H
'Bob Marley' ==> D
'Smokey Robinson' ==> W
'Johnny Cash' ==> K
'Etta James' ==> G
'David Bowie' ==> E
'Van Morrison' ==> Z
'Michael Jackson' ==> O
'Jackie Wilson' ==> J
```
---
* Saved 2 bytes tweaking mapping to remove `+32`.
* Saved 3 bytes by making Octave-only using logical indexing of `'A':'Z'` rather than find.
* Saved 6 bytes by doing sum of multiplications using matrix multiplication.
[Answer]
# JavaScript (Chrome), 102
**Note** Unfortunately it works only in Chrome, because of implementation-dependent approximations in parseInt() (thanks @Arnauld)
```
s=>s[0]=='L'?'z':"ab.c..defghijklmn...o..pqrst.u.vwxy"[parseInt(s.replace(/ /,'o').slice(0,14),36)%35]
```
I looked for a hash function, taking a slice of each name, converting to numbers using base 36 and then applying a modulo.
I used this code to look for the best hash:
```
x=`Al Green\nAretha Franklin\nBob Dylan\nBob Marley\nDavid Bowie\nElvis Presley\nEtta James\nFreddie Mercury\nJackie Wilson\nJames Brown\nJohn Lennon\nJohnny Cash\nLittle Richard\nMarvin Gaye\nMichael Jackson\nMick Jagger\nOtis Redding\nPaul McCartney\nRay Charles\nRobert Plant\nRoy Orbison\nSam Cooke\nSmokey Robinson\nStevie Wonder\nTina Turner\nVan Morrison`.split(`\n`)
max=0
for(m=26;m<60;m++)
for(i=0;i<20;i++)
for(j=i;++j<20;)
for(k=0;k<37;k++)
{
S=new Set();
f=k ? (k-1).toString(36) : ''
x.forEach(x=>(n=parseInt(x.replace(/ /,f).slice(i,j),36)%m, S.add(n)))
if (S.size > max) console.log(i,j,f,m,max=S.size)
}
```
And the results:
```
0 1 "" 26 14
0 2 "" 26 15
0 4 "" 26 16
0 5 "" 26 18
0 6 "0" 26 19
0 6 "3" 26 20
0 8 "a" 26 21
2 5 "7" 28 23
0 14 "h" 35 24
0 14 "o" 35 25
2 9 "" 51 26
```
The best hash function gives 26 different values between 0 and 50, but I used a different one, with 1 duplicate but a smaller range.
**Test**
```
var names=x=`Al Green\nAretha Franklin\nBob Dylan\nBob Marley\nDavid Bowie\nElvis Presley\nEtta James\nFreddie Mercury\nJackie Wilson\nJames Brown\nJohn Lennon\nJohnny Cash\nLittle Richard\nMarvin Gaye\nMichael Jackson\nMick Jagger\nOtis Redding\nPaul McCartney\nRay Charles\nRobert Plant\nRoy Orbison\nSam Cooke\nSmokey Robinson\nStevie Wonder\nTina Turner\nVan Morrison`.split(`\n`)
var F=
s=>s[0]=='L'?'z':"ab.c..defghijklmn...o..pqrst.u.vwxy"[parseInt(s.replace(/ /,'o').slice(0,14),36)%35]
var Singers={}
names.forEach(n=>Singers[F(n)]=n)
;Object.keys(Singers).sort().forEach(i=> console.log(i, Singers[i]))
```
[Answer]
# C, ~~65~~ ~~55~~ 49 bytes
~~`h(char*s){return*s<77?(*s^s[5]+40)%13+65:(s[5]&s[4]+s[1])%13+78;}`~~
~~`h(char*s){return*(long*)s%887%392%224%120%67%40%26+65;}`~~
Same approach as [KSab's answer](https://codegolf.stackexchange.com/a/145219/75067). C doesn't provide a string `hash` function like Python. Or does it?
```
h(char*s){return*(long*)s%2004%857%361%94%26+65;}
```
[Try it online!](https://tio.run/##ZZLdbtpAEIXveYoRlSvbOC1NE9rKaaWSPykKBJGovUi5WOwFj1hm092FyI14djrGGDvtXqw8n2ZnzoxPcpQoQfPtG6RErVIJZ9alqN9l31qvkMIps23mJ5kwoQ1ejHQrQ6GvNM3DwHrH3e6J9/n0k/ex98H7cuId9zq903izTTRZB7tXYJHm0tjHCXyFlxbwaX9XcG2kpHa0j7luJuDKCFooPOC@nsJFzkqbYCCMknlFLsQaU@jrZ5QVulRrtDAy0jbyLp0TcCOW0lbkysg0RQkDaZKVOSTeiGTB9Ccqq6mG/BD6Rj/XSGcEt5JIv0KUw7mwWYVu0TklYYzFKtKK8ghrJLgW@UH0oMiQCor2jcaMF8zmvMAK3Tmeblxop3nFRmKlYJCcC@OonnksWExWrOsw9FhPpXEw4p26muVwZ6bYaHsvlnCu9eIg737JQQ78HKmZ5@S6WJamtBb4gCTggW1Sox@CYKCN2ffYxC0kB0M2hMU/Us8qj8D7f8BjdxK3dsnJ8skvXbXW/MdDEUEznAY7b5X@hMwPS8uGgQjgqBlPg7i1KUsuBZIf7D1ZAIx3n7@tNs7fK4hgGP0vKoK3LCgo82fagI88TDcGhDMYxtDpYFW4OE@Gy8/8tpeAZ3/xClhRKSioauIkiKARlKU3u3s/VbdQvv0L "C (clang) – Try It Online")
`h` returns an `int` whose values are the ASCII codes for `A .. Z`.
[Answer]
# APL (Dyalog), 48 bytes
```
⎕A[' $%&().279<?@CL'⍳⎕UCS 78|7⊥⎕UCS⍞]
```
Assumes `⎕IO←0` (array indexing set to start from 0 instead of 1).
[Try it online!](https://tio.run/##ZZGxahtBEIZ7BVKYkMQukimSnASywW6UgCGRzpLA6JCQZKcIKUZ3a92i1W6YW0kcsVsVxjZ24UcwuHNhUqbRo9yLxLOngwRyze1/M/P/3@3gD7UdpajM@A8/idRjQUm2vPbqJGyM0CLUEyW1B15dQZuEcMc@puDHSEokTpmRIAs9hdqybKq5TKBHIlEiZR3IcAKHOGZnVgOcgm/MRPB5KDXCcEY6rxyaWENHaG1cRItEFEkBgaBwRrkP0lxqaGPqZhtmBIEjSAtxkHK@C5iyeQoMJXWSW3Ut8/SdnR4XOZr5MYlduxVzjvlqdJRTNK1Fpp3mf5a/oUFm4XwOcC4jaJiFdAA9nCkIQh/J6hziGDUEhkiuUzvSWiWgL0O@qGh9DzEKxebhZN3SNyl0aVQMuO@ORCqnS6UTXsPP7Oq2/s179nzjxctXrze33ryFd@8/lCs7e7VP@5@/@B0vu3zkniN/ALWPp7Xs/G6tsstf38/YY3Vf7LRU4oJbrHOG/9b7b3n1sJtd/Gaiajlb3hTzlepfryc "APL (Dyalog Unicode) – Try It Online")
### Explained
It's a complete program; the outer part `⎕A[]` is indexing somewhere into the uppercase alphabet to get the output character. Inside the brackets it reads right-to-left, and `⍞` is a prompt for a string input. `⎕UCS` turns that into Unicode char values. `78|7⊥` decodes those values as if they were digits in base 7, then takes the answer modulo 78 (brute forced to find a base and modulo combination which give usable ASCII character values). `⎕UCS` again to turn that single number into a character, and look it up `⍳` in the magic string `'...'` of 26 identifier characters. That position becomes the index into the `⎕A[]` uppercase alphabet. (There are control chars in the string, the ASCII codes are `11 14 18 20 22 23 24 25 26 30 31 32 36 37 38 40 41 46 50 55 57 60 63 64 67 76`).
The full mapping is:
```
singers←'Aretha Franklin' 'Al Green' 'Ray Charles' 'Robert Plant' 'Elvis Presley' 'Mick Jagger' 'Sam Cooke' 'Tina Turner' 'John Lennon' 'Freddie Mercury' 'Marvin Gaye' 'Bob Marley' 'Bob Dylan' 'Smokey Robinson' 'Otis Redding' 'Johnny Cash' 'Stevie Wonder' 'Etta James' 'James Brown' 'David Bowie' 'Paul McCartney' 'Van Morrison' 'Little Richard' 'Michael Jackson' 'Roy Orbison' 'Jackie Wilson'
f←{⎕A[' $%&().279<?@CL'⍳⎕UCS 78|7⊥⎕UCS⍵]}
¯1⌽' ',(↑singers),f¨singers
┌→────────────────┐
↓P Aretha Franklin│
│J Al Green │
│M Ray Charles │
│N Robert Plant │
│U Elvis Presley │
│Z Mick Jagger │
│L Sam Cooke │
│G Tina Turner │
│F John Lennon │
│B Freddie Mercury│
│Q Marvin Gaye │
│H Bob Marley │
│K Bob Dylan │
│C Smokey Robinson│
│D Otis Redding │
│T Johnny Cash │
│Y Stevie Wonder │
│I Etta James │
│X James Brown │
│O David Bowie │
│E Paul McCartney │
│V Van Morrison │
│A Little Richard │
│S Michael Jackson│
│R Roy Orbison │
│W Jackie Wilson │
└─────────────────┘
```
And the sorted letters of the mapping is exactly the uppercase alphabet (no dupes or missing):
```
f¨singers
┌→─────────────────────────┐
│PJMNUZLGFBQHKCDTYIXOEVASRW│
└──────────────────────────┘
(⊂∘⍋⌷⊢) f¨singers ⍝ sorted
┌→─────────────────────────┐
│ABCDEFGHIJKLMNOPQRSTUVWXYZ│
└──────────────────────────┘
⎕A ≡ (⊂∘⍋⌷⊢) f¨singers ⍝ matches the alphabet
1
```
[Answer]
## Javascript, 98 bytes
```
s=l=>("heCysvCm hirDb iiesm ultOyr rb c ndeMbeonh tdvMnacic".indexOf(l[4]+l[2])/2+10).toString(36)
```
I found that the combination of the 2nd and the 4th character of the names is unique for each of them.
Therefore I create a string with the combinations of `name[4] + name[2]`, not `name[2] + name[4]` or I would have a repetition of the char group `eh` of the first name Aretha Franklin `eh` and when Smokey Robinson and Johnny Cash `oehn` are concatenated.
I could just move Johnny Cash to another position of the string and get a different mapping, but concatenating the 4th and the 2nd character in this order avoids the collision and leaves the dataset order intact without adding more length to the solution. So I decided to go that way (it's just personal preference)
I search for the position of the concatenation of the 4nd and 2nd letter of the given parameter in the string and divide it by 2 so that I get a number between 0 and 25. Then I add 10 and convert it to string from base 36, where 10 corresponds to `a` and 35 to `z`
```
let singers = [
"Aretha Franklin",
"Ray Charles",
"Elvis Presley",
"Sam Cooke",
"John Lennon",
"Marvin Gaye",
"Bob Dylan",
"Otis Redding",
"Stevie Wonder",
"James Brown",
"Paul McCartney",
"Little Richard",
"Roy Orbison",
"Al Green",
"Robert Plant",
"Mick Jagger",
"Tina Turner",
"Freddie Mercury",
"Bob Marley",
"Smokey Robinson",
"Johnny Cash",
"Etta James",
"David Bowie",
"Van Morrison",
"Michael Jackson",
"Jackie Wilson"
]
s=l=>("heCysvCm hirDb iiesm ultOyr rb c ndeMbeonh tdvMnacic".indexOf(l[4]+l[2])/2+10).toString(36)
singers.forEach(singer => console.log(s(singer), singer))
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 101 ~~126~~ bytes
```
Alphabet[][[#&@@#&@@Position[(t=ToCharacterCode)@"nZ-Be_;f%d^q 0w@x~KDaLJ&`k",Total@t@#~Mod~98+32]]]&
```
`+32` seems leading to the shortest stirng hashtable in Mathematica `InputForm`.
[Try it online!](https://tio.run/##XVFdi9swEHzPr1h8NLRcSkr70hICzkfvII05k4QWanztxt7EwrLUrjfJmdL89VSyUw7uQaCRNLMzowqloApFZXjZjS@vZbyxswIZMyGe2ZxGeizhzWiifxW4JUnSJLnph6Ffsa2VKGsSCQPz/e2Ufox2r/LH3/DuFD6dv8xxuej/LIPBxgrq0KmcI5ufP328/fA@TdM3/YuuBcbwJ5gwSYFwx2hKrUwwgGCFDXgfmmoPP@ujqiFmqjU1/mCNFcysLSkY9AAgWNjCwJKMsS09Qj4qA/fYkIdTu4V5o7G9exAntaI8V2bvsKMHa6GjIvhmTU7s3yywohqmbE8tJcaDhiibIYvp5i@ViCZYqcyZzK8yK9vAA29V3ZmYaLhnoi6P3RILxM6DtAZVVsIC9/t2nidvlEHYHNh0Du7YOySIiLMDN/9TRL6SroHKpW/ACSvTDexdezCuOqyLtjcRhDaMR3M8qhym9qTaVr6igcgyq2d65POQdpSsvKbwW9@N0v7gby9mZSTZwTAE93/pCwzDIawtSwqXfw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Excel, 96 bytes
After too much time wasted trying other approaches, have implemented @Eduardo Paez's approach:
```
=CHAR(FIND(MID(A1,5,1)&MID(A1,3,1),"her DbMbdvsv tdeicsm hnhltirac c i uCyrbOyCmeoie nMn")/2+65)
```
[Answer]
# ///, ~~390~~ 231 bytes
```
/gg/U/
/a///b///c///d///e///f///g///h///i///j///k///l///m///n///o///p///q///r///s///t///u///v///w///x///y///z//
/ F//
/A //
/ G//
/ M//
/M //
/J B/X/
/J //
/L //
/ R//
/R C/Y/
/S C/Z/
/B D/K/
/ B//
/ J//
/ T//
/S W/I/
/R O/N/
/JU/U/
/R //
/E P/H/
/PC/Q/
```
[Try it online!](https://tio.run/##HZHbwpMwEITv8xT7BvsMhR60Fou0v796l8IKkXSjIaXiy9cJF9/ksMnMBiZvp0Gm14v7nt@YLTPfQAs6IOAn6MEAHPgFRuDBHSgI4Df4AyKYQAIPMIMn@AsW8A/QHrKhPDtkqSBVXh6p4G95wPy01htIQyV/Z75g@MFc0JY/oVLk8jHLlXPxnT/mo2f@DIO3/JwmO@yo5g/Mdclf2GyipMHSPlodvVOz8XSIImoau1A52OhlMk24SUxUe6vJ7PzsJqqjTF4WU7l2pKPte4nmYu9UhjCKuTq1dH1Exe4xDEonUQ1q9lG6zglVEttHxG0bZ6d0sIuYItyoynnLOt0uSDOXO@wWQgNOJxicE7KbbKL96qzoEr/MXJLMMH4P2iFzl5JFV3f0vioVMTzVbO3sOirC04mp7cNT1ZY2JkXkV6tUhRhdTjm5lLxQ41p8gC6/cbDiYdiOudyEhc7xth7NeznXeaxer/8 "/// – Try It Online")
231 bytes after removing the newlines.
This is very long, but /// cannot handle different characters generically. In other words, /// does not support regex.
] |
[Question]
[
Your challenge is to passwordify the string! What is passwordifying, you ask?
Take a string as input. This string will only contain uppercase letters, lowercase letters, digits, and spaces.
You must replace all spaces with underscores and move all numbers to the end of the string in the order that they appear from left to right. Then, for every letter in the string, randomly change it to uppercase or lowercase.
Examples (case of characters should vary every time):
```
Input
Hello world
Output
HElLo_wORld
Input
pa55 w0rd
Output
pA_Wrd550
Input
14 35
Output
_1435
Input
0971
Output
0971
Input
[space]
Output
_
```
## Shortest code in bytes wins!
Whoever asks on Information Security SE if this is a good hashing algorithm wins!--Don't worry SE overlords, I'm just kidding.
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 76 bytes
```
`:_64/"32}
,` (3 :=-{
"`{"; _v2$ ;`3
"`".:@ ; ".5(`3.
< "" `^`;>
```
Another collab with @MartinBüttner and on the more insane side of the Labyrinth spectrum – for the first time we have all four of `^>v<` in the one program. [Try it online!](http://labyrinth.tryitonline.net/#code=IGA6XzY0LyIzMn0KLGAgICAgKDMgIDo9LXsKImB7IjsgX3YyJCAgO2AzCiJgIi46QCA7ICIuNShgMy4KPCAgICAgICAiIiBgXmA7Pg&input=cGE1NSB3MHJk)
### Explanation
The general algorithm, which runs in a loop, is as follows:
```
1. Read a char
2. If EOF:
3. Move all digits from auxiliary stack to main
4. Output all digits on main stack
5. Halt
Otherwise:
6. If char is a letter (c >= 64):
7. If random turns left:
8. Output char XOR 32
Otherwise:
9. Output char
Otherwise:
10. Shift char to auxiliary stack
11. If char is space (c-32 == 0):
12. Pull char back from auxiliary stack
13. Output underscore
Otherwise:
14. Continue loop
```
To keep the explanation compact, here's roughly how each part of the program corresponds to the pseudocode above:
[![enter image description here](https://i.stack.imgur.com/3NKYa.png)](https://i.stack.imgur.com/3NKYa.png)
Here are the interesting parts.
### Getting randomness in Labyrinth
There's only one way to get randomness in Labyrinth, and it's when the IP tries to go forwards but 1) there's neither a path forwards nor backwards and 2) there's paths available left and right. In this case, the IP randomly chooses between the left and right routes.
This is only possible using the`^>v<` operators, which pop `n` and shift the row/column `n` away by 1. For example, the program ([Try it online!](http://labyrinth.tryitonline.net/#code=IiAxCiIidiFACiAgMgogICAhQA&input=))
```
" 1
""v!@
2
!@
```
outputs either 1 or 2 randomly, since the `v` shifts the column with offset 0 (i.e. the column the IP is on) by 1, yielding
```
"
""1!@
v
2!@
```
The IP is facing rightward and tries to go forwards (top of stack is zero) but can't. It also can't move backwards, so it randomly chooses between left or right.
### Golf tricks
* The program starts from the first char in reading order, which you'll notice is actually step 6. However, popping from an empty Labyrinth stack yields 0, so steps 10 and 14 occur, shifting a zero to the auxiliary stack, which is effectively a no-op.
* The main stack is effectively empty after every iteration, which allows us to golf the code layout by using `>` and `<` on the implicit zeroes at the bottom. The `>` wraps the bottom row around so that the IP moves from the bottom right to the bottom left, and the `<` shifts the row back. The IP then happily moves up the left column to continue the loop.
* Digits in Labyrinth pop `n` and push `10*n + <digit>`. In addition, chars are taken modulo 256 before being output. Putting these two together lets us output 95 (underscore) by doing ``33` to 32 (space), which works because `-3233 % 256 = 95`. Even though there are other ways to turn 32 into 95 (`;95` being the easiest), working with a negative number here allows us to compact the code a bit with left turns.
[Answer]
# Pyth, 15 bytes
```
s}D`MTrRO2Xzd\_
```
[Demonstration](https://pyth.herokuapp.com/?code=s%7DD%60MTrRO2Xzd%5C_&input=pa55+w0rd&debug=0)
```
s}D`MTrRO2Xzd\_
Implicit: z = input(), d = ' '
Xzd\_ In z, replace ' ' with '_'.
rR To each character, apply r-function
O2 Randomly 0 or 1. r 0 is lowercase, r 1 is uppercase.
}D Order the characters based on presence in
`MT The strings of the numbers 0 to 9.
s Concatenate into a string.
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~22~~ ~~21~~ 20 bytes
Code:
```
þ¹žh-s«ð'_:vyždÈiš}?
```
Uses **CP-1252** encoding.
[Try it online!](http://05ab1e.tryitonline.net/#code=w77CucW-aC1zwqvDsCdfOnZ5xb5kw4hpxaF9Pw&input=cGE1NSB3MHJk)
[Answer]
## Python, 107 bytes
```
from random import*
lambda s:''.join([choice(c+c.swapcase()),'_'][c<'!']for c in sorted(s,key=str.isdigit))
```
An improvement on the [other](https://codegolf.stackexchange.com/a/76550/21487) [two](https://codegolf.stackexchange.com/a/76501/21487) Python answers because:
* `[...,'_'][c<'!']` is used instead of `s.replace(' ','_')`, and
* `choice(c+c.swapcase())` is used instead of `choice([c.upper(),c.lower()])`
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 25 bytes
```
lelS'_er{58<}${2mr{eu}&}%
```
[**Try it online!**](http://cjam.tryitonline.net/#code=bGVsUydfZXJ7NTg8fSR7Mm1ye2V1fSZ9JQ&input=SGVsbG8sIDEyMyBpdCBpcw)
### Explanation
Translation of my MATL answer.
```
l e# read line as a string
el e# make lowercase
S'_er e# replace spaces by underscores
{58<}$ e# (stable) sort with key "is digit"
{ }% e# map block over the string
2mr e# generate 0 or 1 equiprobably
{eu}& e# if it's 1, make uppercase
```
[Answer]
## CJam, 23 bytes
```
lS'_er{60<}${eu_el+mR}%
```
[Test it here.](http://cjam.aditsu.net/#code=lS'_er%7B60%3C%7D%24%7Beu_el%2BmR%7D%25&input=pa55%20w0rd)
### Explanation
```
l e# Read input.
S'_er e# Turn spaces into underscores.
{60<}$ e# Sort (stably) by whether the character is a digit or not. This moves digits
e# to the end, without changing the relative order within digits or non-digits.
{ e# Map this block over the characters...
eu e# Convert to upper case.
_el e# Make a copy and convert to lower case.
+ e# Join them into one string.
mR e# Randomly choose one of the characters. Of course, this entire block is a
e# no-op for non-letter characters.
}%
```
[Answer]
## JavaScript (ES6), ~~114~~ 101 bytes
```
s=>s.replace(/./g,c=>c>'9'?c[`to${Math.random()<.5?"Low":"Upp"}erCase`]():c>' '?(s+=c,''):'_',s='')+s
```
47 bytes just to randomise the case of a character...
Edit: Saved a massive 13 bytes thanks to @edc65.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 27 bytes
```
k32'_'XEt58<2$S"@rEk?Xk]]v!
```
[**Try it online!**](http://matl.tryitonline.net/#code=azMyJ18nWEV0NTg8MiRTIkByRWs_WGtdXXYh&input=J3BhNTUgdzByZCc)
```
k % implicit input. Make lowercase. Non-lettters are not affected
32'_'XE % replace spaces by underscores
t58< % duplicate. Create logical index: true for digits, false otherwise
2$S % sort first string according to second. Sort is stable
" % for each character in that string
@ % push that character
rEk % generate 0 or 1 with 1/2 probability each
? % if it's a 1
Xk % make uppercase. Non-letters are not affected
] % end if
] % end for each
v % vertically concatenate all stack contents
! % transpose into a row char array, i.e. a string. Implicit display
```
[Answer]
# Python 3, ~~128 122~~ 118 chars
```
from random import*
s=lambda x:''.join(choice(i.upper()+i.lower())for i in sorted(x.replace(' ','_'),key=str.isdigit))
```
Thanks to xnor for shaving off 6 bytes.
[Answer]
# Perl 6, ~~77~~ ~~75~~ 61 bytes
```
{[~] |S:g/' '/_/.comb(/\D/)».&{(.lc,.uc).pick},|.comb(/\d/)}
```
`S///` is like `s///` except it doesn't modify `$_` in place
[Answer]
# Pyth, 17 bytes
```
smrdO2o}N`UT:zd\_
```
[Try it here!](http://pyth.herokuapp.com/?code=smrdO2o%7DN%60UT%3Azd%5C_&input=pa55%20w0rd&debug=0)
## Explanation
```
smrdO2o}N`UT:zd\_ # z = input
:zd\_ # replace spaces with underscores
o # Sort ^ with key function(N)
}N`UT # N in "0123456789", gives 1 for numbers so they get sorted to the right
m # map every character d of ^
rdO2 # Convert d randoms to upper- or lowercase
s # join list back into one string
```
[Answer]
## Mathematica, 86 bytes
*Thanks to Sp3000 for saving 1 byte.*
```
RandomChoice[{ToLowerCase,Capitalize}]@#/." "->"_"&/@Characters@#~SortBy~{DigitQ}<>""&
```
Ahhh, string processing Mathematica... isn't it lovely. This is an unnamed function that takes and returns a string.
Due to all the syntactic sugar, the reading order is a bit funny:
```
Characters@#
```
Split the string into characters, otherwise we can't really do anything at all with it.
```
...~SortBy~{DigitQ}
```
Sorts the digits to the end. By wrapping the test function in a list, we make the sorting stable.
```
...&/@...
```
Maps the left-hand function over each character in the list.
```
RandomChoice[{ToLowerCase,Capitalize}]
```
Chooses a random case-changing function for the current character.
```
...@#...
```
Applies it to the current character.
```
.../." "->"_"
```
Replaces spaces with underscores.
```
...<>""
```
Finally joins all the characters back together into a string.
[Answer]
# PowerShell, 113 Bytes
```
-join([char[]]$args[0]-replace" ","_"|%{if($_-match"\d"){$d+=$_}else{"'$_'.To$("Low","Upp"|random)er()"|iex}})+$d
```
---
PowerShell stands for horrible golfing language. Split into char array and replace spaces with underscores. Take each character and process. Collect numbers into variable $d for later output. Each other character is randomly make into uppercase or lowercase by invoking an expression using `'char'.ToLower()` or `'char'.ToUpper()`. If any digits were collected append them on the end.
[Answer]
# Perl, ~~51~~ 48 bytes
Includes +2 for `-lp`
Run with the input on STDIN:
```
perl -lp passwordify.pl <<< "Hel1lo wo4rld"
```
`passwordify.pl`:
```
s%\pL%$&^$"x rand 2%eg;$_=y/ 0-9/_/dr.s/\D//gr
```
[Answer]
# Julia, ~~88~~ ~~87~~ 78 bytes
```
s->join([c<33?'_':rand([ucfirst,lcfirst])("$c")for c=sort([s...],by=isdigit)])
```
This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.
First we break the input string into an array of its characters, and sort the array according to whether each character is a digit. This maintains order in the text and digits but pushes digits to the end. Then, for each character in the array, we check whether it's a space. If so, replace with an underscore, otherwise randomly choose one of `ucfirst` or `lcfirst` to apply to the character, thereby converting it to upper- or lowercase, respectively. Join the array into a string and we're done!
[Try it here](http://goo.gl/NiwvFh)
Saved 9 bytes thanks to Sp3000!
[Answer]
# Ruby, 84 bytes
Anonymous function. Removing the space before `c.downcase` causes a syntax error for some reason and I'm not sure why.
```
->s{q="";s.gsub(/./){|c|c=~/\d/?(q+=c;p):c==" "??_:rand<0.5?c.upcase: c.downcase}+q}
```
[Answer]
# Factor, 154 bytes
or 222 with importing `kernel splitting sequences ascii combinators.random regexp`
```
: f ( x -- y ) R/ \d/ R/ \D/ [ all-matching-subseqs ] bi-curry@ bi [ { [ >upper ] [ >lower ] } call-random ] map [ "" join ] bi@ " " "_" replace prepend ;
```
I'm not too good at golfing in factor, and I'm not sure if I took the best approach here, but thought I'd give it a go
[Answer]
## Lua, 125 Bytes
When object meets functional, you can do some pretty things, even in lua! I don't think I can golf this down, it's already quite a huge mess, and I'm already happy to beat most of the python answers :D.
```
s=""print((...):gsub("%d",function(d)s=s..d return""end):gsub("%s","_"):gsub("%a",1<math.random(2)and s.upper or s.lower)..s)
```
### Ungolfed and explanations
```
s="" -- Initialise the string that will contains the digits
print((...) -- apply the following to the argument then print it
:gsub("%d",function(d) -- iterate over the digits
s=s..d -- concatenate them in s
return"" -- remove them from the arg
end)
:gsub("%s","_") -- replace spaces by underscores
:gsub("%a", -- iterate over letters
1<math.random(2) -- pick a random integer between 1 and 2
and s.upper -- if it is 2, use the function upper() of object s
or s.lower) -- else, use the function lower() of object s
..s) -- concatenate with s
```
[Answer]
## Seriously, 25 bytes
```
,`'_' (Æ≈"ûù"J£ƒ`M;ì;(-+Σ
```
[Try it online!](http://seriously.tryitonline.net/#code=LGAnXycgKMOG4omIIsO7w7kiSsKjxpJgTTvDrDsoLSvOow&input=J3BhNTUgdzByZCc)
Explanation:
```
,`'_' (Æ≈"ûù"J£ƒ`M;ì;(-+Σ
,` `M map over input:
'_' (Æ replace spaces with underscores
≈ cast to int (does nothing if cast fails)
"ûù"J£ƒ randomly upper- or lowercase it (does nothing if not letter)
;ì;(-+ move ints to back
Σ join
```
[Answer]
# [IPOS](https://github.com/DenkerAffe/IPOS) - non competing, 14 bytes
```
S'_RE`N-`dE!k?
```
Yes, I added builtins for this challenge, but those are not especially targeted at this problem.
This works with [version 0.1 of the interpreter](https://github.com/DenkerAffe/IPOS/releases/tag/v0.1).
## Example run
```
> python IPOS.py S'_RE`N-`dE!k? -i "pa55 w0rd"
Pa_WrD550
```
## Explanation
```
# Implicit: place input on the stack (C)
S # Push a space to the stack (B)
'_ # Push an underscore to the stack (A)
R # In C replace B with A -> replace underscores with spaces
# the stack contains now only the replaced string (C)
E # Push an empty string (B)
` # Start a command literal,
# the stack for this gets initialized with a single character (B) later
N # Push the digits 0-9 as string to the stack (A)
- # Remove every character from B that is in A
` # End command literal (A)
d # split C on B, sort the parts descending with the key A and join back on B.
# The key function A transforms each character of the string to an empty string if it is a digit.
# Since the resulting char does not contain a digit, it's key value is it's length.
# This maps the key 0 to digits and the key 1 to non-digits. Sorting this in descending
# order moves the digits to the right and leaves non-digits in the order they were before.
E # Push an empty string
!k # Push the command k (=swapcase)
? # Apply ^ to every character randomly
# Implicit: Output stack contents
```
[Answer]
# PHP, 368 bytes
```
$str = "pa55 w0rd";
$str = str_replace(" ","_",$str);
$output AND $numStr = "";
$numArray = ['0','1','2','3','4','5','6','7','8','9'];
for($i=0;$i<strlen($str);$i++){
in_array($str[$i],$numArray)?($numStr = $numStr.$str[$i]):((rand(10,100)%2==0)?$str[$i] = strtoupper($str[$i]) AND $output = $output.$str[$i]:$output = $output.$str[$i]);
}
echo $output = $output.$numStr;
```
Ungolfed Code:
```
$str = "pa55 w0rd";
$str = str_replace(" ","_",$str);
$len = strlen($str);
$output = "";
$numStr = "";
$numArray = ['0','1','2','3','4','5','6','7','8','9'];
for($i=0;$i<$len;$i++){
if(in_array($str[$i],$numArray)){
$numStr = $numStr.$str[$i];
}else {
if(rand(10,100)%2==0)
{
$str[$i] = strtoupper($str[$i]);
}
$output = $output.$str[$i];
}
}
$output = $output.$numStr;
echo $output;
```
[Answer]
## Python 2, 179 bytes
```
from random import*
f=lambda s,a=[str.upper,str.lower],n='0123456789':''.join(map(lambda x:choice(a)(x),filter(lambda x:x not in n,s).replace(' ','_')))+filter(lambda x:x in n,s)
```
There's probably a lot of room for improvement here that I'll work out later.
[Answer]
## AWK, 128 Bytes
```
{srand();for(;++i<=split($0,a,"");){s=a[i];if(s!=s+0){o=s==" "?"_":rand()>0.5?tolower(s):toupper(s);A=A o}else{N=N s}}print A N}
```
The `srand()` is needed to give us different random numbers each time it runs.
For this to work properly with multi-line input, we'd need to put something like `A=N=""` before the `for` loop.
[Answer]
# Python 3.5 - 118 bytes:
```
from random import*
lambda y:''.join(choice([q.upper(),q.lower()])for q in sorted(y.replace(' ','_'),key=str.isdigit))
```
As you can see, I am basically using the random module's `choice` function to choose a random function (either .upper() or .lower()) for each letter in the sorted version of the string given, in which all the digits go to the end. Also, every space is replaced with an underscore in the sorted string.
[Answer]
## Python 3, 151 bytes
```
import random as r
x=input();s="";n=""
for c in x:
if c.isdigit():n+=c
else:s+=c.upper() if r.randint(0,1) else c.lower()
print(s.replace(" ","_")+n)
```
[Answer]
# PHP, 164 158 chars/bytes
This is better than [the other PHP golf](https://codegolf.stackexchange.com/a/76757/43587), because:
* It takes inputs
* It's shorter
# Script
```
<?$a=$b='';foreach(str_split(strtolower($argv[1]))as$c){if($c==' ')$c='_';if(preg_match("/[0-9]/",$c))$a.=$c;else$b.=(rand(0,1)?$c:strtoupper($c));}echo$b.$a;
```
# Example
```
php password.php 'thats some 1337 shit'
```
>
> ThATs\_Some\_\_sHiT1337
>
>
>
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 73 bytes
```
i:"@")?v:" ")?v0) ?\rl?!;o01!.<
v8< 8>00.! <o"_"/
8<>x<%*4/^o+*
^c<
```
Nothing crazy here, it :
* prints `_` when it encounters
* takes the mod 32 of letters, then randomly adds 8\*8 or 12\*8 before printing them
* stacks the number and print them once the end of the input is reached
You can try it [here](https://fishlanguage.com/playground) !
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 86 bytes
```
-join$(switch -r($args){' '{'_'}'[A-Z]'{"$_"|%('*per','*wer'|random)}\d{$n+="$_"}})+$n
```
[Try it online!](https://tio.run/##TZBda8IwFIavl19xcHFp1Y7KLGMXgjIGXgwUvRjMSenS4xe16ZJKBzW/vTtt3di5Ocnz5LwJyVSB2uwxSSq@HZeVd1SHlDumOORyD552eKR3xi0FiFKEwor11HvfiLLDw86l64hehloMRI9SxEVHaaxOrv2IS572x/UZa90@TyvL2MRhbOCIGV2loFA6iWlu9pK8qrCYL2nn1jqLggAKX9cym4ZvOg4Cv1XDETwEhMPhiHqD/KfHIZGmNQBqT0vmwgW6UDKg4ibXh3Q3AI7fGcocYxgDD1un0ZyTnMAd38KkPdmY9WL1fDa5Os0/jzS0mbRhda3OUqIxdcp13MOvf@k3t5AqgpLoHjXeQ65AqlMWaYT2k0BGBs1f4vL3FdfARlhmqx8 "PowerShell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 19 bytes
```
kd$F?kd↔+ð\_Vƛk≈℅ßN
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=kd%24F%3Fkd%E2%86%94%2B%C3%B0%5C_V%C6%9Bk%E2%89%88%E2%84%85%C3%9FN&inputs=happy%20sword%20123%20green&header=&footer=)
```
$F # Filter out
kd # Digits
? # Take input
↔ # Filter out
kd # Non-digits
+ # Concatenate
ð\_V # Replace spaces with underscores
ƛ # Map...
k≈℅ß # If random bit
N # Swap case
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
v rS'_ ñ§9 Ëpu ö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=diByUydfIPGnOSDLcHUg9g&input=InBhNTUgdzByZCI)
```
v rS'_ ñ§9 Ëpu ö :Implicit input of string
v :Lowercase
r :Replace
S : Space
'_ : with underscore
ñ :Sort by
§9 : <=9
Ë :Map
p : Append
u : Uppercase
ö : Random character
```
] |
[Question]
[
Write the shortest code for finding the sum of primes between \$a\$ and \$b\$ (inclusive).
**Input**
1. \$a\$ and \$b\$ can be taken from command line or stdin (space seperated)
2. Assume \$1 \le a \le b \le 10^8\$
**Output**
Just print the sum with a newline character.
**Bonus Points**
1. If the program accepts multiple ranges (print one sum on each line), you get extra points. :)
[Answer]
# J,41 32 19 characters:
*Update*
(simple sieve)
```
g=:+/@(*1&p:)@-.&i.
```
e.g.
```
100 g 1
1060
250000x g 48
2623030823
```
*Previous*
```
h=:3 :'+/p:i.(_1 p:>:y)'
f=:-&h<:
```
eg:
```
100 f 1
1060
```
[Answer]
## Mathematica 7 (31 chars in plain text)
If PARI/GP solution allowed, then:
```
Plus@@Select[Range[a,b],PrimeQ]
```
[Answer]
# C, 117 bytes
```
main(a,b,s,j){
s=0,scanf("%d%d",&a,&b);
for(a+=a==1;a<=b;a++)
for(s+=a,j=2;j<a;)
s-=a%j++?0:(j=a);
printf("%d",s);
}
```
[Answer]
# C#, 294 characters
```
using System;class P{static void Main(){int a=int.Parse(Console.ReadLine()),b=int.Parse(Console.ReadLine());long t=0;for(int i=a;i<=b;i++)if(p(i))t+=i;Console.WriteLine(t);}static bool p(int n){if((n%2<1&&n!=2)||n<2)return 0>1;for(int i=3;i<=Math.Sqrt(n);i+=2)if(n%i==0)return 0>1;return 1>0;}}
```
[Answer]
# Perl, 62 chars
```
<>=~/\d+/;map$s+=$_*(1x$_)!~/^1$|(^11+)\1+$/,$&..$';print$s,$/
```
This one uses the prime number regex.
[Answer]
# C#, 183 characters
```
using System;class P{static void Main(string[] a){long s=0,i=Math.Max(int.Parse(a[0]),2),j;for(;i<=int.Parse(a[1]);s+=i++)for(j=2;j<i;)if(i%j++==0){s-=i;break;}Console.WriteLine(s);}}
```
This would be much shorter if it didn't have to check for 1, or if there was a better way to... In a more readable format:
```
using System;
class P
{
static void Main(string[] a)
{
long s = 0,
i = Math.Max(int.Parse(a[0]),2),
j;
for (; i <= int.Parse(a[1]);s+=i++)
for (j = 2; j < i; )
if (i % j++ == 0)
{
s -= i;
break;
}
Console.WriteLine(s);
}
}
```
[Answer]
# PARI/GP, 44 characters
```
sum(x=nextprime(a),precprime(b),x*isprime(x))
```
[Answer]
# BASH Shell, 47 Characters
```
seq 1 100|factor|awk 'NF==2{s+=$2}END{print s}'
```
Edit: Just realized the sum overflows and is coerced as a double.
### 52 50 Characters
Here's a bit longer solution, but handles overflows aswell
```
seq 1 100|factor|awk NF==2{print\$2}|paste -sd+|bc
```
[Answer]
## Haskell (80)
```
c=u[2..];u(p:xs)=p:u[x|x<-xs,x`mod`p>0];s a b=(sum.filter(>=a).takeWhile(<=b))c
```
`s 1 100 == 1060`
[Answer]
## APL (25 characters)
```
+/((R≥⎕)^~R∊R∘.×R)/R←1↓⍳⎕
```
This is a modification of a well-known idiom (see [this page](http://www.users.cloud9.net/%7Ebradmcc/APL.html) for an explanation) for generating a list of primes in APL.
Example:
```
+/((R≥⎕)^~R∊R∘.×R)/R←1↓⍳⎕
‚éï:
100
‚éï:
1
1060
```
[Answer]
## Normal Task (Python 3): 95 chars
```
a,b=map(int,input().split())
r=range
print(sum(1%i*all(i%j for j in r(2,i))*i for i in r(a,b+1)))
```
## Bonus Task (Python 3): 119 chars
```
L=iter(map(int,input().split()))
r=range
for a,b in zip(L,L):print(sum(1%i*all(i%j for j in r(2,i))*i for i in r(a,b+1)))
```
[Answer]
# Pari/GP (24 characters)
```
s=0;forprime(i=a,b,s+=i)
```
Like some other solutions, this doesn't strictly meet the requirements, as `a` and `b` aren't read from stdin or the command line. I thought it was a nice alternative to the other Pari/GP and Mathematica solutions however.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
òV fj x
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.5&code=8lYgZmogeA==&input=MgoyMw==)
[Answer]
# Ruby 1.9, 63 chars
```
require'prime';p=->a,b{Prime.each(b).select{|x|x>a}.inject(:+)}
```
Use like this
```
p[1,100] #=> 1060
```
Using the `Prime` class feels like cheating, but since the Mathematica solutions used built-in prime functions...
[Answer]
# Regex `üêá` (ECMAScript[RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE), 32 bytes
```
^(x*),x*(?=\1)(?!(xx+)\2+$)x\Bx*
```
Takes its input in unary, as two strings of `x` characters whose lengths represent the numbers, joined by a `,` delimiter, specifying an inclusive range. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)
[Try it online!](https://tio.run/##RU@9TsMwEN79FId1g52Y1gnqUjdNi8rKxBhhlaiVUrlJSIJkFMzIA/CIvEi4ggTj93vftYfOLabzK2BnYHRNuXeAc0MwW@22D9t1YMemE9hn2qzWRo5QHQnJse2qegBe1NwEUhOKuKx/eeoHclt1nahEHp4vev7PauLlEq2hFhDoqG5DqdZVg@CKK2IMA8CSrsGpqeof9rxvR@65Rxs2Tmbvc5EvsZMiz8c4xlLpIGnx76C/EDlnHL4@PoHPsKR1b7SRhWDt3f3O2ulR@EgqH4k8KxLquhLex7JIY5S@uPXRNNEHmiVapZqlKr1hF6y/AQ "Perl 5 – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=RU89TsMwFN5zioflwU7c1gkLqpumRWVlYoywStRIQW4SklQyCmbkAKwsHeAIPUxXjsAJeCUIJuv7fZ_f3utNY_bHr-0j0EZBb6psbYBOFMJ4tlreLOfOy6uG0TaWajZXvIciR8T7uinKDkhaEuVQDTFi4nZ313bo1mIUipBvHk568s9K5PmUaoUtwKjBugWmalN0jAgikFEeAM3wGtxXRfnDbtd1TyyxVLuF4fHzhCVT2nCWJH0Q0ExIx3HxMOgvhM4xgc-XVyBjmuG6J9zoOaf11fVK649dl48ujnDLrM-F9VkSpyFWnjFrA55GAeU2vbT-4Nv_Pgf8lfRCKSLpRSI6905YDuI3 "Perl - Attempt This Online") - Perl
[Try it online!](https://tio.run/##dVThbts2EP6vp7i4a0xaTCDZwFBYUYM2zbAfWTMYKbAhzgSFpmwhMiVQ0uyk9d8@QB@xDzLvSEq23KSGLVPHu@@7@45HXhQnc863r1LJs3om4KzgSpwu3jp8ESuIits7CGHSe79aPdyP6r8fH/@6Wfy6WpDtP2Q9oGw9IOfh1Kfk/Iis1y6dDt1f6Hr6fj3Y0h9jegwGRRgVrh84e76ymqW5JuyaVCrnh7Y0R6uIl8/93jqprKDAZRUJpXJFeC7LCkwBg6Uoy3gu6GfkGY85OsDZGTRWvTR2IWdZAEpUtZLgBxunlmU6l2IGWS7n9hHLciVUYNiWjxGPsyyvK6L1al@i@yznDzDgFD5bd9fdwXoIa2LjVBJ0cAA/xS0WkQlJCnri34VeADYhWxoUPOyR83EvwJUbFvavh2pfaMUp2muEHA2jCnIdrPHnuDDYXaBUFnWlw5WAgRIBdDVCUYpK2Wglyjqr7FqrmSSlqBhgcZjlvFrYnfxfwatc3Y7uLBWihmCVyJdFmgmU5ZRHSE4ogz8vJpfRh@ubd1dX8MW@fbr57Q2DY8tsFy2VRy1mmgA5UoK2@iWmxQnBstCbQU8DmRwVxJiSCYfXszG8LqcSD1sH0/I0wN2OYdr7XtrtBPGILvJJK2pEnIsqS6Ug9gylklk9adC2sc33iQLataqkP5V9GiCIH5gtE3Fapk@C0DD0qO5AlcpaBHsEJEWVNa1tTLnf22VV5CU6HDC3sVKsIoxnILGsuMrThrRpBLg6mAaHcZiatv4Atzs/XIuEY9JjveC5B/IQneqA4myihpyUDEiTB27qpws@/qSm9@kLGLfo5Lr6mumz/uH@BkRWipdS2xMvLW@H9EWqzcHbUizxXJASHY1g/XUfVcN2mWw0hkXTWbWHoFVCHgKjeOhkhU5SOSNYBTNWk0QrMIRhdyDHY2lUv0fdHgLrHuLN4zzP97AN8P3rN8C5t9eLSW/naWe3nUSxFpwoweDjp6srBtgYU6pnvs0AMxh1dNKpWowzD46PW7yj0M7s5WRyPYk@Xv/x7ubid@r8/Khc6pnsHBfdxJ@7N5W0V3GS1eXihZqaOjeOmfixHVUlBGZMd3dsc3s5m63PfM/xPTb0nCEbjhz97v3Hkyyel9uTTCv0Pw "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##hVXrTuNGFP6fpzh4KzLjGBoHdYViDGIhEpEgrLJB3S5QyziTxMIeW74sgZa/fYA@Yh@k9MzFjkOyagTJzJlzvnOdb4I03ZsHwduHKZuFnMHns/Gg551dnw@8m9Fw4v06PJ9cwGHrQ8iDqJwyOEqDjPX2F8etYOFn4KW39@DC2Pj09PT4cFD@9vz8dbL4@LQgb7@TpUmtpUlO3DubkpMdslx26F2v8xNd3n1amm/0vY1hgZm6XtqxnYbDvMhCPhceV7IwQSnz4@MNveNWyAtIcVl4LMuSjAQJzwuQ0Zoxy3N/zij8kRfTfj9ADTg6Ai0WSylnfBo5kLGizDjYzusGptgHyZRZ8JAkESTuzI9yASvdaLjb3i8f750W4CecAZGF8@ZMY3haiygcoip/c3ZxOj40qT60IA9fWDIjdeA/V5KGPqVUehEfksCJSiJIygL6UCdKRXqGNAMZQR@Md8lLY8NAK@OOG7Suxywq84XKpC5K67VV8jycczaFKOFz9eXz/IlljixY/OwFfhRhGDp3vfMeoiR4BDOw4HsSTsGc@oWPtRNFEktwXSDixKS7KwyqsTudujNd3ZnYDzlBABlgeouDEDFOUrpn37tdR6WgpgPSwDXISd9wcNVxU/Vj4HSeiQmlKC8R8aDnFdhUtBXwc1xI6CZQyNOyEOYyMWwhmBmr9rFfBAtP5mKu1gotY3kZFZZqgaMv3Jfht4GUzGY5w0PMF1OYF4s1BTP5zoICrXQn8OJV/uM0jBjRQ/Hl82RM02A/8DBYQi2N8W0wvvYmg/HVcHQ6GZxX4sHXyWB0PjiHP7Xg6uZyMrwcjgYW7Moo9a@OrUtXM72T4UjqbjTvh/zWeo1iuBv18XDvF8ybZUnspX5RsIyTDOd@dHN5qQGaNniZC7YssKzVyt12rmHJBgpmUA9lBWE1JtXaNnnvAZSrKIzDJsieTZ2G0pSlxf8qZSwoszxM@FZF6XaWZCD55qWeZeSQCMmaqKsdcktNI3WqO1C154UCygUnkfYdb6PrF9d25JG02BdcQqjrdikIzyEvmbNCQKc4hcKtYs98dVZHlSY5Kqx5rmw5e/LQ3gKOTfKLJNRO9VhCRxhTZ91OECVK38HVt0@SmuAxy3A2NdAPEaGaFNuPvQtIjg3VceCh@O6Ajf9cuLfpFoxbVOp0xKPWttrr56/AkOW3hbZyHCu/DadbXb2u7WIW4zSQHBVlwdrLNlYN2yWjERgKTURVDUFVCb4OjMVDJVVofNGnBLOwpFQGURVYcGyDzvp9Lqv@gHV7dJS6K0h@M971NsA/f/0NyJqKm2V4taZiuvULKu92k6awQTLlrvxbEQOu9V1oVE4Er1CPurC7qz3suJrIxuPrsTe6vjqdnF3Q9ao0uKki4CIrWQNbtLb1w3nT@W15EF9/xFHIaYyRVRab3KcU6j1tPifqEOm1fu1U3PjuvtmW3W3ZXavXbfWs3kFL7Lv/BrPIn@dve5EE2Tv8Dw "C++ (gcc) – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=hVbdTuNGFL5unuLgrciMY2gS1BWKMYiFSETiZ5UN6naBWsaZJBbO2LLHS6Dltg_Q2970ppd72YfZXvZJeubHjkNSNSLOzJlzvvM7n_n9S5jGRS6__jQMv9xYO3EaZqy7s2_dfR2-GbNJxBm8Pxn2u_7J1Wnfv74cjPwfBqejM9hvvIl4GBdjBgfKaHd22AhnQQZ-enMHHgytd4-PD_d7xY9PTx9Hs7ePM_JnISY7-1_hJ7KwqbOwyZF326HkaIssFi162219Sxe37xa21vv7m336GsJywE49P2113Jr_XGQRn8oAlrIoQSkL5odreoeNiAtIcSl8lmVJRsKE5wJU8Pac5XkwZRR-zsW41wtRAw4OwIjlUskZH8cuZEwUGYeO-7KGKfdhMmYO3CdJDIk3CeJcwio3Bu6m-_3bO7cB-IkmQFQd_SkzGL7RIhqH6EZcn5wdD_dtag4dyKNnlkxIFfh3paSmTylVXuSHJHCkkwiTQkAPqkSpTM9SZqAi6IH1KnllbFloZd1yi1b1mOAQzXQmVVEaL42C59GUszHECZ_qR8DzR5a5qmDzJz8M4hjDMLmbnX8fJ-ED2KEDn5NoDPY4EAHWThZJLsHzgMgTm24vMajBbrWqzrRNZ-ZBxAkCqADTGxyEmHGS0p3Ondd2dQp6OiANPYsc9SwXVy0v1T8WTumJnFSK8gIR97q-wKairYSf4kJB14EinhZCmqvEsIVgZ6zczwMRznyVi71ca7SM5UUsHN0C19y_D4NPfSWZTHKGh5gvpjAVsxUFO_nMQoFWphN4D0v_8zSKGTFD8eH9aEjTcDf0MVhCHYPxqT-88kf94cXg8njUPy3F_Y-j_uVp_xR-MYKL6_PR4Hxw2XdgW0Vpfk1sbbqc6a0MR9J0o34_1NPo1YrhrdXHx30gmD_JkrmfBkKwjJMM5_7y-vzcANRt8DILthBY1nLlbTo3sGQNBTOohrKEcGqT6myavNcA2lUczaM6yE6HujWlMUvF_yplLCyyPEr4RkXldpJkoPjmuZpl5JAYuZvoqx1xR08jdcs7ULbnmQLKJSeR5i1voutnr-OqI2WxK7mEUM9rU5CeI14wd4mATnEKpVvNnvnyrIoqTXJUWPFc2nL26KO9AxybFIgkMk7NWEJLGlN31U4SJUpfwVW3T5Ga5DHHctc10A-RodoU24-9C0mODTVx4KF8tqCDXy7dd-gGjBtUarXkO67pNFfPX4Ahy28Kbel4rv3WnG509bKym7M5TgPJUVEVrLloYtWwXSoaiaHRZFTlEJSV4KvAWDxU0oXGF_yYYBaOkqogygJLjq3RWa_HVdXvsW4Prlb3JMmvx7vaBvjn198AWVNzswqv0tRMt3pB1d2u0xQ2SKXcVn9LYsC1uQu1ysngNepBG7a3jYctzxDZcHg19C-vLo5HJ2d0tSo1bioJWGQFq2HL1q7YrCRq8tvwQnz5L45CTmOMLLNY5z6tUO1p_XWiD5Feq7edjhvfu_ofqD_-6jiddqPTdrrtRtfp7jXkvq0P_wU "C++ (GCC) - Attempt This Online") - PCRE2
[Try it on replit.com!](https://replit.com/@Davidebyzero/regex-Sum-of-primes-between-given-range) - RegexMathEngine, in ECMAScript mode
```
^ # Anchor to start
(x*) # \1 = lower end of range
, # Skip over delimiter
x* # tail += {any number, including zero}
(?=\1) # Assert that tail ‚â• \1
(?!(xx+)\2+$) # Assert that tail is not composite (i.e., tail is prime or is < 2)
x\Bx* # if tail ‚â• 2, add tail to the number of possible matches; this is
# equivalent to "(?=xx)x+"
```
# Regex (.NET), 32 bytes
```
x(x*),((?=(xx+)\3+$|(x)+)x\B)*\1
```
Returns its output as the capture count of group `\4`.
[Try it online!](https://tio.run/##RY9LboMwFEXnrMJCr8KPnyDpKAg1bcddAUEVpU5w5djINsIKYdoFdIndCCWVqg7vR1fn9mpk2nRMiAV0WWl2Yq7e7SQb6T5YHHUhxpQ@lNS5CA/bCK7UYYTu8IThIV@Cfew/q3PPBXv3sYBLmRVHpVnTdhQE4ZIAl/1gcYKmBJGYXnDrx35BwJUUGnIld2QKkiCkFZe2htdEWJJhFLggrF4a260wj2/mL8UZkw/F5e8EP1I4l6DTtdd2zFBwiNPNveA0am5Z0ilj55UqL8i/QRKp1oOCS0b8lfL784vAOpWetBp6U93Xadv0dtDMpK0apEV/npc8zjMvz@JN5m3izda76ewH "PowerShell – Try It Online")
```
# No need to anchor, as this regex will always match
x(x*) # \1 = {lower end of range} - 1
# This takes advantage of the input specification allowing
# us to assume it to be ‚â• 1.
, # Skip over delimiter; tail = upper end of range
(
(?= # Lookahead - is atomic (the first match found is final)
(xx+)\3+$ # Match if tail is composite (i.e., isn't prime and is ‚â• 2)
| # or...
(x)+ # Push {tail} captures onto the Group 4 stack, i.e. add
# {tail} to the return value.
)
x # tail -= 1
\B # Assert tail > 0
)* # Iterate the above as many times as possible (can be zero)
\1 # Assert tail ‚â• \1
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~19~~ 17 bytes
```
$+Y1=0N_%,_FIa\,b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhYbVbQjDW0N_OJVdeLdPBNjdJIg4lDp5dFGOgpGxrFQLgA)
*-2 thanks to @DLosc*
Uses [DLosc's answer to the prime checker challenge](https://codegolf.stackexchange.com/a/57701/114446)
#### Explanation
```
$+Y1=0N_%,_FIa\,b ; Input on command line
\, ; Inclusive range between
a b ; The two inputs
FI ; Filtered by
1=0N_%,_ ; Is prime (see linked answer)
$+ ; Sum the resulting list
```
Old:
```
$+Y{1=0Na%,a}FIa,Ub ; Input on command line
, ; Range between
a ; The first input
Ub ; To the second input incremented
FI ; Filtered by
{1=0Na%,a} ; Is prime (see linked answer)
$+Y   ; Sum the resulting list
```
[Answer]
# Factor -> 98
```
:: s ( a b -- n )
:: i ( n -- ? )
n 1 - 2 [a,b] [ n swap mod 0 > ] all? ;
a b [a,b] [ i ] filter sum ;
```
Output:
```
( scratchpad ) 100 1000 s
--- Data stack:
75067
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
æRS
```
[Try it online!](https://tio.run/##y0rNyan8///wsqDg////G/03MgYA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
≈∏Dp*O
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6A6XAi3///@jDXUMDQxiAQ "05AB1E – Try It Online")
```
≈∏ Push the list [a, ..., b]
D Push a duplicate of that list
p Replace primes with 1 and everything else with 0
* Element-wise multiply the two lists [1*0, 2*1, 3*1, 4*0, ...]
O Sum of the final list of primes
```
[Answer]
# Common Lisp, 107 chars
```
(flet((p(i)(loop for j from 2 below i never (= (mod i j) 0))))(loop for x from(read)to(read)when(p x)sum x))
```
only works for starting points \$\ge 1\$
[Answer]
# R, 57 characters
```
a=scan();b=a[1]:a[2];sum(b[rowSums(!outer(b,b,`%%`))==2])
```
[Answer]
# [Factor](https://factorcode.org/) + `math.primes math.unicode`, ~~32~~ 23 bytes
```
[ primes-between Σ . ]
```
*-9 bytes* thanks to [chunes](https://codegolf.stackexchange.com/users/97916/chunes)!
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFXUJSZm1oMYZfmZSbnp6QqFBSllpRUAmXyShSs/0crQNToJqWWlKem5imcW6ygpxD730jBnKsgMzlbITkxJ4crOSc1seg/AA)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~164~~ ~~138~~ 122 bytes
```
i,x,y,z;main(f){for(scanf("%d %d",&x,&y);x<y;z+=x++*!f)if(f=0,x<2)++x;else for(i=2;x/2/i&&!(f|=x%i++<1););printf("%i",z);}
```
[Try it online!](https://tio.run/##FcxbDoIwEADAqxQMTWurPH639S6kZXUTLAYwWVDPXsMBZsIljH265xOlML7jINyyRpquj1smy3azOzx7Sgr1B6dZLaFPqMoqiiqWVrKVmwZ2G@zGszHnAjWhQt9Ydp02hmEYl0EclHwHXHc1SVko/HquyBjXatDwmimtR0ul3TX8cm5F2zR/ "C (clang) – Try It Online")
Original code from [Programiz](https://www.programiz.com/c-programming/examples/prime-number-intervals). Just modified the code to reduce bytes. Yes, I'm terrible at this.
Code changed thanks to Pedro Maimere, byte count didn't change. Thanks to ceilingcat for golfing 26 bytes, and another 16 bytes.
[Answer]
# Java 8, ~~239~~ ~~237~~ ~~74~~ 73 bytes
```
a->b->{long r=0,t;for(;a<=b;r-=b--==t?~b:0)for(t=1;b%++t%b>0;);return r;}
```
-1 byte thanks to *@ceilingcat*
[Try it online.](https://tio.run/##jU9Na4QwEL37K4aFBYMaom2hbDaWXnpqT3sUKcmuitZNJI5bROxft7G7tNdeZt58vXmvkRcZma7QzeljObay7@FN1nryAHqUWB@hcRt0wLql5aCPWBtNX25g/2p0Ff5jY41pCiUIWGSUqiidWtcCK1iIvDTW53IvFLeRUFEkBD59qR0j6wBFzNU2CHCrUsYJtwUOVoPl88I9p7IbVOtU3sReTH2CszPgH9DWuspyaauerHYAVrr1rWvudPEJV5zl05SEyd0cTnEYM@by/WOYPLB35oqZ/JwCHMYeizM1A9LOMWOr/T/fz9bKsadorl99SYLNDjZBSWXXtaMvM5aTXxznhHBHO3vz8g0)
**Explanation:**
```
a->b->{ // Method with two Long parameters & Long return-type
long r=0, // Result-sum, starting at 0
t; // Temp-long
for(;a<=b // Loop as long as `a` is still smaller than or equal to `b`:
; // After every iteration:
r-= // Decrease the result-sum by:
b--==t? // If `b` is equal to `t` (which means `b` is a prime):
// (and decrease `b` by 1 afterwards with `b--`)
~b // Decrease the result-sum by `-b-1`
// (aka Increase the result-sum by `b+1`,
// where `+1` is to account for the earlier `b--`)
: // Else:
0) // Leave `r` the same by decreasing with 0
for(t=1; // (Re)set `t` to 1
b%++t%b>0;); // Increase `t` by 1 first with `++t` every iteration,
// and loop as long as `b` is NOT divisible by `t`,
// and `b` is NOT 1 (with the second `%b`)
return r;} // After the nested loop, return the result-sum
```
[Answer]
# [Desmos](http://desmos.com/calculator), ~~124~~ 50 bytes
```
f(a,b)=‚àë_{n=a}^bnsgn((n-1)‚àè_{k=3}^nmod(n,k-1))
```
[Try it on Desmos!](https://www.desmos.com/calculator/gibosoovlc)
~~I had to waste 23 bytes just for the edge case of 0 and 1(`-\left\{n<2:1,0\right\}`). I feel like this could definitely be golfed further, but I'm not that skilled at Desmos. I especially think that the edge cases 0 and 1 could be handled a lot better than what I'm doing currently.~~
To think I've come so far... just a mere 2.5 years ago I was still a complete noob at Desmos golfing. Now, coming back to this answer 2.5 years later, there are so many golfs that I can spot. Shifting the bounds to remove the curly brackets, better ways to deal with the `n=1` edge case, and some other tiny golfs, resulted in an over 50% reduction in my original code. Truly amazing stuff.
### Explanation
I will explain each sub-expression a little out of order from the actual code, but I feel that this is the best way to understand what the code is doing.
`‚àë_{n=a}^b`: Summation from `n=a` to `b`. This will iterate through all integers between `a` and `b` inclusive.
`‚àè_{k=3}^nmod(n,k-1)`: This takes the product of `k=3` to `n` of `mod(n,k-1)`which essentially tests all the possible divisors between `k=2` and `n-1`, and checks if `n` is divisible by `k` with `mod(n,k)` (it is `mod(n,k-1)` in the actual product, which will be explained further below). If `n` is composite then at least one value of `k` will make the `mod` expression equal to `0`, making the entire product equal to `0`. Otherwise, if `n` is a prime, then the product would be a positive integer. The reason why the product goes from `k=3` to `n` instead of the more intuitive `k=2` to `n-1` is because if the upper bound is represented by more than one character, then curly brackets are required to group the characters together. In other words, a product from `k=2` to `n-1` would be `‚àè_{k=2}^{n-1}`, which is four more bytes than `‚àè_{k=3}^n`. But because we have shifted the bounds of the product up by one, we will need to subtract one from all instances of `k` in order to compensate for the shift. Hence, we have `k-1` instead of `k` in the `mod` expression. This adds two bytes to our total code length, resulting in a net -2 bytes from doing this bound shifting. Now, because the bounds start from `k=3`, what happens if `n=1` or `2`? When the upper bound is lower than the lower bound, then the product will default to a value of `1`. This is an issue for the `n=1` case, which will result in the product being a positive integer (specifically `1`), but that is undesirable because a positive integer implies that `n=1` is a prime when in reality it isn't a prime. But there is a way to easily fix this...
`(n-1)`: This expression is solely to deal with the `n=1` case. When `n=1`, `n-1` is `0` which causes the entire product to equal `0`. For any other positive value, `n-1` would simply be a positive integer and not affect the overall sign of the product. Note that this fix only works for testing primality for positive integers, but this is okay for our code because the problem specifies that `a` and `b` can be assumed to be at least `1`. To deal with the `n=0` case as well, something like `0^{0^{n-1}}` would probably work.
`nsgn( ... )`: This takes `n` and multiplies it by the sign (`sgn` in the code) of the entire product expression. Remember that if the inside expression is a positive integer, then it is a prime; otherwise, it is composite. By taking the sign of the resulting integer, we will get `1` if `n` is prime and `0` if `n` is composite. Multiplying that by `n` will give `n` and `0` for the respective possibilities.
Now considering that we are taking a summation from `n=a` to `b`, this will essentially add `n` to the total sum if `n` is a prime, but it won't contribute to the sum if `n` is a composite. In other words, it takes the sum of all integers between `n=a` and `b` which are prime. With that, we are done.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `S`, 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
IœP
```
#### Explanation
```
IœP # Implicit input
I # Inclusive range, [a..b]
œ # Filtered by:
P # Primality
# Implicit output of sum (S flag)
```
#### Screenshot
[![Screenshot](https://i.stack.imgur.com/73R9Sm.png)](https://i.stack.imgur.com/73R9S.png)
[Answer]
## Perl, 103 chars
```
while(<>){($a,$b)=split/ /;for($a..$b){next if$_==1;for$n(2..$_-1){$_=0if$_%$n==0}$t+=$_;}print"$t\n";}
```
It'll accept multiple space separated lines and give the answer for each :D
[Answer]
## In Q (95):
```
d:{sum s:{if[2=x;:x];if[1=x;:0];$[0=x mod 2;0;0=min x mod 2+til floor sqrt x;0;x]}each x+til y}
```
Sample Usage:
```
q)d[1;100]
1060
```
[Answer]
## *Mathematica*, 27
Predefined `a` and `b`:
```
a~Range~b~Select~PrimeQ//Tr
```
As a function (also 27):
```
Tr[Range@##~Select~PrimeQ]&
```
[Answer]
## Python 3.1(153 chars):
```
from sys import*
p=[]
for i in range(int(argv[1]),int(argv[2])):
r=1
for j in range(2,int(argv[2])):
if i%j==0and i!=j:r=0
if r:p+=[i]
print(sum(p))
```
] |
[Question]
[
## Introduction
In this challenge you should split an integer into two pieces. Since nobody likes getting the smaller piece of cake, your goal is to be as fair as possible. For example if you wanted to split the integer `7129` into two pieces, there are 3 possible ways of doing so.
`7,129`, `71,29` and `712,9` are all possibilities, but `71,29` is the fairest way of splitting it into two pieces because it minimizes the difference between the two:
```
7 129 -> |7-129| = 122
71 29 -> |71-29| = 42
712 9 -> |712-9| = 703
```
## Challenge
Given an integer determine the best possible way of partitioning it as described above and **report the resulting difference.**
## Rules
* Splitting only makes sense for integers of length at least two, the input will always be ≥ 10
* Input can be either an integer, list of digits or a string
* You don't have to handle invalid input
## Testcases
You only need to report the resulting difference, the partitioning is only here for illustration:
```
10 -> 1,0 -> 1
11 -> 1,1 -> 0
12 -> 1,2 -> 1
13 -> 1,3 -> 2
101 -> 1,01 -> 0
128 -> 12,8 -> 4
313 -> 3,13 -> 10
1003 -> 1,003 -> 2
7129 -> 71,29 -> 42
81128 -> 81,128 -> 47
999999 -> 999,999 -> 0
9999999 -> 999,9999 or 9999,999 -> 9000
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~12~~ 11 bytes
My first Brachylog answer
Take input as a string
```
{~cĊịᵐ-ȧ}ᶠ⌋
```
[Try it online!](https://tio.run/##ASsA1P9icmFjaHlsb2cy//97fmPEiuG7i@G1kC3Ip33htqDijIv//yIxMDAxIv9a "Brachylog – Try It Online")
### Explanation:
`ᶠ` will **f**ind all possible outputs for the predicate in `{…}` and store them in a list. `~c` says that the output is a list that, when **c**oncatenated, is equal to the input. Next `Ċ` asserts that the the output of `~c` has length 2.
`ịᵐ` converts both elements of the output into integers (this gets rid of leading `0`s), `-ȧ` takes the absolute difference of the two elements.
Once we have our list of all possible outputs, we get the minimum element with `⌋`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
### Code:
```
ā¤âε£ÆÄ}W
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##AR4A4f8wNWFiMWX//8SBwqTDos61wqPDhsOEfVf//zcxMjk "05AB1E – Try It Online")
### Explanation
```
ā # Get the array [1, 2, .., len(input)]
¤â # Cartesian product with the last element, (e.g. for input 12345:
[[1, 5], [2, 5], [3, 5], [4, 5], [5, 5]])
ε } # For each element:
£ # Get the substrings (12345 [3, 5] £ --> [123, 45])
Æ # Reduce by subtraction
Ä # Get the absolute value
W # Take the minimum of all results
```
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
f n=minimum[abs$n`div`10^k-n`mod`10^k|k<-[1..n]]
```
`[1..n]` makes this too slow for the larger test cases.
[Try it online!](https://tio.run/##LYdBDoIwEAC/sgeOQLpwUBN5hcempjVA2LS7EEv14t9rgx5mMrO46KcQcp5BBiYhTqzdI1ZiR3pZVHffiOV1PPLjr43GthVjMjsSGGBL@21/QgVJAskUS7HbIC7r@58zaFQ1IBa6Ql9Qx5xr6H@rik/YXUz@Ag "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
lambda n:min(abs(int(n[i:])-int(n[:i]))for i in range(1,len(n)))
```
[Try it online!](https://tio.run/##LY7NCoMwEITvPkXoKYG0ZKOgWfBJrIfY2jZU19@LiM9uE@sclm@HgZl@mT8d6X3I73tj2@ppGWHriNtq4o5mToXDUlz/iK4U4tWNzDFHbLT0rjnIpiZOQoj9Yad6yldQCBIAlQQdKEYtQYU/9gzeVip4KWiDiZYZgM4wSaU55HPmJKOU2qJQ@K2XUHk0YMS8@jFsuqwbQ3aey81HWztzn5ZHtPBUyoFP8xhMEVb@AA "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 40 bytes
```
{min map {abs [-] @$_},m:ex/^(.+)(.+)$/}
```
[Test it](https://tio.run/##RY7daoNAEIXv5ymGIEXR6I4pSayk5Lb3vesfRqcguKtkbUkRn6x3fTHrGGsXlplzvnPYbfhcbYcPy/i5DfMU9Bfe5HXBeBg6XRrUWYNddrL4tH7Bo/PWB/qOL9GrG/qeXCfqh7FzbNm2eMCqNGxd7@c7zGt9cqPnwo9EPZg2BXnlccyl0FSZQX8qpfBen@f@@h5dpzSBw5eG85YLDztALC3KlwR5AS4wwNXoSGmxVtAPpMQiIJKpgOJZb2TGQGoBe1luYXNFNFpKzakdxclEY9jTX3IHyXSu/eRfJEqpXw "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
min
map
{
abs
[-] # reduce with &infix:«-»
@$_ # the input of this inner block as a Positional
},
# split 「$_」 into 2 in every possible way
m
:exhaustive
/^ (.+) (.+) $/
}
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~195~~ ~~189~~ ~~154~~ ~~117~~ 112 bytes
*35 bytes saved thanks to Eminga*
```
A*H:-findall(X,(between(0,A,I),r(A,I,X)),L),sort(L,[H|_]),!.
r(A,B,C):-Z is 10**B,divmod(A,Z,X,Y),C is abs(X-Y).
```
[Try it online!](https://tio.run/##FckxCoMwGAbQvaewW/7wJUTo5KYuFjxAtJSiJC2B1JRE6tK7pzq94X1i8OEl0uZyrnlXiadbzOQ902CzXTdrF6ZQ40qIbAeaCD0hhbiyHrfu97gTzvJ0bIOWKjEWLhWl4ryBcd93MPuM0BgI7VHTnJgWA8mcS3XhWv4B "Prolog (SWI) – Try It Online")
This is my first try at prolog golfing so it may be a bit horrendous. Here is how it works.
At the highest level we have `*`. `*` takes `A` and `H`, and determines if `H` is the smallest way to split `A`.
```
A*H:-
findall(X,(between(0,A,I),call(r,A,I,X)),L),
sort(L,[H|_]),
!.
```
The first line here uses a technique from [this SO post](https://stackoverflow.com/a/47868877/4040600), to essentially perform a map of the predicate `r(A)` over the integers from `0` to `A`. Since `r` confirms the values of each partitions this will give us the values of all possible partitions, plus a whole load of extra junk. All these partitions will be stored in `L` in no particular order. Once that is done we sort the list to find the smallest element. We then use a cut to prevent backtracing.
Next we have the definition of `r`.
First `r` calculates the two results of the split naming them `X` and `Y`.
```
r(A,B,C):-
Z is 10**B,
divmod(A,Z,X,Y),
C is abs(X-Y).
```
Then we assert that `C` is the difference of them and is positive.
```
C is abs(X-Y).
```
[Answer]
# C, 94 bytes
```
c,r,d,a;f(n){for(c=1,r=0,d=n<11?1:n;n;r+=n%10*c,c*=10,n/=10)a=abs(r-n),d=r&&a<d?a:d;return d;}
```
[Try it online!](https://tio.run/##fc2xDoIwEAbgnadoTCAtltiDQaA0vIhLbcUweJoTJ8KzY8PgYso/3HDf5T9X3J1bVydJemn1wFHMw5O4MyDJKOkNdgA9tKhR09FgCip30uUGlMRTmMIae31zKlCEa8oy2/netl7TbfoQMq@XdcSJPeyIXCRzwkJeFFYDP6T@ggfJBh56hI4QxKmMUxUntddYR63a7VRxPEPZRLGGvZ/Nln8OyH68@bJ@AQ)
[Answer]
# [Python 2](https://docs.python.org/2/), 51 bytes
```
f=lambda n,k=1:min(abs(n/k-n%k),k/n*n or f(n,10*k))
```
[Try it online!](https://tio.run/##NY1BCoMwEEXX7Sn@JmgkYiYKGsHeRSlSSR3F6qKnt9OUDrwZ3mze@t4fC7vzHLtnPw/3HmxCR@08cdoPr5SLkLMK2oSCM8ayYUzZkM2C1ucoypgYZA2IBCeUgo3SGJQ/tbJrct6gofj3cf7Xt9fLuk28I1H1gfwGVR0JFKT1DUrrAw "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~68~~ 65 bytes
```
f x=minimum[abs$read(take i x)-read(drop i x)|i<-[1..length x-1]]
```
[Try it online!](https://tio.run/##HcexCoAgEADQXznCoQaDa2qoLxGHC7WO1MQMHPp3g972DrpP631rDuoaOHJ4gqLtFtmS6QudFhjqIP@afKW/Ly9S4Th6G/dyQJWodQvEcU2ZYxEOuhlxmrv2AQ "Haskell – Try It Online")
## Explanation
```
minimum -- Minimum of ...
[abs$ -- The absolute value of ...
read(take i x) -- The first i characters of x
- -- Minus ...
read(drop i x) -- The last i characters of x
|i<-[1..length x-1] -- From i=1 to i=length x - 1
]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
ḌÐƤḊạḌƤṂ
```
[Try it online!](https://tio.run/##y0rNyan8///hjp7DE44tebij6@GuhUAOkLmz6f/RPS6H2x81rVFx///f0EBHwdAQiI2A2BiIDcAcCx0FYwjXAEiaGxpZ6ihYGILFLcEARlsCAA "Jelly – Try It Online")
-1 byte thanks to Dennis. Input is a list of digits.
**Explanation**
```
ḌÐƤḊạḌƤṂ
ḌÐƤ Convert to integer from decimal for all Ƥostfixes. [1,2,3]->[123,23,3]
Ḋ Remove the first element ->[23,3]
ḌƤ Convert to integer from decimal for all Ƥrefixes [1,2,3]->[1,12,123]
ạ Absolute difference. [23,3]ạ[1,12,123]->[22,9,123]
Ṃ Minimum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
I⌊Eθ↔⁻I…θκI✂θκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczLzO3NFfDN7FAo1BHwTGpGCRUWgyRda5Mzkl1zsgHy2VrauoogIWDczKTU6FCEGD9/7@hkcV/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Conveniently I get to use the 2-arg variant of `Slice`. Explanation:
```
θ Input string
E Map over characters
θ θ Input string
κ κ Current map index
… Mold to length (i.e. head)
✂ Slice (i.e. tail)
I I Cast to integer
⁻ Subtract
↔ Absolute value
⌊ Minimum
I Cast to string
Implicitly print
```
[Answer]
# [Funky](https://github.com/TehFlaminTaco/Funky), ~~159~~ ~~134~~ 99 bytes
```
s=>{S={}fori=1i<#s i++{S[#S]=(((v=s::sublist)(0,i)::[[email protected]](/cdn-cgi/l/email-protection)(i)::reduce@..)^2)^.5};math.min...S}
```
Actually fitting the spec is shorter it seems.
[Try it online!](https://tio.run/##VcdLCsIwEADQqxS6maE62IJQoiPeIUuxoLHFQRsln4KEnD26lbd6U7SPTzFcPB@S5pSnlxNuZV/7Spom6VOtzwwAC3ulfLw@xQeEzUpQKTfeohmPROsF/o5DhwNt826@hDvNYolI5/J2YgMYSH3V/nRVnxHLFw "Funky – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), 36 bytes
```
\B
,$'¶$`
\d+
$*
(1*),\1
Om`^.*
\G1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP8aJS0dF/dA2lQSumBRtLhUtLg1DLU2dGEMuLv/chDg9La4Yd8P//w0NuAwNuQyNuAyNuQwNQCwLLmMw28CYy9zQyJLLEggA "Retina – Try It Online")
### Explanation
```
\B
,$'¶$`
```
This generates all possible partitions on separate lines, as well as a trailing line with the original input.
```
\d+
$*
```
Convert each number in each partition to unary.
```
(1*),\1
```
Remove a maximal and equal amount of `1`s from both parts of each partition (i.e. remove the minimum, and subtract it from the maximum, which gives the absolute difference).
```
Om`^.*
```
Sort the lines.
```
\G1
```
Count the `1`s on the first line, which gives the minimal absolute difference.
[Answer]
# [J](http://jsoftware.com/), 32, 27 23 bytes
-5 bytes thanks to FrownyFrog! -4 bytes if input is a string.
```
[:<./}:@(".\)|@-1}.".\.
```
[Try it online!](https://tio.run/##y/qfbmulYKAAxP@jrWz09GutHDSU9GI0axx0DWv1gCy9/5pcSnoK6mm2euoKOgq1VgrpXFypyRn5CmkK6oYG6goIjiEyxwiZY4zMMUBVZ4HEM0ZTaYDMNTc0skTiWhii6rUEA3U0PlDHfwA "J – Try It Online")
Original:
Takes a number as input
```
(".\(}:@[([:<./|@-)}.@])".\.)@":
```
## How it works:
```
@": - convert the number to list of chars and
(".\ ".\.) - form all prefixes/suffixes and convert them to numbers
(}:@[ }.@]) - drop the last prefix / first suffix
( |@-) - find the absolute differences
[:<./ - find the minimum
```
[Try it online!](https://tio.run/##y/qfbmulYKAAxP81lPRiNGqtHKI1oq1s9PRrHHQ1a/UcYjWBwnqaDkpW/zW5lPQU1NNs9dQVdBRqrRTSubhSkzPyFdIUDA0U4ExDBNMIwTRGMA2QVVjA2cYoagwQHHNDI0s4x8IQWY8lGKBxLRX@AwA "J – Try It Online")
[Answer]
# JavaScript (ES6), 64 bytes
Takes input as a string.
```
f=([c,...s],l=0)=>c?Math.min(Math.abs((l+=c)-s.join``),f(s,l)):l
```
### Test cases
```
f=([c,...s],l=0)=>c?Math.min(Math.abs((l+=c)-s.join``),f(s,l)):l
console.log(f("10" )) // -> 1
console.log(f("11" )) // -> 0
console.log(f("12" )) // -> 1
console.log(f("13" )) // -> 2
console.log(f("101" )) // -> 0
console.log(f("128" )) // -> 4
console.log(f("313" )) // -> 10
console.log(f("1003" )) // -> 2
console.log(f("7129" )) // -> 42
console.log(f("81128" )) // -> 47
console.log(f("999999" )) // -> 0
console.log(f("9999999")) // -> 9000
```
### Commented
```
f = ([c, ...s], // c = current character, s = array of remaining characters
l = 0) => // l = left part of the integer, initialized to 0 (see footnote)
c ? // if c is defined:
Math.min( // return the minimum of:
Math.abs( // 1) the absolute value of:
(l += c) - // the updated left part
s.join`` // minus the right part
), // end of Math.abs()
f(s, l) // 2) the result of a recursive call
) // end of Math.min()
: // else:
l // stop the recursion by returning l (now equal to the input)
```
---
# Non-recursive (ES7), 65 bytes
Takes input as a string.
```
s=>Math.min(...[...s].map(c=>((l+=c)-s.slice(++i))**2,i=l=0))**.5
```
### Test cases
```
let f =
s=>Math.min(...[...s].map(c=>((l+=c)-s.slice(++i))**2,i=l=0))**.5
console.log(f("10" )) // -> 1
console.log(f("11" )) // -> 0
console.log(f("12" )) // -> 1
console.log(f("13" )) // -> 2
console.log(f("101" )) // -> 0
console.log(f("128" )) // -> 4
console.log(f("313" )) // -> 10
console.log(f("1003" )) // -> 2
console.log(f("7129" )) // -> 42
console.log(f("81128" )) // -> 47
console.log(f("999999" )) // -> 0
console.log(f("9999999")) // -> 9000
```
### Commented
```
s => // given s
Math.min(... // get the minimum value in the result of this map():
[...s].map(c => // for each character c in s:
((l += c) // append c to l (the left part)
- s.slice(++i)) // and subtract the right part from it
** 2, // square the result
i = // start with i = 0 (split position)
l = 0 // and l = 0 (left part, see footnote)
) // end of map()
) // end of Math.min()
** .5 // return the square root of the smallest square
```
---
**Note**: In both versions, `l` is coerced to a string on the first iteration. Normally, we should be careful about leading zeros in a numeric literal: `0123 - 10 === 73` because `0123` is parsed as an octal value (this is now deprecated, but still valid in non-strict mode). But `'0123' - '10' === 113`, the leading zero being this time ignored. So, it's sound to do so.
From the [specification](https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber-applied-to-the-string-type) of the abstract operation `ToNumber` applied to a string:
>
> A StringNumericLiteral that is decimal may have any number of leading
> 0 digits
>
>
>
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 27 bytes
```
{⌊/|-/⍎¨↑⊂∘⍵¨↓1,∘.=⍨⍳¯1+≢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqRz1d@jW6@o96@w6teNQ28VFX06OOGY96t4J4kw11gBw920e9Kx71bj603lD7UecioFwtUK@CuqGBOheIMoRQRhDKGEIZwEQtwLQxXNwAwjA3NLIEMywMYWoswQCJaakOAA "APL (Dyalog Unicode) – Try It Online")
**How?**
`¯1+≢⍵` - length of `n` minus 1
`∘.=⍨⍳` - identity matrix
```
1,∘.=⍨⍳3
1 1 0 0
1 0 1 0
1 0 0 1
```
`1,` - prepend `1` for each row
`↓` - split by rows
`⊂∘⍵¨` - for each, partition the string by it
```
1 0 1 0 ⊂ '7129'
┌──┬──┐
│71│29│
└──┴──┘
```
`↑` - flatten
`-/` - reduce each pair with subtraction
`|` - take absolute values
`⌊/` - minimum
---
# [APL (Dyalog)](https://www.dyalog.com/), 35 bytes
```
{⌊/|-/⍎¨(⊂∘⍵⍤1)1,∘.=⍨⍳¯1+≢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqRz1d@jW6@o96@w6t0HjU1fSoY8aj3q2PepcYahrqADl6to96Vzzq3XxovaH2o85FQLlaoE4FdUMDdS4QZQihjCCUMYQygIlagGljuLgBhGFuaGQJZlgYwtRYggES01IdAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ŒṖṖLÐṂḌIAṂ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pwGRz@EJD3c2PdzR4@kIpP9bH25XedS0xv3/f0MDHQVDQyA2AmJjIDYAcyx0FIwhXAMgaW5oZKmjYGEIFrcEAxhtCQA "Jelly – Try It Online")
-3 bytes thanks to dylnan
## How it works
```
ŒṖṖLÐṂḌạ/€Ṃ - Main link. Argument: n (integer) e.g 7129
ŒṖ - Partitions of n's digits; [[7, 1, 2, 9], [7, 1, [2, 9]], [7, [1, 2], 9], [7, [1, 2, 9]], [[7, 1], 2, 9], [[7, 1], [2, 9]], [[7, 1, 2], 9], [7, 1, 2, 9]]
Ṗ - Remove the final element [[7, 1, 2, 9], [7, 1, [2, 9]], [7, [1, 2], 9], [7, [1, 2, 9]], [[7, 1], 2, 9], [[7, 1], [2, 9]], [[7, 1, 2], 9]]
ÐṂ - Keep the lists with the minimum... [[7, [1, 2, 9]], [[7, 1], [2, 9]], [[7, 1, 2], 9]]
L - length
Ḍ - From digits [[7, 129], [71, 29], [712, 9]]
/ - Reduce...
€ - ...each...
ạ - ...by absolute difference [122, 42, 703]
Ṃ - Take the minimum 42
```
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
lambda n:min(abs(n%10**i-n/10**i)for i in range(len(`n`)))
```
[Try it online!](https://tio.run/##PYlBCsIwEEX3nmI2QqaMmEkWNgVv4qIpNjrQTkvajaePNIh/8x7vr5/9vagr6f4oU5yHZwTtZlETh83omW3TyEWvlZiWDAKikKO@RjONanrtEbH8H7bETOyIPbE9rCVf3Xq6sQvU8tFC3Q@hOwGsWXSHZATLFw "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
hSmaFvMdfqlT2./
```
[Try it online!](https://tio.run/##K6gsyfj/PyM4N9GtzDclrTAnxEhP//9/JXNDI0slAA "Pyth – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
"GX@:&)UwU-|vX<
```
Input is a string representing the integer.
[Try it online!](https://tio.run/##y00syfn/X8k9wsFKTTO0PFS3pizC5v9/dQtDQyMLdQA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmfEOH1X8krwsFKTTO0PFS3pizC5n@sS8h/dUMDdS51Q0MQYQQijEGEAYRvASSNoSIGIMrc0MgSSFkYQuQswQDOsFQHAA).
### Explanation
```
" % Implicit input. Do the following as many times as input length
G % Push input
X@ % Push iteration index (1-based), k
: % Range: gives [1 2 ... k]
&) % Two-ouput reference indexing: gives a substring with the first
% k characters in the input and then a substring with the rest
U % Convert to number
wU % Swap, convert to number
-| % Absolute difference
v % Vertically concatenate stack. This concatenates the obtained
% absolute difference with the minimum so far; does nothing in
% the first iteration
X< % Minimum of array
% Implicit end. Implicit display
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes
```
Min@Abs[#-#2&@@FromDigits/@#&/@ReplaceList[#,{a__,b__}:>{a}|{b}]]&
```
Takes a list of digits.
[Try it online!](https://tio.run/##XYrLCsIwEEX3@Y1AFzLS18JWUEYQVwritpSQllQDpkqTXcy3x4ZAEZnFOffeUdw8hOJG9twPO3@RIx463dA1LRLE0/RSR3mXRqdIkxRv4v3kvThLbRoKljMGHWNuu7fcfWzn2jbx10mOBldDipYQm0PmICCPKCLKiGypoQpSws@URd1AmOug1azLbw3L/cW5IMT5Lw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~106~~ 83 bytes
```
import StdEnv
@n#f=toInt o(%)n
=hd(sort[abs(f(0,i)-f(i+1,size n))\\i<-[0..size n]])
```
Defines the function `@`, taking a string.
Mostly self-evident, the only tricky bit is `f=toInt o(%)n`: This takes the `toInt` class of functions, and composes it (`o`) with the curried slice operator class (`%`) already supplied with the first argument (`n`). Since there is only one type (`String`, equivalent to `{#Char}`) which has overloads for both `%` and `toInt` the line actually compiles, whereas normally it's hard to compose functions when golfing due to the lack of contextual information given to the compiler.
[Try it online!](https://tio.run/##TU87a8NADN79KwShcEflcBcPjSGGDO0Q6ObR9nD1IxXYOuNTCu2P79V5DNWg7yU@UDv2juPku8vYw@SII02zXwRK6d74KznyZijEn1jAqyfNSfHZqbAeVO4jqEEZJJ0Oip4tBvrpgbWuazqkldlu70bT6FiKWyTZEM8XCVBAZQ1ai3aHNkNrrmyP2Y2bDF/sLse9vXr5bR6QN/8rxJeyEJ@BoK7XdUjhHjZJsX4yw/Gh4287jO4cYnp6j6/f7CZqwx8 "Clean – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JṬ€œṗ€⁸Ḍạ/€Ṃ
```
A monadic link taking a list of digits and returning the integer.
**[Try it online!](https://tio.run/##y0rNyan8/9/r4c41j5rWHJ38cOd0IP2occfDHT0Pdy3UB3Ie7mz6//9/tLmOoY6RjmUsAA "Jelly – Try It Online")**
### How?
```
JṬ€œṗ€⁸Ḍạ/€Ṃ - Link: list of digits e.g. [7,1,2,9]
J - range of length [1,2,3,4]
Ṭ€ - untruth €ach [[1],[0,1],[0,0,1],[0,0,0,1]]
⁸ - chain's left argument [7,1,2,9]
œṗ€ - partition at truthy for €ach [[[],[7,1,2,9]],[7,[1,2,9]],[[7,1],[2,9]],[[7,1,2],9]]
Ḍ - undecimal (vectorises) [[0,7129],[7,129],[71,29],[712,9]]
/€ - reduce €ach by:
ạ - absolute difference [7129,122,42,703]
Ṃ - minimum 42
```
[Answer]
# Pyth, 10 bytes
```
hSaMv<./Ql
```
[Test suite](https://pyth.herokuapp.com/?code=hSaMv%3C.%2FQl&test_suite=1&test_suite_input=%2210%22%0A%2211%22%0A%2212%22%0A%2213%22%0A%22101%22%0A%22128%22%0A%22313%22%0A%221003%22%0A%227129%22%0A%2281128%22%0A%22999999%22%0A%229999999%22&debug=0)
Takes input as a string.
This uses one of Pyth's more recent features, which is that applying a function to a list defaults to mapping the function over the list, if no other behavior is defined. This means that `v` applied to a list of list of strings evaluates all of the strings.
```
hSaMv<./Ql
hSaMv<./QlQ Implicit variable
./Q Form all partitions of the input string.
Split it in all possible ways, maintaining the order.
Partitions are ordered from shortest to longest.
< lQ Take the prefix as long as the input string.
This keeps just the splits into one and two pieces.
v Evaluate. All strings are converted to numbers.
aM Map the absolute difference function.
hS Minimum
```
Note that the list of splits allows the split into 1 piece, but the value of this will always be larger than the minimum, so it is safely ignored.
[Answer]
# [Tcl](http://tcl.tk/), 116 bytes
```
foreach d [split [set b [set R $argv]] {}] {append L $d
regexp .(.+) $R - R
set b [expr min($b,abs($L-$R))]}
puts $b
```
[Try it online!](https://tio.run/##LYuxCsIwFEX3fMUd3pCg7e4/dMoqGZImrYVaH0kUQfrtrxE9cDlw4dRxFZkeOfnxhohr4XWpTaki/GRBPs8v5/DZ2zxz2iIGUFQ5zenN6HV/MiCLDlb9y/Zn3JdNUzj7UDQNHVlj3K74WQsoiMjlywE "Tcl – Try It Online")
**Explanation**
```
b ← R ← input number
for each digit (d) in the input number:
L += d
strip first digit off of R using a regular expression
b ← min( b, distance between L and R )
print b
```
It works by using a regex trick allowing a degenerate final case that will always compute to greater than the minimum difference. For “12345” the values are:
```
1 2345 → 2344
12 345 → 333
123 45 → 78
1234 5 → 1229
12345 5 → 12340 (degenerate case)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
```
->a{((w=1)..a).map{((a%w*=10)-a/w).abs}.min}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xWkOj3NZQU08vUVMvN7EAyE1ULdeyNTTQ1E3UL9fUS0wqrtXLzcyr/V@gkBZtaGAYywVimBsaWcb@BwA "Ruby – Try It Online")
[Answer]
# APL+WIN, 31 bytes
```
⌊/|(⍎¨m↓¨⊂n)-⍎¨(m←⍳¯1+⍴n)↑¨⊂n←⎕
```
Prompts for screen input of integer as a string.
Explanation:
```
m←⍳¯1+⍴n Create a list of numbers from 1 to length of string - 1
↑¨⊂n←⎕ Using m create a nested vector taking successively characters from the front of the string defined by m
⍎¨ Convert from character to integer
(⍎¨m↓¨⊂n) Using m create a nested vector dropping successively characters from the front of the string defined by m
⌊/| take the minimum absolute value after subtracting the two vectors of integers
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~51~~ 41 + 1 (`-p`) = 42 bytes
```
$\=$_;$\=$\>($"=abs$'-$`)?$":$\while//g}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxlYl3hpExthpqCjZJiYVq6jrqiRo2qsoWanElGdk5qTq66fXVv//b2hk8S@/oCQzP6/4v66vqZ6BocF/3QIA "Perl 5 – Try It Online")
*inspired by @Nahuel-Fouilleul's comment*
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 112 107 + 18 = 125 bytes
```
n=>Enumerable.Range(1,n.Length-1).Min(i=>System.Math.Abs(int.Parse(n.Remove(i))-int.Parse(n.Substring(i))))
```
[Try it online!](https://tio.run/##nVA9a8MwFNz9K0QmCWJhJ0MTUhtCaaYYTDJ0KB1k98URxE@tnhwoJb/dVeLQD@hQ9QYN9@7e3VNNcW0s9B1pbNj2jRy0cq3xdRFFqFqgF1UDWyltl1QaIl0dIHqPmEd9UESstKaxqr0wA38GOeV0zY5GP7NCaeTkrA94fGLKNiQ@dV@OM67xqw7r28EwZhpdznYsYz1m@T12LVjlO8iNwgZ4Oka5BmzcPk6FLHyQzvLrmkK5vVxWxP0KWSpLwFFuoDVH4FqI@Du97aoh8DwRovfX/1LsziAZn/1gtQP/ScB3fJQmIyEWf5enYfJJmHwaJk9C28yC9NPgPkmY4SadzIMMszT0hvkF/7D89Jyi4T31Hw "C# (.NET Core) – Try It Online")
The count includes the 18 bytes in `using System.Linq;`. Takes input as a `string`.
* 5 bytes saved by Caius Jard!
[Answer]
# Common Lisp, 131 bytes
My first time participating in code golf and I decided to use Lisp, since I like it.
Here is my solution:
```
(defun f (s) (loop for i from 1 below (length s) minimizing (abs (- (parse-integer (subseq s 0 i)) (parse-integer (subseq s i))))))
```
Input needs to be a string, not integer or list.
] |
[Question]
[
Without taking any input, output this exact text:
```
A
B A
C B A
D C B A
E D C B A
F E D C B A
G F E D C B A
H G F E D C B A
I H G F E D C B A
J I H G F E D C B A
K J I H G F E D C B A
L K J I H G F E D C B A
M L K J I H G F E D C B A
N M L K J I H G F E D C B A
O N M L K J I H G F E D C B A
P O N M L K J I H G F E D C B A
Q P O N M L K J I H G F E D C B A
R Q P O N M L K J I H G F E D C B A
S R Q P O N M L K J I H G F E D C B A
T S R Q P O N M L K J I H G F E D C B A
U T S R Q P O N M L K J I H G F E D C B A
V U T S R Q P O N M L K J I H G F E D C B A
W V U T S R Q P O N M L K J I H G F E D C B A
X W V U T S R Q P O N M L K J I H G F E D C B A
Y X W V U T S R Q P O N M L K J I H G F E D C B A
Z Y X W V U T S R Q P O N M L K J I H G F E D C B A
```
## Rules
* Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* A single trailing newline is acceptable, but no other formatting changes are allowed.
* Capital letters are required.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
[tail$do c<-reverse a;' ':[c|c<=d]|d<-a]
a=['A'..'Z']
```
[Try it online!](https://tio.run/##DcYxEsIgEADA3ldckZmryAMUCt9gJ1LcHKcynsgASZW3S7LVvql9RHVU9xi@U9Ip/oCtqbJKbQJ0QcCz542ti2GL1lA4kfN4xXnGO4bxpZTBQVn6rVeYYMmasrRjdfz5qfRqw3ApOw "Haskell – Try It Online")
This uses that each line has exactly 25 spaces. So, instead of separately handling the prefix spaces and the spaces between letters, we take 26 spaces, and decide whether to put a letter after each. This unfortunately gives one extra leading space, which we remove.
---
**54 bytes**
```
foldl(\m c->map(' ':)m++[c:' ':last m])["A"]['B'..'Z']
```
[Try it online!](https://tio.run/##FcZRCoMwDADQqwQZRBE9gKCwXWF/1n6ETp0sqaWt1ze69/W@lH4zs8Z@0mXnD5eTgGsGoVAiYFdJXRvX/cuUMoitTPEsrMEXti2OaFVo89BDOPI7R3jA4Xnzc7oX9XQL05q0cSFc "Haskell – Try It Online")
---
**55 bytes**
```
"A"%['B'..'[']
s%(h:t)=((' '<$t)++s):(h:' ':s)%t
s%_=[]
```
[Try it online!](https://tio.run/##DcpBCoMwEEDRfU8xiGESpB4gmEV7hS5TkSBWxRhCZrx@xyz/42@BjiVGKe4rzatRHt/Y9@hxfJDSm2XjtEbAoWXTdWRstZqWjOJ6TM6PcoY9gYN88YcLtHCluKeFoMh//sWwkjznnG8 "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~82 79 77 75~~ 74 bytes
*Saved 2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
*Saved 1 byte thanks to [@gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)*
Derived from my 2nd JS answer.
```
f(x,y,s){for(x=0,y=25;~y;putchar(s>51?x=!y--,13:s&x>y?90-s/2:32))s=++x+y;}
```
[Try it online!](https://tio.run/##BcFBCoMwEADAu69IL2WXJFQjHjRE3yIpqR6s4tqyi9ivpzPRvmLMOQEbMYRnWnfgUBoJrvE/8dvniNO4A/VNNXC4ibWmqju6cy9DW1p6uK52iBS0Zi3@yt91fqplnN@A6iyUSoC@uPIf "C (gcc) – Try It Online")
### How?
We start with \$x=0\$ and \$y=25\$. We increment \$x\$ at the beginning of the line. We set \$x\$ to \$0\$ and decrement \$y\$ at the end of the line, which is reached when \$x+y=52\$. We stop when \$y=-1\$.
This gives:
```
0 1 2 3
123456789012345678901234567890...
25 .........................A
24 ........................B.A
23 .......................C.B.A
22 ......................D.C.B.A
21 .....................E.D.C.B.A
⋮
```
We append a letter when \$x+y\$ is odd and \$x\$ is greater than \$y\$, or a space otherwise.
The ASCII code of the letter at \$(x,y)\$ is given by:
$$90-\left\lfloor\frac{x+y}{2}\right\rfloor, (x+y)\equiv 1 \pmod 2$$
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~7~~ 9 bytes
```
UT↙Eα…α⊕κ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJb88zyc1rURHwTexQCNRR8G5Mjkn1TkjH8zxzEsuSs1NzStJTdHI1gQC6////@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
α Uppercase alphabet
E Map over characters
α Uppercase alphabet
… Truncated to length
κ Current index
⊕ Incremented
↙ Output with a 135° rotation
```
Effectively, this starts with the `A` in the bottom right corner, then works its way to the top left printing longer and longer prefixes of the uppercase alphabet each time, each prefix being printed towards the bottom left. The `UT` simply suppresses Charcoal's default rectangular output, apparently needed for this question for some reason.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), ~~16, 15~~, 12 bytes
```
¬ZAòé hòòxâÄ
```
[Try it online!](https://tio.run/##K/v//9CaKMfDmw6vVMgAkpsqDi863PL/PwA "V (vim) – Try It Online")
Hexdump:
```
00000000: ac5a 41f2 e920 68f2 f278 e2c4 .ZA.. h..x..
```
Thanks to Kritixi Lithos for helping me golf a few off.
Explanation:
```
¬ZA " Insert every character between 'Z' and 'A'
" The cursor is on the 'A'
ò ò " Recursively...
é<space> " Insert a space
h " Move back one character
" If we're on the first column, this will break the loop
ò " Recursively...
x " Delete the current character
â " Stop looping if there's only one non-whitespace character on this line
Ä " Duplicate this line upward
```
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html), 686 bytes
```
the a-b-c corner
i was a child of ten or eleven
i said i am smart,i am likely to get an answer
i got a chance to read papers,novels or some old poetry
i read in class
as i read,i paused a bit
the words,i do admit,were a huge issue
please tutor,i said,i desire a nap
i truly do not
i fibbed
i am hiding a r-real g-great l-lie,a secret
i am idiot,i cant t-truly r-r-read
i think im reading,really im no smart reader
i need a lesson,i say,i really do
not a whole lot of people are helping teach me
i want a tutor,i say,i really want someone smart
i call a skilled tutor on my phone
as i call a person,i see a letter key,then i press down
it worked!i see a letter shape
amazing start for me
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?XVLRrp0wDHvnK7J3@KjQ5tCK0qAmDLGfv3PL1TZNQmrVOI4d40mIl3UJFLRVaVOmm42YQsolkn7Ib51yJQtJtVAm4xxx8EF2cPNpXEvepTzkSps4ccVn92Db1Acb1yC93oQjnXxKs7nqTylG2sj0EFIMPFW8PegbOMwNhc0mSHqf5ozmyySCdM0@OfTf2qKhEJU4HtlnTIYrStcmlM0umc4ibJh/ubb59dAbxPJAVj4x0tsFD2Cp2m198rpKfP2lHHPdgGwLVBTalg2nU1lKlpnJJDT53gWg6mAPXJ18eVnR1zs7nadcd8rH8APWuTMCgpeq71JHaayvyrBaxEzrUP7MYxNlSJ3qWO@dtAgV3BHYKQq7xHCWpJxdtwuHRIeMdGvv@LuJf/hGrUehVf6kG1BCg@25FGgZjaSVjofOBOCbzTeqx/rqFBmy3aXRLs@MoCpwZ4MTCL/rlL0nt0v88R/cEn6PiQ/@1bWb94V8MPSQr6@V428)
Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + common GNU tools, 42
```
echo {Z..A}|sed -n ':l;p;s/[B-Z]//;tl'|tac
```
### Explanation
* `echo {Z..A}` is a bash brace expansion that outputs `Z Y X W V U T S R Q P O N M L K J I H G F E D C B A`
* The sed expression is a loop that:
+ `:l` Define a label l
+ `p`rint the current pattern space
+ `s/[B-Z]//` match the first instance of B-Z and replace it with ""
+ `tl` if a match occurred above, jump back to label l
+ (implicit) otherwise quit. `-n` suppresses implicit output of the pattern space at the end of line processing.
* The output of the sed is the required triangle, but upside down. The `tac` reverses it line-by-line to give the required output.
[Try it online!](https://tio.run/##S0oszvj/PzU5I1@hOkpPz7G2pjg1RUE3T0HdKse6wLpYP9pJNypWX9@6JEe9piQx@f9/AA "Bash – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 34 bytes
```
((32#~26-#)<@u:@,32,@,.65+|.)\i.26
```
[Try it online!](https://tio.run/##LY5BS8NAFITv@ysGC9rQdCkp5hCsRAUPUjyI4MXLZvu2uxLeSvZFFMS/Hrehpwcz37yZj8lhpy80Nmg2WGs8vOwfp@VyWy3@qnq9KG7asWnLbVW2pa6vV7@6eA@6qqdCPd9rvHqC6eIXYSAZB04wcCNbCZGzlMZeGszkHfqQBNGhi9@UQMZ62MhiAgc@5tzJn9E3AhMdzmBgPKEja8ZEkNzXB86yN7n0EJyjgVjQEx/FJzU/2JNcJXzmSfKTT8j@KXjeoxRZHy9v4dT0Dw "J – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 37 bytes
```
25..0|%{' '*$_+[char[]]((90-$_)..65)}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/38hUT8@gRrVaXUFdSyVeOzo5I7EoOjZWQ8PSQFclXlNPz8xUs/b/fwA "PowerShell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 78 72 63 bytes
```
for(i in 1:26){cat(strrep(" ",26-i));cat(LETTERS[i:1],fill=52)}
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdDKyEyzOjmxRKO4pKgotUBDSUFJx8hMN1NT0xok6uMaEuIaFBydaWUYq5OWmZNja2qkWfv/PwA "R – Try It Online")
Nothing fancy. First print spaces, then print letters.
Improvement inspired by <https://codegolf.stackexchange.com/a/195078/89953>, but cannot comment there because of reputation.
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
i=26
s='A'
while i:i-=1;print' '*i+s;s='%c '%(91-i)+s
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWyIyr2FbdUZ2rPCMzJ1Uh0ypT19bQuqAoM69EXUFdK1O72Boor5qsoK6qYWmom6mpXfz/PwA "Python 2 – Try It Online")
We take care not to introduce any trailing spaces, which means avoiding `center` and also avoiding adding a space with `A` for the first row.
[Answer]
# [Python 3](https://docs.python.org/3/), 76 75 bytes:
-1 byte thanks to [@pppery](https://codegolf.stackexchange.com/users/46076/pppery)
```
for i in range(27):print((27-i)*' '+' '.join(chr(64+i-x)for x in range(i)))
```
[Try it online](https://tio.run/##K6gsycjPM/7/Py2/SCFTITNPoSgxLz1Vw8hc06qgKDOvRAPI1M3U1FJXUNcGYr2s/Mw8jeSMIg0zE@1M3QpNkL4KhL5MTU3N//8B).
Another **75 bytes**:
```
for i in range(27):print(' '.join(chr(64+i-x)for x in range(i)).center(51))
```
[Try it online](https://tio.run/##Rco7CoAwDADQq2RrgljwD95GSrVxSEvoUE8fcfLNrzw1ZZnMzqzAwAJ6yBVx3GgvylLRgfN3ZsGQFNe5477Rl9ufmciHKDUqLgOR2Qs).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~57~~ 54 bytes
```
?A.upto(?Z){puts' '*(90-_1.ord)+[*?A.._1].reverse*' '}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN83sHfVKC0ryNeyjNKsLSkuK1RXUtTQsDXTjDfXyi1I0taO1gCr04g1j9YpSy1KLilO1gCpqIbqhhsAMAwA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 76 bytes
```
Array[StringRiffle[Reverse@ToUpperCase@Alphabet[][[;;#]]]&,26]~Column~Center
```
[![enter image description here](https://i.stack.imgur.com/bQyyS.png)](https://i.stack.imgur.com/bQyyS.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;Båi ®¬¸Ãû
mx1
```
Saved a byte thanks to @Shaggy.
Gained 4 bytes due to fixing a bug.
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=O0LlaSCurLjD%2bwpteDE)
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~34~~ 33 bytes
-1 byte thanks to ngn
```
(-26-!26)$`c${,/32,'|65+!x}'1+!26
```
[Try it online!](https://tio.run/##y9bNz/7/X0PXyExX0chMUyUhWaVaR9/YSEe9xsxUW7GiVt1QGyjx/z8A "K (oK) – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 13 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
Z[± *ZL³- ××]
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNBJXVGRjNCJUIxJTIwJXVGRjBBJXVGRjNBJXVGRjJDJUIzJXVGRjBEJTIwJUQ3JUQ3JXVGRjNE,v=8)
Explanation:
```
Z[± *ZL³- ××]
Z[ ] map over the prefixes of the uppercase alphabet
± reverse the current prefix
* interleave it with spaces
ZL³- substract the loop index from 26
× that many spaces
× prepend the spaces to the prefix
```
[7 bytes](https://dzaima.github.io/Canvas/?u=JXVGRjNBJXVGRjNCJUIxJTIwJXVGRjBBJXVGRjNEJXVGRjBG,v=8) with padding with spaces. yep, 2x bytecount to "remove" them..
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 27 bytes
```
1_|^\(," "/+,a),a:`c$90-!26
```
[Try it online!](https://tio.run/##y9bNS8/7/98wviYuRkNHSUFJX1snUVMn0SohWcXSQFfRyOz/fwA "K (ngn/k) – Try It Online")
`!26` is `0 1`..`25`
`90-!26` is `90 89`..`65`
``c$` convert to chars: `"ZY`..`A"`
`a:` assign to `a`
`(,`..`),` prepend as a single element
* `+,a` flip enlist, i.e. make each char a length-1 string: `(,"Z";,"Y";`..`;,"A")`
* `" "/` join with spaces (in some dialects of k this may be `" "/:`)
`^\` without-scan, i.e. start with `"Z Y`..`A"`, then remove `"Z"`, then remove `"Y"`, etc, and collect intermediate results
`|` reverse
`1_` drop the first, as it's an all-spaces string
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ØALḶ⁶ẋṚżUK$ƤY
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//w5hBTOG4tuKBtuG6i@G5msW8VUskxqRZ//8 "Jelly – Try It Online")
A full program that prints the desired output to STDOUT.
## Explanation
```
ØA | Uppercase letters
L | Length (26)
Ḷ | Lowered range (0..25)
⁶ẋ | Space that many times (vectorises)
Ṛ | Reverse list
ż | Zip with:
$Ƥ | - Following applied to each prefix of the uppercase letters:
U | - Reverse
K | - Join with spaces
Y | Join with newlines
```
Without the final Y, a list of lists of Jelly strings woulf be returned, with the spaces and letters in separate sublists. As such, I’ve gone with joining the outer list with newlines and relying on Jelly’s default printing method to produce the correct output.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ASuηí».c
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fMbj03PbDaw/t1kv@/x8A "05AB1E – Try It Online")
```
A # push the alphabet, "abcdefghijklmnopqrstuvwxyz"
S # split to a list of chars
u # uppercase
η # prefixes
í # reverse each
» # join by newlines, joining sublists by spaces
.c # center
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 62 bytes
```
: f 25 for i spaces 25 i - for i 65 + emit ." "next cr next ;
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WymkKRiZKgB5CpkKxQWJyanFIH6mgi5UzMxUQVshNTezREFPSUFBKS@1okQhuUgBTFv/T/sPAA "Forth (gforth) – Try It Online")
### Code explanation
```
: f \ start a new word definition
25 for \ loop from 25 to 0
i spaces \ print loop-index spaces
25 i - for \ loop from (25 - loop-index) to 0
i 65 + \ add inner loop-index to 65 (ascii 'A')
emit \ output ascii char for value
." " \ output a single space
next \ end inner loop
cr \ output a newline
next \ end outer loop
; \ end word definition
```
[Answer]
# k4, 24 bytes
```
(-26-!26)$|:',\.Q.A,'" "
```
explanation:
```
.Q.A,'" " /append space to each capital letter ("A ";"B "; "C "; ... )
,\ /join scan, join each element successively and return intermediate results ("A ";"A B ";"A B C "; ... )
|:' /reverse each
(-26-!26)$ /left-pad each with -26 -27 -28 ...
```
run like:
```
q)k)(-26-!26)$|:',\.Q.A,'" "
" A"
" B A"
" C B A"
" D C B A"
..
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 35 bytes
```
25*
.
Y`.`RL
L^$w`^(..)*
$#1* $'
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8vIVEuBi0uPKzJBLyHIh8snTqU8IU5DT09Ti0tF2VBLQUX9/38A "Retina – Try It Online") Explanation:
```
25*
```
Insert 25 spaces.
```
.
```
Insert `.`s in all available positions. This results in 26 `.`s, because both the start and end can have a `.` inserted.
```
Y`.`RL
```
Cyclically transliterate the `.`s using a reversed uppercase alphabet.
```
L^$w`^(..)*
```
List all (necessarily overlapping) prefixes of even numbers of characters, in reverse order (i.e. longest prefix to shortest).
```
$#1* $'
```
For each prefix, output the number of pairs as a run of spaces (effectively deleting the letters) plus its suffix.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 82 bytes
```
v->{var x="";for(char c=64;++c<91;)System.out.printf("%"+(c-38)+"s%n",x=c+" "+x);}
```
[Try it online!](https://tio.run/##HU1Na8MgGL73V7wIBcVFKBtjw6aXnXcq7DJ6cG9jZ2Y06GtIKfntme3p4fnuzWSa/vy3ojc5w6dxAW4bgLH8eIeQyVCFKbozDNXjR0ouXL5PYNIli0cUoK8jqpDzypaA5GJQHzHkMnRp/1WrB7DtOjWH22QSzC1j2sbE8bcybF9ftJS4f99pcbxm6gYVC6mx3pDlbMskx@b5TUiWt4E9zS1KBkzOQi@rfrxbZRC7kXgo3ou7tmyW9R8 "Java (JDK) – Try It Online")
## Credits
* -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
[Answer]
# vim, 42 41 bytes
```
:set nf=alpha
aZ<ESC>qqYp<C-x>q24@qVggJqqYPxq24@q
```
`<ESC>` is 0x1b, `<C-x>` is 0x18, `<NL>` is 0x0a.
## Annotated
```
:set nf=alpha # make <C-x> work with letters
aZ<ESC> # put Z in buffer
qqYp<C-x>q # Record macro q: Append a line with the previous letter
24@q # ...and execute until we have all the letters
VggJ # combine all lines into "Z Y X ... C B A"
qqYPxq # Record macro q: Copy line to previous line, delete first char
24@q # ...and execute until we have all the rows
```
[Try it online!](https://tio.run/##K/v/36o4tUQhL802MacgI5ErMUq6sDCyQKLQyMShMCw93QvIC6gA8/7/BwA "V (vim) – Try It Online")
[Answer]
# Excel, 79 bytes
```
=LET(k,ROW(1:26),REPT(" ",26-k)&RIGHT(CONCAT(" "&CHAR(91-TRANSPOSE(k))),2*k-1))
```
Explanation
```
k,ROW ' k = 1..26
REPT(" ",26-k)&RIGHT(CONCAT(" "&CHAR(91-TRANSPOSE(k))),2*k-1) ' Final Calculation
REPT(" ",26-k) ' 26-k spaces
CONCAT(" "&CHAR(91-TRANSPOSE(k))) ' " Z Y ...
RIGHT( ,2*k-1) ' Right 2k-1 characters
```
[Answer]
# [Scratch](https://scratch.mit.edu/), ~~256~~ 240 bytes
-16 thanks to @Lyxal because I can't read! XD
[Try it online!](https://scratch.mit.edu/projects/514086333)
At first, I thought it would be shorter to add each string manually, but I was very wrong! It doesn't look very good outside of monospace fonts though...
```
delete all of[P v
set[A v]to[ABCDEFGHIJKLMNOPQRSTUVWXYZ
set[C v]to(25
set[L v]to(
repeat(26
set[S v]to(
repeat(C
set[S v]to(join(S)(
change[C v]by(-1
set[L v]to(join(join(letter(round((length of(L))/(2)))of(A))( ))(L
add(join(S)(L))to[P v
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~57~~ ~~52~~ 42 bytes
```
T`L`_L
}`^
Z
.
$.`$* $&$'¶
\B\w
$&
O`
G`.
```
[Try it online!](https://tio.run/##K0otycxL/P8/JMEnId6HqzYhjiuKS49LRS9BRUtBRU1F/dA2rhinmHIuIIfLP4HLPUHv/38A "Retina 0.8.2 – Try It Online") Explanation:
```
T`L`_L
```
Move all of the letters so far one step backwards in the alphabet, but delete any `A`.
```
^
Z
```
Prefix a `Z` to the current string.
```
}`
```
Repeat the above until the transformation becomes idempotent. This happens when the string is the entire alphabet; the `A` is deleted, the `Z-B` get transliterated into `Y-A`, and another `Z` is prefixed.
```
.
$.`$* $&$'¶
```
Turn the alphabet into a triangle.
```
\B\w
$&
```
Space out the letters.
```
O`
```
Get the lines in the correct order.
```
G`.
```
Remove an extraneous trailing newline. (Retina 0.8.2 always adds a trailing newline, so there would have been two; had I used Retina 1 I could have claimed that newline as my allowed newline.)
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~103~~ ~~93~~ 77 bytes
```
N &UCASE B LEN(1) . B @X :F(END)
A =B ' ' A
OUTPUT =LPAD(A,26 + X) :(N)
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/349TLdTZMdhVwUnBx9VPw1BTQQ/IdIhQsHLTcPVz0eTidFSwdVJQB0JHLk7/0JCA0BAFW58ARxcNRx0jMwVthQhNBSsNP00uoOr//wE "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
VlGp*dt-lGNjdr_<GhN1
```
Pretty happy with this, since it's my first Pyth answer. Probably can be golfed a lot
# Explanation
```
VlG for N in range(26)
p*dt-lGN 26-N spaces outputted
<GhN First N alphabet characters
_ Reversed
r Capitalised
j 1 Joined with spaces (space after each character)
```
[Try it online!](https://tio.run/##K6gsyfj/PyzHvUArpUQ3x90vK6Uo3sY9w8/w/38A "Pyth – Try It Online")
[Answer]
# [Python3](https://docs.python.org/3/), 91 bytes
```
for _ in range(26):print(f'{" ".join([*map(chr,range(65,91))][0:_+1][::-1]):^52}'.rstrip())
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFeITNPoSgxLz1Vw8hM06qgKDOvRCNNvVpJQUkvKz8zTyNaKzexQCM5o0gHosrMVMfSUFMzNtrAKl7bMDbaykrXMFbTKs7UqFZdr6i4pCizQENT8/9/AA)
*-1 byte thanks to @cairdcoinheringaahing*
] |
[Question]
[
# Round away from zero
Inspired by [Round towards zero](https://codegolf.stackexchange.com/q/190670/52194).
Given a number input via any reasonable method, round the number "away from zero" - positive numbers round up, and negative numbers round down.
If you intend to take the input as a string (via STDIN, for example), you should be able to handle numbers with or without the decimal point. If you take it as a number, it should at least be able to handle floating-point precision (double precision not required) or rational numbers.
You can output a floating-point number with the decimal point (e.g. 42.0) if desired. (Or even have some test cases output floating-point and some output integer, if it makes your answer shorter.)
Standard loopholes are not allowed, etc etc.
## Test cases
```
-99.9 => -100
-33.5 => -34
-7 => -7
-1.1 => -2
0 => 0
2.3 => 3
8 => 8
99.9 => 100
42.0 => 42
-39.0 => -39
```
[Sandbox Link](https://codegolf.meta.stackexchange.com/a/18016/52194)
[Answer]
# Excel, 13 bytes
```
=ROUNDUP(A1,)
```
### Alternative
```
=EVEN(A1*2)/2
```
[Answer]
# R, 32 bytes
```
x=scan()
sign(x)*ceiling(abs(x))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ĊṠ¡Ḟ
```
A monadic Link accepting a number which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8//9I18OdCw4tfLhj3v///3WNjfVMAQ "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8//9I18OdCw4tfLhj3v/D7Y@a1vz/H61raalnqaOga2ysZwqkzIHYUM9QR8FAR8FIz1hHwUJHAaQiFgA "Jelly – Try It Online").
### How?
```
ĊṠ¡Ḟ - Link: number, N
¡ - repeat...
Ṡ - ...number of times: sign of N (repeating -1 is the same as 0 times)
Ċ - ...action: ceiling
Ḟ - floor (that)
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 18 bytes
```
d->d.setScale(0,0)
```
[Try it online!](https://tio.run/##VZBBT4QwEIXv/IoJCUlroIFFo@y6ezDGmyeOxkMXChZLIXTAbAy/HYHdAB6avq8zffPagnfcK9LvQZZ11SAUI7OS4xe7O1jbsxalYlmrE5SVnoqJ4sbAO5cafi2Auj0rmYBBjuPWVTKFcqyRGBup849P4E1u6NwK8HbzeX6R@atIZMmVu8oTZHAcUu@UMiMwTrgSxHd9Ohzmy4sjCoMGjjdPANuLIhbZ7oJhyB42@LjRAQtW8le5Y@EKT6v873y/Y/52TjTiTP01YlY1pOPNnHB/zUmXmPHFoChZ1SKrx5dgRmwn8M0eHONo253bXcgYr2t1IVr8wPo1ZCpSSq9jemta/fAH "Java (JDK) – Try It Online")
## Explanations
Uses a `BigDecimal` as input and output. `BigDecimal` has a method [`setScale`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html#setScale(int,int)) that sets the scale of the number. The first parameter is the number of digits after the dot separator, the second is the rounding mode. `ROUND_UP` is the "away-from-zero" rounding and has a value of `0` so I hardcode that value.
[Answer]
# Vim, 36 bytes/keystrokes
```
:s/-/-<Space>
:g/\..*[1-9]/norm <C-v><C-a>lD
:s/<Space><cr>
```
[Try it online!](https://tio.run/##K/v/36pYX1dfV4HLKl0/Rk9PK9pQ1zJWPy@/KFdBjDHHhQsorcD1/7@uoYGBniUA) or [Verify all Test Cases!](https://tio.run/##K/v/30q1WF9XX1eByypdP0ZPTyvaUNcyVj8vvyhXQYwxx4ULJK/w/7@upaWeJZeusbGeKZeuOZeuoZ4hlwGXkZ4xlwUXSAoA)
Explanation:
```
:s/ " Replace...
- " A dash
/-<Space> " With a dash and a space
:g/ " On Every line matching this regex...
\. " A dot
.* " Followed By anything
[1-9] " Followed by a digit other than 0
/norm " Run the following keystrokes...
<C-v><C-a> " Increment the number by 1
" This also conveniently places our cursor just before the dot
l " Move one character right
D " Delete everything after the cursor
:s/ " Replace...
<Space> " A space
" (With nothing)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 23 bytes
```
lambda i:i-i%(1|-(i>0))
```
[Try it online!](https://tio.run/##FcpBCoMwEEbhfU/xb4oJTIJpEJugnqQbSwkO6CjipqhnT@3i8W3e8t2GWXxO7SuP/fT@9ODIhu/KHUZxV2qd07xCwAITgg0E472tLuorZx2hJDysJzwJ/yPesKwsm0rFLrGpTrQd9qREn4XOPw "Python 3 – Try It Online")
*-1 byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
```
AĊ×Ṡ
```
[Try it online!](https://tio.run/##y0rNyan8/9/xSNfh6Q93Lvh/dM/h9kdNa9z//9e1tNSz1FHQNTbWMwVS5kBsqGeoo2Cgo2CkZ6yjYKGjAFIBAA "Jelly – Try It Online")
This ports [recursive](https://codegolf.stackexchange.com/a/191248/66833)'s Stax answer into Jelly, so check that answer out for an explanation.
-1 byte thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes
```
ĊḞ>?0
```
[Try it online!](https://tio.run/##y0rNyan8//9I18Md8@zsDf4f3XO4/VHTGvf//3UtLfUsdRR0jY31TIGUORAb6hnqKBjoKBjpGesoWOgogFQAAA "Jelly – Try It Online")
-1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
## How this one works
```
ĊḞ>?0 - Monadic link. Takes a float, x, as argument
? - If:
> 0 - x > 0
- Then:
Ċ - ceil(x)
- Else:
Ḟ - floor(x)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
å├╪∙Bß
```
[Run and debug it](https://staxlang.xyz/#p=86c3d8f942e1&i=-99.9%0A-33.5%0A-7.0%0A-1.1%0A0.0%0A2.3%0A8.0%0A99.9%0A&a=1&m=2)
### Procedure:
1. Absolute value
2. Ceiling
3. Multiply by original sign
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
**>.@|
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tbTs9Bxq/mtypSZn5CvEGxoYKNgqpCnEW1rqWULEjMAChnqGCgoKUFUQoXiwGETI1MAQLGZqYKBnAlNlYQJRZ2RhrGcKVwhVhzANxAarMzX4DwA "J – Try It Online")
Just a 1 character change from [my answer on the cousin question](https://codegolf.stackexchange.com/a/190684/15469).
[Answer]
# JavaScript (ES6), 20 bytes
```
n=>n%1?n<0?~-n:-~n:n
```
[Try it online!](https://tio.run/##Xc/BCoJAEMbxe08xl0APM@46ha5oPouYRiGzkuHRV98K1oI5//jz8T26tVv6531@ofjrEMYmSHORo22lNu2GUuEmlYTey@KngSZ/S8YEnSOXppBlgNaYg1JmOkflk8YCACIW2izZ3XJlBn6d3suJd2JF5b8qFX0vRPpcCG8 "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = input
n % 1 ? // if n is not an integer:
n < 0 ? // if n is negative:
~-n // return -(floor(-n) + 1) = -floor(-n) - 1
: // else:
-~n // return -(-(floor(n) + 1)) = floor(n) + 1
: // else:
n // return n unchanged
```
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~41 bytes~~~~27 bytes~~24 bytes
```
s=>(int)s+Math.Sign(s%1)
```
[Try it online!](https://tio.run/##TU@xasMwEJ19X3FLQaKyiOOW1rjOUujUQCFDh5BBqJIjcGWqu6SU4G93VZOh0713vPfunqXSkp1PFGKPux9i99nCf6ZfQ/xqwQ6GCN/gAgWx4WDxPIYP3JoQURCnbNgf0KSeJBRZVFzdL6don/wwGlYYIm/QYzdTtxGZSLrdGj7qXeijoJtKzi3A2SRkR4wdRveNi3V/uJRNoxuvsKxrfe9V@ZBhpau8WSlc6zqDR4VX0d1arxZtk@eUQ/2YnLFHsYTnP5YL8q/M8xhpHJx@T4FdruqEFyxlCxNAMcE0/wI "C# (Visual C# Compiler) – Try It Online")
First post here, had fun with it, hope u like it.
Kinda felt C# place is empty here
-14 tnx to @expired data
-3 tnx to @night2
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), ~~18~~ 16 bytes
```
1µ-i:'-A{*+'.A@
```
[Try it online!](https://tio.run/##KyrNy0z@/9/w0FbdTCt1XcdqLW11PUeH//91jYwt9QwB "Runic Enchantments – Try It Online")
"Adds" (away from zero) 0.999999 and floors the result. `µ` is the closest thing to an infinitesimal in language's operators. With a properly functioning `Trunc(x)` command, answer now supports `0` as input.
[Answer]
## C, ~~94~~ ~~43~~ 39 bytes
thanks to ceilingcat for 39 bytes
```
#define f(n)(int)(n>0?ceil(n):floor(n))
```
[TIO](https://tio.run/##PY3NCsIwEIRfpVSEBEzIn7RR0BfxUtKkBNKtVG/iqxtjknqZ@XZnhzVkMibG3WidB9s4BBh5eGIEF3Y11oe0OLmwLGsCHFPUzIMHhF/3NQ0OtfuxIZyxG/xAquJdMZGtZDJrn3W7V6LWdHtIv4nWVONMUtJjoY6yApzyDKwuBJXZ@zr/y0psFakT4fM7fowLw/SIJMxf)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
*±¹⌈a
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8b/WoY2Hdj7q6Uj8//9/tK6lpZ6ljq6xsZ6pjq65jq6hnqGOgY6RnrGOhQ5YysRIzwAob6lnEAsA "Husk – Try It Online") Just takes the sign of the input times the ceiling of its absolute value.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 38 bytes
```
\.0+
.
\b9+\..
0$&
T`9d`d`.9*\..
\..*
```
[Try it online!](https://tio.run/##FYoxCoAwEAT7fYdYJNxyMYjePyxTRImFjYX4/zMWw8Awz/le9@5eqBFEOSwWEjqM2Kq12iot/KUT4C5mNEjOnCELVSGJmqBUTMxYu//lAw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\.0+
.
```
Delete zeroes after the decimal point, to ensure that the number is not an integer; the next two matches fail if there are no digits after the decimal point.
```
\b9+\..
0$&
```
If the integer part is all `9`s, prefix a `0` to allow the increment to overflow.
```
T`9d`d`.9*\..
```
Increment the integer part of the number.
```
\..*
```
Delete the fractional part of the number.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÄîI.±*
```
A 5-byter should definitely be possible..
[Try it online](https://tio.run/##yy9OTMpM/f//cMvhdZ56hzZq/f@va2mpZwQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/wy2H11XqHdqo9V/nf7SupaWepY6usbGeqY6uuY6uoZ6hjoGOkZ6xjoUOWMrESM8AKG@pZxALAA).
**Explanation:**
```
Ä # The absolute value of the (implicit) input,
î # ceiled
* # And then multiplied by
.± # the signum
I # of the input
# (after which the result is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 18 bytes
```
Sign@#⌈Abs@#⌉&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PzgzPc9B@VFPh2NSMYjuVPsfUJSZVxKtrGuX5qAcq6bvUM2la2mpZ6nDpWtsrGcKpMyB2FDPUIfLQIfLSM9Yh8tChwuiwsRIzwCkzlLPgKv2PwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes
```
{$_-.abs%-1*.sign}
```
[Try it online!](https://tio.run/##NYxJDoJAEEX3dYpaqDhQlR5U6AVchBCDkTYkCKZ7YYjx7C2D/tX7b/GetWvP4THgxmIW3qsLcXX1a5J79s29@wRfDWi3By5EuYsxwihGLlSJtnfYNl3t85xfvbv5QMawwSxHkkIAac2n@ekjUILjppMASZYLKxD48wIU6wU1pH@bwpyccEx@AQ "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
.abs # Absolute value
%-1 # Modulo -1
*.sign # Multiply by sign
$_- # Subtract from original
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 5 bytes
```
‼σ±ü*
```
[Try it online!](https://tio.run/##y00syUjPz0n7//9Rw57zzYc2Ht6j9f@/rqWlniWXrrGxnimXrjmXrqGeIZcBl5GeMZcFF1jKxEjPAChvqWcAAA "MathGolf – Try It Online")
## Explanation
It's nice to find usage for the `‼` operator.
```
‼ apply next two operators to (implicit) input
σ sign (-1, 0, or 1)
± absolute value
ü ceiling of that absolute value
* multiply the rounded absolute value with the sign
```
[Answer]
# [PHP](https://php.net/), 30 bytes
```
<?=0^$argn-=0<=>fmod($argn,1);
```
[Try it online!](https://tio.run/##K8go@P/fxt7WIE4lsSg9T9fWwMbWLi03P0UDzNcx1LT@n5qcka@gFJOnZP1f19JSz5JL19hYz5RL15xL11DPkMuAy0jPmMuCCyxlYqRnAJS31DP4l19QkpmfV/xf1w0A "PHP – Try It Online")
If number is not integer, based on the sign -1 (for negative decimals) or 1 (for positive decimals) is added to it and then integer part of the new number is printed.
---
# [PHP](https://php.net/), 32 bytes
```
<?=[ceil,floor][$argn<0]($argn);
```
[Try it online!](https://tio.run/##K8go@P/fxt42Ojk1M0cnLSc/vyg2WiWxKD3PxiBWA8zQtP6fmpyRr6AUk6dk/V/X0lLPkkvX2FjPlEvXnEvXUM@Qy4DLSM@Yy4ILLGVipGcAlLfUM/iXX1CSmZ9X/F/XDQA "PHP – Try It Online")
Basically outputs `floor` of input if it is less than 0, else `ceil` of it.
---
# [PHP](https://php.net/), 34 bytes
```
<?=($argn>0?:-1)*ceil(abs($argn));
```
[Try it online!](https://tio.run/##K8go@P/fxt5WQyWxKD3PzsDeStdQUys5NTNHIzGpGCKqqWn9PzU5I19BKSZPyfq/rqWlniWXrrGxnimXrjmXrqGeIZcBl5GeMZcFF1jKxEjPAChvqWfwL7@gJDM/r/i/rhsA "PHP – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
⌋₁ℤ₁|⌉₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/1FP96OmxkctS4BkzaOeTiD1/390vKWlnqVOvLGxnqlOvLlOvKGeoY6BjpGesY6FDljKACgQDyRiAQ "Brachylog – Try It Online")
or `⌉₁ℕ₁|⌋₁`.
```
⌋₁ The input rounded down
ℤ₁ is an integer less than -1
| and the output, or, the input
⌉₁ rounded up is the output.
```
[Answer]
# [Factor](https://factorcode.org/), 57 bytes
```
: f ( x -- x ) [ signum ] [ abs ceiling ] bi * >integer ;
```
[Try it online!](https://tio.run/##PYw9D4IwFEV3fsUd1aQNHxotJK6GhcU4GQeopTZCIaUk@utrU4jLeee@5N625nYw7nYtq0uOtzBadOhr@wqg7ay5VYOeMBph7Xc0SlsUUVnl4MNTEDl0rcvRYoMPCPHY4o5JST33eHitmwlcqE5p6XOjsMPZbwgpDApHGKPMt2lEsowesOhxvQlNgsSBKc2W/ynw39ynNF4n2GLuBw "Factor – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes
```
{⍎'⌈⌊'[0>⍵],⍕⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9fapP@rpeNTTpR5tYPeod2uszqPeqUC69n8aUAVQGqK4q/nQeuNHbROBvOAgZyAZ4uEZ/P9R76pqdc@8gtISKwV1oMatOuoK/qUlUH4ayJhDKw6tt7TUs1QA6jfWMwVS5kBsqGeoYKBgpGesYKEAljUx0jMAKbHUMwAA "APL (Dyalog Unicode) – Try It Online")
Simple Dfn. Uses `⎕IO←0`.
### How:
```
{⍎'⌈⌊'[0>⍵],⍕⍵} ⍝ Main function, argument ⍵.
⍕⍵ ⍝ Stringified argument
, ⍝ Appended to
[0>⍵] ⍝ This item... (0 if ⍵ is positive or 0, else 1)
'⌈⌊' ⍝ of this string (which are the functions Ceiling and Floor, respectively)
⍎ ⍝ Executed as APL code.
```
[Answer]
# sed, 131 bytes + 2 bytes for `-r` flag
```
/^-?[^.]*(\.0*)?$/bQ
s/^(-?)9/\109/
s/([0-8]9*)\..*$/_\1/
h
s/.*_//
y/0123456789/1234567890/
G
s/(.*)\n(.*)_(.*)/\2\1/
:Q
s/\..*$//
```
## Ungolfed
```
#!/bin/sed -rf
# identify integers
/^-?[^.]*(\.0*)?$/ b isInt
# add a leading 0 if we'll need it later
s/^(-?)9/\109/
# convert to format: -?[0-9]_[0-8]9*
s/([0-8]9*)\..*$/_\1/
# move the part that will remain constant into the hold buffer
h
s/.*_//
# [0-8]9* can be incremented via character substitution
y/0123456789/1234567890/
# reassemble parts
G
s/(.*)\n(.*)_(.*)/\2\1/
:isInt
# Get rid of anything after the decimal point
s/\..*$//
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pF/\./`, 35 bytes
```
$_&&=$F[0]+($_!=int&&$_*(@F-1)/abs)
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXk3NVsUt2iBWW0MlXtE2M69ETU0lXkvDwU3XUFM/MalY8/9/Yz0DLl0TPVMuAyDD4l9@QUlmfl7xf92cAjf9GD19AA "Perl 5 – Try It Online")
[Answer]
## JavaScript (node.js), ~~30~~ ~~23~~ 21 bytes
```
s=>~~s+Math.sign(s%1)
```
Inspired by the C# answer.
Thanks to @Value Ink and @Gust van de Wal for -7 bytes!
Thanks again, @Gust van de Wal for another -2 bytes!
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~45~~ ~~38~~ 37 bytes
```
[int]("$args"-replace'\.0*[^0]','.9')
```
[Try it online!](https://tio.run/##RY1dT4MwFIav6a84aaqAKU2hmI2LJST@AI3zjqFh9cyPsIEUosnkt2PHR7zq@6Tv@5y6@sbGvGNZBrpqcGCHzXnIPk5t7lFWNG@GBg3WZaHR3Ql5kz3L3OWuSFx/6AlJPcJTL0gSkXAIQin9kZUSt5ZVPOHK5tUUQxFaiEaQHKZ@JBQHNcY1h/UYJuVipHEkJOUQT0saqGRk@/rEh1@4gjNx2Kk77rHhwPCnRt3iK2yAvdiPBk1Xtpau2QHmGnGyh@1dZ9rqeL//tPUcUitxtp3WaMxlOs8C/PpX2gZ9QtOCLgzSS2vROY/LlXlInJ70ZPgD "PowerShell Core – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~54~~ 48 bytes
```
$a,$u=$args-split'\.'
(1,-1)[2*!+$u+($a-lt0)]+$a
```
[Try it online!](https://tio.run/##XY5dT4MwFIav119xJNWBtA1QzEYMCYnx2sV5NxfD8MyPMEFaosnkt2NHWWbsTd@nPe/T1tUXNuoVy5IXVYM93ab7nuaMtinNmxfFVV2@6emjmBI3ZDz0VtHlmU9b36U5L3XgrX2a9x0hmUtY5vIkEQkDHgaBN7CU4sqwjC3OTJ7ZGIrQQDRAwMDOR0IykEOcM5gPwSqPRieOROAwiG3T4TIZ2Owe8eAHzmFPJvSj3W2wYUDxu8ZC4zOkQJ@uzU2Dqi21wQu6hXHOnK8Wy5tW6Wp3t3k3hTVkRjNZtkWBSh3KY4/j50lqJpwHVBqKXKFzmLI@Av/W/fHRUWOKt38@dvJ1pCP9Lw "PowerShell Core – Try It Online")
Thanks [@mazzy](https://codegolf.stackexchange.com/users/80745/mazzy) for the improved golfing !
## Original implementation
```
$a,$u="$args"|% s*t '.'
(((1,-1)[$a-lt0]+$a),$a)[!+$u]
```
[Try it online!](https://tio.run/##TY3RSsMwFIavm6c4hsy1LgltU9mKFAritYN5N4p09UyRzs4mQWHrs9esnbqLkP87Od@fffOFrX7DuhZV02LPttmhZyVnNqOsbF81PU5A3xiYyinxfT/iIgrWrBS1CYsZKwPuzvpqxmzRd4TkPuG5L9JUphxEFIbBwErJW8cqGXHu8nyMkYwcxAOEHMb9WCoOaogLDoshjJW/jTSJZUg5JKNJhUoHdndAAjjCBA7EYx92t8GWA8PvPVYGXyAD9nznXlrUtjYOr9kWzntuvl6u7q02ze5x8@6EAnJX461sVaHWJ/nsCfz8L3WeR59QG6hKjfS09lfoPVz8fCF0pCP9Dw "PowerShell Core – Try It Online")
## Explanations
```
$a,$u="$args"|% s*t '.' # splits the input as a string using '.'
[!+$u] # if there are no decimals
( ,$a) # return the int part as is
((1,-1)[$a-lt0]+$a) # return the int part + or - one depending of the sign of the input
```
[Answer]
# [Julia 1.0](http://julialang.org/), 17 bytes
Save 6 bytes thanks to the awesome comments of [MarcMush](https://codegolf.stackexchange.com/users/20260/xnor)!
```
x->x+sign(x%=1)-x
```
[Try it online!](https://tio.run/##FYrLCsIwEEV/5VIqzOAkNAbRLNIvcSP0wYiMpSrk72NcXM7hcB/fp95DqUuuxY3l@NbVqBxyYNfia4dCDeRS8kngYvTnhktb8EEwCE4@Cq6C/4Ox7Wof6npSRh7R09KMb9YxZpvqDw "Julia 1.0 – Try It Online")
An alternative with 22 bytes
```
x->sign(x)ceil(abs(x))
```
[Try it online!](https://tio.run/##FYrBCsIwEAV/5VF62IVNMAbRHNov8VK1kZWyllYhfx/jYZg5zOu76BRKzUMtbtz1aVT4PutC021vyTW/NyjUQC4lnwQuRn9qOjeCD4KD4Oij4CL4H4x1U/tQ15MyhhE95VZ8tY4x26P@AA "Julia 1.0 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `r`, ~~5~~ 4 bytes
*Built-ins I previously didn't know existed FTW!*
```
ȧ⌈∆±
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%C8%A7%E2%8C%88%E2%88%86%C2%B1&inputs=-33.5&header=&footer=)
Explanation:
```
# Implicit input
ȧ # Absolute value
⌈ # Ceiling
∆± # Change to the sign of input
# Implicit output
```
] |
[Question]
[
A polyquine is both quine and polyglot.1 You are to write a quine which is valid in at least two different languages. This is code golf, so the shortest answer (in bytes) wins.
1 I made that up. Or rather, [Geobits did](http://chat.stackexchange.com/transcript/240?m=17522730#17522730). Apparently, [he wasn't the first one either](https://code.google.com/p/mchouza/source/browse/trunk/quine/polyquine.c?r=122), though.
### Rules for Quines
Only *true* quines are accepted. That is, you need to print the entire source code verbatim to STDOUT, **without**:
* reading your source code, directly or indirectly.
* relying on a REPL environment which just simply evaluates and prints every expression you feed it.
* relying on language features which just print out the source in certain cases.
* using error messages or STDERR to write all or part of the quine. (You may write things to STDERR or produce warnings/non-fatal errors as long as STDOUT is a valid quine and the error messages are not part of it.)
Furthermore, your code *must* contain a string literal.
### Rules for Polyglots
The two languages used must be distinctly different. In particular:
* They must not be different versions of the same language (e.g. Python 2 vs. Python 3).
* They must not be different dialects of the same language (e.g. Pascal vs. Delphi).
* One language may not be a subset of the other one (e.g. C vs. C++).
[Answer]
# CJam/GolfScript, 34 bytes
```
{"__X.0#@@?LL
;~"N}__X.0#@@?LL
;~
```
The byte count contains a trailing linefeed, since the program wouldn't be a quine without it.
While CJam and GolfScript are *very* similar in some aspects, there are *a lot* of differences. To make this an "honest" polyquine, I decided to rely on the *differences* as much as possible. Except for the block and string syntax (which the languages share with oh so many others), no part of the code achieves exactly the same in both languages.
The online GolfScript interpreter has a bug; this program works only with the official interpreter.
### Example run
```
$ cat polyquine
{"__X.0#@@?LL
;~"N}__X.0#@@?LL
;~
$ md5sum polyquine <(cjam polyquine) <(golfscript polyquine)
e2f1f3cd68abbbceec58080513f98d9a polyquine
e2f1f3cd68abbbceec58080513f98d9a /dev/fd/63
e2f1f3cd68abbbceec58080513f98d9a /dev/fd/62
```
### How it works (CJam)
```
" Push that block. ";
{"__X.0#@@?LL
;~"N}
" Push two copies of the block, 1 (computed as 1**0) and rotate the block copies on top. ";
__X.0#@@
" If 1 is truthy (oh, the uncertainty), execute the first copy; else, execute the second.
Evaluating the block pushes the string it contains; N pushes a linefeed. ";
?
" Push two empty arrays. ";
LL
" Discard one empty array and dump the second. ";
;~
" (implicit) Print all items on the stack. ";
```
### How it works (GolfScript)
```
# Push that block.
{"__X.0#@@?LL
;~"N}
# Push a copy of the block; _ and X are noops, # initiates an inline comment.
__X.0#@@?LL
# Discard the 0 and execute the copy of the block.
# Evaluating the block pushes the string it contains; N is a noop.
;~
# (implicit) Print all items on the stack, followed by a linefeed.
```
---
# CJam/GolfScript, 12 bytes
```
{"0$~"N}0$~
```
Cheaty solution that avoids the languages' differences as much as possible.
Try it online:
* [CJam](http://cjam.aditsu.net/)
* [GolfScript](http://golfscript.apphb.com/?c=eyIwJH4iTn0wJH4%3D)
### How it works (CJam)
```
"0$~" " Push that string. ";
N " Push a linefeed. ";
{ }0$~ " Push a copy of the block and execute it. ";
" (implicit) Print the stack. ";
```
### How it works (GolfScript)
```
"0$~" # Push that string.
N # Undefined token (noop).
{ }0$~ # Push a copy of the block and execute it.
# (implicit) Print the stack, followed by a linefeed.
```
[Answer]
## C#/Java, 746 bytes
I use the property that chars in Java can be written as identical unicode sequences. If we have `A` instruction for C# compiler and `B` instruction for Java, we can use the following code fragment:
```
//\u000A\u002F\u002A
A//\u002A\u002FB
```
It will be "recognized" by the following way with C#:
```
//\u000A\u002F\u002A
A//\u002A\u002FB
```
And by the following way by Java:
```
//
/*
A//*/B
```
Because of `\u000A` is line break, `\u002F` is `/` and `\u002A` is `*` in Java.
So the final polyglot-quine is:
```
//\u000A\u002F\u002A
using System;//\u002A\u002F
class Program{public static void//\u000A\u002F\u002A
Main//\u002A\u002Fmain
(String[]z){String s="//@#'^using System;//'#^class Program{public static void//@#'^Main//'#main^(String[]z){String s=!$!,t=s;int[]a=new int[]{33,94,38,64,35,39,36};String[]b=new String[]{!&!!,!&n!,!&&!,!&@!,!&#!,!&'!,s};for(int i=0;i<7;i++)t=t.//@#'^Replace//'#replace^(!!+(char)a[i],b[i]);//@#'^Console.Write//'#System.out.printf^(t);}}",t=s;int[]a=new int[]{33,94,38,64,35,39,36};String[]b=new String[]{"\"","\n","\\","\\u000A","\\u002F","\\u002A",s};for(int i=0;i<7;i++)t=t.//\u000A\u002F\u002A
Replace//\u002A\u002Freplace
(""+(char)a[i],b[i]);//\u000A\u002F\u002A
Console.Write//\u002A\u002FSystem.out.printf
(t);}}
```
However, the size is too huge because of languages verbosity.
Compilation available on ideone.com: [C#](http://ideone.com/JrrbeL), [Java](https://ideone.com/PzJxcB).
[Answer]
### Python 3 and JavaScript, 134 bytes
Here's my (final?) attempt:
```
a='eval(a.split(" ")[2%-4]),1//2# q=String.fromCharCode(39);console.log("a="+q+a+q+a.slice(-8)) print(a[-12:]%a) a=%r;eval(a)';eval(a)
```
It can probably be golfed a bit more, especially if anyone knows a better way to get single quotes in JavaScript.
---
Boiled down, the program looks like this:
```
a='a long string';eval(a)
```
The `eval()` function will evaluate expressions in both languages. So the long string gets executed:
```
eval(a.split(" ")[2%-4]),1//2# ... the rest gets commented out
```
This splits the long string by spaces and evaluates the substring indexed by `2%-4`. JavaScript will run the third substring (`2 % -4 == 2`) and Python the second last (`2 % -4 == -2`), because their modulo operators behave differently for negatives.
The rest of the string gets ignored in both languages. JavaScript stops at the `//`, while Python sees it as integer division and stops at the `#`.
So JavaScript prints the source code to the console here:
```
q=String.fromCharCode(39);console.log("a="+q+a+q+a.slice(-8))
```
And Python here:
```
print(a[-12:]%a)
```
Both make use of the final part of the string, which is a template of the program:
```
a=%r;eval(a)
```
[Answer]
# Ruby/Perl/PHP, 52
```
$b='$b=%c%s%c;printf$b,39,$b,39;';printf$b,39,$b,39;
```
Copied verbatim from [Christopher Durr](http://www.nyx.net/~gthompso/self_perl.txt)'s Perl quine.
This is rules abuse. Ruby and Perl are definitely not the same language, nor is Perl a subset of Ruby (most of the linked Perl quines don't work in Ruby, for example). But Ruby was designed to be able to look a lot like Perl if you want it to, and this happens a lot when golfing.
[Answer]
# PHP/Perl - 171
```
#<?PHP$s=1;$t="";
$a='%s<%cPHP$s=1;$t="";%c$a=%c%s%c;$t==$s?$t="#":$s;printf($a,$t,63,10,39,$a,39,10,63);%c#%c>';$t==$s?$t="#":$s;printf($a,$t,63,10,39,$a,39,10,63);
#?>
```
Run with:
```
$ php quine.pl
$ perl quine.pl
```
The `php` code is actually running (not just printing itself).
[Answer]
# Bash/Ruby, ~~104~~ 82
```
"tee`#";puts <<a*2+'a'#`" -<<'a';echo a
"tee`#";puts <<a*2+'a'#`" -<<'a';echo a
a
```
Older version:
```
"alias" "puts=f()(tee -;echo a);f"
puts <<a *2+"a"
"alias" "puts=f()(tee -;echo a);f"
puts <<a *2+"a"
a
```
# Bash/Ruby, 128 without undefined behavior
```
"alias" 'puts=f()(a=`cat`;echo "$a
$a
a");f'
puts <<'a' *2+"a"
"alias" 'puts=f()(a=`cat`;echo "$a
$a
a");f'
puts <<'a' *2+"a"
a
```
[Answer]
# Bash/GolfScript, 73
```
.~0 ()
{
declare "-f" @* ".~0" " ()
"+@n.;
echo '.~0;'
}
.~0;
```
There is a trailing space on each of the first 3 lines.
# Bash/GolfScript, 78
```
alias :a~a.='eval "alias :a~a."\
;set [61 39]+a[39]+n"":a;echo ":a~a."'
:a~a.
```
[Answer]
## [Perl 5](https://www.perl.org/)/[Ruby](https://www.ruby-lang.org/)/[JavaScript (Node.js)](https://nodejs.org)/[Bash](https://www.gnu.org/software/bash/)/[Python 2](https://docs.python.org/2/)/[PHP](https://php.net/), 1031 bytes
```
s=1//2;_=r'''<?#/.__id__;s=+0;#';read -d '' q<<'';s=\';Q='echo s=1//2\;_=r$s$s$s\<\?\#/.__id__\;s=+0\;#$s\;read -d $s$s q\<\<$s$s\;s=\\$s\;Q=$s$Q$s\;eval\ \$Q;echo $q';eval $Q
$_='eval("0"?0?"def strtr(s,f,t);s.tr(f,t) end;class String;def chr(n);self+n.chr end;end":"$u=strtr=(s,f,t)=>[...f].reduce((s,a,i)=>s.replace(RegExp(a,`g`),t[i]),s);printf=console.log;(S=String).prototype.chr=function(n){return this+S.fromCharCode(n)}":[]&&"sub strtr{eval q(q(X)=~y/X/X/r)=~s/X/shift/ger}");printf(strtr("%s<?#/.__id__;s=+0;#j;read -d jj q<<jj;s=zj;Q=jecho s=1//2z;_=rksksksz<z?z#/.__id__z;s=+0z;#ksz;read -d ksks qz<z<ksksz;s=zzksz;Q=kskQksz;evalz zkQ;echo kqj;eval kQwk_=j%sj;eval(k_);//;#jjj;f=jjjs=1//2;_=r%%s%%s%%s;f=%%s%%s%%s;q=_[18]*3;print f%%%%(q,_,q,q,f,q)jjj;q=_[18]*3;print f%%(q,_,q,q,f,q)%s","jkwz","".chr(39).chr(36).chr(10).chr(92).chr(92)),[]&&"s=1//2;_=r".chr(39).chr(39).chr(39),$_,$u?"":"".chr(10));';eval($_);//;#''';f='''s=1//2;_=r%s%s%s;f=%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)''';q=_[18]*3;print f%(q,_,q,q,f,q)
```
[Verify it online!](https://tio.run/##jVPbcpswEH3nKzQYB2gU7MTTThNZ8UOmH0DzkhnjIZiLARMukmhq4vTX3RU4JGnsSS1gb0dnd7Xy0uPxbvfoozMfWUle1sISSUGUh@DrO7sMWfbGga6RVdRCWmVGFFYvN4ejbEmUvAjCw9GUE2UJFRyO8hjybkRc5Ecyb4gy6ACTY4gJUMQlOgsQjwsm3KIMc1d4K3qUNC6JArSfb9rKM9nK1rddEVvZ6F6fbNu@Xnm9LPuvUo6wHmJTBu2U9q6nMsNsiVOOeYzLDTwTDPkwQJ/38zyG7FG7Hafno9EFcSnTdX06G4ws100C1yWcno7JQCcs9ALZg66jajrVdQg4OrGpHvpxgbrtjtyvcbmcqTNzehanpXHIAAI9k4ShCoDTdoMkdKS0Kdi21MJfXuYgR7NJm0Sr9NaFNFvRXMgMuqGO1dl4pgZhhLhgghkcR1iYhFugSw2FeUD8zOMc3QqW5CsisX7MjBxQYRad5hZYLQxe9UrVatpS0T0XvZ5blhUtLBYGtR8a4PZwAm4OnjLzwPUzXP34XRoevl/dm1jMk4WJuUlKyCci6hc5L7LQyooVMW5pV4ZplawQhdiUocxPozr34R7kUNYTC0XNciTihJ/eWhErHm5ij93AhYDos3o1X5ycqLxedi0/tYdSGZVxZ9I/m9EdLAYaB8njJBKjVcie1ZdyjO6c1CH/OOe0n06ayjmnKQSaFGaSvplzI@e85nI102bW9CxNS9OQAQR6JglDFQCn7QZJ2EhpU7Btqcn6G9Ss93NeV2k357X9uHZpOuSdbaxdk4xGUCWUFVH4vt7a4ZB3DwRe9Yq68/Pviy@TrnUUDeFnVNjFFawIV6akOoB6hxlyFavp@rEBocpZGZNLs5PfOnk@7uTlRS9N3A2pr/Cfna8Say7W6pkKN099YTNJd9UNbd8y/CuhM/i@aZnLJfvtlM/akBQfMe8gyl8 "Bash – Try It Online")
Based on my updates to [this answer](https://codegolf.stackexchange.com/a/162690/9365), I thought I'd try and optimise out the code that prints a different permutation, but ended up adding in Bash, which added a load more bytes anyway. Whilst this is more optimised than my first attempt (saved over 300 bytes) I'm sure it can still be golfed further.
---
## Alternative [Perl 5](https://www.perl.org/)/[Ruby](https://www.ruby-lang.org/)/[JavaScript (Node.js)](https://nodejs.org)/[Bash](https://www.gnu.org/software/bash/)/[Python 2](https://docs.python.org/2/)/[PHP](https://php.net/), 1040 bytes
```
s=1//2;_=r'''<?#/.__id__;s=+0;#';read -d '' q<<'';s=\';Q='echo s=1//2\;_=r$s$s$s\<\?\#/.__id__\;s=+0\;#$s\;read -d $s$s q\<\<$s$s\;s=\\$s\;Q=$s$Q$s\;eval\ \$Q;echo $q';eval $Q
$_='$z=0?"$&".next+92 .chr+10 .chr: 0..a||eval("printf=console.log;unescape`$%27%5C%0Ak`");$q=$z[1]?$z[1]:h^O;printf("%s%s%s%s<?#/.__id__;s=+0;#%s;read -d %s%s q<<%s%s;s=%s%s;Q=%secho s=1//2%s;_=r%ss%ss%ss%s<%s?%s#/.__id__%s;s=+0%s;#%ss%s;read -d %ss%ss q%s<%s<%ss%ss%s;s=%s%s%ss%s;Q=%ss%sQ%ss%s;eval%s %s%sQ;echo %sq%s;eval %sQ%s%s_=%s%s%s;eval(%s_);//;#%s%s%s;f=%s%s%ss=1//2;_=r%%s%%s%%s;f=%%s%%s%%s;q=_[18]*3;print f%%%%(q,_,q,q,f,q)%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)%s",[]&&"s=1//2;_=r",$r=[]&&$q,$r,$r,$q,$q,$q,$q,$q,$b=$z[2]?$z[2]:chr(92),$q,$q,$b,$d=$z[0]?$z[0]:h^L,$d,$d,$b,$b,$b,$b,$b,$d,$b,$d,$d,$b,$b,$d,$d,$b,$b,$b,$d,$b,$d,$d,$d,$b,$b,$b,$d,$d,$q,$d,$n=$z[3]?$z[3]:chr(10),$d,$q,$_,$q,$d,$q,$q,$q,$q,$q,$q,$q,$q,$q,$z[4]?"":$n);';eval($_);//;#''';f='''s=1//2;_=r%s%s%s;f=%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)''';q=_[18]*3;print f%(q,_,q,q,f,q)
```
[Verify it online!](https://tio.run/##jVNtk5pADP7Or9jBRbRyiNKb9lyp0@nXznT4LJYDwcMr5W3xWi397TZZkNM7maub2WySJ092E/Q9Hh2Pv9bkZk30bZLtSr3cpkz6Gdxe2FlYxGcO8ono6a5EK4uZVOz8/fVo4TMpSYPwevSRM8mHG1yP8gjq7ssoTToq75nUqwFmF8IEiigjNwHhUVqUbpqFiVt6D1YnaZQxCWjfTqqwJxU@vaovUeFDm7NZiXc983px/F9X6WC9xib1xJQa158s1gpfe@Qaj7RsD2JqUE8D6N9mnl3IFnU8cmsyHk@ZaxWqqs4XvbHuutvAdRm3RgbrqawIvQDfoKokn89VFQKOymxLDddRSup0B/Mpx@XMnYXTsjiCxmE9CLRMCCM5AOciAQkd1LYFto2n8MmLHeJQm4kiNFeFi1Bboq6l0oNlLGTal/Uk/F2O7qZEX0fFaGIIPSOGrntVhRkDOSu2Sbmx1mnC0zjU4/SB7ZKQr70svKfK9INy@0UxPv@4l4eM5hY9LCerhdhn0fdvrM4eyAqv1@sGKbx9FwKwR6ghKpQN6qxR4IFOKZyfBMALhbekInFkgOqJ8Bk34kkuMuan7KZKfcZSoO3awtfDdTDYdFHheeMnAqVwt8kWzgHYQzYeY2Xh3Jy42y9EAVMIxtpzbrnLycfVO7PuFtko8BvkmqvlsDZaPmwIrwBfwGRtuer35eeKskYLC300h5OQ/FJ8nNlUzGy6msH4B3fTYRvUaIBxQ8QNnOlXcAnxLyU47cGZJ@gAvPAHohjsCRYzRTGzvszEGJ7i7gmVd8th@X61kOUZTYas/uYHtJkK/D2h7bCfzeNyUG82GCleYy4g0j8 "Bash – Try It Online")
A little closer to my original approach, but the repetition of the args for `printf` is still insane. Using positional arguments instead make this only work in Chrome and is tricky to get working in PHP as well because the `$s` in `%1$s` is interpolated, but could save a lot of bytes, perhaps using a combination of the two approaches...
[Answer]
## Ruby/Mathematica, 225 bytes
Here is my own very beatable polyquine (which serves as example and proof-of-concept):
```
s="s=%p;puts s%%s;#Print[StringReplace[s,{(f=FromCharacterCode)@{37,112}->ToString@InputForm@s,f@{37,37}->f@37}]]&@1";puts s%s;#Print[StringReplace[s,{(f=FromCharacterCode)@{37,112}->ToString@InputForm@s,f@{37,37}->f@37}]]&@1
```
The first part is based [on this Ruby quine](https://codegolf.stackexchange.com/a/80/8478) and is basically:
```
s="s=%p;puts s%%s;#MathematicaCode";puts s%s;#MathematicaCode
```
The string assignment is exactly the same in Mathematica. The `puts s%s` is interpreted as a product of 4 symbols: `puts`, the string `s`, `%` (the last REPL result or `Out[0]` if it's the first expression you evaluate) and another `s`. That's of course completely meaningless, but Mathematica doesn't care and `;` suppresses any output, so this is just processed silently. Then `#` makes the rest of the line a comment for Ruby while Mathematica continues.
As for the Mathematica code, the largest part of it, is to simulate Ruby's format string processing without using any string literals. `FromCharacterCode@{37,112}` is `%p` and `FromCharacterCode@{37,112}` is `%%`. The former gets replaced with the string itself, (where `InputForm` adds the quotes) the latter with a single `%`. The result is `Print`ed. The final catch is how to deal with that `#` at the front. This is Mathematica's symbol for the first argument of a pure (anonymous) function. So what we do is we *make* all of that a pure function by appending `&` and immediately invoke the function with argument `1`. Prepending a `1` to a function call "multiplies" the result with `1`, which Mathematica again just swallows regardless of what kind of thing is returned by the function.
[Answer]
# reticular/befunge-98, 28 bytes [noncompeting]
```
<@,+1!',k- ';';Oc'43'q@$;!0"
```
[Try reticular!](http://reticular.tryitonline.net/#code=PEAsKzEhJyxrLSAnOyc7T2MnNDMncUAkOyEwIg&input=) [Try befunge 98!](http://befunge-98.tryitonline.net/#code=PEAsKzEhJyxrLSAnOyc7T2MnNDMncUAkOyEwIg&input=)
Anything in between `;`s in befunge is ignored, and `!` skips into the segment between `;`s for reticular. Thus, reticular sees:
```
<@,+1!',k- ';';Oc'43'q@$;!0"
< move left
" capture string
0 push zero
;! skip `;` (end program)
$ drop zero
q@ reverse TOS
'43' push 34 (")
c convert to char
O output all
; end program
```
Befunge sees:
```
<@,+1!',k- ';';Oc'43'q@$;!0"
< move left
" capture string
!0 push 1
; ; skip this
- ';' push 27
,k output top 27 chars
+1!' push 34 (")
, output "
@ end program
```
[Answer]
# C/PHP, ~~266~~ ~~304~~ ~~300~~ ~~282~~ ~~241~~ 203 + 10 bytes
```
//<?php
function main($a){printf($a="%c//<?php%cfunction main(%ca){printf(%ca=%c%s%c,13,10,36,36,34,%ca,34,36,10,10,10);}%c#if 0%cmain();%c#endif",13,10,36,36,34,$a,34,36,10,10,10);}
#if 0
main();
#endif
```
+10 bytes because compiling in C requires the GCC compiler flag `-Dfunction=`.
How it works (in PHP):
* The PHP interpreter simply prints everything before the `<?php` as HTML. `//` is not a comment in HTML, so it's simply printed.
* `main` is declared as a function with a variable `a`.
* `printf` prints a carriage return (to override the already-printed `//`) and then the source code, using a standard C/PHP quining method.
* `#if 0` is ignored by PHP.
* `main($a)` initializes an empty variable `a`. (Previously used `error_reporting(0)` to ignore errors caused by calling `main()`)
* `#endif` is also ignored by PHP.
How it works (in C):
* `//<?php` is a single-line comment, so it is ignored.
* The `function` keyword is ignored due to the command-line compiler argument `-Dfunction=`.
* GCC and Clang don't care if variables start with or contain `$`. (This saved the day.)
* `printf` prints a carriage return (useless in this instance) and then the source code, using a standard C/PHP quining method.
* `#if 0` ignores everything until the `endif`, so PHP can call `main`.
* `#endif` ends the "ignore me" block.
[Answer]
# [Wumpus](https://github.com/m-ender/wumpus)/[><>](https://esolangs.org/wiki/Fish)/[Befunge-98](https://github.com/catseye/FBBI) 31 bytes
```
"]#34[~#28&o@,k+deg0 #o#!g00
```
[Try it in Wumpus!](https://tio.run/##Ky/NLSgt/v9fSSFW2dgkuk7Z2FAt30EnWzstTdvISkVBOV9ZEcj4/x8A),
[Try it in ><>!](https://tio.run/##S8sszvj/X0khVtnYJLpO2dhQLd9BJ1s7LU3byEpFQTlfWRHI@P8fAA),
[Try it in Befunge-98!](https://tio.run/##S0pNK81LT9W1tPj/X0khVtnYJLpO2dhQLd9BJ1s7LU3byEpFQTlfWRHI@P8fAA)
## How it Works:
### Wumpus Code:
```
" Start string literal
Bounce off end of line and come back
" End string literal
] Push top of stack to bottom
#34 Push double quote
[~ Get bottom of stack and swap it with the double quote
#31 Push 31
&o@ Print the top 31 items on stack and terminate program
```
### ><> Code:
```
" Start string literal
Wrap when it reaches the end of the line
" End string literal
]# Clear stack and reflect
" Wrapping string literal again, but backwards
+2: Copy the space and add 2 to get "
#o#! Skip into the printing loop
Exit with an error
```
### Befunge-98 Code:
```
" Wrapping string literal
] Turn right
] Turn right again, going West
" Wrapping string literal going West
!+2: Get double quote and invert it
#o# Skip over the o instruction
+2:$ Get double quote
+ff Push 30
@,k Print 30+1 items from the stack and terminate program.
```
[Answer]
## ><> and CJam, 165 bytes
```
"~~~~~~~~~~~~~~~~~~~~~~~r00gol?!v93*0.Hi
' < .1*5av!?log10oar~~~r
'"`{"`"\"_~e#.21 <.2+4*96;!?log10oa"}_~e#.21 <.2+4*96;!?log10oa
```
To CJam, the program starts with a multi-line string literal. This is escaped with ```, and then it uses the standard quine to print the quine code, as well as a trailing comment.
To ><>, the first `"` starts a string literal that goes through the entire first row, pushing every character to the stack. After that, the trailing spaces (created due to the input being padded) are deleted, and then the stack is reversed. Every character in the stack (i.e. the entire first row) is output, and then it moves down to the second row.
The second row essentially does the same thing, except that it's in the opposite direction, so you don't need to reverse the stack. (I do anyway, because I have to delete the trailing spaces.)
Finally, it moves on to the third line. The only major difference is that you must skip the CJam block, which is done using `.` The single quote captures the entire line (again, backwards), and then it is output.
[Answer]
# C/Lisp, 555 bytes
```
t(setq /*;*/){}main(){char q='\"',s='\\';char*a=
"~%t(setq /*;*/){}main(){char q='~A';char*a=
~S;char*b=/*
)(setq a ~S)
(setq */ ~S;printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}~%";char*b=/*
)(setq a "\\\"',s='\\\\")
(setq */ "
t(setq /*;*/){}main(){char q='%c%c',s='%c%c';char*a=
%c%s%c;char*b=/*
)(setq a %c%c%c%c%c',s='%c%c%c%c%c)
(setq */ %c%s%c;printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}
";printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}
```
Intentionally blank first line.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 70 bytes/ [Python 3](https://docs.python.org/3/), 77 bytes
```
a="`q‛:Ė+34Cp‛a=print('a=%r;exec(a[13:])#\\140:Ė'%a)";exec(a[13:])#`:Ė
```
Vyxal : [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYT1cImBx4oCbOsSWKzM0Q3DigJthPXByaW50KCdhPSVyO2V4ZWMoYVsxMzpdKSNcXFxcMTQwOsSWJyVhKVwiO2V4ZWMoYVsxMzpdKSNgOsSWIiwiIiwiIl0=)
```
a="`q‛:Ė+34Cp‛a=print('a=%r;exec(a[13:])#\\140:Ė'%a)";exec(a[13:])#`:Ė
```
Python : [Try it online!](https://tio.run/##K6gsycjPM/7/P9FWKaHwUcNsqyPTtI1NnAuAzETbgqLMvBIN9URb1SLr1IrUZI3EaENjq1hN5ZgYQxMDoFJ11URNJVSpBKDw//8A "Python 3 – Try It Online")
The difference beetween the number of bytes is due to the fact that vyxal and python doesn't use the same charset
## Explanation :
* Vyxal
```
a=" # do nothing revelent here
`q‛:Ė+ `:Ė # structure for a quine
34Cp‛a=p # prepend `a="` to the string
rint # do stuff that somehow push 0 to the stack
( # for loop over 0 (do nothing)
# # comment and implicily close the loop
# implicit output
```
* Python
The quine is a variation of `a="print('a=%r;exec(a)'%a)";exec(a)`
[Answer]
# 05AB1E/2sable, 14 bytes, non-competing
```
0"D34çý"D34çý
```
[Try it online! (05AB1E)](http://05ab1e.tryitonline.net/#code=MCJEMzTDp8O9IkQzNMOnw70K&input=)
[Try it online! (2sable)](http://2sable.tryitonline.net/#code=MCJEMzTDp8O9IkQzNMOnw70K&input=)
2sable is derived from 05AB1E and is similar, but has major differences.
Trailing newline.
[Answer]
# C/TCL, 337 bytes
```
#define set char*f=
#define F
#define proc main(){
set F "#define set char*f=
#define F
#define proc main(){
set F %c%s%c;
proc /* {} {}
puts -nonewline %cformat %cF 34 %cF 34 91 36 36]
set a {*/printf(f,34,f,34,91,36,36);}
";
proc /* {} {}
puts -nonewline [format $F 34 $F 34 91 36 36]
set a {*/printf(f,34,f,34,91,36,36);}
```
[Answer]
# C/Vim 4.0, 1636 bytes
Contains control characters.
```
map () {}/*
map g ;data0df"f"cf"
f"cf"
f"D2kyyP;g6k2dd4x5jA"JxA","JxA","jyyPkJxA"jok;g2kdd4xkJx3jdd
map ;g O"vdldd0i# 0# 1# 2# 3# 4# 5# #0lx2lx2lx2lx2lx2lx2lx:s/##/#/g
o:s//"/gk0y2lj02lp"addk@ao:s//\\/gk0ly2lj02lp"addk@ao:s///gk04ly2lj02lp05l"vp"addk@ao:s///gk05ly2lj02lp05l"vp"vp"addk@ao:s//
/gk06ly2lj02lp05l"vp"vp"vp"addk@ao:s//
/gk02ly2lj02lp05l"vp"addk@a
unmap ()
map ;data o*/ char*g[]={"map () {}/*#2map g ;data0df#0f#0cf#0#5#3f#0cf#0#5#3f#0D2kyyP;g6k2dd4x5jA#0#3JxA#0,#0#3JxA#0,#0#3jyyPkJxA#0#3jo#3k;g2kdd4xkJx3jdd#2map ;g O#4#4#4#4#3#0vdldd0i## 0## 1## 2## 3## 4## 5## ###30lx2lx2lx2lx2lx2lx2lx:s/####/##/g#5o:s//#0/g#3k0y2lj02lp#0addk@ao:s//#1#1/g#3k0ly2lj02lp#0addk@ao:s//#4#4#3/g#3k04ly2lj02lp05l#0vp#0addk@ao:s///g#3k05ly2lj02lp05l#0vp#0vp#0addk@ao:s//#4#4#5/g#3k06ly2lj02lp05l#0vp#0vp#0vp#0addk@ao:s//#4#4#5/g#3k02ly2lj02lp05l#0vp#0addk@a#2unmap ()#2#2map ;data o*/ char*g[]={","#A#0#a#0,#0#b#0,#0#c#0#C#2","}; /*#3#2#2#0*/ print(char*s){char*t=s,c,d;while(c=*t++)if(c==35){c=*t++;if(c==35)putchar(c);else if(c==48)putchar(34);else if(c==49)putchar(92);else if(c==50)printf(#0#1n#0);else if(c==51)putchar(27);else if(c==52)putchar(22);else if(c==53)putchar(13);else if(c>64&&c<91)print(g[c-65]);else printf(g[c-97]);}else putchar(c);} main(){print(g[1]);}"}; /*
"*/ print(char*s){char*t=s,c,d;while(c=*t++)if(c==35){c=*t++;if(c==35)putchar(c);else if(c==48)putchar(34);else if(c==49)putchar(92);else if(c==50)printf("\n");else if(c==51)putchar(27);else if(c==52)putchar(22);else if(c==53)putchar(13);else if(c>64&&c<91)print(g[c-65]);else printf(g[c-97]);}else putchar(c);} main(){print(g[1]);}
```
Your Vim needs to have the following set:
```
set noai
set wm=0
set nosi
set tw=0
set nogdefault
```
[Answer]
## Perl/Javascript (SpiderMonkey), 106 bytes
```
$_='$q=+[]?h^O:unescape("%27");print("$_="+$q+$_+$q+";eval($_)"||(q($_),"=$q$_$q;",q(eval($_))))';eval($_)
```
[Try the Perl online!](https://tio.run/##K0gtyjH9/18l3lZdpdBWOzrWPiPO36o0L7U4ObEgVUNJ1chcSdO6oCgzr0RDCahKSVulUFslHkQqWaeWJeZoqMRrKtXUaBSCGDpKtiqFKvEqhdZKOoUaMGkgUIer/f8fAA "Perl 5 – Try It Online")
[Try the JavaScript online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/18l3lZdpdBWOzrWPiPO36o0L7U4ObEgVUNJ1chcSdO6oCgzr0RDCahKSVulUFslHkQqWaeWJeZoqMRrKtXUaBSCGDpKtiqFKvEqhdZKOoUaMGkgUIer/f8fAA "JavaScript (SpiderMonkey) – Try It Online")
### Explanation
The quine data is stored in `$_` in both languages and then `eval`ed, which is pretty much standard procedure in Perl. I chose SpiderMonkey on TIO as it has a `print` function, but this could easily be ported to browser for + 20 bytes (add `eval("print=alert");` to the beginning of `$_`s definition).
Perl sees the data stored in `$_` and `eval`s it as usual. Since `+[]` is truthy in Perl,`'` is stored in `$q` via the stringwise-XOR of `h` and `O`. The final trick is in the call to `print` where the first part for JavaScript uses `+`, which in Perl treats all items as numbers, and adds up to `0`, then we use the `||` operator to return what we actually want `(q($_),"=$q$_$q;",q(eval($_)))` which is equivalent to `"\$_=$q$_$q;eval(\$_)"`.
In JavaScript, `+[]` returns `0`, so we call `unescape("%27")` to store `'` in `$q` (unfortunately, `atob` doesm't exist in SpirderMonkey...). In the call to `print`, since `+` is the concatenation operator in JavaScript, the first block builds the desired output and the second part after the `||` is ignored.
**Thanks to [Patrick Roberts' comment](https://codegolf.stackexchange.com/q/37464/9365#comment-299961) for the `unescape` trick!**
---
## Perl/JavaScript (Browser), 108 bytes
```
$_='eval("q=_=>_+``;printf=console.log");printf(q`$_=%s%s%s;eval($_)`,$q=+[]?h^O:atob("Jw"),$_,$q)';eval($_)
```
[Try the Perl online!](https://tio.run/##K0gtyjH9/18l3lY9tSwxR0Op0Dbe1i5eOyHBuqAoM68kzTY5P684PydVLyc/XUkTKqhRmADUoVoMgtZgfSrxmgk6KoW22tGx9hlx/laJJflJGkpe5UqaOirxQAlNdbi6//8B "Perl 5 – Try It Online")
```
$_='eval("q=_=>_+``;printf=console.log");printf(q`$_=%s%s%s;eval($_)`,$q=+[]?h^O:atob("Jw"),$_,$q)';eval($_)
```
### Explanation
We store the quine data in `$_` in both languages and then `eval` it, which is pretty much standard procedure in Perl.
Perl sees the data stored in `$_` and `eval`s it as usual. The `eval` within `$_` is executed and fails to parse, but since it's `eval`, doesn't error. `printf` is then called, with a single quoted string `q()`, with ``` as the delimter, as just using ``` would result in commands being executed in shell, then for the first use of `$q`, since `+[]` is truthy in Perl, `'` is stored in `$q` via stringwise-XOR of `h` and `O`.
In JavaScript, the `eval` block within `$_` sets up a function `q`, that `return`s its argument as a `String` and aliases `console.log` to `printf`, since `console.log` formats string like `printf` in Perl. When `printf` is called `+[]` returns `0`, so we call `atob` to decode `'` and store in `$q`.
[Answer]
# [Perl 5](https://www.perl.org/)/[Ruby](https://www.ruby-lang.org/)/[PHP](https://php.net/)/JavaScript (Browser), 153 bytes
```
$_='$z=0?"$&".next: 0..a||eval("printf=console.log;atob`JCc`");printf("%s_=%s%s%s;eval(%s_);",$d=$z[0]?$z[0]:h^L,$q=$z[1]?$z[1]:h^O,$_,$q,$d);';eval($_);
```
[Try the Perl online!](https://tio.run/##K0gtyjH9/18l3lbdoKYmtSwxR0OpoCgzryTNNjk/rzg/J1UvJz9dSdMaIqihpFocb6taDILWYNVAvqaSjkqSrYG9hrGZpl5yRpGVgnZ0rH1GnI@ClUJiSX6ShpKXo5KmjkohWI0lihp/hJpykJp4oDKgaZrqENNV4jX//wcA "Perl 5 – Try It Online")
[Try the Ruby online!](https://tio.run/##KypNqvz/XyXeVt2gpia1LDFHQ6mgKDOvJM02OT@vOD8nVS8nP11J0xoiqKGkWhxvq1oMgtZg1UC@ppKOSpKtgb2GsZmmXnJGkZWCdnSsfUacj4KVQmJJfpKGkpejkqaOSiFYjSWKGn@EmnKQmnigMqBpmuoQ01XiNf//BwA "Ruby – Try It Online")
[Try the PHP online!](https://tio.run/##K8go@G9jXwAkVeJt1VWqbA3slVTUlPTyUitKrBQM9PQSa2pSyxJzNJQKijLzStJsk/PzivNzUvVy8tOtE0vykxK8nJMTlDStIdIaSqrF8baqxSBoDdYH5GtaK@mopNiqVEUbxNqDSauMOB8dlUKQkCFYyBAk5K@jEg8UBarVtFaH6FYBav7/HwA "PHP – Try It Online")
```
$_='$z=0?"$&".next: 0..a||eval("printf=console.log;atob`JCc`");printf("%s_=%s%s%s;eval(%s_);",$d=$z[0]?$z[0]:h^L,$q=$z[1]?$z[1]:h^O,$_,$q,$d);';eval($_);
```
[Answer]
# C/dc, 152 bytes
```
z1d//[[z1d//]P91PP93P[dx]Pq
;main(){char*a="z1d//[[z1d//]P91PP93P[dx]Pq%c;main(){char*a=%c%s%c;printf(a,10,34,a,34);}//]dx";printf(a,10,34,a,34);}//]dx
```
Taking advantage of comments, yeah!
] |
[Question]
[
My Precalc teacher has one of his favorite problems that he made up (or more likely ~~stole~~ inspired by [xkcd](https://blog.xkcd.com/2009/09/02/urinal-protocol-vulnerability/)) that involves a row of `n` urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an `X`, then
`X-X--X`
is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.
## Task
Your program will take a number through `stdin`, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.
## Examples
`0 -> 1` (the null case counts as checkmate)
`1 -> 1` (`X`)
`2 -> 2` (`X-` or `-X`)
`3 -> 2` (`X-X` or `-X-`)
`4 -> 3` (`X-X-`, `-X-X`, or `X--X`)
`5 -> 4` (`X-X-X`, `X--X-`, `-X-X-`, or `-X--X`)
`6 -> 5` (`X-X-X-`, `X--X-X`, `X-X--X`, `-X--X-` or `-X-X-X`)
`7 -> 7` (`X-X-X-X`, `X--X-X-`, `-X-X--X`, `-X--X-X`, `X-X--X-`, `X--X--X` or `-X-X-X-`)
`8 -> 9` (`-X--X--X`, `-X--X-X-`, `-X-X--X-`, `-X-X-X-X`, `X--X--X-`, `X--X-X-X`, `X-X--X-X`, `X-X-X--X`, `X-X-X-X-`)
`...`
## Scoring
The smallest program in bytes wins.
[Answer]
# [Oasis](http://github.com/Adriandmen/Oasis), 5 bytes
**Code**
```
cd+2V
```
**Extended version**
```
cd+211
```
**Explanation**
```
1 = a(0)
1 = a(1)
2 = a(2)
a(n) = cd+
c # Calculate a(n - 2)
d # Calculate a(n - 3)
+ # Add them up
```
[Try it online!](http://oasis.tryitonline.net/#code=Y2QrMlY&input=&args=OA)
[Answer]
## Java 7, ~~65~~ 42 bytes
```
int g(int u){return u>1?g(u-2)+g(u-3):1;}
```
The sequence just adds previous elements to get new ones. Hat tip to orlp and Rod for this shorter method ;)
**Old:**
```
int f(int u){return u<6?new int[]{1,1,2,2,3,4}[u]:f(u-1)+f(u-5);}
```
After the fifth element, the gap in the sequence rises by the element five previous.
[Answer]
# Python 2, 42 40 39 35 bytes
```
f=lambda n:n>1and f(n-2)+f(n-3)or 1
```
Generating the actual sets:
```
lambda n:["{:0{}b}".format(i,n).replace("0","-").replace("1","X")for i in range(2**n)if"11"not in"{:0{}b}".format(i*2,2+n).replace("000","11")]
```
[Answer]
# Ruby, ~~58~~ 34 bytes
Heavily inspired by Geobits' original Java answer.
```
f=->n{n<3?n:n<6?n-1:f[n-1]+f[n-5]}
```
See it on repl.it: <https://repl.it/Dedh/1>
## First attempt
```
->n{(1...2**n).count{|i|!("%0#{n}b"%i)[/11|^00|000|00$/]}}
```
See it on repl.it: <https://repl.it/Dedh>
[Answer]
## Python, 33 bytes
```
f=lambda n:+(n<2)or f(n-2)+f(n-3)
```
Uses the shifted base cases `f(-1) = f(0) = f(1) = 1`. If `True` could be used for 1, we would not need 3 bytes for the `+()`.
[Answer]
# J, ~~31~~ ~~27~~ 23 bytes
*Saved 4 bytes thanks to miles!*
```
0{]_&(]}.,+/@}:)1 1 2"_
```
An explanation is to come soon.
## Old solution
```
(>.1&^)`(-&3+&$:-&2)@.(2&<)
```
This is an agenda. The LHS is a gerund composed of two verbs: `>.1&^` and `-&3+&$:-&2`. The first one is used if the condition (`2&<`) fails. That means the fork `>.1&^` is activated over the argument. Observe:
```
1 ^ 0 1 2
1 1 1
(1&^) 0 1 2
1 1 1
0 1 2 >. (1&^) 0 1 2
1 1 2
(>.1&^) 0 1 2
1 1 2
```
Here, `>.` takes the max of two values. Thus, it yields 1, 1, and 2 as the initial terms.
The second verb in the gerund is a fork:
```
-&3 +&$: -&2
```
The left and right tines are applied to the verb, subtracting 3 and 2 respectively; then the middle verb is called with left and right arguments equal to those. `$:` calls the verb on each argument, and `+` adds those two. It's basically equivalent to `($: arg - 3) + ($: arg - 2)`
### Test cases
```
f =: (>.1&^)`(-&3+&$:-&2)@.(2&<)
f 0
1
f 2
2
f 4
3
f 6
5
f 8
9
F =: f"0 NB. for tables
F i.13
1 1 2 2 3 4 5 7 9 12 16 21 28
i.13
0 1 2 3 4 5 6 7 8 9 10 11 12
(,. F) i.13
0 1
1 1
2 2
3 2
4 3
5 4
6 5
7 7
8 9
9 12
10 16
11 21
12 28
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~25~~ 23 bytes
```
W:qB7BZ+t!XAw3BZ+!3>a>s
```
[Try it online!](http://matl.tryitonline.net/#code=VzpxQjdCWit0IVhBdzNCWishMz5hPnM&input=NQ) Or [check all test cases](http://matl.tryitonline.net/#code=IkAKVzpxQjdCWit0IVhBdzNCWishMz5hPnMKRA&input=MDo4).
### Explanation
*Two* convolutions! Yay!
This builds an array, say A, where each possible configuration is a row. `1` in this array represents an occupied position. For example, for input `4` the array A is
```
0 0 0 0
0 0 0 1
0 0 1 0
···
1 1 1 0
1 1 1 1
```
The code then convolves array A with `[1 1 1]`. This gives an array B. Occupied positions and neighbours of occupied positions in A give a nonzero result in array B:
```
0 0 0 0
0 0 1 1
0 1 1 1
···
2 3 2 1
2 3 3 2
```
So the first condition for a configuration to be a checkmate is that B contains no zeros in that row. This means that in that row of A there no empty positions, or there were some but were neighbours of occupied positions.
We need a second condition. For example, the last row fulfills the above condition, but is not part of the solution because the configuration was not valid to begin with. A valid configurations cannot have two neighbouring occupied positions, i.e cannot have two contiguous `1`'s in A. Equivalently, it cannot have two contiguous values in B exceeding `1`. So we can detect this by convolving B with `[1 1]` and checking that in the resulting array, C,
```
0 0 0 0
0 1 2 1
1 2 2 1
···
5 5 3 1
5 6 5 2
```
no value in that row exceeds `3`. The final result is the number of configurations that fulfill the two conditions.
```
W:q % Range [0 1 ... n-1], where n is implicit input
B % Convert to binary. Each number produces a row. This is array A
7B % Push array [1 1 1]
Z+ % 2D convolution, keeping size. Entries that are 1 or are horizontal
% neighbours of 1 produce a positive value. This is array B
t! % Duplicate and transpose (rows become columns)
XA % True for columns that contain no zeros
w % Swap. Brings array B to top
3B % Push array [1 1]
Z+ % 2D convolution, keeping size. Two horizontally contiguous entries
% that exceed 1 will give a result exeeding 3. This is array C
! % Transpose
3> % Detect entries that exceed 3
a % True for columns that contain at least one value that exceeds 3
> % Element-wise greater-than comparison (logical and of first
% condition and negated second condition)
s % Sum (number of true values)
```
[Answer]
# PHP, ~~105~~ ~~113~~ 93 bytes
+3 for `n=1`; +9 for `$argv`, -1-3 golfed
-20: noticed that I don´t have to the combinations, but only their count
```
for($i=1<<$n=$argv[1];$i--;)$r+=!preg_match("#11|(0|^)0[0,]#",sprintf("%0{$n}b,",$i));echo$r;
```
run with `-r`
loop from 2\*\*n-1 to 0:
* check binary n-digit representation for `11`, `000`, `00` at the beginning or the end, or a single `0`
* if no match, increase result
print result
**same size, slightly simpler regex**
```
for($i=1<<$n=$argv[1];--$i;)$r+=!preg_match("#11|^00|00[,0]#",sprintf("%0{$n}b,",$i));echo$r;
```
* loop from 2\*\*n-1 to 1 (instead of 0)
* check binary representation for `11`, `00` at the beginning or the end, or `000`
* prints nothing for n=0
**PHP, 82 bytes**
[Arnauld´s answer](https://codegolf.stackexchange.com/q/94085#94085) ported and golfed:
```
for($i=$k=1<<$n=$argv[1];--$i;)$r+=!($i&$x=$i/2|$i*2)&&(($i|$x)&~$k)==$k-1;echo$r;
```
prints nothing for n=0
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
,’fR_2߀So1
```
[Try it online!](http://jelly.tryitonline.net/#code=LOKAmWZSXzLDn-KCrFNvMQ&input=&args=MTk) or [verify all test cases](http://jelly.tryitonline.net/#code=LOKAmWZSXzLDn-KCrFNvMQo54bi2wrXFvMOH4oKsRw&input=).
### How it works
```
,’fR_2߀So1 Main link. Argument: n
’ Decrement; yield n - 1.
, Pair; yield [n, n - 1].
R Range; yield [1, ..., n].
f Filter; keep the elements that are common to both lists.
This yields [n, n - 1] if n > 1, [1] if n = 1, and [] if n < 1.
_2 Subtract 2 from both elements, yielding [n - 2, n - 3], [-1], or [].
߀ Recursively call the main link for each integer in the list.
S Take the sum of the resulting return values.
o1 Logical OR with 1; correct the result if n < 1.
```
[Answer]
# JavaScript (ES6) / Recursive, ~~30~~ 27 bytes
*Edit: saved 3 bytes thanks to Shaun H*
```
let
f=n=>n<3?n||1:f(n-2)+f(n-3)
for(var n = 1; n < 16; n++) {
console.log(n, f(n));
}
```
# JavaScript (ES6) / Non-recursive ~~90~~ 77 bytes
*Edit: saved 13 bytes thanks to Conor O'Brien and Titus*
```
let f =
n=>[...Array(k=1<<n)].map((_,i)=>r+=!(i&(x=i>>1|i+i))&&((i|x)&~k)==k-1,r=0)|r
for(var n = 1; n < 16; n++) {
console.log(n, f(n));
}
```
[Answer]
# Mathematica, 35 bytes
```
a@0=a@1=1;a@2=2;a@b_:=a[b-2]+a[b-3]
```
Defines a function `a`. Takes an integer as input and returns an integer as output. Simple recursive solution.
[Answer]
# [AnyDice](http://anydice.com), 51 bytes
```
function:A{ifA<3{result:(A+2)/2}result:[A-2]+[A-3]}
```
There should be more AnyDice answers around here.
My solution defines a recursive function that calculates `a(n)=a(n-2)+a(n-3)`. It returns `a(0)=a(1)=1` and `a(2)=2` using some integer division magic.
[Try it online](http://anydice.com/program/96c7)
Note: the output may look weird, and that's because it's usually used to output dice probabilities. Just look at the number to the left of the bar chart.
[Answer]
# Perl, ~~35~~ 34 bytes
Includes +1 for `-p`
Give input on STDIN
```
checkmate.pl <<< 8
```
`checkmate.pl`:
```
#!/usr/bin/perl -p
$\+=$b-=$.-=$\-$b*4for(++$\)x$_}{
```
A newly developed secret formula. Ripple update 3 state variables without the need for parallel assignments.
It is equally short (but a lot slower and taking a lot more memory) to just solve the original problem:
```
#!/usr/bin/perl -p
$_=grep!/XX|\B-\B/,glob"{X,-}"x$_
```
but that doesn't work for `0`
[Answer]
## JavaScript (ES6), 62 bytes
```
n=>[1,...Array(n)].reduce(($,_,i,a)=>a[i]=i<3?i:a[i-3]+a[i-2])
```
This is the first time that I've needed two dummy variable names. A recursive version would probably be shorter, but I really like `reduce`... Edit: Found a solution, also 62 bytes, which only has one dummy variable:
```
n=>[1,...Array(n)].reduce((p,_,i,a)=>a[i]=i<5?i+2>>1:a[i-5]+p)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
The recursive solution [is ~~probably~~](https://codegolf.stackexchange.com/a/94125/53748) shorter...
```
Ḥ⁹_c@⁸
+3µ:2R0;瀵S
```
See it at **[TryItOnline](http://jelly.tryitonline.net/#code=4bik4oG5X2NA4oG4CiszwrU6MlIwO8On4oKswrVT&input=&args=OQ)**
Or see the series for `n = [0, 99]`, also at **[TryItOnline](http://jelly.tryitonline.net/#code=4bik4oG5X2NA4oG4CiszwrU6MlIwO8On4oKswrVTCsKz4bi2w4figqw&input=)**
How?
Returns the `n+3`th Padovan's number by counting combinations
```
Ḥ⁹_c@⁸ - Link 1, binomial(k, n-2k): k, n
Ḥ - double(2k)
⁹ - right argument (n)
_ - subtract (n-2k)
⁸ - left argument (k)
c@ - binomial with reversed operands (binomial(k, n-2k))
+3µ:2R0;瀵S - Main link: n
µ µ - monadic chain separation
+3 - add 3 (n+3)
:2 - integer divide by 2 ((n+3)//2)
R - range ([1,2,...,(n+3)//2]
0; - 0 concatenated with ([0,1,2,...,(n+3)//2]) - our ks
ç€ - call previous link as a dyad for each
S - sum
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 25+2 = 27 bytes
```
211rv
v!?:<r@+@:$r-1
>rn;
```
Needs the input to be present on the stack at program start, so +2 bytes for the `-v` flag. [Try it online!](http://fish.tryitonline.net/#code=MjExcnYKdiE_OjxyQCtAOiRyLTEKPnJuOw&input=&args=LXYgOA)
The first line initialises the stack to `1 1 2 n`, where `n` is the input number. The second line, running backwards, checks that `n` is greater than 1. If it is, `n` is decremented and the next element in the sequence is generated as follows:
```
r$:@+@r a(n-3) a(n-2) a(n-1) n
r Reverse - n a(n-1) a(n-2) a(n-3)
$ Swap - n a(n-1) a(n-3) a(n-2)
: Duplicate - n a(n-1) a(n-3) a(n-2) a(n-2)
@ Rotate 3 - n a(n-1) a(n-2) a(n-3) a(n-2)
+ Add - n a(n-1) a(n-2) a(n)
@ Rotate 3 - n a(n) a(n-1) a(n-2)
r Reverse - a(n-2) a(n-1) a(n) n
```
The final line outputs the number on the bottom of the stack, which is the required element in the sequence.
[Answer]
# FRACTRAN, ~~104~~ 93 bytes
Input is `11**n*29` and output is `29**checkmate(n)`.
This is mostly for fun, especially since I'm currently being outgolfed by Python, JS, *and* Java. Same number of bytes as PHP though :D Golfing suggestions welcome.
```
403/85 5/31 3/5 9061/87 3/41 37/3 667/74 37/23 7/37 38/91 7/19 5/77 1/7 1/17 1/2 340/121 1/11
```
**Ungolfing**
```
At the start we have 11**n * 29
1/11 If n < 2, we remove the 11s and print 29**1
340/121 If n >= 2, we subtract two 11s (n-2) and add one 17, two 2s and one 5.
We now have 17**1 * 29**1 * 2**2 * 5.
These are the register for a, b, c at registers 17, 29, and 2.
5 is an indicator to start the first loop.
This loop will move a to register 13.
403/85 5/31 Remove the 17s one at a time, adds them to the 13 register.
5 and 31 reset the loop.
3/5 Next loop: moves b to a and adds b to a in register 13.
9061/87 3/41 Remove the 29s one at a time, adds them to the 17 and 13 registers.
3 and 41 reset the loop.
37/3 Next loop: moves c to b in register 29.
667/74 37/23 Remove the 2s one at a time, adds them to the 29 register.
37 and 23 reset the loop.
7/37 Next loop: moves a+b to c in register 2.
38/91 7/19 Remove the 13s one at a time, adds them to the 2 register.
7 and 19 reset the loop.
5/77 Move to the first loop if and only if we have an 11 remaining.
1/7 1/17 1/2 Remove the 7 loop indicator, and all 17s and 2s.
Return 29**checkmate(n).
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 20 bytes
```
1_2_{2$2$+}ri*;;;o];
```
[Try it online!](http://cjam.tryitonline.net/#code=MV8yX3syJDIkK31yaSo7OztvXTs&input=OA)
### Explanation
This uses the recurrence relationship shown in the [OEIS page](http://oeis.org/A228361).
```
1_2_ e# Push 1, 1, 2, 2 as initial values of the sequence
ri e# Read input
{ } * e# Repeat block that many times
2$2$ e# Copy the second and third elements from the top
+ e# Add them
;;; e# Discard the last three elements
o e# Output
]; e# Discard the rest to avoid implicit display
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 12 bytes
```
XXXIGX@DŠ0@+
```
**Explanation**
```
XXX # initialize stack as 1, 1, 1
IG # input-1 times do:
X@ # get the item 2nd from bottom of the stack
DŠ # duplicate and push one copy down as 2nd item from bottom of the stack
0@ # get the bottom item from the stack
+ # add the top 2 items of the stack (previously bottom and 2nd from bottom)
# implicitly print the top element of the stack after the loop
```
[Try it online!](http://05ab1e.tryitonline.net/#code=WFhYSUdYQETFoDBAKw&input=MTU)
[Answer]
# Actually, 25 bytes
This seems a little long for a simple `f(n) = f(n-2) + f(n-3)` recurrence relation. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pWXMjEx4pWcwqxgKTsoKylgbmFr4pWcMuKVnDI8SUBF&input=OA)
```
╗211╜¬`);(+)`nak╜2╜2<I@E
```
**Ungolfing**
```
Implicit input n.
╗ Save n to register 0.
211 Stack: 1, 1, 2. Call them a, b, c.
╜¬ Push n-2.
`...`n Run the following function n-2 times.
); Rotate b to TOS and duplicate.
(+ Rotate a to TOS and add to b.
) Rotate a+b to BOS. Stack: b, c, a+b
End function.
ak Invert the resulting stack and wrap it in a list. Stack: [b, c, a+b]
╜ Push n.
2 Push 2.
╜2< Push 2 < n.
I If 2<n, then 2, else n.
@E Grab the (2 or n)th index of the stack list.
Implicit return.
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 18 bytes
This is an Actually port of Dennis' longer Jelly answer. Golfing suggestions welcome. [Try it online!](https://tio.run/##ASwA0/9hY3R1YWxsef//Mys74pWWwr1MdXLijKA7z4TilZwtQOKWiOKMoU3Oo///OQ "Actually – Try It Online")
```
3+;╖½Lur⌠;τ╜-@█⌡MΣ
```
**Ungolfing**
```
Implicit input n.
3+ Add 3. For readibility, m = n+3.
;╖ Duplicate and store one copy of m in register 0.
½Lu floor(m/2) + 1.
r Range from 0 to (floor(m/2)+1), inclusive.
⌠...⌡M Map the following function over the range. Variable k.
; Duplicate k.
τ╜- Push m-2k. Stack: [m-2k, k]
@█ Swap k and m-2k and take binomial (k, m-2k).
If m-2k > k, █ returns 0, which does not affect the sum() that follows.
End function.
Σ Sum the list that results from the map.
Implicit return.
```
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
r=1:1:2:zipWith(+)r(tail r)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v8jW0MrQysiqKrMgPLMkQ0Nbs0ijJDEzR6FI839uYmaebUFRZl6JQnSRomJFTYWNbrShnp6RQWzsfwA "Haskell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
⁺»‡_+TḞ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLigbrCu+KAoV8rVOG4niIsIiIsIiJd)
Uses the same recurrence relation `a(n) = a(n-2) + a(n-3)`
```
Ḟ # Create an infinite list
⁺» # Starting from digits of 112
‡ # Generate new terms by a function
T # Taking in the last three terms
_ # Pop the first
+ # Add the other two together
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÉKΦΘÄO¢
```
[Run and debug it](https://staxlang.xyz/#p=904be8e98e4f9b&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&a=1&m=2)
Uses the recurrence relation. `C(n) = C(n-2) + C(n-3)`
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 33 bytes
```
f(n){return n<2?1:f(n-2)+f(n-3);}
```
[Try it online!](https://tio.run/##Fcg9CoAwDEDh3VMEQUioBa2b9eciLlKtZDBK0Uk8e63Le/A5vTkXo0ehJ6zXHQSkM2PdJtGG1L@G7Bv3mQXpAX8EZLmA@8pyZ1KUIjhDMo95sYAeoFgmyUsuPTKRhTeLHw "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ƵBSλè₂₃+
```
[Try it online](https://tio.run/##yy9OTMpM/f//2Fan4HO7D6941NT0qKlZ@/9/CwA) or [verify the infinite list](https://tio.run/##yy9OTMpM/f//2Fan4HO7HzU1PWpq1v7/HwA).
**Explanation:**
```
ƵB # Push compressed integer 112
S # Convert it to a list of digits: [1,1,2]
λ # Start a recursive environment,
è # to output the 0-based (implicit) input'th value
# (which will be output implicitly as result afterwards)
ƵBS # Starting at a(0)=1, a(1)=1, a(2)=2
# And where every following a(n) is calculated as:
₂₃+ # a(n-2) + a(n-3)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵB` is `112`.
] |
[Question]
[
## Challenge:
**Input:** A list of distinct positive integers within the range \$[1, \text{list-size}]\$.
**Output:** An integer: the amount of times the list is [riffle-shuffled](https://upload.wikimedia.org/wikipedia/commons/7/7c/Riffle_shuffle.jpg). For a list, this means the list is split in two halves, and these halves are interleaved (i.e. riffle-shuffling the list `[1,2,3,4,5,6,7,8,9,10]` once would result in `[1,6,2,7,3,8,4,9,5,10]`, so for this challenge the input `[1,6,2,7,3,8,4,9,5,10]` would result in `1`).
## Challenge rules:
* You can assume the list will only contain positive integers in the range \$[1, \text{list-size}]\$ (or \$[0, \text{list-size}-1]\$ if you choose to have 0-indexed input-lists).
* You can assume all input-lists will either be a valid riffle-shuffled list, or a sorted list which isn't shuffled (in which case the output is `0`).
* You can assume the input-list will contain at least three values.
## Step-by-step example:
Input: `[1,3,5,7,9,2,4,6,8]`
Unshuffling it once becomes: `[1,5,9,4,8,3,7,2,6]`, because every even 0-indexed item comes first `[1, ,5, ,9, ,4, ,8]`, and then all odd 0-indexed items after that `[ ,3, ,7, ,2, ,6, ]`.
The list isn't ordered yet, so we continue:
Unshuffling the list again becomes: `[1,9,8,7,6,5,4,3,2]`
Again becomes: `[1,8,6,4,2,9,7,5,3]`
Then: `[1,6,2,7,3,8,4,9,5]`
And finally: `[1,2,3,4,5,6,7,8,9]`, which is an ordered list, so we're done unshuffling.
We unshuffled the original `[1,3,5,7,9,2,4,6,8]` five times to get to `[1,2,3,4,5,6,7,8,9]`, so the output is `5` in this case.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input Output
[1,2,3] 0
[1,2,3,4,5] 0
[1,3,2] 1
[1,6,2,7,3,8,4,9,5,10] 1
[1,3,5,7,2,4,6] 2
[1,8,6,4,2,9,7,5,3,10] 2
[1,9,8,7,6,5,4,3,2,10] 3
[1,5,9,4,8,3,7,2,6,10] 4
[1,3,5,7,9,2,4,6,8] 5
[1,6,11,5,10,4,9,3,8,2,7] 6
[1,10,19,9,18,8,17,7,16,6,15,5,14,4,13,3,12,2,11,20] 10
[1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20] 17
[1,141,32,172,63,203,94,234,125,16,156,47,187,78,218,109,249,140,31,171,62,202,93,233,124,15,155,46,186,77,217,108,248,139,30,170,61,201,92,232,123,14,154,45,185,76,216,107,247,138,29,169,60,200,91,231,122,13,153,44,184,75,215,106,246,137,28,168,59,199,90,230,121,12,152,43,183,74,214,105,245,136,27,167,58,198,89,229,120,11,151,42,182,73,213,104,244,135,26,166,57,197,88,228,119,10,150,41,181,72,212,103,243,134,25,165,56,196,87,227,118,9,149,40,180,71,211,102,242,133,24,164,55,195,86,226,117,8,148,39,179,70,210,101,241,132,23,163,54,194,85,225,116,7,147,38,178,69,209,100,240,131,22,162,53,193,84,224,115,6,146,37,177,68,208,99,239,130,21,161,52,192,83,223,114,5,145,36,176,67,207,98,238,129,20,160,51,191,82,222,113,4,144,35,175,66,206,97,237,128,19,159,50,190,81,221,112,3,143,34,174,65,205,96,236,127,18,158,49,189,80,220,111,2,142,33,173,64,204,95,235,126,17,157,48,188,79,219,110,250]
45
```
[Answer]
# JavaScript (ES6), 44 bytes
*Shorter version suggested by [@nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof)*
Expects a deck with 1-indexed cards as input.
```
f=(a,x=1)=>a[x]-2&&1+f(a,x*2%(a.length-1|1))
```
[Try it online!](https://tio.run/##ndLNqsIwEAXgvU/hRmmuU@3kxzaL@iLiInjbqpRWVMSF715P7gURWiGaZUi@OTPJwV3deXvaHy9x0/4WXVfmkaNbziJfufVtE8vplGel3/uRk8jN66KpLruY7yxEt22bc1sX87qtojJaM0lSGyHGn63FYpyMhijSZD7jhilF8qtU3KeWyJUCzJDNkiFOAuRhKgOmwVmABmQoJfuUBZaCMwDRbDCl@pQBpsEpgBJkKKWHxm6AWDAaUBb2BKBMn@KE2ILiDNE4BctLH874J9DwWfkJSt87vs5/Zj/25H0sHMQtEPD4mfKvlPQoKqDci5V2Dw "JavaScript (Node.js) – Try It Online")
Given a deck \$[c\_0,\ldots,c\_{L-1}]\$ of length \$L\$, we define:
$$x\_n=\begin{cases}
2^n\bmod L&\text{if }L\text{ is odd}\\
2^n\bmod (L-1)&\text{if }L\text{ is even}\\
\end{cases}$$
And we look for \$n\$ such that \$c\_{x\_n}=2\$.
---
# JavaScript (ES6), ~~ 57 52 ~~ 50 bytes
Expects a deck with 0-indexed cards as input.
```
f=(a,x=1,k=a.length-1|1)=>a[1]-x%k&&1+f(a,x*-~k/2)
```
[Try it online!](https://tio.run/##ndK9TsMwFAXgvU/hhSoGO8n1T5MM7tiXqDpYJW0hIalohTIgXj0cg4SQEiQXb7bs7x5f@9m/@cv@9el8lV3/WI/jwSVeDI5E43za1t3xepL0Ttyt/ZZ2crhrlkt6OIRN9/KjyRQfN8wxz9yaYTV98edkCJOBSUacLxb7vrv0bZ22/THZJFsSSugd5@y2kWUsn6WEEfY2bp7SQv0rFU2pFXIVAEtkq4QVlEfI81QJzICrAFqQsZSaUhWwApwFiMtGU3pKWWAGnAaoQMZSZq7tFkgFxgAq454AlJ1SlAuqQFGJaFSApVUIZ8MTGPikQwdVuDu@znfm0Pb871jYiFMg4NFPyq9SKqCogHK/rGL8BA "JavaScript (Node.js) – Try It Online")
### How?
Since JS is lacking native support for extracting array slices with a custom stepping, simulating the entire riffle-shuffle would probably be rather costly (but to be honest, I didn't even try). However, the solution can also be found by just looking at the 2nd card and the total number of cards in the deck.
Given a deck of length \$L\$, this code looks for \$n\$ such that:
$$c\_2\equiv\left(\frac{k+1}{2}\right)^n\pmod k$$
where \$c\_2\$ is the second card and \$k\$ is defined as:
$$k=\begin{cases}
L&\text{if }L\text{ is odd}\\
L-1&\text{if }L\text{ is even}\\
\end{cases}$$
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
f=lambda x:x[1]-2and-~f(x[::2]+x[1::2])
```
[Try it online!](https://tio.run/##HZJLaltRFAS34qFM2nDPuX9DViI0UDAihkQxQQFlkq0r1R49eNB9i@rz8ff2/dc1H4/L1x/nn9/ezk/31/sxTi95vr69/Lsc7sfX1zx94Z@/z4@P3@/X29Pl8H79@HM7PD8/jqFooZqKmRpVWap2U9amyK4Yij7UpmJNzaWMpShb2TbJokrBDI0kmdoU1EqSNOHe1ShYQ3OSpKTQ0GioW7WQLBpBMrQpMEWSdripUbC65iBJSaHBGJUGnh5bo5As2hSYIkkT7lWNgtU0O0lKCg3GqDTw9FjqFOytTYEp0mmSqUbBqpoIMEWhwRiVBp4eU52CvbQQYIokTbiHGgUrNRFgikKDMSoNPD2GOgV7aoFviiBNuBehP1YI/WkK/KcxGODTfxf@Yw/hP03BAFa/hf1YRdhPQ6A/TVFdQLAJ/bG70J@GwD8PYx/5MbeQn2bAfhqiegKCVdgPjgD7aQb08y7ycR/cAO6zmJ8CQ2Df8rkB5Ac3gPw0A/Z5F/eoD04A9ckFoD7NUA1ALoT64AJQn0bAPc9iHvHBASA@2R/xaYT0@@SKEB/sj/g0AeZ5Fe9oD@ZHe7I@2tME9s6zrI/2YP1lcCrw7rOr8tUzPtKT7ZGeJrB1omzvo2d7rOfn9OTJkSbO9DhPlsd5msDSibK8T57lkZ4mwHr2cvoP "Python 2 – Try It Online")
-4 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒœẎ$ƬiṢ’
```
**[Try it online!](https://tio.run/##BcGxFUAwGIXRZZRf4YVIMoujVHAsoDOBgkqrtgA9e7DI796@HYbR7F7u9b3m7Dm699y/aTOzWhR4AgkJFcijgBKOkoqIcuRQiSoUcXnzAw "Jelly – Try It Online")**
### How?
```
ŒœẎ$ƬiṢ’ - Link: list of integers A
Ƭ - collect up until results are no longer unique...
$ - last two links as a monad:
Œœ - odds & evens i.e. [a,b,c,d,...] -> [[a,c,...],[b,d,...]]
Ẏ - tighten -> [a,c,...,b,d,...]
·π¢ - sort A
i - first (1-indexed) index of sorted A in collected shuffles
’ - decrement
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ ~~26~~ ~~23~~ 22 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHnQsf9W5@1LkIyLYyeNTdYqj9qKMdyIl@1DvJqAYk17sFyI2t/Z/2qG3Co96@R31TPf0fdTUfWm/8qG0ikBcc5AwkQzw8g/@nKWgY6hjrmOqY61jqGOmY6JjpWGhygUWNgOImQBkzoJyFjqUmAA "APL (Dyalog Unicode) – Try It Online")
Thanks to Ad√°m for the help, Erik the Outgolfer for -3 and ngn for -1.
The TIO link contains two test cases.
Explanation:
```
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]}
{⍵≡⍳≢⍵:0⋄1+∇⍵[⍒2|⍳⍴⍵]} ⍝ function takes one argument: ⍵, the array
⍵≡⍳≢⍵ ⍝ if the array is sorted:
⍵≡⍳≢⍵ ⍝ array = 1..length(array)
:0 ‚çù then return 0
⋄ ⍝ otherwise
1+ ‚çù increment
‚àá ‚çù the value of the recursive call with this argument:
‚çµ[ ] ‚çù index into the argument with these indexes:
⍳⍴⍵ ⍝ - generate a range from 1 up to the size of ⍵
2| ‚çù - %2: generate a binary mask like [1 0 1 0 1 0]
‚çí ‚çù - grade (sorts but returns indexes instead of values), so we have the indexes of all the 1s first, then the 0s.
```
[¬π](https://github.com/vendethiel/trying.apl/blob/master/ex/stop-shuffling.dyalog)
[Answer]
# [R](https://www.r-project.org/), ~~58~~ ~~55~~ 45 bytes
```
a=scan();while(a[2]>2)a=matrix(a,,2,F<-F+1);F
```
[Try it online!](https://tio.run/##nZTNattAFIX3fQpBNhadwNw7M9KIJN3VL1G6ECZuBYkDjkMLpc/ufkf@CemmTrNUfM499ztX2u7Xze11s37ZrHbT02Yxtc2v5nk1bt48bafm6vPjy8O4mzbfDv9eP22b3f2zHuzHOz1atDc/vk8P94vxi3/95O149zjuttPPxRiCh@Xt9fKjtTfL/e8P68VqYTxLbXvVvPcvvspDDuW9Fid5Cv4/0@0o75jfY1LJMIQSLF7kZufpBbkj7t6Two/yyvyMfMCkYHbh9JN8wKDHomACh0vl6SgvGGQs0rxCd6k8v9l9OGwf6qX7lzN5sxn4TF4N0MS/TbqjHJ0NCK2itJ4k1smzyDPjaUlAXVg4stNqFv9Kzz/5JTI87LzMbO8ywpURr/r@ND/jwS96yME@pjDQZELgZRYVqsWyEg29yRL7zMQcQ8KghwHxIvVjkBQ2z0EKfWpqF3qKUa6IQ8YhAYpgfQydduICMFAKT3PWwuIYVFbjsJUi4qAYCQdGd0PoIsoYBgyUwv2wPy8hBjWHvqBULzgoRsKB0V0NBYMB5hgohduMqIAMg8oVAUApIg6KkXBQLdw2BgNFAUApPM7Yi4WMQaV3AChFxEExEg6M7jhttdKHSnyloCE1UzgaDKoF8LtSwN8VgwJm/pwBBgNVEl8pKEDouXj0NQbou0KA35UiyQAhnyL0Qwngd4WAP4OhD3zreVNZXxmg7wqRVAFCDgo9RwB9VwbwMxf4SQfKq872UfkxUAjoCz43AHzjBoDvygB95sIe9MYJdLo/4qNXhqQA6Hh7kHMBoHdFgL1unw8Jcg4A8E7/gHdFcM1HFwPgjf4B70pg@gAb3JPeAoazOe2D3ZVA3BlL@0XvXAxVwbEwfboN6rp6yge60z3QXQlEHSnd6@jpHuo@V6@PvgFdN0/1MHeah7krgaAjpXmdPM0D3ZUA6l70Iuay/wM "R – Try It Online")
Simulates the sorting process. Input is 1-indexed, returns `FALSE` for 0.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~34~~ 32 bytes
*-2 bytes thanks to Jo King*
```
{(.[(2 X**^$_)X%$_-1+|1]...2)-1}
```
[Try it online!](https://tio.run/##XZTNbhNBEITvPIUPATmhY013z68Q7xEpMhEHfAKBwikCnt18tcY5cPNOb1fXfNXrH1@ev/bzt5fdu9Pu4/nX/vC4j93D3d2nm6fbh7c3T/f@/rcfD4dD3N77n/PPzy@7057a7vT9@c2jW1ge7d8Pq9YuD2lx@dE5HzxOasuaebmcTyqV2qLaqF/PF5VBrVFF5PW8UanUkmpQv54nlUEtqHabl0Mv5otDn3T44AXv6mkyUHnTUyND@hj/T4oj6rxMp78qb6KhdrQQvnZ5pZPzgSsMl7TFvZLXom2vNi6K0MQGXS4hRCtzarFEYEAJKwUYCKSM1W18A4JmdRtcWm4KChWFXJbYGcW6/IMNAbmI3Bw2LonA5EIEIBcFBdlIFBjdl/VCZ7GFgFxEXG5NiAjMaqPRqcBQkI1EgdF9WkNgwRcBuQjfwDRAITBJCAByUVCQjURBEZA0AotQACAXUTbYza0iMNkUAMhFQUE2EgVGd/ZBWQyb2JcLclEerRj4fbqBP@QC/iEbBLDxJ3IEFgFiXy4IQOjZJvpnMeiHTIA/5CIlQCOrTP9qBv6QCfgzGPrA98Hecn15gH7IRCoCGlkj@lkC6Ic8gJ@5wE8tI4vP7Yv8IyAT0Bd8dgD4zg4AP@QB@syFPeidFejaOuzTLw8pA/TxcdDOBoA@ZAH22nM@K9pZAMAH@QM@ZCE0n75igHfyB3zIgesDdrindp/h3Jz0wR5yIO6MJf2m76vYlHEkXJ@@Q11bT/hAD7IHesiBqNNK9lp6sod6bNHrT8OBrp0nepgHycM85EDQaSV5rTzJAz3kAOrRyvHD@S8 "Perl 6 – Try It Online")
Similar to [Arnauld's approach](https://codegolf.stackexchange.com/a/181304/9296). The index of the second card after n shuffles is `2**n % k` with k defined as in Arnauld's answer.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 59 bytes
```
a->{int c=0;for(;a[(1<<c)%(a.length-1|1)]>2;)c++;return c;}
```
[Try it online!](https://tio.run/##bVJNa8JAEL37K4aCkNQ1uDFR06jgpdBDT@1NPGyjsbFxE7IbQWx@u327EdG2B5GZ90lmd@Ig@rv11znbl0WlaYfZq3WWe49x588urWWis0IaMMmFUvQqMkmnDlFZf@RZQkoLjb9Dka1pD8x501Umt8sViWqrXEslei9epH6@mE0zqZerOaU0O4v@/ISRktkgTovKicXS4dNp4nYd4eUbudWfff7N3dXcj92k14urja4rSUncnGNrbc0QpzdKK5pdAolOnPls2LC7kQUsvF0NmX87jsAZYzkBL2Ih44N7cgjUBza6XU8gC7COAIYg3Ysi4GMwQnCQ9gsNgQdgDK3x6N/AqI1kk/umnNuCtqlpjOa3BCA8AsQnwPgYPnxkVKFRBVDxoenqm0r4NP/mAgALEuj5tYa19o0JHGF/1TbtQcwZ7VHsSZ7aw7jXu7wdld7svaLWXomXolPnodsPB@qJuuuufGC0qCpxVJ4u2pfkGL3LKPVEWebHhcJLandum9d0zK85/wA "Java (JDK) – Try It Online")
Works reliably only for arrays with a size less than 31 or solutions with less than 31 iterations. For a more general solution, see the following solution with 63 bytes:
```
a->{int i=1,c=0;for(;a[i]>2;c++)i=i*2%(a.length-1|1);return c;}
```
[Try it online!](https://tio.run/##bVLPT8IwFL7zV7yYkGxaFjoYMOdIvJh48KQ3wqEOhsXRLWtnQnB/O37tCAH1QMh738/sdSu@xGC7@jzKXVXWhraYg8bIIrhNen92eaMyI0tlwawQWtOLkIoOPaKqeS9kRtoIg7@vUq5oB8x7NbVUm8WSRL3RvqMSvZXPyjydzB6kMovlnHJKj2IwP2AkmXKWpcMkL2svEQu5nIdJdnfny1Tehn1PBMVabczHgH9zP6nXpqkVZUl7TJy9M0SkWWujKT2FEh04C9moZVcjG7PocjVi4eU4AWeK5Qy8mEWMD6/JEdAQ2ORyPYNsjHUMMALpWhQDn4IRgYO0X2gEfAzGyBlP/g2Mu0g2u27KuSvomtrGaH5JAMJjQHwGjE/hwydWFVnVGCo@sl1DWwmf5t9cAGBBAj0/13DWoTWBI@zP2rY7iD2jO4o7yX13GP98l9e9NutdUDYmqPBaTO7d9AfRUN9Tf9VXN4we61rsdWDK7jV5Vu8zygNRVcX@UeM1dTu/y2t79tcefwA "Java (JDK) – Try It Online")
## Explanation
In a riffle, the next position is the previous one times two modulo either length if it's odd or length - 1 if it's even.
So I'm iterating over all indices using this formula until I find the value 2 in the array.
## Credits
* -8 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). (Previous algorithm, using array)
* -5 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~36 34~~ 32 bytes
*-2 bytes thanks to nwellnhof*
```
$!={.[1]-2&&$!(.sort:{$++%2})+1}
```
[Try it online!](https://tio.run/##lZQxb1NBEIRr/CscyUQxXpzbvbv37pAoKOioaRwXKYKEFAiyaZDl326@eRYIUdkpnZvZuW/23o@n3fNwOi1u3h/WG9@@jdvbxc3dev@y@/nusFitXsdxufLj6cvLbn73/PX70345P8xe7R9/zTn37f5hs37zsL1ff/z84dNydjxt3MLydn7tX5qdlVasbq9XZovrZ7qUA1NH9I3J3ap52l6obGgL6o6@4nCRMqTsaEfUFT3JL1NmKSvagjqjDxwuUpYzoYqmoyro2mW0qpSezDtKbwz2ERcfNLqKVsHOs24fuggdnhN5@ncov3MIBXL/m2FyDnlgiPsf6ThNLcj558g1YZSydWBnzkadzlfo49YIhNTlhnNhWEmWMRgpl1CJhjDIilimDBXuGjjYCEVFSjgUHHK3TKYx2aCb0BQGShF5ilm5LgaNW7E3SpFwUIyMA6OHbkNCmaxjoBQR56uz2Ri0YmNFqT3DQTEyDowemlUMOqQxUIrwiU6FFgaNygGgFAkHxcg4qAzWD4NOPQBQikgT8epWMGgsOACUIuGgGBkHRg@soAoZrRFfKShHpdRk4PfmBv5QCviHYlDAxJ/yMei0SHyloAChZz3Rt2TQD4UAfyhFlgFC3jf6Xg38oRDwZzD0ge8jj4nrKwP0QyGyKkDILqFnCaAfygB@5gI/ay15jdw@KT8GCgF9wWcHgO/sAPBDGaDPXNiD3lmBQatHfPTKkBUAHa8NORsA@lAE2GvjeevIWQDAB/0DPhQhNB9dMsA7/QM@lMD1VXO4Zz0AhnNz2gd7KIG4M5b2q15asqbgWLi@hw51bT3lAz3oHuihBKKOlO619HQP9Ziq15fUga6dp3qYB83DPJRA0JHSvFae5oEeSgD1qP99UEr9DQ "Perl 6 – Try It Online")
Reverse riffle shuffles by sorting by the index modulo 2 until the list is sorted, then returns the length of the sequence.
It's funny, I don't usually try the recursive approach for Perl 6, but this time it ended up shorter than the original.
### Explanation:
```
$!={.[1]-2&&$!(.sort:{$++%2})+1}
$!={ } # Assign the anonymous code block to $!
.[1]-2&& # While the list is not sorted
$!( ) # Recursively call the function on
.sort:{$++%2} # It sorted by the parity of each index
+1 # And return the number of shuffles
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 bytes
```
[DāQ#ι˜]N
```
[Try it online!](https://tio.run/##HZK7bR1AEAOLUcrglvfPFRtQLLzABlSI@nAjzp0ZUEvPQ4UXkDcYbps/f9XH8/n@@vfz7eXrz7/fjx@8SjVK3aptrS63rjvkPlSeqqWaS2OrztY@ch1Vu/K4JJs6Bbu0TNK6FPROkjThOTUoOEt7k6Sk0TBo6Fe9kWxaRbJ0KQiFSSc8NCg4U3uRpKTREIxOA1@vq9VINl0KQmHShGfXoOAM7UmSkkZDMDoNfL2OJgX36lIQCidN0hoUnK6NgFA0GoLRaeDrtTUpuEcHAaEwacKzNCg41kZAKBoNweg08PVamhTcrQN@KIo04dmE/jol9DsU@HcwGODb/xT@6y7h36FggKi/wn6dJuw7EOh3KHoKCA6hv@4U@h0I/PMx9pFf@wr5DgP2HYieCQh2Yb84Auw7DOjnX@TjvrgB3LuFn4JAYD/yuQHkFzeAfIcB@/yLe9QXJ4B6cwGodxh6AMiVUF9cAOodBNzzLeYRXxwA4s3@iHcQnP/JNSG@2B/xDgHm@RXvaC/mR7tZH@0OQbzzLeujvVj/BJwKvOfsunL1jI90sz3SHYJYJ8r2OXq2x7q/pydPjjRxpse5WR7nDkGkE2X5nDzLI90hwLpne/wH "05AB1E (legacy) – Try It Online")
**Explanation**
```
[ # ] # loop until
ā # the 1-indexed enumeration of the current list
D Q # equals a copy of the current list
ι˜ # while false, uninterleave the current list and flatten
N # push the iteration index N as output
```
[Answer]
# [J](http://jsoftware.com/), ~~28~~ 26 bytes
-2 bytes thanks to Jonah!
```
1#@}.(\:2|#\)^:(2<1{])^:a:
```
[Try it online!](https://tio.run/##bZTNalRBEIX3eYrCLJKADl3VXf1zURAEV65cR0HEELLxAdRnH79zB5wZcBHI3Oo6dfo7de/L8dXh7snebXZnr63Yxt@bg334/Onj0W/f/zncP27x@/bx4et2H2/91xf@@bYdH27s5sf355/2ZG5h9eqHNcvzg2px/tGpDx5NzixL82KXJ5NiUOrnh5OexsNFKTni5VxbVAf15ARjrmpJtVGvu2S/qp0GrdMom5f23E@uZE82sXsu89wXBZ9UfKDhXT2pnkaPVzkMWYHEfybymDM00O3/DOzCIQn0EL/s9EY3tcEluGOptsBRORq5H0/4IDaxQ6dLDOHGrFasIjC4F5YKDBGoMth2Cwk3zes2YCRHBYWGQuXyWBrFuu4BaQTkIuruMrksApNLkahcFBRko6LA6L6sFzqLLQTkIuJ0c7YDgdlsJJ1ijYJsVBQY3aclAgvOCMhF@A4ngYXAJFAAyEVBQTYqCoqCBUFgEQ4A5CLKDjzdGgKTLAEgFwUF2agoMLqzQspj2MS@XJCNMkkWAYHpBv6QC/iHbBDAzp/oEViEiH25IAChZ/non8WgHzIB/pCLKgEaeUfoX2ngD5mAP4OhD3wfrDvXlwfoh0xURUAjq0Q/SwD9kAfwMxf4VUvJ@8Lti/wjIBPQF3x2APjODgA/5AH6zIU96J0V6No87NMvD1UG6OONoJ0NAH3IAuy177yNtLMAgA/yB3zIQmg@fcUA7@QP@JAD15fB4V61/wzn5qQP9pADcWcs6afes2JTxpFwfVMc6tp6wgd6kD3QQw5EnVay19KTPdRjj15fIwe6dp7oYR4kD/OQA0GnleS18iQP9JADqEeW418 "J – Try It Online")
Inspired be Ven's APL solution.
## Explanation:
```
^: ^:a: while
(2<1{]) the 1-st (zero-indexed) element is greater than 2
( ) do the following and keep the intermediate results
i.@# make a list form 0 to len-1
2| find modulo 2 of each element
/: sort the argument according the list of 0's and 1's
1 }. drop the first row of the result
#@ and take the length (how many rows -> steps)
```
# [K (ngn/k)](https://gitlab.com/n9n/k), 25 bytes
Thanks to ngn for the advice and for his K interpreter!
```
{#1_{~2=x@1}{x@<2!!#x}\x}
```
[Try it online!](https://tio.run/##VZTBbhsxDER/hUEObQ8FRFLUSmkL5EMK5JYcCuRswHB/3X2jDQrkZJsrDkdvuP7z/f3t/X5/fbo@@sv1b/y6PPvtenn@GQ8Pj5fb78vt/vrFvrqF5Q/bH9at9DUt9DGoHfyY1JeVeTsfFtWgNvRzcqzzc1EsHp6HFvWDJ8Uz1D6qRb3zJLfA@CS4Tkmb52T3PXBPlgOc6AEVX5R8UvODPh86XTrdOe0pD6GRXOmTPgWecpQ@/z9uS4aaUUL27PFOH9UDm/hvaYtLJoei9sHi1shMLNDjkkGyM6U3SwQOboGNBhkEUqb6Hl4w0aRhBxTkpaHQUUiuipmj2ZB3KCIgF5HbX3FBBCbXIRq5aCjIRqLA6LFsNDqbLQTkIuK8M9EiMLsdRafIoiAbiQKjx7RCYMEWAbkI31gKTAhMIgOAXDQUZCNREH5iR2ARCADkItpGXW4dgUlyAJCLhoJsJAqMHqyHkjhsYl8uSEVpFLEjMN3AH3IB/5ANAtj8iRuBRXzYlwsCEHrWi/7ZDPohE@APuUgJ0MiC07/KwB8yAX8GQx/4frDEXF8eoB8ykYqARpaIfpYA@iEP4Gcu8FOLyFvA7Zv8IyAT0Bd8dgD4zg4AP@QB@syFPeidFRjaOezTLw8pA/Sx/7SzAaAPWYC9dpx3jHYWAPBB/oAPWQjNp68Z4J38AR9y4HqtHe6pzWc4Nyd9sIcciDtjSb/0bjWbMo6E6w/Boa6tJ3ygB9kDPeRA1Gkley092UM9dvT6K3Gga@eJHuZB8jAPORB0WkleK0/yQA85gHpU@2b3fw "K (ngn/k) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
L↑S≠ŀ¡ȯΣTC2
```
[Try it online!](https://tio.run/##HZK9jRZQEAMbcvDW7z8mJYPsRI5EiMiJkAjpAEQB9ICEREQR18jH@AqwdzTe958@fng8Xj9/@fbm@ev3P59///j769/Pt6/8eDyeSjVK3aptrS63rjvkPlSeqqWaS2OrztY@ch1Vu/K4JJs6Bbu0TNK6FPROkjThOTUoOEt7k6Sk0TBo6Fe9kWxaRbJ0KQiFSSc8NCg4U3uRpKTREIxOA6fX1Wokmy4FoTBpwrNrUHCG9iRJSaMhGJ0GTq@jScG9uhSEwkmTtAYFp2sjIBSNhmB0Gji9tiYF9@ggIBQmTXiWBgXH2ggIRaMhGJ0GTq@lScHdOuCHokgTnk3or1NCv0OBfweDAV78T@G/7hL@HQoGiPor7Ndpwr4DgX6HoqeA4BD6606h34HAP4exj/zaV8h3GLDvQPRMQLAL@8UTYN9hQD93kY/74gdw7xZ@CgKB/cjnB5Bf/ADyHQbscxf3qC9eAPXmA1DvMPQAkCuhvvgA1DsIuOcs5hFfPADizf6IdxCc@@SaEF/sj3iHAPNcxTvai/nRbtZHu0MQ75xlfbQX65@AU4H3vF1Xvp7xkW62R7pDEOtE2T5Pz/ZY98v05MmRJs70ODfL49whiHSiLJ@XZ3mkOwRY92zv/gM "Husk – Try It Online")
[Answer]
# APL(NARS), chars 49, bytes 98
```
{0{∧/¯1↓⍵≤1⌽⍵:⍺⋄(⍺+1)∇⍵[d],⍵[i∼d←↑¨i⊂⍨2∣i←⍳≢⍵]}⍵}
```
why use in the deepest loop, one algo that should be nlog(n), when we can use one linear n? just for few bytes more?
[⍵≡⍵[⍋⍵] O(nlog n) and the confront each element for see are in order using ∧/¯1↓⍵≤1⌽⍵ O(n)]test:
```
f←{0{∧/¯1↓⍵≤1⌽⍵:⍺⋄(⍺+1)∇⍵[d],⍵[i∼d←↑¨i⊂⍨2∣i←⍳≢⍵]}⍵}
f ,1
0
f 1 2 3
0
f 1,9,8,7,6,5,4,3,2,10
3
f 1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20
17
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
f=->d,r=1{d[r]<3?0:1+f[d,r*2%(1|~-d.max)]}
```
[Try it online!](https://tio.run/##XZDLCsIwEEX3foUbwcconaTpQ6x@SMhCKd0JUhAqrf56PanowlWSe@aehLT3y2Mcm2p7rKWttK99Gw72lOx103iitVksdXht69313K3Cc/RexYgN8lklFTftrZhpzUhzTgWkFCeaBJmRF5AUVkIdPObEJSAHOSCKb@wAKcgCDfhrsZAcZqCZFNOsJqIlmRYUNIdrFisu3p4yqDbeZ6KdN/@ZiOAM09SfeJKaWMeFmFbgB2790A23ue@k8V3gN94 "Ruby – Try It Online")
### How:
Search for number 2 inside the array: if it's in second position, the deck hasn't been shuffled, otherwise check the positions where successive shuffles would put it.
[Answer]
# [R](https://www.r-project.org/), ~~70~~ 72 bytes
```
x=scan();i=0;while(any(x>sort(x))){x=c(x[y<-seq(x)%%2>0],x[!y]);i=i+1};i
```
[Try it online!](https://tio.run/##FctLCsIwFAXQrVwHhQQVctM/Md1I6aCUggGp2Ai@IK496vTA2XMWH5d5U9oFb9zrGm6rmrekZIj3/alEa/0WvygZ0@Uc18dPisIOZjrJeEjTv4UjPy5kokSNFj1IsARrsAV7WFRo0IEGtGAFNmAHa/IX "R – Try It Online")
Now handles the zero shuffle case.
[Answer]
# C (GCC) ~~64~~ 63 bytes
-1 byte from nwellnhof
```
i,r;f(c,v)int*v;{for(i=r=1;v[i]>2;++r)i=i*2%(c-1|1);return~-r;}
```
This is a drastically shorter answer based on Arnauld's and Olivier Grégoire's answers. I'll leave my old solution below since it solves the slightly more general problem of decks with cards that are not contiguous.
[Try it online](https://tio.run/##dZPNahtBEITvfgphMEh2GaZ7dnZmWJQXUXwISmR0iBIWx/gnzqsrXy8k4IN1XFHVxVc1@9v7/f58PmqeDuu9HjfH08P14/R6@DGvj9t5a9Pj7nj3yaebm3lz3B6v/Wq9v7Xftpnmbw@/5tOf23l6O6Naff9yPK03q9eLFb/48LTzku5W29WryQZTdll1jVmesvogz4PMi2yUlVFDlbWq2uTWZKnLh44yKWNQTaOjdHUMckaJGnEpGjBoo2pFiUnCYcAhd@WEMmk0lKaOQaRw1CEeNGDQiuqIEpOEQ8TIOHB67BoTyqSOQaRw1IhL1oBBG1QLSkwSDhEj48Dpsalg0Ls6BpHCQ43SNWDQsioAIkXCIWJkHDg9VhUMelMDQKRw1IiLacCguSoAIkXCIWJkHDg9jioY9KpG/EhhqBGXJPBbM4HfIwX8PWJQwMK/CP7WR8HfIwUFBPou6FtLgr5HCPB7pMhhgHAQ@K0Xgd8jBPw5DH3gW@0CvkcG6HuEyFEBwizoGyOAvkcG8HMX@LA3NgB7T5EfgwgB/YDPBoBvbAD4Hhmgz13Yg96YAOidBYDeI0OOAOhMoDcWAHqPCLDnLOQBbwwA8E7/gPeI4HEfXRLgjf4B75EA8lyFO9iN@sHutA92jwTBnbO0D3aj/RbBsYB7zC4rVk/5QHe6B7pHgqCOlO5j9HQPdV@qR48ONXKqh7nTPMw9EgR0pDQfk6d5oHskgDrv721a3uPPmRd5WF9eff18utRhzT962mymi/@v9Xnn/x4r3dBFX1aXlzcWsyIFoaPdtCx5WN5twP7oRtLzuxMvu/ruwmL4gbjqJbRv578)
---
# C (GCC) 162 bytes
```
a[999],b[999],i,r,o;f(c,v)int*v;{for(r=0;o=1;++r){for(i=c;i--;(i&1?b:a)[i/2]=v[i])o=(v[i]>v[i-1]|!i)&o;if(o)return r;for(i+=o=c+1;i--;)v[i]=i<o/2?a[i]:b[i-o/2];}}
```
[Try it online](https://tio.run/##dZPNahtBEITvfgphMEh2GaZ7dnZmWJQXUXwISmR0iBIWx/gnzqsrXy8k4IN1XFHVxVc1@9v7/f58PmqeDuu9HjfH08P14/R6@DGvj9t5a9Pj7nj3yaebm3lz3B6v/Wq9v7Xftpnmbw@/5tOf23l6O6Naff9yPK03q9eLFb/48LTzku5W29WryQZTdll1jVmesvogz4PMi2yUlVFDlbWq2uTWZKnLh44yKWNQTaOjdHUMckaJGnEpGjBoo2pFiUnCYcAhd@WEMmk0lKaOQaRw1CEeNGDQiuqIEpOEQ8TIOHB67BoTyqSOQaRw1IhL1oBBG1QLSkwSDhEj48Dpsalg0Ls6BpHCQ43SNWDQsioAIkXCIWJkHDg9VhUMelMDQKRw1IiLacCguSoAIkXCIWJkHDg9jioY9KpG/EhhqBGXJPBbM4HfIwX8PWJQwMK/CP7WR8HfIwUFBPou6FtLgr5HCPB7pMhhgHAQ@K0Xgd8jBPw5DH3gW@0CvkcG6HuEyFEBwizoGyOAvkcG8HMX@LA3NgB7T5EfgwgB/YDPBoBvbAD4Hhmgz13Yg96YAOidBYDeI0OOAOhMoDcWAHqPCLDnLOQBbwwA8E7/gPeI4HEfXRLgjf4B75EA8lyFO9iN@sHutA92jwTBnbO0D3aj/RbBsYB7zC4rVk/5QHe6B7pHgqCOlO5j9HQPdV@qR48ONXKqh7nTPMw9EgR0pDQfk6d5oHskgDrv721a3uPPmRd5WF9eff18utRhzT962mymi/@v9Xnn/x4r3dBFX1aXlzcWsyIFoaPdtCx5WN5twP7oRtLzuxMvu/ruwmL4gbjqJbRv578)
```
a[999],b[999],i,r,o; //pre-declare variables
f(c,v)int*v;{ //argument list
for(r=0;o=1;++r){ //major loop, reset o (ordered) to true at beginning, increment number of shuffles at end
for(i=c;i--;(i&1?b:a)[i/2]=v[i]) //loop through v, split into halves a/b as we go
o=(v[i]>v[i-1]|!i)&o; //if out of order set o (ordered) to false
if(o) //if ordered
return r; //return number of shuffles
//note that i==-1 at this point
for(i+=o=c+1;i--;)//set i=c and o=c+1, loop through v
v[i]=i<o/2?a[i]:b[i-o/2];//set first half of v to a, second half to b
}
}
```
[Answer]
# R, 85 bytes
```
s=scan();u=sort(s);k=0;while(any(u[seq(s)]!=s)){k=k+1;u=as.vector(t(matrix(u,,2)))};k
```
[Try it online.](https://tio.run/##lZTNjtowFIX3fYpUs0lUt7Kv7cQRZdmnqLpACFrEDKgk9EejeXb6nQzMqN0UWIacc4@/c53DaV19fF@tj7vluNnv6k1TPVbDcrH762mzqe4@PRzvF@Nm9/X57/X@UI2rQQ9Ow1yP6mZ2nA/7w1gPzWw797Of3zb3q3qx@10fPw@r7zz@8nY@NM3jdr59F3h5MXz4sVqO@0M91g@L8bD5VR@ds6Zpnmbb09Obdb2sgzMXm@auuvXnX@UuuXyrxUUelef26eEsb5nfYVLI0Lvsgr/KLbxMz8gNcXtLCjvLC/MT8h6TjNmV0y/yHoMOi4wJHK6Vx7M8Y5CwiNMR2mvl6a@z98@nd@Xa8@cX8iFMwCfyaoAm/m/SnuXoQo8wFJShI0lo5ZnlmfAMUUBNWFiyy9GC/yc9f/ImMjzCy2Eme5MRrox41XeX@QkP3uggB3sfXU@TEYHlSZSpFstCNPRBltgnJibvIgYdDIjnqR@DqLBpCpLpU1Nb11GMcnkcEg4RUATrvGt1JjYAA6WwOGXNHByDwtFYbKXwOChGxIHRbe9aj9K7HgOlMHs@P5cQg5Jcl1GqFxwUI@LA6La4jEEPcwyUwsKEKIMMg8IWAUApPA6KEXFQLew2Bj1FAUApzE/Yc3AJg0LvAFAKj4NiRBwY3bLaaqVzhfhKQUNqJrM0GJTgwG9KAX9TDAqY@LMGGPRUSXyloAChZ@PRF@@gbwoBflOKKAOEfIrQ99mB3xQC/gyGPvBDx03l@MoAfVOIqAoQslDoWQLomzKAn7nAj1pQrjqn98qPgUJAX/DZAeAHdgD4pgzQZy7sQR9YgVb7R3z0yhAVAB23BzkbAHpTBNhr9/mQIGcBAG/0D3hTBNN8dN4BPtA/4E0Jgj7AAe5Rt4DhnJz2wW5KIO6Mpf2sO@ddUXAsgj7dAeraesoHutE90E0JRB0p3Wvp6R7qNlWvj34Aunae6mFuNA9zUwJBR0rzWnmaB7opAdQt6yKmfPoD)
**Explanation**
Stupid (brute force) method, much less elegant than following the card #2.
Instead of unshuffling the input `s` we start with a sorted vector `u` that we progressively shuffle until it is identical with `s`. This gives warnings (but shuffle counts are still correct) for odd lengths of input due to folding an odd-length vector into a 2-column matrix; in that case, in R, missing data point is filled by recycling of the first element of input.
The loop will never terminate if we provide a vector that cannot be unshuffled.
Addendum: you save one byte if unshuffling instead. Unlike the answer above, there is no need to transpose with `t()`, however, ordering is `byrow=TRUE` which is why `T` appears in `matrix()`.
# [R](https://www.r-project.org/), 84 bytes
```
s=scan();u=sort(s);k=0;while(any(s[seq(u)]!=u)){k=k+1;s=as.vector(matrix(s,,2,T))};k
```
[Try it online!](https://tio.run/##BcFNCsIwEAbQq0x3MzRIW/8Ww9zCnbgIJdASbTFfYhXx7PG9VCsMo19YtBjWlBmi0Trdpvke2C8fxhXhyUVujRWRb7TY9grz2L3CmNfED5/T/GY4N7iLyE9j7WlPRzrTQAc61T8 "R – Try It Online")
[Answer]
# [PowerShell](https://docs.microsoft.com/en-us/powershell/), ~~116 114 108 84~~ 78 bytes
-24 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)'s [solution](https://codegolf.stackexchange.com/a/181306/68224).
-6 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy).
```
param($a)for(;$a[1]-2){$n++;$t=@{};$a|%{$t[$j++%2]+=,$_};$a=$t.0+$t.1;$j=0}+$n
```
[Try it online!](https://tio.run/##HZLLaltBEER/ZgwStxKme94Igf/DmKCFQzCObRSBF7K/XTntzV1cqJrDqX5/@3g6//vz9PJyu72fzqe/u3Ta/3477w7p9GCPP3x/Ta/bdkiX4/31i5@fd9d0eUjP23bnj9tR6Vf8PabLz7zxsUN6PuavLb3ebrf7ncmqqbhsuHqR56JV5aXKvMm6rHXVIZtDY8ptyvKS10Uyq1AwTN1JuhYFpZAkTbg1VQpm1xgkKck0VBrKUskks7qRNC0KgsJJR7iqUjCbRidJSaYhMAoNPN2XeiaZtSgICidNuBVVCmbVaCQpyTQERqGBp/tUo2AtLQqCwiNN0lUpmEUDAUGRaQiMQgNP96FGwZqaCAgKJ024mSoF0zUQEBSZhsAoNPB072oUrKEJflAYacItC/02Tej3oMC/BwYDfPtvwr@tLvx7UDBAqF/Cvs0s7HtAoN@DokQBwSr022pCvwcE/nkY@8i3sYR8Dwbse0CUmIBgEfaNI8C@BwP6eRf5uDduAPeeg5@CgMB@yOcGkG/cAPI9GLDPu7hHvXECqHcuAPUeDCUAyJlQb1wA6j0QcM@zmEe8cQCId/ZHvAeCx/vkshBv7I94DwLM8yre0W7Mj3ZnfbR7EIR3nmV9tBvrzwCnAu9xdkVx9YyPdGd7pHsQhHWibB9Hz/ZY9@/pyZMjTZzpce4sj3MPgpBOlOXj5Fke6R4EWPeW9/8B)
[Answer]
# [Lua (LuaJIT)](https://luajit.org/), ~~119~~ ~~96~~ 79 bytes
```
n=t;while 2~=n[2]do n={}for a=1,#t*2,2 do x=a-#t n[#n+1]=t[a]or t[x+x%2]end;t=n
```
[Try it online!](https://tio.run/##HZLBahtBEETv/gqBCVhxGaZ7ZnZmMHvKZwgdhGwTGbMKZk0Mxvl15bWOWlQ1j1f99nF4ePs4vJ7Wy8vHclxP52Xz6/z0fLduL8u8Pv79fXp73vi/edn5/um8Weav75fz@@Ywm27Xny7f8PVzPjzcrptld7vc235ed4c9/1l3n/efP3z/vDw9rvNyOc53xw3f0/bebvh48@f9tKx3x@31x8312S@TFVN2WXNNWZ6yRpHnIvMqm2R1Ummy3tS63LosDXkZJJMyBc00QZZcg4KcSZImXKsKBX1SayQpSTQUGvJQTiSTJiNpGhQEhZOOcFGhoFe1iSQliYbAyDTw9DQ0JZJJg4KgcNKEa1ahoBe1SpKSRENgZBp4euqqFIyhQUFQeKRJugoFPashICgSDYGRaeDpqalSMLo6AoLCSROupkJBdzUEBEWiITAyDTw9TaoUjKYOflAYacI1Cf3WTej3oMC/BwYDXP1X4d/GJPx7UDBAqB/CvvUk7HtAoN@DIkcBwSL026hCvwcE/nkY@8i3NoR8Dwbse0DkmIBgFvaNI8C@BwP6eRf5uDduAPeegp@CgMB@yOcGkG/cAPI9GLDPu7hHvXECqHcuAPUeDDkAyJlQb1wA6j0QcM@zmEe8cQCId/ZHvAeCx/vkkhBv7I94DwLM8yre0W7Mj3ZnfbR7EIR3nmV9tBvr9wCnAu9xdllx9YyPdGd7pHsQhHWibB9Hz/ZY9@v05MmRJs70OHeWx7kHQUgnyvJx8iyPdA8CrHtN39vLfw "Lua (LuaJIT) – Try It Online")
[Answer]
# MATLAB, 70 bytes
```
function s(l),x=max(l);find(find(l==2)==1+mod(2.^(1:x),x-1))*(l(2)~=2)
```
explanation:
every nth shuffle, 2 will be pushed n^2 indices down from its previous position, wrapping around when it reaches the last position. That means that the function for index(n) is
1+mod(2^n,list-size-1)
for a list-size of 10, then, the indices are:
* index(1) = 3 -> [1 6 **2** 7 3 8 4 9 5 10]
* index(2) = 5 -> [1 8 6 4 **2** 9 7 5 3 10]
* index(3) = 9 -> [1 9 8 7 6 5 4 3 **2** 10]
* index(4) = 17 => 8 -> [1 5 9 4 8 3 7 **2** 6 10]
etc.
Using this, I find the index where 2 is, and find which power of 2 that is along the array. That power corresponds the the number of shuffles. To account for 0 shuffles, the whole thing is multiplied by the boolean value of l(2)~=2 to make sure that it returns 0 when 2 is in the right place, which only happens for an unshuffled array.
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, ~~77~~ 68 bytes
```
map{push@{$_%2},$_}0..$#F;++$\,@F=@F[@0,@1]while"@F"ne"@{[1..@F]}"}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saC6oLQ4w6FaJV7VqFZHJb7WQE9PRdnNWltbJUbHwc3WwS3awUDHwTC2PCMzJ1XJwU0pD0hWRxvq6Tm4xdYq1Vb//2@oYKxgqmCuYKlgpGCiYKZg8S@/oCQzP6/4v66vqZ6BocF/3cQCAA "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes
```
c=0;While[Sort[a]!=a,a=a[[1;;-1;;2]]~Join~a[[2;;-1;;2]];c++];c
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2hbbaijYKajYAikTIGUgY6CiY6CpY6CsY6ChY6CkY6Cee3/ZFsD6/CMzJzU6OD8opLoxFhF20SdRNvE6GhDa2tdIDaKja3zys/MqwMKGcGFrJO1tYHE/4CizLyS6OTY/wA "Wolfram Language (Mathematica) – Try It Online")
# Explanation
The input list is `a` . It is unriffled and compared with the sorted list until they match.
[Answer]
# [Red](http://www.red-lang.org), ~~87~~ ~~79~~ 78 bytes
```
func[b][c: 0 while[b/2 > 2][c: c + 1 b: append extract b 2 extract next b 2]c]
```
[Try it online!](https://tio.run/##bZTNjhoxEITv@xR9zyHutj1jc8hD5IrmsPwpK0UIIaLk7clXJkJAdk4wdlWXv27Peb@7ft/v1svbYXU9/Dpu15tlvV1Zst8/Pn7u15uvYd8sxrutfTG3zcreT6f9cWf7P5fz@/ZiG4v77yM/9GLZLtfT@eN4sYOtnQ15eXv@b8XqYjyP7zNK@/c8vp9QzKw2VN2qeVpehZUNwfL0VKghLbzvrFZ2IXxc7myY2VLZRO3X5cqGwpY8vKfX5VvRfitrbfkvtPvIOkIrPIe4H@/z51GP0DtKb0h9ppRPMq0yLZh61olCuUGaFvuMSdciO5Hh4fe0wz5khCslpH@qXnBgfebgoEnZOiAz26MOSYUsho1gqF2GmBfqlWQZgxkEhEvQxyArahkxKrhVc7IZrkqVcCg4ZDgRa0426UQ0CAOliDySVo6NQeNgjIRSJBwUI@NA6anblFAm6xgoRcTt9AwcBq3YXFGqLTgoRsaB0lOzikGHOAZKET4AVYBh0BgCAChFwkExMg5qCqOFQadNAFCKSAN6dSsYNNoOAKVIOChGxoHSE5OnnszWiK8U9Ed9qcwMBs0N/KEU8A/FoAGDP0OAQaeRxFcKGiD0DCz6lgz6oRDgD6XIMkDItUPfq4E/FAL@FIY@8H3monB8ZYB@KERWCxAyTugZAuiHMoCfusDPGk9uGqdPyo@BQkBf8JkB4DszAPxQBuhTF/agd0Zg0vQRH70yZAVAx@VBzgSAPhQB9pp87jFyBgDwQf8BH4oQqo8uGeCd/gM@lMD1sXG4Z90BinNyug/2UAJxpyzdr7pxyZqCY@H6TDnUNfU0H@hB74EeSiDqSOm9hp7eQz1G6/WBc6Br5mk9zIPOwzyUQNCR0nmNPJ0HeigB1KPyibn@BQ "Red – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18 bytes
```
L?SIb0hys%L2>Bb1
y
```
[Try it online!](https://tio.run/##K6gsyfj/38c@2DPJIKOyWNXHyM4pyZCr8v//aEMdYx1THXMdSx0jHRMdMx2LWAA "Pyth – Try It Online")
-2 thanks to @Erik the Outgolfer.
The script has two line: the first one defines a function `y`, the second line calls `y` with the implicit `Q` (evaluated stdin) argument.
```
L?SIb0hys%L2>Bb1
L function y(b)
? if...
SIb the Invariant b == sort(b) holds
0 return 0
h otherwise increment...
y ...the return of a recursive call with:
B the current argument "bifurcated", an array of:
b - the original argument
> 1 - same with the head popped off
L map...
% 2 ...take only every 2nd value in each array
s and concat them back together
```
[¬π](https://github.com/vendethiel/trying.pyth/blob/master/stop-shuffling.pyth)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~62~~ ~~71~~ ~~70~~ 66 bytes
*+9 bytes when Test cases with an even number of elements added.*
*-1 byte with splatting.*
*-4 bytes: wrap the expression with `$i`,`$j` to a new scope.*
```
for($a=$args;$a[1]-2;$a=&{($a|?{++$j%2})+($a|?{$i++%2})}){$n++}+$n
```
[Try it online!](https://tio.run/##XZTRbhMxEEXf8xUr2FaJ1pXssb3rBVX0PxBCEaSlKGpLEgRSmm8P5zokactDUWzfO9dnxvv0@GexWv9YLJf79ra5brb728fVtJ1ft/PV3fpjO/8cvlwZ/19fbll@/rTtuvbnhe1m3eFne991@rmbbduHrtt17cN@N5ncTCcN/9zUuyY4c3H25rdLLh/Xgtais7e/XXq10rMysF7Qji674I/bdhBkthG5/tV6QZhYH9nNnDrLorZHDgwcyRxSzfN20nbmQOJIrN79i@18Ljoeyrpy3OsPeUOoMWte5Sb/6UYVBH/DyGYo7IYBq9BLl6VL6EJUYlMusJ1qc/RFcbY4h4jlcMpSzU02eFLgrE41ekg4sD9wLS7uoxvBFDluuUoy3DAsxEIdZIh5ol7yLmIwcEeiedhiEBU01RgZmKrZuwFqSuVxSDhEQBBr8K7XfcCPgVJYrEkzl8agcDHarRQeB8WIOFC6H13vUXo3YqAUZofbM1IYlOSGjFLccVCMiAOl@@IyBiO8MVAKCxVQBhgGhRYDQCk8DooRcVBLGBwMRpoEAKUwX6Hn4BIGhb4CQCk8DooRcaB0z1ypJ4MrxFcK@qO@ZIYCgxIc@E0p4G@KQQMqf0YAg5FGEl8paIDQM47oi3fQN4UAvylFlAFCHhb6MTvwm0LAn8LQB34YeAZcXxmgbwoR1QKEjBN6hgD6pgzgpy7wo4aTd8TtvfJjoBDQF3xmAPiBGQC@KQP0qQt70AdGoNf0ER@9MkQFQMfrQM4EgN4UAfaae14pcgYA8Eb/AW@KYKqPzjvAB/oPeFOCoM9JgHvUG6A4N6f7YDclEHfK0v2s9@ZdUXAsgj5EAeqaepoPdKP3QDclEHWk9F5DT@@hbrX1@oQFoGvmaT3Mjc7D3JRA0JHSeY08nQe6KQHULfMMZ81zc9Fs63NsF3@fFt82i@@uaed8gduvh@XVYv17uWHhkg/zzbx536yflvPN5v7hrh54107/n7la/DqZzD4cle8mu/0/ "PowerShell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ ~~11~~ 10 bytes
Taking my shiny, new~~, **very**-work-in-progress~~ interpreter for a test drive.
```
ÅÎÍ©ÒßUñÏu
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xc7NqdLfVfHPdQ&input=WzEsMyw1LDcsOSwyLDQsNiw4XQ) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=xc7NqdLfVfHPdQ&input=WwpbMSwyLDNdClsxLDIsMyw0LDVdClsxLDMsMl0KWzEsNiwyLDcsMyw4LDQsOSw1LDEwXQpbMSwzLDUsNywyLDQsNl0KWzEsOCw2LDQsMiw5LDcsNSwzLDEwXQpbMSw5LDgsNyw2LDUsNCwzLDIsMTBdClsxLDUsOSw0LDgsMyw3LDIsNiwxMF0KWzEsMyw1LDcsOSwyLDQsNiw4XQpbMSw2LDExLDUsMTAsNCw5LDMsOCwyLDddClsxLDEwLDE5LDksMTgsOCwxNyw3LDE2LDYsMTUsNSwxNCw0LDEzLDMsMTIsMiwxMSwyMF0KWzEsMyw1LDcsOSwxMSwxMywxNSwxNywxOSwyLDQsNiw4LDEwLDEyLDE0LDE2LDE4LDIwXQpbMSwxNDEsMzIsMTcyLDYzLDIwMyw5NCwyMzQsMTI1LDE2LDE1Niw0NywxODcsNzgsMjE4LDEwOSwyNDksMTQwLDMxLDE3MSw2MiwyMDIsOTMsMjMzLDEyNCwxNSwxNTUsNDYsMTg2LDc3LDIxNywxMDgsMjQ4LDEzOSwzMCwxNzAsNjEsMjAxLDkyLDIzMiwxMjMsMTQsMTU0LDQ1LDE4NSw3NiwyMTYsMTA3LDI0NywxMzgsMjksMTY5LDYwLDIwMCw5MSwyMzEsMTIyLDEzLDE1Myw0NCwxODQsNzUsMjE1LDEwNiwyNDYsMTM3LDI4LDE2OCw1OSwxOTksOTAsMjMwLDEyMSwxMiwxNTIsNDMsMTgzLDc0LDIxNCwxMDUsMjQ1LDEzNiwyNywxNjcsNTgsMTk4LDg5LDIyOSwxMjAsMTEsMTUxLDQyLDE4Miw3MywyMTMsMTA0LDI0NCwxMzUsMjYsMTY2LDU3LDE5Nyw4OCwyMjgsMTE5LDEwLDE1MCw0MSwxODEsNzIsMjEyLDEwMywyNDMsMTM0LDI1LDE2NSw1NiwxOTYsODcsMjI3LDExOCw5LDE0OSw0MCwxODAsNzEsMjExLDEwMiwyNDIsMTMzLDI0LDE2NCw1NSwxOTUsODYsMjI2LDExNyw4LDE0OCwzOSwxNzksNzAsMjEwLDEwMSwyNDEsMTMyLDIzLDE2Myw1NCwxOTQsODUsMjI1LDExNiw3LDE0NywzOCwxNzgsNjksMjA5LDEwMCwyNDAsMTMxLDIyLDE2Miw1MywxOTMsODQsMjI0LDExNSw2LDE0NiwzNywxNzcsNjgsMjA4LDk5LDIzOSwxMzAsMjEsMTYxLDUyLDE5Miw4MywyMjMsMTE0LDUsMTQ1LDM2LDE3Niw2NywyMDcsOTgsMjM4LDEyOSwyMCwxNjAsNTEsMTkxLDgyLDIyMiwxMTMsNCwxNDQsMzUsMTc1LDY2LDIwNiw5NywyMzcsMTI4LDE5LDE1OSw1MCwxOTAsODEsMjIxLDExMiwzLDE0MywzNCwxNzQsNjUsMjA1LDk2LDIzNiwxMjcsMTgsMTU4LDQ5LDE4OSw4MCwyMjAsMTExLDIsMTQyLDMzLDE3Myw2NCwyMDQsOTUsMjM1LDEyNiwxNywxNTcsNDgsMTg4LDc5LDIxOSwxMTAsMjUwXQpd)
```
ÅÎÍ©ÒßUñÏu :Implicit input of integer array U
√Ö :Slice the first element off U
Î :Get the first element
Í :Subtract from 2
© :Logical AND with
Ò : Negation of bitwise NOT of
ß : A recursive call to the programme with input
Uñ : U sorted
Ï : By 0-based indices
u : Modulo 2
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü≈:☻‼Xí┌ùß♦▲▬á
```
[Run and debug it](https://staxlang.xyz/#p=81f73a021358a1da97e1041e16a0&i=%5B1,2,3%5D%0A%5B1,2,3,4,5%5D%0A%5B1,3,2%5D%0A%5B1,6,2,7,3,8,4,9,5,10%5D%0A%5B1,3,5,7,2,4,6%5D%0A%5B1,8,6,4,2,9,7,5,3,10%5D%0A%5B1,9,8,7,6,5,4,3,2,10%5D%0A%5B1,5,9,4,8,3,7,2,6,10%5D%0A%5B1,3,5,7,9,2,4,6,8%5D%0A%5B1,6,11,5,10,4,9,3,8,2,7%5D%0A%5B1,10,19,9,18,8,17,7,16,6,15,5,14,4,13,3,12,2,11,20%5D%0A%5B1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20%5D%0A%5B1,141,32,172,63,203,94,234,125,16,156,47,187,78,218,109,249,140,31,171,62,202,93,233,124,15,155,46,186,77,217,108,248,139,30,170,61,201,92,232,123,14,154,45,185,76,216,107,247,138,29,169,60,200,91,231,122,13,153,44,184,75,215,106,246,137,28,168,59,199,90,230,121,12,152,43,183,74,214,105,245,136,27,167,58,198,89,229,120,11,151,42,182,73,213,104,244,135,26,166,57,197,88,228,119,10,150,41,181,72,212,103,243,134,25,165,56,196,87,227,118,9,149,40,180,71,211,102,242,133,24,164,55,195,86,226,117,8,148,39,179,70,210,101,241,132,23,163,54,194,85,225,116,7,147,38,178,69,209,100,240,131,22,162,53,193,84,224,115,6,146,37,177,68,208,99,239,130,21,161,52,192,83,223,114,5,145,36,176,67,207,98,238,129,20,160,51,191,82,222,113,4,144,35,175,66,206,97,237,128,19,159,50,190,81,221,112,3,143,34,174,65,205,96,236,127,18,158,49,189,80,220,111,2,142,33,173,64,204,95,235,126,17,157,48,188,79,219,110,250%5D%0A&m=2)
[Answer]
# Python 3, 40 bytes
```
f=lambda x:x[1]-2and 1+f(x[::2]+x[1::2]) # 1-based
f=lambda x:x[1]-1and 1+f(x[::2]+x[1::2]) # 0-based
```
[Try it online!](https://tio.run/##bZTRahsxEEXf/RV6jMkUNKPVrmTwlxg/uKShgdYJcR7s/rx7rgzFKQkLwZLmztW5s/t2@fj5eizX6/mUtmm3cwsre1ul8Xf7aZPV@6Vicf9z5szCYuNct2qePx@u7AZ78/1yo2xiubNZOfS5qLO/cKJyhm7/7Vb2J06UITx/2bDfWlr77NR9GBxO5Rjn9wfY8c6WN/Z8QcdnVVVVTVR5kdeQJdB82ZcNTlFCvf@zMaRDIigif1c7Gk8IsL1wHy6ci3XoFE5HHRUVXOg1PFHs0kN7ot2UrSCwcD18ZZAiUORyGi4qENVytgVcMpVRmFAoMMDVkm3WZcCOgFxEGUYrN0agcS8ylouMgmwUFGg9d5szldk6AnIRcbs8M4NAm2ypVAo5CrJRUKD13Kwi0IGNgFyEDz4VXgg0sgWAXGQUZKOgoDyYFwQ6CQFALiIP5tVtQqARKQDkIqMgGwUFWs/MkyJZrGFfLohHsVTmAYHmBv6QC/iHbBDA4E/@CHRyxL5cEIDQM4fUt2zQD5kAf8hFkQCFvDnU92rgD5mAP42hD3xfmH6uLw/QD5koioBCpol6hgD6IQ/gpy/wiyaT14fbZ/lHQCagL/jMAPCdGQB@yAP06Qt70DsjMGv4sE@9PBQZoI4Xg3ImAPQhC7DX0PNyUs4AAD7IH/AhC6H@1GUDvJM/4EMOXN8Lh3vRK0Bzbk76YA85EHfakn7Vy5atyTgSri@NQ11TT/hAD7IHesiBqFNK9hp6sod6jOj1jXKga@aJHuZB8jAPORB0SkleI0/yQA85gHrUvN@vVofj@PZlSzw@nhhPsTRZqpZmFrW3sFCpeN7@Ovz@/nRI58155/tvcTg@JX98fjjvNpvYP7Ko/2tOvr6ns6VLejmmPy9vD@eTJfqtN@PlP5xOP94/EnXrtN2mC4vX618 "Python 3 – Try It Online")
I need to refresh the page more frequently: missed Erik the Outgolfer's edit doing a similar trick =)
] |
[Question]
[
There are already [30 challenges dedicated to pi](https://codegolf.stackexchange.com/questions/tagged/pi) but not a single one asks you to find the nth decimal, so...
# Challenge
For any integer in the range of `0 <= n <= 10000` display the nth decimal of pi.
# Rules
* Decimals are every number after `3.`
* Your program may be a function, or a full program
* You must output the result in base 10
* You may get `n` from any suitable input method (stdin, input(), function parameters, ...), but not hardcoded
* You may use [1-based indexing](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28array%29#Array%5Fsystem%5Fcross-reference%5Flist) if that's native to your language of choice
* You don't have to deal with invalid input (`n == -1`, `n == 'a'` or `n == 1.5`)
* Builtins are allowed, if they support up to **at least** 10k decimals
* Runtime doesn't matter, since this is about the shortest code and not the fastest code
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins
# Test cases
```
f(0) == 1
f(1) == 4 // for 1-indexed languages f(1) == 1
f(2) == 1 // for 1-indexed languages f(2) == 4
f(3) == 5
f(10) == 8
f(100) == 8
f(599) == 2
f(760) == 4
f(1000) == 3
f(10000) == 5
```
For reference, [here](http://www.geom.uiuc.edu/%7Ehuberty/math5337/groupe/digits.html) are the first 100k digits of pi.
[Answer]
## 05AB1E, 3 bytes
```
žs¤
```
**Explained**
```
žs # push pi to N digits
¤ # get last digit
```
[Try it online](http://05ab1e.tryitonline.net/#code=xb5zwqQ&input=MTAwMDE)
Uses 1-based indexing.
Supports up to 100k digits.
[Answer]
## Python 2, 66 bytes
```
n=input()+9
x=p=5L**7
while~-p:x=p/2*x/p+10**n;p-=2
print`x/5`[-9]
```
Input is taken from stdin.
---
**Sample Usage**
```
$ echo 10 | python pi-nth.py
8
$ echo 100 | python pi-nth.py
8
$ echo 1000 | python pi-nth.py
3
$ echo 10000 | python pi-nth.py
5
```
[Answer]
# Bash + coreutils, ~~60~~ 49 bytes
~~`echo "scale=10100;4*a(1)"|bc -l|tr -d '\\\n'|cut -c$(($1+2))`~~
```
bc -l<<<"scale=$1+9;4*a(1)-3"|tr -dc 0-9|cut -c$1
```
Improved by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). Thanks!
The index is one-based.
[Answer]
# Python 2, ~~73~~ ~~71~~ 73 bytes
thanks to @aditsu for increasing my score by 2 bytes
Finally an algorithm that can complete under 2 seconds.
```
n=10**10010
a=p=2*n
i=1
while a:a=a*i/(2*i+1);p+=a;i+=1
lambda n:`p`[n+1]
```
[Ideone it!](http://ideone.com/xuf3qa)
Uses the formula `pi = 4*arctan(1)` while computing `arctan(1)` using its taylor series.
[Answer]
# MATL, ~~11~~ 10 bytes
*1 byte saved thanks to @Luis*
```
YPiEY$GH+)
```
This solution utilizes 1-based indexing
[**Try it Online**](http://matl.tryitonline.net/#code=WVBpRVkkR0grKQ&input=MTAwMDE)
[All test cases](http://matl.tryitonline.net/#code=YApZUGlFWSRAR0grKQpEVA&input=MQoyCjMKNAoxMQoxMDEKMTAwMQoxMDAwMQ)
**Explanation**
```
YP % Pre-defined literal for pi
iE % Grab the input and multiply by 2 (to ensure we have enough digits to work with)
Y$ % Compute the first (iE) digits of pi and return as a string
G % Grab the input again
H+ % Add 2 (to account for '3.') in the string
) % And get the digit at that location
% Implicitly display the result
```
[Answer]
# Mathematica 30 bytes
```
RealDigits[Pi,10,1,-#][[1,1]]&
```
---
```
f=%
f@0
f@1
f@2
f@3
f@10
f@100
f@599
f@760
f@1000
f@10000
```
1
4
[Answer]
# CJam, 32
```
7e4,-2%{2+_2/@*\/2e10005+}*sq~)=
```
[Try it online](http://cjam.tryitonline.net/#code=N2U0LC0yJXsyK18yL0AqXC8yZTEwMDA1K30qc3F-KT0&input=MTAwMDA) (it's a bit slow)
[Answer]
# Sage, ~~32~~ 25 bytes
```
lambda d:`n(pi,9^5)`[d+2]
```
My first answer in a language of this kind.
`n` rounds `pi` to 17775 digits.
[Answer]
# Mathematica, ~~23~~ 21 bytes
```
⌊10^# Pi⌋~Mod~10&
```
# SageMath, 24 bytes
```
lambda n:int(10^n*pi)%10
```
[Answer]
# [J](http://jsoftware.com), ~~19~~ 15 bytes
```
10([|<.@o.@^)>:
```
Takes an integer *n* and outputs the *n**th* digit of pi. Uses zero-based indexing. To get the *n**th* digit, compute pi times 10*n*+1, take the floor of that value, and then take it modulo 10.
## Usage
The input is an extended integer.
```
f =: 10([|<.@o.@^)>:
(,.f"0) x: 0 1 2 3 10 100 599 760 1000
0 1
1 4
2 1
3 5
10 8
100 8
599 2
760 4
1000 3
timex 'r =: f 10000x'
1100.73
r
5
```
On my machine, it takes about 18 minutes to compute the 10000*th* digit.
## Explanation
```
10([|<.@o.@^)>: Input: n
>: Increment n
10 The constant n
^ Compute 10^(n+1)
o.@ Multiply by pi
<.@ Floor it
[ Get 10
| Take the floor modulo 10 and return
```
[Answer]
# Clojure, 312 bytes
```
(fn[n](let[b bigdec d #(.divide(b %)%2(+ n 4)BigDecimal/ROUND_HALF_UP)m #(.multiply(b %)%2)a #(.add(b %)%2)s #(.subtract % %2)](-(int(nth(str(reduce(fn[z k](a z(m(d 1(.pow(b 16)k))(s(s(s(d 4(a 1(m 8 k)))(d 2(a 4(m 8 k))))(d 1(a 5(m 8 k))))(d 1(a 6(m 8 k)))))))(bigdec 0)(map bigdec(range(inc n)))))(+ n 2)))48)))48)))
```
So, as you can probably tell, I have no idea what I'm doing. This ended up being more comical than anything. I Google'd "pi to n digits", and ended up on the [Wikipedia page for the Bailey–Borwein–Plouffe formula](https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula). Knowing just barely enough Calculus(?) to read the formula, I managed to translate it into Clojure.
The translation itself wasn't that difficult. The difficulty came from handling precision up to n-digits, since the formula requires `(Math/pow 16 precision)`; which gets huge really fast. I needed to use `BigDecimal` everywhere for this to work, which *really* bloated things up.
Ungolfed:
```
(defn nth-pi-digit [n]
; Create some aliases to make it more compact
(let [b bigdec
d #(.divide (b %) %2 (+ n 4) BigDecimal/ROUND_HALF_UP)
m #(.multiply (b %) %2)
a #(.add (b %) %2)
s #(.subtract % %2)]
(- ; Convert the character representation to a number...
(int ; by casting it using `int` and subtracting 48
(nth ; Grab the nth character, which is the answer
(str ; Convert the BigDecimal to a string
(reduce ; Sum using a reduction
(fn [sum k]
(a sum ; The rest is just the formula
(m
(d 1 (.pow (b 16) k))
(s
(s
(s
(d 4 (a 1 (m 8 k)))
(d 2 (a 4 (m 8 k))))
(d 1 (a 5 (m 8 k))))
(d 1 (a 6 (m 8 k)))))))
(bigdec 0)
(map bigdec (range (inc n))))) ; Create an list of BigDecimals to act as k
(+ n 2)))
48)))
```
Needless to say, I'm sure there's an easier way to go about this if you know any math.
```
(for [t [0 1 2 3 10 100 599 760 1000 10000]]
[t (nth-pi-digit t)])
([0 1] [1 4] [2 1] [3 5] [10 8] [100 8] [599 2] [760 4] [1000 3] [10000 5])
```
[Answer]
# Clojure, 253 bytes
```
(defmacro q[& a] `(with-precision ~@a))(defn h[n](nth(str(reduce +(map #(let[p(+(* n 2)1)a(q p(/ 1M(.pow 16M %)))b(q p(/ 4M(+(* 8 %)1)))c(q p(/ 2M(+(* 8 %)4)))d(q p(/ 1M(+(* 8 %)5)))e(q p(/ 1M(+(* 8 %)6)))](* a(-(-(- b c)d)e)))(range(+ n 9)))))(+ n 2)))
```
Calculate number pi using [this formula](https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula "this formula"). Have to redefine macro `with-precision` as it's used too frequently.
You can see the output here: <https://ideone.com/AzumC3>
1000 and 10000 takes exceeds time limit used on ideone, *shrugs*
[Answer]
# [Python 3](https://docs.python.org/3.6/), 338 bytes
This implementation is based on the [Chudnovsky algorithm](https://en.wikipedia.org/wiki/Chudnovsky_algorithm), one of the fastest algorithms to estimate pi. For each iteration, roughly 14 digits are estimated (take a look [here](https://www.craig-wood.com/nick/articles/pi-chudnovsky/) for further details).
```
f=lambda n,k=6,m=1,l=13591409,x=1,i=0:not i and(exec('global d;import decimal as d;d.getcontext().prec=%d'%(n+7))or str(426880*d.Decimal(10005).sqrt()/f(n//14+1,k,m,l,x,1))[n+2])or i<n and d.Decimal(((k**3-16*k)*m//i**3)*(l+545140134))/(x*-262537412640768000)+f(n,k+12,(k**3-16*k)*m
```
[Try it online!](https://repl.it/repls/DoubleStupendousBoastmachine)
[Answer]
# Smalltalk – 270 bytes
Relies on the identity `tan⁻¹(x) = x − x³/3 + x⁵/5 − x⁷/7 ...`, and that `π = 16⋅tan⁻¹(1/5) − 4⋅tan⁻¹(1/239)`. SmallTalk uses unlimited precision integer arithmetic so it will work for large inputs, if you're willing to wait!
```
|l a b c d e f g h p t|l:=stdin nextLine asInteger+1. a:=1/5. b:=1/239. c:=a. d:=b. e:=a. f:=b. g:=3. h:=-1. l timesRepeat:[c:=c*a*a. d:=d*b*b. e:=h*c/g+e. f:=h*d/g+f. g:=g+2. h:=0-h]. p:=4*e-f*4. l timesRepeat:[t:=p floor. p:=(p-t)*10]. Transcript show:t printString;cr
```
Save as `pi.st` and run as in the following test cases. Indexing is one based.
```
$ gst -q pi.st <<< 1
1
$ gst -q pi.st <<< 2
4
$ gst -q pi.st <<< 3
1
$ gst -q pi.st <<< 4
5
$ gst -q pi.st <<< 11
8
$ gst -q pi.st <<< 101
8
$ gst -q pi.st <<< 600
2
$ gst -q pi.st <<< 761
4
$ gst -q pi.st <<< 1001
3
$ gst -q pi.st <<< 10001 -- wait a long time!
5
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org) (Chrome 67+), ~~75~~ ~~73~~ ~~67~~ 63 bytes
```
n=>`${eval(`for(a=c=100n**++n*20n,d=1n;a*=d;)c+=a/=d+++d`)}`[n]
```
[Try it online!](https://tio.run/##pU7LisIwFN37FUHKcNNk0lTRoZTrYnZ@gzg0JKlU4k1pRYRhvr3Gx8L9nMXhPBbnHM3FjHbo@vMnReenFifCTZP9@osJ0LRxAIMWS60pz4WgfKFJOiypNjm6mluBpkAnhHAN/2t2tJ/qnZaslGwh2TKJu9GJVlUl2df6aV@s9@pkergy3DAbaYzBqxAP0MJ3d9jSGa48oZ7N3kv4z0EOj13iagyd9fA6UnI1@D6YlBQ/oHgh2Tz7UPM0Pt0A "JavaScript (Node.js) – Try It Online")
Using \$\pi/2=\sum\_{k=0}^{\infty}k!/(2k+1)!!\$ (same logic used by Leaky Nun's Python answer, but thanks to the syntax of JS that makes this shorter). Input is passed to the function as a BigInt. 2 bytes can be removed if 1-based indexing is used:
```
n=>`${eval(`for(a=c=100n**n*20n,d=1n;a*=d;)c+=a/=d+++d`)}`[n]
```
# [JavaScript (Node.js)](https://nodejs.org) (Chrome 67+), ~~90~~ 89 bytes
```
n=>`${eval(`for(a=100n**++n*2n,b=a-a/3n,c=0n,d=1n;w=a+b;a/=-4n,b/=-9n,d+=2n)c+=w/d`)}`[n]
```
[Try it online!](https://tio.run/##tY5BTsMwEEX3PYVVVWgcO7aTQlEUTRfsOENVFNdxqlRmHCVVWwlx9mCgCy7ALP7Mn7d5J3uxkxv74ZxTbP3c4Uy4bVYf/mIDNF0cwWJhDGWZEJSVJA9oc6vXJB0aki0WVF/RikNtNeaPiadVJSCwJO4EXnXb8M9mR/u53hnJCslKydbp@C4mxVNVSfa8@a33NHv1bge4MdwyF2mKwasQj9DBS398pTPceJp6sfgL4X/UOfwYEVdT6J2Hu2LB1eiHYNNHv4HiWrLl6kEtk9b8BQ "JavaScript (Node.js) – Try It Online")
Using \$\pi/4=\arctan(1/2)+\arctan(1/3)\$. Input is passed to the function as a BigInt. 2 bytes can be removed if 1-based indexing is used:
```
n=>`${eval(`for(a=100n**n*2n,b=a-a/3n,c=0n,d=1n;w=a+b;a/=-4n,b/=-9n,d+=2n)c+=w/d`)}`[n]
```
[Answer]
# Java 7, ~~262~~ 260 bytes
```
import java.math.*;int c(int n){BigInteger p,a=p=BigInteger.TEN.pow(10010).multiply(new BigInteger("2"));for(int i=1;a.compareTo(BigInteger.ZERO)>0;p=p.add(a))a=a.multiply(new BigInteger(i+"")).divide(new BigInteger((2*i+++1)+""));return(p+"").charAt(n+1)-48;}
```
Used [*@LeakyNun's* Python 2 algorithm](https://codegolf.stackexchange.com/a/84465/52210).
**Ungolfed & test code:**
[Try it here.](https://ideone.com/eqlwsu)
```
import java.math.*;
class M{
static int c(int n){
BigInteger p, a = p = BigInteger.TEN.pow(10010).multiply(new BigInteger("2"));
for(int i = 1; a.compareTo(BigInteger.ZERO) > 0; p = p.add(a)){
a = a.multiply(new BigInteger(i+"")).divide(new BigInteger((2 * i++ + 1)+""));
}
return (p+"").charAt(n+1) - 48;
}
public static void main(String[] a){
System.out.print(c(0)+", ");
System.out.print(c(1)+", ");
System.out.print(c(2)+", ");
System.out.print(c(3)+", ");
System.out.print(c(10)+", ");
System.out.print(c(100)+", ");
System.out.print(c(599)+", ");
System.out.print(c(760)+", ");
System.out.print(c(1000)+", ");
System.out.print(c(10000));
}
}
```
**Output:**
```
1, 4, 1, 5, 8, 8, 2, 4, 3, 5
```
[Answer]
# Maple, 24 bytes
```
trunc(10^(n+1)*Pi)mod 10
```
Test cases:
```
> f:=n->trunc(10^(n+1)*Pi)mod 10;
> f(0);
1
> f(1);
4
> f(2);
1
> f(3);
5
> f(10);
8
> f(100);
8
> f(599);
2
> f(760);
4
> f(1000);
3
> f(10000);
5
```
] |
[Question]
[
Given the name of an HTTP status code, such as `OK` or `Continue`, output or return the corresponding number. Your code is limited to **200 bytes**, and the winner is the answer that correctly finds the number for the most status codes.
For this challenge, the status codes your program should handle are:
```
100 Continue
101 Switching Protocols
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
```
Test cases:
```
Continue -> 100
OK -> 200
No Content -> 204
Not Found -> 404
```
For invalid status codes or ones not supported by your program, any behavior is fine. Input and output can be in any reasonable format. If there is a tie, the shortest program that can support that many status codes wins.
[Answer]
# [Node.js](https://nodejs.org), ~~135 126 125~~ 123 bytes, score 40
*Saved 2 bytes by using unprintable characters, as suggested by @dingledooper*
```
s=>Buffer('~>/6%sH~~d4~\\~i~~,~~~~~.~~~~n)W*~~~~;~CR@M"~1E~$~ _Z9~')[parseInt(s[0]+s[4]+s[19],34)*57%65]*209%523
```
[Try it online!](https://tio.run/##VVJNbxoxED1WinpoK7WV2kOtqgiWAE34SIQiUAkiCWpoEB@tVIIqZz0LrhZ7a3sh9OC/TscGVLKHlWc8896bN/5Nl1SHiiemKCSDTdTY6EbzMo0iULmsbX4@y@gba5@xqr2/t9y@ss8L1r63L1/bd7Zk8RPBj7d5d7iw7cGX3kd72rGfLPn1s24/vHmRDSYJVRq6wuT05GR6rCdV9zutTwuVapCvnWfOatN8@aSeqZUrm4tJti2F4SKFbCE7XHETzrmYkb6SRoYy1pi9@4q/tgJqgOGpFYaQbI/fpCi2UjOXihtq@BJIV0RSLfAshb8nDh2EwWAAGsxB3KfKcBofZHppbHgSA2nPJQ/BcffkEhjpA2IKLIrXmLuSqXDsQwByZ@agPJMhPcl4xL2wsQY3wqMrH8EikYqqNRkA4wpCR3VJGYZ/UtAuGgu6neKv7@7T9QLJfAE2MM@pHjhjIHZcew09wD5GXKoVx3K1swUj7xJ9iJ2vXgpxTiEsD709h@g7JWTEFyBTpwhNiWLupV5L4TBuQczM/LCrj7NIwbhHu6I8foLVQSazJiMpyS1VM/h/VRwPutu8FDM/vU4TtAh3SnpoESWjdXJQj@kBFTPwUw5RvI74brDOY4J@0qcK8OmBErjZIaglKNJRSu531F3gfp25vtJt4Rqf1Yqu/T7VEtdOcBtLxNpR7O4PvLkZjfrkOyjtWL2mvfzs9OiohA@wQ8N5TpNGk6BBWsZQiuUsp0sJZR3BcpVyQI5JlNNBEGz@AQ "JavaScript (Node.js) – Try It Online")
### Decoding example
Let's consider the input string `"Internal Server Error"`.
We extract the characters at indices \$0\$, \$4\$ and \$19\$ and concatenate them together:
```
**I**nte**r**nal Server Err**o**r
^ ^ ^
```
This gives `"Iro"`.
We parse this string as a base-34 value, leading to \$\color{blue}{21750}\$.
**Note:** For many shorter entries, some characters are undefined. This leads to strings such as `"Piundefined"` and much higher integers.
We apply the hash formula:
$$(\color{blue}{21750}\times57)\bmod65=5$$
We extract the corresponding character from the lookup string (which is a `"s"`) and take its ASCII code, leading to \$\color{blue}{115}\$.
We apply another black magic formula to turn this into the final HTTP status code:
$$(\color{blue}{115}\times209)\bmod 523=500$$
Given an HTTP status code \$c\$, the ASCII code \$k\$ of the encoding character is given by the following reverse formula:
$$k = \lfloor c / 100\rfloor \times 23 - (c \bmod 100) \times 5$$
[Try it online!](https://tio.run/##bZHPSsNAEMbveYohIJvYJGazu621VpHioQdPOYqHsP2Tmtot2yCC@gaCF4/6Hj5PX8BHiN@mFCoYGGZ3ft98O2Hui8dio@1iXccrM5k2jTarjVlOk6WZB4w0avRCV/loPEbWZWGTNk91xcKB90cdt18n/j87uXfL0zTiKY8y5KzNGUIgJEIhupEAE2ACTIAJMAEm0l4kwSSYBJNgEkyCSfTJlp8i@pHk0HHoOHQcOg4dh45Dx3uRgo@Cj4KPgo@Cj0rVnZfMjL0udBloGl7Qs0dU0ZBuirpMZktjLOonhL8I6ZgyQTGhcLQvqAH0FvrK0bQPojLhirrclc9JZHRJLH1i1KEqqU1e28VqHvBumKyLSV4Xtg6yiOB3Rj7zodopkpk1DyMsYISdBFUI4DPyW/ODLfhErkc7jE21l4NnDh4RrQXtRW7CXY@7uXOAkYdwwrjbz4@f73eGkdj2680dQ6zzNRw0zS8 "JavaScript (Node.js) – Try It Online")
---
# [Node.js](https://nodejs.org), 84 bytes, score 40
With a built-in.
```
s=>Object.keys(c=require('http').STATUS_CODES).find(k=>c[k]==s)||413+(~s.length/6&3)
```
[Try it online!](https://tio.run/##VVNRb9owEH7vr/DTkqgj08a0lylIjNEOrRREwl6qajL2hbgYO7Wd0EzV/jo7G9DSl8h3vrvvu@9znmhLLTOidgOlORzL7Giz0WLzBMylO@hszDIDz40wEEeVc3WUpHkxLtb578ni@zRP0lIoHu@yEXvYPWaZTV5fP38cXsd/bSpBbV314cu7YXL8@hBNtHJCNRC9j/KDcKwSakuWRjvNtLSYXfzEz8QAdcDxNGYM6tPxXqvBuHGVNsJRJ1ogM1Vqs8ezVuGe@OmgHAYrsOB68ZIaJ6jsZeaNdKKWQCaVFgw89ly3wMkScKbCItlh7kY3yqPnAGThKjAByZG55qIUgdjagl/hxZcXsK@1oaYjK@CoF/NQ3yjH8LkB66O1oqct/oTuJe32CBYKsIEHTLMRnIM6Y104zAH7OPGpsZT6cJYFo6AS3Uiva6BCvFI4VrAgT3/6mQkpxB504xmhKKUUgeqtVn7GXXCt37XEXbTiIky7oUK@mTVFJNeRQmtyR80W/l8N1qvZKa/VNmxvmxolQk/JHCWipOjqXj2mV1RtIWyZI3lbivNi05ca9aRvGczQT6PQ2RxMC4ZMjdEXj2Z79NeLGyq9C7f4rA60C36aFm0n6EaLs84Q5/ueNj@KYkl@gbEeNXC60I8er65SfIBTyqrYkmxEUCCrJaRSb2Ob1pRP8a8YfkrINSljmyTJ8R8 "JavaScript (Node.js) – Try It Online")
### How?
There are 3 strings that do not match the values stored in `STATUS_CODES` for codes **413**, **414** and **416**. For these ones, we use the length of the input to figure out the correct answer.
```
string | len | ~len/6 | &3 | +413
-----------------------------------+-----+---------+----+------
"Request Entity Too Large" | 24 | -4.1667 | 0 | 413
"Request-URI Too Long" | 20 | -3.5000 | 1 | 414
"Requested Range Not Satisfiable" | 31 | -5.3333 | 3 | 416
```
[Answer]
# [Python 3](https://docs.python.org/3/), 68 bytes, score: 40
A cheap builtin answer.
```
lambda s:+http.HTTPStatus[re.sub('\W','_',s.upper())]
import http,re
```
[Try it online!](https://tio.run/##TVPLTttAFN3nK@4GOVZDFOcBLVIWFAGNSkpEQrsAVE3sm3gke8adGSe4@@76Ce3P8SPpGZvQrDz3ec4997qoXKrVYLcaP@4ykS8TQfbsXepc0f20WMzmTrjSPhju2nLZDh6/BZ3ge9Cx3bIo2LTD8Kkl80IbR76kY3i3TWXGFJ21KNYJd0iJnGlMUhWla4ddW2TStQMKOhSFLSqMVDCPLFKObEBH1F61fUnYIR/xPUK8g5e/v1/@/AoeXqM0Hv@PP4W7qNejC62cVCW3ol5E8610cSrVmmZGOx3rzLb6SLr9jE9EF4aF4wTvPp3HMReNMaAvWh2fl9DESIwuN0wTtdImx1srZAyRUSOxcjBHdMeW3YHnhGbCOCmyN98AsNMyc7KAMBepljFbOCOa6g0nNGN0V0jMKnj7dKVLleA1oDkz3bqUDSyP61CRyJVkHx7RvWU/3LMvO6UF@z0IU4FRIg3HrjUE8EeRwPGjZOvtiO6VaKb7iS5DwM1ElQO8TkKZdw7AwSxlkrCC1SA3rIaAnTLqk9p5nmV6W5ecNHatpFhmDNdpQ468mgCQcS3hIc77PTNayJx16Rl@8LKtMunpRz261gq9oohuWK1delAdgTqm1CqRdd8rgbvz/sFb10uguooWWtONMGvfaLgPHt/fTZqIVmsEIKeyOGqcMnYyhYSCFlXha072NQjcCbXmetY5xrEr2QwbndLlcwHNxSGXEfSf4AaMwjXM2WzY0KUx2iAS1U0mOW7Cy19n9@ttXeMwt6KCPaiLcC5@axv0rMFG2MhrzptuI@zF/670lY31DGqG@3H@AQ "Python 3 – Try It Online")
# [Python 2](https://docs.python.org/2/), ~~131~~ ~~119~~ ~~115~~ 104 bytes, score: 40
A nicer method with the same score, using a magic formula. [@Arnuald's answer](https://codegolf.stackexchange.com/a/220538/88546) had a really nice way of calculating the status code, which saves me *a ton* of bytes.
```
lambda s:ord('?".\, ;
?Zd?s>M?C6/W4?)??*??H1@R???i_??n$?9E?%'[hash(s)%762%517%233%56])*209%523
```
[Try it online!](https://tio.run/##TVNRbxJBEH40ufigJmqiD06MlzsqRe6OA1uDZyW0JZaWANVo25jt3QKbHLvn7kKLfx5n96DyxM3M9803881SrPRM8HA9aV@vczK/zQioQyEz30tevK1dV@HT4@RX9iR5oz4/fd1POq@aj559@NFIKkmylySnwZfnwyRJ2O8k4e@Sg27y0vWuZkTNfFVxW83QjYOWG0aRGzdvKnth/cCNw2jN5oWQGtRKOSoVkkIb6s5ESFDAuEnXlM4Yr0lKspxxqvzKoQOpyGgVOJkbvIFIVviVmipypn0PvCoEFcfApKSpRszEN@AKtNvYVvuGX3GgVHzf3gIdKCSWwXMVclzlgQv@hlr9T8Rv7/ynd7Vh3Tgb1qhzMeweorjtuw7qdegIrhlfUCeoBzC6YzqdMT6FgRRapCJXToigi2/4E0AHd9Q0w@8QjtKUFmUQwbng@0cLPI5kmmi2pNDjaNEcvwVHRAMRVolyjWEMQ6qo3sk0YUCkZiR/yEUo21/kmhU5hc5MsJQqTAbQF0uawYBid47AfIXZEI7Fgmf4FcGIUrjQMyoxMroaGRmbMGrKMVwqapa7N7QWjKm5LpErnChj1uEGCn8lGSb@LKgycQCXnJTb/cUuDZQbkNUcxS0IaSYZ4QzylmUZ5RiVyuVUDZTtU@RnNnmU5@LOUpplbJ0ktznFVKscDoybKMBSa@GuzsftZDBmcyoWZsIDY9skZ2b8oA4ngmOvIIAzyqd6tsMOcHTcUvCM2b7HhOU2Hz107aKqXsFYCDgjcmoaNbbF/cthr6wIPsUC2snVojB/ELxJHy0kMF4VhtPccrAwJHxK7a4jXEdNWLls0ILufYGek91ZYvS/h29AcnwNIyqXVEJXSiGxEtgmvTm@CWO/RYf2Wif4MO/ICuPIkvC5mKstsacVi/EiG8yDbzHe5XQ8HsB3KpWZwE64Xecf "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 40, tiebreak score 61 bytes
```
ȷ;€ȷḥ€ɠḋ“^,fḷɱ⁹⁴ƒẈ®ẒỤĖṅ}PG¬Ƭṙ⁴&©ẉ}Ḳḍƙḋ¥ȤẊḌÐẈ’b123¤%127b28ḅ³+³
```
[Try it online!](https://tio.run/##AYcAeP9qZWxsef//yLc74oKsyLfhuKXigqzJoOG4i@KAnF4sZuG4t8mx4oG54oG0xpLhuojCruG6kuG7pMSW4bmFfVBHwqzGrOG5meKBtCbCqeG6iX3huLLhuI3GmeG4i8KlyKThuorhuIzDkOG6iOKAmWIxMjPCpCUxMjdiMjjhuIXCsyvCs///T0s "Jelly – Try It Online")
# [Jelly](https://github.com/DennisMitchell/jelly), score 40, tiebreak score 58 bytes, in collaboration with @Arnauld and @ChartZ Belatedly
```
ȷ;€ȷḥ€ɠḋ“Rḳk_ṇṙƤĊ⁻ƒƓḍ¹⁹¡Ɱṫ°ė÷Ḣ4[⁶æȥ.’b41¤ị“£¬®Ø©‘Ḷ+"J׳ƊF¤
```
[Try it online!](https://tio.run/##AZsAZP9qZWxsef//yLc74oKsyLfhuKXigqzJoOG4i@KAnFLhuLNrX@G5h@G5mcakxIrigbvGksaT4biNwrnigbnCoeKxruG5q8KwxJfDt@G4ojRb4oG2w6bIpS7igJliNDHCpOG7i@KAnMKjwqzCrsOYwqnigJjhuLYrIkrDl8KzxopGwqT//1JlcXVlc3QgRW50aXR5IFRvbyBMYXJnZQ "Jelly – Try It Online")
## Discussion
I found an almost asymptotically optimal algorithm for solving this sort of problem (mapping a set of given inputs into specific numbers, not caring about other inputs) [a while ago](https://codegolf.stackexchange.com/a/214222). The algorithm takes a few bytes to express in Jelly, but the savings in not having any wasted bytes actually describe the outputs are worthwhile, making this the currently shortest non-builtin-based solution. (As a side note, it may well be worth adding the algorithm in question as a Jelly builtin, which would save 11-13 bytes from this program depending on how it was implemented; it seems likely to come up in the future.)
The algorithm basically generates programs that work by running a large number of hash functions on the input to produce a vector of hashes, then taking the dot product of that vector with a hardcoded vector over a finite field. (When implementing this in Jelly, we use a finite field of prime order, because it doesn't have builtins for dealing with other sorts of finite field.) It turns out that the minimum length of a hardcoded vector that solves this problem is almost always equal to the number of input/output pairs, and the maximum size of the vector elements is the order of the finite field, so the amount of storage used by this is equal to the amount of storage needed to store the possible outputs (thus asymptotically optimal). Adding a new HTTP status code to this program would typically cost less than a byte on average per code, unless it was outside the range of the existing codes (e.g. [here's how to add "I'm a teapot" to the original program at the cost of only one more byte](https://tio.run/##AZAAb/9qZWxsef//yLc74oKsyLfhuKXigqzJoOG4i@KAnMKiyKfKgsKm4bqOa8Kh4buNxpnCtsmT4bmY4bqgWMOeYDNeyovigbXGk@G5rOG5m8Kp4bmYQMK94bqg4biNw4bhuIrDn@G5hSh04biK4oCZYjEyNsKkJTEyN2IyOeG4hcKzK8Kz//9JJ20gYSB0ZWFwb3Q "Jelly – Try It Online")).
I've since automated a program generator that generates Jelly programs to solve these programs. So this codegolf submission was pretty much entirely automatically generated. [This is the generation program I used](https://tio.run/##hVVNbxtFGL77V4xWqmSrG@P1B/2IekirtqQ0bZS4RdCWarw7a0/ZnVlmZpOYU0FCHHrrqQeQOMANIaHQphUSB1eVys9I/oh53tl17AgEh935eL@e93OeiCybzucnT7@/mmlrdc5SmTlhmFCxToRpNxobZlzmQjl7uTE7ZFdYJq1jOmVSFaWzrMnVlLlpIVph4@Tr31cYYm2MsIVWiVRjpkv3L/wvwa/KfASLkCgAQY4ysWTOS@gaCVYYmYsWW2NJWWQy5k5Yxo2AjVI5kTCtYhEyrhI21SXL@ZTxJGHiwBl@qkwqIhrIJDrnOLkJd16LEnsAUFookqnXsC/thPC9Ar5bFCMg0GPD80qoig4gqFo7lDtNR6xiDGVevWCGq7FgnXb7c/K1aUoFIQcIeSHhp4NXIbMaCGBbae/rWGepSHx4jv7X/H/aW4CqMTbJACAgiIZSUqkJ2Qg07zy3rODGJ4@UpVLxbGG5hVIY4jLnBzIv85Ws1YUgLTKfS8oGrEadTodAaYMqooucfyG81hrMwiEOKeeyym0J3uYTynk88Z6QgBUxamgByk2MEOz9kSWlEOaG3K/RjESm94lwKi7tAvgiUQgb2@VjcSakIdufCEXBCanWUO3g@mfkl2yoEDdBxlA/dXucCi5DNxZKGE4ROdtdQHRHO3HZ42MTTsZszrPM444F@YpMokxhP@UyQ7ZCZE1UPlscSziOmDojDxBj1hyJmCOHNWbsLBvJ8ZpA86EARtxSryiUuZVa2dZCGWHNBPcdmsixRO6rQoLwMqhE5aiqxqdojRj6Ulj1bgJbSW3oYVsAUiXcmIaEyeeR2pCjvPerMvlgkX0ufVUERhidZUEdNB@ck6c/NDBqbq2ffPPL@6Pj1z9jnb1h51DRDQyqHD2x5R1v3rzRBDOjUgehFTI6zQ7ffgeJd8@P37zw1@zhf/KjyWcv905@@5Wm1yefLeVmr8wV60wTFd@kmdbMW602BopPx@NYizSVsUTqm612JlMs5yMI@SpoGlFAsu3lIIZjxmPRDFgQBkGLnWfB8etvA6yG9qPuoHP8x7O3L249LLudKPH/eL1a3h@tRuKvH49fP6u41tdXuC/V3KNTpbOfzq14W4sQtbo9On7zp3cWRI82CNpPtFQUovV1CkALu3fP7/tgYDufzx8E17RyUpUCbuyiBeIJ1ca20U7HOrO4vfsxfteMoLLHbiOORVFt72i1tlG6iTbScSf3BNtUqTYoYpSkpzPSjoDisCOscCvnbcwliZZa3myVmZMFBse1iZYoPrrSe@i1bQGdCkzZFHc38EKQ9V1MjbuoMuMtObalE4l5Q6R7aA64cEDsQ5EX2nAzZTsikUbEZOoqT3D8shSWTvcUr7z4yktv8yn1v2eAQOJtmpFMEqFqWwsMWwJyCaOrjQyTqg4LTj5KHE8fKSQojCIFtfTWITyr2mskbIjHA@1E4dYqxatI25takY7bQo0xn1akto0fo9Jru4EiPqPrOiy5KRtqzW7TRF2S1u7tbFb3Wo2997YsECKaalsIEWdDPOZLflzv@NlLfu0CvE1l7dj1gwLx5GcRbCKfhoblrjD0Cl83Ri9ytJkjvxRcz0lZuImy2udTn0@zh7QzZGMPumoTNX0lNh8Nh9vsfjX3KkwL@MGj@QM8U2HUicIu1q5fu/h6@Pr4Bvg@DHug9UDrgdYDrQdaD7Re50LYB60PWh@0Pmh90Pqg9SHX9/SL@C6F/Qh8Efgi8EXgi8AXgS8CX3QhHEDPAHoG0DOAngH0DDqDR/Ooe2EePAbMET6MjO7FYI5xcRHb2eH52WHwNw "Jelly – Try It Online") (configured to generate a solution to this problem). The Sage program it generates, when run, generates [this Jelly program](https://tio.run/##HYw7DsJADERPQ8UUa@9mP8oNuAKiiUSDcgG6CImKC4AEEgV0dCkSiS404RibiwSbwhp7PPN227rez/OajIFnkAmgBI5Qo5CjgEcAi3hYA0JKcAYhgZiRIpyFN4gBTurEmtCFEC2i1CKChRQpapqErhgPR4p0fpP7I7GtuDD5ffqcV1Nzm5prKTN25XR4jV3un6Lfe@5P8izLf@KiiUqaw2NBHPShBkfhDe1yaMWZ5x8 "Jelly – Try It Online") which generates the program written above.
The reason I've described the algorithm as "almost asymptotically optimal" is that it has two failure modes. One is mathematical; the algorithm involves solving a set of simultaneous equations, which can almost always be solved using a vector whose length is equal to the number of input/output pairs, but rarely and randomly have no solution (the odds of this become smaller as the size of the codomain becomes larger, and when it happens you can "reroll" by adding an arbitrary extra input/output pair, leading to a slightly larger program). The other is a deficiency of Jelly; the shortest way in Jelly to describe a list of integers drawn from a uniform random distribution is to use a large constant integer and base-convert it, but this mechanism is incapable of expressing lists with a leading 0 (the program generator I've written above doesn't attempt to fix this problem itself, but the odds of it happening are again just 1 in the size of the output domain).
## Explanation (original version)
Here's how this program is implemented in Jelly:
```
ȷ;€ȷḥ€ɠḋ“…’b123¤%127b28ḅ³+³
ḥ Hash
ɠ a line taken from standard input
using
€ each of the following hash configurations:
ȷ € each number from 1 to 1000 (the salt)
; concatenated with
ȷ 1000 (the codomain of the hash function);
ḋ take the dot product of the resulting hashes and
¤ a constant calculated by
“…’ converting a large constant integer
b123 to a list of base 123 digits;
%127 take the resulting dot product modulo 127,
b28 convert to a list of base 28 digits,
ḅ³ interpret as base 100 digits,
+³ and add 100
```
Everything up to the %127 is just the implementation of our general-purpose input→output mapper. The `b28ḅ³+³` after that implements the inverse of a function that maps HTTP status codes from 100…505 onto integers in the range 0…117; producing a smaller codomain allows for a smaller hardcoded vector. (The basic idea is to note that the last two digits of the status code are never greater than 27, so the double base conversion "closes some of the gaps" in the range of possible outputs.)
As it happens, our hardcoded vector didn't contain any of the values 123, 124, 125, or 126, so it was possible to use 123 as the base for that base conversion. (The gain from this is minimal; if Jelly had a builtin for this algorithm, you'd hardcode that the "123" and "127" were the same number.)
There's no particular algorithmic reason for the codomain of the hash function to be 1…1000 (any sufficiently large codomain would do), and calculating 1000 hashes is likewise not algorithmically useful because we only use the first 40 of them. This is just a tiny byte saving: 1000 has a 1-byte representation, whereas most other numbers can't be written in a single byte.
Incidentally, the reason we take input from standard input is that 100 (the lowest HTTP status code) can be represented in 1 byte in Jelly if the program has no command-line arguments, but takes 3 bytes if there are any command-line arguments. There wasn't a byte cost to doing anything because I needed to take explicit input anyway (attempting to take implicit input would run into a parse ambiguity that would need a byte to fix, so the extra byte for explicit input doesn't cost).
## Explanation (improved version)
@Arnauld suggested, instead of the base-28 calculation used in the previous version, to generate a list of the 41 possible (return values + 306) (trying to omit 306 from the list would cost more bytes than simply just adding it; and including it also gives us a prime number of possible outputs, which we need to be able to do finite field operations over the range of outputs in Jelly).
We can generate a list of the values like this:
```
“£¬®Ø©‘Ḷ+"J׳ƊF
“£¬®Ø©‘ [2,7,8,18,6]
Ḷ range from 0 to n-1, i.e. [[0,1],[0,1,…,6],…]
Ɗ group the three preceding bultins together
+ add
׳ 100 times
J the index of
" each sublist to every element of the sublist
F flatten
```
In other words, we're adding 1 to each element of the first list, 2 to each element of the second list, etc., 100 times, thus effectively adding
[100,200,300,400,500] to each element of the corresponding sublist of [[0,1],[0,1,…,6],…] to produce [[100,101],[200,201,…,206],…], which can be flattened to produce the list of status codes we want.
I originally generated the list using slightly different code (doing the addition 100 times rather than adding 100 times the index), and connected the list to the original program using a newline and `ị¢`; `ị` is wrapping indexing into a list (thus contains an implicit "modulo 41"; 41 is the size of the finite field we're using in this version and also the number of status codes in the list), and `¢` tells Jelly to look at the previous line to find the list to index into. However, @ChartZ Belatedly realised that rearranging the list generation like this, although it still takes the number of bytes, makes the list generation into a nilad followed by a sequence of monads. This makes it possible to treat the entire list generation like a literal constant by using a single `¤` byte, which is a less general method of specifying the grouping than the a newline and `¢` were, but worth it as it's a byte shorter overall.
This approach, where almost all the outputs are used, costs several bytes for the more complex post-processing, but makes the hardcoded vector require substantially less storage because the numbers in it now only go up to 40 rather than 122, so it saves more bytes than it costs.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n -l -rnet/http/status`, 31 bytes, score: 37
```
p Net::HTTP::STATUS_CODES.key$_
```
[Try it online!](https://tio.run/##TVJNc9owEL3rV@yhVyd3bpSQlGkcPNj0mhHWYmsqtK60hrg/vu5KJCQ3Sfv8vtZhPEzzPMAL8mLxo2mqxaJuls2@fl1tH9b13W@cvr3O84o8Wz@iqi@W2976DqpATC25qLY/1SqgZjRq2bY4pMML@WI5ck/BsmZ7Rtj4I4WTnMnLFBIjelY7jMi3W6UDW@1u93J0bAeHsOrJthhVSWc0UKEweQG4ST3S6I2qEWHLPQbhZijJ2KMVG/uIyejbpBo8DRR0mGCHxgZsWX3XRi5/Roys9l5f3f6Vryo9nYQ8DwVqRCMcrDHoM/tVsUTBG0gPS@fokkPLOTegDw5VFobUgpDZNkf/5HxXhsaekEZWEvnorNh6Io/qGX3H/Se6Esfkjc0cj9q6LwxrYecJGiJ41qHDj0Gx322ur@Q7SRjHQSqQ7UApFWhopuGGlced9h3mPLVYjUebQ6zfBulKf9XdyG6Cly3VGM4YYB0CXXvfnGRXqTpBpXaf5Ke46EkloKwPpOWzcGTi99ktf/r54BeGmJSyiw@7/2hI8nEu/Fy4uQge@b5nHu6jGBvjfw "Ruby – Try It Online")
Another cheap builtin answer. Not a perfect score because the reason phrases in the library are taken from [RFC 7231](https://www.rfc-editor.org/rfc/rfc7231#page-49) instead of the older [RFC 2616](https://www.rfc-editor.org/rfc/rfc2616#page-40) (as used in the question).
---
# [Ruby](https://www.ruby-lang.org/) `-n -l -rnet/http/status`, 47 bytes, score: 40
```
p Net::HTTP::STATUS_CODES.key($_)||416-~/$//7%4
```
[Try it online!](https://tio.run/##TVLPb9MwFL77r/BhSHAIEdIEUm@ldKNiXaMm5Tq58Wti4fgF@6Vd0MSfTnh2t2432@/L9@vFD/txmnp5DzSbfa@qYjYrq3m1Kx8Wm2/L8uMvGN9fPXx4err@9Dn7m1/l@Zd319O0QEfGDSDKk6G6Na6RhUfCGm0Qmx9i4UERaDGva@jj4R5dNh@oRW9IkTmCXLkD@o7P6HgqIyM4ElsIQJdboTwZZS/39WDJ9BbkokVTQxBrPIKWBTCTY4AdxQ0OTosSQG6oBc/cJNeozcGwjV2AaPRxFBV0PXrlR7kFbTzUJL4qzZffAwQSO6fObv/wV4UaOyZPQ4Zq1vB7ozW4xH5WXAPjtYwPc2vxlELzOTWg9hZEEpaxBSYzdYr@yvmsLCvTAQ4kOPLBGrZ1iw7EHbiG2ld0wY7RaZM4bpSxbxiWzE6jrBDlnfINvAyy3XZ1fkXXcMIw9FwBb0euuQIlq7G/YPlxq1wDKU/JVsPBpBDLx567Um91V7wb73hLJfgjeLn0Hs@9rzreVayOUbHdW/4pTmoUEcjrk9zykTkS8fPskj/@jPIn@BCVkosXu/@wj/JhytyU2SnzDihvifo8sLEh/Ac "Ruby – Try It Online")
Uses the length of the input to return the correct code for the three reason phrases not stored in the builtin hash. Credit to @Arnauld for the idea.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~200~~ ~~190~~ 188 bytes Score:40
Thanks to pxeger for -8 bytes, ChartZ Belatedly for -4 bytes!
At least I didn't use a builtin :P this was an editor nightmare, couldn't copy and paste my encoded data correctly. I stopped working on this when it came out to exactly 200 bytes. I don't know what kind of black magic created dingledooper's solution and I'm afraid to ask.
```
lambda i:sum(e[1:(e.index(sum(i)&4095)+2):2])
e=[*map(ord,"ͅdޕšcʸ̙୧θӾت^ڪǼ̿ѲͯܕА]Ԃؿ͍ښԵୣװ̲Ɖ׃ݓࣣ܈۩߾SׅϹݕיॽ")]
```
[Try it online!](https://tio.run/##TVTNaxtHFGdyi/6Khw5lt3GCVh92ItDBNU5qGifCknvZbGG0@yQN7M5sZmdlqceGQHoIFIopza2YUpqSDwKBFNoEemih2GlLAwpp0vo/cd/s2kannffx@/3ee/Nm05kZK9k4Cjs3jmKeDCIOop3liYO@13bwgpARTh3rEO57zdqllnuu7rbrgVvBjv9@wlNH6WipenA7@neX/XIv/P0Z2/@aHT74jr18xv5@zuZ32Ov7n7y5z377ie2/YH89YQeP2NvdM39@Ebz6jL1@wV7eZQd32Zt77NVTgu2x@WO2/4T9@jmb32LvvmSHe3vs7R12@M0P7PDhV@yf79l/z3vz2@yPH9m7XTYnqW9/ZlU3OKpE3EAHBtVq1avVYE1JI2SOFa/mQW9HmHAs5Ai6WhkVqjir1Cnp@kf08WBNIzcY0bkOq2GIaWk04JqS51dzGpAWhhsxQdiQQ6UTOitJGU3KKJRQGjJbsIUZmgXPMnS5NoLHp74GyW7msRFpjLA2ViLEjJwebKoJRtBFYpeUGM/IW4fLKpcRnRrQQ4TrZoyaLKtrCBGJoUAbbsF2hra5qYWtQB@TVGmuZ1RRJDSGptIk4Q94RI6bOWbW9mBb8rK7T4mlSXJdPktIvEgimHU2qAY9EFGEkqxSuayqSbKbSPiocK7GsdopIMulXUySD2Ik10pZHNhpkoAIixEu6lw8qQz6IkGV2wov2bENY2HL92pwRUni8jy4inJkxgtoj0qnLpWMRMF7mYu48DdOWddJ1cygrxRc5XpkiZonwfPbWxtlRMkRBWicMstTGiFtAvUYCQ79WWoxyycYCmxxOcKi1x61kw1F2ay3AuvTlGbOF2tp0fw3aAe0pG3ooZ6ghnWtlaaIV5BsJLQTdvxFdr24rSu0mDt8RnajANG62FubEGch1qIbOc45nVuL7uXDfr8LH6PObAVFhSft0PuwT4XTW3F8Z@o328HS1G83AhdotWEKQgLFL2RpLIwzqN6Q9LrcisaMEL4TOoOZwcwRfi1w3SXhe8dAcQzkAeXa1ClldDpCGhLxFtmJKqik2kbsf0Wj6x6bMUrHUpCjoFya2HyUeYKamrSp7cpZMQRJHU3oeLbEEaMvAvfofw "Python 3 – Try It Online")
The encoded data goes like this:
```
[Sum of description bytes & 0xfff,Numeric change in HTTP Code,Sum of ...
```
e.g.
```
[837, 100, 1941, 1, 154, 99, 696, 1, 793, 1, 2919, 1, 952, 1, 1278, 1, 1480, 1, 1578, 94, 1706, 1, 508, 1, 831, 1, 1138, 1, 879, 1, 1813, 2, 1040, 93, 1282, 1, 1599, 1, 909, 1, 845, 1, 1690, 1, 1333, 1, 2915, 1, 1520, 1, 818, 1, 393, 1, 1475, 1, 1875, 1, 2275, 1, 1800, 1, 2155, 1, 2967, 1, 1769, 1, 2046, 83, 1477, 1, 1017, 1, 1877, 1, 1497, 1, 2429, 1]
```
Here's the code I used to generate it (plus some useless vestigial code...):
```
dat = b"""100 Continue
101 Switching Protocols
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported"""
data = ([(x[4:],x[:3]) for x in dat.split(b"\n")])
def e(d) : return sum(d)&0xfff
d2 = ([(x[1],e(x[0])) for x in data])
print(d2)
ol=[]
px = 0
for x in d2:
ol.append(x[1])
ol.append(int(x[0])-px)
px = int(x[0])
de="".join([chr(x) for x in ol])
with open("de","w") as fh:
fh.write(de)
ind=b"Non-Authoritative Information"
print(len(bytes(de,'utf-8')))
ct=f"""\
d="{de}"
e=list(map(ord,d))
c=lambda i:(sum(e[1:(e.index(sum(i)&0xfff)+2):2]))\
"""
with open("decoder.py","w") as fh:
fh.write(ct)
from decoder import *
res = [(c(bytes(i[0])),i[1]) for i in data]
re = [x[0]==int(x[1]) for x in res]
print(sum(re))
print(len(data))
for i,v in enumerate(re):
if not v:
print(res[i])
print(ct)
```
[Try it online!](https://tio.run/##fVRNc@M2DD1HvwKjQ1dqHY/lj2TrGR/STHab6abrSZxeHB9oEbLZkUmVovzRTn97@kjZrvfQnkQCDw/AA6jq4NZGD97fpXA0oWUcx1mvR/dGO6UbjrJeRi875fK10iuaWuNMbso66gP09Rd8Mrq3LBxLnPt0l@dctZcB/Wr09V0DfquccGrL9KgLYzc4Gw3EEIiQibXDdUTPXLO7sNzQVFinRHm2DZD2qSmdqkqm@7VROdcwZvRktixpymDXAJYHWPv0yTRa4jSgF2b66tZscfN5HSKkKhR794hea/bN7X3YLc14Uxkr7AEVSWU5d9EQiX8SEoY/Gq79PaNXLdru/gTLEOmm4rBB8gBCmDcOUINdKilZ49ZmbqsaIu0TI14G411Zml0IuWnvQUmxLBmm27Y48moigcqDhJd5Pp4qo5nasGl8hT962YpS@fKzHn02GlxZRl9Yr9z6IjpD6ejSaKkC7yehymAfnFkfkNUdaGYMfRF25YmGJ@f16/Nj6zF6BQfk1HVTQUJsAnqUStDsUPmYm1MMHM9Crzj0@oJ26kK1zWa39LCvoLm4rGUE/R@xA1ZjG17YbtnSg7XGwpMFkscNdsLLH9D9MK3PWMydOOA@CEFYFz@1LThDshEmcsScdRthLj/PZlP6jW3tKwgVntrB@4jwVATeSjJP9vPheNHZz8eDRUpYbdqT0gR/t65K5ZJl/KbjdJFGkgviRKY0JsuusZrqZoP7d719URSR7J/4skWH8ekt0m8JBUgqq7RLZD@NTDmZL6Jqj6he9C@sP46uTNkVVcVaBrL00uCjA/V1tYcjhJ9tKHESx93fjdLJPF/bZH9RgCkBwF9gTQZMSSw57sS7OCVRU7FG1mLd3eGVo0VOo0hpOVnG//v8Yzq2U4JveXBcI7TzoXHF9ccPaZpGuZsUEPstkpP4L8l/xxFPSlW7ZCOqxFjZkR40KcVmKQWpceIF5Xk2TriL/LwPBnVUOP2hn477EPUt8hP8tpfcSLbd6vBfPeUOPRXWbOiIJeX/D46@jyzXEHGe5MceVJhcR3npg3zqPD9gPdSLPZm0smeXWwOqxVETX7nlNL2QyFPAECg7W49n3WzYYnk9FOWqgjQ2dYvjVRsHxrnC4I40oY2r6P39Hw "Python 3 – Try It Online")
[Answer]
# [YaBASIC](http://www.yabasic.de), 195 bytes, score:40
```
h=0
for i=1 to len(c$)
h=h+asc(mid$(c$,i,1))
next
x=instr(")64rRz!\"VEjX(#3I 2nBAsfm=tC_TuUhid",chr$(mod(xor(h,1329),127)))
b=99
if x>2 b=197
if x>9 b=290
if x>17 b=382
if x>35 b=464
?b+x;
```
[Try it online!](https://tio.run/##bVJNb9pAEFWlXupLL1VV9TR1ORiFSOGjSVHlRgSRFDU0CEzUQ6Vq8Q54K3uXrtfE5s/TsQk2Ib3tm5mdefPmZWzOYuFvF0rDxm2CUdA5szQyDn5tG7hnVp4Ru0yI0vFrdStwgxMW@04keI0CDdFo1uuWxNRYqStkbLRjv6ifv@vot5PNh1/2/fvBn5/Ox/ab4avWS3n1uhcvItf0f3vJLBDcbviBrjmR4k6qtBM0mu1Wt95oti7q1HXudruWWED6tQVzt9m92IEugVb3bAeaF4Tan1s71P5EqHPesS7nJ@mX7aUNNKFW0IONZXFmGNh9JY2QCdqPePogjB8IuYSxVkb5Koz3qbvv@1efdDHI97Dn@7g6wD@UPO0lJlBaGGbEGmEoSb2I3kpWRZDPRmn2kQnGaI6DY6aNYOFxeJSERqxChH6ghI8lx5FaI4cx0jBJ5WG2T1yrRJYEp4hwZwLUFRkDI8XFQlRbzGLMNUjLFh5GK6WZzmCCXGj0SzZX5JIJ/k0wLkMzyXYKbKqOY5ZFRKoopf@84qbngnOUh3SeEB4h9eKQx3thqB4OtaZQoT@bh@UVC96Q34DmCb8Q/tnYR8bgiQhVUjInpRehqJa7UbLse4tyaYJnncYkhpJcFGOumQifDxkQD5OBpxTcMr3Eo/zpbDLcJZVcVhrGyYokJ2vBiCRn4GWr45@UmzC5xEKcKW0aL8ShFIN0RZdi/6E2JEdpSd6aol6jhoHW6okjhhE5LL9Y9Se/9A15/4FllZn0miwIdPE19T@c/Vh5rPA3zxvDPeo451TQ3q9pb/8B "Yabasic – Try It Online")
Well this bit of voodoo was probably the hardest challenge I've completed on Code-Golf! But here it is - a complete, self contained routine that recognizes all 40 codes, in 195 bytes, in good old-fashioned BASIC.
As genius as [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s answer was, I really wanted to come up with my own solution, not blindly copy his formula, nor just pull codes off the net.
An early attempt with 2 bytes per status code, based on a Pearson hash, bottom out at 238 bytes, and it became obvious I needed a hash table with a single byte per code. Worse, due to the vagaries of UTF-8 coding, attempting to use all 256 ASCII codes gave garbage out, so I was stuck with the basic 127...
I based my answer on the fact that the sum of the ASCII values for each code was unique, and I just needed to find a way to get a unique byte from each one. I ended up writing a seperate utility to generate hash tables, XOR them, test for collisions, and increment the XOR until each hash was unique. 1329 was the "magic number" I got. *Of course*, the result had to include a " so I lost a byte with the \ needed to add it to a string, plus an extra X to deal with that sneaky jump from 305 to 307.
I really feel I levelled up as a programmer on this one, and I hope you like it!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/),
# 186 bytes, Score : 40 ~~41~~
```
S←18 22 53 56 38 91 76 83 98 11 31 86 90 62 40 47 25 80 72 5 10 99 85 24 2 68 52 96 77 19 9 65 4 87 33 36 57 16 49 28 41
C←{(∊⍳¨⍵)+⍵\100×1+⍳5}2 7 8 18 6
f←{C[⍸S=∊⍎2↑⌽⍕8-⍨|-/∊⎕UCS¨33⍴⍵]}
```
I made a very sketchy "hash function", that is so hobbled together it will only work for these messages.
```
{⍎2↑⌽⍕8-⍨|-/∊⎕UCS¨33⍴⍵} 'Foo Bar'
33⍴⍵ ⍝ 'Foo BarFoo BarFoo BarFoo BarFoo B'
∊⎕UCS¨ ⍝ convert to UTF8 numerical array 70 111 111 32...
|-/ ⍝ |70-111+111-32...|=104
8-⍨ ⍝ 96
⍎2↑⌽⍕ ⍝ 69
```
Rehydrating the Status Codes
```
{(∊⍳¨⍵)+⍵\100×1+⍳5}2 7 8 18 6
100×1+⍳5 ⍝ 100 200 300 400 500
⍵\ ⍝ 100 100 200 200 200 200 200 200 200 300...
∊⍳¨⍵ ⍝ 0 1 0 1 2 3 4 5 6 0 1 2 3...
+ ⍝ 100 101 200 201 202 203 204...
```
Lookup Status Code
```
C[⍸S=∊Calculated_Hash]
```
[Try it online!](https://tio.run/##ZVLLbtNAFN3nK84uIBQR2/FrwaJEbYloSJQHG2AxjSfJSM5MGE/SBui2QohUsKj4he4LEhs25U/8I@HasZWmbOyZM/dxzrmXzeNatGKxmmzSq@tWJ738Vt/06WsFsG24DlwPToDQgu8hcBAGsCw4FgIPYR2ejUYdDR@2i6AOn1Jg1RGGCFzYDdjwArg2Qg@@DytECM9FA4EPx4HjwSXUQyOEHaBhVZrU@uOj9POXdH17d5Oufz1@Qp@3Vr3@94dFx1v3woYPIhHAq4yz6OabdP27/yzPubLTy@/p1z/p@jqopeubT7WnGX51PWz2724cJ13/pHLvLiqbzRjVppJGyAWvokK3/pkwo6mQE3S1Mmqk4qSa4Z2X@a@pOTM8ys8HoxGfZ5c88ZWStYOFmSotDDNiydGSY6VndFayDEHWjEuzvfd4ws0@1GXaCBbvg@1FbMQ85mhOlRjxpEDVkkfocmohKTRebeEjtZAFpT7n6Jgp12V7g7aKxFiUnIcJz2Ser@5rL5AMGPDZXGmmV@jxSGg@Kgg9ZxEh7xc8KYChZFvpH8rSXbaaEas8jDKjkpw@FVHE5Y7RPb5tTjUiZOhBHKuznbUE5Gaz07iYU04SmeHURYxylx80KxhiIGZcLQqmZOw4FqWQYyWLeidcTsz0QYUuSVYyEnnxIybih6UPqbdZYaAUTpie8L3X2rDX2j4pOSl9ShZzspS2Bm2ylGGwmu9n0UuPyQnPbeiTrmQsdrIPz@c0BfYfoRati5a0OH2ul1zjUGt1b@ytGa1PNo8yPpvgMW3yGStnT3m0W6BJLqnurmMRte/ii8Ggi9dcJxmPnGgpq1qpVP4B "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 123 bytes
```
⎕FIX'file:///opt/mdyalog/17.1/64/unicode/Library/Conga/HttpUtils.dyalog'
f←{⊃s⌿⍨(⊂⍵)≡⍥(⌈~∘'-')¨⊣/⌽s←HttpUtils.HttpStatuses}
```
No builtins that do this exactly (as far as I can tell) but luckily the statuses are stored in Dyalog's HTTP utilities.
[Try it online!](https://tio.run/##TVK7bhNBFO3zFbdzUpj1@hVAFIQoD4uEWLGDKGgm3mt7pPXMMjt2YqKkABQlJo5okKgQDyGlRzRICIlPmR8xZ3ZxcLV7X@ece@aKJC5GYxHrXpGPLauIo9nMXb/fbDwrdGXM94Mg0IkNBnlTEK7eCYN6NRgq2dERBzvy0AgzDta16olg29rkwMo4vZO3F5a67vzdiZu8Tt3Vbze9WXaTV276Y8VdfnbTb8vu6uLMXXwoFAsrf27c5Gvgrn6lmPiP4/9aVthhyunp7MRzkhIDRpObXmMW2A9DN/lSoMIJkN3kHDRnD56fuelPd/kJqVM3/Uju7RvCWhjzEKDvZjCnoJ1@r5ZmYSmk1pG0nb5UPWoabXVHx@lSuVSivcf4hLRuWFiO8F@mtU6Hkzyo0BOtimtD29dGQqkcMTVUV5sB/rVCRxUdBINgr0VYo31O2S5k6tQUxkoR3@YqoN0dxlYmMdN6X8sOp0iGtKtHHFGTga7QGI@RLdOmHqoIfxVqMdOe7bNB5HktJiLZlezLNTpI2S937MdWqc2DRPvng6JIGu7YpSqIH4kIiRdDTn0c0oES@XYvgVIFXVOMByDPmjDmkxVoMIcyilghyplzVVXQ7jLmoyy5Fsf6KBup53HmpDiMGanVXBx5N0EgO5mFizx358qoLQesh17hPW9bN5ZefliiLa2AFYa0w6pn@wvTIaRjS60imeFuCly4z1duUTfAasfU1pp2hOl5oOq8WDzYb@QVHDsKsFOlwwQW4hKwYyQFtceJn6nPZ1DYF6rH2a4trJN2Zb5suEobxwk8F4taavC/gRswCtfQYjNiQxvGaINKmIE0BrgJb3/WXc5eawuHeSTGiCvZEM7Fv9oImBlZDS/yr@fWtxreZbvdbtJTNqlXkCmcr/MX "APL (Dyalog Extended) – Try It Online")
[Answer]
# c# 9, 101 bytes.
```
System.Console.WriteLine(args.Length>0?(int)System.Enum.Parse<System.Net.HttpStatusCode>(args[0]):0);
```
[Answer]
# Java EE, 111 bytes, score: 40
```
s->javax.servlet.http.HttpServletResponse.class.getField("SC_"+s.toUpperCase().replaceAll(" |-","_")).get(null)
```
[`HttpServletResponse`](https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpServletResponse.html#field.summary) has public fields for all the statuses prefixed with `"SC_"`. The names, however, are all uppercase and spaces or dashes are replaced with underscores. The values of these fields can be obtained dynamically using reflection.
[Demo](https://www.browxy.com#ALIEN_109694)
[Answer]
# [Zsh](https://www.zsh.org/), ~~197~~ 187 bytes, score 40
```
>`sum`
F()for a {let n++;ls|grep -q $[32#$a]$&&<<<$n&&bye}
for b (5SOO E3HOIOTU3P5PJL 1K82FFFCPFC5JIQF 3AIQ9M13UPUUQ0PR9RBUIAHSNOF8M32QLT2H C2Q1BISP3DKE)n=$[m++]99 F `fold -2<<<$b`
<<<201
```
[Try it online!](https://tio.run/##jVPNbtpAEL77KUaqRaAICduQhAYqEYrBCQQDphcaCWMPsJLZJWsDgTTP0EvVUx@kz9MX6CPQWVPSSL2Ui3d@v2@@Gfbx4tDK5rLZw/tJvF5ONDubmwkJPjxFmADP56@i@PNc4goKD6CPLfON7t/rmUy1WtV5JjPd4bOmCqaQLQ97PWha7Z7T80aWW3ZvOmDcXpq2bTdcu1G@cfo2WHWnX@ka1sgdjfpFd1AZXI@cent417Mvu5bZ73hmGxpm37h2hq714baZ4zV9vMzn7ysVsGEyE1EIBVPBTycafcyicchpcglvtZy2XbAIQaIfAsJeC4U2r01aKnk/0dgMxmPQEWqgz@H@Hp4wWAjlIFPfw8/vX3/9@HKl5vby@WfAKMZ/c75RzjN15litNjWjWISG4AnjayTDgOGWJcGC8Tm4UiQiEFGsmZTUu6WPAQ3ilmBIbxPqQYCro2HBneCF@jpZCMkSP2EbBIeTrkt6C04ZJcpIkZAnZJZhgDER/es5B9eXCfOjF59FsN11lLAVadJYCBZgTE4DumKDIbhI3TklRjvymmCLNQ/pZcEQEXrJAiVZCjehipDNGKpwGUYkCw33qMouwMPlSkhf7ohRyCQGiVYi4GtawQAf1hgr24AR94/T7alLieBcf7ck8DSJypTTIg5yysIQOVlH5COrEsF2kerD1FmPIrFNS86PdqqkP42QXBdHcqDUJAAWpBK@xrk8MQOPLVGsFcOKkm0WMUXfKEKL9ksPAzrI58niVbVB1GlKwUOW9rV9Ojnlt166Ngk12YEnBHR8OVeNSqdgYTRwjhHB5xQgOXm8XpGEdAk0Y8h88HYrVXN@qqHAwOdzTGcd0jjxjB2HNS6g@bgizf3XXMqkv0M3IDldwxDlBiU0pRSSIkbaxFnSTSj502wz3VaLDnPr78i20iI6F7W1DfVMwcq0kT85L7qVaS9tz3PhI8pYMUgZnsbRmpr6h57V/ud3plKHgZD47hPo3uE3 "Zsh – Try It Online")
Can probably be a fair bit shorter, but I'm not really with it right now.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 41 bytes
```
+[net.httpstatuscode]($args-replace" |-")
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Xzs6L7VEL6OkpKC4JLGktDg5PyU1VkMlsSi9WLcotSAnMTlVSaFGV0nz////SkGphaWpxSW6oUGeCiH5@Qo@@XnpSgA "PowerShell – Try It Online")
Cheap builitins, again
-7 bytes for @ZaelinGoodman
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 133 bytes, score 40
```
f=(t,i,c,s=require('http').STATUS_CODES[i])=>s==t?i:i>999?0:(g=_=>s&&s.slice(--j)==t.slice(j)?g():j)(j=0)>=c?f(t,-~i,c):f(t,-~i,j)||i
```
[Try it online!](https://tio.run/##XVRdb9owFH3vr/BTSSRAUKAbVAExRju0MhCEvVRV5SaXYBTs1HZo2br9dXZtHFh5S865H@fec5M13VIVSZbpChcx7PfLwNNlVo7KKpDwkjMJXmmldVbyq/OwHy7mT4PJ1@H8gT36QVcFge6xDuu22@1ereMlwROCl5eqqlIWgVeprH0McW9rv5d4fmfte@ug5neDqLfEXpW/2M3vFI9r//2d7SfPa4h0FbiWDJT3@4KQeq3WIaWB4JrxHEplC9URmr8yHa0YT8hUCi0ikSrLXtmEyXf3YkIHEqiG2CFXiPSjCLIT1EDoh@CVfq5XQjJNNdsCGfGlkBt8FtzFNW0cMWpQowNbCM5AgT7DrxGfUqkZTT8wDStwnKeaZSmQwUrglpSjjNyx2EJMpoC9OSalO8cZ4bci57F7N6rnAGSiVyAddlCoyVjEbMmgCDUaFwrMqt6Kcp8QC2GTCUnljswgRtOjg8SmlfiFxgi/5KAK1KhbcHrY0i9XvWmFTelug2JtAhYqqIbVLJ9ZHAN3WKHxNEvTChwD1o2JofppKl6PRa5dwsE1@pyCI8wIdiRinMP2LLJ2nav4bC2yk5CQbUDkxUTtw3Et8VIdVDej3wnuetTNzPfAE706q1q3Y@POBI@Z7XpLWXpkG//1HKIyvSOhEOSeyqQo3TyFVBaz0YEXPHG0NY2rPEOL8FbJGC2iJNxlRf71KR/pGeUJ2O3NcQlqyU6LqptFDd8y9JeeK21Zr0d4n5Ljpc5BbkGSoZRCOr7u1j/a4L0ak4@ZV@5K7vDzeqU7hx7uUm7xrAleyxZ7HaW0rPsu/oMXLXsD38JwSn6CVEalnaUYv3Txx6/iBzmk0crzHiL8bZWJhjf96JOgS8y/Ap1QIoVqKhIPfyzI@WXiHkgQEJPj32Cdm/0/ "JavaScript (Node.js) – Try It Online")
I have no idea why it is so complex. But it at least works within 200 bytes.
---
# [JavaScript (Node.js)](https://nodejs.org), 54 bytes, score 37
```
f=(t,i)=>require('http').STATUS_CODES[i]==t?i:f(t,-~i)
```
[Try it online!](https://tio.run/##bVRNb9pAEL3zK@ZSYatAQ4C0TeRUlJIUNQQEppcoqjb2ABuZXWe9JqFV@tfp7HoNBeVk@83Xm3njeWRrlkWKp7ouZIzb7TzwdI37waXCp5wr9KpLrdOq35iG3XA2/dUbfetP7/h9EOgv/HxOzvW/3N9GUmQaskgqhAC6SrFNY67kyhs9PGKkGyi04ph5fyoAzZOTc6j2pNBc5FitWahJ0PSZ62jJxQLGSmoZySSz1lMbMPrhPoxrTyHTGDvklJBuFGG6h1oE3UpR7@Z6KRXXTPM1wkDMpVrRuxTOr239wLAhjg7sEDjBDPURfkb4mCnNWXJgaVmCwzzRPE0QekvJI8ycydAdyjXGMEaqLSgo2TibIX4lcxG7b8N6iggjvUTlsIKhhqGM@Zxj6Wo4zjI0o3op030kLMRVKhVTG5hgTAJGBcW2pfiVxQQ/5ZiVqGE3E6yY0m@XvW2JjdlmRWRtACUqTS3LWT3wOEbhsJLjvpe2JThEyhuDMXWTRD7vkpy5gEI19pCgM5gWbEtglKPyPLJyHbP4ZCWynUDIVyjzsqPPxXLNE1623jStX0vhajRNzzcoFnp5lLVp26aZSRFzW/WK8WRnbf1Xs0/M9AZCKeGGqUWZur13qc8mg8IuxcKZrWgiy1OSiHYVhiQRg3CTlvFn@3gyT5hYoJ3elIaQzfl@UE0zqP5LSvqyY6Ydq/WA9lMJ2tQpqjUq6CsllbM33fgHK9pXI/Iu8tRtyTX9Xs9s49BiL9Wa1hpoW9ZUa0elY9V3/gdadOwOfA/DMfxElRmWtpey/Wrl1fcbNP08Qs@zx6MGdxHdoRpofNH3PgSXYE6GpnU2TwBzaGSCjUQuPLo@5OXXwL1AEICJ9i@sq0KdK@GO0nvw3vJ6BVqvaAke@m8UqN5@6FYpPUsy9I135TDrReW1BieUqHIQ9S6GVHKh6QIUfv72Hw "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript, 63 bytes (Node.js), score 36 for some reason
```
n=>Object.keys(a=require('http').STATUS_CODES).find(e=>a[e]==n)
```
Works with ES6 and above.
[Answer]
# [Julia 1.0](http://julialang.org/), ~~143~~ 135 bytes, score 40
```
x->Int["Ƙ...Ĭ..ƙ.ƞıƕƐƛ.ǵƚ.ÎĮįƜijǷʃdĭƠÌƖǶơÍƔǸÈƑǴƗƓǹƟËÉe....Ɲ.İ"...][sum(Int[x...])%217%159%117%54]
```
[Try it online!](https://tio.run/##TVPbTiNHEH33V5QsIRktjBhfIDwYLYuARYFggckL4WGYKdu9GndPenrAjvIBe9dmN/fsJpv3XJXNZZ9ttT@LnO7hNpLlrqpTdU5VVz8oUhGFo4te@2K0uLYjzXHVfhsEwfSXILDfBfbH6Z/2K/vC/hDM/rbfB5Pn09@mv9vX079m/04e25fJ9Ff7dvLUfj37x/48eWa/nP03eWi/mL2z39hXs/f2p8mTySNGvcC@CaZ/VHE4Oc6LYc0xjZw1P1cPV@bC1upciP9W8@TCcG5yalO1Wq2ES0u0oaQRsmAYIR2eCxMPhOxTRyujYpXmlTpA@x/iL6QNzZHhBOc6rccxZ6XRoI@UXFwvzEBpYSIjzph2ZE/pIc5KAtEEwjOxNDBbdMA5m1ueZepE2ogovfY1QLtXpEZkKdPGQImYczhD2lNnnFCHUV0CmI7hrdOWKmSCU4MOmWnfDFjDcrwGGYnoCXbhFh3l7JobubQV6vIwUzrSYyhKhObYVJogvhclcHxaYFawQzqSUdndZ6jSBF0nGg9B7kFIc84GNOhTkSQsYZXMpaomaPcY@Yl3rqepOvcpy6XtJxmdpgzXSimO3DRBIGI/wts8H1wpo64YsiqcwlU3tl4qnPxwibaVRK0wpF2WfTO4lR1COrpUMhG@7lYkUu9vXFfdBKsZU1cp2o103xVqXgUXjw52yoiSfQQwTpkXGUaITUCPiYioO85czvJVDgIHkeyz7/UQ7eQ9UTYbrtDmKMPMo9taWpg/9pe1xDYcsj5jTZtaK41I6IvsDLETbvweXfe3tY3FPI/GsBs@Cevibu0MNT1ZCzdyibmeWwv3cr/b7dDHrHOnwCu8asc9kEoeK814LUuVCvaZ3OMhISnPUmFq/iktUPUTWZ2vEL5YJbwA0Mgg5QazQKkYCtOulyjNOfYaiF7NQefp8zX4Mu2Doncdb/t63uu@fqpOMZFS0Z02hT7CaX4DybTAg5C12o2Qhcty8yU3Yx3dr3I3H6jzstjF/w "Julia 1.0 – Try It Online")
it could probably be more golfed but good enough for now
[Answer]
# Java, 32 bytes
```
n -> HttpStatus.valueOf(n).value()
```
Using Spring. Plus a couple of megs of libs!
[Answer]
# [R](https://www.r-project.org/), ~~131~~ 128 bytes, score 40
```
`-`=utf8ToInt
c(408:417,0:7+100*1:5%x%!!1:8)[-"+41i@N!>Q
-bTE6 ;?J85
M0IP)F/^]3G* "==sum(-readLines())%%217%%124]
```
[Try it online!](https://tio.run/##TVJRj9JAEI6v64PRBxNfdDhDQu@OSE9OCBdUJIDo9a5C0Qdz5pZ2CpuU3brdAtX423Fa7nr0aXfm6zff983qXdgNU@kboWQtseAvaOTBpZCYQBfKjpXAa/iheRyjhlBpMJgYIRe72/ptNzVh21NjaZhfazbanabdOm10Wid2o3Fsd86r22qlYnfa1s/60aOTpv1EfLx6Xnn/DYrvZf3Z3Bu8g4sPX9rnj8FpjF1r@ObVr5u3L56OjgGOut0kXdXqpayaZVWrZ3arWrXPmje7f8zhcS08PeyzvpKkLkU23QjjL0kouFoZ5asoYddfWZ/QBgPW832M88OVkvVeapZKC8ONWCOMJdlc8dw9dSFnRHI4wQRNeXO5NoJH5d1JIyPiCKG/VMLHhDlqjQG4SEySAFHGhiqVAZsiwrVZoiZuA44KRChIxizBXOg2Yx6uYqW5zmCCgdDoG/aJB3T5nVLybCb5Xu0f@svl2YrIiyZBA5qh5yIIUBbs@4kOEj6AvNCLIrUpTNO5SIDPI2TFYMhTIDLhF9YfOO8mgydWqFKTRxxGgmSNlER2iXJhlg9olxQrGYiCY8hFdMAwIHaTgacUXHK9wPtGfTYZ76tKLshhksYUAW0HHIqAg5fFJZaKEy4XWPiZktQkFIWJwTamrPjhXHqYqCVtaYp6Tc93oLXa5z5e0a7y6AiVpzuiR7HhGcuBtD6glNfEURDf9Ur/nz3Phe@ok3xSoeJe7u4/ "R – Try It Online")
Unlike many other answers, this one isn't really based on some "magic formula". Here we use modulo hashing simply to convert the byte sum of the input to a unique checksum and then to make it fit within ASCII in order to avoid multi-byte characters (albeit with some unprintables). The lookup string is then just a catalog of these checksums.
Finally, we return a value from the vector of status codes at the position where the checksum matches. The status codes themselves are completely unencoded: Initially, I just used a literal concatenation of relevant ranges `c(100:101,200:206,...)`, but then managed to squeeze off a few extra bytes by declaring a "structured" range encompassing the values `x00:x07` for each hundred. However, the savings are rather modest, as we now also have to fill the lookup string with dummy values (whitespace) for missing codes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) + [Plug](https://hexdocs.pm/plug/readme.html), ~~30~~ 29 bytes, score 40
```
l„ -'_º‡…ƒË :”§¬.¡¤n.‡‚.”rJ.E
```
Beats all other answers. No TIO link because the module (`Plug.Conn.Status`) used here is not on TIO.
```
l„ -'_º‡…...”...”rJ.E # trimmed program
l # push...
# implicit input...
l # in lowercase...
‡ # with each character in...
„ - # literal...
‡ # replaced with corresponding character in...
'_ # literal...
º # concatenated with...
'_ # literal...
º # reversed
…... # push "code :"
”...” # push "Plug. Conn. Status."
# in title case
r # reverse stack
.E # evaluate...
J # joined stack...
.E # as Elixir code
====================
Plug. Conn. Status.code # full program
Plug. Conn. Status.code # return HTTP status code with given name
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/40713/edit)
There are various coding standards enforced at software companies which have the goal of increasing code reliability, portability, and, most importantly, readability in code written jointly by different developers.
Two notable examples are the [MISRA C](http://en.wikipedia.org/wiki/MISRA_C), and the C++ standard developed for the [JSF project](http://www.stroustrup.com/JSF-AV-rules.pdf).
These are usually in the following form, after carefully specifying what the words "must", "shall", "should", "might", etc. mean:
Example:
>
> Rule 50: Floating point variables shall not be tested for exact
> equality or inequality.
>
>
> **Rationale:** Since floating point numbers are subject to rounding and truncation errors, exact equality may not be achieved, even when
> expected.
>
>
>
These coding standards pose restrictions, usually on code which would be legal from the compiler's point of view, but it is dangerous or unreadable, and is therefore "considered harmful".
# Now let's abuse this!
You are accepted as a member of a small standardizing committee at your company, which is intended to design the new coding standards every developer at the company will be required to use. Unbeknown to the others, you are secretly in the employ of a sinister organization and have as your mission to sabotage the company.
You have to propose one or more entries to the coding standard which will later hinder the developers. However, you must be careful to not make this immediately obvious, otherwise you risk it not being accepted into the standard.
In other words, **you must introduce rules to the coding standard which look legitimate** and have a good chance of being accepted by the other members of committee. After the projects are started and countless man-hours are invested in the code, you should be able to abuse these rules (for example, by a technicality, or by a **very** literal interpretation) to flag otherwise normal and good quality code as being against the standard. So they must put a lot of effort in to redesign it, and the rules will hinder them from this point on, but as the rules are active for quite some time now, pure momentum will keep these roles alive, and as there are significant conflicts of interests between different levels of management, the other managers will probably keep the rules alive (they would be foolish to admit their mistake!), therefore hindering the company! Mwahahahahaaa!
# Scoring
The highest voted answer after approximately 2 weeks from the first valid entry wins. I have an idea for a good answer, but I will only post it a few days later, as someone else might come to the same idea, and I don't want to rob them from the pleasure. Of course, my own answer will not be accepted above any other, no matter the score.
Voters are encouraged to score answers based on how well the loopholes are hidden, and how frustrating to the developers they would be.
# Rules and regulations
* The rule or rules must look professionally written, like in the above example
* The rules should look genuine (so things like *"all variables must contain at least one underscore, one upper case letter, one lower case letter and two numbers"* are not accepted. They would indeed hinder developers, but would most likely not be accepted by the committee) and if their merit is not immediately obvious, you should give a good rationale.
* You should be able to find a way to use/abuse your rules to sabotage the developers later on. You might abuse any ambiguity in other rules, or you might use multiple rules which are harmless on their own, but diabolical once combined!
* You should post an explanation in spoiler tags at the end of your post about how you could abuse the rules
* The language used must not be an esoteric language. A language widely used in real projects must be chosen, so languages with C-like syntax (instead of things like Golfscript) are preferred.
[Answer]
# C / C++
>
> **Rule 1:** octal constants shall not be used
>
>
> Rationale: octal constants can be a cause of confusion. For example, a
> casual glance over the line
> `const int coefficients[] = {132, 521, 013, 102};`
>
> might miss the fact, that one of the numbers in the array
> is defined in octal.
>
>
>
If you want to be even more evil, add the following:
>
> **Rule 2:** hexadecimal constants shall only be used in the context of bit manipulation.
>
>
> Rationale: If a constant represents a numerical value, it's more
> readable if it's in decimal. A hexadecimal constant should indicate
> that it represents a bit mask, not a numerical value.
>
>
>
## How it can be abused:
Take the following simple program which will add the first 10 elements of an array. This code would not be standard-conforming.
```
sum = 0;
for (i = 0; i < 10; i++)
{
sum += array[i];
}
```
>
> Note, that `0` is, per definition, an octal constant. Per rule 1, requiring it to be written as 0x00 all through the code is frustrating. Per rule 2, even more frustrating.
>
>
>
[Answer]
## Python
Rule 1: All code must be byte-compiled using the `-OO` flag, which optimizes the bytecode. We want optimized bytecode for size and efficiency!
Rule 2: Tests must be run against the same "artifact" of code that will be put into production. Our auditors require this.
>
> Using `-OO` removes `assert` statements. Combined with rule 2, this effectively bans the use of `assert` statements in tests. Have fun!
>
>
>
[Answer]
This is for a Node.JS project.
>
> ### Section 3 - Speed and efficiency are of essence
>
>
> **Rule 3.1:** Files should be kept to a maximum of 1kb. Files bigger than
> this take too long to parse.
>
>
> **Rule 3.2:** Don't nest functions more than 3 levels deep. The V8 engine
> must keep track of many variables, and deep closures like this make it
> work harder, slowing down general interpretation.
>
>
> **Rule 3.3:** Avoid `require()` runarounds.
>
>
> **Rule 3.3.1:** Any modules `require()`d should not `require()` to a depth
> of more than 3. Deep `require()` chains are expensive both in terms of
> memory usage and speed.
>
>
> **Rule 3.3.2:** Core modules count as a single `require()`, no matter how
> many times they `require()` internally.
>
>
> **Rule 3.3.3:** External modules count as a maximum of 2 `require()`s. We
> cannot afford the same leniency as with core modules, but can assume
> that module authors are writing efficient code.
>
>
> **Rule 3.4:** Avoid synchronous calls at all cost. These often take a long
> time, and block the entire event loop from continuing.
>
>
>
## How it can be abused:
>
> Rules 3.1 and 3.3 do not work well together. By keeping a maximum of 1kb and 3 `require()`s down the chain, they will be hard-pressed to succeed.
>
> Rules 3.2 and 3.4 are almost incompatible. 3.4 bans synchronous calls; 3.2 makes advanced asynchronous work difficult by limiting the number of callbacks.
>
> Rule 3.4 is, in all honesty, a rule that is good to follow for real. 3.1, 3.2, and 3.3 are complete bogus.
>
>
>
[Answer]
## JavaScript (ECMAScript)
>
> ### 7.3.2: Regular expression literals
>
>
> Regular expression literals must not be used. Specifically, the source code
> must not contain any substring matching the *RegularExpression* nonterminal
> defined below.
>
>
>
> ```
> RegularExpression :: '/' RegularExpressionBody '/'
> RegularExpressionBody :: [empty]
> RegularExpressionBody [any-but-'/']
>
> ```
>
> *[empty]* matches the empty string and *[any-but-'/']* matches any single-character string except the one containing '/' (slash, `U+002F`).
>
>
> **Rationale**
> Regular expressions are often discouraged for readability reasons. It is
> often easier to understand code with traditional string operations rather than
> by resorting to regular expressions. More importantly however, many regular
> expression engines offer subpar performance. Regular expressions have also
> been associated with [security issues](http://www.collinjackson.com/research/xssauditor.pdf) in the context of JavaScript.
>
>
> However, the Organization™ recognizes that regular expressions occasionally
> *is* the best tool for the job. Therefore, the `RegExp` object itself is not
> forbidden.
>
>
>
(The syntax of the grammar excerpt itself [not the one it defines] corresponds to that of the ECMAScript
specification. This would of course be defined more rigourously at
another point of the hypothetical specification.)
### The trick
The following program is non-conforming:
```
// sgn(x) is -1 if x < 0, +1 if x > 0, and 0 if x = 0.
function sgn(x) {
return x > 0? +1
: x < 0? -1
: 0
}
```
>
> The productions for the *RegularExpressionBody* nonterminal given above
> shows a common way of expressing lists in BNF by relying on explicit
> recursion. The trick here is that I "accidentally" allow the empty string
> as a *RegularExpressionBody*, such that the string `//` is forbidden in the
> source code.
>
> But who needs single-line comments anyway? C89 and CSS seem
> to do all right while allowing only `/* */` block comments.
>
>
>
[Answer]
# C#
>
> **12.1 Static methods that affect the state of the program are forbidden**
>
>
> This is because it is hard to reliably test the results of a static method, especially one that changes some state.
>
>
> **12.2 Static methods must be deterministic**
>
>
> If the static method takes an input and gives an output the result must be the same each time the static method is called with the same input.
>
>
>
# Why
>
> The entry point for a C# program is the private static method 'main'. By the first rule this is now forbidden because the rule forgets to state that only public, protected or internal methods should follow this rule. If testing really is the concern only public methods should follow rule 1. Main may also break rule 2 as the program will give an error code if the program fails, this may occur independent of the input parameters. For example the program might not find a file or may have dependencies on other systems that are not setup correctly.
>
>
>
[Answer]
# JAVA/SPRING
>
> ### 4.2 Use of Reflection in Production Code
>
>
> Because Reflection can be used to access otherwise restricted parts of our source code
> use of reflection in Production Code is strictly prohibited.
>
>
>
### The Trick
>
> Spring technically uses reflection to instantiate and manage the objects that it supports. By enforcing this rule, all Spring utility would have to be removed.
>
>
>
[Answer]
## Website encoding
>
> **666.13 UTF-8 must not be used and shall be replaced by UTF-7**
>
> Rationale: UTF-7 is more efficient than UTF-8, especially when targeting users from Arabic countries which we do.
>
>
>
How it can be abused:
>
> HTML5 specifically disallows UTF-7. That means, modern browsers won't support it. If all the testing is done on a browser such as IE 11, nobody will notice this until it is too late.
>
>
>
[Answer]
## JavaScript Bitwise Operators
>
> **1.9 You shall not use multiplication or division or flooring unless they are considerably faster than their bitwise counterparts. They shall be replaced by the bitwise operators <<, >> and ~~ respectively.**
>
> Rationale: The bitwise operators are more efficient.
>
>
>
How it can be abused:
>
> Using << or >> instead of multiplication or division will cause troubles when handling large numbers. Also, they ignore operation precedence and decimal points. The double tilde will return different values when you give it a negative number.
>
>
>
[Answer]
## JavaScript (ECMAScript)
>
> ### 7.3.1: Identifier conventions
>
>
> Restrictions are placed on identifiers depending on what type of identifier
> it is. Identifiers are split into the types *Variable*, *Constant*,
> *Function* and *Constructor*; see 5.3. The restrictions are given below.
>
>
> * **Variable:** The first character must be a lowercase letter character.
> *Camel-case* (see 1.3) should be used to separate words
> within an identifier.
> * **Constant:** The identifier must consist of only uppercase letter
> characters and underscores ('\_', `U+005F`). Underscores
> should be used to separate words within an identifier.
> * **Function:** Functions must follow the same rules as the *Identifier*
> type.
> * **Constructor:** The first character must be an uppercase letter character.
> *Camel-case* (see 1.3) should be used to separate words
> within an identifier.
>
>
> **Rationale**
> Readable identifier names is very important for maintainability. Restricting
> the identifiers to well-known conventions also eases transition between
> different code bases. These particular conventions are modelled after the
> standard conventions for the Java™ programming language [[1]](http://www.oracle.com/technetwork/java/codeconventions-135099.html).
>
>
>
### The trick
>
> I regret to inform the jQuery team that the most common name for their
> "global jQuery object" clashes with this name convention. Luckily, they've
> already thought of that and provide both `$` and `jQuery` as global names
> referring to the same object. I imagine that the userbase might not be as
> keen to switch from `$` to `jQuery` everywhere, though.
>
>
>
] |
[Question]
[
# It's all in the title...
Take as input a positive integer `n>=12` and... do what the title says.
Yes, this is on OEIS [A187924](https://oeis.org/A187924).
**Some test cases**
```
12 -> 912
13 -> 11713
14 -> 6314
15 -> 915
16 -> 3616
17 -> 15317
18 -> 918
19 -> 17119
20 -> 9920
40 -> 1999840
100-> 99999999999100
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins!
[Answer]
# Befunge, 81 bytes
```
&>00p0v<!%g0<
v%"d":_>1+:0^
>00g->#^_:0v
0g10g-#^_.@1>
>0p:55+/\:v>
^1+g01%+55_$^
```
[Try it online!](http://befunge.tryitonline.net/#code=Jj4wMHAwdjwhJWcwPAp2JSJkIjpfPjErOjBeCj4wMGctPiNeXzowdgowZzEwZy0jXl8uQDE+Cj4wcDo1NSsvXDp2PgpeMStnMDElKzU1XyRe&input=NDA)
Can handle up to *n* = 70 at least, after which some values will start overflowing the stack cell size on most implementations, and on those that don't, it'll take so long that it's not worth waiting to find out.
Given those constraints, we don't even bother trying to handle values of *n* greater than 99, which means we can more easily test if the value ends in *n* with by simply comparing the value modulo 100 with *n*.
Below is more detailed breakdown of the code.
![Source code with execution paths highlighted](https://i.stack.imgur.com/n3yFY.png)
![*](https://i.stack.imgur.com/jmV4j.png) Read *n* from stdin and save in memory.
![*](https://i.stack.imgur.com/z4eIY.png) Initialize the test value *v* to 0 and start the main loop, incrementing *v* up front.
![*](https://i.stack.imgur.com/RFUim.png)
[Answer]
## JavaScript (ES6), ~~55~~ 54 bytes
```
f=(s,p=0,a=p+s)=>a%s|eval([...a].join`+`)-s?f(s,p+1):a
```
```
<input type=number min=12 oninput=o.textContent=f(this.value)><pre id=o>
```
Takes input as a string. Needs a browser with tail recursion support for the larger results. Edit: Saved 1 byte thanks to @Arnauld.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
[NI«ÐIÖsSOIQ*#
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2s/z0OrDEzwPTysO9vcM1FL@/9/EAAA "05AB1E – Try It Online")
**Explanation**
Solutions requiring large prefixes will time out on TIO
```
[ # start a loop
NI« # append input to current iteration number
Ð # triplicate
IÖ # is the first copy evenly divisible by input?
sSOIQ # is the digit sum of the second copy equal to the input?
* # multiply
# # if true, break loop
# output the third copy
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) v2, ~~12~~ 10 bytes
```
a₁.;A×?≜ẹ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf96htw6Omxoe7Ov8nAmk9a8fD0@0fdc55uGun9v//hpYA "Brachylog – Try It Online")
This is a function submission that takes input via `.` and produces output via `?` (the opposite of the normal convention; all Brachylog functions have exactly two arguments, which can be input or output arguments, but the language doesn't enforce any particular argument usage). We [don't normally consider conventions for argument usage to be relevant at PPCG](https://codegolf.meta.stackexchange.com/a/11909).
## Explanation
A previous version of this solution had a special case (`Ḋ|`, i.e. "return digits literally") for single digits, but the question apparently states that you don't have to check for that (thanks @DLosc for catching this), so I removed it. (The solution as written won't work on single digits as Brachylog won't consider 1 as a possibility for an unknown in a multiplication, to prevent infinite loops; its multiplications are arbitrary-arity.)
So this answer now goes for a pretty much direct translation of the specification. Starting with `?` (the output / number we're trying to find; a Brachylog predicate always implicitly starts with `?`) we use `a₁.` to assert that it has `.` (the input) as a suffix. Then `;A×?` means that we can multiply (`×`) the result by something (`;A`) to produce `?` (the output). Finally, `ẹ+` sums (`+`) the digits (`ẹ`) of `?`, and there's by default an implicit assertion at the end of every Brachylog program that the final result produces `.`. So in other words, this program is "`.` is a suffix of `?`, `.` multiplied by something is `?`, `.` is the digit sum of `?`", which is very close to a literal translation of the original program.
The `≜` is necessary for the digit sum requirement to be enforced. I assume something about `ẹ` doesn't like unknowns, so the `≜` tells Brachylog to use a brute-force approach for that part of the program rather than algebra.
[Answer]
# [Haskell](https://www.haskell.org/), 72 bytes
```
f n=[x|x<-[n,n+lcm n(10^length(show n))..],sum[read[j]|j<-show x]==n]!!0
```
[Try it online!](https://tio.run/##HclBDoMgEADAr6xJDxCUoOlRntAXbLYJabFoYTViUw7@nSad6wSX3z7GWidgi@UsY4fcsoqPBCx6c4@eX0cQOaxfYCm1pjZ/Eu7ePXGhcxm7fxWylqlpTE1uZrCQ3HYDse0zH6BhknAB7AetB0OgFODVUP0B "Haskell – Try It Online")
Note that the found number minus n must be a multiple of both n and 10^length(n).
Inspired by Laikoni and totallyhuman
[Answer]
## [Alice](https://github.com/m-ender/alice), 35 bytes
```
/o
\i@/!w?+.?~\ & /-$K..?\ L z $ /K
```
[Try it online!](https://tio.run/##S8zJTE79/18/nysm00FfsdxeW8@@LkZBTUFfV8VbT88@RsFHoUpBRUHf@/9/Q0sA "Alice – Try It Online")
### Explanation
This program has a really nice mix and interaction between Cardinal (integer-processing) and Ordinal (string-processing) mode.
The usual framework for challenges with decimal I/O which operate largely in Cardinal mode:
```
/o
\i@/...
```
And the actual program:
```
! Store the input N on the tape.
We'll use an implicit zero on top of the stack as our iterator variable X,
which searches for the first valid result.
w Store the current IP position on the return address stack. This marks
the beginning of the main search loop. We can avoid the divisibility
test by going up in increments of N. To check the other two
conditions, we'll use individual conditional loop ends that skip to
the next iteration. Only if both checks pass and all loop ends are
skipped will the search terminate.
?+ Increment the iterator X by N.
. Duplicate X.
?~ Put a copy of N underneath.
\ Switch to Ordinal mode.
& Implicitly convert X to a string, then fold the next command over its
characters, i.e. its digits. Here, "fold" means that each character
is pushed to the stack in turn, followed by one execution of that
next command.
/ Switch back to Cardinal mode (this is not a command).
- Fold subtraction over the digits. This implicitly converts each
digit back to its numerical value and subtracts it from N. If the
digit sum of X is equal to N, this will result in 0.
$K Jump back to the w if the digit sum of X isn't N.
.. Duplicate X twice.
? Get a copy of N.
\ Switch to Ordinal mode.
L Shortest common superstring. Implicitly converts X and N to strings
and gives the shortest string that starts with X and ends with N.
This will be equal to X iff X already ends with N. Call this Y.
z Drop. If X contains Y, this deletes everything up to and including
Y from X. This can only happen if they are equal, i.e. if X ended
with N. Otherwise X remains unchanged.
$ Skip the next command if the string is empty, i.e. if X ended with N.
/ Switch back to Cardinal mode.
K Jump back to w if X didn't end with N.
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~136~~ ~~110~~ ~~103~~ 92 bytes
*-26 thanks to JollyJoker*
*-7 again thanks to JollyJoker*
*-11 thanks to Oliver Grégoire*
```
a->{for(int i=a;!(""+a).endsWith(""+i)|i!=(""+a).chars().map(x->x-48).sum();a+=i);return a;}
```
[Try it online!](https://tio.run/##hc7NbsIwDAfwe5/CcEqEGj5WGFNU3gAuHHaYdvDaMMzatEpSxMT67F3a9TpysWT7J/t/wSvGVa30Jf/qsgKthT2SvkcApJ0yJ8wUHPp2GIBifUUu/aSNfLEOHWVwAA0pdBjv7qfKDIhSlBM2nc6QC6Vz@0ru3LfEf2iSjovsjMYyLkqs2S3e3eJky4VtSsYlzlLi0ijXGA0o205GdfNR@Gfjz2tFOZQ@LTs6Q/rz7d0H@4t6/LZOlaJqnKj9yhWaaaHYcsWH5P@DpxBIQmAdApsQeA6BbQi8BMBqEQDJAObzR08W45E2artf "Java (OpenJDK 8) – Try It Online")
Gotta love Java! It could well be that I am using an inefficient approach, but not having a built in checksum function and the double conversion to String to check for the end of the number costs bytes...
Ungolfed:
```
a->{ //input n (as integer)
for (int i = a; //initiate loop
!("" + a).endsWith("" + i) //check if the calculated number ends with the input
| i != ("" + a).chars().map(x -> x - 48).sum(); //check if the checksum is equal to the input
a += i) //for every iteration, increase i by the input to save checking for divisibility
; //empty loop body, as everything is calculated in the header
return a; //return number
}
```
[Answer]
# Mathematica, 72 bytes
```
(t=#;While[Mod[t,10^IntegerLength@#]!=#||Tr@IntegerDigits@t!=#,t+=#];t)&
```
*-18 bytes from @MartinEnder*
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X6PEVtk6PCMzJzXaNz8lukTH0CDOM68kNT21yCc1L70kw0E5VtFWuaYmpMgBKu6SmZ5ZUuxQAhTWKdG2VY61LtFU@x9QlJlX4pAWbWgUywVnmyPYxgYItrlp7H8A "Wolfram Language (Mathematica) – Try It Online")
Here is another version from Martin Ender
This approach can go up to `n=40` (41 exceeds the default iteration limit)
# Mathematica, 65 bytes
```
#//.t_/;Mod[t,10^IntegerLength@#]!=#||Tr@IntegerDigits@t!=#:>t+#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfX68kXt/aNz8lukTH0CDOM68kNT21yCc1L70kw0E5VtFWuaYmpMgBKu6SmZ5ZUuxQAhS2sivRVlb7H1CUmVfikBZtYhD7HwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~20 19~~ 17 bytes
```
ḟȯ=⁰Σdfȯ€d⁰ṫdm*⁰N
```
Thanks @Zgarb for -2 bytes!
[Try it online!](https://tio.run/##yygtzv7//@GO@SfW2z5q3HBucUraifWPmtakADkPd65OydUCMvz@//9vaAQA "Husk – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
This solution assumes that `n <= sys.maxint`.
```
n=x=input()
while sum(map(int,str(x)))-n*str(x).endswith(`n`):x+=n
print x
```
**[Try it online!](https://tio.run/##JcpLCoAgEADQvadwOdMPql3gXQoSFHIadEQ7vQXt3uLxI@6mpTUy1XjiLICqOH9ZnXKAcDB4kiFJhIqII3U/J0tnKl4c7LTjVntDiuNXdW1tXl8 "Python 2 – Try It Online")**
[Answer]
# C (gcc) ~~71~~ 69 bytes , fails on 100
I tried with long and %1000 but times out
-2 bytes thanks to steadybox
```
s,i,j;f(n){for(j=0;s^n|j%100!=n;)for(s=0,i=j+=n;i;i/=10)s+=i%10;j=j;}
```
[Try it online](https://tio.run/##HY3LCsIwEEX38xW1EGloiplaXwzxS0QoKZUJOErjTuuvx8blPRzO9c3N@5SiYRNorES/x8dUBWcpXuUTFFq7ckI60@isYRfqZTPxxqHVsXa8OBRcoDnde5acgGzTN/pexqpUQ2nWoknDc2J5/UnRnAs1XKQ0YvKrJpgTtoBbwA5wB7gHPAAeAU/Q2gI6@wM)
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 90 84 83 + 18 = 101 bytes
```
using System.Linq;
n=>{for(int i=n;!(""+n).EndsWith(""+i)|n%i>0|(""+n).Sum(c=>c-48)!=i;n++);return n;}
```
[Try it online!](https://tio.run/##lVBNSwMxEL3nV0wXhIS1S1sKVtIsiOhJQeihB/EQ0mwN7E40yQrS9revs26x7dE5TGYm7735MHFsfLBdGx1uYfUdk22KJ4efkjHUjY0f2li4my5ubmdztmNAZmodI7wEvw26@a0M9d5i0skZ@PJuA8/aIY8pkPLrG@iwjeIPd2L0duz72KJZOkzXQK6EChRgW9fyAlupDlW5q3zghAKnUI54luUoigfcxLVL733qxB6vXDnZH/9WbcONKs14vhAj5STmuZDBpjYgoDx0tO9FFx9g0KchpjNJ71LBbEIBES@gZwvce4y@tsU6uGTpipZnx9PxDHLSyCETJNgnFXdCSPY/lfnkRKf4jH9ggz@w7gc "C# (.NET Core) – Try It Online")
* 6 bytes saved thanks to Emigna and my uncanny ability to write `(""+n)` in some places and `n.ToString()` in others.
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 16 bytes
```
£^›u³↔ξ³¥s}Σ³E*‽
```
[Try it online!](https://tio.run/##AScA2P9vaG0y///Co17igLp1wrPihpTOvsKzwqVzfc6jwrNFKuKAvf//MTM "Ohm v2 – Try It Online")
[Answer]
# JavaScript REPL (ES5), ~~60~~ 59 bytes
```
for(n=prompt(i=0);eval([].join.call(t=++i+n,'+'))-n|t%n;);t
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 12 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƘS=n$Ḋn$ø>&&
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNiU5OFMlM0RuJTI0JUUxJUI4JThBbiUyNCVDMyVCOCUzRSUyNiUyNiZmb290ZXI9JmlucHV0PTEyJTIwLSUzRSUyMDkxMiUwQTEzJTIwLSUzRSUyMDExNzEzJTBBMTQlMjAtJTNFJTIwNjMxNCUwQTE1JTIwLSUzRSUyMDkxNSUwQTE2JTIwLSUzRSUyMDM2MTYlMEExNyUyMC0lM0UlMjAxNTMxNyUwQTE4JTIwLSUzRSUyMDkxOCUwQTE5JTIwLSUzRSUyMDE3MTE5JTBBMjAlMjAtJTNFJTIwOTkyMCZmbGFncz1D)
#### Explanation
```
ƘS=n$Ḋn$ø>&& # Implicit input
Ƙ # First positive integer where:
S= # Digit sum equals input
n$ & # AND
Ḋ # Divisible by input
n$ & # AND
ø> # Ends with input
# Implicit output
```
[Answer]
# Julia, 70 bytes
```
f(x)=(n=x;while(sum(digits(n))!=x||x!=n%(10^length("$x")));n+=x;end;n)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 18 bytes
```
T!y%a&$+y=aY++i.ay
```
Algorithm inspired by [Emigna's answer](https://codegolf.stackexchange.com/a/149204/16766). [Try it online!](https://tio.run/##K8gs@O@mkKhgaKQQo6NgZKBQzaUQoJCoV6ynUf0/RLFSNVFNRbvSNjFSWztTL7Hyv0KtQqIml0KmgpWCAZdCpIKSElftfwA "Pip – Try It Online")
### How it works
```
a is 1st cmdline arg, i is 0, y is "" (implicit)
T Loop until
!y%a& y%a is 0 and
$+y=a sum of y is a:
++i Increment i
Y .a and yank (i concat a) into y
y After the loop exits, autoprint y
```
[Answer]
## Scala, 120 bytes
```
def a(n:Int)={val b=math.pow(10,math.ceil(math.log10(n))).##;var c=b+n;while(c%n!=0||(0/:c.toString)(_+_-'0')!=n)c+=b;c}
```
This works until `n = 70`, after which integers overflow. For one extra character, the `Int` can change to a `Long` and allow values for `n > 100` to be computed.
Here is the slightly longer ungolfed version:
```
def golfSourceLong(n: Long): Long = {
val delta = math.pow(10, math.ceil(math.log10(n))).toInt
var current = delta + n
while (current % n != 0 || current.toString.foldLeft(0)(_ + _ - '0') != n) {
current += delta
}
current
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
f=lambda n,x=0:x*(x%n<sum(map(int,`x`))==n==x%10**len(`n`))or f(n,x+n)
```
[Try it online!](https://tio.run/##DYtBCoAgEAC/0kVYrYN2K9q/aJQU6CpmsL3ePM4wk796JZpb8xhc3A830MSoV1bAgrbnjRBdhpvqZNlKiUiILIxWKpwElrpLZfDQt5Fky6WnHc0i2w8 "Python 2 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
è}╘⌐ƒw┴L≤⌂IÑ═eαü
```
[Run and debug it](https://staxlang.xyz/#p=8a7dd4a99f77c14cf37f49a5cd65e081&i=12)
[Answer]
# [Haskell](https://www.haskell.org/), 75 bytes
```
f n=[x|x<-[0,n..],sum[read[d]|d<-show x]==n,mod x(10^length(show n))==n]!!0
```
[Try it online!](https://tio.run/##PYtbCoMwFET/s4or9EPBSOI7YLoRsSCoVaqxqKWB2rXbmwjNz5yTmdvX66Mdx@PoQMlS77qgJfNVEFT@@prKpa2bsqn2pqBrP79BV1Iqf5ob0C5nt7FV9613baU8D7vKcdgx1YMCCc9lUBtcoIOYkQ8lPAR6BYEBhEeGOc8Q0GJjaYSJkpyzxHBqOEoxUTJ7k0QIaPk5yw0L22QcgYTMFgITSGyFCyFyRDNlzLb/hx@Efo8f "Haskell – Try It Online")
**Explanation:**
```
f n=[x| ]!!0 -- Given input n, take the first x
x<-[0,n..], -- which is a multiple of n,
sum[read[d]|d<-show x]==n, -- has a digital sum of n
mod x(10^length(show n))==n -- and ends in n.
```
I wonder whether the "ends in `n`" part can be shortened. I also tried `show n`elem`scanr(:)""(show x)`, but it's longer.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~65 63 54~~ 53 bytes
```
->n{a=n;a+=n until/#{n}$/=~a.to_s&&a.digits.sum==n;a}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtE2zzpR2zZPoTSvJDNHX7k6r1ZF37YuUa8kP75YTS1RLyUzPbOkWK@4NNcWpLT2f0FpSbFCWrShUSwXjGkOZxobwJkmBrH/AQ "Ruby – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~22~~ 21 bytes
```
fq2-/,%T^;l`QsjT;Q%TQ
```
**[Try it here!](https://pyth.herokuapp.com/?code=fq2-%2F%2C%25T%5E%3Bl%60QsjT%3BQ%25TQ&input=13&debug=0)**
[Answer]
# [Haskell](https://www.haskell.org/), 75 bytes
```
f n=[i|i<-[n,n+10^length(show$n)..],i`mod`n<1,sum[read[j]|j<-show$i]==n]!!0
```
[Try it online!](https://tio.run/##HcpBDoMgEADAr6yJBw1IwPQIT/AFGxpJxIKF1YhNL/6dJp3zBFfePqVaVyCD8Y56QOLElHwmT68rdCXs35Z6ISyPc96XmbTi5ZPx9G7Bzd6bHv4nWmPINo2s2UUCA9kdE3THGekCAWsPLaAahRilBcYAH9LWHw "Haskell – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 84 bytes
```
for($n=$i=$args[0];$i%$n-or$i-notmatch"$n$"-or([char[]]"$i"-join'+'|iex)-$n){$i++}$i
```
[Try it online!](https://tio.run/##DchBCoMwEAXQu4RfVEKggrviSUIWQWIzojNlFCy0PfvUt3wvOYvutayr2SzagkfQiKzPPd7TA3QDB1FQYDm2fEzVgeGuauNUs8aUHMiFRYgb33ypvLsA7j4g738gM@uHPw "PowerShell – Try It Online")
Simple construction but lengthy commands. Times out on TIO for `n=100`, but if we explicitly set `i` to be close, [it outputs correctly.](https://tio.run/##RchBCoMwEAXQu4RfVEIgXQbxJCGLIGkzxc6UKFhoe/bRXd/yvWQvba1lWVRBU/jzIYw3aT14Qm73Nfo0gi5gJw3kWLZn3uZqwDBn9XGuucWUDMi4hxB3tvtSeQ8OPHxA1v5Aqnr1/gA "PowerShell – Try It Online")
This is just a simple `for` loop that keeps going so long as any one of the conditions is true. The three conditions are 1) `$i%$n`, i.e., we have a remainder; 2) `$i-notmatch"$n$"`, i.e., it doesn't regex match the last couple of digits; and 3) `([char[]]"$i"-join'+'|iex)-$n`, i.e., the digits summed together is not equal to `$n` (here checked by simple subtraction, since nonzero values are truthy). Inside the loop we're simply incrementing `$i`.
Thus, if we don't have a remainder, the regex matches, and the numbers are equal, all three conditions are `$false` and we exit the loop. As a result, we just can leave `$i` on the pipeline, and output is implicit.
[Answer]
# PHP, 73+1 bytes
```
while(array_sum(str_split($i+=$n=$argn))-$n|$i%10**strlen($n)-$n);echo$i;
```
Run as pipe with `-R`.
loops `$i` through multiples of `<input>` until `sum_of_digits-<input>` and `tail_of_i-$n` are falsy;
then prints `i`.
[Answer]
# m4, 210 bytes
```
define(d,define)d(i,ifelse)d(s,`i($1,,0,`eval(substr($1,0,1)+s(substr($1,1)))')')d(k,`r($1,eval($2+1))')d(r,`i(s($2),$1,i(regexp($2,$1$),-1,`k($1,$2)',i(eval($2%$1),0,$2,`k($1,$2)')),`k($1,$2)')')d(f,`r($1,1)')
```
Defines a macro `f` which computes the answer. It's a bit slow—unusably so—but I promise it works.
I thought m4 would be nice because it treats integers as strings by default, but this is pretty bad.
[Answer]
# [R](https://www.r-project.org/), 115 bytes
```
function(n,d=nchar(n):1){while(sum(D<-F%/%10^((k=nchar(F)):1-1)%%10)-n|any(D[k-d+1]-n%/%10^(d-1)%%10)|F%%n)F=F+n
F}
```
[Try it online!](https://tio.run/##NcrBCoJAEAbgu0/hZWAGHXKhU@hN5iWiQFwXxfoFSyKyZ9882PXjm2NIS41hQfscJjByX6Htm5khJyefVz/cOn4sd65LNTqQK67M435MtqROaGNRrA3eXJ9H9Zm7KPbt/2E1IohVliGxbwx8LCT@AA "R – Try It Online")
Terrible R function. Increments `F` (starts at `0`) by `n` until a value is found that satisfies the required properties, which it then returns. The use of `any` on a `double` expression sends out a warning for each iteration of the loop, but does not affect the correctness.
Times out on TIO for large enough inputs (n=55 or higher) but should correctly compute the solution given enough time/space.
[Answer]
# Perl 5, ~~46~~ 44 + 1 ( -p ) = 45 bytes
2 bytes saved thanks to Xcali, couldn't find better
```
($\=++$t.$_)%$_|$_-eval$\=~s//+/gr.0&&redo}{
```
first answer
```
$\=++$x.$_;eval$\=~s//+/gr."-$_"|$\%$_&&redo}{
```
[Try it online](https://tio.run/##K0gtyjH9/19DJcZWW1ulRE8lXlNVJb5GJV43tSwxByhaV6yvr62fXqRnoKZWlJqSX1v9/7@h8b/8gpLM/Lzi/7oFAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 21 bytes
```
DS=³a³ḍaDṫ³DLC¤Ḍ=³ø1#
```
[Try it online!](https://tio.run/##y0rNyan8/98l2PbQ5sRDmx/u6E10ebhz9aHNLj7Oh5Y83NEDFD@8w1D5////hkYA "Jelly – Try It Online")
Edit: compressed to a single line
**Explanation**
```
DS=³a³ḍaDṫ³DLC¤Ḍ=³ø1#
ø1# Evaluate the condition before this and increment a counter until it is met then output the counter
D Digits of incremented variable as a list
S Sum
=³ Equals argument of program?
a Logical and
³ḍ Does arg divide incremented variable?
a Logical and
Dṫ Ḍ Last n digits of inc. var. where n is number of digits in program input
³DLC 1 - (number of digits of program input)
¤ Book ends above nilad
=³ Equals program input?
```
This took me many hours to write because I'm learning Jelly but now that I'm done I'm so satisfied. For a long time I didn't realize I needed the `¤` and I just couldn't get it to work. Looking at [this][1] well explained code helped me seal the deal. Lots of other Jelly answers in PPCG guided me too.
] |
[Question]
[
# Church booleans
A [Church boolean](https://en.wikipedia.org/wiki/Church_encoding#Church_Booleans) is a function that returns `x` for true and `y` for false where `x` is the first argument to the function and `y` is the second argument to the function. Further functions can be composed from these functions which represent the `and` `not` `or` `xor` and `implies` logical operations.
# Challenge
Construct the Church booleans and `and` `not` `or` `xor` and `implies` Church gates in a language of your choice. `and` `or` and `xor` should take in two functions (representing Church booleans) and return a function (representing another Church boolean). Likewise, `not` should invert the function it takes and the `implies` gate should perform boolean implies logic where the first argument `implies` the second.
# Scoring
The total length of all of the code required to make Church `true` and `false` in your language and the `and` `not` `or` `xor` and `implies` Church gates excluding the function's name. (for example, `false=lambda x,y:y` in Python would be 13 bytes). You can reuse these names later in your code with them counting 1 byte toward the byte total of that gate.
# Pseudo code Examples:
The functions you create should be able to be called later in your code like so.
```
true(x, y) -> x
false(x, y) -> y
and(true, true)(x, y) -> x
and(true, false)(x, y) -> y
# ... etc
```
[Answer]
# [Haskell](https://www.haskell.org/), 50 - 6 = 44 bytes
*-1 byte thanks to Khuldraeseth na'Barya, and -1 byte thanks to Christian Sievers.*
```
t=const
f=n t
n=flip
a=n n f
o=($t)
x=(n>>=)
i=o.n
```
[Try it online!](https://tio.run/##bcwxDsIwDIXh3afw0KFdEBzAvUsEWFgEu6IZcvtQKiFV5I3v6df3SOvznnNrRa7hayEV50Iumm2htA1npZBxKBNVGX2eZSKTOHl7JXO5BRHz8jYvPHDhC58PW/d9OLxLvI/SFv1n30@7T0GnPRgADAAGAAOBFYAVgBWAFYEGQAOgAdB@YPsA "Haskell – Try It Online")
[Answer]
# [Binary Lambda Calculus](https://tromp.github.io/cl/cl.html), 13.875 12.875 bytes (103 bits)
Binary Lambda Calculus Language (BLC) by John Tromp is basically an efficient serialization format for lambda calculus. It is a great fit for this task, as Church notation is even the "idiomatic" way to work with booleans in BLC.
I used the following lambda functions for the combinators, some of which I copied and golfed from the Haskell answer:, which were found by an exhaustive search with a proof limit of 20 β-reductions for each case. There is a good chance these are shortest possible.
```
True: (\a \b a)
False: (\a \b b)
Not: (\a \b \c a c b)
And: (\a \b b a b)
Or: (\a a a)
Xor: (\a \b b (a (\c \d d) b) a)
Impl: (\a \b a b (\c \d c))
```
These translate to the following (binary) BLC code sequences:
```
bits | name | BLC
------+-------+---------
7 | True | 0000 110
6 | False | 0000 10
19 | Not | 0000 0001 0111 1010 110
15 | And | 0000 0101 1011 010
8 | Or | 0001 1010
28 | Xor | 0000 0101 1001 0111 0000 0101 0110
20 | Impl | 0000 0101 1101 0000 0110
```
Functions above are in total 111 bits long (13.875 bytes) 103 bits long (12.875 bytes). They don't need to be aligned to byte boundaries to be used inside a program, so it makes sense to count fractional bytes.
There is no code re-use between the combinators, because there are no variables/references/names in BLC - everything had to be copied over. Still, the efficiency of the encoding makes for quite a terse representation.
[Answer]
# [Python 2](https://docs.python.org/2/), (-3?) ~~ 101 ~~ 95 bytes
[David Beazley](https://www.youtube.com/watch?v=pkCLMl0e_0k "YouTube: Lambda Calculus from the Ground Up - PyCon 2019") eat your heart out!
-6 thanks to Chas Brown (moved the repeated `:` into the join text >.<)
```
exec'=lambda x,y=0:'.join('F y;T x;N x(F,T);A x(y,F);O x(T,y);X x(N(y),y);I O(y,N(x))'.split())
```
**[Try it online!](https://tio.run/##lZExb4MwEIV3fsVt51OtKOkIYsiClAUWhgyVIpqahAoMoiTCv56eQ5zWTdSqN51833vPZ3dmOLb6eZrUqPYY10Xz@lbAKE28DHHx3lZaYAImymGMUhhFInOK1twYmVCUcZNLQ9GWm1QYsv0GMp6mYiTCxUdXV4Mgmsq2B100CioNbIkSMEcKA@AqT3oPMahzUQvL0OW06ys9zJonwJAVlhMruSQWv2gMghnBNMTA@hf94dQoPexcECY5zhFu5GI89HueN5CQ3ki6JLtIDvc3Wmfbzf/2mVE2qVU57H65uy2Pcd73QroJrHFfHY5/OtvyQWf/QE6ebN7o/hbyUfL1@zz6J3h94y9vfufpEw "Python 2 – Try It Online")**
I think it might be `95 - 3` because I don't reuse the functions `A`, `X`, or `I`, but I use a single `=` for assignment (in front of `lambda`). Maybe I cant remove any; maybe I even get to remove 3.5?
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~92~~ ~~86~~ 83 - 7 = 76 bytes
```
t=p=>q=>p
f=t(q=>q)
n=p=>p(f)(t)
a=p=>n(p)(f)
o=p=>p(t)
x=p=>p(n)(f())
i=p=>n(p)(t)
```
[Try it online!](https://tio.run/##hY3RDoIwDEXf9xXEpzVRP0Ay/mUq1RmyDpi6v8cCESgh4aW57b2352U/tr01LsSTp3vZddEEU9SmCApN1CxqUL6/BY2gIyjbL14H4F3R6PA5jcrzWQMoN6UidO2TvuZqihv5lqryXNFDX3Vs3iWnbdWWXFh6h3iAXPUtbufSwsnCteUvWcyzOeC5PWuEdd5y/thXeCIXB81z/mD5w@LJsOJiRekibFBol0KSQpJCkkLblLRLSZKSJCVJStqmuF2KkxQnKU5S3J/S/QA "JavaScript (Node.js) – Try It Online") Link includes basic test cases. Edit: Saved ~~6~~ 9 bytes thanks to @tsh.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~133 - 6 = 127~~ 94 bytes
```
exec"t!u;f!v;n!u(f,t);a!u(v,f);o!u(t,v);x!u(n(v),v);i!o(v,n(u))".replace('!','=lambda u,v=0:')
```
[Try it online!](https://tio.run/##dc5BDsIgEAXQvaco3cAkxFSXkh4GKxNJKpAGCJ4eaXRRHbv78/l5ITzj3btzraaYqY8sKWRZOZYEyghKt5AlgvItRJlBlRacyLBmy3x7dSIB9MfFhFlPRnDGJR9n/bjedJdkHocLhxoW62IXxUkOcHgfuDk@lRMRthMnEOhKt59879YGfxokG5T/NE80TzRPNL@jFaIVohWilR3NEs0SzRLNEq2@AA "Python 2 – Try It Online")
Shamelessly stealing the sneaky idea behind [Jonathan Allan's](https://codegolf.stackexchange.com/a/190361/69880) answer; no bytes deducted though.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 61-7=54 bytes
```
t=#&
f=#2&
a=#2~#~f&
o=t~#~#2&
n=f~#~t&
x=n@#~#2~#&
i=#2~#~t&
```
[Try it online!](https://tio.run/##VcyxCsMgEAbg3aeQBJwc2o4BoUufQhwkreQGvVJuEEp9daOEJpfluPvv54uellf0BLOvlcyoRDDjTQnfZhlLUAINtaVnyYS2kRLZpHuPSqvDViRVH/OC9utt0MHZq744LftBx0H8Q//PT8vBp@ckByc2A7mB3EBu4NnAzyQPI3MjcyNzI5@N3JHdAG4AN4AbcDYgvpmR7N5LlrUSUm/VFQ "Wolfram Language (Mathematica) – Try It Online")
un-golfed: inspired by [Wikipedia](https://en.wikipedia.org/wiki/Church_encoding#Church_Booleans),
```
t[x_, y_] := x
f[x_, y_] := y
and[x_, y_] := x[y, f]
or[x_, y_] := x[t, y]
not[x_] := x[f, t]
xor[x_, y_] := y[not[x], x]
imply[x_, y_] := x[y, t]
```
[Answer]
# [Underload](https://github.com/catseye/stringie), ~~56~~ 52 bytes
```
(~!)(!)((~)~*):((!)~^)*(:^)(~(!)~^(~)~*)(()~(~)~^~*)
```
[Try it online!](https://tio.run/##zZK9CsMgEMd3n8JuZ6DQdvQ1sguCtgSsFpNAp3t1m1y0ZGjqqpv@P@6HOntjowvapAR4Evy74HLW8cGnOFspesYkB37XbrQCgU4Fqh7YKsE@V4LkrSYBBXYlDVdK@jCV3EKE6ld8ETkciVu3BDKIbuu@Ubf2Zt9dH/DXQeIxR@mokYJU@QoyZYgNQiIZ8oNl0OH5coMdG6SFdc6yp9@Vad8N3mtKHw "Underload – Try It Online") (includes a testsuite and text identifying parts of the program)
This scores surprisingly well for a very low-level esolang. (Church numerals, Church booleans, etc. are very commonly used in Underload for this reason; the language doesn't have numbers and booleans built in, and this is one of the easier ways to simulate them. That said, it's also common to encode booleans as the Church numerals 0 and 1.)
For anyone who's confused: Underload lets you define reusable functions, but doesn't let you name them in the normal way, they just sort of float around on the argument stack (so if you define five functions and then want to call the first one you defined, you need to write a new function that takes five arguments and calls the fifth of them, then call it with insufficiently many arguments so that it looks for spare arguments to use). Calling them destroys them by default but you can modify the call to make it non-destructive (in simple cases, you just need to add a colon to the call, although the complex cases are more common because you need to make sure that the copies on the stack don't get in your way), so Underload's function support has all the requirements we'd need from the question.
## Explanation
### true
```
(~!)
( ) Define function:
~ Swap arguments
! Delete new first argument (original second argument)
```
This one's fairly straightforward; we get rid of the argument we don't want and the argument we do want just stays there, serving as the return value.
### false
```
(!)
( ) Define function:
! Delete first argument
```
This one's even more straightforward.
### not
```
((~)~*)
( ) Define function:
~* Modify first argument by pre-composing it with:
(~) Swap arguments
```
This one's fun: `not` doesn't call its argument at all, it just uses a function composition. This is a common trick in Underload, in which you don't inspect your data at all, you just change how it functions by pre- and post-composing things with it. In this case, we modify the function to swap its arguments before running, which clearly negates a Church numeral.
### and
```
:((!)~^)*
( ) Define function:
~^ Execute its first argument with:
(!) false
{and implicitly, our second argument}
* Edit the newly defined function by pre-composing it with:
: {the most recently defined function}, without destroying it
```
The question permits defining functions in terms of other functions. We define "and" next because the more recently "not" has been defined, the easier it is to use it. (This doesn't subtract from our score, because we aren't naming "not" at all, but it saves bytes over writing the definition out again. This is the only time that one function refers to another, because referring to any function but the most recently defined would cost too many bytes.)
The definition here is `and x y = (not x) false y`. In other words, if `not x`, then we return `false`; otherwise, we return `y`.
### or
```
(:^)
( ) Define function:
: Copy the first argument
^ Execute the copy, with arguments
{implicitly, the original first argument}
{and implicitly, our second argument}
```
@Nitrodon pointed out in the comments that `or x y = x x y` is normally shorter than `or x y = x true y`, and that turns out to be correct in Underload as well. A naive implementation of that would be `(:~^)`, but we can golf off an additional byte by noting that it doesn't matter whether we run the original first argument or the copy of it, the result is the same either way.
Underload doesn't actually support currying in the usual sense, but definitions like this make it look like it does! (The trick is that non-consumed arguments just stick around, so the function you call will interpret them as its own arguments.)
### implies
```
(~(!)~^(~)~*)
( ) Define function:
~ Swap arguments
~^ Execute the new first (original second) argument, with argument:
(!) false
{and implicitly, our second argument}
(~)~* Run "not" on the result
```
The definition used here is `implies x y = not (y false x)`. If y is true, this simplifies to `not false`, i.e. `true`. If y is false, this simplifies to `not x`, thus giving us the truth table we want.
In this case, we're using `not` again, this time by rewriting its code rather than referencing it. It's just written directly as `(~)~*` without parentheses around it, so it gets called rather than defined.
### xor
```
(()~(~)~^~*)
( ) Define function:
~ ~^ Execute the first argument, with arguments:
(~) "swap arguments"
() identity function
~* Precompose the second argument with {the result}
```
This time, we're evaluating only one of our two arguments, and using it to determine what to compose onto the second argument. Underload lets you play fast and loose with arity, so we're using the first argument to choose between two two-argument two-return functions; the argument swap that returns them both but in the opposite order, and the identity function that returns them both in the same order.
When the first argument is true, we therefore produce an edited version of the second argument that swaps its arguments before running, i.e. precompose with "swap arguments", i.e. `not`. So a true first argument means we return `not` the second argument. On the other hand, a false first argument means we compose with the identity function, i.e. do nothing. The result is an implementation of `xor`.
[Answer]
# [J](http://jsoftware.com/), 67 bytes - 7 = 60
```
t=.[
f=.]
n=.~
a=.2 :'u v]'
o=.2 :'[u v'
x=.2 :'u~v u'
i=.2 :'v u['
```
[Try it online!](https://tio.run/##fZC9DsMgDIR3P4U3JwtDx0q8QaesKENU1QodwkIiprw6jaBJ84O7IHzH8R28Y/RaGWCtWhi0mqHT6oZ3GnFqCVwezDIRhK8zTzgS2Dwte0Px9ewd0oNQp9UjNQRZbFaRk3hWK49DvTu@3VHxalwcjx36usRIFpctllP8SxVg7hg7WiyVdzLMnWD7@kGGBRkWZFj48zIrf6OVYVaqyFsqfgA "J – Try It Online")
Worth noting:
Higher order functions work differently in J than in a functional language. To create a new verb from 1 or 2 existing verbs, you need to use either an adverb (in the case of 1) or a conjunction (in the case of 2).
Syntactically, adverbs come after a verb, and conjunctions go between them. Thus to "not" a verb `f` you do `f n`, and to "and" verbs `f` and `g`, you `f a g`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 82 - 4 = 78 bytes
```
f,t,a,n,i,o,x=%w(y:y x:x f:y t:f t:y y:t y:n[y]).map{|s|eval"->x,y=0{x==f ?#{s}}"}
```
[Try it online!](https://tio.run/##VYjBCgIxDETvfkVYERSirNdC9UNCDxUMCNotblcTuv32WhEFD29m3tynk9bKmNBjwAsOKHb1XKtRECPArZPhhoKa1AikbrO7@ZjncT4//LXbHgTV9lmsZTgu81hKV2oEph73bhHBU0J2Xxv@LFD6baFA7PAdn6@@AA "Ruby – Try It Online")
[Answer]
# Java 8, score: ~~360~~ ~~358~~ ~~319~~ ~~271~~ 233 (240-7) bytes
```
interface J<O>{O f(O x,O y,J...j);}J t=(x,y,j)->x;J f=(x,y,j)->y;J n=(x,y,j)->j[0].f(y,x);J a=(x,y,j)->j[0].f(j[1].f(x,y),y);J o=(x,y,j)->j[0].f(x,j[1].f(x,y));J x=(x,y,j)->j[0].f(j[1].f(y,x),j[1].f(x,y));J i=(x,y,j)->j[0].f(j[1].f(x,y),x);
```
~~This was trickier to accomplish than I thought when I started it.. Especially the `implies`. Anyway, it works.. Can probably be golfed a bit here and there.~~ EDIT: Ok, not re-using functions but just duplicating the same approach is a lot cheaper in terms of byte-count for Java.. And I get the full -7 bonus for not using any of the functions as well.
[Try it online.](https://tio.run/##rZBBa4MwGIbv/RUfngyk2Xada6E7DCZsHrrDoPSQtcmI00Q0dhHxt7vYS7eJ2pSGQPySx3zvk5ge6Dzef7W7hBYFvFAh61ZIzXJOdwzCh2hZR8D9CAyOoMIhISRGQROCXvgGVzhG86UJQuCnsrKlPJXx5nZLuF9hg@wB7R3Em7tusbvITouoHmLwL6hDzNAtXZf/sBhtaVO1AFn5kYgdFJpquxyU2ENq38Jf61zIz80WKKpnYEf3QpAuJPs@fvooOG6vq0KzlKhSk8z@oRPpe295yW6eaFKwe/CGuZRom8Vbedh79NAYx8/iRhK9Kj0RRZ5aYBsMnc/yyyKt5H4iEv0baTJWn@cOPHe8n1@uHuUT5srRXDmaK0dzdS3zdzWlbhzVjaO6cVQ311J/TrNEsGJCXzjqC0d94agvhvSbWdP@AA)
**Explanation:**
```
// Create an interface J to create lambdas with 2 Object and 0 or more amount of optional
// (varargs) J lambda-interfaces, which returns an Object:
interface J<O>{O f(O x,O y,J...j);}
// True: with parameters `x` and `y`, always return `x`
J t=(x,y,j)->x;
// False: with parameters `x` and `y`, always return `y`
J f=(x,y,j)->y;
// Not: with parameters `x`, `y`, and `j` (either `t` or `f`), return: j(y, x)
J n=(x,y,j)->j[0].f(y,x);
// And: with parameters `x`, `y`, and two times `j` (either `t` or `f`), return:
// j1(j2(x,y), y);
J a=(x,y,j)->j[0].f(j[1].f(x,y),y);
// Or: with parameters `x`, `y`, and two times `j` (either `t` or `f`), return:
// j1(x, j2(x,y))
J o=(x,y,j)->j[0].f(x,j[1].f(x,y));
// Xor: with parameters `x`, `y`, and two times `j` (either `t` or `f`), return:
// j1(j2(y,x), j2(x,y))
J x=(x,y,j)->j[0].f(j[1].f(y,x),j[1].f(x,y));
// Implies: with parameters `x`, `y`, and two times `j` (either `t` or `f`), return:
// j1(j2(x,y), x)
J i=(x,y,j)->j[0].f(j[1].f(x,y),x);
```
[Answer]
# C++17, ~~207−49=158~~ 195 − 58 = 137 bytes
The linebreaks are unnecessary (other than the first two).
```
#define A auto
#define D(v,p)A v=[](A x,A y){return p;};
D(true_,x)
D(false_,y)
A not_=[](A f){return f(false_,true_);};
D(and_,x(y,false_))
D(or_,x(true_,y))
D(xor_,x(not_(y),y))
D(implies,x(y,true_))
```
[Try it online!](https://tio.run/##nZOxboMwEIZ3nuKkDtgKGTp1QAxIjJlYqwpZYCJLxFjYREZRXr3UYGjahKaGDZ//784fhlyIfV4Rfuz7l4KWjFOIgbSq9uZlgs6BwDGco/cPFIMOYujwpaGqbTiI8Bp6CVJNS7NA4wSVpJLmsTMAr1VmmfI7X86BkcCGThDhhWFRF9gtbLrUzVCxXbuhoG1laIk6bGvsJCpG5YjadriXiiiWZ0RK2ijkH3yIIhg3h0UAfupjHHp3sXSM2fG/csvB8RR24rOuh1t4Mnva28aHlzGJw/8j0gdmadLf0HQZ6ybNkLuUuTx3pwfEQenGrDX6ybgIWUpvMNJblPQWJ71Wys6a/qe1X98d5qw2c@52y9yiIOMKToRxhOFy7T/zsiJH2e@lKqJ8t3t9@wI)
Unit-tested with assertions such as:
```
static_assert('L' == true_('L', 'R'));
static_assert('R' == not_(true_)('L', 'R'));
static_assert('L' == and_(true_, true_)('L', 'R'));
static_assert('L' == or_(true_, true_)('L', 'R'));
static_assert('R' == xor_(true_, true_)('L', 'R'));
static_assert('L' == implies(true_, true_)('L', 'R'));
```
UPDATED: formerly I'd had
```
A not_=[](A f){return[f](A x,A y){return f(y,x);};};
```
but [Roman's answer](https://codegolf.stackexchange.com/a/190398/11791) pointed the way to the shorter version. Notice that now `not_(std::plus<>)` is ill-formed, where formerly it was equivalent to `std::plus<>`; but since `std::plus<>` doesn't "represent a Church boolean," I think either behavior is okay by the rules.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 133 bytes - 7 = 126 122
```
: j execute ;
: t drop ;
: f nip ;
: n ['] f ['] t rot j ;
: a dup j ;
: o over j ;
: x 2dup a n -rot o a ;
: m over n -rot a o ;
```
[Try it online!](https://tio.run/##hY/NDsIgEITvPsXcsEm9eNRHUQ/Egta0bIPUtE9flz@jtlEOMAzf7C6arLtuLtof07TDDWpQ594p7Fc7OFSWuiA1TB2VwUGc@O53B0uOQ96XqPouaQI9lE2XAVv/Ijm58Tix9H4boeRK9vc8gXpNoNra4WyZFQPEyM2yE9YRzvZqPZQYi0Tob0LL5v6JCC5juAkyYsitfaFihgmuRxE9gmygylhyGZYZlqb6T5vIv9N@lphYjrS5Qd12Ta3uv5rokJolAlvi7cfTEw "Forth (gforth) – Try It Online")
-4 bytes thanks to Quuxplusone
Initially I significantly overthought this, considering things like macros and literals, but then I realized that if I define things in terms of true and false (like I should have done in the first place), it gets much simpler.
### Code explanation
```
\ Helper function to save some bytes
: j \ define a new word
execute \ execute the word at the provided address
; \ end word definition
\ True
: t \ define a new word
drop \ drop the second argument
; \ end the word
\ False
: f \ define a new word
nip \ drop the first argument
; \ end the word
\ Not - The "hardest" one because we have to reference true and false directly
: n \ define a new word
['] f \ get address of false
['] t \ get the address of true
rot \ stick the input boolean back on the top of the stack
j \ call the input boolean, which will select the boolean to return
; \ end the word
\ And
: a \ define a new word
dup \ duplicate the 2nd input value
j \ call the 2nd input on the first and second input
; \ end the word
\ Or
: o \ define a new word
over \ duplicate the 1st input value
j \ call the 1st input on the first and second input
; \ end the word
\ Xor
: x \ define a new word
2dup \ duplicate both of the inputs
a n \ call and, then not the result (nand)
-rot \ move the result behind the copied inputs
o a \ call or on the original inputs, then call and on the two results
; \ end the word
\ Implies
: m \ define a new word
over \ duplicate the 1st input value
n \ call not on the 1st input value
-rot \ move results below inputs
a o \ call and on the two inputs, then call or on the two results
; \ end the word
```
[Answer]
## SKI-calculus + C combinator, ~~36~~ 33 bytes
```
true=K
false=SK
not=C
and=SCI
or=SII
xor=C(CIC)I
implies=CCK
```
I don't actually know of any interpreter that allows you to define additional combinators in terms of previous ones, so I had to test this using <http://ski.aditsu.net/> by pasting in the desired combinators e.g. `CCKK(SK)pq` outputs `q`, showing that `K` does not imply `SK`.
Edit: Saved 3 bytes thanks to @Bubbler.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 47 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Based on [Jonah's J solution](https://codegolf.stackexchange.com/a/190379/43319).
`true` and `false` are infix functions, `not` is a suffix operator, and the rest are infix operators.
```
true←⊣
false←⊢
and←{⍺(⍶⍹false)⍵}
not‚Üê‚ç®
or←{⍺(true⍶⍹)⍵}
xor‚Üê{‚ç∫(‚ç∂not‚çπ‚ç∂)‚çµ}
implies‚Üê{‚ç∫(‚çπ‚ç∂true)‚çµ}
```
As per OP, this counts everything from and including `‚Üê` to the end of each line, and counts each call a previous definition as a single byte.
[Try it online!](https://tio.run/##dZFNDsIgEIX3nKI7dNELeBuS1oSkLQ2tCWrcujAh8Qy68QKa1ONwEHGA/gDibnjvm/cmgbRVXhwIrYnWPd@V6nxVlzvakqpz8w2RpoDpqOR7peRLycGaayWfJ9Sw3lDygRifIBtjQceIxQLZbMgBBmfSuq1o2S2AsUyCtbXGZs7ghMy2bjDCAmdWxHv3sIZ7AecTZi1Aw7Ao4YdeZA@H@/0KeEb8rDDug4wnTgExdUnMzqoPh/EimS/@FIh0Q4SPf@PXjFKianJSdcmt0JrXPqztKWs6nXdf "APL (dzaima/APL) – Try It Online")
true and false are the left and right identity functions.
`not` simply swaps the arguments of its operand function.
The rest implement the decision tree:
`and` uses the righthand function `‚çπ` to select the result of the lefthand function `‚ç∂` if true, else the result of the `false` function.
`or` uses the lefthand function `‚ç∂` to select the `true` if true, else the result of the righthand function `‚çπ`.
`xor` uses the righthand function `‚çπ` to select the the negated result of the lefthand function `‚ç∂not` if true, else the result of the lefthand function.
`implies` uses the lefthand function `‚ç∂` to select the result of the righthand function `‚çπ` if true, else the result of the `true` function.
[Answer]
# [Julia 1.0](http://julialang.org/), 36 bytes
```
(b::Bool)(x,y)=b ? x : y;i(x,y)=!x|y
```
I don't know if that counts, I'm actually just overloading the native `Bool` type to be callable, so I get most of the logic gates for free. Unfortunately, Julia doesn't have an `implies` gate, so I had to write my own function.
[Try it online!](https://tio.run/##yyrNyUw0rPj/XyPJysopPz9HU6NCp1LTNknBXqFCwUqh0joTIqBYUVP5v6AoM68kJ0@jpKg0VcOqQkfBqlJTkwsmmpaYU4xFWEMRpFwTiwRIXKFGAawPp7waQXlFXAoywSp0cEuDZXRQnfcfAA "Julia 1.0 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~120~~ ~~106~~ ~~102~~ 101 bytes
*-1 byte thanks to Jo King*
```
my (\t,\f,&n,&a,&o,&i,&x)={@_[0]},{@_[1]},|<f,t &^v,f t,&^v &^v,t n(&^v),&v>>>.&{"&\{\&^u($_)}".EVAL}
```
[Try it online!](https://tio.run/##bY/NasMwEITP1lMsxmxk2Jr20kN@THJoTj2GXqommDQLhkQKjhocFD@7K9kkNSWnmZ2P0aDjrtq/tu3hAlJZUkyoCQtCQ1gS1unMzTefz18NBX3xep0yWcD1mRgsee28BS29poTnPM8zdDEqp3D9I5NN2sTZ28fivQkryWoJM7hOV7DMJ0KcigvEdgwObCY9S6GJJ33KIeX/qTZW2nQMqL10bEi4J3wngk0lolGhv0cE/l/emypYE2x5OO7L3SncZbjrntXiKYdEe7cFF4moez7RSlrqprfewN/6kPOd8wPOtz4/7vOtz8N@0/4C "Perl 6 – Try It Online")
[Answer]
# C++17, ~~202−49=153~~ 193 − 58 = 135 bytes
Inspired by the comment-discussion of what counts as a 2-ary function anyway, here's a [curried](https://en.wikipedia.org/wiki/Currying) version of my previous C++17 solution. It's actually shorter because we can use the same macro to define `not_` as to define all the other functions!
```
#define D(v,p)auto v=[](auto x){return[=](auto y){return p;};};
D(true_,x)
D(false_,y)
D(not_,x(false_)(true_)(y))
D(and_,x(y)(false_))
D(or_,x(true_)(y))
D(xor_,x(not_(y))(y))
D(implies,x(y)(true_))
```
[Try it online!](https://tio.run/##nZNBj4MgEIXv/RUke5BJ28Oe9tB489iT16ZpCGJDYtEINpimf31ZEE271u2i8YJv3pvhA6VVtaUFEWdjPjKWc8FQgq@bCkijSnSND0fcrTTcaqaaWhziXmkHBVW7u31WCVZ1w04bDQnOSSHtsrVLUSqr9Qp4D@AWbImIzJVaGKpWK2snPbu0l1wfJ3iRX6qCM@nT3g1GKqI4PREpWa1wtI9QHKOu6F4AR2kEsFuNbGln8zv45Zs2dvvo9/em6/5hHtDf9fZ2dyBD7/9HpC@ZqUl/h0ZXMi8UDmWvL5zpJRKA9MjMJXrOhAD5lF5ApJcg6SVMei6Un9X/UHO/vlEsGG3IhdNN5yYBuVDoQrjAgG53803zgpyl2UqVxXS9/vz6AQ)
This one is tested with assertions like
```
static_assert('R' == and_(true_)(false_)('L')('R'));
static_assert('L' == or_(true_)(false_)('L')('R'));
```
Notice that `or_` is defined as effectively
```
auto or_=[](auto x){return[=](auto y){return x(true_)(y);};};
```
We could define `or_` more "concisely" as
```
auto or_=[](auto x){return x(true_);};
```
but that would cost us because we wouldn't get to use the `D` macro anymore.
[Answer]
# [Birb](https://esolangs.org/wiki/Birb), 23 (or 41?) bytes
```
true: üê¶üê•
false: üê•üê¶
not: üê•ü¶©üïä
and: üê¶ü¶©ü¶úüê•ü¶¢
or: üêßüê¶ü¶ú
xor: ü¶©ü¶©ü¶©üê¶ü¶©
implies: ü¶úü¶©üê•
```
It works a bit like @Neil's answer, but Birb's alternating associative order changes things a bit. Here are the respective parentheses to indicate the associativity:
```
true: (üê¶üê•)
false: (üê•üê¶)
not: ((üê•ü¶©)üïä)
and: ((üê¶((ü¶©ü¶ú)üê•))ü¶¢)
or: ((üêßüê¶)ü¶ú)
xor: ((ü¶©((ü¶©ü¶©)üê¶))ü¶©)
implies: ((ü¶úü¶©)üê•)
```
You may realize that several programs could be significantly shorter (e.g. `true: üê•`, `not: ü¶©`, `or: ü¶ú`, or `and: ü¶©ü¶¢ü¶¢üê•`. However, to have a uniform way of application (due to Birb's alternating associativity), `true` and `false` need to have the same length and all other functions need an odd length >2. I also tried to use a variety of birbs :)
Example applications:
```
not true
~> üê¶üêß üê•ü¶©üïä üê¶üê•
~> [üê¶] (false)
xor true false
~> üê¶üêß üê¶üêß ü¶©ü¶©ü¶©üê¶ü¶© üê¶üê• üê•üê¶
~> üê• (true)
```
I'm unsure whether to count the additional üê¶üêß.. If not, the sum of the length of all Birb functions is 23 bytes. If yes, `2+l(not) + 4+l(and) + 4+l(or) + 4+l(xor) + 4+l(implies) = 41` bytes.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 34 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¿S£↓♣└²≡é♫Jíg░EèΩRΦ♂°┤rà╝¶πï╡^O|Θà
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=a8539c1905c0fdf0820e4aa167b0458aea52e80bf8b47285bc14e38bb55e4f7ce985&i=)
Pushes a bunch of blocks to the stack. Each block expects its last argument atop the stack, followed in reverse order by the rest.
### Unpacked (41 bytes):
```
{sd}Y{d}{y{d}a!}X{ya!}{b!}{cx!sa!}{sx!b!}
```
Each pair of `{ }` is a block. I used the two registers X and Y to hold `true` and `not` so I could access 'em easily later. Unfortunately, `false` couldn't simply be a no-op, as that would leave the stack cluttered and mess up a single XOR case.
[Test suite, commented](https://staxlang.xyz/#c=%7Bsd%7DY%09%09false%0A%7Bd%7D%09%09true%0A%7By%7Bd%7Da%21%7DX%09not%0A%7Bya%21%7D%09%09and%0A%7Bb%21%7D%09%09or%0A%7Bcx%21sa%21%7D%09xor%0A%7Bsx%21b%21%7D%09%09implies%0A%0ALr%7E%09%09Put+in+a+list+in+the+input+stack%0A%0A%22false%3A+%22p%0A%3B0%40%09%09Push+false%0AOZ%21P%09%09Apply+to+1+and+0%3B+print%0ALrh%7E%09%09Clean+up+the+stack%0A%0A%22true%3A+%22p%0A%3B1%40%09%09Push+true%0AOZ%21P%09%09Apply+to+1+and+0%3B+print%0ALrh%7E%09%09Clean+up%0A%0A%22not%3A+%22p%0A%3B0%40%09%09Push+false%0A%3B2%40%21%09%09Apply+not%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%09%09Push+true%0A%3B2%40%21%09%09Apply+not%0AOZ%21P%09%09Apply+to+1+and+0%3B+print%0A%0A%22and%3A+%22p%0A%3B0%40%3B0%40%09%09Push+false+and+false%0A%3B3%40%21%09%09Apply+and%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B0%40%3B1%40%09%09Push+false+and+true%0A%3B3%40%21%09%09Apply+and%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%3B0%40%09%09Push+true+and+false%0A%3B3%40%21%09%09Apply+and%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%3B1%40%09%09Push+true+and+true%0A%3B3%40%21%09%09Apply+and%0AOZ%21P%09%09Apply+to+1+and+0%3B+print%0A%0A%22or%3A+%22p%0A%3B0%40%3B0%40%09%09Push+false+and+false%0A%3B4%40%21%09%09Apply+or%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B0%40%3B1%40%09%09Push+false+and+true%0A%3B4%40%21%09%09Apply+or%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%3B0%40%09%09Push+true+and+false%0A%3B4%40%21%09%09Apply+or%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%3B1%40%09%09Push+true+and+true%0A%3B4%40%21%09%09Apply+or%0AOZ%21P%09%09Apply+to+1+and+0%3B+print%0A%0A%22xor%3A+%22p%0A%3B0%40%3B0%40%09%09Push+false+and+false%0A%3B5%40%21%09%09Apply+xor%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B0%40%3B1%40%09%09Push+false+and+true%0A%3B5%40%21%09%09Apply+xor%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%3B0%40%09%09Push+true+and+false%0A%3B5%40%21%09%09Apply+xor%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%3B1%40%09%09Push+true+and+true%0A%3B5%40%21%09%09Apply+xor%0AOZ%21P%09%09Apply+to+1+and+0%3B+print%0A%0A%22implies%3A+%22p%0A%3B0%40%3B0%40%09%09Push+false+and+false%0A%3B6%40%21%09%09Apply+implies%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B0%40%3B1%40%09%09Push+false+and+true%0A%3B6%40%21%09%09Apply+implies%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%3B0%40%09%09Push+true+and+false%0A%3B6%40%21%09%09Apply+implies%0AOZ%21p%09%09Apply+to+1+and+0%3B+print%0A%3B1%40%3B1%40%09%09Push+true+and+true%0A%3B6%40%21%09%09Apply+implies%0AOZ%21P%09%09Apply+to+1+and+0%3B+print&i=&a=1)
```
false
{sd} stack: x y
s swap: y x
d discard: y
true
{d} stack: x y
d discard: x
not
{y{d}a!} stack: p
y{d} push: p f t
a rotate: f t p
! apply: p(f,t)
and
{ya!} stack: p q
y push: p q f
a rotate: q f p
! apply: p(q,f)
or
{b!} stack: p q
b copies: p q p q
! apply: p q(q,p)
xor
{cx!sa!} stack: p q
c copy: p q q
x! not: p q nq
s swap: p nq q
a rotate: nq q p
! apply: p(nq,q)
implies
{sx!b!} stack: p q
s swap: q p
x! not: q np
b copies: q np q np
! apply: q np(np,q)
```
[Answer]
# [Befunge-98](https://github.com/catseye/Funge-98/blob/master/doc/funge98.markdown#funge-98-final-specification), ~~105~~ ~~77~~ 65 bytes
Playing further with the notion of "function" in languages without functions... here's a Befunge-98 version of Church booleans!
In this constrained dialect of Befunge-98, a program consists of a series of "lines" or "functions," each of which begins with a `>`(Go Right) instruction in column x=0. Each "function" can be identified with its line number (y-coordinate). Functions can take input via Befunge's *stack*, as usual.
Line 0 is special, because (0,0) is the starting IP. To make a program that executes line L, just place instructions on line 0 that, when executed, fly the instruction pointer to (x=L, y=0).
The magic happens on line 1. Line 1, when executed, pops a number `L` from the stack and jumps to line number `L`. (This line had previously been `> >>0{{2u2}2}$-073*-\x`, which can "absolute jump" to any line; but I just realized that since I know this line is pegged to line 1, we can "relative jump" `L-1` lines in a heck of a lot less code.)
Line 2 represents Church `FALSE`. When executed, it pops two numbers `t` and `f` from the stack and then flies to line number `f`.
Line 3 represents Church `TRUE`. When executed, it pops two numbers `t` and `f` from the stack and then flies to line number `t`.
Line 6, representing Church `XOR`, is innovative. When executed, it pops two numbers `a` and `b` from the stack, and then flies to line `a` with stack input `NOT EXEC b`. So, if `a` represents Church `TRUE`, the result of `a NOT EXEC b` will be `NOT b`; and if `a` represents Church `FALSE`, the result of `a NOT EXEC b` will be `EXEC b`.
---
Here's the ungolfed version with test harness. On line 0, set up the stack with your input. For example, `338` means `IMPLIES TRUE TRUE`. Make sure the closing `x` appears at exactly (x,y)=(0,15) or else nothing will work! Also make sure your stack setup begins with `ba`, so that the program will actually terminate with some output.
[Try it online!](https://tio.run/##dZBda4MwFIbv9yteSi8iNGLUrl1wobJZKNgP1EIvRGhBy27aXSgoY7/daVaDY3rIRd4Dz5Nzckmz4nZN6cuSflbyWtcCuJxhWTZgZJSVTwJCMGqcaVyiX/7HLQXj8E7eGyk1ouu6hldc7/kdLTVNHDh9wFGUybF2/dAjuUYyRUrRIzZ8PE3wvyRvcUTBcQjPFW7Fo7jNsQ/akau/cNNptaovLeaAR1rmHLt91Nu8c8jVOtXDw@L5mOeZ4zQ2TvOARtqgRKYw7a@YFe0xLFp8J0q04HB378OiSo3VLTb0O7@eJcdme/A3Xjjq6u3WuCbeMYgms6ZWMoW@u5ZxtqrrHw)
```
> ba 334 0f-1x
> >>1-0a-\x Line 1: EXEC(x)(...) = goto x
> $^< < < Line 2: FALSE(t)(f)(...) = EXEC(f)(...)
> \$^ Line 3: TRUE(t)(f)(...) = EXEC(t)(...)
> 3\^ Line 4: OR(x)(y)(...) = EXEC(x)(TRUE)(y)(...)
> 3\2\^ Line 5: NOT(x)(...) = EXEC(x)(FALSE)(TRUE)(...)
> 1\5\^ Line 6: XOR(x)(y)(...) = EXEC(x)(NOT)(EXEC)(...)
> 2>24{\1u\1u\03-u}^ Line 7: AND(x)(y)(...) = EXEC(x)(y)(FALSE)(...)
> 3^ Line 8: IMPLIES(x)(y)(...) = EXEC(x)(y)(TRUE)(...)
> "EURT",,,,@
> "ESLAF",,,,,@
```
---
Here's the version whose bytes I counted.
```
>>>1-0a-\x
>$^<< }u-30\<
>\$^
>3\^\
>3\2^
>1\5^
>2>24{\1u\1u^
>3^
```
Notice that to define a function in this dialect you don't mention its name at all; its "name" is determined by its source location. To call a function, you do mention its "name"; for example, `XOR` (`6`) is defined in terms of `NOT` and `EXEC` (`5` and `1`). But all my "function names" already take only one byte to represent. So this solution gets no scoring adjustments.
] |
[Question]
[
My wife is very, let's say, particular when it comes to putting ornaments on our Christmas tree. Let's get her some code to help her in this trying time.
### Input
Given an input `2 < n < 10` the height of the tree and `0 < k < n` the distinct number of ornaments.
### Task
Decorate the tree starting with `1` and increment to `k` as we wrap the ornaments around the tree. If we reach `k` and we have more branches to decorate then start back at `1`.
It is okay if there are not the same number of each ornament on the tree, as long as the pattern is satisfied.
The ornaments should appear above each branch `^` except for the top row.
The tree is structured by starting with one branch then the next level has + 1 branches with a space between each, staggered from the top like:
```
^
^ ^
```
For a third row you would add one more branch and stagger them again such that no branch is on the same column (if you think of it like a grid).
```
^
^ ^
^ ^ ^
```
### Output
Output your decorated tree.
### Examples
### 1.
`n = 3, k = 2`
```
^ //Height is 3
^ ^
^ ^ ^
```
Now we decorate each branch starting with 1 and increment to k:
```
^
1 2
^ ^
1 2 1
^ ^ ^
```
### 2.
`n = 6, k = 5`
```
^ //Non-Decorated
^ ^
^ ^ ^
^ ^ ^ ^
^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^
^ //Decorated
1 2
^ ^
3 4 5
^ ^ ^
1 2 3 4
^ ^ ^ ^
5 1 2 3 4
^ ^ ^ ^ ^
5 1 2 3 4 5
^ ^ ^ ^ ^ ^
```
### 3.
`n = 5, k = 1`
```
^
^ ^
^ ^ ^
^ ^ ^ ^
^ ^ ^ ^ ^
^
1 1
^ ^
1 1 1
^ ^ ^
1 1 1 1
^ ^ ^ ^
1 1 1 1 1
^ ^ ^ ^ ^
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins! Have fun and good luck!
[Answer]
# C# 226 221 Bytes
*Saved 5 Bytes thanks to @Mukul Kumar and @aloisdg*
Golfed:
```
string C(int n,int k){string o="",x;int j=1,i=1,m;for(;i<=n;i++){o+=string.Concat(Enumerable.Repeat("^ ",i)).PadLeft(n+i)+"\n";m=0;x="";if(i<n){while(m<i+1){if(j>k)j=1;x+=j+++" ";m++;}o+=x.PadLeft(n+i+1)+"\n";}}return o;}
```
Ungolfed:
```
public string C(int n, int k, WifeMode wifeMode = WifeMode.Maniacal)
{
string o = "",x;
int j = 1,i=1,m;
for (; i <= n; i++)
{
o += string.Concat(Enumerable.Repeat("^ ", i)).PadLeft(n+i) + "\n";
m = 0;
x = "";
if (i < n)
{
while (m < i + 1)
{
if (j > k) j = 1;
x += j++ + " ";
m++;
}
o += x.PadLeft(n + i + 1) + "\n";
}
}
return o;
}
```
Testing:
```
Console.Write(new ChristmasTreeDecorating().C(20, 9));
^
1 2
^ ^
3 4 5
^ ^ ^
6 7 8 9
^ ^ ^ ^
1 2 3 4 5
^ ^ ^ ^ ^
6 7 8 9 1 2
^ ^ ^ ^ ^ ^
3 4 5 6 7 8 9
^ ^ ^ ^ ^ ^ ^
1 2 3 4 5 6 7 8
^ ^ ^ ^ ^ ^ ^ ^
9 1 2 3 4 5 6 7 8
^ ^ ^ ^ ^ ^ ^ ^ ^
9 1 2 3 4 5 6 7 8 9
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
1 2 3 4 5 6 7 8 9 1 2
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
3 4 5 6 7 8 9 1 2 3 4 5
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
6 7 8 9 1 2 3 4 5 6 7 8 9
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
1 2 3 4 5 6 7 8 9 1 2 3 4 5
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
6 7 8 9 1 2 3 4 5 6 7 8 9 1 2
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
```
*Edit: I had a play casting `int` to `ConsoleColor`... Tis the season :)*
[![enter image description here](https://i.stack.imgur.com/LJ6Wp.png)](https://i.stack.imgur.com/LJ6Wp.png)
*MerryChristmas.gif*
[![enter image description here](https://i.stack.imgur.com/yjJL5.gif)](https://i.stack.imgur.com/yjJL5.gif)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~29~~ ~~27~~ 24 bytes
Saved three bytes thanks to Adnan!
```
>GN„^ ×NÝNLO<+²%>ðý}\».c
>G For N in [1, ..., input[0]]
N„^ × Push a string of "^ " N times
NÝ Push [0, ..., N]
NLO< Compute the decoration offset, sum([1, ..., N])-1
+ Add the offset value to each array cell
²% Modulo input[1]
> Add 1 so that it is in range [1, k] instead of [0, k-1]
ðý Join with spaces, now we have a string with the full decoration for the current layer
} End for
\ Remove the last decoration
» Join everything with newlines
.c Center all and implicitly display
```
[Try it online!](http://05ab1e.tryitonline.net/#code=PkdO4oCeXiDDl07DnU5MTzwrwrIlPsOww719XMK7LmM&input=Ngo1)
[Answer]
## JavaScript (ES6), 97 bytes
It seems like your wife *really* is maniacal, so this doesn't include any leading or trailing newline, nor any leading or trailing space. :-)
```
f=(n,k,x,s=`^
`)=>n--?(p=' '.repeat(n)+s,x?p.replace(/\^/g,_=>x++%k+1)+p:p)+f(n,k,x||k,'^ '+s):''
```
### Demo
```
f=(n,k,x,s=`^
`)=>n--?(p=' '.repeat(n)+s,x?p.replace(/\^/g,_=>x++%k+1)+p:p)+f(n,k,x||k,'^ '+s):''
console.log(f(6, 5))
```
[Answer]
# C++ 214 - 13 - 3 - 1 -1 - 10 = 186 bytes
golfed
```
#define s std::cout<<
int f(int n,int k){int N=++n,K=0,i=0,I;for(;i<n;i++,N--){for(I=N;I--;)s' ';for(I=0;I++<i&&i-1;)s' '<<(K++%k)+1;s'\n';for(I=N;I--;)s' ';for(I=0;I++<i;)s" ^";s'\n';}}
```
Thanks @ cyoce for saving 1 byte.
Thanks @ conor for *chopping* it down to 186!
Ungolfed + copy&compile
```
#include<iostream>
#include<conio.h>
#define s(a) std::cout<<a;
int main()
{
int n,N,k,K=0,i,I;
std::cin>>n>>k;
N=++n;
for(i=0;i<n;i++,N--)
{
for(I=N;I--;)
s(' ')
for(I=0;I<i&&i-1;I++)
s(' '<<(K++%k)+1)
s('\n')
for(I=N;I;I--)
s(' ')
for(I=0;I<i;I++)
s(" ^")
s('\n')
}
getch();//or any func to pause the console
}
```
[Answer]
## Python 2, 133 bytes
```
n,k=input()
d=-1
j=' '.join
for i in range(1,n+1):s=' '*(n-i);print(['',s+j(`x%k+1`for x in range(d,d+i))+'\n'][i>1]+s+j('^'*i));d+=i
```
[Answer]
**Clojure, 223 bytes**
My first go at golfing with Clojure:
```
(let[r repeat](defn d[n k](apply str(concat(r(dec n)\ )"^\n"(flatten(for[i(range 2(inc n))m[nil true]](concat(r(- n i)\ )(butlast(interleave(if m(r\^)(rest(iterate #(inc(mod % k))(dec(/(* i(dec i))2)))))(r i\ )))"\n")))))))
```
When called like `(println (str "\n" (d 6 5)))` a newline makes it nicer on REPL:
```
^
1 2
^ ^
3 4 5
^ ^ ^
1 2 3 4
^ ^ ^ ^
5 1 2 3 4
^ ^ ^ ^ ^
5 1 2 3 4 5
^ ^ ^ ^ ^ ^
```
Un-golfed:
```
(defn tree-row [n k index mode]
(concat
(repeat (- n index) \ ) ; Left padding
(butlast ; Removing trailing space
(interleave
; Either printing carets or numbers...
(if mode
(repeat \^)
; Using "rest" as the iteration starts from a large value
; from which the modulo has not been calculated yet.
(rest (iterate #(inc (mod % k)) (dec (/ (* index (dec index)) 2)))))
; ...and interleaved with spaces
(repeat index \ )))
"\n"))
(defn decorate [n k]
(apply str (concat
(repeat (dec n) \ ) "^\n"
(flatten (for [index (range 2 (inc n)) mode [nil true]]
(tree-row n k index mode))))))
```
I had some issues with lazy sequences and nested lists but I was able to save some characters by not repeating `repeat` ;) and using `\^` characters instead of `"^"` strings. I could also leave out surprisingly many spaces.
[Answer]
## Ruby 107 bytes
```
t=->(n,k){d=[*1..k]*n*n;o=0;(1..n).each{|b|s=' '*(n-b);b>1&&(puts(s+d[o,b].join(' '));o+=b);puts s+'^ '*b}}
```
Called like this
```
t.call(5,4)
```
Output:
```
^
1 2
^ ^
3 4 1
^ ^ ^
2 3 4 1
^ ^ ^ ^
2 3 4 1 2
^ ^ ^ ^ ^
```
[Answer]
# C, 170 bytes
```
i=0;d,j,l;t(n,k){char s[20],r[20];d=k-2;l=n;for(;i++<n;){for(j=0;j<l;++j)s[j]=r[j]=32;for(j=n-i;j<l;j+=2){s[j]=94;r[j]=(++d%k)+49;}s[l]=r[l++]=0;if(i-1)puts(r);puts(s);}}
```
Call with:
```
int main()
{
t(5,4);
}
```
As a bonus, here's a 4-bit binary version:
```
m=0;b(n,k){char*a="000100100011010001010110011110001001";char s[20],r[20];d=k*4-2;l=n;for(;m++<n;){for(j=0;j<l;++j)s[j]=r[j]=32;for(j=n-m;j<l;j+=2){s[j]=94;r[j]=a[++d%(k*4)];}s[l]=r[l++]=0;if(m-1)puts(r);puts(s);}}
```
] |
[Question]
[
Your task is to create a program that will, given an input image, create an output image of the same size, where all pixels are ordered by hex value.
Your program may:
* Sort the pixels from left to right and then down or first sort down in columns and then right. In any case, the top left pixel is the smallest, and the bottom right is the largest.
* Use transparency, but this is not required.
* Sort by RGB, but you may use CMY, or any other format with at least 3 values. You can choose what values to sort on. (HSV may give some nice images)
* Use any well-known image format that most computers can open.
Rules:
* Output must be written to disk or be pipeable to a file.
* Input is given as a commandline argument, in the form of a relative path to the image, or piped in from the commandline.
* This is code golf, so shortest code in bytes wins!
[Answer]
# Pyth - 10 bytes
Reads image, collapses bitmap, sorts, and then splits up bitmap again, then writes.
```
.wclK'zSsK
```
Doesn't work online for obvious reasons. Takes input as relative path to image file and outputs into `o.png`.
Output from American Gothic:
[![](https://i.stack.imgur.com/Py50h.png)](https://i.stack.imgur.com/Py50h.png)
[Answer]
# JavaScript (ES6), ~~383~~ ~~377~~ 354 bytes
```
f=s=>{d=document,i=new Image,i.src=s,i.onload=$=>{c=d.createElement`canvas`,x=c.getContext`2d`,c.width=w=i.width,c.height=h=i.height,x.drawImage(i,0,0),D=x.getImageData(0,0,w,h),t=D.data,t.set([].concat(...[...t].map((v,i,T)=>i%4?[,,,0]:T.slice(i,i+4)).sort((a,b)=>a.some((v,i)=>k=v-b[i])&&k)).slice(12*w*h)),x.putImageData(D,0,0),d.body.appendChild(c)}}
```
[![sample output](https://i.stack.imgur.com/8pdQW.png)](https://i.stack.imgur.com/8pdQW.png)
**Runnable demo:**
```
f=function(s) {l=[i=new Image].slice,i.crossOrigin="anonymous",i.src=s,i.onload=function($){d=document,c=d.createElement`canvas`,c.width=w=i.width,c.height=h=i.height,x=c.getContext`2d`,x.drawImage(i,0,0),D=x.getImageData(0,0,w,h),t=D.data,t.set([].concat.apply([],l.call(t).map((v,i)=>i%4?[0,0,0,0]:l.call(t,i,i+4)).sort((a,b)=>a.reduce((A,v,i)=>A||v-b[i],0))).slice(3*t.length)),x.putImageData(D,0,0),d.body.appendChild(c)}}
$("img").click(function() { f(this.src); })
```
```
canvas { padding-right: 4px; } img { cursor: pointer; }
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/The_Scream.jpg/114px-The_Scream.jpg"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/67/Claude_Monet_La_Grenouill%C3%A9re.jpg/193px-Claude_Monet_La_Grenouill%C3%A9re.jpg"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/cc/Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg/120px-Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg"><br>
```
How this code works is to use `getImageData` to get an array of the form
```
[R,G,B,A,
R,G,B,A,
R,G,B,A,
...]
```
And `map` it to an array of the form
```
[[R,G,B,A],[0,0,0,0],[0,0,0,0],[0,0,0,0],
[R,G,B,A],[0,0,0,0],[0,0,0,0],[0,0,0,0],
[R,G,B,A],[0,0,0,0],[0,0,0,0],[0,0,0,0],
...]
```
So that the R values are mapped to arrays of the RGBA set, and the B, G, and A values turn into minimum-value zero arrays. When we sort this array, all the `[0,0,0,0]` arrays sort to the bottom and the real-value arrays sort normally at the top:
```
[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],
[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],
[0,0,0,0],..., [R,G,B,A],[R,G,B,A],[R,G,B,A],...]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
extract & flatten these sorted pixels
```
We skim the top fourth of the array (to lose the empty values we created), flatten it with `[].concat.apply`, and end up with an array of the first form again, but this time, it's sorted.
Slightly de-golfed with whitespace and comments:
```
f=s=>{
// first, load image, then do everything else onload
i=new Image,
i.src = s,
i.onload=$=>{
// set up the canvas
d=document,
c=d.createElement`canvas`,
w=c.width=i.width,
h=c.height=i.height,
x=c.getContext`2d`,
// draw image to canvas and capture pixel data
x.drawImage(i,0,0),
D=x.getImageData(0,0,w,h),
t=D.data,
// set pixel data to...
t.set(
// the flattened array...
[].concat(...
// that is a mapping of the pixel data...
[...t].map(
// that clumps RGBA families into subarrays
// by replacing every fourth value with [R,G,B,A]
// and all other values to [0,0,0,0]...
(v,i,T)=>i%4?[,,,0]:T.slice(i,i+4)
)
// and is then sorted...
.sort(
// by reducing each array to a positive, negative, or zero
// by comparing R,G,B,& A until the first nonzero difference
(a,b)=>a.some((v,i)=>k=v-b[i])&&k
)
)
// then eliminate the low-sorted empty [0,0,0,0] values we created,
// leaving only the top fourth, with real values
// (note that 3*4*w*h is the same as 3*t.length)
.slice(3*4*w*h)
),
// now that `t` is set, store `D` in canvas
x.putImageData(D,0,0),
// show canvas
d.body.appendChild(c)
}
}
```
Note that most browsers may fail to run this code for large images, because it passes a huge number of arguments into `[].concat`. When the browser environment does not allow sufficient memory for all the arguments, an alternative approach is to re-map the RGBA values out of the top fourth arrays back onto the array, for a total score of **361 bytes**:
```
f=s=>{d=document,i=new Image,i.src=s,i.onload=$=>{c=d.createElement`canvas`,x=c.getContext`2d`,c.width=w=i.width,c.height=h=i.height,x.drawImage(i,0,0),D=x.getImageData(0,0,w,h),t=D.data,t.set([...t].map((v,i,T)=>i%4?[,,,0]:T.slice(i,i+4)).sort((a,b)=>a.some((v,i)=>k=v-b[i])&&k).map((v,i,A)=>A[3*w*h+(i>>2)][i%4])),x.putImageData(D,0,0),d.body.appendChild(c)}}
```
We simply replace the `[].concat(...{stuff}).slice(12*w*h)` with `{stuff}.map((v,i,A)=>A[3*w*h+(i>>2)][i%4])`.)
[Answer]
# Mathematica ~~86 83~~ 72 bytes
```
f=Flatten;Image[f[Sort[f[s=ImageData@#1,1]]]~ArrayReshape~Dimensions@s]&
```
---
With 14 bytes saved thanks to @Martin Buttner.
---
**Example**
The image itself is input. Alternatively, a variable containing the image could be used.
[![gothic](https://i.stack.imgur.com/Po94N.png)](https://i.stack.imgur.com/Po94N.png)
[Answer]
# Javascript ES6, 334 bytes
```
f=s=>{with((d=document).body.appendChild(c=d.createElement`canvas`).getContext`2d`)(i=new Image).src=s,drawImage(i,0,0,w=c.width=i.width,h=c.height=i.height),t=(g=getImageData(0,0,w,h)).data,t.set([...t].map(i=>(0+i.toString(16)).slice(-2)).join``.match(/.{8}/g).sort().join``.match(/../g).map(i=>parseInt(i,16))),putImageData(g,0,0)}
```
Ungolfed:
```
f=s=>{ // create function that accepts image name
with((d=document).body.appendChild( // use "with" to exclude having to prepend "<context2d>." to drawImage, getImageData and putImageData
c=d.createElement`canvas`).getContext`2d`) // create canvas to get pixels from and draw output to
(i=new Image).src=s, // create image, define source filename
drawImage(i,0,0,w=c.width=i.width, // draw image to canvas
h=c.height=i.height),
t=(g=getImageData(0,0,w,h)).data, // get image data from canvas in form of Uint8Array
t.set([...t] // convert image data from Uint8Array to standard array
.map(i=>(0+i.toString(16)).slice(-2)) // convert R,G,B,A bytes to base16 strings with leading zeros
.join``.match(/.{8}/g) // convert array of [R,G,B,A,R,G,B,A,...] to [RGBA,RGBA,...]
.sort() // sort pixel values
.join``.match(/../g) // convert array of [RGBA,RGBA,...] to [R,G,B,A,R,G,B,A,...]
.map(i=>parseInt(i,16))), // convert hex strings back to integers, reassign to image data
putImageData(g,0,0) // dump image data onto canvas
}
```
[Answer]
# C (using SDL1.2), ~~333~~ ~~322~~ 315 bytes
C is most probably not the 'sharpest knife in the shelf' for this kind of work, I wanted to give it a try anyway. Tips for improving my answer are welcome. The program gets the name of the input image file as a cli argument.
```
#include <SDL.h>
#include <SDL_image.h>
#define X SDL_Surface*
#define Y const void*
C(Y a,Y b){return*(Uint32*)a-*(Uint32*)b;}main(int o,char**a){X i=IMG_Load(a[1]);X s=SDL_SetVideoMode(i->w,i->h,32,0);i=SDL_ConvertSurface(i,s->format,0);qsort(i->pixels,i->w*i->h,4,C);SDL_BlitSurface(i,0,s,0);for(;;SDL_Flip(s));}
```
compile and run : `gcc -I/usr/include/SDL snippet.c -lSDL -lSDL_image && ./a.out`
[![enter image description here](https://i.stack.imgur.com/F5YCR.png)](https://i.stack.imgur.com/F5YCR.png)
I don't usually golf in C, but I've just answered [this challenge](https://codegolf.stackexchange.com/questions/62095/a-single-pixel-moving-in-a-circular-path) yesterday and I just wanted to continue playing with that new toy :)
thanks to @pseudonym117 for helping me saving 5 bytes
[Answer]
## JavaScript (ES6), 452 ~~480~~ ~~484~~ ~~487~~ ~~511~~ bytes
Wow, this got longer than expected:
```
f=u=>{i=new Image;i.src=u;i.onload=_=>{c=(d=document).createElement`canvas`;c.width=w=i.width;c.height=h=i.height;x=c.getContext`2d`;x.drawImage(i,0,0,w,h);p=x.getImageData(0,0,w,h).data;t=[];f=[];for(j=0;j<p.length;++j)t.push([p[j],p[++j],p[++j],p[++j]]);t.sort((a,b)=>a[0]>b[0]||a[0]==b[0]&&a[1]>b[1]||a[0]==b[0]&&a[1]==b[1]&&a[2]>b[2]).map(u=>f.push.apply(f,u));x.putImageData(new ImageData(new Uint8ClampedArray(f),w,h),0,0);d.body.appendChild(c)}}
```
The function takes an URL as its input `f('test.jpg');` and draws the result into a `canvas`-element which is appended to the `body`.
Note that the source must be on the same domain or the script will halt with a security issue.
---
**Limitations**
I've tested it in Firefox 42 on OS X (10.10) on a machine with 2.5 GHz i7 and 16 GB RAM. The maximum image size I could process without Firefox asking to continue the script execution was *1600 x 1932 px*.
---
**Ungolfed**
```
f = u => {
i = new Image;
i.src = u;
i.onload = _ => {
c = (d = document).createElement`canvas`;
c.width = w = i.width;
c.height = h = i.height;
x = c.getContext`2d`;
x.drawImage(i, 0, 0, w, h);
p = x.getImageData(0, 0, w, h).data;
t = [];
f = [];
for (j = 0; j < p.length;++j)
t.push([p[j], p[++j], p[++j], p[++j]]);
t.sort( (a,b) => a[0] > b[0] || a[0] == b[0] && a[1] > b[1] || a[0] == b[0] && a[1] == b[1] && a[2] > b[2] )
.map(u => f.push.apply(f,u));
x.putImageData( new ImageData( new Uint8ClampedArray(f), w, h), 0, 0);
d.body.appendChild(c)
}
}
```
---
**Output**
For a better comparison I also took the "*American Gothic*" as the example source:
[![enter image description here](https://i.stack.imgur.com/PvV79.jpg)](https://i.stack.imgur.com/PvV79.jpg)
---
**Edits**
* *Saved* **24 bytes** by using `for (a in b)` instead of `for(;;)`. Thanks to [ar34z](https://codegolf.stackexchange.com/users/46842/ar34z)
* *Saved* **3 bytes** by storing `document` in a variable.
* *Saved* **4 bytes** by dropping some of these `()`.
* *Saved* **10 bytes** by using [tagged template strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings#Tagged_template_strings), omitting the `()` on object creation and removing another pair of redundant `()`. Thanks to [apsillers](https://codegolf.stackexchange.com/users/7796/apsillers).
* *Saved* **14 bytes** by massive refactoring of the code that flattens the color array after sorting. Thanks a lot to [apsillers](https://codegolf.stackexchange.com/users/7796/apsillers) and [Ypnypn](https://codegolf.stackexchange.com/users/16294/ypnypn) for undercutting each other.
* *Saved* **1 byte** by refactoring the `for`-loop that gets the colors of each pixel.
[Answer]
# Bash + GNU utils, 80
```
s()(sed 1d $1|cut -d\ -f$2)
sed 1q $1
s $1 2-|sort -t_ -k1.16|paste <(s $1 1) -
```
This assumes input/output format is in ImageMagick pixel enumeration .txt format. The input is passed as a filename and the output goes to STDOUT.
---
If the above is not considered a well-known image format, then we can add in the necessary conversions:
# Bash + GNU utils + ImageMagick, 108
```
s()(sed 1d t|cut -d\ -f$1)
convert $1 txt:t
(sed 1q t
s 2-|sort -t_ -k1.16|paste <(s 1) -)|convert txt:- $2
```
Input and output are specified as filenames. ImageMagick determines what file formats to use by the passed file extensions, so we can use any common ones:
```
$ ./sortpixels.sh 398px-Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg o.png
$
```
The resulting o.png looks like:
[![enter image description here](https://i.stack.imgur.com/M1l49.png)](https://i.stack.imgur.com/M1l49.png)
[Answer]
# Python 2, 128 bytes
```
from PIL import*
a=Image.open('a')
b=a.load()
c,d=a.size
a.putdata(sorted(b[e,f]for f in range(d)for e in range(c)))
a.save('b')
```
Provided the image is a file named `a` with no extension, the output will be a file named `b` with no extension.
![American Gothic](https://i.stack.imgur.com/CRikX.jpg)
![American Gothic (sorted)](https://i.stack.imgur.com/yGjgg.jpg)
[Answer]
# Java, 316 bytes
```
import javax.imageio.*;class C{public static void main(String[]a)throws Exception{java.awt.image.BufferedImage i=ImageIO.read(new java.io.File(a[0]));int w=i.getWidth(),h=i.getHeight(),v[]=i.getRGB(0,0,w,h,null,0,w);java.util.Arrays.sort(v);i.setRGB(0,0,w,h,v,0,w);ImageIO.write(i,"png",new java.io.File("a.png"));}}
```
Places the hexadecimal values of the pixel colors in an array. The array is sorted, and the colors are remapped to the pixels in the image. The name of the resulting image is `a.png`.
[![yellow tulips input](https://i.stack.imgur.com/FlO1w.jpg)](https://i.stack.imgur.com/FlO1w.jpg)
[![yellow tulips output](https://i.stack.imgur.com/AXczO.png)](https://i.stack.imgur.com/AXczO.png)
[![American Gothic input](https://i.stack.imgur.com/odLLK.jpg)](https://i.stack.imgur.com/odLLK.jpg)
[![enter image description here](https://i.stack.imgur.com/ywgzc.png)](https://i.stack.imgur.com/ywgzc.png)
[Answer]
# SmileBASIC, ~~39~~ 35 bytes
Assuming the image is loaded onto the 512\*512 graphics page:
```
DIM A[0]GSAVE A,0SORT A
GLOAD A,0,1
```
Explained:
```
DIM IMG[0] 'create array
GSAVE IMG,0 'save graphics to array
SORT IMG 'sort
GLOAD IMG,0,1 'load graphics from array
```
It's that simple!
~~Unfortunately we have to use integers, which adds 4 bytes to the program size due to the type suffixes.~~
[Answer]
# Java, ~~424~~ ~~417~~ 404 bytes
Well, this is not a language you want to golf in...
```
import java.awt.image.*;import java.io.*;import javax.imageio.*;class F{public static void main(String[]x)throws Exception{BufferedImage i,o;i=ImageIO.read(new File(x[0]));o=new BufferedImage(i.getWidth(),i.getHeight(),BufferedImage.TYPE_INT_RGB);o.setData(i.getRaster());int[]p=((DataBufferInt)o.getRaster().getDataBuffer()).getData();java.util.Arrays.sort(p);ImageIO.write(o,"png",new File("o.png"));}}
```
[Answer]
# C#, 497 bytes
First time post, first golf. Clearly not the best for golfing
Not really respecting the piping.
Takes an image path as an input and outputs it with letter "o" prepend to the name.
Works better with bitmaps, odds results with others
```
using System.Linq;using System.Drawing;using System.Runtime.InteropServices;class Program{static void Main(string[]args){using(var im=(Bitmap)Image.FromFile(args[0])){int h=im.Height;int w=im.Width;var b=im.LockBits(new Rectangle(0,0,w,h),System.Drawing.Imaging.ImageLockMode.ReadWrite,System.Drawing.Imaging.PixelFormat.Format32bppRgb);var p=new int[h*w];Marshal.Copy(b.Scan0,p,0,h*w);var q=p.ToList();q.Sort();p=q.ToArray();Marshal.Copy(p,0,b.Scan0,h*w);im.UnlockBits(b);im.Save("o"+args[0]);}}}
```
[Answer]
## Haskell, 195 bytes
```
import Data.List
import Graphics.GD
f p=do
a<-loadPngFile p;(x,y)<-imageSize a;let l=[(i,j)|j<-[0..y],i<-[0..x]]
mapM(flip getPixel a)l>>=mapM(\(d,c)->setPixel d c a).zip l.sort;savePngFile"o"a
```
This uses the `GD` library. Usage `f <filename>`. The input file must be in `png` format. The output file is named `o`.
How it works: straightforward, i.e. read the picture, walk over all coordinates and get the pixels, sort the pixels, walk over the coordinates again, but this time set the pixels in the order they appear in the sorted list, write the file to disk.
[![enter image description here](https://i.stack.imgur.com/WroC7.png)](https://i.stack.imgur.com/WroC7.png)
[Answer]
# Java + Processing, 198 bytes
```
PImage p;void settings(){p=loadImage("peter-olexa-Ejgx4k3iryg-unsplash.jpg");size(p.width,p.height);}void setup(){p.loadPixels();p.pixels=sort(p.pixels);p.updatePixels();image(p,0,0);save("2.jpg");}
```
Outputs image as `1.jpg`.
[![enter image description here](https://i.stack.imgur.com/r0PuD.jpg)](https://i.stack.imgur.com/r0PuD.jpg)
[![enter image description here](https://i.stack.imgur.com/clCMd.jpg)](https://i.stack.imgur.com/clCMd.jpg)
[![enter image description here](https://i.stack.imgur.com/KwRhx.jpg)](https://i.stack.imgur.com/KwRhx.jpg)
[![enter image description here](https://i.stack.imgur.com/5t1O7.jpg)](https://i.stack.imgur.com/5t1O7.jpg)
[Answer]
# [Funky2](https://github.com/tehflamintaco/funky2), 156 Bytes
```
I=draw.newImageData(arg[1)C=[]j=i=0I.mapPixels((x,y,r)=>C[i++]=r)C=C:sort((a,b)=>(a.r*256+a.g+a.b/256)-(b.r*256+b.g+b.b/256))I.mapPixels(@C[j++)I.export"o"
```
Non-Competing due to the fact that several features were implemented in response to this challenge, including image exporting and list sorting. Also several features needed fixing.
## Ungolfed
```
I = draw.newImageData(arg[1]); $// Load the specified image as a bitmap.
c = []; $// Generate a table for us to pour colours into.
j=i=0; $// Initialize two counters, I and J. Saves us resetting i, and c[#c] is prohibitively memory intensive
I.mapPixels((x,y,r)=>c[i++]=r); $// Iterate over the image and assign each colour (Contained as a list in r) into c.
c = c:sort((a,b)=>(a.r*256+a.g+a.b/256)-(b.r*256+b.g+b.b/256)); $// Sort C by R, then G, then B.
I.mapPixels(@c[j++]); $// Map back over I, replacing each colour with their index in C
I.export"o"; $// Export as "o"
```
There are a couple of opportunities for improvement; such as using `c[#c]` rather than `c[i++]` or Sorting `c` every time I try to index it in the second mapping; but these methods cause the execution time to skyrocket.
**Output, American Gothic**
![Gothic](https://i.gyazo.com/936e57826cd9bcea9db8ba0cde42b7f0.png)
] |
[Question]
[
# Results (May 22 2017 21:40:37 UTC)
[`Master`](https://codegolf.stackexchange.com/a/121038/42649) won 18 rounds, lost 2 rounds, and tied 0 rounds
[`Save One`](https://codegolf.stackexchange.com/a/120848/42649) won 15 rounds, lost 3 rounds, and tied 2 rounds
[`Machine Gun`](https://codegolf.stackexchange.com/a/120740/42649) won 14 rounds, lost 3 rounds, and tied 3 rounds
[`Monte Bot`](https://codegolf.stackexchange.com/a/121312/42649) won 14 rounds, lost 3 rounds, and tied 3 rounds
[`Amb Bot`](https://codegolf.stackexchange.com/a/120921/42649) won 12 rounds, lost 8 rounds, and tied 0 rounds
[`Coward`](https://codegolf.stackexchange.com/a/120696/42649) won 11 rounds, lost 3 rounds, and tied 6 rounds
[`Pain in the Nash`](https://codegolf.stackexchange.com/a/121943/42649) won 11 rounds, lost 9 rounds, and tied 0 rounds
[`Nece Bot`](https://codegolf.stackexchange.com/a/120695/42649) won 10 rounds, lost 7 rounds, and tied 3 rounds
[`Naming Things is Hard`](https://codegolf.stackexchange.com/a/120723/42649) won 10 rounds, lost 7 rounds, and tied 3 rounds
[`The Procrastinator`](https://codegolf.stackexchange.com/a/122043/42649) won 10 rounds, lost 8 rounds, and tied 2 rounds
[`Yggdrasil`](https://codegolf.stackexchange.com/a/121362/42649) won 10 rounds, lost 10 rounds, and tied 0 rounds
[`Simple Bot`](https://codegolf.stackexchange.com/a/120704/42649) won 9 rounds, lost 4 rounds, and tied 7 rounds
[`Table Bot`](https://codegolf.stackexchange.com/a/120732/42649) won 9 rounds, lost 6 rounds, and tied 5 rounds
[`Prioritized Random Bot`](https://codegolf.stackexchange.com/a/120717/42649) won 8 rounds, lost 7 rounds, and tied 5 rounds
[`Upper Hand Bot`](https://codegolf.stackexchange.com/a/120710/42649) won 7 rounds, lost 13 rounds, and tied 0 rounds
[`Aggressor`](https://codegolf.stackexchange.com/a/120706/42649) won 6 rounds, lost 10 rounds, and tied 4 rounds
[`Insane`](https://codegolf.stackexchange.com/a/120706/42649) won 5 rounds, lost 15 rounds, and tied 0 rounds
[`The Ugly Duckling`](https://codegolf.stackexchange.com/a/120700/42649) won 4 rounds, lost 16 rounds, and tied 0 rounds
[`Know Bot`](https://codegolf.stackexchange.com/a/120892/42649) won 3 rounds, lost 14 rounds, and tied 3 rounds
[`Paranoid Bot`](https://codegolf.stackexchange.com/a/120965/42649) won 0 rounds, lost 19 rounds, and tied 1 round
[`Panic Bot`](https://codegolf.stackexchange.com/a/120965/42649) won 0 rounds, lost 19 rounds, and tied 1 round
Unfortunately I could not test The Crazy X-Code Randomess because I can't get it to run from bash on Linux. I will include it if I can get it to work.
[Full Controller Output](https://hastebin.com/eduxedatoq.txt)
---
# The Game
This is a very simple KoTH game. It's a one-on-one snowball fight. You have an initially-empty container that can hold up to `k` snowballs. You can duck up to `j` times. Each turn, both players are asked to simultaneously give a choice for what move to make. There are three moves:
* reload: gives you another snowball (up to `k`)
* throw: throws a snowball, which will kill the other player if they decide to reload. If both players throw a snowball, nobody dies (they have such good aim that they will hit each other's snowballs)
* duck: does nothing, and avoids getting hit if the other player throws a snowball. If you have no more ducks left, then nothing happens and if the other player throws a snowball you die.
# Objective
Don't die.
# Challlenge Specifications
Your program can be written in any language. You are to take each of these
variables as an argument on each execution:
```
[turn, snowballs, opponent_snowballs, ducks, opponent_ducks, max_snowballs]
```
`turn` - how many turns have elapsed (`0` on the first iteration)
`snowballs` - how many snowballs you have
`opponent_snowballs` - how many snowballs the opponent has
`ducks` - how many more times you can duck
`opponent_ducks` - how many more times the opponent can duck
`max_snowballs` - the maximum number of snowballs you can store (`k`)
The key function's output should be `0` for reload, `1` for throw, and `2` for duck. You must output your move, newline terminated. Please don't output invalid moves, but the controller is very resilient and will not break if you output invalid moves (even if your move isn't even an integer). It **must** be newline-terminated though. If the move isn't in `[0, 1, 2]`, it will default your move to `0`. The winner will be decided as the player with the most wins from a full round-robin tournament.
# Rules
You can read/write from/to one file for memory storage between iterations. Your bot will be placed in its own directory so filename conflicts will not occur. You cannot change built-in functions (such as the random generator). It was quite funny [the first time it was done](https://codegolf.stackexchange.com/a/25392/42649), but it won't be anymore. Your program is not allowed to do things that are just blatant execution stalling. [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
# Testing
The source code for the controller can be found [here](https://hastebin.com/uvaduyuqen.java). Example of running it: `java Controller "python program1/test1.py" "python program2/test2.py" 10 5` for 10 snowballs and 5 ducks.
# Judging
The winner will be decided by selecting the person with the most wins after a full round-robin. While this is a tie, remove all people who do not have the most wins. Then, repeat until one person wins. The judging standard will be 50 snowballs and 25 ducks.
Happy KoTHing!
**EDIT**: The game will be declared a tie if 1000 rounds pass. Your bot may assume that `turn < 1000`.
[Answer]
# Master, C#
I trained a small neural network (using [Sharpneat](https://github.com/colgreen/sharpneat)). It seems to like picking up snowballs and ducking...
In a previous version of the controller, it even found a bug. It went from 0% winning to 100% when it discovered how to win by cheating.
**Edit:** I forgot to reset the networks interal state and trained the network wrong. The newly trained network is much smaller.
```
using System;
using System.Collections.Generic;
public class Master
{
public CyclicNetwork _network;
public static void Main(string[] args)
{
int s = int.Parse(args[1]);
int os = int.Parse(args[2]);
int d = int.Parse(args[3]);
int od = int.Parse(args[4]);
int ms = int.Parse(args[5]);
var move = new Master().GetMove(s, os, d, od, ms);
Console.WriteLine(move);
}
public Master()
{
var nodes = new List<Neuron>
{
new Neuron(0, NodeType.Bias),
new Neuron(1, NodeType.Input),
new Neuron(2, NodeType.Input),
new Neuron(3, NodeType.Input),
new Neuron(4, NodeType.Input),
new Neuron(5, NodeType.Input),
new Neuron(6, NodeType.Output),
new Neuron(7, NodeType.Output),
new Neuron(8, NodeType.Output),
new Neuron(9, NodeType.Hidden)
};
var connections = new List<Connection>
{
new Connection(nodes[1], nodes[6], -1.3921811701131295),
new Connection(nodes[6], nodes[6], 0.04683387519679514),
new Connection(nodes[3], nodes[7], -4.746164930591382),
new Connection(nodes[8], nodes[8], -0.025484025422054933),
new Connection(nodes[4], nodes[9], -0.02084856381644095),
new Connection(nodes[9], nodes[6], 4.9614062853759124),
new Connection(nodes[9], nodes[9], -0.008672587457112968)
};
_network = new CyclicNetwork(nodes, connections, 5, 3, 2);
}
public int GetMove(int snowballs, int opponentBalls, int ducks, int opponentDucks, int maxSnowballs)
{
_network.InputSignalArray[0] = snowballs;
_network.InputSignalArray[1] = opponentBalls;
_network.InputSignalArray[2] = ducks;
_network.InputSignalArray[3] = opponentDucks;
_network.InputSignalArray[4] = maxSnowballs;
_network.Activate();
double max = double.MinValue;
int best = 0;
for (var i = 0; i < _network.OutputCount; i++)
{
var current = _network.OutputSignalArray[i];
if (current > max)
{
max = current;
best = i;
}
}
_network.ResetState();
return best;
}
}
public class CyclicNetwork
{
protected readonly List<Neuron> _neuronList;
protected readonly List<Connection> _connectionList;
protected readonly int _inputNeuronCount;
protected readonly int _outputNeuronCount;
protected readonly int _inputAndBiasNeuronCount;
protected readonly int _timestepsPerActivation;
protected readonly double[] _inputSignalArray;
protected readonly double[] _outputSignalArray;
readonly SignalArray _inputSignalArrayWrapper;
readonly SignalArray _outputSignalArrayWrapper;
public CyclicNetwork(List<Neuron> neuronList, List<Connection> connectionList, int inputNeuronCount, int outputNeuronCount, int timestepsPerActivation)
{
_neuronList = neuronList;
_connectionList = connectionList;
_inputNeuronCount = inputNeuronCount;
_outputNeuronCount = outputNeuronCount;
_inputAndBiasNeuronCount = inputNeuronCount + 1;
_timestepsPerActivation = timestepsPerActivation;
_inputSignalArray = new double[_inputNeuronCount];
_outputSignalArray = new double[_outputNeuronCount];
_inputSignalArrayWrapper = new SignalArray(_inputSignalArray, 0, _inputNeuronCount);
_outputSignalArrayWrapper = new SignalArray(_outputSignalArray, 0, outputNeuronCount);
}
public int OutputCount
{
get { return _outputNeuronCount; }
}
public SignalArray InputSignalArray
{
get { return _inputSignalArrayWrapper; }
}
public SignalArray OutputSignalArray
{
get { return _outputSignalArrayWrapper; }
}
public virtual void Activate()
{
for (int i = 0; i < _inputNeuronCount; i++)
{
_neuronList[i + 1].OutputValue = _inputSignalArray[i];
}
int connectionCount = _connectionList.Count;
int neuronCount = _neuronList.Count;
for (int i = 0; i < _timestepsPerActivation; i++)
{
for (int j = 0; j < connectionCount; j++)
{
Connection connection = _connectionList[j];
connection.OutputValue = connection.SourceNeuron.OutputValue * connection.Weight;
connection.TargetNeuron.InputValue += connection.OutputValue;
}
for (int j = _inputAndBiasNeuronCount; j < neuronCount; j++)
{
Neuron neuron = _neuronList[j];
neuron.OutputValue = neuron.Calculate(neuron.InputValue);
neuron.InputValue = 0.0;
}
}
for (int i = _inputAndBiasNeuronCount, outputIdx = 0; outputIdx < _outputNeuronCount; i++, outputIdx++)
{
_outputSignalArray[outputIdx] = _neuronList[i].OutputValue;
}
}
public virtual void ResetState()
{
for (int i = 1; i < _inputAndBiasNeuronCount; i++)
{
_neuronList[i].OutputValue = 0.0;
}
int count = _neuronList.Count;
for (int i = _inputAndBiasNeuronCount; i < count; i++)
{
_neuronList[i].InputValue = 0.0;
_neuronList[i].OutputValue = 0.0;
}
count = _connectionList.Count;
for (int i = 0; i < count; i++)
{
_connectionList[i].OutputValue = 0.0;
}
}
}
public class Connection
{
readonly Neuron _srcNeuron;
readonly Neuron _tgtNeuron;
readonly double _weight;
double _outputValue;
public Connection(Neuron srcNeuron, Neuron tgtNeuron, double weight)
{
_tgtNeuron = tgtNeuron;
_srcNeuron = srcNeuron;
_weight = weight;
}
public Neuron SourceNeuron
{
get { return _srcNeuron; }
}
public Neuron TargetNeuron
{
get { return _tgtNeuron; }
}
public double Weight
{
get { return _weight; }
}
public double OutputValue
{
get { return _outputValue; }
set { _outputValue = value; }
}
}
public class Neuron
{
readonly uint _id;
readonly NodeType _neuronType;
double _inputValue;
double _outputValue;
public Neuron(uint id, NodeType neuronType)
{
_id = id;
_neuronType = neuronType;
// Bias neurons have a fixed output value of 1.0
_outputValue = (NodeType.Bias == _neuronType) ? 1.0 : 0.0;
}
public double InputValue
{
get { return _inputValue; }
set
{
if (NodeType.Bias == _neuronType || NodeType.Input == _neuronType)
{
throw new Exception("Attempt to set the InputValue of bias or input neuron. Bias neurons have no input, and Input neuron signals should be passed in via their OutputValue property setter.");
}
_inputValue = value;
}
}
public double Calculate(double x)
{
return 1.0 / (1.0 + Math.Exp(-4.9 * x));
}
public double OutputValue
{
get { return _outputValue; }
set
{
if (NodeType.Bias == _neuronType)
{
throw new Exception("Attempt to set the OutputValue of a bias neuron.");
}
_outputValue = value;
}
}
}
public class SignalArray
{
readonly double[] _wrappedArray;
readonly int _offset;
readonly int _length;
public SignalArray(double[] wrappedArray, int offset, int length)
{
if (offset + length > wrappedArray.Length)
{
throw new Exception("wrappedArray is not long enough to represent the requested SignalArray.");
}
_wrappedArray = wrappedArray;
_offset = offset;
_length = length;
}
public double this[int index]
{
get
{
return _wrappedArray[_offset + index];
}
set
{
_wrappedArray[_offset + index] = value;
}
}
}
public enum NodeType
{
/// <summary>
/// Bias node. Output is fixed to 1.0
/// </summary>
Bias,
/// <summary>
/// Input node.
/// </summary>
Input,
/// <summary>
/// Output node.
/// </summary>
Output,
/// <summary>
/// Hidden node.
/// </summary>
Hidden
}
```
[Answer]
# PrioritizedRandomBot, Java
```
import java.util.Random;
public class PrioritizedRandomBot implements SnowballFighter {
static int RELOAD = 0;
static int THROW = 1;
static int DUCK = 2;
static Random rand = new Random();
public static void main(String[] args) {
int t = Integer.parseInt(args[0]);
int s = Integer.parseInt(args[1]);
int os = Integer.parseInt(args[2]);
int d = Integer.parseInt(args[3]);
int od = Integer.parseInt(args[4]);
int ms = Integer.parseInt(args[5]);
if (s > os + od) {
System.out.println(THROW);
return;
}
if (os == 0) {
if (s == ms || s > 0 && s == od && rand.nextInt(1001 - t) == 0) {
System.out.println(THROW);
} else {
System.out.println(RELOAD);
}
return;
}
if (os == ms && d > 0) {
System.out.println(DUCK);
return;
}
int r = rand.nextInt(os + od);
if (r < s) {
System.out.println(THROW);
} else if (r < s + d) {
System.out.println(DUCK);
} else {
System.out.println(RELOAD);
}
}
}
```
This bot selects a random integer in the range `0` to `os + od`, and then chooses to either throw, duck, or reload, with the thresholds determined by its current number of snowballs and ducks.
One thing that is important to realize, is that once one bot has more snowballs than the other bot has snowballs + ducks, then you can force a win. From this, we can come up with the concept of "points":
```
my points = s - os - od
op points = os - s - d
effects of moves on my points
OPPONENT
R T D
R L ++
M T W
E D - + +
```
If either of these numbers becomes positive, then that player is able to force a win.
```
points dif = p - op = 2*(s - os) + d - od
effects of moves on the difference in points (me - my opponent)
OPPONENT
R T D
R L +++
M T W -
E D --- +
points sum = p + op = - (d + od)
effects of moves on the sum of points (me + my opponent)
OPPONENT
R T D
R L +
M T W +
E D + + ++
```
The "difference in points" table forms the foundation of the game theory for this competition. It doesn't quite capture all information, but it does show how snowballs are fundamentally more valuable than ducks (as snowballs are both offense and defense). If the opponent throws a snowball and you successfully duck, then you are one step closer to a forcible victory, since your opponent used up a more valuable resource. This table also describes what you should do in a lot of the special cases, such as when certain move options are not available.
The "sum of points" table shows how, over time, the sum of points approaches zero (as both players run out of ducks), at which point the first player to make a mistake (reload when they didn't need to) immediately loses.
Now, let's try to extend this forcing strategy to cases where it's not actually forcible (as in, we're winning by a large margin but mind-reading on the part of the opponent will beat us). Basically, we have `s` snowballs but need to snowball our opponent `s+1` (or `s+2`, etc.) time consecutively to win. In this case, we want to either perform a few ducks or a few reloads to buy ourselves some time.
Right now, this bot always tries to sneak in some ducks, simply because then it doesn't risk an immediate loss: we assume that the opponent is following a similar strategy of lobbing as many snowballs as it can, so attempting to reload is really dangerous. Also, in order to prevent predictability, we want to sneak these in following a uniformly-random distribution: the probability of ducking is related to how many ducks we need to perform relative to the number of snowballs we need to throw.
If we are losing badly, in which case `s + d < os + od` then we need to sneak in some reloads in addition to using all of our ducks, in this case, we want to reload randomly, but only as many times as we need.
This is why our bots prioritizes in the order of throw, duck, and reload, and uses `os + od` to generate the random number, since that is the threshold number of moves that we need to make.
There is one edge case, and two other special cases, that the bot currently handles. The edge case is when the opponent has neither snowballs nor ducks, and so randomization doesn't work, so we throw if possible, otherwise we reload. One other special case is when the opponent cannot reload, and so there is no benefit to throwing (since the opponent will either duck or throw), so we always duck (since saving our snowballs is more valuable than saving our ducks). The final special case is if the opponent has no snowballs, in which case we play it safe and reload if possible.
[Answer]
# Save One, Python
Throws most of its snowballs immediately, but always saves one in case the opponent is watching for a lack of ammo. Then, it ducks as long as possible (again, saving 1) before reloading unless there is a guaranteed safe reload or guaranteed kill.
```
import sys
turn, snowballs, opponent_snowballs, ducks, opponent_ducks, max_snowballs = map(int, sys.argv[1:])
reload_snowball=0
throw=1
duck=2
if snowballs<=1:
if opponent_snowballs==0:
if opponent_ducks==0:
print throw
else:
print reload_snowball
elif ducks > 1:
print duck
else:
print reload_snowball
else:
print throw
```
[Answer]
# NeceBot - Python
Here's the game theory table for the game:
```
OPPONENT
R T D
R ~ L +D+S
M T W ~ +D-S
E D -D-S -D+S ~
```
Where `~` means no advantage, `W` is win, `L` is lose, `+-S` means a snowball is gained / lost over the opponent, and `+-D` means a duck is gained / lost over the opponent. This is a completely symmetrical game.
Note that my solution does not take that table into account. Because I'm bad at maths.
```
import sys
RELOAD = 0
THROW = 1
DUCK = 2
def main(turn, snowballs, opponent_snowballs, ducks, opponent_ducks, max_snowballs):
if 2 + ducks <3:
if 2 + snowballs <3:
return RELOAD
if 2 + opponent_ducks <3 or 2 + opponent_snowballs <3:
return THROW
return RELOAD
if 2 + snowballs <3:
if -opponent_snowballs <3 - 5 or 2 + abs(opponent_snowballs - 1) <3:
return DUCK
return RELOAD
if 2 + opponent_ducks <3 or 2 + abs(snowballs - max_snowballs) <3:
return THROW
if -snowballs <3 - 6 or turn % 5 <3:
return THROW
return DUCK
print(main(*map(int, sys.argv[1:])))
```
It's called the NeceBot because it tries to reduce what is necessary first. It has some arbitrary strategies after that, which I hope work.
[Answer]
## Coward - Scala
Throws, if opponent doesn't have any ammo, otherwise (in order of priority) ducks, throws or reloads.
```
object Test extends App {
val s = args(1).toInt
val os = args(2).toInt
val d = args(3).toInt
val move =
if(os == 0)
if(s > 0)
1
else
0
else if(d > 0)
2
else if(s > 0)
1
else
0
println(move)
}
```
[Answer]
# TheUglyDuckling - Python
Will always duck until it can't then tries to throw if the opponent is empty or reload if both are empty. Will use reload as a last resort.
```
import sys
arguments = sys.argv;
turn = int(arguments[1])
snowballs = int(arguments[2])
opponent_snowballs = int(arguments[3])
ducks = int(arguments[4])
opponent_ducks = int(arguments[5])
max_snowballs = int(arguments[6])
if ducks > 0:
print 2
elif opponent_snowballs == 0 and snowballs > 0:
print 1
elif opponent_snowballs == 0 and snowballs <= 0:
print 0
elif snowballs > 0:
print 1
elif snowballs <= 0:
print 0
```
[Answer]
# SimpleBot - Python 2
```
import sys
turn, snowballs, opponent_snowballs, ducks, opponent_ducks, max_snowballs = map(int, sys.argv[1:])
if opponent_snowballs > 0 and ducks > 0: print 2
elif snowballs: print 1
else: print 0
```
Simple stuff.
* If the opponent has snowballs and you have ducks, then you duck.
* If the opponent doesn't have snowballs and you have, then you throw.
* On any other case, you reload.
[Answer]
# The Naming-things-is-hard Bot - VB.NET
Naming things is hard, and I'm not sure I have a cohesive strategy to name it off of.
Tries to gamble the first few rounds to get an early victory. After that, plays safer the rest of the time, trying to win by attrition.
```
Module SnowballFight
Private Enum Action
Reload = 0
ThrowSnowball = 1
Duck = 2
End Enum
Sub Main(args As String())
Dim turn As Integer = args(0)
Dim mySnowballs As Integer = args(1)
Dim opponentSnowballs As Integer = args(2)
Dim myDucks As Integer = args(3)
Dim opponentDucks As Integer = args(4)
Dim maxSnowballs As Integer = args(5)
If mySnowballs = 0 AndAlso opponentSnowballs = 0 Then
' can't throw, no need to duck
Console.WriteLine(Action.Reload)
Exit Sub
End If
If turn = 2 AndAlso opponentSnowballs > 0 Then
' everyone will probably reload and then throw, so try and duck, and throw turn 3
Console.WriteLine(Action.Duck)
Exit Sub
End If
If turn = 3 AndAlso opponentSnowballs = 0 Then
' they threw on turn 2, get them!
Console.WriteLine(Action.ThrowSnowball)
Exit Sub
End If
If mySnowballs > 0 AndAlso opponentSnowballs = 0 Then
' hope they don't duck
Console.WriteLine(Action.ThrowSnowball)
Exit Sub
End If
If mySnowballs = 0 AndAlso opponentSnowballs > 0 Then
If myDucks > 0 Then
' watch out!
Console.WriteLine(Action.Duck)
Exit Sub
Else
' well, maybe we'll get lucky
Console.WriteLine(Action.Reload)
Exit Sub
End If
End If
If opponentSnowballs > 0 AndAlso myDucks > 5 Then
' play it safe
Console.WriteLine(Action.Duck)
Exit Sub
End If
If mySnowballs > 5 OrElse opponentDucks < 5 Then
' have a bunch saved up, start throwing them
Console.WriteLine(Action.ThrowSnowball)
Exit Sub
End If
' start saving up
Console.WriteLine(Action.Reload)
End Sub
End Module
```
[Answer]
# MachineGun, Python 3
Tries to save up snowballs until it's either guaranteed to kill the opponent, or until its out of ducks (In which case, it starts blindly firing all its snowballs, like a machine gun)
It also ducks whenever the opponent has a snowball, because it doesn't want to die.
```
from os import sys
args = sys.argv[1:]
turn = int(args[0])
snowballs = int(args[1])
opponent_snowballs = int(args[2])
ducks = int(args[3])
opponent_ducks = int(args[4])
max_snowballs = int(args[5])
if ducks > 0 and opponent_snowballs > 0:
print("2")
elif snowballs > 0 and opponent_snowballs == 0 and opponent_ducks == 0:
print("1")
elif ducks == 0 and snowballs > 0:
print("1")
elif snowballs < max_snowballs:
print("0")
elif snowballs == max_snowballs:
print("1")
else:
print("0")
```
[Answer]
# Knowbot, Python3
Keeps track frequency of previous moves, assumes opponent will make the most frequent one again, defends against that.
\*\* Updated to not expect moves opponent can't make \*\*
```
import sys,pickle
TURN,BALLS,OTHROWS,DUCKS,ODUCKS,MAXB,OLOADS = [i for i in range(7)]
def save_state(data,prob):
with open('snowball.pickle', 'wb') as f:
pickle.dump((data,prob), f)
def load_state():
with open('snowball.pickle', 'rb') as f:
return pickle.load(f)
def reload(data = None):
if not data or data[BALLS]<data[MAXB]:
print(0)
return True
return False
def throw(data):
if data[BALLS]>0:
print(1)
return True
return False
def duck(data):
if data[DUCKS]>0:
print(2)
return True
return False
data = [int(v) for v in sys.argv[1:]]
data.append(0)
if data[TURN] > 0:
last_data,prob = load_state()
delta = [l-n for l,n in zip(last_data, data)]
if delta[OTHROWS]<0:
delta[OTHROWS]=0
delta[OLOADS]=1
prob = [p+d for p,d in zip(prob,delta)]
else:
prob = [0]*7
expected = sorted(((prob[action],action) for action in [OTHROWS, ODUCKS, OLOADS]),
reverse=True)
expect = next( (a for p,a in expected if data[a]>0), OLOADS)
if expect == OTHROWS:
duck(data) or throw(data) or reload()
elif expect == ODUCKS:
reload(data) or duck(data) or throw(data) or reload()
else:
throw(data) or reload(data) or duck(data) or reload()
save_state(data,prob);
```
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), The Aggressor
```
<<?1:0
```
The aggressor is no coward! If he has a snowball, he shall throw! If he has no snowballs, he shall make more!
# [Braingolf](https://github.com/gunnerwolf/braingolf), The Insane
This isn't actually a bot, it's just a programmer whom I kidnapped and forced to port every project he's ever made over to braingolf. He no longer has a shred of sanity.
```
<3r!?:1+|%
```
Generates a random number less than 3, and outputs `t % r` where t is the current turn and r is the random number
To run these, you'll need to download `braingolf.py` from github, then either save the braingolf code to a file and run
```
python3 braingolf.py -f filename <space separated inputs>
```
or simply insert the code directly like this
```
python3 braingolf.py -c '<<?1:0' <space separated inputs>
```
The inputs are fairly irrelevant as long as the 2nd argument after the code/filename is the amount of snowballs The Aggressor has.
Note: The aggressor actually behaves identically to the TestBot, I just wanted to make an entry in braingolf
# [Braingolf](https://github.com/gunnerwolf/braingolf), The Brainy [Broken right now]
```
VR<<<!?v1:v0|R>!?v1:v0|>R<<!?v1:v0|>R<!?v1:v0|<VR<<.m<.m~v<-?~v0:~v1|>vc
VRv.<.>+1-?2_;|>.M<v?:0_;|1
```
[Answer]
# TestBot - Python
This is a test submission to show you what a valid submission may look like. The strategy: Alternate reloading and throwing. Quite a bad strategy but it gives you an idea of how your program should work.
```
from os import sys
arguments = sys.argv;
turn = int(arguments[1])
print(turn % 2)
```
[Answer]
# UpperHandBot, Python 3
```
import sys
turn, snowballs, opponent_snowballs, ducks, opponent_ducks, max_snowballs = map(int, sys.argv[1:])
if snowballs <= opponent_snowballs:
if opponent_snowballs > 0 and ducks > 0:
print(2)
else:
if snowballs < max_snowballs:
print(0)
else:
print(1)
else:
print(1)
```
This bot tries to collect more snowballs than its opponent, and at that point starts throwing. If at any point UHB doesn't have more snowballs than its opponent, it will:
* Duck, if the opponent has snowballs and it has ducks left
* Otherwise, reload (unless UHB is at the maximum, then it throws instead, although I don't think this situation would ever come up)
[Answer]
## Yggdrasli, Java
```
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Yggdrasil implements SnowballFighter {
public static boolean debug = false;
static int RELOAD = 0;
static int THROW = 1;
static int DUCK = 2;
static int INVALID = -3;
static Random rand = new Random();
public static void main(String[] args) {
int t = Integer.parseInt(args[0]);
int s = Integer.parseInt(args[1]);
int os = Integer.parseInt(args[2]);
int d = Integer.parseInt(args[3]);
int od = Integer.parseInt(args[4]);
int ms = Integer.parseInt(args[5]);
System.out.println((new Yggdrasil()).move(t, s, os, d, od, ms));
}
public final int move(int t, int s, int os, int d, int od, int ms) {
State state = State.get(s, os, d, od);
double val = state.val(4);
double[] strat = state.strat;
int move = INVALID;
if (debug) {
System.out.println(val + " : " + strat[0] + " " + strat[1] + " " + strat[2]);
}
while (move == INVALID) {
double r = rand.nextDouble();
if (r < strat[RELOAD] && strat[RELOAD] > 0.0001) {
move = RELOAD;
} else if (r < strat[RELOAD] + strat[THROW] && strat[THROW] > 0.0001) {
move = THROW;
} else if (r < strat[RELOAD] + strat[THROW] + strat[DUCK] && strat[DUCK] > 0.0001) {
move = DUCK;
}
}
return move;
}
public static class State {
public static boolean debug = false;
public static int ms = 50;
public int s;
public int os;
public static int md = 25;
public int d;
public int od;
public State(int s, int os, int d, int od) {
super();
this.s = s;
this.os = os;
this.d = d;
this.od = od;
}
Double val;
int valdepth;
double[] strat = new double[3];
public Double val(int maxdepth) {
if (s < 0 || s > ms || d < 0 || d > md || os < 0 || os > ms || od < 0 || od > md) {
return null;
} else if (val != null && valdepth >= maxdepth) {
return val;
}
if (s > os + od) {
val = 1.0; // force win
strat = new double[] { 0, 1, 0 };
} else if (os > s + d) {
val = -1.0; // force loss
strat = new double[] { 1.0 / (1.0 + s + d), s / (1.0 + s + d), d / (1.0 + s + d) };
} else if (d == 0 && od == 0) {
val = 0.0; // perfect tie
if (s > 0) {
strat = new double[] { 0, 1, 0 };
} else {
strat = new double[] { 1, 0, 0 };
}
} else if (maxdepth <= 0) {
double togo = 1 - s + os + od;
double otogo = 1 - os + s + d;
double per = otogo * otogo / (togo * togo + otogo * otogo);
double oper = togo * togo / (togo * togo + otogo * otogo);
val = per - oper;
} else {
Double[][] fullmatrix = new Double[3][3];
boolean[] vm = new boolean[3];
boolean[] ovm = new boolean[3];
for (int i = 0; i < 3; i++) {
int dest_s = s;
int dest_d = d;
if (i == 0) {
dest_s++;
} else if (i == 1) {
dest_s--;
} else {
dest_d--;
}
for (int j = 0; j < 3; j++) {
int dest_os = os;
int dest_od = od;
if (j == 0) {
dest_os++;
} else if (j == 1) {
dest_os--;
} else {
dest_od--;
}
if (i == 0 && j == 1 && dest_os >= 0 && dest_s <= ms) {
fullmatrix[i][j] = -1.0; // kill
} else if (i == 1 && j == 0 && dest_s >= 0 && dest_os <= ms) {
fullmatrix[i][j] = 1.0; // kill
} else {
fullmatrix[i][j] = get(dest_s, dest_os, dest_d, dest_od).val(maxdepth - 1);
}
if (fullmatrix[i][j] != null) {
vm[i] = true;
ovm[j] = true;
}
}
}
if (debug) {
System.out.println();
System.out.println(maxdepth);
System.out.println(s + " " + os + " " + d + " " + od);
for (int i = 0; i < 3; i++) {
System.out.print(vm[i]);
}
System.out.println();
for (int i = 0; i < 3; i++) {
System.out.print(ovm[i]);
}
System.out.println();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.printf(" %7.4f", fullmatrix[i][j]);
}
System.out.println();
}
}
// really stupid way to find an approximate best strategy
val = -1.0;
double[] p = new double[3];
for (p[0] = 0; p[0] < 0.0001 || vm[0] && p[0] <= 1.0001; p[0] += 0.01) {
for (p[1] = 0; p[1] < 0.0001 || vm[1] && p[1] <= 1.0001 - p[0]; p[1] += 0.01) {
p[2] = 1.0 - p[0] - p[1];
if (p[2] < 0.0001 || vm[2]) {
double min = 1;
for (int j = 0; j < 3; j++) {
if (ovm[j]) {
double sum = 0;
for (int i = 0; i < 3; i++) {
if (vm[i]) {
sum += fullmatrix[i][j] * p[i];
}
}
min = Math.min(min, sum);
}
}
if (min > val) {
val = min;
strat = p.clone();
}
}
}
}
if (debug) {
System.out.println("v:" + val);
System.out.println("s:" + strat[0] + " " + strat[1] + " " + strat[2]);
}
}
valdepth = maxdepth;
return val;
}
static Map<Integer, State> cache = new HashMap<Integer, State>();
static State get(int s, int os, int d, int od) {
int key = (((s) * 100 + os) * 100 + d) * 100 + od;
if (cache.containsKey(key)) {
return cache.get(key);
}
State res = new State(s, os, d, od);
cache.put(key, res);
return res;
}
}
}
```
I named this bot "Yggdrasil" because it actually looks ahead down the game tree and performs state valuation, from which it can compute an approximately-ideal mixed strategy. Because it relies on mixed strategies, it is *very* non-deterministic. I don't know how well this thing will do in real competition.
A few things about this bot:
* The core is a recursive function that calculation the value and near-ideal mixed strategy for any particular game state. Right now I have it set to look 4 steps ahead.
* It plays extremely drawish, as in a lot of cases this bot is equivalent to "picking a random move in rock-paper-scissors". It holds its ground and hopes that its opponent gives it a statistical advantage. If this bot were perfect (which it's not), the best you could do against it would be 50% wins and 50% losses. As a result, there is no opponent that it consistently beats, but also none it consistently loses to.
[Answer]
# Pain in the Nash (C++)
So called because the fact that I had to write my own Nash equilibrium solver was a real pain. I'm amazed that there aren't any readily-available Nash-solving libraries!
```
#include <fstream>
#include <iostream>
#include <vector>
#include <array>
#include <random>
#include <utility>
typedef double NumT;
static const NumT EPSILON = 1e-5;
struct Index {
int me;
int them;
Index(int me, int them) : me(me), them(them) {}
};
struct Value {
NumT me;
NumT them;
Value(void) : me(0), them(0) {}
Value(NumT me, NumT them) : me(me), them(them) {}
};
template <int subDimMe, int subDimThem>
struct Game {
const std::array<NumT, 9> *valuesMe;
const std::array<NumT, 9> *valuesThemT;
std::array<int, subDimMe> coordsMe;
std::array<int, subDimThem> coordsThem;
Game(
const std::array<NumT, 9> *valuesMe,
const std::array<NumT, 9> *valuesThemT
)
: valuesMe(valuesMe)
, valuesThemT(valuesThemT)
, coordsMe{}
, coordsThem{}
{}
Index baseIndex(Index i) const {
return Index(coordsMe[i.me], coordsThem[i.them]);
}
Value at(Index i) const {
Index i2 = baseIndex(i);
return Value(
(*valuesMe)[i2.me * 3 + i2.them],
(*valuesThemT)[i2.me + i2.them * 3]
);
}
Game<2, 2> subgame22(int me0, int me1, int them0, int them1) const {
Game<2, 2> b(valuesMe, valuesThemT);
b.coordsMe[0] = coordsMe[me0];
b.coordsMe[1] = coordsMe[me1];
b.coordsThem[0] = coordsThem[them0];
b.coordsThem[1] = coordsThem[them1];
return b;
}
};
struct Strategy {
std::array<NumT, 3> probMe;
std::array<NumT, 3> probThem;
Value expectedValue;
bool valid;
Strategy(void)
: probMe{}
, probThem{}
, expectedValue()
, valid(false)
{}
void findBestMe(const Strategy &b) {
if(b.valid && (!valid || b.expectedValue.me > expectedValue.me)) {
*this = b;
}
}
};
template <int dimMe, int dimThem>
Strategy nash_pure(const Game<dimMe, dimThem> &g) {
Strategy s;
int choiceMe = -1;
int choiceThem = 0;
for(int me = 0; me < dimMe; ++ me) {
for(int them = 0; them < dimThem; ++ them) {
const Value &v = g.at(Index(me, them));
bool valid = true;
for(int me2 = 0; me2 < dimMe; ++ me2) {
if(g.at(Index(me2, them)).me > v.me) {
valid = false;
}
}
for(int them2 = 0; them2 < dimThem; ++ them2) {
if(g.at(Index(me, them2)).them > v.them) {
valid = false;
}
}
if(valid) {
if(choiceMe == -1 || v.me > s.expectedValue.me) {
s.expectedValue = v;
choiceMe = me;
choiceThem = them;
}
}
}
}
if(choiceMe != -1) {
Index iBase = g.baseIndex(Index(choiceMe, choiceThem));
s.probMe[iBase.me] = 1;
s.probThem[iBase.them] = 1;
s.valid = true;
}
return s;
}
Strategy nash_mixed(const Game<2, 2> &g) {
// P Q
// p a A b B
// q c C d D
Value A = g.at(Index(0, 0));
Value B = g.at(Index(0, 1));
Value C = g.at(Index(1, 0));
Value D = g.at(Index(1, 1));
// q = 1-p, Q = 1-P
// Pick p such that choice of P,Q is arbitrary
// p*A+(1-p)*C = p*B+(1-p)*D
// p*A+C-p*C = p*B+D-p*D
// p*(A+D-B-C) = D-C
// p = (D-C) / (A+D-B-C)
NumT p = (D.them - C.them) / (A.them + D.them - B.them - C.them);
// P*a+(1-P)*b = P*c+(1-P)*d
// P*a+b-P*b = P*c+d-P*d
// P*(a+d-b-c) = d-b
// P = (d-b) / (a+d-b-c)
NumT P = (D.me - B.me) / (A.me + D.me - B.me - C.me);
Strategy s;
if(p >= -EPSILON && p <= 1 + EPSILON && P >= -EPSILON && P <= 1 + EPSILON) {
if(p <= 0) {
p = 0;
} else if(p >= 1) {
p = 1;
}
if(P <= 0) {
P = 0;
} else if(P >= 1) {
P = 1;
}
Index iBase0 = g.baseIndex(Index(0, 0));
Index iBase1 = g.baseIndex(Index(1, 1));
s.probMe[iBase0.me] = p;
s.probMe[iBase1.me] = 1 - p;
s.probThem[iBase0.them] = P;
s.probThem[iBase1.them] = 1 - P;
s.expectedValue = Value(
P * A.me + (1 - P) * B.me,
p * A.them + (1 - p) * C.them
);
s.valid = true;
}
return s;
}
Strategy nash_mixed(const Game<3, 3> &g) {
// P Q R
// p a A b B c C
// q d D e E f F
// r g G h H i I
Value A = g.at(Index(0, 0));
Value B = g.at(Index(0, 1));
Value C = g.at(Index(0, 2));
Value D = g.at(Index(1, 0));
Value E = g.at(Index(1, 1));
Value F = g.at(Index(1, 2));
Value G = g.at(Index(2, 0));
Value H = g.at(Index(2, 1));
Value I = g.at(Index(2, 2));
// r = 1-p-q, R = 1-P-Q
// Pick p,q such that choice of P,Q,R is arbitrary
NumT q = ((
+ A.them * (I.them-H.them)
+ G.them * (B.them-C.them)
- B.them*I.them
+ H.them*C.them
) / (
(G.them+E.them-D.them-H.them) * (B.them+I.them-H.them-C.them) -
(H.them+F.them-E.them-I.them) * (A.them+H.them-G.them-B.them)
));
NumT p = (
((G.them+E.them-D.them-H.them) * q + (H.them-G.them)) /
(A.them+H.them-G.them-B.them)
);
NumT Q = ((
+ A.me * (I.me-F.me)
+ C.me * (D.me-G.me)
- D.me*I.me
+ F.me*G.me
) / (
(C.me+E.me-B.me-F.me) * (D.me+I.me-F.me-G.me) -
(F.me+H.me-E.me-I.me) * (A.me+F.me-C.me-D.me)
));
NumT P = (
((C.me+E.me-B.me-F.me) * Q + (F.me-C.me)) /
(A.me+F.me-C.me-D.me)
);
Strategy s;
if(
p >= -EPSILON && q >= -EPSILON && p + q <= 1 + EPSILON &&
P >= -EPSILON && Q >= -EPSILON && P + Q <= 1 + EPSILON
) {
if(p <= 0) { p = 0; }
if(q <= 0) { q = 0; }
if(P <= 0) { P = 0; }
if(Q <= 0) { Q = 0; }
if(p + q >= 1) {
if(p > q) {
p = 1 - q;
} else {
q = 1 - p;
}
}
if(P + Q >= 1) {
if(P > Q) {
P = 1 - Q;
} else {
Q = 1 - P;
}
}
Index iBase0 = g.baseIndex(Index(0, 0));
s.probMe[iBase0.me] = p;
s.probThem[iBase0.them] = P;
Index iBase1 = g.baseIndex(Index(1, 1));
s.probMe[iBase1.me] = q;
s.probThem[iBase1.them] = Q;
Index iBase2 = g.baseIndex(Index(2, 2));
s.probMe[iBase2.me] = 1 - p - q;
s.probThem[iBase2.them] = 1 - P - Q;
s.expectedValue = Value(
A.me * P + B.me * Q + C.me * (1 - P - Q),
A.them * p + D.them * q + G.them * (1 - p - q)
);
s.valid = true;
}
return s;
}
template <int dimMe, int dimThem>
Strategy nash_validate(Strategy &&s, const Game<dimMe, dimThem> &g, Index unused) {
if(!s.valid) {
return s;
}
NumT exp;
exp = 0;
for(int them = 0; them < dimThem; ++ them) {
exp += s.probThem[them] * g.at(Index(unused.me, them)).me;
}
if(exp > s.expectedValue.me) {
s.valid = false;
return s;
}
exp = 0;
for(int me = 0; me < dimMe; ++ me) {
exp += s.probMe[me] * g.at(Index(me, unused.them)).them;
}
if(exp > s.expectedValue.them) {
s.valid = false;
return s;
}
return s;
}
Strategy nash(const Game<2, 2> &g, bool verbose) {
Strategy s = nash_mixed(g);
s.findBestMe(nash_pure(g));
if(!s.valid && verbose) {
std::cerr << "No nash equilibrium found!" << std::endl;
}
return s;
}
Strategy nash(const Game<3, 3> &g, bool verbose) {
Strategy s = nash_mixed(g);
s.findBestMe(nash_validate(nash_mixed(g.subgame22(1, 2, 1, 2)), g, Index(0, 0)));
s.findBestMe(nash_validate(nash_mixed(g.subgame22(1, 2, 0, 2)), g, Index(0, 1)));
s.findBestMe(nash_validate(nash_mixed(g.subgame22(1, 2, 0, 1)), g, Index(0, 2)));
s.findBestMe(nash_validate(nash_mixed(g.subgame22(0, 2, 1, 2)), g, Index(1, 0)));
s.findBestMe(nash_validate(nash_mixed(g.subgame22(0, 2, 0, 2)), g, Index(1, 1)));
s.findBestMe(nash_validate(nash_mixed(g.subgame22(0, 2, 0, 1)), g, Index(1, 2)));
s.findBestMe(nash_validate(nash_mixed(g.subgame22(0, 1, 1, 2)), g, Index(2, 0)));
s.findBestMe(nash_validate(nash_mixed(g.subgame22(0, 1, 0, 2)), g, Index(2, 1)));
s.findBestMe(nash_validate(nash_mixed(g.subgame22(0, 1, 0, 1)), g, Index(2, 2)));
s.findBestMe(nash_pure(g));
if(!s.valid && verbose) {
// theory says this should never happen, but fp precision makes it possible
std::cerr << "No nash equilibrium found!" << std::endl;
}
return s;
}
struct PlayerState {
int balls;
int ducks;
PlayerState(int balls, int ducks) : balls(balls), ducks(ducks) {}
PlayerState doReload(int maxBalls) const {
return PlayerState(std::min(balls + 1, maxBalls), ducks);
}
PlayerState doThrow(void) const {
return PlayerState(std::max(balls - 1, 0), ducks);
}
PlayerState doDuck(void) const {
return PlayerState(balls, std::max(ducks - 1, 0));
}
std::array<double,3> flail(int maxBalls) const {
// opponent has obvious win;
// try stuff at random and hope the opponent is bad
(void) ducks;
int options = 0;
if(balls > 0) {
++ options;
}
if(balls < maxBalls) {
++ options;
}
if(ducks > 0) {
++ options;
}
std::array<double,3> p{};
if(balls < balls) {
p[0] = 1.0f / options;
}
if(balls > 0) {
p[1] = 1.0f / options;
}
return p;
}
};
class GameStore {
protected:
const int balls;
const int ducks;
const std::size_t playerStates;
const std::size_t gameStates;
public:
static std::string filename(int turn) {
return "nashdata_" + std::to_string(turn) + ".dat";
}
GameStore(int maxBalls, int maxDucks)
: balls(maxBalls)
, ducks(maxDucks)
, playerStates((balls + 1) * (ducks + 1))
, gameStates(playerStates * playerStates)
{}
std::size_t playerIndex(const PlayerState &p) const {
return p.balls * (ducks + 1) + p.ducks;
}
std::size_t gameIndex(const PlayerState &me, const PlayerState &them) const {
return playerIndex(me) * playerStates + playerIndex(them);
}
std::size_t fileIndex(const PlayerState &me, const PlayerState &them) const {
return 2 + gameIndex(me, them) * 2;
}
PlayerState stateFromPlayerIndex(std::size_t i) const {
return PlayerState(i / (ducks + 1), i % (ducks + 1));
}
std::pair<PlayerState, PlayerState> stateFromGameIndex(std::size_t i) const {
return std::make_pair(
stateFromPlayerIndex(i / playerStates),
stateFromPlayerIndex(i % playerStates)
);
}
std::pair<PlayerState, PlayerState> stateFromFileIndex(std::size_t i) const {
return stateFromGameIndex((i - 2) / 2);
}
};
class Generator : public GameStore {
static char toDat(NumT v) {
int iv = int(v * 256.0);
return char(std::max(std::min(iv, 255), 0));
}
std::vector<Value> next;
public:
Generator(int maxBalls, int maxDucks)
: GameStore(maxBalls, maxDucks)
, next()
{}
const Value &nextGame(const PlayerState &me, const PlayerState &them) const {
return next[gameIndex(me, them)];
}
void make_probabilities(
std::array<NumT, 9> &g,
const PlayerState &me,
const PlayerState &them
) const {
const int RELOAD = 0;
const int THROW = 1;
const int DUCK = 2;
g[RELOAD * 3 + RELOAD] =
nextGame(me.doReload(balls), them.doReload(balls)).me;
g[RELOAD * 3 + THROW] =
(them.balls > 0) ? -1
: nextGame(me.doReload(balls), them.doThrow()).me;
g[RELOAD * 3 + DUCK] =
nextGame(me.doReload(balls), them.doDuck()).me;
g[THROW * 3 + RELOAD] =
(me.balls > 0) ? 1
: nextGame(me.doThrow(), them.doReload(balls)).me;
g[THROW * 3 + THROW] =
((me.balls > 0) == (them.balls > 0))
? nextGame(me.doThrow(), them.doThrow()).me
: (me.balls > 0) ? 1 : -1;
g[THROW * 3 + DUCK] =
(me.balls > 0 && them.ducks == 0) ? 1
: nextGame(me.doThrow(), them.doDuck()).me;
g[DUCK * 3 + RELOAD] =
nextGame(me.doDuck(), them.doReload(balls)).me;
g[DUCK * 3 + THROW] =
(them.balls > 0 && me.ducks == 0) ? -1
: nextGame(me.doDuck(), them.doThrow()).me;
g[DUCK * 3 + DUCK] =
nextGame(me.doDuck(), them.doDuck()).me;
}
Game<3, 3> make_game(const PlayerState &me, const PlayerState &them) const {
static std::array<NumT, 9> globalValuesMe;
static std::array<NumT, 9> globalValuesThemT;
#pragma omp threadprivate(globalValuesMe)
#pragma omp threadprivate(globalValuesThemT)
make_probabilities(globalValuesMe, me, them);
make_probabilities(globalValuesThemT, them, me);
Game<3, 3> g(&globalValuesMe, &globalValuesThemT);
for(int i = 0; i < 3; ++ i) {
g.coordsMe[i] = i;
g.coordsThem[i] = i;
}
return g;
}
Strategy solve(const PlayerState &me, const PlayerState &them, bool verbose) const {
if(me.balls > them.balls + them.ducks) { // obvious answer
Strategy s;
s.probMe[1] = 1;
s.probThem = them.flail(balls);
s.expectedValue = Value(1, -1);
return s;
} else if(them.balls > me.balls + me.ducks) { // uh-oh
Strategy s;
s.probThem[1] = 1;
s.probMe = me.flail(balls);
s.expectedValue = Value(-1, 1);
return s;
} else if(me.balls == 0 && them.balls == 0) { // obvious answer
Strategy s;
s.probMe[0] = 1;
s.probThem[0] = 1;
s.expectedValue = nextGame(me.doReload(balls), them.doReload(balls));
return s;
} else {
return nash(make_game(me, them), verbose);
}
}
void generate(int turns, bool saveAll, bool verbose) {
next.clear();
next.resize(gameStates);
std::vector<Value> current(gameStates);
std::vector<char> data(2 + gameStates * 2);
for(std::size_t turn = turns; (turn --) > 0;) {
if(verbose) {
std::cerr << "Generating for turn " << turn << "..." << std::endl;
}
NumT maxDiff = 0;
NumT msd = 0;
data[0] = balls;
data[1] = ducks;
#pragma omp parallel for reduction(+:msd), reduction(max:maxDiff)
for(std::size_t meBalls = 0; meBalls < balls + 1; ++ meBalls) {
for(std::size_t meDucks = 0; meDucks < ducks + 1; ++ meDucks) {
const PlayerState me(meBalls, meDucks);
for(std::size_t themBalls = 0; themBalls < balls + 1; ++ themBalls) {
for(std::size_t themDucks = 0; themDucks < ducks + 1; ++ themDucks) {
const PlayerState them(themBalls, themDucks);
const std::size_t p1 = gameIndex(me, them);
Strategy s = solve(me, them, verbose);
NumT diff;
data[2+p1*2 ] = toDat(s.probMe[0]);
data[2+p1*2+1] = toDat(s.probMe[0] + s.probMe[1]);
current[p1] = s.expectedValue;
diff = current[p1].me - next[p1].me;
msd += diff * diff;
maxDiff = std::max(maxDiff, std::abs(diff));
}
}
}
}
if(saveAll) {
std::ofstream fs(filename(turn).c_str(), std::ios_base::binary);
fs.write(&data[0], data.size());
fs.close();
}
if(verbose) {
std::cerr
<< "Expectations changed by at most " << maxDiff
<< " (RMSD: " << std::sqrt(msd / gameStates) << ")" << std::endl;
}
if(maxDiff < 0.0001f) {
if(verbose) {
std::cerr << "Expectations have converged. Stopping." << std::endl;
}
break;
}
std::swap(next, current);
}
// Always save turn 0 with the final converged expectations
std::ofstream fs(filename(0).c_str(), std::ios_base::binary);
fs.write(&data[0], data.size());
fs.close();
}
};
void open_file(std::ifstream &target, int turn, int maxDucks, int maxBalls) {
target.open(GameStore::filename(turn).c_str(), std::ios::binary);
if(target.is_open()) {
return;
}
target.open(GameStore::filename(0).c_str(), std::ios::binary);
if(target.is_open()) {
return;
}
Generator(maxBalls, maxDucks).generate(200, false, false);
target.open(GameStore::filename(0).c_str(), std::ios::binary);
}
int choose(int turn, const PlayerState &me, const PlayerState &them, int maxBalls) {
std::ifstream fs;
open_file(fs, turn, std::max(me.ducks, them.ducks), maxBalls);
unsigned char balls = fs.get();
unsigned char ducks = fs.get();
fs.seekg(GameStore(balls, ducks).fileIndex(me, them));
unsigned char p0 = fs.get();
unsigned char p1 = fs.get();
fs.close();
// only 1 random number per execution; no need to seed a PRNG
std::random_device rand;
int v = std::uniform_int_distribution<int>(0, 254)(rand);
if(v < p0) {
return 0;
} else if(v < p1) {
return 1;
} else {
return 2;
}
}
int main(int argc, const char *const *argv) {
if(argc == 4) { // maxTurns, maxBalls, maxDucks
Generator(atoi(argv[2]), atoi(argv[3])).generate(atoi(argv[1]), true, true);
return 0;
}
if(argc == 7) { // turn, meBalls, themBalls, meDucks, themDucks, maxBalls
std::cout << choose(
atoi(argv[1]),
PlayerState(atoi(argv[2]), atoi(argv[4])),
PlayerState(atoi(argv[3]), atoi(argv[5])),
atoi(argv[6])
) << std::endl;
return 0;
}
return 1;
}
```
Compile as C++11 or better. For performance, it's good to compile with OpenMP support (but this is just for speed; it's not required)
```
g++ -std=c++11 -fopenmp pain_in_the_nash.cpp -o pain_in_the_nash
```
---
This uses Nash equilibria to decide what to do on each turn, which means that *in theory* it will always win or draw in the long run (over many games), no matter what strategy the opponent uses. Whether that's the case in practice depends on whether I made any mistakes in the implementation. However, since this KoTH competition only has a single round against each opponent, it probably won't do very well on the leaderboard.
My original idea was to have a simple valuation function for each game state (e.g. each ball is worth +b, each duck is +d), but this leads to obvious problems figuring out what those valuations should be, and means it can't act on diminishing returns of gathering more and more balls, etc. So instead, this will analyse the *entire game tree*, working backwards from turn 1000, and fill in the actual valuations based on how each game could pan out.
The result is that I have absolutely no idea what strategy this uses, except for a couple of hard-coded "obvious" behaviours (throw snowballs if you have more balls than your opponent has balls+ducks, and reload if you're both out of snowballs). If anybody wants to analyse the dataset it produces I imagine there's some interesting behaviour to discover!
Testing this against "Save One" shows that it does indeed win in the long-run, but only by a small margin (514 wins, 486 losses, 0 draws in the first batch of 1000 games, and 509 wins, 491 losses, 0 draws in the second).
---
# Important!
This will work out-of-the-box, but that's not a great idea. It takes about 9 minutes on my moderately-developer-spec laptop to generate the full game tree. But it will save the final probabilities into a file once they're generated, and after that each turn is just generating a random number and comparing it against 2 bytes, so it's super-fast.
To shortcut all that, just [download this file](https://github.com/davidje13/snowball_koth_pitn/blob/master/nashdata_0.dat) (3.5MB) and put it in the directory with the executable.
Or you can generate it yourself by running:
```
./pain_in_the_nash 1000 50 25
```
Which will save one file per turn, until convergence. Note that each file is 3.5MB and it will converge at turn 720 (i.e. 280 files, ~1GB), and since most games don't get anywhere near turn 720, the pre-convergence files have very low importance.
[Answer]
# Swift - TheCrazy\_XcodeRandomness
Sadly, this can only be ran locally, in Xcode, because it contains the `Foundation` module and its function, `arc4random_uniform()`. However, you can pretty much tell what the algorithm is:
```
import Foundation
func game(turn: Int, snowballs: Int, opponent_snowballs: Int, ducks: Int, opponent_ducks: Int, max_snowballs: Int) -> Int{
let RELOAD = 0
let THROW = 1
let DUCK = 2
if turn == 0{
return arc4random_uniform(2)==0 ? THROW : DUCK
}
else if ducks == 0{
if snowballs != 0{return THROW}
else {return RELOAD}
}
else if snowballs < max_snowballs && snowballs != 0{
if opponent_ducks == 0 && opponent_snowballs == 0{return THROW}
else if opponent_snowballs == 0{
return arc4random_uniform(2)==0 ? THROW : RELOAD
}
else if opponent_ducks == 0{return THROW}
else { return arc4random_uniform(2)==0 ? THROW : RELOAD }
}
else if opponent_snowballs == max_snowballs{
return DUCK
}
else if snowballs == max_snowballs || opponent_ducks < 1 || turn < max_snowballs{return THROW}
return arc4random_uniform(2)==0 ? THROW : RELOAD
}
```
[Answer]
# TableBot, Python 2
Called TableBot because it was created by implementing this table:
```
snow duck osnow oduck move
0 0 0 0 0
0 0 0 1 0
0 0 1 0 0
0 0 1 1 0
0 1 0 0 0
0 1 0 1 0
0 1 1 0 2
0 1 1 1 2
1 0 0 0 1
1 0 0 1 1
1 0 1 0 1
1 0 1 1 1
1 1 0 0 1
1 1 0 1 1
1 1 1 0 1
1 1 1 1 1
```
A 1 represents having 1 or more, a 0 represents having none.
The bot:
```
import sys
reload=0
throw=1
duck=2
t,snowballs,o_snowballs,ducks,o_ducks,m=map(int,sys.argv[1:])
if snowballs > 0:
print throw
elif ducks==0:
print reload
elif o_snowballs==0:
print reload
else:
print duck
```
[Try it online!](https://tio.run/nexus/python2#@5@ZW5BfVKJQXFnMxVWUmpOfmGJrwFWSUZRfbmvIlVKanG1rxMVVolOcl1@elJiTU6yTH49gg@RBIhA61zY3sUAjMw@ourJYL7EovSza0CpWk4srM00BrkfBTsHAiouzoAioTgFsD1dqDlAB2AhbW4QcxDEQSSQ7sSopToWLgcz5/x8A "Python 2 – TIO Nexus")
[Answer]
# AmbBot - Racket Scheme
I mostly wanted to try out using `amb`, because it's cool. This bot randomly orders the options (reload, throw, and duck), filters out the ones that don't make sense, and picks the first option. But with `amb`, we get to use continuations and backtracking!
```
#lang racket
(require racket/cmdline)
; Defining amb.
(define failures null)
(define (fail)
(if (pair? failures) ((first failures)) (error "no more choices!")))
(define (amb/thunks choices)
(let/cc k (set! failures (cons k failures)))
(if (pair? choices)
(let ([choice (first choices)]) (set! choices (rest choices)) (choice))
(begin (set! failures (rest failures)) (fail))))
(define-syntax-rule (amb E ...) (amb/thunks (list (lambda () E) ...)))
(define (assert condition) (unless condition (fail)))
(define (!= a b)
(not (= a b)))
(define (amb-list list)
(if (null? list)
(amb)
(amb (car list)
(amb-list (cdr list)))))
; The meaningful code!
; Start by defining our options.
(define reload 0)
(define throw 1)
(define duck 2)
; The heart of the program.
(define (make-choice turn snowballs opponent_snowballs ducks opponent_ducks max_snowballs)
(let ((can-reload? (reload-valid? snowballs opponent_snowballs ducks opponent_ducks max_snowballs))
(can-throw? (throw-valid? snowballs opponent_snowballs ducks opponent_ducks max_snowballs))
(can-duck? (duck-valid? snowballs opponent_snowballs ducks opponent_ducks max_snowballs)))
(if (not (or can-reload? can-throw? can-duck?))
(random 3) ; something went wrong, panic
(let* ((ls (shuffle (list reload throw duck)))
(action (amb-list ls)))
(assert (or (!= action reload) can-reload?))
(assert (or (!= action throw) can-throw?))
(assert (or (!= action duck) can-duck?))
action))))
; Define what makes a move possible.
(define (reload-valid? snowballs opponent_snowballs ducks opponent_ducks max_snowballs)
(not (or
(= snowballs max_snowballs) ; Don't reload if we're full.
(and (= opponent_ducks 0) (= opponent_snowballs max_snowballs)) ; Don't reload if opponent will throw.
)))
(define (throw-valid? snowballs opponent_snowballs ducks opponent_ducks max_snowballs)
(not (or
(= snowballs 0) ; Don't throw if we don't have any snowballs.
(= opponent_snowballs max_snowballs) ; Don't throw if our opponent won't be reloading.
)))
(define (duck-valid? snowballs opponent_snowballs ducks opponent_ducks max_snowballs)
(not (or
(= ducks 0) ; Don't duck if we can't.
(= opponent_snowballs 0) ; Don't duck if our opponent can't throw.
)))
; Parse the command line, make a choice, print it out.
(command-line
#:args (turn snowballs opponent_snowballs ducks opponent_ducks max_snowballs)
(writeln (make-choice
(string->number turn)
(string->number snowballs)
(string->number opponent_snowballs)
(string->number ducks)
(string->number opponent_ducks)
(string->number max_snowballs))))
```
I also made a small test program to run two of these bots against each other. It feels like the second bot wins more often, so I may have made a mistake somewhere.
```
(define (run)
(run-helper 0 0 0 5 5 5))
(define (run-helper turn snowballs opponent_snowballs ducks opponent_ducks max_snowballs)
(printf "~a ~a ~a ~a ~a ~a ~n" turn snowballs opponent_snowballs ducks opponent_ducks max_snowballs)
(let ((my-action (make-choice turn snowballs opponent_snowballs ducks opponent_ducks max_snowballs))
(opponent-action (make-choice turn opponent_snowballs snowballs opponent_ducks ducks max_snowballs)))
(cond ((= my-action reload)
(cond ((= opponent-action reload)
(run-helper (+ turn 1) (+ snowballs 1) (+ opponent_snowballs 1) ducks opponent_ducks max_snowballs))
((= opponent-action throw)
(writeln "Opponent wins!"))
((= opponent-action duck)
(run-helper (+ turn 1) (+ snowballs 1) opponent_snowballs ducks (- opponent_ducks 1) max_snowballs))))
((= my-action throw)
(cond ((= opponent-action reload)
(writeln "I win!"))
((= opponent-action throw)
(run-helper (+ turn 1) (- snowballs 1) (- opponent_snowballs 1) ducks opponent_ducks max_snowballs))
((= opponent-action duck)
(run-helper (+ turn 1) (- snowballs 1) opponent_snowballs ducks (- opponent_ducks 1) max_snowballs))))
((= my-action duck)
(cond ((= opponent-action reload)
(run-helper (+ turn 1) snowballs (+ opponent_snowballs 1) (- ducks 1) opponent_ducks max_snowballs))
((= opponent-action throw)
(run-helper (+ turn 1) snowballs (- opponent_snowballs 1) (- ducks 1) opponent_ducks max_snowballs))
((= opponent-action duck)
(run-helper (+ turn 1) snowballs opponent_snowballs (- ducks 1) (- opponent_ducks 1) max_snowballs)))))))
```
[Answer]
# MonteBot, C++
I basically took the code from this [koth](https://codegolf.stackexchange.com/a/105175/32700) and modified it for this challenge. It uses the Decoupled UCT Monte Carlo Tree Search algorithm. It should be pretty close to the nash equilibrium.
```
#include <cstdlib>
#include <cmath>
#include <random>
#include <cassert>
#include <iostream>
static const int TOTAL_ACTIONS = 3;
static const int RELOAD = 0;
static const int THROW = 1;
static const int DUCK = 2;
//The number of simulated games we run every time our program is called.
static const int MONTE_ROUNDS = 10000;
struct Game
{
int turn;
int snowballs;
int opponentSnowballs;
int ducks;
int opponentDucks;
int maxSnowballs;
bool alive;
bool opponentAlive;
Game(int turn, int snowballs, int opponentSnowballs, int ducks, int opponentDucks, int maxSnowballs)
: turn(turn),
snowballs(snowballs),
opponentSnowballs(opponentSnowballs),
ducks(ducks),
opponentDucks(opponentDucks),
maxSnowballs(maxSnowballs),
alive(true),
opponentAlive(true)
{
}
Game(int turn, int snowballs, int opponentSnowballs, int ducks, int opponentDucks, int maxSnowballs, bool alive, bool opponentAlive)
: turn(turn),
snowballs(snowballs),
opponentSnowballs(opponentSnowballs),
ducks(ducks),
opponentDucks(opponentDucks),
maxSnowballs(maxSnowballs),
alive(alive),
opponentAlive(opponentAlive)
{
}
bool atEnd() const
{
return !(alive && opponentAlive) || turn >= 1000;
}
bool isValidMove(int i, bool me)
{
if (atEnd())
{
return false;
}
switch (i)
{
case RELOAD:
return (me ? snowballs : opponentSnowballs) < maxSnowballs;
case THROW:
return (me ? snowballs : opponentSnowballs) > 0;
case DUCK:
return (me ? ducks : opponentDucks) > 0 && (me ? opponentSnowballs : snowballs) > 0;
default:
throw "This should never be executed.";
}
}
Game doTurn(int my_action, int enemy_action)
{
assert(isValidMove(my_action, true));
assert(isValidMove(enemy_action, false));
Game result(*this);
result.turn++;
switch (my_action)
{
case RELOAD:
result.snowballs++;
break;
case THROW:
result.snowballs--;
if (enemy_action == RELOAD)
{
result.opponentAlive = false;
}
break;
case DUCK:
result.ducks--;
break;
default:
throw "This should never be executed.";
}
switch (enemy_action)
{
case RELOAD:
result.opponentSnowballs++;
break;
case THROW:
result.opponentSnowballs--;
if (my_action == RELOAD)
{
result.alive = false;
}
break;
case DUCK:
result.opponentDucks--;
break;
default:
throw "This should never be executed.";
}
return result;
}
};
struct Stat
{
int wins;
int attempts;
Stat() : wins(0), attempts(0) {}
};
/**
* A Monte tree data structure.
*/
struct MonteTree
{
//The state of the game.
Game game;
//myStats[i] returns the statistic for doing the i action in this state.
Stat myStats[TOTAL_ACTIONS];
//opponentStats[i] returns the statistic for the opponent doing the i action in this state.
Stat opponentStats[TOTAL_ACTIONS];
//Total number of times we've created statistics from this tree.
int totalPlays = 0;
//The action that led to this tree.
int myAction;
//The opponent action that led to this tree.
int opponentAction;
//The tree preceding this one.
MonteTree *parent = nullptr;
//subtrees[i][j] is the tree that would follow if I did action i and the
//opponent did action j.
MonteTree *subtrees[TOTAL_ACTIONS][TOTAL_ACTIONS] = { { nullptr } };
MonteTree(const Game &game) :
game(game), myAction(-1), opponentAction(-1) {}
MonteTree(Game game, MonteTree *parent, int myAction, int opponentAction) :
game(game), myAction(myAction), opponentAction(opponentAction), parent(parent)
{
//Make sure the parent tree keeps track of this tree.
parent->subtrees[myAction][opponentAction] = this;
}
//The destructor so we can avoid slow ptr types and memory leaks.
~MonteTree()
{
//Delete all subtrees.
for (int i = 0; i < TOTAL_ACTIONS; i++)
{
for (int j = 0; j < TOTAL_ACTIONS; j++)
{
auto branch = subtrees[i][j];
if (branch)
{
branch->parent = nullptr;
delete branch;
}
}
}
}
double scoreMove(int move, bool me)
{
const Stat &stat = me ? myStats[move] : opponentStats[move];
return stat.attempts == 0 ?
HUGE_VAL :
double(stat.wins) / stat.attempts + sqrt(2 * log(totalPlays) / stat.attempts);
}
MonteTree * expand(int myAction, int enemyAction)
{
return new MonteTree(
game.doTurn(myAction, enemyAction),
this,
myAction,
enemyAction);
}
int bestMove() const
{
//Select the move with the highest win rate.
int best;
double bestScore = -1;
for (int i = 0; i < TOTAL_ACTIONS; i++)
{
if (myStats[i].attempts == 0)
{
continue;
}
double score = double(myStats[i].wins) / myStats[i].attempts;
if (score > bestScore)
{
bestScore = score;
best = i;
}
}
return best;
}
};
int random(int min, int max)
{
static std::random_device rd;
static std::mt19937 rng(rd());
std::uniform_int_distribution<int> uni(min, max - 1);
return uni(rng);
}
/**
* Trickle down root until we have to create a new leaf MonteTree or we hit the end of a game.
*/
MonteTree * selection(MonteTree *root)
{
while (!root->game.atEnd())
{
//First pick the move that my bot will do.
//The action my bot will do.
int myAction;
//The number of actions with the same bestScore.
int same = 0;
//The bestScore
double bestScore = -1;
for (int i = 0; i < TOTAL_ACTIONS; i++)
{
//Ignore invalid or idiot moves.
if (!root->game.isValidMove(i, true))
{
continue;
}
//Get the score for doing move i. Uses
double score = root->scoreMove(i, true);
//Randomly select one score if multiple actions have the same score.
//Why this works is boring to explain.
if (score == bestScore)
{
same++;
if (random(0, same) == 0)
{
myAction = i;
}
}
//Yay! We found a better action.
else if (score > bestScore)
{
same = 1;
myAction = i;
bestScore = score;
}
}
//The action the enemy will do.
int enemyAction;
//Use the same algorithm to pick the enemies move we use for ourselves.
same = 0;
bestScore = -1;
for (int i = 0; i < TOTAL_ACTIONS; i++)
{
if (!root->game.isValidMove(i, false))
{
continue;
}
double score = root->scoreMove(i, false);
if (score == bestScore)
{
same++;
if (random(0, same) == 0)
{
enemyAction = i;
}
}
else if (score > bestScore)
{
same = 1;
enemyAction = i;
bestScore = score;
}
}
//If this combination of actions hasn't been explored yet, create a new subtree to explore.
if (!(*root).subtrees[myAction][enemyAction])
{
return root->expand(myAction, enemyAction);
}
//Do these actions and explore the next subtree.
root = (*root).subtrees[myAction][enemyAction];
}
return root;
}
/**
* Chooses a random move for me and my opponent and does it.
*/
Game doRandomTurn(Game &game)
{
//Select my random move.
int myAction;
int validMoves = 0;
for (int i = 0; i < TOTAL_ACTIONS; i++)
{
//Don't do idiotic moves.
//Select one at random.
if (game.isValidMove(i, true))
{
validMoves++;
if (random(0, validMoves) == 0)
{
myAction = i;
}
}
}
//Choose random opponent action.
int opponentAction;
//Whether the enemy has encountered this situation before
bool enemyEncountered = false;
validMoves = 0;
//Weird algorithm that works and I don't want to explain.
//What it does:
//If the enemy has encountered this position before,
//then it chooses a random action weighted by how often it did that action.
//If they haven't, makes the enemy choose a random not idiot move.
for (int i = 0; i < TOTAL_ACTIONS; i++)
{
if (game.isValidMove(i, false))
{
validMoves++;
if (random(0, validMoves) == 0)
{
opponentAction = i;
}
}
}
return game.doTurn(myAction, opponentAction);
}
/**
* Randomly simulates the given game.
* Has me do random moves that are not stupid.
* Has opponent do random moves.
*
* Returns 1 for win. 0 for loss. -1 for draw.
*/
int simulate(Game game)
{
while (!game.atEnd())
{
game = doRandomTurn(game);
}
if (game.alive > game.opponentAlive)
{
return 1;
}
else if (game.opponentAlive > game.alive)
{
return 0;
}
else //Draw
{
return -1;
}
}
/**
* Propagates the score up the MonteTree from the leaf.
*/
void update(MonteTree *leaf, int score)
{
while (true)
{
MonteTree *parent = leaf->parent;
if (parent)
{
//-1 = draw, 1 = win for me, 0 = win for opponent
if (score != -1)
{
parent->myStats[leaf->myAction].wins += score;
parent->opponentStats[leaf->opponentAction].wins += 1 - score;
}
parent->myStats[leaf->myAction].attempts++;
parent->opponentStats[leaf->opponentAction].attempts++;
parent->totalPlays++;
leaf = parent;
}
else
{
break;
}
}
}
int main(int argc, char* argv[])
{
Game game(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]));
MonteTree current(game);
for (int i = 0; i < MONTE_ROUNDS; i++)
{
//Go down the tree until we find a leaf we haven't visites yet.
MonteTree *leaf = selection(¤t);
//Randomly simulate the game at the leaf and get the result.
int score = simulate(leaf->game);
//Propagate the scores back up the root.
update(leaf, score);
}
int move = current.bestMove();
std::cout << move << std::endl;
return 0;
}
```
Compile Instructions for linux:
Save to `MonteBot.cpp`.
Run `g++ -o -std=c++11 MonteBot MonteBot.cpp`.
Command to run: `./MonteBot <args>`
[Answer]
# The [Procrastinator](http://waitbutwhy.com/2013/10/why-procrastinators-procrastinate.html) - Python 3
The procrastinator will procrastinate by playing save the first couple of turns.
Suddenly the panic monster wants to avoid loosing the resource war by countering the opponents most used move.
```
import sys
turn, snowballs, opponent_snowballs, ducks, opponent_ducks, max_snowballs = map(int, sys.argv[1:])
max_ducks = 25
times_opponent_ducked = max_ducks - ducks
times_opponent_thrown = (turn - times_opponent_ducked - opponent_snowballs) / 2
times_opponent_reloaded = times_opponent_thrown + opponent_snowballs
## return a different action, if the disiered one is not possible
def throw():
if snowballs:
return 1
else:
return duck()
def duck():
if ducks:
return 2
else:
return reload()
def reload():
return 0
def instant_gratification_monkey():
## throw, if you still have a ball left afterwards
if snowballs >= 2 or opponent_ducks == 0:
return throw()
## duck, if opponent can throw
elif opponent_snowballs > 0:
return duck()
## reload, if opponent has no balls and you have only one
else:
return reload()
def panic_monster():
## throw while possible, else reload
if times_opponent_reloaded > times_opponent_ducked:
if snowballs > 0:
return throw()
else:
return reload()
## alternating reload and duck
else:
if turn % 2 == 1:
return reload()
else:
return duck()
def procrastinator():
if turn < 13 or (snowballs + ducks > opponent_snowballs + opponent_ducks):
return instant_gratification_monkey()
else:
return panic_monster()
print(procrastinator())
```
[Answer]
# ParanoidBot and PanicBot - [ActionScript3](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/) ([RedTamarin](http://redtamarin.com/about))
From an unfitting, niche language (with extensions to provide command-line arguments) hails skittish ParanoidBot and his dull ally, PanicBot.
## ParanoidBot
ParanoidBot is losing its mind, and has a needlessly specific strategy to depend on. First, it launches snowballs until a threshold is reached, keeping some in reserve. Then, after three cautionary ducks, paranoia sets in, and the bot attempts to stockpile more snowballs in between random ducks. After replenishing its supply, ParanoidBot returns to blindly throwing. Due to the voices in its head, ParanoidBot can tell if it is guaranteed to win or lose, and will "strategize" accordingly.
```
import shell.Program;
import shell;
var TURN:int = Program.argv[0];
var SB:int = Program.argv[1];
var OPSB:int = Program.argv[2];
var DC:int = Program.argv[3];
var OPDC:int = Program.argv[4];
var MAXSB:int = Program.argv[5];
var usedDucks:int = 0;
if (!FileSystem.exists("data"))
FileSystem.write("data", 0);
else
usedDucks = FileSystem.read("data");
if (SB > OPSB + OPDC)
{ trace(1); Program.abort(); }
if (SB + DC < OPSB) {
if (DC > 0)
trace(2);
else if (SB > 0)
trace(1);
else
trace(0);
Program.abort(); }
if (usedDucks >= 3) {
if (SB > MAXSB / 3) {
usedDucks = 0;
FileSystem.write("data", usedDucks);
trace(1);
Program.abort();
}
else {
if (Number.random() > 0.5 && DC > 0)
trace(2);
else
trace(0);
}
}
else {
if (SB > (MAXSB / 6) && SB >= 3)
{ trace(1); Program.abort(); }
else {
usedDucks++;
FileSystem.write("data", usedDucks);
if (DC > 0)
trace(2);
else if (SB > 0)
trace(1);
else
trace(0);
Program.abort();
}
}
```
Braces are a little wonky to help condense size
## PanicBot
Having already gone insane, PanicBot reacts out of instinctual fear. After running out of ducks from cowering in fear, PanicBot blindly throws all of its snowballs, then desperately makes and throws more snowballs until (probably) defeated.
```
import shell.Program;
var SB:int = Program.argv[1];
var DC:int = Program.argv[3];
if (DC > 0)
{ trace(2); Program.abort(); }
if (SB > 0)
{ trace(1); Program.abort(); }
else
{ trace(0); Program.abort(); }
```
---
This is one of less than 15 other entries using AS3 here on PPCG. One day, perhaps this arguably exotic language will find a puzzle to dominate.
[Answer]
# Defender, Python
Reloads when neither player has snowballs. If it has snowballs, it throws. If it doesn't have snowballs, but the opponent does, it ducks if it can, otherwise reloads.
```
def get_move(turn, snowballs, opponent_snowballs, ducks, opponent_ducks, max_snowballs):
if snowballs == opponent_snowballs == 0:
return 0 #Reload
elif snowballs > 0:
return 1 # Throw
elif ducks > 0:
return 2 # Duck
else:
return 0 # Reload
if __name__ == "__main__": # if this is the main program
import sys
print(main(*[int(arg) for arg in sys.argv[1:]]))
```
Note: not tested yet
] |
[Question]
[
I have an ASCII-art box and I need a program to open it.
## Examples
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
# Specification
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position.
[Answer]
## JavaScript ES6, 57 bytes
```
s=>s[r="replace"](/-+/,s=>s[r](/-/g,`
$'/`))[r](/-/g,' ')
```
Outputs a leading newline. Works by taking the row of `-`s and converting them into a triangle, then replacing the `-`s with spaces.
Edit: Saved 5 bytes thanks to @edc65.
[Answer]
# Pyth, ~~16~~ 14 bytes
```
j+_m+*;d\/Uz.z
```
Explanation
```
m Uz - [V for d in range(len(input()))]
+*;d\/ - " "*d + "/"
_ - ^[::-1]
j+ .z - "\n".join(^+rest_of_input())
```
Thanks [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for new algorithm!
[Try it here.](http://pyth.herokuapp.com/?code=j%2B_m%2B*%3Bd%5C%2FUz.z&input=-------%0A|+++++|%0A|_____|&debug=0)
[Answer]
# [pb](https://esolangs.org/wiki/pb) (NONCOMPETING), 125 bytes
```
^w[B!0]{>}w[B!45]{<w[B=10]{t[T+1]b[0]}}v[X]vw[T!0]{vb[124]<[X]b[124]>w[B=0]{>}t[T-1]}w[X!1]{<b[95]}<w[B!0]{^}w[Y!-1]{b[47]>^}
```
The version of pbi that you need to run this answer is newer than the question. It would have worked in older versions except that I never got around to allowing newlines in input. Oh well.
First, this determines the height of the box by counting newlines in the input. Once it knows that, it goes to the Y location of the right side of the box, goes down to where it needs to be and draws the walls and floor, finishing with the lid.
Check out this fun animation!
![](https://i.stack.imgur.com/VkaWF.gif)
The long pause is the brush going over the input.
**Ungolfed:**
```
^w[B!0]{>} # Go to the end of the input
w[B!45]{< # Head left until hitting a hyphen
w[B=10]{ # For each newline on the way:
t[T+1] # Count it
b[0] # Delete it
}
}
v[X] # Move down as far as it is right + the number of \n
v # ...plus one
w[T!0]{ # While the counting variable is nonzero:
vb[124] # Go down and draw a pipe
<[X]b[124] # Draw a pipe on the left as well
>w[B=0]{>} # Go back to the right side
t[T-1] # Decrement variable
}
w[X!1]{<b[95]} # Draw the bottom of the box
<w[B!0]{^} # Go up the left wall
w[Y!-1]{b[47]>^} # Go up and right, drawing the lid
```
[Answer]
# Retina, ~~34~~ 20 bytes
```
-(?=(-*))¶?
$1/¶
-
```
In the first step every `-` is substituted with the `-`'s following it, a `/` and a newline. The newline at the end of the original first line is deleted. In the second step we change the new `-`'s to spaces which results in the desired output.
[Try it online here.](http://retina.tryitonline.net/#code=LSg_PSgtKikpwrY_CiQxL8K2Ci0KIA&input=LS0tLS0tLQp8ICAgICB8CnxfX19fX3w)
[Answer]
# CJam, 14 bytes
```
l,{N'/@S*}%W%q
```
[Try it online!](http://cjam.tryitonline.net/#code=bCx7TicvQFMqfSVXJXE&input=LS0tLS0tLQp8ICAgICB8CnxfX19fX3w)
### How it works
```
l Read the first line from STDIN.
, Compute the line's length. Result: L
{ }% Map; for each I in [0 ... L-1]:
(implicit) Push I.
N Push a linefeed.
'/ Push a slash.
@ Rotate I on top of the stack.
S* Turn I into a string of I spaces.
W% Reverse the resulting array of strings and characters.
q Read the remaining input from STDIN.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 14 ~~15~~ bytes
```
' /'jnXyPQ)`jt
```
Input should have a trailing newline.
[**Try it online!**](http://matl.tryitonline.net/#code=JyAvJ2puWHlQUSlganQ&input=LS0tLS0tLQp8ICAgICB8CnxfX19fX3wKCgo)
### Explanation
```
' /' % push string (will be indexed into to generate the open lid)
jn % read first line of input and push its length
Xy % identity matrix with that size
P % flip vertically
Q % add 1. Now the matrix contains 1 and 2, to be used as indices
) % index into string. Produces a 2D char array for the lid
` % do-while loop
j % push input line
t % duplicate. Truthy if nonempty
% implicitly end loop. The loop condition is the top of the stack,
% that is, the input line that has just been read.
% This is truthy if non-empty; and in that case another line will
% be read in the next iteration.
% implicitly display stack contents, bottom to top
```
[Answer]
# Japt, ~~28~~ ~~26~~ ~~25~~ ~~22~~ ~~18~~ 17 bytes
```
Ur-@"
{SpUa- -Y}/
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VXItQFIrU3BVYS0gLVkgKycv&input=Ii0tLS0tLS0KfCAgICAgfAp8X19fX198Ig==)
Outputs a leading newline, which is acceptable according to the OP.
### How it works
```
Ur-@ // Replace each hyphen X in the input and its index Y with this function:
" // Start a string that contains a newline.
{ } // Insert here:
Ua- -Y // Take the index of the last hyphen in the input, subtract Y,
Sp // and return that many spaces.
/ // Finish off the string with a slash.
```
This would be 4 bytes shorter if the hinge is allowed to be on the right edge of the box:
```
Ur-@"
{SpY}\\
```
[Answer]
# JavaScript (ES6), 66
```
b=>([a,t]=b.split`-
`,[...a+0].map(_=>(t=l+`/
`+t,l+=' '),l=''),t)
```
**TEST**
```
f=b=>([a,t]=b.split`-\n`,[...a+0].map(_=>(t=l+`/\n`+t,l+=' '),l=''),t)
var box = `-------
| |
|_____|`
console.log=x=>O.textContent=x
console.log(f(box))
```
```
<pre id=O></pre>
```
[Answer]
# Java 8, ~~158~~ 118 bytes
This is just a start, but hey, FGITWFTW.
```
n->{String o="";int z=n.lastIndexOf("-"),i=z;for(;i-->0;o+="/\n")for(int y=i;y-->0;o+=" ");return o+n.substring(z+2);}
```
Expects input as a string, returns the box.
[Answer]
# Bash, ~~85~~ ~~84~~ 79 characters
(Pure Bash version, no external commands used.)
```
r(){
a="${a/-
/
$s/
}"
s+=\
[[ $a = -* ]]&&r
}
mapfile a
r
IFS=
echo "${a[*]}"
```
Outputs a leading newline.
Sample run:
```
bash-4.3$ bash open-the-box.sh <<< $'-------\n| |\n|_____|'
/
/
/
/
/
/
/
| |
|_____|
```
[Answer]
## **Perl, 61 54 33 + 3 = 36 characters**
```
s^-^" "x(length$')."/\n"^ge&chomp
```
Run it as
```
perl -ple 's^-^" "x(length${chr 39})."/\n"^ge&chomp' closed_box_file
```
Each `-` in first line is replaced by a string that is a result of concatenation of some number of , `/` and `\n`. `${chr 39}` evaluates to perl's (in)famous `$'` aka `$POSTMATCH` special variable. Lastly, chomp gets rid of the trailing newline character that was added for the last `-` character.
Thanks to @manatwork for saving 7 + more characters.
**Bonus** - `s^-^" "x$i++."\\\n"^ge&&chop` opens the box from the right edge in 29 + 3 characters :). Run it as:
```
gowtham@ubuntu:~$ cat a
----
| |
|__|
gowtham@ubuntu:~$ perl -plE 's^-^" "x$i++."\\\n"^ge&&chop' closed_box_file
\
\
\
\
| |
|__|
```
[Answer]
## Pyth, ~~26~~ 23 bytes
```
jXK.z0jm+*\ t-lhKd\/lhK
```
Yuck. Can definitely be shorter; still working on it.
[Answer]
# Python 3, 1̶7̶0̶ 88 bytes
Here is my short(er) code:
EDIT: Now 82 bytes Shorter With @Dennis 's Code Edit!
```
f=open('f.txt')
d=len(f.readline())-1
a=f.read()
while d:d-=1;print(' '*d+'/')
print(a)
```
# Python 3, 421 bytes
Alternatively, just for fun, you could use one that opens it slowly:
```
import time
import os
f = open('f.txt', 'r')
e = f.readline()
a = f.read()
d = len(e)
c = 0
t = e + a
g = ''
clear = lambda: os.system('cls')
while c <= d - 1:
clear()
print(("\n" * ((d - 1) - (c))) + t)
c += 1
e1 = e[0:(d - c) -1]
e2 = e[(d - c):len(e)]
e1 += '/'
e2 = ' ' * len(e2)
y = (' ' * len(e1)) + '/' + '\n'
g += y
t = (g + e1 + e2 + '\n' + a)[d:len(g + e1 + e2 + '\n' + a)]
time.sleep(0.2)
f.close()
```
To use either, you must create a text file in the same directory containing an ascii box of any width or depth called 'f.txt'. It will then open that box.
[Answer]
# Python3, 76 bytes
```
f=open(0)
w=len(f.readline())
while w:w-=1;print(' '*w+'/')
print(f.read())
```
1. Get the length of the first input line.
2. Print lines of `/` preceded by a decreasing number of spaces.
3. Push the rest of `stdin` straight to `stdout`.
EDIT: I've just noticed that my code is almost identical to @Dennis' comment edit of @Monster's shorter Python3 code, the only difference being print the remainder of `stdin` directly instead of store it in a variable. Great minds!
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~6~~ 4 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
jL/o
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjRBJXVGRjJDJXVGRjBGJXVGRjRG,i=JTYwJTYwJTYwJTBBLS0tLS0tLSUwQSU3QyUyMCUyMCUyMCUyMCUyMCU3QyUwQSU3QyUyMCUyMCUyMCUyMCUyMCU3QyUwQSU3Q19fX19fJTdDJTBBJTYwJTYwJTYw,v=6)
Explanation:
```
j remove 1st line of the input
L get the width of the remaining input
/ push a diagonal of that size
o and output that diagonal
and implicitly output the remaining input
```
[Answer]
# Python 2, 100 bytes
```
def o(b):
m=b.split('\n')[1:]
print"\n".join(["/".rjust(i)for i in range(len(m[0]),0,-1)]+m)
```
Defines a function `o` that takes a string as its input. (Full program wasn't specified in the question).
[Answer]
## PowerShell, 55 bytes
```
$d,$b=$args-split"`n";($d.length-1)..0|%{" "*$_+"/"};$b
```
Takes input `$args` as a string, `-split`s on newlines ``n` ([reference link](https://technet.microsoft.com/en-us/library/hh847835.aspx)), stores the first line into `$d` (as a string) and the remaining into `$b` (as an array of strings). We then loop from the `length` of the first line (minus 1) to `0` and each iteration output that number of spaces plus a `/`. Finally, output `$b` (the rest of the input string) which by default will output one per line.
### Example Run
```
PS C:\Tools\Scripts\golfing> .\help-me-open-the-box.ps1 "----`n| |`n|__|"
/
/
/
/
| |
|__|
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
a=>a[b="replace"](/-+/,c=>c[b](d=/-/g,`
$'/`))[b](d,' ')
```
[Try it online!](https://tio.run/##JctBCoMwEEDRfU4RpJCEJs4JxouINOMYpSUYiaWr3D1qfcsP/0M/2jm/t69b0xTqjJWwo37EJoctEodm0OCeYBk77sdBTwgOFuvFQ4E35p@skspUTuueYmhjWvSsvbuJIi9FlNelnE89AA "JavaScript (Node.js) – Try It Online")
Should be written as a comment of **@Neil**'s [answer](https://codegolf.stackexchange.com/a/70655/82328) but I can't create comments yet
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 bytes
```
g'/1.Λ|»»
```
[Try it online! (legacy-only)](https://tio.run/##MzBNTDJM/f8/XV3fUO/c7JpDuw/t/v9fFwK4ahRAoIarJh4EagA "05AB1E (legacy) – Try It Online")
### How it works
```
g'/1.Λ|»» – Full program. Takes input from STDIN.
g - Length. Only takes the first line into account.
'/ – Push a slash character, "/".
1.Λ – And diagonally up-right, draw a line of slashes of the given length.
|» – Push the remaining inputs (all other lines) joined on newlines.
» – Then join the stack on newlines.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal/wiki), 14 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page)
```
↙L§⪪θ¶⁰M→✂⪪θ¶¹
```
[Try it online (verbose)](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJb88zyc1rUTHJzUvvSRDw7HEMy8ltUIjuCAns0SjUEcpJk9JU8dAU1OTyze/LFXDKigzPaNEkys4JzM5FU2Voeb//9FKSkq6EMBVowACNVw18SBQA5SJ/a9blgMA) or [try it online (pure)](https://tio.run/##S85ILErOT8z5//9R28z3e9YcWv5o1apzOw5te9S44f2etY/aJj2a0wQVOrTz//9oJSUlXQjgqlEAgRqumngQqAHKxAIA).
**Explanation:**
Split the input by newlines, take the length of the first line, and print a line of that length from the Top-Right to Down-Left:
```
Print(:DownLeft,Length(AtIndex(Split(q,"\n"),0)))
↙L§⪪θ¶⁰
```
Move once to the right:
```
Move(:Right)
M→
```
Split the input by newlines again, and remove the first item, and print what's left implicitly:
```
Slice(Split(q,"\n"),1)
✂⪪θ¶¹
```
(NOTE: Putting the input split by newlines in a variable (since I do it twice above) is ~~1 byte longer~~ also 14 bytes by using a slightly different method (thanks to *@Neil*):
`≔⮌⪪θ¶θ↙L⊟θM→⮌θ` [Try it online (verbose)](https://tio.run/##Pcy9CsMgGIXh3asQp08wN5BMhY4phHRsQwnhqwqi8Qe7eO/GUNpnPS9nU2vY3GpqvcSopYUZM4aIcN@NTuAFZU/LOBfU84FMQdsE/dV97IjvJOiIViYFk9vBc96Km8sI/aylSv/@d9mKodYHY6z7IoWeCimvU2nLUrtsDg) or [try it online (pure)](https://tio.run/##S85ILErOT8z5//9R55RH63oerVp1bsehbed2PGqb@X7Pmkdd88/teL9n7aO2SUDJczv@/49WUlLShQCuGgUQqOGqiQeBGqBMLAA)).
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 16 bytes
```
L:£(&‹¥\/꘍,)□Ḣ⁋,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=L%3A%C2%A3%28%26%E2%80%B9%C2%A5%5C%2F%EA%98%8D%2C%29%E2%96%A1%E1%B8%A2%E2%81%8B%2C&inputs=----%0A%7C%20%20%7C%0A%7C__%7C&header=&footer=)
[Answer]
# JavaScript ES6, 106 bytes
```
q=>(q=q.split`
`,n=q[0].length,eval('for(i=0,r="";i<n;i++)r+=" ".repeat(n-i-1)+"/\\n"'),r+q.slice(1).join`
`)
```
Simple enough: getting the length of the first line, creating a spaced-triangle with trailing `/`, and adding that to the original, sliced and joined.
## Test it out! (ES6 only `:(`)
```
F=q=>(q=q.split`
`,n=q[0].length,eval('for(i=0,r="";i<n;i++)r+=" ".repeat(n-i-1)+"/\\n"'),r+q.slice(1).join`
`)
function n(){q.innerHTML=F(o.value)}
o.onkeydown=o.onkeyup=o.onchange=o.onkeypress=n;
n();
```
```
*{font-family:Consolas,monospace;}textarea{width:100%;height:50%;}#q{white-space:pre;}
```
```
<textarea id=o>----
| |
|__|</textarea><div id=q>
```
[Answer]
## Python 2.7, ~~120~~ 122 chars
Needs a file `f` with the original/closed box, output is the opened one. Cheers to @Monster for the idea... will try to figure out multi-line input later and see if it's shorter.
```
for l in open('f').readlines():
if l[1]==('-'):
for x in range(1,len(l)):print(' '*(len(l)-x+1)+'/')
else:print l[:-1]
```
**Edit**
* just noticed that the leftmost `/` has a space in front; +2 bytes
[Answer]
# Ruby, 59 characters
(57 characters code + 2 characters command line options.)
```
s=""
$_=$_.chars.map{(s<<" ")[1..-1]+?/}.reverse*$/if$.<2
```
Sample run:
```
bash-4.3$ ruby -ple 's="";$_=$_.chars.map{(s<<" ")[1..-1]+?/}.reverse*$/if$.<2' <<< $'-------\n| |\n|_____|'
/
/
/
/
/
/
/
| |
|_____|
```
[Answer]
## Bash, 129 characters
Requires a file called `a` with the closed box, outputs to stdout.
```
for i in $(seq `cat a|awk 'NR==1{print length($1)-1}'` -1 1);{ for j in `seq 1 $i`;{ printf " ";};echo "/";};echo "/";tail -n2 a
```
It might be possible to make it shorter by using `sed` and using stdin and piping.
[Answer]
# PHP, 127 characters
```
$s=$argv[1];$l=strlen(strtok($s,"\n"));for($i=0;$i<$l;$i++)$s=preg_replace("/-/","\n".str_repeat(" ",$l-$i-1)."/",$s,1);echo$s;
```
Ungolfed version :
```
$s=$argv[1];
$l=strlen(strtok($s,"\n"));
for($i=0;$i<$l;$i++){
$v="\n".str_repeat(" ",$l-$i-1)."/";
$s=preg_replace("/-/",$v,$s,1);
}
echo $s;
```
[Answer]
# Python, 125 bytes (110 without box)
```
i="\n---\n| |\n|_|"
l,b,r=i.count("-"),i.split('\n'),range
for x in r(1,l):print" "*(l-x)+"/"
for x in r(2,len(b)):print b[x]
```
If anyone has any idea how to shorten it, please let me know!
[Answer]
# Awk, ~~47~~ 46 characters
(44 characters code + 2 characters command line option.)
```
/-/{OFS=RS;for(i=NF;i;i--){$i=s"/";s=s" "}}1
```
Sample run:
```
bash-4.3$ awk -F '' '/-/{OFS=RS;for(i=NF;i;i--){$i=s"/";s=s" "}}1' <<< $'-------\n| |\n|_____|'
/
/
/
/
/
/
/
| |
|_____|
```
[Answer]
# Gema, ~~51~~ ~~49~~ 31 characters
```
-\P/-+/=@subst{-=\\ ;$1}/\n
-=/
```
Sample run:
```
bash-4.3$ gema -e '-\P/-+/=@subst{-=\\ ;$1}/\n;-=/' <<< $'-------\n| |\n|_____|'
/
/
/
/
/
/
/
| |
|_____|
```
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), 18 bytes
```
{(" /"@|=#*x),1_x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpDSUFfyaHGVlmrQlPHML6i9n@ahpIuBChxKSgo1SiAQA2EHQ8CNUqa/wE "K (ngn/k) – Try It Online")
] |
[Question]
[
As input you will receive
* An integer \$a\$
* A list of integers that is *infinite* and *strictly-monotonic*1.
Your program should check **in finite time** if \$a\$ appears the list.
You should output one of two distinct values. One if \$a\$ appears in the list and the other if \$a\$ does not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored by their length in bytes with fewer bytes being better.
---
You may take an infinite lists in any of the following formats:
* A list, stream, iterator or generator if your language allows them to be infinite.
* A function or pointer to a function that outputs the next value when queried with no input.
* A function or pointer to a function that outputs the \$n\$th value when passed \$n\$ as an input.
Additionally you may repeatedly query STDIN with the assumption that each query will provide the next term in the sequence.
---
## Test cases
Since I cannot put infinite lists in the body of a challenge I will provide the first couple terms along with a description of the list and a definition in Haskell.
```
6
1 2 3 4 5 6 7 8 9 10 ... (positive integers) l=[1..]
=>
True
```
---
```
6
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 ... (negative integers) l=[-1,-2..]
=>
False
```
---
```
109
0 2 4 6 8 10 12 14 16 18 20 ... (non-negative even integers) l=[0,2..]
=>
False
```
---
```
-5
200 199 198 197 196 195 194 193 192 ... (integers smaller than 201) l=[200,199..]
=>
True
```
---
```
256
1 2 3 5 8 13 21 34 55 89 144 ... (unique Fibonacci numbers) l=1:2:zipWith(+)l(tail l)
=>
False
```
---
```
1
1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 ... (integers less than 2) l=[1,0..]
=>
True
```
1: A strictly monotonic sequence is either entirely increasing or entirely decreasing. This means if you take the differences between consecutive elements they will all have the same sign.
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
Takes as input the target integer \$a\$, and a lambda function \$g\$. Since the list is always either strictly increasing or decreasing, we only need to check if \$a\$ appears in the next \$ |a-g(0)|+1 \$ numbers.
```
lambda a,g:a in map(g,range(abs(a-g(0))+1))
```
[Try it online!](https://tio.run/##bY9BCsIwEEX3nuKDm8SmkFQUFN16ApdupjatgTYtaQtx49VrClIjuJuZvHl/0j2HR2uzqTzfppqavCCQqI4EY9FQxyrhyFaaUd4zSismOU8U51PnjB1Qsr3AZ80f4ZFAcaxxdaNerf4yLz8DF6r7iFDy8OvZIPuDpbuYyqRECv/NK02OcwQomDK4TqHQwYPwznxYCepkaRRf9Fsp5vESDFbou9PU6wJDi61EMeq5GsjUcPo@ut60lkf/ED/x0XXTGw "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
t#l@(a:r)=t==a||(a<t)==(l<r)&&t#r
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0Q5x0Ej0apI07bE1jaxpkYj0aZE09ZWI8emSFNNrUS56H9uYmaegq1CSr5CQVFmXolCtEKmgrJCtLGOqZ5erEINkGejqxBtoKdnGasQy6UAByiqzbGq/g8A "Haskell – Try It Online")
[Answer]
# [convey](http://xn--wxa.land/convey/), ~~[144](https://codegolf.stackexchange.com/revisions/216260/1)~~ 92 bytes
```
v<<<<<<<<<<<
>; >">>??>=@]
"">>,<1[v)>#,
v}^>)?:`(#>#^
v{^"9>v]^",^
>;@">>@`"#^
1>0 >>>^
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiIHY8PDw8PDw8PDw8PFxuPjsgID5cIj4+Pz8+PUBdXG5cIlwiPj4sPDFbdik+IyxcbnZ9Xj4pPzpgKCM+I15cbnZ7XlwiOT52XV5cIixeXG4+O0BcIj4+QGBcIiNeXG4xPjAgICA+Pj5eIiwidiI6MSwiaSI6IjUgMyA0IDYgNyA4IDkgMTAgMTEgMTIgMTMgMTQgMTUgMTYgMTcgMTggMTkgMjAgMjEgMjIgMjMgMjQgMjUgMjYgMjcgMjggMjkgMzAgMzEgMzIgMzMgMzQgMzUgMzYgMzcgMzggMzkgNDAgNDEgNDIgNDMgNDQgNDUgNDYgNDcgNDggNDkgNTAgNTEgNTIgNTMgNTQgNTUgNTYgNTcgNTggNTkgNjAgNjEgNjIgNjMgNjQgNjUgNjYgNjcgNjggNjkgNzAgNzEgNzIgNzMgNzQgNzUgNzYgNzcgNzggNzkgODAgODEgODIgODMgODQgODUgODYgODcgODggODkgOTAgOTEgOTIgOTMgOTQgOTUgOTYgOTcgOTggOTkgMTAwIDEwMSAxMDIgMTAzIDEwNCAxMDUgMTA2In0=)
[![Gif](https://i.stack.imgur.com/KeYmp.gif)](https://i.stack.imgur.com/KeYmp.gif)
Input is given as a list of integers with the first integer being the goal and the remaining being the list. Since there is no way to accept infinite input, this program instead only consumes a prefix of the input. You can see this in that there is a very long relay line to stop additional input.
### Explanation
To start we need to split the first element off the input, to be used. To do this I use a simple switch, and because we want to use the input a bunch I feed it into a sort of generating vortex to continuously pump out new copies.
[![Explanation 0](https://i.stack.imgur.com/uiWsj.gif)](https://i.stack.imgur.com/uiWsj.gif)
Now we split the main stream in two, and calculate the differences on one of the parts. This will tell us if the list is ascending or descending.
[![Explanation 1 (Ascending)](https://i.stack.imgur.com/2Wu8a.gif)](https://i.stack.imgur.com/2Wu8a.gif)
[![Explanation 1 (Descending)](https://i.stack.imgur.com/FDXNp.gif)](https://i.stack.imgur.com/FDXNp.gif)
Now we use the difference stream to redirect the main stream, to the two different comparison sites. If the list is ascending we want to go until the element is greater than or equal to n if it is descending we want to go until it is less than or equal to n.
[![Explanation 2](https://i.stack.imgur.com/wE4ZL.gif)](https://i.stack.imgur.com/wE4ZL.gif)
So that stream coming out now will give us some ones and then at some point switch to zeros. What we are concerned about is the first number that gives a zero. We want to know if it is equal to n. So we create another stream and get whether that is equal to n.
[![Explanation 3](https://i.stack.imgur.com/P8Csw.gif)](https://i.stack.imgur.com/P8Csw.gif)
At this point I'm going to stop with the gifs, since they really look like the end product mostly. We redirect the streams with each other, discarding all the elements before the comparison starts giving zero. Then we use a lock to grab just the first equality. We output this and send a signal to stop taking input. With no input the machine slowly winds down and halts.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 61 bytes
```
def f(l,v):
a=l()
while(a-v)*(b:=a-l())>0:a-=b
return a==v
```
[Try it online!](https://tio.run/##bY7BbsMgDIbvPIWPsEEFnTptkeirILOQFolAxki2Pn3mRDtU2w6WrO@zf3u6tWvJTy9TXdc@DDDwJBfRMUCbuGDweY0pcFSLeOC@s6iIirPuUFnPoIY210yzdlkvNuHoewQK6Cjm4FwOX805CYtgbKhlhNhCbaWkD4jjVGqDtzLnxth2ec7xfQ5uiJ5v9wHBgqcy1O9fgNkwCblzLwEf/U5uMaQekLGpxtz4he@x3AgJz0L8ospIUP8rLeFIwujXP@qo9c@aOt3J@6dp@USZ6zc "Python 3.8 (pre-release) – Try It Online")
Input is a function that returns the next value on every call and an integer.
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~70~~ 69 bytes
1 byte shorter thanks to @JonathanAllan.
```
def g(l,v):
a=next(l)
while(a-v)*(b:=a-next(l))>0:a-=b
return a==v
```
[Try it online!](https://tio.run/##bY5BDsIgEEX3nGKWoJBAjUab4FUMWNqSIFSk1Z6@0qYLoy4mmbyXP3@6MbXB745dnKbK1NBgRwdSIlDSm1fCjiB4ttYZrNhANliXUrHVkDMvFZMaQTSpjz5n5DDVMdzAJhNTCO4B9taFmOAaep8Qmit6b@@9udRW47kIFEjQeUTelyoQM86CLlxTUFu9kNEaV4FCqIvWJ9zg5SwWhMKBkC/KBAX2X3EKRRaCn35UwfkaY/sP@fl0Du/zzekN "Python 3.8 (pre-release) – Try It Online")
Input is a generator and an integer, can probably be shorter with one of other input formats.
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
a#k@(b:c)|k>c=(-a)#map(0-)k|b<a=a#c|1>0=b>a
```
[Try it online!](https://tio.run/##BcFLCoAgEADQw@jCgSaUFlGkdI9oMUqQ@EnKpXe39276whVj78TCLuzqoAXjtEAClqgIiRCa3UgTc00Zqa2hnshnXV6fK89P5QLnBdiBasBpHM/@Aw "Haskell – Try It Online")
This outputs `False` if the integer is present and `True` if it is not although I have added a `not` to the handler because that sort of output is confusing to me.
---
## Explanation
The first check we do is `k>c`, that is whether the input is greater than its own tail. Since this list is strictly monotonic the heads of these lists cannot be equal so `k>c` is a short way of comparing their heads. This check thus tells us whether the first element is larger than the second and by extension whether the input is decreasing. If the input is decreasing we negate everything to make it increasing
```
(-a)#map(0-)k
```
The next check is whether `b<a`, that is the head of the list is less than the thing we are looking for. If it is then we should find `a` later in the list so we discard `b` and go again
```
a#c
```
If that fails then `a<=b` meaning that either `b` is `a` or `b` should come before `a`. Since `b` is the first element we know that the only way for `a` to be present is for it to be `b`. Thus we halt returning
```
b>a
```
Which is a shorter way of writing `b/=a` since we know already that `b>=a`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~47~~ ~~44~~ ~~43~~ 42 bytes
```
read m
sed 1$[(m-($1))**2]q\;i$m|grep ^$1$
```
[Try the test suite online!](https://tio.run/##rdJtT4JQGAbg7/yKe8kciiRQsoXipu5obIUV6JdetgOe1E3QUFtb9NsJI1n50pzrfDvbc86u3c/t0vko9ugC9Vk4HYbUR612QrrtkzhkdACfm7MBFP5e8CWBVwqFYlF9fHmojnk/GoZshide4eNknuO8kT8dYCm@4fsnjsPXycEhtoOcouOma5uO2ScwLYd0yJ1dgkPDIVtgHCzYkIXQuOdpCEEIDKVaDUSxUEh@eAfzRlPwQfUDEU7La6qGOsoD9loOlpMJkM@nc064ZIii9NKmkznbpKg6LNJpHEqRVhZJWln@nXKWULqWlHFIn1j7TYp8kankVUCG@pcqGT/Wda5nClwR24Zz2bCgysqWSapkJFWW10ntI0mVY0UVHT3LvO0RtM1m12q0Wias3nVzV05qReNoUiGkMnfVJs@gJWq4JVc0vB9AdxOYvD2SyGu7Q9te46@Wp83av8SDNfEn "Bash – Try It Online")
*3 bytes off thanks to user41805's pointing out that a single `sed` could be used to replace both the `echo` and the `head`.*
*1 more byte thanks to user41805 again.*
*And now 1 more from user41805.*
The target integer (the integer \$a\$ in the challenge description) is passed as an argument, and the infinite list is read from stdin. (The challenge says: "Additionally you may repeatedly query STDIN with the assumption that each query will provide the next term in the sequence.")
The output is the program's exit code (0 for truthy, 1 for falsey).
---
**Explanation:**
The program reads the first number in the infinite list into \$m\$.
Let \$a\$ be the target integer that we're looking for (it's `$1` in the program). In principle we need to check, after \$m\$, at most \$\left| m-a \right|\$ additional values in the infinite list, because we're starting at \$m\$ and either going up by at least 1 for each number in the list or going down by at least 1 for each number in the list.
However, the program actually checks (more than) \$(m-a)^2\$ additional values. That's OK, because \$(m-a)^2\ge\left|m-a\right|\$. We may be checking additional (unnecessary) values, but that's harmless.
The original version checked exactly \$(m-a)^2\$ additional numbers (using `head`). Unfortunately, replacing `head -${n}` with `sed -${n}q` doesn't work if the value of `n` is 0, so we need to enlarge the number of items checked. To do this, I simply prepend a `1` to the number (which takes one fewer byte than adding 1 to it).
The golfing benefit in doing all this is that, in bash, squaring a number requires fewer bytes than taking the absolute value of a number (as far as I can see).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
D¥нdiIë(I(}.i
```
-1 byte thanks to *@Grimmy*.
05AB1E has infinite lists, but no functions. So it assumes the infinite list is already at the top of the stack. Assuming this is [allowed for stack-based languages according to the meta](https://codegolf.meta.stackexchange.com/a/8493/52210), but it explicitly mentions functions, so not sure how to handle it here.
Alternatively, the infinite list can be put in a pre-defined variable (i.e. `X`), in which case this would be 15 bytes with that `X` as additional leading byte.
[Try it online](https://tio.run/##yy9OTMpM/a/kmVdQWlJspaBk72mvpJCYlwJkcT3qmKfB5RJyaDFQ6FHbJKDQf5dDSy/sTcn0PLxaw1OjVi/zv85/MwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF9pr6SQmJcCZHE96pinAMQaIMLm0HYFIwNDIEsXxD3cmnZomYIRiKvJ5Xd4hUvIocVAjY/aJgE1/nc5tPTC3pTMysOrNSo1avUy/@v8jzbTMdMxNLDU0TXVMTIFMmMB). The second line of the header contains the infinite list(s). In the output the first 10 values are printed as example sublist, so you know which infinite list was used in the program.
**Explanation:**
05AB1E has a builtin to check if an integer is in an infinite list that is guaranteed to be non-decreasing, which is `.i`. Using that builtin, we have the following program:
```
D # Duplicate the infinite list at the top of the stack
¥ # Take it's deltas / forward-differences
н # Pop and push the first difference of this list
di # If it's non-negative:
I # Simply push the input-integer
ë # Else (it's negative):
( # Negate all values in the infinite list
I( # Push the input-integer, and negate it as well
} # After the if-else, where we now have a non-decreasing infinite list
.i # Check if the (possibly negative) input we pushed is inside this infinite list
# (after which the result is output implicitly)
```
Note that this approach only works because the infinite list is guaranteed to be either only increasing or only decreasing. With an infinite list that is both (i.e. \$a(n) = \left\lfloor10\tan(n)\right\rfloor\$ → `[0, 15, -22, -2, 11, -34, -3, 8, -68, -5, ...]`), this approach of course wouldn't work.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~20~~ ~~17~~ ~~16~~ 9 bytes
Takes `a` on STDIN, then a list of values on STDIN.
**Edit:** Wow, under 10 bytes now! Really shows how powerful Pyth is :P
```
}Q+JEmEaJ
```
[Try it online!](https://tio.run/##DcyrDcQwAARRPq1EK3n9dwEhYVfCsZBIASEHrnbHdJ409@855/x/tmO/9u8xpwox4IE7brjigjNOOGLjwKDTqBQyiVUJyCiihDLroYoa6mgsCi8 "Pyth – Try It Online")
Port of @dingledooper's [Python answer](https://codegolf.stackexchange.com/a/203008/58563).
```
}Q+JEmEaJ
Q # Initialize Q to be the first input from STDIN
JE # Initialize J to be the next input from STDIN
}Q # Return true if Q is in:
+ # The union of
JE # - the first element of the sequence
mEaJ(Q) # - abs(J-Q) more inputs from STDIN (Q appended implicitly)
```
---
**8 bytes**, if we can return the index of `a` in the list
```
x+JEmEaJ
```
[Try it online!](https://tio.run/##Dcy7DYQwAATRfFpBK3n9dwEkdEF2yUkEBFC9cTpPmuu9f3M@27H/9/OYU4UY8MAdN1xxwRknHLFxYNBpVAqZxKoEZBRRQpn1UEUNdTQWhQ8 "Pyth – Try It Online")
```
x+JEmEaJ
x (Q) # Find index of Q in:
+ # The union of:
JEmEaJ(Q) # J and the next abs(J-Q) elements
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 21 bytes
```
{|/x=y'!1+|/-:\x-y.0}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qu0a+wrVRXNNSu0de1iqnQrdQzqOXiSos2szbUjgXTuoa6IIahgaW1kRaIpWtqbWRgABW0rlaJrrAxtDa0zo+u0DWK1QZRhrGxtbEK+grFqSUKJfkKRqZmCoklCpX5pUUK+eV5CkWZxdmKQN3GBtZAswF81CU7)
## Explanation
*x* is number, *y* is function representing infinite list.
* `1+|/-:\x-y.0` equivalent to `1 + abs(x - y(0))`
* `!` range
* `y'` apply *y* to each element
* `|/x=` find *x*
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 33 bytes
```
(@:k\-abs:r;0:g;{(k=g+:g;}r*;r!g+
```
[Try it online!](https://tio.run/##DcbdCkAwAAbQV/ncyVI@Mz9bynvgAmWJos2dPPs4V8eex@oXt113UD2RQ6KAQokKNRowAwnmoAQLUIElWI0h7vQ@pNPstTOZtuaJ99aKP69LjIusCOED "GolfScript – Try It Online")
This is a very, very quick and dirty way of doing this problem.
TL;DR
Check if the first number is the number we're looking for. If not, then find the difference between our number (finite) and the first number (finite) to get the maximum number of elements we need to search (finite). This is a clusterfuck, clumsy, and messy, but it does the job adequately. There's probably a builtin I'm missing, but I'll come back to this later to refine it and to make code short enough worthy of an explanation.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
NθNηNζW›Π⁻⟦θη⟧ζ⁰Nζ№⟦ηζ⟧θ
```
[Try it online!](https://tio.run/##XcuxCsIwGATg/Z4iY36IYJLWKh0dxEHpXhxqLaQQWxMThb58zChdDr7jrjed7@fOpnSeXjFc4/M@eO6oxr/Nykv214x2YPzkhy7kqvHzI/aBX8YpvnnrBDM3wRYiwbZEbP1u/DgFfpxjztbkYR47ojolVe4goaBRYg@poSR0gTLrAFkUUFpDV1XafOwP "Charcoal – Try It Online") Link is to verbose version of code. Reads each value as a separate line on STDIN and outputs `-` only if `a` appears in the monotonic list. Explanation:
```
Nθ
```
Input `a`.
```
NηNζ
```
Input the first two terms of the list.
```
W›Π⁻⟦θη⟧ζ⁰
```
Repeat while the last term of the list so far lies between `a` and the first term.
```
Nζ
```
Read another term from the list.
```
№⟦ηζ⟧θ
```
Output `-` if `a` is the first term or the term just read.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->a,g{[]!=[a]&(0..a*a+g[0]**2).map(&g)}
```
[Try it online!](https://tio.run/##RYzLCsMgEEX3/Yp2I4lGUSGFEsYfERcjNNJFIDQtTAn21y150eU9nHOf7/gpPRTpsEmzDxfwGFillUKOInkdOLe1GnCsWKpzGc@9vzbS0UzC5HD67y/t0@jbJnC7E9muwGotD8m2W4UQwXTkDGOkXo/hPi1IRMDc4XG4mmZpyw8 "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes[SBCS](https://en.wikipedia.org/wiki/SBCS)
```
{⍵∊⍺⍺⍳1+|⍵-⍺⍺1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHHV2PeneB0WZD7RqgiC6Eb1j7P94zLy0zL7Mk1SezuMQ3NTcptag4I7NA4VHbBAUCerm4UstS8yAqjQ5PB0oBhR71TQUJgGVwmW1MlCoTLq681PTEksyyVM@8ktR0oDDELl0UmzDU4DLPiGQdBiTrOLTe@D8A "APL (Dyalog Unicode) – Try It Online") Uses [dingledooper's idea](https://codegolf.stackexchange.com/a/203008/75323).
```
{ } ⍝ Operator accepting function on the left and integer on the right
⍺⍺ ⍝ Apply the input function to
⍳ ⍝ the range of integers from 1 to
1+ ⍝ 1 plus
| ⍝ the absolute value of
⍵- ⍝ the input number minus
⍺⍺1 ⍝ the first value of the input function.
⍵∊ ⍝ Finally check if the input number is in that list.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes
```
α¬>£0å
```
[Try it online!](https://tio.run/##yy9OTMpM/f@oY56RFpeSZ15BaUmxlYKSvUvIocX2SgqJeSlAjqcLkGlrB2T9P7fx0Bq7Q4sNDi/9r/Pf0MASAA "05AB1E – Try It Online") or [verify all test cases](https://tio.run/##yy9OTMpM/V/G9ahjngIQa4AIm0PbFYwMDIEsXRD3cGvaoWUKRiCupt/hFVxKnnkFpSXFVgpK9i4hhxbbKykk5qUAOZUuQKatHZD1/9zGQ2vsDi02OLz0v87/aDMdMx1DA0sdXVMdI1MgMxYA).
Takes the infinite list input via the stack, like [Kevin's 05AB1E answer](https://codegolf.stackexchange.com/a/203032/6484).
```
α # absolute difference of the number with each element of the infinite list
# this list contains 0 iff the original list contains the number
¬ # get the first element
> # increment
£ # get the first n elements, where n = first element + 1
0å # check if 0 is in those elements
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes
```
#2@Range@Abs[#-#2@0]~MemberQ~#&
```
Port of dingledooper's python 2 solution.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78X277X9nIISgxLz3VwTGpOFpZF8g1iK3zTc1NSi0KrFNW@x9QlJlXEu2Yl@LgUM2lUB5tpqOgrKAWq2BrqxBSVJqqAxXThQm6JeYUQ0QNDSx1FIyAqnWBJLqkrilQzsAQKIdhmpEp0Dy3zKT8vMTk5MxoZQVtBcNYTNNBZqPq5qqN/Q8A "Wolfram Language (Mathematica) – Try It Online")
Other similar attempts:
```
⌊#⌋==#&&#>=1&@InverseFunction[#2]@#&
```
and:
```
Tr[1^Solve[#2@x==#,x,PositiveIntegers]]==1&
```
# 9 bytes
Mathematica doesn't have iterators or generators in the same way python does, but Regions and Domains take their place. If you allow Regions as an equivalent,
```
{#}∈#2&
```
just tests if the 1d point of the first argument is in the Region. RAW (Rules as written) don't allow Regions, so I'm going to leave the port as the main answer.
[Try it online!](https://tio.run/##bY/BTsJAFEX3/AZJo9ixZaRNMNbgQhN2ou4mYzKMrzCxnYGZV2xSuuc7@ZHasDBguz057757c4FryAUqKRpImmpYHw@HIfWaV6s0sif9NZtVA2CxP883mZIK32CljGblYzL2q7LmPEk@bAF@r/SQkD/rRWTupI3DaU9a6HnPO9ALVvLOBYl6kmkY/i9Ao06FuUZYgV2w961FFpWf9GbC@X7f5aTlF5@vRmvEjbsPAodCfpsd2DQzP7fS5MG2AIdtvgvo5I7G8TTAFhCVEkF0kS/BEuVIqpZGCynV6Po0vG/F@YZBzZtf "Wolfram Language (Mathematica) – Try It Online")
The best solution is just Mathematica's built-in `Element` over a domain, but Domains do not seem to be able to be defined by the users, only the premade handful exist.
[Answer]
# [Desmos](https://desmos.com/calculator), 41 bytes
```
f(k)=∑_{n=0}^{(k-g(0))^2}0^{(g(n)-k)^2}
```
Because Desmos does not support infinite lists and does not support functions as arguments, the input list should be represented as a function named `g`.
Pretty much a port of dingledooper's [Python answer](https://codegolf.stackexchange.com/a/203008/96039), except I replaced absolute value with square because that is golfier.
[Try It On Desmos!](https://www.desmos.com/calculator/xjeqajjyiq)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/pydv8xfr3c)
[Answer]
# JavaScript (ES7), 49 bytes
*Using [@dingledooper's method](https://codegolf.stackexchange.com/a/203008/58563)*
Takes input as `(integer)(generating_function)`. Returns \$0\$ or \$1\$.
```
n=>g=>(F=k=>k*k>(g(0)-n)**2?0:g(k)-n?F(k+1):1)(0)
```
[Try it online!](https://tio.run/##bc7BCoMwDAbg@54ix6SuoxUcTGi9@R7OqbhKqnPsuFfvKrqTXvpTvpD8z@pTzfWrH9@S/aMJrQlsbGcslsYZ64Sz2KEiySREWqi8Qxc/RYku0ZRrihZqz7MfmsvgO2zxSshgLDAkoIlOx/rlHWl12zAFAXuX2Z@VAnkwkGZxe9vfPRhAPsMYU59hWoLWSgUsHtfIRcZYcYpBkMdn12c7p9dj4Qc "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 54 bytes
Takes input as `(integer)(generating_function)`. Returns a Boolean value.
```
n=>g=>(F=k=>(v=g(k),g(1)>g(0)?v<n:v>n)?F(k+1):v)(0)==n
```
[Try it online!](https://tio.run/##bY7BDoIwDIbvPkWPrTizkWAioePGeyDCgpDOiNnRV8cZ0Qsc2qT/1/b/b3Wop@bR359K/LWdO56FrWOLFQ@xB3Y40MGhIetQUxkKyYMVKiscEkN5oKgyy9x4mfzYHkfvsMMToQBbEEjAEO226UtWyOjzAlPYw5qr7Ie1BrWxkGbxe9dfPDAsEQowUMbK4aPHcxUzxWD/KaV1jsXGfE3mNw "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 59 bytes
```
t;f(a,p)int*p;{for(t=abs(a-*p)+2;t-->0;)t=*p++-a?t:-1;++t;}
```
Takes a pointer to an "infinite" array. The way I implement this is to only calculate the numbers that are used (and then a "safe buffer" at the end to make sure I don't have any off-by-one errors, but this won't skew the result).
Es un puerto de la solución de [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper).
*-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
[Try it online!](https://tio.run/##rZLRasIwFIbvfYpDYdA0zUw6HMys884n2N0mI63pDKtpSdMNEZ@9SxScDqs4Figh55z/fKfJn5P3PO86y4tQxDVS2kY1XxeVCW0qsiYUJKoRTrgl5IlyZNOoxpiIiR0TxjG2fNM5DSyF0uFnpeZosB6AWz4ojHm5o3TG95GqnL/5T7fLTBpIgcbbnF998bw1Rmr7k2N8sE36IX1T5eu52x6B@R1jtBf7EdQsVZjthqiNUxRhcNM40bNp5asOYijC@9hVIphA4IPBOJiKspEB4teSiCKnUNt2f2aN@n4rSi6wGH24lpb00RJKiTp/jWR0Lc3544C23jOHQ2eYUmkJU5WpSos8V6AasAsJlS5X8CVWYCtnvA95KLILV2RaDUaKxskyV1qIxt4e@ezIaz8HftqMxw7k/c781RqfbL27zZ62m/PPmYz@zajs0luyXtKm@wY "C (gcc) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-x`, 24 bytes
```
W(Y(bi))CMa=yCM(bUi)_a=y
```
Uses the third format of infinite list: "A function... that outputs the nth value when passed n as an input." Takes a number and a function as command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboVS7IKlpSVpuhY7wjUiNZIyNTWdfRNtK519NZJCMzXjgUyINFTVumhDA0sdBaVqI63EWrheAA)
### Explanation
```
W(Y(bi))CMa=yCM(bUi)_a=y
a is the number, b is the function, i is 0 (implicit)
W While...
(bi) Call b with argument i
Y Yank the result into y
( )CMa Compare that value with a (returns -1, 0, or 1)
= Equals
yCM Compare y with
(b ) Call b with argument
Ui Increment i
... loop:
_ No-op
When the loop exits, we've either reached or passed a
a=y 1 if the most recent sequence value equals a, 0 otherwise
Autoprint (implicit)
```
[Answer]
# [Perl 5](https://www.perl.org/), 55 bytes
```
sub f{$f=pop;@L=($F=&$f,map&$f,0..abs$_[0]-$F);pop~~@L}
```
[Try it online!](https://tio.run/##zVRNa@MwEL37VwxUbG1itZL8kThCNKeeure9hVCcRuqabWTjD5YQ3L@eHTneXQKhx7oGoa834s3zm6l0/ZacTk23BXMkRlVlJVdPyieP6hsx4T6v3MTu7vJtQ57XbEPJYyAR9f6@eupPNxeBw/H6MpQPof6/2E0PX@bzukaD0Xnb1RpumzZv9a0cDn/opl0uv5e1lt7@4JO27nRITP7W6ED5POzsTptAeqasYX8A0iIefG@dhvjsGQ2A2hyHR4lVXBI7m2HuG4eAGw4CIoghgRTmsIAMOJtcjpH@kGZ4QZ86/pT2f@lTDlQAjYDGQBOgKdA50AXQDOhUiXhrzrLwOn3h5FeiH@kzVD9G5RdOdS6Ax8BT4AsQbEL1aRJeN49g7Cz/SB/3wDO0TIYJZHMcSD5LcGAeWYRDTEBfJOl19Zk0xdZ3/g9cBqP3E6d@BIJDhGWAO8wnjgGhpc1fXopPN89Hpeus/790GXzg/2nMExw9N7teVdgqJL9z22LD6mygVkN3kuM9kNeyVWaEOcD5pvzlDzdqCMXD3tuVVj@72MK@Sm/o9MX2uD@gJs3PwrSSuD2x/f292pW4UIo98KWb@YNYnn865cFsXImg709/AA "Perl 5 – Try It Online")
More or less a translation of @dingledooper's Python2 answer.
[Answer]
# perl -lE, 34 bytes
```
$t=<>;{$_=<>;$_<$t?redo:say$_==$t}
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lxNbGzrpaJR5EqcTbqJTYF6Wm5FsVJ1YCxWxVSmr//7fkMuQy5jLlMucCsgy5LKHgX35BSWZ@XvF/XV9TPQNDg/@6OQA "Perl 5 – Try It Online")
Prints `1` followed by a newline if the first element of the list appears elsewhere; otherwise, it just prints a newline. The program terminates after reading the first number which is equal or larger than the first number.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 67 bytes
```
a->s->{int p=s.get(),n;for(;p*(n=p-s.get())>a*n;)p-=n;return p==a;}
```
[Try it online!](https://tio.run/##dVRdb5swFH3nV1iRIkECVoLUSasLb6s0aasmpX2a9uCAoU7BeLZhq6r89sx8LjgmPET2Pb7ncM8xJ9zg4JS@XWjJK6HASa9hrWgBN8i52ctqlihasbboJAWWEnzHlIEPB@ifVFjRBDwOoIevTJGcCP@HIClNsCIPh5rzghIxluI4BhmIwAUHsQziD8oU4JGEOVGu5zOUVcJFfOOyiAfDrhfjDUMeDyKGBFG1YPpEhNH5grQIXh8LLWFQ0lQ0BaUW6B6UoCz/@QtgkUtv0KuIVO4nv3uF@3teSapoQwZp0kMWECM5XgLtd58nWMWeBuSXhjAbOrgbwXSoHkpcFEQ8v2IW7vbX2PBuElAz@rsmj/RYMZwk9Kkuj6YMs@83ImXb9PlP1eHOjgNmE@qOtaNnhKQF8cGNTeAVv@sTyds4uoNekhJWtYJcT1Zl7mqdrtlarlkU9//ts/KnnisIoV5mEOve726/7cGOe@p@o68LxNwYHZc9@o8Yd0373FHqGJJ5fbvtqWZMhruaKbBRmSEwqYx6ENiorAnRjDsboT1OE2/bsMGFPm1H9ulYoNxGIETX8nUnBG4VD3Gap1RThjubZHuozUlZe1rnZc29EYXewr/qZQEbWnTa75NlslZgP7clbYtaBj8WpWpLWhNMUxY9ubrhC7fD8i1Y8OIKMRpxvvwD "Java (JDK) – Try It Online")
# Credits
* -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), [114 bytes](https://tio.run/##bU89T8MwEN37Kx5mSapWonyWODETzAyMLK7jBkuJbTlnMUT57cFuKyEklrt7el865f22U2pZro1VfWw1auNGCloOYmUs4VjkKcspL78hPlJbVcpYIYjTtpHcHAsqWzf55h9y/v4yvS78mgStqeRBUwwWV8TnJY7GdrBy0KOXSiOZ@alzkMYWJaYVkKGxPhJPQLlIqGuwV0s6wAfXBTmceVRgHKkaQvw6Ds71SK4saE6/pKv8k/Vp3y85F10KykRxhi/sI0TNKvYm@1Gz5J2XB@xwizvc4xFP2OMZu5sf "@ceilingcat deals -8 damage, effective!") 106 bytes
```
#include<iostream>
int f(int a){int p,t;std::cin>>t;if(t-=a)for(;p=t,std::cin>>t,t-=a,p*t>t*t;);return!t;}
```
[Try it online!](https://tio.run/##VU89b8MgEN3zK17pYkeO1PS7xqZTO3fI2IUSbCHZgOCYovx2F5JIbZa7e3pfOuX9ZlRqWW6NVVPa6864SEHLWayMJQxVmbI@lOUb4pH2bauMFYK4GSra9LIeXKi476n5RzaFafyaBK2J1zxoSsHeED8uKRo7wspZRy@VRnbxU9ksja1qHFZAgcb6RDwD5RKh68A@LOkAH9wY5Hzm0YJx5E4I8ef4cW5CdhVBf3oiX/VV1rf9uuRcdDmoENUZvrNdSJq17FNOUbPsPS5P2OIeD3jEM17wijds734B "C++ (gcc) – Try It Online")
---
**Explanation :**
Our only hope of finding \$\alpha\$ in the future terms of the list \$t\$ is if :
* We don't skip over \$\alpha \implies\$ The difference of \$\alpha\$ and \$t\_n\$ doesn't change signs \$\implies \left(\alpha - t\_n\right)\cdot\left(\alpha - t\_{n-1}\right)>0 \space \forall \space n\in N, n > 1\$.(If it is zero, one of the terms is our target)
* The series approaches our target \$\implies {\left| \alpha - t\_n\right|} < {\left| \alpha - t\_{n-1}\right|}\$
We can then combine these two conditions :
$$
{\left| \alpha - t\_n\right|} < {\left| \alpha - t\_{n-1}\right|}
$$
$$
\implies {\left| \alpha - t\_n\right|} \cdot {\left| \alpha - t\_{n-1}\right|} < {\left( \alpha - t\_{n-1}\right)}^2$$
$$
\text{Since we need that}\left(\alpha - t\_n\right)\cdot\left(\alpha - t\_{n-1}\right)>0,
$$
$$
\text{Condition } P \equiv \left( {\left| \alpha - t\_n\right|} < {\left| \alpha - t\_{n-1}\right|} \right) \land \left( \left(\alpha - t\_n\right)\cdot\left(\alpha - t\_{n-1}\right)>0 \right)
$$
$$
P \equiv \left(\alpha - t\_n\right)\cdot\left(\alpha - t\_{n-1}\right) < {\left(\alpha - t\_{n-1}\right)}^2
$$
Hence if \$P\$ is found to be false the either the target has been found or we have passed it (or never reach it).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 56 bytes
```
f=->a,g,t=1{a==g[t]||(g[2]-g[1])*(g[t]-a)<0&&f[a,g,t+1]}
```
Recursively, checks if current term `g[t] == a`, then return `true`. Else, check if the **product** of difference `g[2] - g[1]` and `a - g[t]` are of opposite sign, if yes, then return `false`
[Try it online!](https://tio.run/##RY7LCoMwFET3/QpX4uNeSFIUKkY/JGRhF4nZlXKFBPXbUx@tXc5hODPv6RliNBK7ASyQ5PMgpVWklyWzSmi0iuu8yHaEQ96yNDXqqJZcr/GVGFUDdn72q779E/4iZ48DiMKj@DKsTsT4VRNVDeN2gsBLDkEKcNsVau89NdS5pB8VQQBfBnDbcHPpT9PuiR8 "Ruby – Try It Online")
---
# [Ruby](https://www.ruby-lang.org/), 40 bytes
*Port of [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)'s [Python answer](https://codegolf.stackexchange.com/a/203008/83605)!*
```
->a,g{(1..(a-g[0]).abs+1).map(&g).any?a}
```
[Try it online!](https://tio.run/##RYxLCsIwFAD3nqIrae17IS/SgsWkBwlZpIt@FkrRCAmhZ4@fal3OMMzt0YXUy4TKwhBzYiy3OGhuCma7e0kFu9g53w8vvIbWLmnOel0DKh/9YnZ/wh8SP32EOHgUX4fVqjhtmahqGCUqB14SBClgkhTd@di6xqkpa0ftIIAvA0wlmWbbr6f3Jz0B "Ruby – Try It Online")
[Answer]
# [Julia](http://julialang.org/), 23 bytes
```
N\~=N∈.~(0:abs(N-~0))
```
[Try it online!](https://tio.run/##dZBNDoIwEIX3PcUsaaSmxaiRiHoCTkBCalIUg4Oh@LNizTm9CIJKBdRdO9@892bmcE5iKW5V5QeF59/LclxY3JVbbfms4JRWEXgQEHJKdRhjrusfAlsBjgTZ6H16hcia2dBiCp4HeXZWBjIxoJFMtCIE1a5nyJD1HFve0RjLyQA/AwmmGDZldVHYujpoVIIvalmnpzuNPsokUVmY7yWGDhdGzzn7WExtGDZ@L1wX/7S9s6J4azXhgEsH1s0lwYVnkQk6ej0cavzmdgN/nGH6Ab0B@FBAqgc "Julia 1.0 – Try It Online")
takes a zero-indexed function as input
port of [dingledooper's solution](https://codegolf.stackexchange.com/a/203008/98541). The solution I found on my own was exactly double the length
] |
[Question]
[
Your job is to write a program (or two separate programs) in any language that:
1. Can take a completed Sudoku board as input (in any logical format) and compress it into a string of characters
2. Can take the compressed string as input and decompress it to get the *exact* same completed Sudoku board (output in any logical format of 9 rows)
**Note:** Use the rules of Sudoku to your advantage; that is the idea behind this challenge.
[Sudoku rules on Wikipedia](http://en.wikipedia.org/wiki/Sudoku)
# Rules
* Only printable ASCII characters (32 - 126) are allowed in the compressed output (eg. **no multibyte characters**).
* You can assume that the input is a *valid 3x3 Sudoku board* (normal rules, no variations).
* I won't impose a time-limit, but do not create a brute-force algorithm. Or, submitters should be able to test their submissions before posting (Thanks Jan Dvorak).
If you have any questions or concerns, you can ask for clarification or make suggestions in the comments.
# Winning Conditions
Score = sum of the number of characters from all ten test cases
*Lowest score wins.*
# Test Cases
You may use these to test how well your program works.
```
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
7 2 4 8 6 5 1 9 3
1 6 9 2 4 3 8 7 5
3 8 5 1 9 7 2 4 6
8 9 6 7 2 4 3 5 1
2 7 3 9 5 1 6 8 4
4 5 1 3 8 6 9 2 7
5 4 2 6 3 9 7 1 8
6 1 8 5 7 2 4 3 9
9 3 7 4 1 8 5 6 2
1 5 7 6 8 2 3 4 9
4 3 2 5 1 9 6 8 7
6 9 8 3 4 7 2 5 1
8 2 5 4 7 6 1 9 3
7 1 3 9 2 8 4 6 5
9 6 4 1 3 5 7 2 8
5 4 1 2 9 3 8 7 6
2 8 9 7 6 1 5 3 4
3 7 6 8 5 4 9 1 2
8 3 5 4 1 6 9 2 7
2 9 6 8 5 7 4 3 1
4 1 7 2 9 3 6 5 8
5 6 9 1 3 4 7 8 2
1 2 3 6 7 8 5 4 9
7 4 8 5 2 9 1 6 3
6 5 2 7 8 1 3 9 4
9 8 1 3 4 5 2 7 6
3 7 4 9 6 2 8 1 5
6 2 8 4 5 1 7 9 3
5 9 4 7 3 2 6 8 1
7 1 3 6 8 9 5 4 2
2 4 7 3 1 5 8 6 9
9 6 1 8 2 7 3 5 4
3 8 5 9 6 4 2 1 7
1 5 6 2 4 3 9 7 8
4 3 9 5 7 8 1 2 6
8 7 2 1 9 6 4 3 5
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 8 9 7 2
6 4 8 9 7 2 5 3 1
9 7 2 5 3 1 6 4 8
1 4 5 7 9 2 8 3 6
3 7 6 5 8 4 1 9 2
2 9 8 3 6 1 7 5 4
7 3 1 9 2 8 6 4 5
8 5 9 6 4 7 3 2 1
4 6 2 1 3 5 9 8 7
6 2 4 8 7 3 5 1 9
5 8 7 4 1 9 2 6 3
9 1 3 2 5 6 4 7 8
5 2 7 4 1 6 9 3 8
8 6 4 3 2 9 1 5 7
1 3 9 5 7 8 6 4 2
2 9 1 8 5 4 3 7 6
3 4 8 6 9 7 5 2 1
6 7 5 1 3 2 4 8 9
7 1 2 9 4 5 8 6 3
4 8 3 2 6 1 7 9 5
9 5 6 7 8 3 2 1 4
2 4 6 7 1 3 9 8 5
1 8 5 4 9 6 7 3 2
9 3 7 8 2 5 1 4 6
6 7 8 5 4 2 3 9 1
4 9 3 1 6 8 2 5 7
5 1 2 3 7 9 4 6 8
8 2 4 9 5 7 6 1 3
7 5 9 6 3 1 8 2 4
3 6 1 2 8 4 5 7 9
8 6 1 2 9 4 5 7 3
4 7 5 3 1 8 6 9 2
3 9 2 5 6 7 8 1 4
2 3 6 4 5 9 7 8 1
1 5 4 7 8 3 2 6 9
9 8 7 6 2 1 3 4 5
5 2 9 1 7 6 4 3 8
6 4 8 9 3 2 1 5 7
7 1 3 8 4 5 9 2 6
```
Credit to [http://www.opensky.ca/~jdhildeb/software/sudokugen/](http://www.opensky.ca/%7Ejdhildeb/software/sudokugen/) for some of these
*If you find any issues with the test cases, please tell me.*
[Answer]
# Haskell, 107 points
```
import Control.Monad
import Data.List
type Elem = Char
type Board = [[Elem]]
type Constraints = ([Elem],[Elem],[Elem])
digits :: [Elem]
digits = "123456789"
noCons :: Constraints
noCons = ([],[],[])
disjointCons :: Constraints
disjointCons = ("123","456","789") -- constraints from a single block - up to isomorphism
triples :: [a] -> [[a]]
triples [a,b,c,d,e,f,g,h,i] = [[a,b,c],[d,e,f],[g,h,i]]
(+++) :: Constraints -> Constraints -> Constraints
(a,b,c) +++ (d,e,f) = (a++d,b++e,c++f)
maxB = 12096
-- length $ assignments noCons disjointCons
maxC = 216 -- worst case: rows can be assigned independently
maxD = maxB
maxE = 448
-- foldl1' max [length $ assignments disjointCons colCons
-- | (_, colCons) <- map constraints $ assignments ([],[1],[1]) ([],[1],[1]),
-- let ([a,d,g],[b,e,h],[c,f,i]) = colCons,
-- a < d, d < g, b < e, e < h, c < f, f < i]
maxF = 2 ^ 3 -- for each row the relevant column constraints can be in the same column (no assignment),
-- or in two or three columns (two assignments)
maxG = maxC
maxH = maxF
-- constraints -> list of block solutions
assignments :: Constraints -> Constraints -> [[Elem]]
assignments (r1,r2,r3) (c1,c2,c3) = do
a <- digits \\ (r1 ++ c1); let digits1 = digits \\ [a]
b <- digits1 \\ (r1 ++ c2); let digits2 = digits1 \\ [b]
c <- digits2 \\ (r1 ++ c3); let digits3 = digits2 \\ [c]
d <- digits3 \\ (r2 ++ c1); let digits4 = digits3 \\ [d]
e <- digits4 \\ (r2 ++ c2); let digits5 = digits4 \\ [e]
f <- digits5 \\ (r2 ++ c3); let digits6 = digits5 \\ [f]
g <- digits6 \\ (r3 ++ c1); let digits7 = digits6 \\ [g]
h <- digits7 \\ (r3 ++ c2); let digits8 = digits7 \\ [h]
i <- digits8 \\ (r3 ++ c3)
return [a,b,c,d,e,f,g,h,i]
-- block solution -> tuple of constraints
constraints :: [Elem] -> (Constraints, Constraints)
constraints [a,b,c,d,e,f,g,h,i] = (([a,b,c],[d,e,f],[g,h,i]),([a,d,g],[b,e,h],[c,f,i]))
------------------------------------------------------------------------------------------
-- solution -> Integer
solution2ix :: Board -> Integer
solution2ix [a,b,c,d,e,f,g,h,i] =
let (ar, ac) = constraints a
(br, bc) = constraints b
(_ , cc) = constraints c
(dr, dc) = constraints d
(er, ec) = constraints e
(_ , fc) = constraints f
(gr, _ ) = constraints g
(hr, _ ) = constraints h
(_ , _ ) = constraints i
Just ixA = findIndex (a ==) $ assignments noCons noCons
Just ixB = findIndex (b ==) $ assignments ar noCons
Just ixC = findIndex (c ==) $ assignments (ar +++ br) noCons
Just ixD = findIndex (d ==) $ assignments noCons ac
Just ixE = findIndex (e ==) $ assignments dr bc
Just ixF = findIndex (f ==) $ assignments (dr +++ er) cc
Just ixG = findIndex (g ==) $ assignments noCons (ac +++ dc)
Just ixH = findIndex (h ==) $ assignments gr (bc +++ ec)
Just ixI = findIndex (i ==) $ assignments (gr +++ hr) (cc +++ fc)
in foldr (\(i,m) acc -> fromIntegral i + m * acc) (fromIntegral ixA)
$ zip [ixH, ixG, ixF, ixE, ixD, ixC, ixB] [maxH, maxG, maxF, maxE, maxD, maxC, maxB]
-- list of rows
-- -> list of threes of triples
-- -> three triples of threes of triples
-- -> three threes of triples of triples
-- -> nine triples of triples
-- -> nine blocks
toBoard :: [[Elem]] -> Board
toBoard = map concat . concat . map transpose . triples . map triples
toBase95 :: Integer -> String
toBase95 0 = ""
toBase95 ix = toEnum (32 + fromInteger (ix `mod` 95)) : toBase95 (ix `div` 95)
------------------------------------------------------------------------------------------
ix2solution :: Integer -> Board
ix2solution ix =
let (ixH', ixH) = ix `divMod` maxH
(ixG', ixG) = ixH' `divMod` maxG
(ixF', ixF) = ixG' `divMod` maxF
(ixE', ixE) = ixF' `divMod` maxE
(ixD', ixD) = ixE' `divMod` maxD
(ixC', ixC) = ixD' `divMod` maxC
(ixA , ixB) = ixC' `divMod` maxB
a = assignments noCons noCons !! fromIntegral ixA
(ra, ca) = constraints a
b = assignments ra noCons !! fromIntegral ixB
(rb, cb) = constraints b
c = assignments (ra +++ rb) noCons !! fromIntegral ixC
(_ , cc) = constraints c
d = assignments noCons ca !! fromIntegral ixD
(rd, cd) = constraints d
e = assignments rd cb !! fromIntegral ixE
(re, ce) = constraints e
f = assignments (rd +++ re) cc !! fromIntegral ixF
(_ , cf) = constraints f
g = assignments noCons (ca +++ cd) !! fromIntegral ixG
(rg, _ ) = constraints g
h = assignments rg (cb +++ ce) !! fromIntegral ixH
(rh, _ ) = constraints h
[i] = assignments (rg +++ rh) (cc +++ cf)
in [a,b,c,d,e,f,g,h,i]
-- nine blocks
-- -> nine triples of triples
-- -> three threes of triples of triples
-- -> three triples of threes of triples
-- -> list of threes of triples
-- -> list of rows
fromBoard :: Board -> [[Elem]]
fromBoard = map concat . concat . map transpose . triples . map triples
fromBase95 :: String -> Integer
fromBase95 "" = 0
fromBase95 (x:xs) = (toInteger $ fromEnum x) - 32 + 95 * fromBase95 xs
------------------------------------------------------------------------------------------
main = do line <- getLine
if length line <= 12
then putStrLn $ unlines $ map (intersperse ' ') $ fromBoard $ ix2solution $ fromBase95 line
else do nextLines <- replicateM 8 getLine
putStrLn $ toBase95 $ solution2ix $ toBoard $ map (map head.words) $ line:nextLines
```
The test case results:
```
q`3T/v50 =3,
^0NK(F4(V6T(
d KTTB{pJc[
B]^v[omnBF-*
WZslDPbcOm7'
)
ukVl2x/[+6F
qzw>GjmPxzo%
KE:*GH@H>(m!
SeM=kA`'3(X*
```
The code isn't pretty, but it works. The basis of the algorithm is that while enumerating all solutions would take too long, enumerating all solutions within a single block is rather quick - in fact, it's faster than the subsequent conversion to base95. The whole thing runs within seconds in the interpreter on my low-end machine. A compiled program would finish immediately.
The heavy lifting is done by the `solution2ix` function, which, for each 3x3 block, it generates all possible permutations, subject to constraints from the left and from above, until it finds the one in the encoded solution, remembering only the index of said permutation. Then it combines the indexes using some precomputed weights and the Horner's scheme.
In the other direction, the `ix2solution` function first decomposes the index into nine values. Then for each block it indexes the list of possible permutations with its respective value, then extracts the constraints for the next blocks.
`assignments` is a simple but ugly unrolled recursion using the list monad. It generates the list of permutations given a set of constraints.
The real power comes from the tight bounds on the permutation list lengths:
* The top left corner is unconstrained. The number of permutations is simply `9!`. This value is never used except to find an upper bound for the output length.
* The blocks next to it only have one set of constraints - from the top left. A naive upper bound `6*5*4*6!` is seven times worse than the actual count found by enumeration: `12096`
* The top right corner is constrained twice from left. Each row can only have six permutations, and in the worst case (actually in every valid case), the assignment is independent. Similarly for the bottom left corner.
* The center piece was the hardest to estimate. Once again the brute force wins - count the permutation for each possible set of constraints up to isomorphism. Takes a while, but it's only needed once.
* The right center piece has a double constraint from the left, which forces each row up to a permutation, but also a single constraint from the top, which ensures only two permutations per row are actually possible. Similarly for the bottom center piece.
* The bottom right corner is fully determined by its neighbors. The sole permutation is never actually verified when computing the index. Forcing evaluation would be easy, it's just not necessary.
The product of all these limits is `71025136897117189570560` ~= `95^11.5544`, which means that no code is longer than 12 characters and almost a half of them should be 11 characters or fewer. I have decided not to distinguish between a shorter string and the same string right-padded with spaces. Spaces anywhere else are significant.
The theoretical limit of encoding efficiency for prefix-free codes - base-95 logarithm of `6670903752021072936960` - is `11.035`, meaning that even an optimal algorithm cannot avoid producing length-12 outputs, though it will produce them in only 3.5% of all cases. Allowing length to be significant (or equivalently, adding trailing spaces) does add a few codes (1% of the total amount), but not enough to eliminate the need for length-12 codes.
[Answer]
## Python, 130 points
```
j1:4}*KYm6?D
h^('gni9X`g'#
$2{]8=6^l=fF!
BS ;1;J:z"^a"
\/)gT)sixb"A+
WI?TFvj%:&3-\$
*iecz`L2|a`X0
eLbt<tf|mFN'&
;KH_TzK$erFa!
7T=1*6$]*"s"!
```
The algorithm works by encoding each position in the board, one at a time, into a big integer. For each position, it calculates the possible values given all the assignments encoded so far. So if [1,3,7,9] are the possible values for a given position, it takes 2 bits to encode the choice.
The nice thing about this scheme is that if a position has only a single remaining choice, it takes no space to encode.
Once we have the big integer we write it out in base 95.
There are probably better encoding orderings than lexicographic, but I haven't thought a lot about it.
Encoder:
```
import sys
sets = [range(i*9, i*9+9) for i in xrange(9)]
sets += [range(i, 81, 9) for i in xrange(9)]
sets += [[i/3*27+i%3*3+j/3*9+j%3 for j in xrange(9)] for i in xrange(9)]
M = []
for line in sys.stdin.readlines():
M += [int(x) for x in line.split()]
A = 0
m = 1
for i in xrange(81):
allowed = set(xrange(1,10))
for s in sets:
if i in s:
for j in s:
if j < i: allowed.discard(M[j])
allowed = sorted(allowed)
A += m * allowed.index(M[i])
m *= len(allowed)
s=''
while A != 0:
s+='%c'%(32+A%95)
A /= 95
print s
```
Decoder:
```
sets = [range(i*9, i*9+9) for i in xrange(9)]
sets += [range(i, 81, 9) for i in xrange(9)]
sets += [[i/3*27+i%3*3+j/3*9+j%3 for j in xrange(9)] for i in xrange(9)]
s=raw_input()
A=0
m=1
while s != '':
A += m * (ord(s[0])-32)
s = s[1:]
m *= 95
M=[]
for i in xrange(81):
allowed = set(xrange(1,10))
for s in sets:
if i in s:
for j in s:
if j < i: allowed.discard(M[j])
allowed = sorted(allowed)
M += [allowed[A%len(allowed)]]
A /= len(allowed)
for i in xrange(9):
print ' '.join(str(x) for x in M[i*9:i*9+9])
```
Run it like this:
```
> cat sudoku1 | ./sudokuEnc.py | ./sudokuDec.py
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
```
[Answer]
# perl - score 115 113 103 113
Output:
```
"#1!A_mb_jB)
FEIV1JH~vn"
$\\XRU*LXea.
EBIC5fPxklB
5>jM7(+0MrM
!'Wu9FS2d~!W
":`R60C"}z!k
:B&Jg[fL%\j
"L28Y?3`Q>4w
o0xPz8)_i%-
```
Output:
```
# note this line is empty
S}_h|bt:za
%.j0.6w>?RM+
:H$>a>Cy{7C
'57UHjcWQmcw
owmK0NF?!Fv
# }aYExcZlpD
nGl^K]xH(.\
9ii]I$voC,x
!:MR0>I>PuTU
```
None of those lines have a terminating space. Note that the first line is empty.
This algorithm works as follows. To compress:
1. Start with an empty 'current' string representing the Sudoku grid
2. Consider adding in turn each of the digits 1 .. 9 to that string, and determine which is viable.
3. Get the next digit from the answer grid (and add it to current)
4. If only one is viable, there is nothing to code
5. If more than one is viable, count the number of viable options, sort them, and code that digit as the index into the sorted array. Record the digit and the number viable as a 2-tuple in an array.
6. When all done, code each of the 2-tuples (in reverse order) in a variable based number stored as a bigint.
7. Express the bigint in base 95.
To decode:
1. Start with an empty 'current' string representing the Sudoku grid
2. Decode the base95 number to a bigint
3. Consider adding in turn each of the digits 1 .. 9 to that string, and determine which is viable.
4. If only one is viable, there is nothing to code; add that choice to the grid
5. If more than one is viable, count the number of viable options, sort them, and code that digit as the index into the sorted array.
6. Decode the variable-base bigint using the number of viable options as the base, and the modulus as the index into the array, and output that digit as a cell value.
In order to determine the number of viable options, Games::Sudoku::Solver is used. That's mainly for clarity as there are 3 line Sudoku solvers on this site.
To do all 10 took 8 seconds on my laptop.
The `fudge` operation sorts the array differently to achieve the minimal value for the test cases. As documented, this is a fudge. The fudge reduces the score from 115 to 103. It is handcrafted to ensure that the bigint code for the first test is 0. The worst-case score for any sudoku is 12 giving a score of 120. I thus don't think this counts as hard-coding; rather it optimises for the test data. To see it work without this, change `sort fudge` into `sort` in both places.
Code follows:
```
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use bigint;
use Games::Sudoku::Solver qw (:Minimal set_solution_max count_occupied_cells);
# NOTE THIS IS NOT USED BY DEFAULT - see below and discussion in comments
my @fudgefactor = qw (9 7 3 5 8 1 4 2 6 5 2 6 4 7 3 1 9 8 1 8 4 2 9 6 7 5 3 2 4 7 8 6 5 3 1 9 3 9 8 1 2 4 6 7 5 6 5 1 7 3 9 8 4 2 8 1 9 3 4 2 5 6 7 7 6 5 9 1 8 2 3 4 4 3 2 6 5 7 9 8 1);
my $fudgeindex=0;
my $fudging=0; # Change to 1 to decrease score by 10
sub isviable
{
no bigint;
my $current = shift @_;
my @test = map {$_ + 0} split(//, substr(($current).("0"x81), 0, 81));
my @sudoku;
my @solution;
set_solution_max (2);
my $nsolutions;
eval
{
sudoku_set(\@sudoku, \@test);
$nsolutions = sudoku_solve(\@sudoku, \@solution);
};
return 0 unless $nsolutions;
return ($nsolutions >=1);
}
sub getnextviable
{
my $current = shift @_; # grid we have so far
my %viable;
for (my $i = 1; $i<=9; $i++)
{
my $n;
my $solution;
$viable{$i} = 1 if (isviable($current.$i));
}
return %viable;
}
sub fudge
{
return $a<=>$b unless ($fudging);
my $k=$fudgefactor[$fudgeindex];
my $aa = ($a+10-$k) % 10;
my $bb = ($b+10-$k) % 10;
return $aa<=>$bb;
}
sub compress
{
my @data;
while (<>)
{
chomp;
foreach my $d (split(/\s+/))
{
push @data, $d;
}
}
my $code = 0;
my $current = "";
my @codepoints;
foreach my $d (@data)
{
my %viable = getnextviable($current);
die "Digit $d is unexpectedly not viable - is sudoku impossible?" unless ($viable{$d});
my $nviable = scalar keys(%viable);
if ($nviable>1)
{
my $n=0;
foreach my $k (sort fudge keys %viable)
{
if ($k==$d)
{
no bigint;
my %cp = ( "n"=> $n, "v"=> $nviable);
unshift @codepoints, \%cp;
last;
}
$n++;
}
}
$fudgeindex++;
$current .= $d;
}
foreach my $cp (@codepoints)
{
$code = ($code * $cp->{"v"})+$cp->{"n"};
}
# print in base 95
my $out="";
while ($code)
{
my $digit = $code % 95;
$out = chr($digit+32).$out;
$code -= $digit;
$code /= 95;
}
print "$out";
}
sub decompress
{
my $code = 0;
# Read from base 95 into bigint
while (<>)
{
chomp;
foreach my $char (split (//, $_))
{
my $c =ord($char)-32;
$code*=95;
$code+=$c;
}
}
# Reconstruct sudoku
my $current = "";
for (my $cell = 0; $cell <81; $cell++)
{
my %viable = getnextviable($current);
my $nviable = scalar keys(%viable);
die "Cell $cell is unexpectedly not viable - is sudoku impossible?" unless ($nviable);
my $mod = $code % $nviable;
$code -= $mod;
$code /= $nviable;
my @v = sort fudge keys (%viable);
my $d = $v[$mod];
$current .= $d;
print $d.(($cell %9 != 8)?" ":"\n");
$fudgeindex++;
}
}
my $decompress;
GetOptions ("d|decompress" => \$decompress);
if ($decompress)
{
decompress;
}
else
{
compress;
}
```
[Answer]
# CJam, 309 bytes
This is just a quick baseline solution. I'm sorry I did this in a golfing language, but it was actually the simplest way to do it. I'll add an explanation of the actual code tomorrow, but I've outlined the algorithm below.
**Encoder**
```
q~{);}%);:+:(9b95b32f+:c
```
**Decoder**
```
l:i32f-95b9bW%[0]64*+64<W%:)8/{_:+45\-+}%z{_:+45\-+}%z`
```
[Test it here.](http://cjam.aditsu.net/)
The input of the encoder (on STDIN) and the output of the decoder (on STDOUT) are in the form of a nested CJam array. E.g.
```
[[8 3 5 4 1 6 9 2 7] [2 9 6 8 5 7 4 3 1] [4 1 7 2 9 3 6 5 8] [5 6 9 1 3 4 7 8 2] [1 2 3 6 7 8 5 4 9] [7 4 8 5 2 9 1 6 3] [6 5 2 7 8 1 3 9 4] [9 8 1 3 4 5 2 7 6] [3 7 4 9 6 2 8 1 5]]
```
The 10 test outputs are:
```
U(5wtqmC.-[TM.#aMY#k*)pErHQcg'{
EWrn"^@p+g<5XT5G[r1|bk?q6Nx4~r?
#489pLj5+ML+z@y$]8a@CI,K}B$$Mwn
LF_X^"-h**A!'VZq kHT@F:"ZMD?A0r
?gD;"tw<yG%8y!3S"BC:ojQ!#;i-:\g
qS#"L%`4yei?Ce_r`{@EOl66m^hx77
"EF?` %!H@YX6J0F93->%90O7T#C_5u
9V)R+6@Jx(jg@@U6.DrMO*5G'P<OHv8
(Ua6z{V:hX#sV@g0s<|!X[T,Jy|oQ+K
N,F8F1!@OH1%%zs%dI`Q\q,~oAEl(:O
```
The algorithm is very simple:
* Remove the last column and row.
* Treat the remaining 64 digits as a base-9 number (after decrementing each digit by 1).
* Convert that to base-95, add 32 to each digit and turn that into the corresponding ASCII character.
* For the decoding, reverse the base conversion and fill in the the final column and row with the missing numbers.
[Answer]
# Python 2.7, 107 chars total
**TL;DR** brute-force enumeration of 3x3 squares with top+left constraints
test cases:
```
import itertools
inputs = """
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
7 2 4 8 6 5 1 9 3
1 6 9 2 4 3 8 7 5
3 8 5 1 9 7 2 4 6
8 9 6 7 2 4 3 5 1
2 7 3 9 5 1 6 8 4
4 5 1 3 8 6 9 2 7
5 4 2 6 3 9 7 1 8
6 1 8 5 7 2 4 3 9
9 3 7 4 1 8 5 6 2
1 5 7 6 8 2 3 4 9
4 3 2 5 1 9 6 8 7
6 9 8 3 4 7 2 5 1
8 2 5 4 7 6 1 9 3
7 1 3 9 2 8 4 6 5
9 6 4 1 3 5 7 2 8
5 4 1 2 9 3 8 7 6
2 8 9 7 6 1 5 3 4
3 7 6 8 5 4 9 1 2
8 3 5 4 1 6 9 2 7
2 9 6 8 5 7 4 3 1
4 1 7 2 9 3 6 5 8
5 6 9 1 3 4 7 8 2
1 2 3 6 7 8 5 4 9
7 4 8 5 2 9 1 6 3
6 5 2 7 8 1 3 9 4
9 8 1 3 4 5 2 7 6
3 7 4 9 6 2 8 1 5
6 2 8 4 5 1 7 9 3
5 9 4 7 3 2 6 8 1
7 1 3 6 8 9 5 4 2
2 4 7 3 1 5 8 6 9
9 6 1 8 2 7 3 5 4
3 8 5 9 6 4 2 1 7
1 5 6 2 4 3 9 7 8
4 3 9 5 7 8 1 2 6
8 7 2 1 9 6 4 3 5
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 8 9 7 2
6 4 8 9 7 2 5 3 1
9 7 2 5 3 1 6 4 8
1 4 5 7 9 2 8 3 6
3 7 6 5 8 4 1 9 2
2 9 8 3 6 1 7 5 4
7 3 1 9 2 8 6 4 5
8 5 9 6 4 7 3 2 1
4 6 2 1 3 5 9 8 7
6 2 4 8 7 3 5 1 9
5 8 7 4 1 9 2 6 3
9 1 3 2 5 6 4 7 8
5 2 7 4 1 6 9 3 8
8 6 4 3 2 9 1 5 7
1 3 9 5 7 8 6 4 2
2 9 1 8 5 4 3 7 6
3 4 8 6 9 7 5 2 1
6 7 5 1 3 2 4 8 9
7 1 2 9 4 5 8 6 3
4 8 3 2 6 1 7 9 5
9 5 6 7 8 3 2 1 4
2 4 6 7 1 3 9 8 5
1 8 5 4 9 6 7 3 2
9 3 7 8 2 5 1 4 6
6 7 8 5 4 2 3 9 1
4 9 3 1 6 8 2 5 7
5 1 2 3 7 9 4 6 8
8 2 4 9 5 7 6 1 3
7 5 9 6 3 1 8 2 4
3 6 1 2 8 4 5 7 9
8 6 1 2 9 4 5 7 3
4 7 5 3 1 8 6 9 2
3 9 2 5 6 7 8 1 4
2 3 6 4 5 9 7 8 1
1 5 4 7 8 3 2 6 9
9 8 7 6 2 1 3 4 5
5 2 9 1 7 6 4 3 8
6 4 8 9 3 2 1 5 7
7 1 3 8 4 5 9 2 6
""".strip().split('\n\n')
```
helper function to print sudoku
```
def print_sudoku(m):
for k in m:
print' '.join(str(i) for i in k)
```
generates all possible squares given constraints above and left
see code comment for more details
```
def potential_squares(u1, u2, u3, l1, l2, l3):
"""
returns generator of possible squares given lists of digits above and below
u1 u2 u3
| | |
l1 -- a b c
l2 -- d e f
l3 -- g h i
if no items exist the empty list must be given
"""
for a, b, c, d, e, f, g, h, i in itertools.permutations(xrange(1, 10)):
if a not in u1 and a not in l1 and b not in u2 and b not in l1 and c not in u3 and c not in l1 and d not in u1 and d not in l2 and e not in u2 and e not in l2 and f not in u3 and f not in l2 and g not in u1 and g not in l3 and h not in u2 and h not in l3 and i not in u3 and i not in l3:
yield (a, b, c, d, e, f, g, h, i)
```
extracts all squares from sudoku board as tuples
see code comment for more details
```
def board_to_squares(board):
"""
finds 9 squares in a 9x9 board in this order:
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
4 4 4 5 5 5 6 6 6
4 4 4 5 5 5 6 6 6
4 4 4 5 5 5 6 6 6
7 7 7 8 8 8 9 9 9
7 7 7 8 8 8 9 9 9
7 7 7 8 8 8 9 9 9
returns tuple for each square as follows:
a b c
d e f --> (a,b,c,d,e,f,g,h,i)
g h i
"""
labels = [[3 * i + 1] * 3 + [3 * i + 2] * 3 + [3 * i + 3] * 3 for i in [0, 0, 0, 1, 1, 1, 2, 2, 2]]
labelled_board = zip(sum(board, []), sum(labels, []))
return [tuple(a for a, b in labelled_board if b == sq) for sq in xrange(1, 10)]
```
converts squares back to sudoku board
basically an inverse of the above function
```
def squares_to_board(squares):
"""
inverse of above
"""
board = [[i / 3 * 27 + i % 3 * 3 + j / 3 * 9 + j % 3 for j in range(9)] for i in range(9)]
flattened = sum([list(square) for square in squares], [])
for i in range(9):
for j in range(9):
board[i][j] = flattened[board[i][j]]
return board
```
given squares left, return constraints
see code comment for more details
```
def sum_rows(*squares):
"""
takes tuples for squares and returns lists corresponding to the rows:
l1 -- a b c j k l
l2 -- d e f m n o ...
l3 -- g h i p q r
"""
l1 = []
l2 = []
l3 = []
if len(squares):
for a, b, c, d, e, f, g, h, i in squares:
l1 += [a, b, c]
l2 += [d, e, f]
l3 += [g, h, i]
return l1, l2, l3
return [], [], []
```
given squares above, return constraints
see code comment for more details
```
def sum_cols(*squares):
"""
takes tuples for squares and returns lists corresponding to the cols:
u1 u2 u3
| | |
a b c
d e f
g h i
j k l
m n o
p q r
...
"""
u1 = []
u2 = []
u3 = []
if len(squares):
for a, b, c, d, e, f, g, h, i in squares:
u1 += [a, d, g]
u2 += [b, e, h]
u3 += [c, f, i]
return u1, u2, u3
return [], [], []
```
makes a string
```
def base95(A):
if type(A) is int or type(A) is long:
s = ''
while A > 0:
s += chr(32 + A % 95)
A /= 95
return s
if type(A) is str:
return sum((ord(c) - 32) * (95 ** i) for i, c in enumerate(A))
```
this is a hardcoded list of dependencies for each square
see code comment for more details
```
"""
dependencies: every square as labeled
1 2 3
4 5 6
7 8 9
is dependent on those above and to the left
in a dictionary, it is:
square: ([above],[left])
"""
dependencies = {1: ([], []), 2: ([], [1]), 3: ([], [1, 2]), 4: ([1], []), 5: ([2], [4]), 6: ([3], [4, 5]),
7: ([1, 4], []), 8: ([2, 5], [7]), 9: ([3, 6], [7, 8])}
```
this is a hardcoded list of max number of possible options for each square
see code comment for more details
```
"""
max possible options for a given element
9 8 7 ? ? ? 3 2 1
6 5 4 (12096) 3 2 1
3 2 1 ? ? ? 3 2 1
? ? ? ? ? ? 2 2 1
(12096) (448) 2 1 1 (limits for squares 2,4 determined via brute-force enumeration)
? ? ? ? ? ? 1 1 1 (limit for square 5 determined via sampling and enumeration)
3 3 3 2 2 1 1 1 1
2 2 2 2 1 1 1 1 1
1 1 1 1 1 1 1 1 1
"""
possibilities = [362880, 12096, 216, 12096, 448, 8, 216, 8, 1]
```
these combine the above functions and convert a board to a list of integers
```
def factorize_sudoku(board):
squares = board_to_squares(board)
factors = []
for label in xrange(1, 10):
above, left = dependencies[label]
u1, u2, u3 = sum_cols(*[sq for i, sq in enumerate(squares) if i + 1 in above])
l1, l2, l3 = sum_rows(*[sq for i, sq in enumerate(squares) if i + 1 in left])
for i, k in enumerate(potential_squares(u1, u2, u3, l1, l2, l3)):
if k == squares[label - 1]:
factors.append(i)
continue
return factors
```
and back to a board
```
def unfactorize_sudoku(factors):
squares = []
for label in xrange(1, 10):
factor = factors[label - 1]
above, left = dependencies[label]
u1, u2, u3 = sum_cols(*[sq for i, sq in enumerate(squares) if i + 1 in above])
l1, l2, l3 = sum_rows(*[sq for i, sq in enumerate(squares) if i + 1 in left])
for i, k in enumerate(potential_squares(u1, u2, u3, l1, l2, l3)):
if i == factor:
squares.append(k)
continue
return squares
```
okay that's all the functions
for each board, make string and print it
```
strings = []
for sudoku in inputs:
board = [[int(x) for x in line.split()] for line in sudoku.strip().split('\n')]
print_sudoku(board)
factors = factorize_sudoku(board)
i = 0
for item, modulus in zip(factors, possibilities):
i *= modulus
i += item
strings.append(base95(i))
print 'integral representation:', i
print 'bits of entropy:', i.bit_length()
print 'base95 representation:', strings[-1]
print ''
```
now print the total length of all strings
```
print 'overall output:', strings
print 'total length:', len(''.join(strings))
print ''
```
and un-stringify, to prove it's not a one-way compression
```
for string in strings:
print 'from:', string
i = base95(string)
retrieved = []
for base in possibilities[::-1]:
retrieved.append(i % base)
i /= base
squares = unfactorize_sudoku(retrieved[::-1])
print_sudoku(squares_to_board(squares))
print ''
```
output:
```
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
integral representation: 69411889624053450486136
bits of entropy: 76
base95 representation: q`3T/v50 =3,
7 2 4 8 6 5 1 9 3
1 6 9 2 4 3 8 7 5
3 8 5 1 9 7 2 4 6
8 9 6 7 2 4 3 5 1
2 7 3 9 5 1 6 8 4
4 5 1 3 8 6 9 2 7
5 4 2 6 3 9 7 1 8
6 1 8 5 7 2 4 3 9
9 3 7 4 1 8 5 6 2
integral representation: 48631663773869605020107
bits of entropy: 76
base95 representation: ^0NK(F4(V6T(
1 5 7 6 8 2 3 4 9
4 3 2 5 1 9 6 8 7
6 9 8 3 4 7 2 5 1
8 2 5 4 7 6 1 9 3
7 1 3 9 2 8 4 6 5
9 6 4 1 3 5 7 2 8
5 4 1 2 9 3 8 7 6
2 8 9 7 6 1 5 3 4
3 7 6 8 5 4 9 1 2
integral representation: 3575058942398222501018
bits of entropy: 72
base95 representation: d KTTB{pJc[
8 3 5 4 1 6 9 2 7
2 9 6 8 5 7 4 3 1
4 1 7 2 9 3 6 5 8
5 6 9 1 3 4 7 8 2
1 2 3 6 7 8 5 4 9
7 4 8 5 2 9 1 6 3
6 5 2 7 8 1 3 9 4
9 8 1 3 4 5 2 7 6
3 7 4 9 6 2 8 1 5
integral representation: 57682547793421214045879
bits of entropy: 76
base95 representation: B]^v[omnBF-*
6 2 8 4 5 1 7 9 3
5 9 4 7 3 2 6 8 1
7 1 3 6 8 9 5 4 2
2 4 7 3 1 5 8 6 9
9 6 1 8 2 7 3 5 4
3 8 5 9 6 4 2 1 7
1 5 6 2 4 3 9 7 8
4 3 9 5 7 8 1 2 6
8 7 2 1 9 6 4 3 5
integral representation: 41241947159502331128265
bits of entropy: 76
base95 representation: WZslDPbcOm7'
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 8 9 7 2
6 4 8 9 7 2 5 3 1
9 7 2 5 3 1 6 4 8
integral representation: 9
bits of entropy: 4
base95 representation: )
1 4 5 7 9 2 8 3 6
3 7 6 5 8 4 1 9 2
2 9 8 3 6 1 7 5 4
7 3 1 9 2 8 6 4 5
8 5 9 6 4 7 3 2 1
4 6 2 1 3 5 9 8 7
6 2 4 8 7 3 5 1 9
5 8 7 4 1 9 2 6 3
9 1 3 2 5 6 4 7 8
integral representation: 2289142964266107350685
bits of entropy: 71
base95 representation: ukVl2x/[+6F
5 2 7 4 1 6 9 3 8
8 6 4 3 2 9 1 5 7
1 3 9 5 7 8 6 4 2
2 9 1 8 5 4 3 7 6
3 4 8 6 9 7 5 2 1
6 7 5 1 3 2 4 8 9
7 1 2 9 4 5 8 6 3
4 8 3 2 6 1 7 9 5
9 5 6 7 8 3 2 1 4
integral representation: 33227336099857838436306
bits of entropy: 75
base95 representation: qzw>GjmPxzo%
2 4 6 7 1 3 9 8 5
1 8 5 4 9 6 7 3 2
9 3 7 8 2 5 1 4 6
6 7 8 5 4 2 3 9 1
4 9 3 1 6 8 2 5 7
5 1 2 3 7 9 4 6 8
8 2 4 9 5 7 6 1 3
7 5 9 6 3 1 8 2 4
3 6 1 2 8 4 5 7 9
integral representation: 10303519193492123417583
bits of entropy: 74
base95 representation: KE:*GH@H>(m!
8 6 1 2 9 4 5 7 3
4 7 5 3 1 8 6 9 2
3 9 2 5 6 7 8 1 4
2 3 6 4 5 9 7 8 1
1 5 4 7 8 3 2 6 9
9 8 7 6 2 1 3 4 5
5 2 9 1 7 6 4 3 8
6 4 8 9 3 2 1 5 7
7 1 3 8 4 5 9 2 6
integral representation: 60238104668684129814106
bits of entropy: 76
base95 representation: SeM=kA`'3(X*
overall output: ['q`3T/v50 =3,', '^0NK(F4(V6T(', 'd KTTB{pJc[', 'B]^v[omnBF-*', "WZslDPbcOm7'", ')', 'ukVl2x/[+6F', 'qzw>GjmPxzo%', 'KE:*GH@H>(m!', "SeM=kA`'3(X*"]
total length: 107
from: q`3T/v50 =3,
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
from: ^0NK(F4(V6T(
7 2 4 8 6 5 1 9 3
1 6 9 2 4 3 8 7 5
3 8 5 1 9 7 2 4 6
8 9 6 7 2 4 3 5 1
2 7 3 9 5 1 6 8 4
4 5 1 3 8 6 9 2 7
5 4 2 6 3 9 7 1 8
6 1 8 5 7 2 4 3 9
9 3 7 4 1 8 5 6 2
from: d KTTB{pJc[
1 5 7 6 8 2 3 4 9
4 3 2 5 1 9 6 8 7
6 9 8 3 4 7 2 5 1
8 2 5 4 7 6 1 9 3
7 1 3 9 2 8 4 6 5
9 6 4 1 3 5 7 2 8
5 4 1 2 9 3 8 7 6
2 8 9 7 6 1 5 3 4
3 7 6 8 5 4 9 1 2
from: B]^v[omnBF-*
8 3 5 4 1 6 9 2 7
2 9 6 8 5 7 4 3 1
4 1 7 2 9 3 6 5 8
5 6 9 1 3 4 7 8 2
1 2 3 6 7 8 5 4 9
7 4 8 5 2 9 1 6 3
6 5 2 7 8 1 3 9 4
9 8 1 3 4 5 2 7 6
3 7 4 9 6 2 8 1 5
from: WZslDPbcOm7'
6 2 8 4 5 1 7 9 3
5 9 4 7 3 2 6 8 1
7 1 3 6 8 9 5 4 2
2 4 7 3 1 5 8 6 9
9 6 1 8 2 7 3 5 4
3 8 5 9 6 4 2 1 7
1 5 6 2 4 3 9 7 8
4 3 9 5 7 8 1 2 6
8 7 2 1 9 6 4 3 5
from: )
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 8 9 7 2
6 4 8 9 7 2 5 3 1
9 7 2 5 3 1 6 4 8
from: ukVl2x/[+6F
1 4 5 7 9 2 8 3 6
3 7 6 5 8 4 1 9 2
2 9 8 3 6 1 7 5 4
7 3 1 9 2 8 6 4 5
8 5 9 6 4 7 3 2 1
4 6 2 1 3 5 9 8 7
6 2 4 8 7 3 5 1 9
5 8 7 4 1 9 2 6 3
9 1 3 2 5 6 4 7 8
from: qzw>GjmPxzo%
5 2 7 4 1 6 9 3 8
8 6 4 3 2 9 1 5 7
1 3 9 5 7 8 6 4 2
2 9 1 8 5 4 3 7 6
3 4 8 6 9 7 5 2 1
6 7 5 1 3 2 4 8 9
7 1 2 9 4 5 8 6 3
4 8 3 2 6 1 7 9 5
9 5 6 7 8 3 2 1 4
from: KE:*GH@H>(m!
2 4 6 7 1 3 9 8 5
1 8 5 4 9 6 7 3 2
9 3 7 8 2 5 1 4 6
6 7 8 5 4 2 3 9 1
4 9 3 1 6 8 2 5 7
5 1 2 3 7 9 4 6 8
8 2 4 9 5 7 6 1 3
7 5 9 6 3 1 8 2 4
3 6 1 2 8 4 5 7 9
from: SeM=kA`'3(X*
8 6 1 2 9 4 5 7 3
4 7 5 3 1 8 6 9 2
3 9 2 5 6 7 8 1 4
2 3 6 4 5 9 7 8 1
1 5 4 7 8 3 2 6 9
9 8 7 6 2 1 3 4 5
5 2 9 1 7 6 4 3 8
6 4 8 9 3 2 1 5 7
7 1 3 8 4 5 9 2 6
```
[Answer]
## Mathematica, score: 130 9
*Update:*
After this answer was posted, it inspired a new loophole closer: ["Optimising for the given test cases"](https://codegolf.meta.stackexchange.com/a/2507/10947). I will however leave this answer as is, as an example of the loophole. Feel free to downvote. I won't be hurt.
---
This encodes a cell at a time in raster order, and for each cell rules out its value appropriately for subsequent cells using the basic rules of Sudoku. So, for example, when a cell is encoded and only has four possibilities, then a base 4 digit is added to the large integer. It also codes the test cases directly as small integers, still correctly compressing and decompressing all valid Sudoku boards with an average compressed length of ~12.5 characters, 1.5 more than the optimal 11.035, with relatively simple code and no Sudoku solver required.
```
rule=({#}&/@Union[Join[
Range[#+1,Ceiling[#,9]],Range[#+9,81,9],
Flatten[Outer[Plus,Range[Floor[#+8,9],Ceiling[#,27]-9,9],
Floor[Mod[#-1,9],3]+Range[3]]]]])&/@Range[81];
encode[board_]:=
Block[{step,code,pos},
step[{left_,x_,m_},n_]:={
MapAt[Complement[#,{board[[n]]}]&,left,rule[[n]]],
x+m(FirstPosition[left[[n]],board[[n]]][[1]]-1),m Length[left[[n]]]};
code=Fold[step,{Table[Range[9],{81}],0,1},Range[81]][[2]];
pos=Position[{206638498064127103948214,1665188010993633759502287,
760714067080859855534739,1454154263752219616902129,6131826927558056238360710,
237833524138130760909081600,8968162948536417279508170,3284755189143784030943149,
912407486534781347155987,556706937207676220045188},code];
code=If[pos==={},code+10,pos[[1,1]]-1];
FromCharacterCode[If[code==0,{},IntegerDigits[code,95]+32]]
]
decode[str_]:=
Block[{step,code},
code=FromDigits[ToCharacterCode[str]-32,95];
code=If[code<10,{206638498064127103948214,1665188010993633759502287,
760714067080859855534739,1454154263752219616902129,6131826927558056238360710,
237833524138130760909081600,8968162948536417279508170,3284755189143784030943149,
912407486534781347155987,556706937207676220045188}[[code+1]],code-10];
step[{left_,x_,board_},n_]:=Function[z,{
MapAt[Complement[#,{z}]&,left,rule[[n]]],Quotient[x,Length[left[[n]]]],
Append[board,z]}][left[[n,Mod[x,Length[left[[n]]]]+1]]];
Fold[step,{Table[Range[9],{81}],code,{}},Range[81]][[3]]
]
```
Encoded test cases:
```
<- empty string
!
"
#
$
%
&
'
(
)
```
This does not result in perfect coding (average ~11), since the basic rules do not rule out some choices for which there is in fact no solution. The performance could be made perfect (i.e. the large integer would always be less than the number of possible Sudoku boards) by checking to see if there is no solution to some of the current choices using a Sudoku solver, and eliminating those as well.
[Answer]
## J, 254 points
**Compression**
```
fwrite&'sudoku.z' 1 u: u: 32 + (26$95) #: (9 $ !9x)#. A."1 (1&".);._2 stdin''
```
**Decompression**
```
echo A.&(>:i.9)"1 (9 $ !9x) #: 95x #. 32 -~ 3 u: fread'sudoku.z'
```
Standard I/O is a bit clumsy in J since `jconsole` is actually a REPL, so I took the liberty to write the compressed output to file.
Finds the anagram index of each line, treats the resulting nine numbers as a base-(9!) number, and then finally converts to base-95, adds 32 and converts to ASCII just like in Martin Büttner's solution. The anagram index of a permutation of *1..n* is simply the index of the permutation in the lexically sorted list of all such permutations, e.g. `5 4 3 2 1` has anagram index *5! - 1 = 119*.
All the operations have easy inverses, so decompression is simple.
As a bonus, the examples are in a very J-friendly format, so input/output for decompressed sudokus are exactly as given in the examples (although the input to the encoder *requires* a trailing newline).
---
Compressed strings for the testcases:
```
#p8<!w=C6Cpgi/-+vn)FU]AHr\
"bC]wPv{8ze$l,+jkCPi0,e>-D
2}2EZZB;)WZQF@JChz}~-}}_<
#2Ofs0Mm]).e^raUu^f@sSMWc"
":kkCf2;^U_UDC?I\PC"[*gj|!
#TISE3?d7>oZ_I2.C16Z*gg
,@ CE;zX{.l\xRAc]~@vCw)8R
!oN{|Y6V"C.q<{gq(s?M@O]"]9
VORd2"*T,J;JSh<G=rR*8J1LT
#?bHF:y@oRI8e1Zdl5:BzYO.P.
```
[Answer]
# Python 2.5, 116 points
Code:
```
emptysud=[[' ']*9 for l in range(9)]
def encconfig(dig,sud):
conf1=[(sud[i].index(dig),i) for i in range(9)]; out=[]
for xgroup in range(3):
a=filter(lambda (x,y): xgroup*3<=x<(xgroup+1)*3, conf1)
b=[x-xgroup*3 for (x,y) in sorted(a,key = lambda (x,y): y)]
out.append([[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]].index(b))
for ygroup in range(3):
a=filter(lambda (x,y): ygroup*3<=y<(ygroup+1)*3, conf1)
b=[y-ygroup*3 for (x,y) in sorted(a,key = lambda (x,y): x)]
out.append([[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]].index(b))
return sum([out[i]*(6**i) for i in range(6)])
def decconfig(conf,dig,sud=emptysud):
inp=[]; conf1=[]; sud=[line[:] for line in sud]
for i in range(6):
inp.append([[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]][conf%6]); conf/=6
for groupx in range(3):
for groupy in range(3):
conf1.append((groupx*3+inp[groupx][groupy],groupy*3+inp[groupy+3][groupx]))
for (x,y) in conf1: sud[y][x]=dig
return sud
def compatible(sud,conf,dig):
a=reduce(lambda x,y: x+y, sud)
b=decconfig(conf,dig,sud)
c=reduce(lambda x,y: x+y, b)
return a.count(' ')-c.count(' ')==9
def encode(sud):
k=[encconfig(str(i),sud) for i in range(1,10)]; m=k[0]; p=6**6
cursud=decconfig(k[0],'1')
for i in range(1,9):
t=filter(lambda u: compatible(cursud,u,str(i+1)), range(6**6))
m=m+p*t.index(k[i]); p*=len(t)
cursud=decconfig(k[i],str(i+1),cursud)
return m
def decode(n):
k=[n%46656]; n/=46656; cursud=decconfig(k[-1],'1')
for i in range(2,10):
t=filter(lambda u: compatible(cursud,u,str(i)), range(6**6))
k.append(n%len(t)); n/=len(t); cursud=decconfig(t[k[-1]],str(i),cursud)
return cursud
def base95(n):
out=''
while n: out+=chr(32+n%95); n/=95
return out[::-1]
def base10(s): s=s[::-1]; return sum([(ord(s[i])-32)*(95**i) for i in range(len(s))])
import time
t0=time.clock()
for part in file('sudoku.txt','rb+').read().split('\r\n\r\n'):
sudoku=[line.split(' ') for line in part.split('\r\n')]
encsud=base95(encode(sudoku)); sud2=decode(base10(encsud))
print encsud,sud2==sudoku
print time.clock()-t0
```
Results:
```
!|/FC,">;&3z
rUH">FLSgT|
)3#m|:&Zxl1c
jh _N@MG/zr
%Iye;U(6(p;0
!21.+KD0//yG
"O\B*O@8,h`y
A$`TUE#rsQu
J}ANCYXX*y5
".u2KV#4K|%a
```
Very slow. Took 517 seconds to run and verify on my machine.
*encconfig* takes a sudoku board and a digit from 1-9, lists the x-y coordinates where that digit appears, and outputs a number in range(6\*\*6) that represents those coordinates. (the "digit configuration")
*decconfig* is the reverse function. It takes a number in range(6\*\*6), a digit, and a sudoku board (defaults to empty). It outputs the sudoku board overlayed with the digit configuration. If one of the positions in the digit configuration is already taken in the inputted sudoku board, the digit in that position is overwritten by the new digit.
*compatible* takes a sudoku board and a digit configuration (defined by conf and dig), overlays the digit configuration over the sudoku board and checks for conflicts. It then returns True or False depending on the result.
*encode* is the compression function. It takes a sudoku board and outputs a number representing it. It does this by first copying the positions of the 1's to an empty board and making a list of all the configurations of the number 2 which are compatible with the 1-configuration (that don't take up any of the places already taken by the 1's). It then finds the order of the board's actual 2-configuration in the list and stores it, then copies that configuration to the new board, which now contains only the 1's and 2's. It then lists all the configurations of the number 3 which are compatible with the positions of the 1's and 2's, and so on.
*decode* is the reverse function.
Python 2.5.
[Answer]
## Python 3, 120 points
This program lists all possible 3x3-blocks and remembers which one of them was actually present in the original Sudoku, then puts all those numbers together in a base-95 representation. Although this is very close to hard-coding, it compresses and decompresses the examples in about 5 seconds each on my machine.
```
import functools
def readSudoku(s):
values = [int(c) for c in s.split()]
blocks = []
for i in range(3):
for j in range(3):
block = []
for k in range(3):
for l in range(3):
block.append(values[i * 27 + k * 9 + j * 3 + l])
blocks.append(block)
return blocks
def writeSudoku(blocks):
text = ""
for i in range(9):
for j in range(9):
text += str(blocks[3 * (i // 3) + (j // 3)][3 * (i % 3) + (j % 3)]) + " "
text += "\n"
return text
def toASCII(num):
chars = "".join(chr(c) for c in range(32, 127))
if num == 0:
return chars[0]
else:
return (toASCII(num // len(chars)).lstrip(chars[0]) + chars[num % len(chars)])
def toNum(text):
chars = "".join(chr(c) for c in range(32, 127))
return sum((len(chars) ** i * chars.index(c) for (i, c) in enumerate(text[::-1])))
def compress(sudoku):
info = compressInfo(readSudoku(sudoku))
return toASCII(functools.reduce(lambda old, new: (old[0] + new[0] * old[1], old[1] * new[1]), info, (0, 1))[0])
def compressInfo(sudoku):
finished = [[0]*9]*9
indices = [(-1, 0)]*9
for (index, block) in enumerate(sudoku):
counter = 0
actual = -1
for (location, solution) in enumerate(possibleBlocks(finished, index)):
counter += 1
if block == solution:
actual = location
if actual == -1:
print(finished)
print(block)
raise ValueError
finished[index] = block
indices[index] = (actual, counter)
return indices
def decompress(text):
number = toNum(text)
finished = [[0]*9]*9
for i in range(9):
blocks = list(possibleBlocks(finished, i))
index = number % len(blocks)
number //= len(blocks)
finished[i] = blocks[index]
return writeSudoku(finished)
def possibleBlocks(grid, index):
horizontals = [grid[i] for i in (3 * (index // 3), 3 * (index // 3) + 1, 3 * (index // 3) + 2)]
verticals = [grid[i] for i in (index % 3, index % 3 + 3, index % 3 + 6)]
for i1 in range(1, 10):
if any((i1 in a[0:3] for a in horizontals)) or\
any((i1 in a[0::3] for a in verticals)):
continue
for i2 in range(1, 10):
if i2 == i1 or\
any((i2 in a[0:3] for a in horizontals)) or\
any((i2 in a[1::3] for a in verticals)):
continue
for i3 in range(1, 10):
if i3 in (i2, i1) or\
any((i3 in a[0:3] for a in horizontals)) or\
any((i3 in a[2::3] for a in verticals)):
continue
for i4 in range(1, 10):
if i4 in (i3, i2, i1) or\
any((i4 in a[3:6] for a in horizontals)) or\
any((i4 in a[0::3] for a in verticals)):
continue
for i5 in range(1, 10):
if i5 in (i4, i3, i2, i1) or\
any((i5 in a[3:6] for a in horizontals)) or\
any((i5 in a[1::3] for a in verticals)):
continue
for i6 in range(1, 10):
if i6 in (i5, i4, i3, i2, i1) or\
any((i6 in a[3:6] for a in horizontals)) or\
any((i6 in a[2::3] for a in verticals)):
continue
for i7 in range(1, 10):
if i7 in (i6, i5, i4, i3, i2, i1) or\
any((i7 in a[6:9] for a in horizontals)) or\
any((i7 in a[0::3] for a in verticals)):
continue
for i8 in range(1, 10):
if i8 in (i7, i6, i5, i4, i3, i2, i1) or\
any((i8 in a[6:9] for a in horizontals)) or\
any((i8 in a[1::3] for a in verticals)):
continue
for i9 in range(1, 10):
if i9 in (i8, i7, i6, i5, i4, i3, i2, i1) or\
any((i9 in a[6:9] for a in horizontals)) or\
any((i9 in a[2::3] for a in verticals)):
continue
yield [i1, i2, i3, i4, i5, i6, i7, i8, i9]
```
The main functions are `compress(sudoku)` and `decompress(text)`.
Outputs:
```
!%XIjS+]P{'Y
$OPMD&Sw&tlc
$1PdUMZ7K;W*
*=M1Ak9Oj6i\
!SY5:tDJxVo;
!F ]ki%jK>*R
'PXM4J7$s?#%
#9BJZP'%Ggse
*iAH-!9%QolJ
#&L6W6i> Dd6
```
[Answer]
**C#, 150 bytes**
**Compressed output:**
```
KYxnUjIpNe/YDnA
F97LclGuqeTcT2c
i6D1SvMVkS0jPlQ
32FOiIoUHpz5GGs
aAazPo2RJiH+IWQ
CwAA5NIMyNzSt1I
Cc2jOjU1+buCtVM
OgQv3Dz3PqsRvGA
eSxaW3wY5e6NGFc
olQvtpDOUPJXKGw
```
**How it works:**
It generates all possible permutations of 123456789 and remembers them.
Then it compares the permutations with the rows in the sudoku.
When a matching permutation for a giving row is found it remembers the index of that permutation. After each row it will remove all permutations where there is atleast one char in same position as the current row. This makes sure every number is unique in its column. Then it takes out all permutations that do not work anymore by the box-criteria.
Since the last row is trivial it generates 8 numbers.
I tested what the max value of each of those numbers would be and generated a digit-count-mask for each position of those. { 6, 5, 3, 5, 3, 1, 2, 1, 1 }. The first is obviously the longest with 362880 permutations.
Using the digitmask i construct a BigInteger with a leading 1 to make it 28 digits long. This results in 11 bytes total. Then those bytes get converted to base64. To save one char i remove the = sign at the end.
The reconstrcution works similiar.
It reconstructs the BigInteger from the base64string and then turns it into a string again and splitting it up again using the mentiond digit-count-mask. Those strings get parsed back to the indexes.
Then the algorithm does almost the same, instead of finding the row in the permutations it just uses the index to get the row, the rest works the same.
Probably this could be a bit better to really use the 94 possible charachters instead of only 64 but i lack the brainz to do this.
**Source**:
Copy- and pasteable to make it run with the 10 examples.
.dotNet-Fiddle tells me this exceeds the memorylimit so you need to run it on your machine to text.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
public class Programm
{
public static void Main(string[] args)
{
string[] input = new[] {
"973581426526473198184296753247865319398124675651739842819342567765918234432657981",
"724865193169243875385197246896724351273951684451386927542639718618572439937418562",
"157682349432519687698347251825476193713928465964135728541293876289761534376854912",
"835416927296857431417293658569134782123678549748529163652781394981345276374962815",
"628451793594732681713689542247315869961827354385964217156243978439578126872196435",
"123456789456789123789123456214365897365897214897214365531648972648972531972531648",
"145792836376584192298361754731928645859647321462135987624873519587419263913256478",
"527416938864329157139578642291854376348697521675132489712945863483261795956783214",
"246713985185496732937825146678542391493168257512379468824957613759631824361284579",
"861294573475318692392567814236459781154783269987621345529176438648932157713845926" };
string[] permutations = GetPermutations();
foreach (string sudoku in input)
{
int[] indices = _compressSudoku(sudoku, permutations).ToArray();
string compressedRepresentation = _toCompressedRepresentation(indices);
Console.WriteLine(compressedRepresentation);
indices = _fromCompressedRepresentation(compressedRepresentation);
string decompressedSudoku = _decompressSudoku(indices, permutations);
if (decompressedSudoku != sudoku)
throw new Exception();
}
Console.ReadKey();
}
static int[] _digitMask = new int[] { 6, 5, 3, 5, 3, 1, 2, 1, 1 };
private static int[] _fromCompressedRepresentation(string compressedRepresentation)
{
BigInteger big = new BigInteger(Convert.FromBase64String(compressedRepresentation + "="));
string stringValue = big.ToString().Substring(1);
List<int> indexes = new List<int>();
int i = 0;
while (stringValue.Length > 0)
{
int length = _digitMask[i++];
string current = stringValue.Substring(0, length);
stringValue = stringValue.Substring(length);
indexes.Add(int.Parse(current));
}
return indexes.ToArray(); ;
}
private static string _toCompressedRepresentation(int[] indices)
{
StringBuilder builder = new StringBuilder("1");
int i = 0;
foreach (int index in indices)
{
string mask = "{0:D" + _digitMask[i++].ToString() + "}";
builder.AppendFormat(mask, index);
}
string base64 = Convert.ToBase64String(BigInteger.Parse(builder.ToString()).ToByteArray());
return base64.Substring(0, base64.Length - 1); // remove the = at the end.
}
private static IEnumerable<int> _compressSudoku(string input, string[] remainingPermutations)
{
string[] localRemainingPermutations = null;
List<HashSet<char>> localUsed = null;
for (int i = 0; i < 8; i++)
{
string currentRow = _getCurrentRow(input, i);
if (i % 3 == 0)
{
localRemainingPermutations = remainingPermutations;
localUsed = _initLocalUsed();
}
int index = 0;
foreach (string permutation in localRemainingPermutations)
{
if (permutation == currentRow)
{
yield return index;
break;
}
index++;
}
remainingPermutations = remainingPermutations.Where(permutation => _isStillValidPermutation(currentRow, permutation)).ToArray();
if (i % 3 < 2)
{
for (int j = 0; j < 9; j++)
localUsed[j / 3].Add(currentRow[j]);
localRemainingPermutations = localRemainingPermutations.Where(permutation => _isStillValidLocalPermutation(permutation, localUsed)).ToArray();
}
}
}
private static string _decompressSudoku(int[] indices, string[] remainingPermutations)
{
StringBuilder result = new StringBuilder();
string[] localRemainingPermutations = null;
List<HashSet<char>> localUsed = null;
for (int i = 0; i < 9; i++)
{
if (i % 3 == 0)
{
localRemainingPermutations = remainingPermutations;
localUsed = _initLocalUsed();
}
string currentRow = localRemainingPermutations[i < indices.Length ? indices[i] : 0];
result.Append(currentRow);
remainingPermutations = remainingPermutations.Where(permutation => _isStillValidPermutation(currentRow, permutation)).ToArray();
if (i % 3 < 2)
{
for (int j = 0; j < 9; j++)
localUsed[j / 3].Add(currentRow[j]);
localRemainingPermutations = localRemainingPermutations.Where(permutation => _isStillValidLocalPermutation(permutation, localUsed)).ToArray();
}
}
return result.ToString();
}
private static string _getCurrentRow(string input, int i)
{
return new string(input.Skip(i * 9).Take(9).ToArray());
}
private static List<HashSet<char>> _initLocalUsed()
{
return new List<HashSet<char>> { new HashSet<char>(), new HashSet<char>(), new HashSet<char>() };
}
private static bool _isStillValidLocalPermutation(string permutation, List<HashSet<char>> localUsed)
{
for (int i = 0; i < 9; i++)
{
if (localUsed[i / 3].Contains(permutation[i]))
return false;
}
return true;
}
private static bool _isStillValidPermutation(string currentRow, string permutation)
{
return permutation.Select((c, j) => c != currentRow[j]).All(b => b);
}
static string[] GetPermutations(char[] chars = null)
{
if (chars == null)
chars = new[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
if (chars.Length == 2)
return new[] { new String(chars), new String(chars.Reverse().ToArray()) };
return chars.SelectMany(c => GetPermutations(chars.Where(sc => sc != c).ToArray()), (c, s) => c + s).ToArray();
}
}
```
[Answer]
# Perl - 290 characters = 290 points
This program uses no hard coding and reliably compresses a grid into exactly 29 characters (theoretically it would be possible to find some smaller ones).
Here's how it works:
* First convert the 9 x 9 array to 60 numbers. This can be done as the last column, the last row, and the final square of each 3 x 3 cell can be dropped.
* Then convert using bigint to a single integer, using 9^60 elements.
* Then convert the bigint to base 95.
Compressor and decompressor:
```
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use bigint;
sub compress
{
my @grid;
my @nums;
while (<>)
{
push @grid, [split];
}
# encode into 60 numbers omitting last from each row, column and 3 x 3 square
my $i;
my $j;
for ($i=0; $i<=7; $i++)
{
for ($j=0; $j<=7; $j++)
{
push @nums, $grid[$i][$j] if (($i % 3 !=2 ) || ($j % 3 !=2));
}
}
# encode into a big int
my $code = 0;
foreach my $n (@nums)
{
$code = $code * 9 + ($n-1);
}
# print in base 95
my $out="";
while ($code)
{
my $digit = $code % 95;
$out = chr($digit+32).$out;
$code -= $digit;
$code /= 95;
}
print "$out";
}
sub decompress
{
my @grid;
my @nums;
my $code = 0;
# Read from base 95 into bigint
while (<>)
{
chomp;
foreach my $char (split (//, $_))
{
my $c =ord($char)-32;
$code*=95;
$code+=$c;
}
}
# convert back to 60 numbers
for (my $n = 0; $n<60; $n++)
{
my $d = $code % 9;
$code -= $d;
$code/=9;
unshift @nums, $d+1;
}
# print filling in last column, row and 3 x 3 square
for (my $i=0; $i<=8; $i++)
{
for (my $j=0; $j<=8; $j++)
{
if ($j == 8)
{
my $tot = 0;
for (my $jj = 0; $jj<=7; $jj++)
{
$tot += $grid[$i][$jj];
}
$grid[$i][$j]=45-$tot;
}
elsif ($i == 8)
{
my $tot = 0;
for (my $ii = 0; $ii<=7; $ii++)
{
$tot += $grid[$ii][$j];
}
$grid[$i][$j]=45-$tot;
}
elsif (($i % 3 == 2 ) && ($j % 3 == 2))
{
my $tot = 0;
for (my $ii = $i-2; $ii<=$i; $ii++)
{
for (my $jj = $j-2; $jj<=$j; $jj++)
{
next if (($ii % 3 == 2 ) && ($jj % 3 == 2));
$tot += $grid[$ii][$jj];
}
}
$grid[$i][$j]=45-$tot;
}
else
{
$grid[$i][$j] = shift @nums;
}
print $grid[$i][$j].(($j==8)?"":" ");
}
print "\n";
}
}
my $decompress;
GetOptions ("d|decompress" => \$decompress);
if ($decompress)
{
decompress;
}
else
{
compress;
}
```
[Answer]
# PHP, 214
```
<?php
// checks each row/col/block and removes impossible candidates
function reduce($cand){
do{
$old = $cand;
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) == 1){ // if filled in
// remove values from row and col and block
$remove = $cand[$r][$c];
for($i = 0; $i < 9; ++$i){
$cand[$r][$i] = array_diff($cand[$r][$i],$remove);
$cand[$i][$c] = array_diff($cand[$i][$c],$remove);
$br = floor($r/3)*3+$i/3;
$bc = floor($c/3)*3+$i%3;
$cand[$br][$bc] = array_diff($cand[$br][$bc],$remove);
}
$cand[$r][$c] = $remove;
}
}}
}while($old != $cand);
return $cand;
}
// checks candidate list for completion
function done($cand){
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) != 1)
return false;
}}
return true;
}
// board format: [[1,2,0,3,..],[..],..], $b[$row][$col]
function solve($board){
$cand = [[],[],[],[],[],[],[],[],[]];
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if($board[$r][$c]){ // if filled in
$cand[$r][$c] = [$board[$r][$c]];
}else{
$cand[$r][$c] = range(1, 9);
}
}}
$cand = reduce($cand);
if(done($cand)) // goto not really necessary
goto end; // but it feels good to use it
else return false;
end:
// back to board format
$b = [];
for($r = 0; $r < 9; ++$r){
$b[$r] = [];
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) == 1)
$b[$r][$c] = array_pop($cand[$r][$c]);
else
$b[$r][$c] = 0;
}
}
return $b;
}
function add_zeros($board, $ind){
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
$R = ($r + (int)($ind/9)) % 9;
$C = ($c + (int)($ind%9)) % 9;
if($board[$R][$C]){
$tmp = $board[$R][$C];
$board[$R][$C] = 0;
if(!solve($board))
$board[$R][$C] = $tmp;
}
}}
return $board;
}
function base95($str, $b, $z){
$tmp = gmp_init($str, $b); $zero = gmp_init(0); $gmp95 = gmp_init(95);
$out = '';
while(gmp_cmp($tmp, $zero) > 0){
$arr = gmp_div_qr($tmp, $gmp95);
$tmp = $arr[0];
$out .= chr(32+gmp_intval($arr[1]));
}
$out = chr((32+($z << 2))|($b - 10)) . strrev($out);
return $out;
}
function encode($board, $ind){
// remove last row+col
$board[8] = [0,0,0,0,0,0,0,0,0];
foreach($board as &$j) $j[8] = 0;
// remove bottom corner of each box
$board[2][2] = $board[2][5] = $board[5][2] = $board[5][5] = 0;
$board = add_zeros($board, $ind);
$str = '';$z=0;
for($r = 0; $r < 8; ++$r){
for($c = 0; $c < 8; ++$c){
if(($r==2||$r==5)&&($c==2||$c==5)) continue;
if($str == '' && !$board[$r][$c]) ++$z;
else $str .= $board[$r][$c];
}
}
$b10 = base95(rtrim($str,'0'), 10, $z);
$b11 = base95(rtrim(str_replace(['00'],['A'],$str),'0'), 11, $z);
$b12 = base95(rtrim(str_replace(['000','00'],['B','A'],$str),'0'), 12, $z);
$l10 = strlen($b10);
$l11 = strlen($b11);
$l12 = strlen($b12);
var_dump($z);
if($l10 < $l11)
if($l10 < $l12)
return $b10;
else
return $b12;
else
if($l11 < $l12)
return $b11;
else
return $b12;
}
function decode($str){
$fc = ord($str[0]);
$base = 10 + ($fc & 3);
$z = ($fc - 32) >> 2;
$tmp = gmp_init(0);
$zero = gmp_init(0); $gmp95 = gmp_init(95);
while(strlen($str = substr($str, 1))){
$tmp = gmp_mul($tmp, $gmp95);
$tmp = gmp_add($tmp, gmp_init(ord($str[0])-32));
}
$str = gmp_strval($tmp, $base);
$expanded = str_repeat('0', $z) . str_replace(['a','b'],['00','000'],$str) . str_repeat('0', 81);
$board = [];
$ind = 0;
for($i = 0; $i < 8; ++$i){
$board[$i] = [];
for($j = 0; $j < 8; ++$j){
if(($i == 2 || $i == 5) && ($j == 2 || $j == 5))
$board[$i][$j] = 0;
else
$board[$i][$j] = (int)$expanded[$ind++];
}
$board[$i][8] = 0;
}
$board[8] = [0,0,0,0,0,0,0,0,0];
return solve($board);
}
function printBoard($board){
for($i = 0; $i < 9; ++$i){
echo implode(' ', $board[$i]) . PHP_EOL;
}
flush();
}
function readBoard(){
$board = [];
for($r = 0; $r < 9; ++$r){
$board[$r] = fscanf(STDIN, "%d%d%d%d%d%d%d%d%d");
}
return $board;
}
if(isset($argv[1])){
if($argv[1] === 'enc'){
$board = readBoard();
$bests = ''; $bestl = 999;
for($i = 0; $i < 71; ++$i){
$str = encode($board, $i);
$len = strlen($str);
if($len < $bestl){
$bestl = $len;
$bests = $str;
}
}
echo $bests . PHP_EOL;
}else if($argv[1] === 'dec'){
echo printBoard(decode(trim(fgets(STDIN))));
}
}else{
echo "Missing argument. Use `{$argv[0]} [enc|dec]`.\n";
}
```
This solution first clears out the right column and bottom row, as well as the bottom-right corner of each 3x3 block. It then tries clearing out a cell. If a simple solution exists, the cell remains blank.
Then, the sudoku grid is formatted into a string, from left to right and top to bottom, excluding the right column, bottom row, and bottom-right corner. Leading zeros are counted (let this be `z`) and removed. Trailing zeros are likewise removed.
The string is formatted into either a base 10, 11, or 12 integer (let this base be `b`), with `A` representing two zeros, and `B`, three.
This is converted into a base-95 integer, and prepended by the base-95 digit representing `z << 2 | (b - 10)`.
Call `php sudoku-compress.php enc` to encode, and `php sudoku-compress.php dec` to decode. Encoder takes the format given in the question, with a mandatory trailing newline.
Test outputs:
```
R'Ngxgi#Hu~+cR)0nE)+
Veu-b454j|:tRm(b-Xk'I
V.{mi;*6-/9Ufu[~GE"e>
F/YgX]PeyeKX5=M_+,z+Z
R&3mEHyZ6sSF'-$L<:VmX
"#b'npsIv0%L,t0yr^a.+'&
UNjx*#~I/siBGck7u9eaC%
Z!SuM^f{e<ji@F&hP-S<
*0:43tD r;=x8|&I0/k[&%
B1Mm-dx@G}[2lZId/-'h{zU
```
[Answer]
# Java, 330 Points
Before I get ridiculed for such a high score let me clarify that I attempted to try and solve this in a different kind of way knowing it probably wouldn't be quite as optimal as some of the better answers here. I was more or less curious if I could get *close* which to my surprise I didn't realize just how much worse it would turn out. Here is the run down of what my approach was here:
1. Develop an algo for solving a Sudoku puzzle.
2. Develop a scrambling algo that can still be solvable. It does this somewhat randomly while removing clues that can be trivially determined before hand. I could get to about 22 clues reliably before it took far too long.
3. Once scrambled, the puzzle could be represented by a triplet of single digit integers for each clue, in my case 22 triplets of 3. I thought if I could combine these into a single 66 digit number then base95 encode this then I have something that can be easily decoded.
The encoded string ended up being longer than I hoped at generally around 33 characters long. At which point I tried an alternative way than using Java BigInteger where I created a large number from an 81 bit mask representing the 81 cells of a grid where 1 means a clue exists for this cell. I then combined that bitmask to 4 bit representations of each cell value in sequential order, rounded up to bytes and found that I roughly got the same encoded string length after base95 encoded.
So basically I am posting my code in case anybody was interested in a different approach that didn't work out so well.
**Class Puzz**
```
public class Puzz {
enum By {
Row, Column, Block
}
static final List<Integer> NUMBERS = Arrays.asList(new Integer[] { 1, 2, 3,
4, 5, 6, 7, 8, 9 });
List<Square> entries = new ArrayList<Square>();
HashMap<Integer, List<Square>> squaresByRow = new HashMap<Integer, List<Square>>();
HashMap<Integer, List<Square>> squaresByColumn = new HashMap<Integer, List<Square>>();
HashMap<Integer, List<Square>> squaresByBlock = new HashMap<Integer, List<Square>>();
public Puzz(int[][] data) {
// Create squares put them in squares by row hashtable
for (int r = 0; r < 9; r++) {
List<Square> squaresInRow = new ArrayList<Square>();
for (int c = 0; c < 9; c++) {
Square square = new Square(r, c, data[r][c], this);
entries.add(square);
squaresInRow.add(square);
}
squaresByRow.put(r, squaresInRow);
}
// Put squares in column hash table
for (int c = 0; c < 9; c++) {
List<Square> squaresInColumn = new ArrayList<Square>();
for (int r = 0; r < 9; r++) {
squaresInColumn.add(squaresByRow.get(r).get(c));
}
squaresByColumn.put(c, squaresInColumn);
}
// Put squares in block hash table
for (int i = 1; i < 10; i++) {
squaresByBlock.put(i, new ArrayList<Square>());
}
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
int block = getBlock(r, c);
squaresByBlock.get(block).add(get(r, c));
}
}
// Discover the possibilities
updatePossibilities();
}
public void updatePossibilities() {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
Square theSquare = get(r, c);
if (theSquare.value != 0) {
theSquare.possibilities.removeAll(NUMBERS);
continue;
} else {
theSquare.possibilities.addAll(NUMBERS);
}
int block = getBlock(r, c);
HashSet<Square> squares = new HashSet<Square>();
squares.addAll(squaresByRow.get(r));
squares.addAll(squaresByColumn.get(c));
squares.addAll(squaresByBlock.get(block));
for (Square s : squares) {
if (s == theSquare)
continue;
theSquare.possibilities.remove(s.value);
}
}
}
}
public int getValue(int row, int column) {
return squaresByRow.get(row).get(column).value;
}
public Square get(int row, int column) {
return squaresByRow.get(row).get(column);
}
public boolean set(int row, int column, int value) {
if (value == 0) {
squaresByRow.get(row).get(column).value = 0;
updatePossibilities();
return true;
}
if (isValid(row, column, value)) {
squaresByRow.get(row).get(column).value = value;
updatePossibilities();
return true;
} else {
return false;
}
}
public boolean isValidSubset(By subset, int row, int column, int value) {
List<Dubs> dubss = new ArrayList<Dubs>();
List<Trips> tripss = new ArrayList<Trips>();
Square theSquare = get(row, column);
int block = getBlock(row, column);
List<Square> squares = new ArrayList<Square>();
switch (subset) {
case Row:
squares.addAll(squaresByRow.get(row));
break;
case Column:
squares.addAll(squaresByColumn.get(column));
break;
default:
squares.addAll(squaresByBlock.get(block));
break;
}
for (Square r : squares) {
if (r == theSquare)
continue;
// if any of the impacted squares have this value then it is not a
// valid value
if (r.value == value)
return false;
if (r.possibilities.size() == 3) {
List<Integer> poss = new ArrayList<Integer>(r.possibilities);
tripss.add(new Trips(poss.get(0), poss.get(1), poss.get(2),
r.row, r.col));
}
if (r.possibilities.size() == 2) {
List<Integer> poss = new ArrayList<Integer>(r.possibilities);
dubss.add(new Dubs(poss.get(0), poss.get(1), r.row, r.col));
}
}
// Find the trips and rule out the value if a triplet exists in squares
List<Trips> tripsCopy = new ArrayList<Trips>(tripss);
for (Trips trips : tripsCopy) {
int countOfOccurrences = 0;
for (Trips tr : tripss) {
if (tr.equals(trips) && !(tr.row == row && tr.col == column))
countOfOccurrences++;
}
for (Dubs dubs : dubss) {
if (trips.containedWithin(dubs)
&& !(dubs.row == row && dubs.col == column))
countOfOccurrences++;
}
if (countOfOccurrences == 3 && trips.containedWithin(value))
return false;
}
// Find the dubs and rule out the value if a double exists in squares
List<Dubs> dubsCopy = new ArrayList<Dubs>(dubss);
for (Dubs dubs : dubsCopy) {
int countOfOccurrences = 0;
for (Dubs du : dubss) {
// Count occurrences of Dubs that are not the tested square
if (du.equals(dubs) && !(du.row == row && du.col == column))
countOfOccurrences++;
}
if (countOfOccurrences == 2 && dubs.containedWithin(value))
return false;
}
return true;
}
public boolean isValid(int row, int column, int value) {
return isValidSubset(By.Row, row, column, value)
&& isValidSubset(By.Column, row, column, value)
&& isValidSubset(By.Block, row, column, value);
}
public int getBlock(int row, int column) {
int blockRow = (int) Math.floor(row / 3);
int columnRow = (int) Math.floor(column / 3) + 1;
return (blockRow * 3) + columnRow;
}
public Puzz solve(Puzz arg, boolean top) throws Exception {
// Make an original copy of the array
Puzz p = (Puzz) arg.clone();
for (int i = 1; i < 10; i++) {
for (Square s : p.squaresByBlock.get(i)) {
if (s.value == 0) {
for (Integer number : NUMBERS) {
if (p.set(s.row, s.col, number)) {
// System.out.println(p);
Puzz solved = solve(p, false);
if (solved != null)
return solved;
}
}
// no numbers fit here, return null and backtrack
p.set(s.row, s.col, 0);
return null;
}
}
}
// Check for remaining 0's
for (Square s : p.entries) {
if (s.value == 0)
return null;
}
return p;
}
public Puzz scramble(int clues) throws Exception {
Puzz p = (Puzz) clone();
Random rand = new Random();
int removed = 0;
//Remove the last row, it is a freebie
int toRemove = 81 - clues - 15;
for (int c = 0; c < 9; c++) {
p.set(8, c, 0);
}
p.set(0, 0, 0);
p.set(0, 3, 0);
p.set(0, 6, 0);
p.set(3, 0, 0);
p.set(3, 3, 0);
p.set(3, 6, 0);
// Keeping track of this because randomly removing squares can potentially create an
// unsolvable situation
HashSet<Square> alreadyTried = new HashSet<Square>();
while (removed < toRemove) {
if (alreadyTried.size() >= ((toRemove + clues) - removed)) {
// Start over
removed = 0;
alreadyTried = new HashSet<Square>();
p = (Puzz)clone();
for (int c = 0; c < 9; c++) {
p.set(8, c, 0);
}
p.set(0, 0, 0);
p.set(0, 3, 0);
p.set(0, 6, 0);
p.set(3, 0, 0);
p.set(3, 3, 0);
p.set(3, 6, 0);
}
int randX = rand.nextInt((7) + 1);
int randY = rand.nextInt((8) + 1);
int existingValue = p.getValue(randX, randY);
if (existingValue != 0) {
p.set(randX, randY, 0);
// confirm it is still solvable after removing this item
Puzz psol = solve(p, true);
if (psol != null && psol.equals(this)) {
removed++;
alreadyTried = new HashSet<Square>();
System.out.println("Clues Remaining: " + (81 - 15 - removed));
} else {
// otherwise set it back to what it was and try again
p.set(randX, randY, existingValue);
Square s = new Square(randX, randY, existingValue, p);
alreadyTried.add(s);
}
}
}
p.updatePossibilities();
return p;
}
public static String encode(Puzz p) { // Remove all zero'ed items
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 9; i++) {
for (Square s : p.squaresByRow.get(i)) {
if (s.value == 0)
continue;
sb.append(s.row).append(s.col).append(s.value);
}
}
// number mod 95 gives lowest digit, subtract that from original number
BigInteger num = new BigInteger(sb.toString());
byte[] numBytes = num.toByteArray();
StringBuffer retVal = new StringBuffer();
while (num.compareTo(BigInteger.ZERO) > 0) {
int modu = num.mod(new BigInteger("95")).intValue();
retVal.append((char) (modu + 32));
num = num.subtract(new BigInteger("" + modu));
num = num.divide(new BigInteger("95"));
}
return retVal.toString();
}
@Override
public boolean equals(Object arg0) {
if (arg0 == null || !(arg0 instanceof Puzz))
return false;
Puzz p = (Puzz) arg0;
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
int val1 = getValue(r, c);
int val2 = p.getValue(r, c);
if (val1 != val2)
return false;
}
}
return true;
}
@Override
protected Object clone() throws CloneNotSupportedException {
int[][] data = new int[9][9];
for (Square square : entries) {
data[square.row][square.col] = square.value;
}
return new Puzz(data);
}
@Override
public String toString() {
if (entries == null)
return "";
StringBuffer sb = new StringBuffer();
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
sb.append(getValue(r, c)).append(' ');
}
sb.append('\n');
}
return sb.toString();
}
}
class Square {
public Square(int row, int col, Puzz p) {
this.row = row;
this.col = col;
this.p = p;
}
public Square(int row, int col, int value, Puzz p) {
this(row, col, p);
this.value = value;
}
int row;
int col;
int value;
HashSet<Integer> possibilities = new HashSet<Integer>(Puzz.NUMBERS);
Puzz p;
@Override
protected Object clone() throws CloneNotSupportedException {
Square s = new Square(row, col, value, p);
s.possibilities = new HashSet<Integer>();
for (Integer val : possibilities) {
s.possibilities.add(new Integer(val));
}
return s;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Square))
return false;
Square s = (Square) obj;
return row == s.row && col == s.col && value == s.value
&& p.equals(s.p);
}
@Override
public int hashCode() {
return row ^ col ^ value ^ p.hashCode();
}
}
class Dubs {
int p1;
int p2;
int row, col;
public Dubs(int p1, int p2) {
this.p1 = p1;
this.p2 = p2;
}
public Dubs(int p1, int p2, int row, int col) {
this(p1, p2);
this.row = row;
this.col = col;
}
public boolean containedWithin(int value) {
return (p1 == value || p2 == value);
}
@Override
public boolean equals(Object arg0) {
if (!(arg0 instanceof Dubs))
return false;
Dubs d = (Dubs) arg0;
return (this.p1 == d.p1 || this.p1 == d.p2)
&& (this.p2 == d.p1 || this.p2 == d.p2);
}
}
class Trips {
int p1;
int p2;
int p3;
int row, col;
public Trips(int p1, int p2) {
this.p1 = p1;
this.p2 = p2;
}
public Trips(int p1, int p2, int p3) {
this(p1, p2);
this.p3 = p3;
}
public Trips(int p1, int p2, int p3, int row, int col) {
this(p1, p2, p3);
this.row = row;
this.col = col;
}
public boolean containedWithin(int value) {
return (p1 == value || p2 == value || p3 == value);
}
public boolean containedWithin(Dubs d) {
return (d.p1 == p1 || d.p1 == p2 || d.p1 == p3)
&& (d.p2 == p1 || d.p2 == p2 || d.p2 == p3);
}
public boolean equals(Object arg0) {
if (!(arg0 instanceof Trips))
return false;
Trips t = (Trips) arg0;
return (this.p1 == t.p1 || this.p1 == t.p2 || this.p1 == t.p3)
&& (this.p2 == t.p1 || this.p2 == t.p2 || this.p2 == t.p3)
&& (this.p3 == t.p1 || this.p3 == t.p2 || this.p3 == t.p3);
}
}
```
**My Test Case**
```
public class TestCompression extends TestCase {
public static int[][] test1 = new int[][] {
new int[] { 9, 7, 3, 5, 8, 1, 4, 2, 6 },
new int[] { 5, 2, 6, 4, 7, 3, 1, 9, 8 },
new int[] { 1, 8, 4, 2, 9, 6, 7, 5, 3 },
new int[] { 2, 4, 7, 8, 6, 5, 3, 1, 9 },
new int[] { 3, 9, 8, 1, 2, 4, 6, 7, 5 },
new int[] { 6, 5, 1, 7, 3, 9, 8, 4, 2 },
new int[] { 8, 1, 9, 3, 4, 2, 5, 6, 7 },
new int[] { 7, 6, 5, 9, 1, 8, 2, 3, 4 },
new int[] { 4, 3, 2, 6, 5, 7, 9, 8, 1 } };
public static int[][] test2 = new int[][] {
new int[] { 7, 2, 4, 8, 6, 5, 1, 9, 3 },
new int[] { 1, 6, 9, 2, 4, 3, 8, 7, 5 },
new int[] { 3, 8, 5, 1, 9, 7, 2, 4, 6 },
new int[] { 8, 9, 6, 7, 2, 4, 3, 5, 1 },
new int[] { 2, 7, 3, 9, 5, 1, 6, 8, 4 },
new int[] { 4, 5, 1, 3, 8, 6, 9, 2, 7 },
new int[] { 5, 4, 2, 6, 3, 9, 7, 1, 8 },
new int[] { 6, 1, 8, 5, 7, 2, 4, 3, 9 },
new int[] { 9, 3, 7, 4, 1, 8, 5, 6, 2 } };
public static int[][] test3 = new int[][] {
new int[] { 1, 5, 7, 6, 8, 2, 3, 4, 9 },
new int[] { 4, 3, 2, 5, 1, 9, 6, 8, 7 },
new int[] { 6, 9, 8, 3, 4, 7, 2, 5, 1 },
new int[] { 8, 2, 5, 4, 7, 6, 1, 9, 3 },
new int[] { 7, 1, 3, 9, 2, 8, 4, 6, 5 },
new int[] { 9, 6, 4, 1, 3, 5, 7, 2, 8 },
new int[] { 5, 4, 1, 2, 9, 3, 8, 7, 6 },
new int[] { 2, 8, 9, 7, 6, 1, 5, 3, 4 },
new int[] { 3, 7, 6, 8, 5, 4, 9, 1, 2 } };
public static int[][] test4 = new int[][] {
new int[] { 8, 3, 5, 4, 1, 6, 9, 2, 7 },
new int[] { 2, 9, 6, 8, 5, 7, 4, 3, 1 },
new int[] { 4, 1, 7, 2, 9, 3, 6, 5, 8 },
new int[] { 5, 6, 9, 1, 3, 4, 7, 8, 2 },
new int[] { 1, 2, 3, 6, 7, 8, 5, 4, 9 },
new int[] { 7, 4, 8, 5, 2, 9, 1, 6, 3 },
new int[] { 6, 5, 2, 7, 8, 1, 3, 9, 4 },
new int[] { 9, 8, 1, 3, 4, 5, 2, 7, 6 },
new int[] { 3, 7, 4, 9, 6, 2, 8, 1, 5 } };
public static int[][] test5 = new int[][] {
new int[] { 6, 2, 8, 4, 5, 1, 7, 9, 3 },
new int[] { 5, 9, 4, 7, 3, 2, 6, 8, 1 },
new int[] { 7, 1, 3, 6, 8, 9, 5, 4, 2 },
new int[] { 2, 4, 7, 3, 1, 5, 8, 6, 9 },
new int[] { 9, 6, 1, 8, 2, 7, 3, 5, 4 },
new int[] { 3, 8, 5, 9, 6, 4, 2, 1, 7 },
new int[] { 1, 5, 6, 2, 4, 3, 9, 7, 8 },
new int[] { 4, 3, 9, 5, 7, 8, 1, 2, 6 },
new int[] { 8, 7, 2, 1, 9, 6, 4, 3, 5 } };
public static int[][] test6 = new int[][] {
new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
new int[] { 4, 5, 6, 7, 8, 9, 1, 2, 3 },
new int[] { 7, 8, 9, 1, 2, 3, 4, 5, 6 },
new int[] { 2, 1, 4, 3, 6, 5, 8, 9, 7 },
new int[] { 3, 6, 5, 8, 9, 7, 2, 1, 4 },
new int[] { 8, 9, 7, 2, 1, 4, 3, 6, 5 },
new int[] { 5, 3, 1, 6, 4, 8, 9, 7, 2 },
new int[] { 6, 4, 8, 9, 7, 2, 5, 3, 1 },
new int[] { 9, 7, 2, 5, 3, 1, 6, 4, 8 } };
public static int[][] test7 = new int[][] {
new int[] { 1, 4, 5, 7, 9, 2, 8, 3, 6 },
new int[] { 3, 7, 6, 5, 8, 4, 1, 9, 2 },
new int[] { 2, 9, 8, 3, 6, 1, 7, 5, 4 },
new int[] { 7, 3, 1, 9, 2, 8, 6, 4, 5 },
new int[] { 8, 5, 9, 6, 4, 7, 3, 2, 1 },
new int[] { 4, 6, 2, 1, 3, 5, 9, 8, 7 },
new int[] { 6, 2, 4, 8, 7, 3, 5, 1, 9 },
new int[] { 5, 8, 7, 4, 1, 9, 2, 6, 3 },
new int[] { 9, 1, 3, 2, 5, 6, 4, 7, 8 } };
public static int[][] test8 = new int[][] {
new int[] { 5, 2, 7, 4, 1, 6, 9, 3, 8 },
new int[] { 8, 6, 4, 3, 2, 9, 1, 5, 7 },
new int[] { 1, 3, 9, 5, 7, 8, 6, 4, 2 },
new int[] { 2, 9, 1, 8, 5, 4, 3, 7, 6 },
new int[] { 3, 4, 8, 6, 9, 7, 5, 2, 1 },
new int[] { 6, 7, 5, 1, 3, 2, 4, 8, 9 },
new int[] { 7, 1, 2, 9, 4, 5, 8, 6, 3 },
new int[] { 4, 8, 3, 2, 6, 1, 7, 9, 5 },
new int[] { 9, 5, 6, 7, 8, 3, 2, 1, 4 } };
public static int[][] test9 = new int[][] {
new int[] { 2, 4, 6, 7, 1, 3, 9, 8, 5 },
new int[] { 1, 8, 5, 4, 9, 6, 7, 3, 2 },
new int[] { 9, 3, 7, 8, 2, 5, 1, 4, 6 },
new int[] { 6, 7, 8, 5, 4, 2, 3, 9, 1 },
new int[] { 4, 9, 3, 1, 6, 8, 2, 5, 7 },
new int[] { 5, 1, 2, 3, 7, 9, 4, 6, 8 },
new int[] { 8, 2, 4, 9, 5, 7, 6, 1, 3 },
new int[] { 7, 5, 9, 6, 3, 1, 8, 2, 4 },
new int[] { 3, 6, 1, 2, 8, 4, 5, 7, 9 } };
public static int[][] test10 = new int[][] {
new int[] { 8, 6, 1, 2, 9, 4, 5, 7, 3 },
new int[] { 4, 7, 5, 3, 1, 8, 6, 9, 2 },
new int[] { 3, 9, 2, 5, 6, 7, 8, 1, 4 },
new int[] { 2, 3, 6, 4, 5, 9, 7, 8, 1 },
new int[] { 1, 5, 4, 7, 8, 3, 2, 6, 9 },
new int[] { 9, 8, 7, 6, 2, 1, 3, 4, 5 },
new int[] { 5, 2, 9, 1, 7, 6, 4, 3, 8 },
new int[] { 6, 4, 8, 9, 3, 2, 1, 5, 7 },
new int[] { 7, 1, 3, 8, 4, 5, 9, 2, 6 } };
@Test
public void test2() throws Exception {
int encodedLength = 0;
Puzz expected = new Puzz(test1);
Puzz test = (Puzz) expected.clone();
long start = System.currentTimeMillis();
test = test.scramble(22);
long duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
String encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test2);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test3);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test4);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test5);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test6);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test7);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test8);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test9);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test10);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
encodedLength += encoded.length();
System.out.println("Final Result: " + encodedLength);
}
}
```
**Test Output**
```
Duration of scramble for 22 clue puzzle: 427614
Scrambled
0 0 3 0 0 0 0 0 6
0 2 0 0 0 0 0 9 0
0 0 0 0 9 6 7 5 0
0 4 0 0 0 5 0 1 0
0 0 0 1 0 0 0 0 0
0 5 0 0 0 0 8 4 0
0 0 0 3 0 0 5 0 7
7 0 0 9 0 8 0 3 0
0 0 0 0 0 0 0 0 0
Building encoded string: U5[XZ+C6Bgf)}O."gDE)`\)kNv7*6}1w+
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 167739
Scrambled
0 2 4 0 0 0 0 0 0
1 6 0 0 4 0 8 0 5
0 0 5 0 9 7 2 0 0
0 0 0 0 2 4 0 0 1
0 0 3 9 0 0 0 0 0
0 0 0 0 0 0 0 0 7
0 4 0 0 0 0 0 0 8
0 1 0 5 0 0 0 3 0
0 0 0 0 0 0 0 0 0
Building encoded string: 7\c^oE}`H6@P.&E)Zu\t>B"k}Vf<[0a3&
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 136364
Scrambled
0 0 7 0 8 0 0 0 0
0 3 2 0 0 9 6 0 0
0 0 0 0 0 0 2 5 0
0 2 0 0 0 6 0 0 0
0 0 0 9 0 0 0 0 0
0 0 4 1 0 5 7 2 0
5 0 1 0 0 0 0 7 0
2 8 9 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
Building encoded string: [S#bHlTDwS,&w,moQ{WN}Z9!{1C>.vN{-
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 392150
Scrambled
0 0 0 0 0 6 0 0 0
0 9 0 0 0 0 0 0 1
4 0 0 0 0 3 6 0 8
0 0 0 0 0 0 0 8 0
0 0 3 0 7 8 0 0 9
7 0 0 0 0 0 0 0 3
6 0 2 0 0 0 0 9 0
9 0 1 3 4 0 2 0 0
0 0 0 0 0 0 0 0 0
Building encoded string: T-yKJ2<d)Dj~[~>]334*9YpxM<JQNf2|<
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 169355
Scrambled
0 0 0 0 0 1 0 0 0
0 9 4 7 0 0 0 8 0
0 1 3 0 0 0 5 0 2
0 0 0 0 0 0 0 0 9
0 0 0 0 2 7 3 5 4
0 8 0 0 0 0 0 1 0
0 0 0 0 4 0 9 0 8
0 0 0 5 0 0 0 0 6
0 0 0 0 0 0 0 0 0
Building encoded string: 5@.=FmOKws7jl5*hWMQqqou\lv'e^Q}D:
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 786
Scrambled
0 2 3 0 0 6 0 0 0
0 5 0 7 0 0 1 2 3
0 8 0 0 2 0 0 0 0
0 0 0 0 0 5 0 0 7
0 6 5 8 0 0 0 0 0
0 0 7 0 0 4 3 0 0
0 3 0 0 4 0 0 0 2
0 0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0 0
Building encoded string: wY%(O9tOSDZu-PBaFl^.f0xH7C~e)=\3&
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 826530
Scrambled
0 0 0 0 9 0 0 0 0
0 0 0 0 0 0 0 0 0
0 9 0 3 0 1 7 0 0
0 3 0 0 0 8 0 4 5
0 0 9 0 0 7 3 0 0
0 0 2 0 3 0 0 8 0
6 0 0 0 0 0 0 0 9
5 0 0 4 1 0 2 0 3
0 0 0 0 0 0 0 0 0
Building encoded string: K|>.Aa?,8e&NRL;*ut=+Iqk8E$@&-zlF9
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 4834
Scrambled
0 2 0 0 1 0 0 3 8
8 6 0 3 0 0 1 0 0
0 0 0 0 0 8 6 0 2
0 0 0 0 0 0 0 7 0
0 0 8 0 0 0 0 0 0
0 0 0 0 3 0 0 0 0
0 0 2 0 0 5 8 0 3
4 0 0 0 0 1 7 9 0
0 0 0 0 0 0 0 0 0
Building encoded string: GOS0!r=&HR5PZ|ezy>*l7 HWU`wIN7Q4&
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 42126
Scrambled
0 0 0 0 0 3 0 0 5
0 0 5 4 0 0 0 3 2
9 0 0 8 0 0 0 0 0
0 0 0 0 0 2 0 0 0
0 0 0 0 6 8 2 0 7
5 1 0 0 7 0 0 0 8
8 0 0 0 5 0 0 1 0
7 0 0 0 0 0 0 0 4
0 0 0 0 0 0 0 0 0
Building encoded string: [4#9D_?I1.!h];Y_2!iqLyngbBJ&k)FF;
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 156182
Scrambled
0 6 0 0 0 0 0 7 0
4 0 5 3 1 0 0 0 2
0 0 0 0 6 0 0 0 0
0 3 0 0 0 9 0 8 1
0 0 0 0 0 0 0 0 0
0 0 7 0 0 1 0 4 5
5 0 9 0 0 0 0 0 8
6 0 0 0 3 2 0 0 0
0 0 0 0 0 0 0 0 0
Building encoded string: r+a;I%hGj4YCA-pXz+n=ioRL:agzH'K<(
Encoded Length with BigInteger: 33
Final Result: 330
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal)- 407 Bytes
[Compressor](https://vyxal.pythonanywhere.com/#WyJhUEEiLCLIp+G5hSIsImbGm+KMijnOsjvGm+KMiuKAuTvhuYXijIpTx5LGm+KMimtQaTvhuYUiLCIiLCI5NzM1ODE0MjY1MjY0NzMxOTgxODQyOTY3NTMyNDc4NjUzMTkzOTgxMjQ2NzU2NTE3Mzk4NDI4MTkzNDI1Njc3NjU5MTgyMzQ0MzI2NTc5ODFcbjcyNDg2NTE5MzE2OTI0Mzg3NTM4NTE5NzI0Njg5NjcyNDM1MTI3Mzk1MTY4NDQ1MTM4NjkyNzU0MjYzOTcxODYxODU3MjQzOTkzNzQxODU2MlxuMTU3NjgyMzQ5NDMyNTE5Njg3Njk4MzQ3MjUxODI1NDc2MTkzNzEzOTI4NDY1OTY0MTM1NzI4NTQxMjkzODc2Mjg5NzYxNTM0Mzc2ODU0OTEyXG44MzU0MTY5MjcyOTY4NTc0MzE0MTcyOTM2NTg1NjkxMzQ3ODIxMjM2Nzg1NDk3NDg1MjkxNjM2NTI3ODEzOTQ5ODEzNDUyNzYzNzQ5NjI4MTVcbjYyODQ1MTc5MzU5NDczMjY4MTcxMzY4OTU0MjI0NzMxNTg2OTk2MTgyNzM1NDM4NTk2NDIxNzE1NjI0Mzk3ODQzOTU3ODEyNjg3MjE5NjQzNVxuMTIzNDU2Nzg5NDU2Nzg5MTIzNzg5MTIzNDU2MjE0MzY1ODk3MzY1ODk3MjE0ODk3MjE0MzY1NTMxNjQ4OTcyNjQ4OTcyNTMxOTcyNTMxNjQ4XG4xNDU3OTI4MzYzNzY1ODQxOTIyOTgzNjE3NTQ3MzE5Mjg2NDU4NTk2NDczMjE0NjIxMzU5ODc2MjQ4NzM1MTk1ODc0MTkyNjM5MTMyNTY0NzhcbjUyNzQxNjkzODg2NDMyOTE1NzEzOTU3ODY0MjI5MTg1NDM3NjM0ODY5NzUyMTY3NTEzMjQ4OTcxMjk0NTg2MzQ4MzI2MTc5NTk1Njc4MzIxNFxuMjQ2NzEzOTg1MTg1NDk2NzMyOTM3ODI1MTQ2Njc4NTQyMzkxNDkzMTY4MjU3NTEyMzc5NDY4ODI0OTU3NjEzNzU5NjMxODI0MzYxMjg0NTc5XG44NjEyOTQ1NzM0NzUzMTg2OTIzOTI1Njc4MTQyMzY0NTk3ODExNTQ3ODMyNjk5ODc2MjEzNDU1MjkxNzY0Mzg2NDg5MzIxNTc3MTM4NDU5MjYiXQ==)
```
fƛ⌊9β;ƛ⌊‹;ṅ⌊Sǒƛ⌊kPi;ṅ
```
[Decompressor](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiZsaba1DhuJ9TXFwwMsO44oazO+G5hWbGm+KMiuKAujvhuask4bmqJFwiZuG5hSIsIiIsInc5Z0BXMEU1eChAdmE2RWxLKT1nLllOSV94QGdzQE5jV3FoOEEwT3ghXG4iXQ==)
```
fƛkPḟS\02ø↳;ṅfƛ⌊›;ṫ$Ṫ$"fṅ
```
Input formatted as the test cases, but it converts it to an integer left to right then top to bottom so that's what I used for demonstrating. Not an entire sudoku solver, but it is a compression of 50.2%.
[Answer]
## C++ 241, score: 82\*10=820
Adds '!' to beginning of encoded string to determine which operation to perform.
Golfed 241 chars
```
void D(char i){static int x=0;cout<<(int)(i-'a')<<" ";if(x++%8==0) cout<<endl;}
int main()
{
int i=81;int n;string S;
char c=cin.peek();
if(c=='!'){cin>>S;for_each(S.begin()+1,S.end(),D);}
else{S.push_back('!');while(i--){cin>>n;S.push_back(n+'a');}cout<<S;}
}
```
Ungolfed 312 chars
```
void decode(char i) {
static int x=0;
cout<<(int)(i-'a')<<" ";
if(x++%8==0) cout<<endl;
}
int main()
{
int i=81;
int n;
string d;
char c=cin.peek();
if(c=='!'){
cin>>d;
for_each(d.begin()+1,d.end(),decode);
}
else{
d.push_back('!');
while(i--)
{
cin>>n;
d.push_back(n+'a');
}
cout<<d;
}
}
```
[Answer]
# Python, 106 bytes
```
def empty_sudoku():
return [[0 for _ in range(9)] for _ in range(9)]
def indexes():
return [(i, j) for i in range(9) for j in range(9)]
def valid_digits(sudoku, index):
r = set()
i, j = index
r.update(sudoku[i])
r.update(row[j] for row in sudoku)
k, l = [x - x % 3 for x in index]
r.update(sudoku[k + z][l + w] for z in range(3) for w in range(3))
return sorted(set(range(1, 10)) - r)
def compress(sudoku):
aux = empty_sudoku()
compressed = []
for index in indexes():
digits = valid_digits(aux, index)
i, j = index
x = digits.index(sudoku[i][j])
aux[i][j] = sudoku[i][j]
compressed.append((x, len(digits)))
assert (aux == sudoku)
n = 0
for x, y in reversed(compressed):
n *= y
n += x
bytes_length = 1
while True:
try:
b = n.to_bytes(bytes_length)
break
except OverflowError:
bytes_length += 1
return b
def uncompress(b):
n = int.from_bytes(b)
sudoku = empty_sudoku()
# compressed = []
for index in indexes():
digits = valid_digits(sudoku, index)
y = len(digits)
x = n % y
# compressed.append((x, y))
i, j = index
sudoku[i][j] = digits[x]
n //= y
return sudoku
```
Test:
```
from pprint import *
with open("testcases") as f:
tests = f.read()
tests = [[[int(cell) for cell in row.split()] for row in test.splitlines()] for test in tests.split("\n\n")]
compressed = list(map(compress, tests))
uncompressed = list(map(uncompress, compressed))
assert (all(t == u for t, u in zip(tests, uncompressed)))
score = sum(map(len, compressed))
print(score)
```
] |
[Question]
[
You work at a bakery and every day you make exactly 100 bagels. However your customers are not as reliable and every day a random number of bagels will be ordered. So sometimes you will run out of bagels and sometimes you will have leftovers.
Now leftover bagels will still be good for 1 more day. After a day on the shelves they have to be tossed. But until then you can still sell them. So you keep them for the next day. Customers will *prefer* fresh bagels so if you haven't run out of fresh bagels they will get a fresh bagel. Only when you are out of fresh bagels will they ask for a day-old bagel.
So for example if you have have 25 bagels left over one day and the next day 100 bagels are ordered, you don't sell any of the old bagels so you throw them out and have 0 leftover bagels the next day.
Your task is to write a program or function which takes a non-empty list of non-negative integers representing how many orders were placed in a given time:
e.g.
```
[106,25,134,99,85,12]
```
means that on the first day 106 bagels were ordered, on the second day 25 bagels were ordered and then 134 etc.
Your task is to calculate how many bagels were sold in the described period. You should assume that at the start of the period there will be no leftover bagels available.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal.
## Test cases
```
[100,100,100] -> 300
[372,1920,102] -> 300
[25,25,25] -> 75
[25,100,120] -> 225
[0,200] -> 200
[0,175,75] -> 250
[75,150,150] -> 300
[0,101,199]-> 201
[200,0] -> 100
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-p -MList::Util+min`, 28 bytes
```
$\+=min$_,100+$-;$-=100-$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lRts2NzNPJV7H0MBAW0XXWkXXFsjSVYmvrf7/38iUC8jhMjQy@JdfUJKZn1f8X7fgv66vT2ZxiZVVaElmjjZQMwA "Perl 5 – Try It Online")
## Explanation
Adds the `min`imum of `$_` (implicit input via `-p`) or `100+$-` (where `$-` starts as `0`) to `$\` (which is automatically output at the end of all lines of input).
`$-` is set to `100-$_`, which is safe because `$-` can never be negative.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 17 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
+´⊢⌊100+·»0⌈100⊸-
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgK8K04oqi4oyKMTAwK8K3wrsw4oyIMTAw4oq4LQoKRsKo4p+oMTAw4oC/MTAw4oC/MTAwLDM3MuKAvzE5MjDigL8xMDIsMjXigL8yNeKAvzI1LDI14oC/MTAw4oC/MTIwLDDigL8yMDAsMOKAvzE3NeKAvzc1LDc14oC/MTUw4oC/MTUwLDDigL8xMDHigL8xOTnin6k=)
-1 from ovs.
## Explanation
```
{+¬¥ùï©‚åä100+¬ª0‚åà100-ùï©}
100-ùï© subtract input from 100
0‚åà maximum with 0
» shift right, prepending a 0
100+ add 100. This is the number of bagels available on a day.
ùï©‚åä minimum with input
+´ sum the minimums
```
[Answer]
# Brainfuck, 148 bytes
```
,[->[-]>[-<+>]>++++++++++[-<++++++++++>],[>>>+<<<-<[->>+>>-<<<<[->>>+<<<]]>>>[-<<<+>>>]>[-<<<<<[->>>+<<<[->>>>+<<<<]]>>>>[-<<<<+>>>>]>]<<<]<<<]>>>>.
```
First is inputed length of array, then the values. Sadly I can't find any site which supports input&output as decimal numbers. Best I got is [this site](https://copy.sh/brainfuck/) where you can input escape squences like `\3\100\100\100`, but the output is ASCII, so you will need to convert it to decimal. (Please let me know about any sites supporting decimal in comments)
## Explanation
**Memory map**: `arrayLength old fresh order output temp flag`
```
,[- loop through all elements of array
>[-] reset old count
>[-<+>] set old count to the remaining amount from fresh
>++++++++++[-<++++++++++>] set fresh to 100
,[ while there is order
>>>+ set flag
<<<- reduce order size
<[ check if there are any fresh
- reduce amount of fresh
>>+ increase output
>>- unset flag
<<<<[->>>+<<<] copy fresh to temp variable so condition can exit
]
>>>[-<<<+>>>] copy from temp back to fresh
>[ check if flag is set (if previous condition wasnt executed it acts as else)
- unset flag
<<<<<[ check if there are any old
- reduce amount of old
>>>+ increase output
<<<[->>>>+<<<<] copy old to temp variable so condition can exit
]
>>>>[-<<<<+>>>>] copy from temp back to old
>
]<<<
]<<<
]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~57~~ ~~55~~ 54 bytes
```
x=>x.map(i=>[s+=i>a?a:i,a=i>99?100:200-i],s=0,a=100)|s
```
[Try it online!](https://tio.run/##RY3BisIwEIbv@xTixWSd1mSklCqJt32BPZayjDWVSGy7jSsu7Lt3kyoUMmHmG775L3QnXw@2vyVtdzJjo8aH0o/0Sj2zSpd@raymA@0sUOiK4iCF2KEQia3AKxFoAPzPj/vBfP/YwbBl45c8HQydPqwzn79tzQSsHN1sK1dx0TuqDduw9J0nOv6bM7AvIDhypeuu9Z0zqevOrGHmTo4R5zC3Sq2PnI9liIVXVYtEL7ZCvJXbHEEWGCnOFDOY3kTybAKTik8VMTAB@LqE0QnbPIP86WAWSBhlJmLNl2OQDIlFNXnyHw "JavaScript (Node.js) – Try It Online")
Badly golfed maybe...
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
sum.(zipWith(min.max 100.(-)200)=<<(100:))
```
[Try it online!](https://tio.run/##VY/BCoMwDIbvfYocW@ikjRRx6CPsvIPI6EGxzIqsHYy9vEvL3BCaQ7/8@f9ksuE@zPO2jW14@oK/3Xp1ceLeLYW3L9BKFfwkUCnRNg2n71mILQ4hBmgZdMA7YvJbvYSSlAwk8bJCqWtMDTw00Mj8CFbmz7IHJg/EHSuJ2RV/w6SpjKzSMJodEtFGpToEpWhNO9TZQe9RlJN0Out6xrx1SzoGvF0vN@Drwy0RChhThSggn8u2Dw "Haskell – Try It Online")
Since there's now a Haskell answer I thought I'd toss mine in the ring.
[Answer]
# Excel, 66 bytes
```
=LET(o,A:A,a,100+INDEX((100-o)*(o<100),ROW(o)-1),SUM(IF(o<a,o,a)))
```
Input is in the range `A:A` with each day's order in a cell by itself. Output is wherever the formula is.
The `LET()` function allows you to define variables and later reference them by that variable name. The terms come in pairs (`variable, value`) except the last term which is just the output value.
* `o,A:A` defines `o` (orders) to be the entirety of column A. This technically limits you to about 2,870 years of bagel orders. I consider this to be acceptable.
* `a,100+INDEX((100-o)*(o<100),ROW(o)-1)` defines `a` (available) and does most of the heavy lifting so let's break it down into pieces.
+ `100` is how many bagels are made fresh each day.
+ `(100-o)` is how many leftover fresh bagels there are each day.
+ `*(o<100)` filters out negatives (more orders than fresh so no leftovers).
+ `ROW(o)-1` tells us that we're going to be looking at the data for the previous day.
+ In plain(er) text: `100+INDEX([leftover fresh]*[not negative],[from yesterday])`.
+ All together, you could read it as `[fresh] + [yesterday's fresh leftovers]`.
* `IF(o<a,o,a)` returns either the number of orders (if it was less than what was available) or just what was available.
* `SUM(IF(~))` adds it all up.
[![Result](https://i.stack.imgur.com/6Fsz0.png)](https://i.stack.imgur.com/6Fsz0.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
тs-Dd*т+тšø€ßO
```
Port of [@Razetime's BQN answer](https://codegolf.stackexchange.com/a/241377/52210).
[Try it online](https://tio.run/##ASsA1P9vc2FiaWX//9GCcy1EZCrRgivRgsWhw7jigqzDn0///1swLDEwMSwxOTld) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/4tNxbouKVoXm7QvNh1deHjHo6Y1h@f7/9f5Hx1taGCgA8WxOtHG5kY6hpZGIK4RkGtkqgNGECZYmRFImYGOkQGENjQ31TEHyQNpQ1MDEIaIGxgCDbIEaQTqMoiNBQA).
**Explanation:**
```
# e.g. input = [0,101,199]
—Çs- # Subtract the values in the (implicit) input-list from 100
# STACK: [100,-1,-99]
D # Duplicate this list
# STACK: [100,-1,-99],[100,-1,-99]
d # Check for each that they're non-negative (>=0)
# STACK: [100,-1,-99],[1,0,0]
* # Multiply the values at the same positions
# STACK: [100,0,0]
—Ç+ # Add 100 to each
# STACK: [200,100,100]
тš # Prepend 100
# STACK: [100,200,100,100]
√∏ # Create pairs with the (implicit) input-list,
# ignoring the additional trailing item
# STACK: [[0,100],[101,200],[199,100]]
ۧ # Get the minimum of each pair
# STACK: [0,101,100]
O # Sum those minima
# STACK: 201
# (after which the result is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 36 bytes
```
Tr[i=c=100;Min[2c-c~Min~i,i=#]&/@#]&
```
[Try it online!](https://tio.run/##LYzBCgMhDETv/sZCT1kaU0SWYukPFArtTXoQ6VIPu4fFm@iv2yhCJrwhM9lc/H03F4N3dTX1fdhgvJGI10fYLfnZF4YSIJjpczrfedXnEfZop/m2Nlte3u0licQlGMog0kUTyIWap@ZJQZ/BPUk9iUA4QGoFukcYpMKmcUHJ75be5ipmkesf "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# C(gcc -O0), ~~115~~ ~~109~~ ~~84~~ ~~82~~ 78 bytes.
```
m,l,g;f(a,n)int*a;{m=l=0;for(g=100;n--;++a)m+=fmin(g+l,*a),l=*a<g?g-*a:0;m=m;}
```
[Try it online!](https://tio.run/##HY5BDoIwFET3nKLRmFD4NQUWRj/Vg6iLn2IrSVsM4IpwdWt1dpN5MxktrNYxenBg0eQEgfdhLggXr5ySaIYxt6qSEoMQWJbEfamM70NuSwcFcXCqoNZerCjoJNErj2vc9kG7d/dg7TR3/bB/nrO0yjylHl8ylvTzNI7V9a6W5lBDdawlVLJe8R@/xgSYfLPrbmEDLD1LLLCGc8zWLMb40caRnaJw/gs)
The function takes two arguments, a pointer to the array and the size of the array.
*-25 bytes thanks to AZTECCO*
*-4 bytes thanks to ceilingcat*
Can I golf it further?
[Answer]
# [Python](https://www.python.org), 56 bytes
```
lambda a:sum(map(min,[200-min(r,100)for r in[100]+a],a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NU1bCsIwEPz3FPlMMMImUvoAT1LzEbGhgSYNMVU8iz8F0Wt4jt7GpFHYYWd2Z3Yfb3cP_WjnpzocX1NQu2qpBmlOZ4lkc5kMNtJhoy1tOcAuEuwpAyBq9MgjbdsoxFYKKgnJ-c-t10OHWOO8tgEr3F3lgLV1U8CE_F3z0qco_UFs2n3JKat5kjxKXtC1Ml1tPNmAcsidlQUt0z52VkBCngOLh-oUjCkQ-eEX)
If it weren't for Python 2 padding arguments to `map` with `None`s, we could abuse its global ordering like so:
```
lambda a:sum(map(min,[200-min(r,100)for r in[a]+a],a))
```
because `a` will always be "larger" than `100`.
As it is, we have to work around it with `a+[0]))` for [58](https://ato.pxeger.com/run?1=NU1BCsIwELz7ihxTuoVNpFQLviTmENHQQJuGmCK-xUtBxC_4lf7GpFHYYWZ3Z2cfb3cP3Wj5_NSH42sKutotba-G01kR1V6ngQ7K0cFYEByxioJ6YIiFHj3xxFihZKkkqFKgLIqc8Ll1pr8Q1jpvbCCaGuumQP_reelEjIAf5EZsGw5sz1PLY8trWCvL1caTDYFjZtbU0KR9ZFZjQp4ji0H7dBivUOaHXw).
---
## [Python](https://www.python.org), 58 bytes
```
lambda a,S=100:sum(min(r,100-S+(S:=min(r,100)))for r in a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PU1BCoMwELz3FTluaIQkRawBX-HRekipwYBGSWNL39KLUNpv9B3-pomRwg67szsz-_yMD9cOZn6p4vSenEqOi-hkf75IJElZMErFdeqh1wYs8Swp91CK4s8xxmqwyCJtkMQx4XtvddcgJkarjQMFzU12oM04OfD6TTUvbeUDyIZ6Vx0yTljOA-We8pSsFcdVxoOMEk5jZ1lKsnD3naU0IO4p80F5MHoXrePDHw)
[Answer]
# [R](https://www.r-project.org/), ~~51~~ 48 bytes
```
function(n,`~`=pmin)sum(c(n,0)~100-c(0,n-100~0))
```
[Try it online!](https://tio.run/##VY5LCsMwDETX7SkM3Vggg6xgTKC9S8BgyCJuaZutr@7InywCEog30oy@JaqnUSXuKfzXd9IJl7y8Ptua4LdvOgggyJbIBE2YjEyZAEoUSWYcDXB7qInoXvnkGe3MVeCLwA5bCRTq3QmbCXcT5o4JudlWNM5lyTv045xdp4Kso9qXrJpu5Y359LA9TaKGraSWAw "R – Try It Online")
Ports [Razetime's BQN answer](https://codegolf.stackexchange.com/a/241377/67312).
-3 bytes thanks to pajonk.
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
+/@:<.100>.0,200-}:
```
[Try it online!](https://tio.run/##VY1BCoAwEAPvvmKPilqzK6W0qPgXsYgXX@Dba1XEFjaHDJtkD8GPjupudoNiYFJoBGhPF9ZlO6j0FOmnqvhgb4TYyk3lp6Lfy8iTlSQLEmSWjSaThKJljVvZFzhO2qQ7FqMKFw "J – Try It Online")
* `}:`: Remove the last number.
* `200` `-`: Subtract each number from 200.
* `0` `,`: Prepend 0.
* `100` `>.`: Take the maximum of each number with 100. This produces the number of available bagels for each day.
* `<.`: Take the minimum of that and the original values...
`@:`: and then (using composition)...
`+/`: take the sum of the values.
(This whole thing is a hook.)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 63 62 bytes
```
f=lambda o,*v,l=1:min(o,99+l)+(len(v)and f(*v,l=max(1,101-o)))
```
[Try it online!](https://tio.run/##TY/RCoMwDEXf/Yo8tlsGTaW4DvwS8cHhZAVtRcvYvt6l1cGgeejJvTfJ/InP4MvrvGzbUI/ddO87CHh64VjTbXJeBLT2PMqzGB9evGTnexhE7k/dWxCSokuQUm7xscYVamgK0ZBSeFSLUColkWlZaSSrE9Z/WBvMj1FlfiS7dXJrs0OFOqfpw8b9ymBlsmRH/CejUv3Fp3G8prXZS/sATk8aypq2GMICwmGQ4DzkQ24FzIvzkSmf6yT3ti8 "Python 3.8 (pre-release) – Try It Online")
Takes the input as a vararg list
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
IΣEθ⌊⟦ι⌈⟦¹⁰⁰∧κ⁻²⁰⁰§θ⊖κ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUCjUEfBNzMvMxfIjc4EshMrIGxDAwMdBce8FI1ssILSYg0jsEiJZ15KagVIm0tqclFqbmpeSSpQkSYQxAIhCFj//x8dbaBjaGCoY2hpGRv7X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over orders
⌊⟦ Minimum of
ι Today's order and
⌈⟦ Maximum of
¹⁰⁰ Literal integer `100` and
κ Current index
‚àß Logical And
²⁰⁰ Literal integer `100`
⁻ Subtract
§θ⊖κ Previous day's order
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# APL+WIN, 24 bytes
Prompts for input
```
+/b⌊100+¯1↓0,0⌈n←100-b←⎕
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7Z@0qOeLkMDA@1D6w0ftU020DF41NORB1JgYKCbBKSBGv4DlXL9T@MCCilAMVcal7G5kYKhpRGIawTkGpkqgBGECVZmBFJmoGBkAKENzU0VzEHyQNrQ1ACEIeIGhkCDLEEagboMAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~57~~ 55 bytes
```
(0!)
r!(x:t)|x>100=0!t+min(100+r)x|j<-100-x=x+j!t
_!x=0
```
[Try it online!](https://tio.run/##VZBBbsMgEEX3PsU4KxBYAiLLShVygnTVpWNFVmQ3SW0X2VRl4bOXDrh1G4mR0Psz/w9c6@mt6Trf6pMnIqXJmBL3ZOnsDlIILVLL@ttA8M5G6ub7PsNr5rRj99Qm59Rp4fv6NoCGvjbPZzAf9sWOxwHKBMh0ff8E20yWMrY5DRvGfuHYTBAgAMIFEWic0ToqSz9OQAIziRY8yEBhn5UIAUiJm/CfqjhshaB8EbaF4nKngqIeFZXzeJAW@T8YbVSwUWrlgqvorP7msavIeRHmVb5SRDIXoR7TwgISN9lFE7nmYVjoxFBaIesaG/5Dt/GdUCX@69J29evks4sx3w "Haskell – Try It Online")
*saved 2 Bytes thanks to @Wheat Wizard*
[Answer]
# x86-64 machine code, 24 bytes
```
31 c0 99 97 91 ad 01 c7 83 e8 64 01 c2 78 02 29 d7 99 21 c2 e2 ef 97 c3
```
Fixed.
[Try it online!](https://tio.run/##bVTvb9owEP2M/4oT1bZkMgjoT2Cd1NFO6zRtUvulUtcPJnGCN8dObQeYEP/62DkhNGVEJCQ@v3fv3l0S5XknjaLNhtkMArhrB6SbSj1lEqYs5dKS6m9EWkttgLMl9RfA4whurh7gEnpd0oriZ2geGLuuY8tolgKPRQ3EGC4xlXLcdAuB5Cp1sxAWws1KyqAX7mDR8hBs8tDYvcUjBPaOIzy/cMNpmWghpISZljG4GQdVZFNuQCfbOsFihAJTsZdOrBwdpGuwdCStVKBVXKh0j1byxOk53lf8KE/q2Mav@L5pVqmJCmO4cjVcgVBO@/JQUTxnKqr5c40R3CEU3NzfIimL46a5SHoVv67QxGgBLmnvAiJsMa362O/1KsR9MXWGRa5cSYzOqsy50XFRZlYdjOySLfeSldGK/39URyLuF9r7W@SNyr8WWQ4iQaHMvbOgeMqcmHMIMm143RI2Z0KyqeR@m6orCesayqrjrZDgB9ZsFsLy8KUeb4OdaeMShl3b6tlW6L3wokaHpvez77If4bLBJY1IFUyF861Fd7wZat@MT8J5AXD1/XoMGfvNbcnBnwt8nfysYsF1pRR6oGvJ5XDoHKxsaJjoAici1gtVKfYqqlkvuz9Brz2omgzmMKH6A05k3B586e6xlKiqxXBbSAeBp7m@DXfDhjjD3Z4Vd9wVRnVJ2IZwTPgSp09Be9KGFcK2nQr8raIQaWWdp4P3LByvCTkSKpJFzOGDdbHQ3dlHQqxDAyKwzhS@Rdy6iKFpJZ0al2j2ePGE8DpmH5/wW7Iiq2O6whbS7ble03Lp@HxA@8OBXxvUa4NTWv4azyVqUKEGdNWjgxcKjJyf0vPddnzon/b82djR62OaYY1HNK2iZ17Vmc/XPz6hwyG9wDtUQtZj4qvJmFBBSFakleAnNKhMYgV6/tbBaOeADUmrlRtEJEH7jfip2rS213XRXNdlIXZgvdn8jRLJUrvpZGcneMFP96X/Ksh/)
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length in RDI and the address of an array of 32-bit integers in RSI.
Assembly:
```
.global bagels
bagels:
xor eax, eax # EAX = 0.
cdq # EDX = 0.
xchg edi, eax # Exchange EDI (length) with EAX (0).
xchg ecx, eax # Exchange ECX with EAX (length).
# Here, EDI will hold the number of bagels sold, and EDX
sl: # will hold -l, with l being the number of leftover bagels.
lodsd # Load the current number n into EAX, advancing the pointer in ESI.
add edi, eax # Add the number ordered to EDI.
sub eax, 100 # Subtract 100 from EAX, producing n-100.
add edx, eax # Add n-100 to EDX, producing n-100-l.
js skip # Jump if that's negative (more bagels available than ordered).
sub edi, edx # (Otherwise) Subtract the shortfall n-100-l from EDI.
skip:
cdq # Fill EDX with the sign bit of EAX.
and edx, eax # Bitwise AND; makes EDX equal n-100 if it's negative, 0 otherwise.
loop sl # Count down from the length in ECX, looping that many times.
xchg edi, eax # Switch the result (in EDI) into EAX.
ret # Return.
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 73 bytes
```
a->{int s=0,l=0,h=100;for(var o:a){s+=h+l<o?h+l:o;l=o<h?h-o:0;}return s;}
```
[Try it online!](https://tio.run/##ZVDBasMwDL33K0ShkKyOcTJCadK09DLYYafuVjrw2qRxl8TBVgql5Ns92@QyBn6Sn6QnCd34nUe3y48RbS8Vws1yOqBo6Es@@xerhu6MQnYueW641vDBRQfPGUA/fDfiDBo5WneX4gKtzQUHVKK7Hk/A1VWHvhTgU753@DY124gOj6ctVFAYHm2floIuGGks6iJmLK@kCu5cgcx4@NTLol42G7mzNpN5U8hNvasjmbF8VCUOqgOdjyb3g6wSvBRLjZD9WQLAD7YxxR9QwN55TTWqkreBE1DdNwKD@fGLRevTch6GtOW9Xz6wKK@lyrKeK11aFlKUvkUQ5lP/w0Nj2VI5IO3tFbAK5gudweKy6ObEr0Sgorzvm8deu6Z@lXDSjzOH0Rh7AjLBvK4SEq8TRxKTpMQ/9/EFCTOMJMzZeJWSVWqsjVPm4GIstuK1sRWE/QI "Java (JDK) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 56 bytes
```
f(b)=sum(i=1,#b,min(b[i],100+if(i>1,max(0,100-b[i-1]))))
```
[Try it online!](https://tio.run/##TY3BCsIwDEDvfoXgpcUUkpRSdqg/MnpYD5MeKkMR/PuZpkMMySEvecm2PKu7b/u@mmLT691MTQSXAq0@TJlrBkK81tXUG0FbPgY7cDJxlK1EN2dBcFS2KXnEk1AfGWjijvkPcwDNjmI4iNqs9plZKQKPczw8WYgBonocFElPAXup6H@LSPJ5GjJ9AQ "Pari/GP – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), ~~115~~ 101 bytes
shaved off 14 bytes thanks to a helpful user
```
{var s=0;var l=0;for(d in it){var t=Math.min(d,100);t+=Math.min(d-t,l);s+=t;l=100-Math.min(d,100)};s}
```
[Try it online!](https://tio.run/##pZPBToQwEIbvPsWEU5sF0xYREbuJ8eTB@AzVBSV2i4GuiVl5C@PJp/NFsF0QCW4Csk3a0mmZr//M9CnXMlP1iyjgTjwk8krI@40UOi/gHNBlUYjXi2ullxi8JZgPXm/t2ZKT2M7SzGleoBVkCjKNd5ua3wj9eLzOFFq5lBAc60XP5GlX4rhccB1Lbra9wekqLqs63ShYC2PD2yMw7bnIlEaOTkoNFBwcQ5aiwY2RsNe9TZHx4rYdY/s3cA6@WTRuAJDz9fn@ZtxAIsukb/2w1j9ENkb0Q@YCjRgxI2EWeiDRHyOywIWmtxItEcJgNvFkCtFGFShrw2qIjM0nBmNEw2JdCn80si6qUu0jNtb9xNMJRBoanWE/qiyYn8dwjGhpNCC7oYvqIZVzNkUjobZco9/XwQidTYxGK8dWzTCP9B8aq/ob "Kotlin – Try It Online")
#### Ungolfed:
```
fun bagelCalculator1(arg: Array<Int>) : Int
{
var sold = 0
var left = 0
for(demand in arg)
{
var soldToday = min(demand,100)
// V the deficit V
soldToday += min(demand-soldToday, left)
sold += soldToday
left = 100-min(demand,100)
}
return sold
}
```
[Answer]
# [PHP](https://php.net/), 79 bytes
```
function b($a){foreach($a as$o){$t+=min(100+$d,$o);$d=max(0,100-$o);}return$t;}
```
And now I want a bagel :)
[Try it online!](https://tio.run/##bZDPCoMwDMbvewqRHip2o@2QIk72INsOnX@oB9viKgzEZ@9SGduhQgLh@yVfQqyy/nK1yh66RpnkiW@MUvLNR3ZK7zqtfuwsOGElD5BHkBdkiz2wGfLYkBJO91QmCiJiJ1BZQUPuzVAGx5Xxetj97/f9rBs3GA0IyWzpzdTJRkGdyBcy2YJcXo@DxnByjloCUoXaepRvvP3kGIR16tw8aeSq1fsP "PHP – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~25~~ 23 bytes
```
MN{H[ah+yYMX[h-a0]]}MSg
```
Takes the list of orders-per-day as separate command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhbbff2qPaITM7QrI30jojN0Ew1iY2t9g9MhslBFW6MNDcx0jEx1DI1NdCwtdSyALKNYqCQA) Or, [verify all test cases](https://ato.pxeger.com/run?1=m724ILNgWbSSbo5S7KbqSAMFjaCAdE09JQVdOwUlPY2lpSVpuhbbff2qPaITM7QrI30jojN0Ew1iY2t9g9MhsjerNWsVfEMVorkUog0NDKyhOBbINTY3sja0NALxjUB8I1NrMIKywSqNwCoNrI0MoAxDc1Nrc7ASIMPQ1ACEoTIGhkDjLMG6gVqBorEQJyxYAKEB).
### Explanation
```
; We store the number of leftovers in y (initially = 0)
g ; List of cmdline args
MS ; Map this function and sum the results:
MN ; Apply min to the result of
{ } ; This function:
H ; All but the last element of
[ ] ; This list:
a ; Function arg (today's number of orders),
h+y ; 100 plus yesterday's leftovers,
Y ; and yank the new number of leftovers:
MX[ ] ; Take the max of
h-a ; 100 minus function arg
0 ; and 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ȷ2ð_«Ż+ḷṖ«S
```
[Try it online!](https://tio.run/##y0rNyan8///EdqPDG@IPrT66W/vhju0Pd047tDr4/@F2zcj//6MNDQx0oDhWJ9rY3EjH0NIIxDUCco1MdcAIwgQrMwIpM9AxMoDQhuamOuYgeSBtaGoAwhBxA0OgQZYgjUBdBrEA "Jelly – Try It Online")
Another handful of ports of [Razetime's BQN](https://codegolf.stackexchange.com/a/241377/85334).
`ȷ2` could hypothetically be golfed to `³` if this is used as a function in a program with no command-line arguments, but the existing Jelly corpus seems to discourage this. Modifying the programs to use STDIN has yielded no savings (but thanks to emanresu A for reminding me).
```
»∑2√∞ With 100 as the left argument to a dyadic chain:
¬´ Take the minimum of each element of the input and 100,
_ and subtract each minimum from 100.
Ż Prepend a 0,
+·∏∑ add 100 to each,
·πñ remove the last element,
¬´ take the pairwise minima with the input,
S and sum.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ȷ2ɓ«ṖạŻ+ɓ«S
```
[Try it online!](https://tio.run/##y0rNyan8///EdqOTkw@tfrhz2sNdC4/u1gZxgv8fbteM/P8/2tDAQAeKY3Wijc2NdAwtjUBcIyDXyFQHjCBMsDIjkDIDHSMDCG1obqpjDpIH0oamBiAMETcwBBpkCdII1GUQCwA "Jelly – Try It Online")
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ȷ2ðḤ_«Ṗ⁸;«S
```
[Try it online!](https://tio.run/##y0rNyan8///EdqPDGx7uWBJ/aPXDndMeNe6wPrQ6@P/hds3I//@jDQ0MdKA4Vifa2NxIx9DSCMQ1AnKNTHXACMIEKzMCKTPQMTKA0IbmpjrmIHkgbWhqAMIQcQNDoEGWII1AXQaxAA "Jelly – Try It Online")
[Answer]
# [Go](https://go.dev), 106 bytes
```
func(a[]int)(s int){l,h:=0,100
for _,o:=range a{if h+l<o{s+=h+l}else{s+=o}
if o<h{l=h-0}else{l=0}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVHdTsMgGI23PAXuqmTMAEtTt4x38N4YQ5ayVikstPWG9Em8aUx8Gd9gPo3QVtfaJvwezuF8B94_Tqa93J7F8VWcUliIXIO8OBtb3a1kUa0AeBMWSv5ZV3Jzf3mRtT5G4vEp1xWKShgmp3C25wRTQoA0Fj5js-dWaH-dcLmE2VodjCvX3C-aVJVpWJsG-CNzyJzi2Yb0uOKkaYBNq9rqpnf8vvkKll1hEYIOPFjvqXTUleC8Jx56g-UCiPCWEPRPtU0YpjsWGOwqm6CLOhbjrl01fwjCSbxA78pgZCL4xRBmbKYhmI2j9FsUxjmTJrF3HZMHxPPjGd8f0ZiEflWMsMXA4S2of5TdxGSAQlV0ltmHG8fttihkRmD40rbt5x8)
Port of [Olivier's Java solution](https://codegolf.stackexchange.com/a/241536/77309).
[Answer]
# [///](https://esolangs.org/wiki////), 63 bytes
```
/b|/|bbbbb// /bbbb||//b1///b\||1/||//1///b*/*s//*/\/// *//sb//
```
[Try it online!](https://tio.run/##HYuhDcBADMR4pwgOsbLPk0aqVFAWerunnzfwyeDqu@t9qrmgSaEcwJiVIIOtJQWTpxwvcNYOc6h5dERYDP0D "/// – Try It Online")
Takes input appended to the program, as space-separated unary numbers using `1`s; produces output in unary using `s`s.
Or, run a [modified version](https://tio.run/##VZA7bsMwDIZ3nYKzF0pKVde7b@DVSwwF6FBAg7ZA6Bnapo/kLrlTj@D8pBW7FUz@30fJ8CO/7PPzIc8zvxqWshyZHcfE7NEROwnkgyYgLAB6rARs7wh@WhnSbZLkASn@GejERDYUhaK@wlS4TLJEiIVK0Y207I@lJF5GddJwkwUaHnVAjfQ8qWTuB8mhr9AP6@Jh7P@P@Pd64c2h501hP6tBvu8C/qoM/FwQdFICfAgg35GIN/1wSSN0xM8/zs5aqmV2rSfXeRFvfCC9BPSAt8aSt9JdG6gNBt0FKyUz63BzZ3CC7HwD "/// – Try It Online") with added pre-processing and post-processing to use decimal numbers in input and output.
## Explanation
```
/b|/|bbbbb/
/ /bbbb||/
```
The first substitution modifies the second substitution's replacement string: each `|` multiplies the number of `b`s by 5 as it passes through them, resulting in `||bbb*…(100)…*bbb`.
Then, the second substitution replaces each space with that string. In addition to the spaces between the input numbers, there is one more space from the end of the program (just before the input), so the string appears at the start of every day, providing the 100 bagels (as `b`s) made for the day and a separator `||`.
```
/b1//
```
Use bagels to fulfil orders made on the same day, removing both.
```
/b\||1/||/
```
Use bagels to fulfil orders made on the next day, removing both. The backslash prevents this code from being modified by the first substitution.
```
/1//
```
Remove unfulfilled orders.
```
/b*/*s/
/*/\//
/ */
```
The last of these three pieces will have already been modified by the second substitution in the program, to `/||bbb*…(100)…*bbb*/`. It is further modified here, becoming `/||*sss*…(100)…*sss/` and then `/||/sss*…(100)…*sss/`, and then executed, replacing each day separator `||` with a hundred `s`s, again producing the number of bagels made that day.
```
/sb//
```
Cancel out bagels made with bagels unsold, leaving the number of bagels sold in `s`s.
[Answer]
# TI-Basic, 26 bytes
```
sum(min(Ans,ᴇ2+augment({0},max(0,ᴇ2-ΔList(cumSum(Ans)-Ans
```
Takes input in `Ans`.
] |