text
stringlengths 180
608k
|
---|
[Question]
[
Write a program in the minimum number of bytes that prints a string split into chunks of every length from 1 to the string's length (ascending and then descending), separated by spaces.
## Example
```
Input : abcdef
Output: a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f
```
[Answer]
# Ruby, ~~84~~ 81 characters
```
i=gets.chop
puts (a=(1..i.size).map{|n|i.scan(/.{0,#{n}}/)*' '})+a.reverse[1..-1]
```
The magic is in the regex: `i.scan(/.{0,#{n}}/)`. Since Ruby does regex interpolation too, it will become
```
i.scan(/.{0,1}/)
i.scan(/.{0,2}/)
...
```
This means it will grab as many characters as it can, limited to `n`. `n` progressively gets bigger, and is used to generate the first half of the output.
Then I just call `reverse` to generate the second half. I had to use `[1..-1]` in order to avoid repeating the middle line (what that does is basically chop off the first element of the array).
Sample run:
```
c:\a\ruby>spacesplitgolf.rb
CodeGolfStackExchange // (this is the input)
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e
```
[Answer]
### GolfScript, 22 characters
```
:I,,{)I/' '*n+}%.-1%1>
```
Try the example [here](http://golfscript.apphb.com/?c=ImFiY2RlZiIKOkksLHspSS8nICcqbit9JS4tMSUxPg%3D%3D&run=true).
```
> abcdef
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f
```
*Code explained:*
```
:I # Save input to variable I
,, # Create array [0..n)
{
) # Increment loop variable by 1
I/ # Split input into chunks with as many characters
' '* # Join with spaces
n+ # Append newline
}%
.-1%1> # Create reverse copy (minus first element)
```
[Answer]
# Smalltalk (Smalltalk/X) (137 chars)
```
s := Stdin nextLine.
(1 to:s size),(s size-1 downTo:1) do:[:n |
((s asCollectionOfSubCollectionsOfSize:n) asStringWith:' ') printNL]
```
### output (first line is input):
```
abcdef
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f
```
[Answer]
# J - ~~32~~ 27 char
Thanks to [randomra](/u/7311) for improvements.
```
(,&' '\(,@)"{~#-~|@i:@<:@#)
```
Explained:
* `<:@#` - One less than the length of the string.
* `|@i:` - Count from that number down to 0, then back up to that number. (J has weird primitives!)
* `#-~` - Subtract from each of those numbers the length. When you do the math, the result is that you count from -1 to the negation of the length and back up.
* `u\(,@)"{~` - For each negative integer, apply the verb `u` on non-overlapping infixes of the string, with length the negative of the integer, and then run it into a single string. So e.g. for `_2` it will split the string up into non-overlapping pairs of letters, apply `u`, then make a string back of all the new infixes.
* `,&' '` - Append a space. (This fills in `u` above.)
Usage:
```
(,&' '\(,@)"{~#-~|@i:@<:@#) 'abcdef'
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f
```
[Answer]
## Python 94 (bit verbose, but that;s Python)
```
s=raw_input();print'\n'.join(' '.join(map(''.join,zip(*[iter(s)]*n)))for n in range(1,len(s)))
```
[Answer]
### Delphi XE3 - WayToMany characters (WayToMany==321 261 245)
Im sure I can get this shorter so consider this as Work In Progress ^.^
**Edits:**
*Removed use of array making 2 units redundant saving a total of 61 chars*
*Removed useless begin..end for loop saving 16 chars*
```
{$APPTYPE CONSOLE}uses idglobal;var i,st:int16;s,r:string;p:boolean;begin readln(s);st:=1;p:=true;repeat r:='';for I:=1to Length(s)do r:=r+iif(i mod st=0,s[i]+' ',s[i]);writeln(r);if st=length(s)then p:=false;st:=iif(p,st+1,st-1);until st<1;end.
```
### With indent
```
{$APPTYPE CONSOLE}
uses idglobal;
var
i,st:int16;
s,r:string;
p:boolean;
begin
readln(s);
st:=1;
p:=true;
repeat
r:='';
for I:=1to Length(s)do
r:=r+iif(i mod st=0,s[i]+' ',s[i]);
writeln(r);
if st=length(s)then
p:=false;
st:=iif(p,st+1,st-1);
until st<1;
end.
```
Result: (first line is input)

[Answer]
# Rebol (144 chars)
```
s: input o:[]repeat i(length? s) - 1[t: copy s forskip t i + 1[insert t" "]append o next t]append o reverse append copy o s forall o[print o/1]
```
### Un-golfed:
```
s: input
o: []
repeat i (length? s) - 1 [
t: copy s
forskip t i + 1 [insert t " "]
append o next t
]
append o reverse append copy o s
forall o [print o/1]
```
### Usage example:
```
rebol script.reb <<< "abcdef"
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f
```
[Answer]
## R, 95
```
x=scan(,"");z=1:nchar(x);for(i in c(z,rev(z)[-1]))cat(gsub(paste0("(.{",i,"})"),"\\1 ",x),"\n")
```
(based on regular expressions)
Example:
```
> x=scan(,"");z=1:nchar(x);for(i in c(z,rev(z)[-1]))cat(gsub(paste0("(.{",i,"})"),"\\1 ",x),"\n")
1: abcdef
2:
Read 1 item
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f
```
[Answer]
# JavaScript - 242
I'm new to CodeGolf (and JS as well) and this is my first try. Any suggestions are welcome :)
```
function f(s){var i,j,a=s.split(''),t;for(i=1;i<=a.length;i++){t='';for(j=1;j<=a.length;j++){t+=a[j-1];if(j%i==0)t+=' ';}
console.log(t);}
for(i=a.length;i>0;i--){t='';for(j=1;j<=a.length;j++){t+=a[j-1];if(j%i==0)t+=' ';}
console.log(t);}}
```
**Example:**
```
>>> f('CodeGolfIsAwesome');
C o d e G o l f I s A w e s o m e
Co de Go lf Is Aw es om e
Cod eGo lfI sAw eso me
Code Golf IsAw esom e
CodeG olfIs Aweso me
CodeGo lfIsAw esome
CodeGol fIsAwes ome
CodeGolf IsAwesom e
CodeGolfI sAwesome
CodeGolfIs Awesome
CodeGolfIsA wesome
CodeGolfIsAw esome
CodeGolfIsAwe some
CodeGolfIsAwes ome
CodeGolfIsAweso me
CodeGolfIsAwesom e
CodeGolfIsAwesome
CodeGolfIsAwesom e
CodeGolfIsAweso me
CodeGolfIsAwes ome
CodeGolfIsAwe some
CodeGolfIsAw esome
CodeGolfIsA wesome
CodeGolfIs Awesome
CodeGolfI sAwesome
CodeGolf IsAwesom e
CodeGol fIsAwes ome
CodeGo lfIsAw esome
CodeG olfIs Aweso me
Code Golf IsAw esom e
Cod eGo lfI sAw eso me
Co de Go lf Is Aw es om e
C o d e G o l f I s A w e s o m e
```
[Answer]
## Perl, ~~77~~ 71
Better late, than never (and since so far no Perl solution):
```
chomp($s=<>);say$s=~s/.{$_}/$& /gr for@a=1..length$s,reverse@a[[[email protected]](/cdn-cgi/l/email-protection)]
```
Requires `5.014` because of `r` modifier. Uses 'say' feature. And
```
echo CodeGolfStackExchange| perl -M5.010 spaces.pl
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e
```
[Answer]
# CJam, ~~20 19~~ 18 bytes
Not a valid entry as CJam was created sometime after this question and moreover, this code is using some of the even newer features of the language.
```
q:Q,{)Q/S*N}%_W%3>
```
1 byte saved thanks to Martin.
**Explanation**:
```
q:Q, "Read the input, store it in Q and take its length";
{ }% "Map over 0 to length - 1";
)Q/ "Increment iterator and split Q into pieces of length iterator";
S*N "Join by space and add new line";
_W% "Copy the mapped string array and reverse it";
3> "Remove the first 3 elements, which comprise of 2 new lines and";
"the original string which should appear once only";
```
Example input:
```
CodeGolfStackExchange
```
Output:
```
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e
```
[Try it online here](http://cjam.aditsu.net/#code=q%3AQ%2C%7B)Q%2FS*N%2B%7D%25_W%25(%3B&input=CodeGolfStackExchange)
[Answer]
## D - ~~178~~ 176
**Golfed**:
```
import std.stdio,std.range;void main(string[]a){int l=a[1].length;for(int i=1;i<=l;++i)a[1].chunks(i).join(" ").writeln;for(int i=l-1;i>0;--i)a[1].chunks(i).join(" ").writeln;}
```
**Un-golfed**:
```
import std.stdio, std.range;
void main( string[] a )
{
int l = a[1].length;
for( int i = 1; i <= l; ++i )
a[1].chunks( i ).join( " " ).writeln;
for( int i = l - 1; i > 0; --i )
a[1].chunks( i ).join( " " ).writeln;
}
```
**Example 1**:
```
F:\Code\D\Other>rdmd spaces.d abcdef
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f
```
**Example 2**:
```
F:\Code\D\Other>rdmd spaces.d CodeGolfStackExchange
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e
```
[Answer]
# k [50 chars]
```
{x c,1_|c:{1_,/-1,/:(y*!-_-(#x)%y)_x}[!c]'1+!c:#x}
```
### Example
```
{x c,1_|c:{1_,/-1,/:(y*!-_-(#x)%y)_x}[!c]'1+!c:#x}"abcdef"
"a b c d e f"
"ab cd ef"
"abc def"
"abcd ef"
"abcde f"
"abcdef"
"abcde f"
"abcd ef"
"abc def"
"ab cd ef"
"a b c d e f"
```
### Example 2
```
{x c,1_|c:{1_,/-1,/:(y*!-_-(#x)%y)_x}[!c]'1+!c:#x}"CodeGolfStackExchange"
"C o d e G o l f S t a c k E x c h a n g e"
"Co de Go lf St ac kE xc ha ng e"
"Cod eGo lfS tac kEx cha nge"
"Code Golf Stac kExc hang e"
"CodeG olfSt ackEx chang e"
"CodeGo lfStac kExcha nge"
"CodeGol fStackE xchange"
"CodeGolf StackExc hange"
"CodeGolfS tackExcha nge"
"CodeGolfSt ackExchang e"
"CodeGolfSta ckExchange"
"CodeGolfStac kExchange"
"CodeGolfStack Exchange"
"CodeGolfStackE xchange"
"CodeGolfStackEx change"
"CodeGolfStackExc hange"
"CodeGolfStackExch ange"
"CodeGolfStackExcha nge"
"CodeGolfStackExchan ge"
"CodeGolfStackExchang e"
"CodeGolfStackExchange"
"CodeGolfStackExchang e"
"CodeGolfStackExchan ge"
"CodeGolfStackExcha nge"
"CodeGolfStackExch ange"
"CodeGolfStackExc hange"
"CodeGolfStackEx change"
"CodeGolfStackE xchange"
"CodeGolfStack Exchange"
"CodeGolfStac kExchange"
"CodeGolfSta ckExchange"
"CodeGolfSt ackExchang e"
"CodeGolfS tackExcha nge"
"CodeGolf StackExc hange"
"CodeGol fStackE xchange"
"CodeGo lfStac kExcha nge"
"CodeG olfSt ackEx chang e"
"Code Golf Stac kExc hang e"
"Cod eGo lfS tac kEx cha nge"
"Co de Go lf St ac kE xc ha ng e"
"C o d e G o l f S t a c k E x c h a n g e"
```
[Answer]
# C# - ~~182~~ 176
```
using C=System.Console;class P{static void Main(string[]p){int l=p[0].Length,i=-l,j;for(;++i<l;){for(j=0;++j<=l;)C.Write(p[0][j-1]+(j%(i>0?l-i:l+i)>0?"":" "));C.WriteLine();}}}
```
Ungolfed:
```
using C=System.Console;
class P
{
static void Main(string[] p)
{
int l=p[0].Length,i=-l,j;
for (; ++i < l;)
{
for(j=0;++j<=l;)C.Write(p[0][j-1]+(j%(i>0?l-i:l+i)>0?"":" "));
C.WriteLine();
}
}
}
```
Output:
```
D:\>program CodeGolfStackExchange
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e
```
**Edit**: now using parameters instead of ReadLine().
[Answer]
# JavaScript 127
```
function f(s) {
o=s+'\n'
for(i=s.length;--i;){
l='',j=0
while((p=s.substr(i*j++,i)))l+=p+' '
l+='\n',o=l+o+l
}
console.log(o)
}
```
[Answer]
## **Python - 153**
```
a=raw_input()
k=0
b=len(a)
for i in range(b+1)+range(b-1):
k+=1
p=[i,b-2-i][k>b]
s=a
if kb+1:
for j in a[p::p+1]:s=s.replace(j, j+" ",1)
print s
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
żvẇ∞⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvHbhuofiiJ7igYsiLCIiLCJhYmNkZWYiXQ==)
```
ẇ # Cut into slices of length...
v # Each of...
ż # Range from 1 to length of input
∞ # Mirror
⁋ # Join by newlines, joining each line with spaces
```
[Answer]
# Q, 34
```
{a,1_(|)a:" "sv'(1+(!)(#)x)cut\:x}
```
[Answer]
# C - ~~134~~ 132
Maximum 8 characters of input, ignoring buffer overflow
```
#define L n){for(i=0;b[i];){if(i%n==0)p(32);p(b[i++]);}p(10);}
main(i){char b[9],n=1,(*p)()=putchar;gets(b);for(;b[n];++L for(;n;--L}
```
[Answer]
# Haskell, 109 bytes
```
p s=putStr$unlines$f s++(reverse$init$f s)
f s=map(unwords.(s#))[1..length s]
[]#i=[]
s#i=take i s:drop i s#i
```
Usage example: `p "abcdef"`. Output:
```
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f
```
[Answer]
# [Factor](https://factorcode.org/), 78 bytes
```
[ dup length [1,b] dup reverse rest append [ group " "join print ] with each ]
```
[Try it online!](https://tio.run/##JYwxDsIwEAT7vGLlGiHRwgMQDQ2iilJcnItjMGfnbMPzTQTVjkaancmWqO1@u1zPRzxZhQMyr5XFcsaLyrJXErex01iTFwcfceo6Q6OdeDZd6zHVhMDiyoL@sBuHn1B@s2beNhdQSiwT@v8LDMwjekFSLwUDPn5LmeyCoVkKoX0B "Factor – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Êõ@òX ¸Ãê
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=yvVA8lgguMPq&input=IkNvZGVHb2xmU3RhY2tFeGNoYW5nZSI)
```
Êõ@òX ¸Ãê
Ê # Get the length of the input
õ@ Ã # For each X in the range [1...length]:
òX # Split the input into substrings with length X
¸ # Join them with spaces
ê # Palindromize
-R # Join with newlines and print
```
[Answer]
# [Raku](https://raku.org/), 44 bytes
```
{.put for map {.comb($^n)},(1...+.comb...1)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wq@gtEQhLb9IITexQKFaLzk/N0lDJS5Ps1ZHw1BPT08bLAJkGGrW/k/TUE9MSk5JTVPX/A8A "Perl 6 – Try It Online")
Raku conveniently has a `comb` method on strings that can split one into chunks of a given size, so it's just a matter of mapping that method from 1, up to the number of characters in the string, then back down to 1 again.
] |
[Question]
[
Given an array of integers A, the task is to output another array B of the same length so that B[i] is the maximum over A for every index that is not i. That is \$B[i] = \max\_{i' \ne i} A[i']\$.
Examples:
```
A = [1, 5, -3, 4, 2]. B = [5, 4, 5, 5, 5]
A = [1, 2, 3]. B = [3, 3, 2]
A = [-1, -2, -3, -1]. B = [-1, -1, -1, -1]
```
The restriction is that your code **must run in linear time** in the length of the input array A.
The input will always contain at least two integers.
[Answer]
# JavaScript (ES6), 54 bytes
*-2 thanks to @l4m2*
```
a=>a.map(v=>v-a?a:m,a.map(v=>a>v?m>v?0:m=v:(m=a,a=v)))
```
[Try it online!](https://tio.run/##bYtBCsIwEEX3nmKWCcwUm@omMOlBxMVQW1E6TWllrh8Dghtd/M177z/FZB@2x/qiJd/GMnERTtKorM44GUkvUfELJFmvdceobNEpCwqb974MednzPDZzvrvJXVqEMwJ1CCeEcPX@8BsEhO6PoaoofM7U1qC8AQ "JavaScript (Node.js) – Try It Online")
### Method
During the first pass, we compute \$m\_0=\max A\_i\$ and \$m\_1=\max\_{i\neq j}A\_i\$ where \$j\$ is the index of the first occurrence of \$m\_0\$. So we have \$m\_1=m\_0\$ if \$m\_0\$ appears more than once and \$m\_1<m\_0\$ otherwise.
During the second pass, we replace each value \$v\$ in the input array with \$m\_1\$ if \$v=m\_0\$ or \$m\_0\$ otherwise.
In the JS implementation, we use `a` for \$m\_0\$ and `m` for \$m\_1\$.
### Commented
```
a => // a[] = input array,
// re-used as m0 (initially NaN'ish)
a.map(v => // (2nd pass) for each value v in a[]:
v - a ? // if v is not equal to a:
a // output a
: // else:
m, // output m
a.map(v => // (1st pass) for each value v in a[]:
a > v ? // if a is a number greater than v:
m > v ? // if m is a number greater than v:
0 // do nothing
: // else:
m = v // save v in m
: // else:
( //
m = a, // save the previous maximum a in m
a = v // save the new maximum v in a
) //
) // end of map()
) // end of map()
```
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 34 bytes
```
zW ma<tl<g rS*^g lS
```
```
g h=h ma~<mn
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY2xDoIwAET3fsXppKYdAE0MKR_gYELC4EAwIaGFxhaxlMXBH3FhMX4TfyMC0-XeXe7e3ypvb0Lrflgp09ytw6PLtZJKFIit0F0hyBLEn85JdhzWMnpeYHLuNC9hk921hE5IiSqqRvzipl6ajROtaxGGSNNT7bKMzCAiQIrUozhQsIBiT-FnI6QT9CmCxbHRMn8uMe8PM0JMruppw5yxaSw45BbT8vzb97P-AA)
## Explanation
First this calculates the minimum value of the list (linear time). Then this scans the list rightwards calculating cumulative maxima, then it scans leftwards calculating cumulative maxima (both linear time). Finally it zips the two results together (lienar time). Since the cumulative maxima are the maxima of the prefixes / suffixes this means that when we zip them together we get the maximum of the values in the prefix before our value and the suffix after. This, naturally is the entire list other than the value in question. Since this is just a series of linear time operations the entire algorithm is linear time.
## Reflection
It feels wrong that `g` shorter in point-free, however I think this is mostly because in normal golf, writing things in point free saves 2 bytes automatically by removing the function declaration. However here we *need* the function declaration (inlining `g` completely is very long) so point-free has to compete on even ground.
* `fid` should not be 3 bytes. This would make the point-free version of `g` shorter by a byte, replacing a `($ ma)` with `fi ma`, but would still be longer than the point-ful version.
* What this really wants is a way to zip with an offset. I'm not sure how universally applicable this idea is, but if implemented it would really simplify this answer.
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
(={],1>./@}.i.|.[)>./
```
[Try it online!](https://tio.run/##PUw9C8IwEN37Kx4usXA5TWKXQsQPcHJyLaGDtFgXFwdB/e3x2tjAPXifd48LVj18DQXCGrVAM46X8yku/TuQ2fJq9@WBP9yUwmNZdNfbAz0MoSK0jrAh2OzCws2iNWitVIQU3Wt4KlXs4dGkqf5PA@MwutUkq3QhNy3BzRVZuHGRQi2ptumRNnNncjNC/AE "J – Try It Online")
*Thanks to Jonathan Allen for pointing out I had missed the linear time constraint. This answer fixes that.*
*Inspired by [Arnauld's answer](https://codegolf.stackexchange.com/a/269943/15469)*
* `>./` Max of all elements
* `1>./@}.i.|.[` Max of all elements after the first instance of the ordinary max is removed. Note because J does not have a "delete at" verb this is accomplished in a roundabout way: We rotate the elements left to put the normal max up front, then delete the first element, then take max.
* `],` Returns "ordinary max" catted with the "modified max" as just described.
* `=` Boolean mask indicating all positions equal to the ordinary max.
* `{` When the mask is `1`, return the modified max. Otherwise return the ordinary max.
## [J](http://jsoftware.com/), orig quadratic time, non-competing, 7 bytes
```
1>./\.]
```
[Try it online!](https://tio.run/##PYyxCgIxEET7fMVgE4TNajamOThBBSsrWw0p5I7TxsbCv4@5iwnswO7Mm32lFesRfQcNwhZdlmGcrpdzsnve3DmktRoe0xsjLMEToiPsCNJcCFw9okWUjORFDd/nR2t1QI9bqZp/NTCOs@uX05cJjRSCq0huuLlRQpNTI@WRsZVZ3KaQfg "J – Try It Online")
J's outfix solves this directly.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œṡFṀṭʋṀiⱮCị⁸ʋ
```
A monadic Link that accepts the list and yields the maximised version.
**[Try it online!](https://tio.run/##y0rNyan8///o5Ic7F7o93NnwcOfaU91AOvPRxnXOD3d3P2rccar7////0YY6CqY6CrrGOgomOgpGsQA "Jelly – Try It Online")**
### How?
```
œṡFṀṭʋṀiⱮCị⁸ʋ - Link: list of integers, A
Ṁ - maximum of {A} -> Max
ʋ - last four links as a dyad - f(A, Max):
œṡ - {A} split at first {Max}
F - flatten {that}
Ṁ - maximum of {that} -> SecondMax (possibly equal to Max)
ṭ - tack {SecondMax} to {Max} -> TwoMaxes = [Max, SecondMax]
ʋ - last four links as a dyad - f(TwoMaxes, A):
Ɱ - map across {V in A} with:
i - first 1-indexed index of {V} in {TwoMaxes} or 0 if not found
-> 1 if V==Max;
2 if V==SecondMax and SecondMax!=Max;
0 otherwise
C - complement {those} (1-x) takes 0:1, 1:0, 2:-1
⁸ - chain's left argument -> TwoMaxes
ị - {complemented locations in TwoMaxes} index into {TwoMaxes}
(1-indexed and modular, so 1:Max, 0:SecondMax, -1:Max)
```
---
### Non restricted solution, 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṁ-Ƥ - map max over overlapping outfixes of length one less than the input
```
[Try it online!](https://tio.run/##y0rNyan8///hzgbdY0v@//8fbaijYKqjoGuso2Cio2AUCwA)
[Answer]
# [C (GCC)](https://gcc.gnu.org) `-lm`, ~~97~~ ~~93~~ ~~90~~ ~~104~~ 101 bytes
-2 bytes thanks to [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
-1 byte thanks to [@att](https://codegolf.stackexchange.com/users/81203/att)
+14 bytes due to a bug fix (`m` was initialized with `a[0]` this causes problems when `a[0]` is the max)
-3 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
f(n,a,m,M,i)int*a;{for(m=fmin(M=*a,a[1]),i=2*n;--i;)i>n?M<*++a?m=M,M=*a:m<*a?m=*a:0:(*a--=*a-M?M:m);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVBLboMwEFWXcAqLqpIx4wpIK1UxJCfgBAhVFoHUUuxEYFaIk3STTdR9b9OepjafKG0X9ryZ9_xmxu-X8nVflh-5Rw_SKz7vhSoP3a5CSat34vj4trl0uqYvX1WNFXCQkIHwhdKEs74-NlimtRQKZynhwPOo8EGkMVGMUsF8sVHbLCFBwLcyzcCK1jIhNjMoXGPCKTWQZttsLX02TM2-7_amA5LcGPuod51WN12pLXIsodgMeNPkURgWJh-Qrlpd8rZq8wKlo7Z_BtRHgEygK0BPgOJhgIUwJ_pHrKYXMaDVXDFkT60wnsQ0mgl7D4DI0pe5rmN-BOGlYKa4zsSukG4UQ0GwpON-To1vaLjRmg19u-1obFcWxjVkJiS_HUUQ-OjUGEmNvYcd8v645KIYjU6dbrHnWTy483-fz1P8AQ)
---
# [C (GCC)](https://gcc.gnu.org), ~~97~~ ~~93~~ ~~90~~ 104 bytes
```
f(n,a,m,M,i)int*a;{for(M=*a,m=M<a[1]?M:a[1],i=2*n;--i;)i>n?M<*++a?m=M,M=*a:m<*a?m=*a:0:(*a--=*a-M?M:m);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVBLboMwEFWXcIoRVSVj7ApIK1UxJCfgBAhVFgmJpeJEYFaIk3STTS7Q27Sn6ZhPlbYLe97Me_PG4_dr-Xooy8vHvdLlW7fbQ9KanTo9HjfXzlT85fNYEc0kq1nGlK-0oVL01akhWUqxmmaJzKNim61tYCqNqRacK-Grjd5mCQ0CuUUVs_J1nVCbIQrXhErOEfIMm2tfDNO8r7sDDoFaKk186F2nNU1XGoscS2gxA9k0eRSGBeYDmH1rStnu27yAdNT2zwz6iAEGvmLwxCAeBrYQeKJ_xGrqiBms5gqSPbfCeBLzaCbsPTCgy1zhug5-CpClgK_4eZP4gXyjBQTBko77ORW5odmNFjf07bajsV1ZoWsoMCS_HVUQ-HBuUFIR72EH3h-XXBWj0bkzLfE8iwd3_u_LZYrf)
[Answer]
# [Python 3](https://docs.python.org/3.8/), 71 bytes
```
def f(a):h=nlargest(2,a);return[h[x>h[1]]for x in a]
from heapq import*
```
[Try it online!](https://tio.run/##RY/NDoIwDMfve4reBNMdAEkMZrzI0sNEcCSyzTETfHrcZqJNm/Tj1@Zf9w7amubs/L7fxgmmQpWdFuah/H1cQ1GjKi9@DC9vpJZbr2VFNFkPG8wGFLHJ2wX0qNwT5sVZH457iIurAMkgmpQVQovAG4QTQk0Iss1p@3Ui/IM1QpOICDcJ/s14HPL6e4ZXCcmdXxAxYiwJU3hN0rKILm8PIPJfuXB@NqFQeOC8P@AVh4gLAUO5fwA "Python 3.8 (pre-release) – Try It Online")
-4 bytes thanks to movatica
Compute the first and second maximum `h[0]` and `h[1]` of array `a`, then output `h[0]` or `h[1]` where appropriate.
Using `sorted` would take 20 fewer bytes than using `heapq.nlargest`, but would break the O(n) requirement.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 71 bytes
```
x=>x.map(v=>v-n?m:M(...x.filter(u=>u-n||0*++n)),m=n=M(...x))
M=Math.max
```
[Try it online!](https://tio.run/##ZY3LCoMwEEX3fsUsk5rEqnVTGAvd@wXiIlhtFU3EF1n476lVKNjCzGbuOXdqOcsh76tu5Eo/CluiNRgb0cqOzBjPXN3aa0KEEEaUVTMWPZkwnrhalvPJdRWlrEWFO0Gpk2Aix9eqG5trNeimEI1@kpKkPoOIAQ8ZXBgEGaXgeQLugJBG2y3aJ3P@xYBBeDDWlvDT8svyFebB/ob7B2WLvpvZNw "JavaScript (Node.js) – Try It Online")
-1 byte from Arnauld
After first meet of n, n is increased so it's larger than max, aka no more value can equal to n
[Answer]
# [Python](https://www.python.org) + NumPy, 44 bytes
```
lambda L:L[L.argpartition(-2)[(L<max(L))-2]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jY9LCsIwEIb3PcUsJ5AITS2I2kW7zg1qFxGpFpoHIQV7FjcF0Tu59iL2YbtVmGGYH76PmdvTtv5idHcvk8Oj8SXbvGgt1fEkQWxFLlbSna10vvKV0cg4yVHslbyiIITxovgy79IZBbpRtoVKWeM8SOdkG6SQQB5SiCmwiMKaAi92kA1pPK7xVEVgXaU9YokjiCkhSZKRlaxrJGTxcArRLOh90eD7B2U9y_h0BAtnw5gu_UM0vdp10_wA)
Takes and returns NumPy arrays. `numpy.argpartition` uses the linear time introselect algorithm to find in this case the second largest element (or rather its index) and split at this value.
[Answer]
# Google Sheets, 49 bytes
```
=let(a,A1:E1,m,max(a),sort(if(a=m,large(a,2),m)))
```
Put the input in cells `A1:E1` and the formula in cell `G1`.
`max()` and `large()` get evaluated once only. `sort()` is used as an array enabler and won't actually sort anything.
[Answer]
# [J](https://www.jsoftware.com), ~~20~~ 19 bytes
```
(]{~[=0{])(2$,\:,)/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxWSO2ui7a1qA6VlPDSEUnxkpHUx8iczNWkysRpNHe0EDF0IArNTkjXyERQhna6enH6MF4aTCGujrxOiCWLFgAoQE)
Copy of [my answer in chat](https://chat.stackexchange.com/transcript/message/65143744#65143744) to the [CMC version of this challenge](https://chat.stackexchange.com/transcript/message/65143701#65143701).
-1 byte thanks to Jonah by spotting `\:~@,` → `,\:,`.
```
(]{~[=0{])(2$\:~@,)/ input: v = a vector
( )/ tops = reduce from right:
\:~@, concatenate and sort descending
(this sorts a constant(2 or 3) number of values,
so it runs in constant time per element)
2$ take the first two (largest and 2nd largest)
( ) run the rest with v on the left and tops on the right:
0{] the largest
[= per element, 1 if it is equal to the largest,
0 otherwise
]{~ per element, 2nd largest if ^ is 1, largest otherwise
(gives 2nd largest for largest and largest otherwise)
```
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
=Ṁị;Ṣṫ-ʋ/
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//PeG5gOG7izvhuaLhuastyosv////WzEsIDUsIC0zLCA0LCAyXQ "Jelly – Try It Online")
Jelly port of the above algorithm.
# [J](https://www.jsoftware.com), 16 bytes
```
(2$,\:,)/{~>./=]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxQcNIRSfGSkdTv7rOTk_fNhYifDNWkysRpMve0EDF0IArNTkjXyERQhkC1cXowXhpMIa6OvE6IJYsWAChAQ)
J backport of the Jelly port of the above algorithm, which turns out to be shorter! Does not reuse the "tops" array and computes the maximum again instead, which does not affect the overall time complexity.
# [J](https://www.jsoftware.com), 20 bytes
```
(>.|.)&(#$__,>./\)|.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxRcNOr0ZPU01DWSU-XsdOTz9Gs0YPInUzVpMrEaTT3tBAxdCAKzU5I18hEUIZglTqwXhpMIa6OvE6IJYsWAChAQ)
Port of [Wheat Wizard's Haskell+hgl answer](https://codegolf.stackexchange.com/a/269952/78410).
`f/\` normally creates prefixes and reduces each prefix by `f` from the right, which costs quadratic time, but it is [special-cased](https://code.jsoftware.com/wiki/Vocabulary/SpecialCombinations#Partitions) for atomic and associative functions, which includes `>.` (max of two numbers).
```
(>.|.)&(#$__,>./\)|. input: v = a vector
|. reverse(v)
call the rest with v on the left and reverse(v) on the right:
( )&( ) apply the right to both sides:
>./\ cumulative max (linear)
#$__, prepend __ (negative infinity) and
chop one from the end (linear)
>.|. reverse the right side again and
take elementwise max (linear)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
≔⌈θη≔⌕θηζ≔⌈Φθ⁻κζζIEθ⎇⁼ιηζη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7EiM7c0V6NQU0chQ9OaCyrslpmXolEIEtJRqEIIw1S7ZeaUpBaBFPhm5pUWa2SDVGlC1QYUZeaVaDgnFpcA1ReAFIWkFuUlFlVquBaWJuYUa2RCzQVRQGD9/390tKGOgpGOgnFs7H/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⌈θη
```
Get the maximum value of the input list.
```
≔⌕θηζ
```
Get the index of its first occurrence.
```
≔⌈Φθ⁻κζζ
```
Make a new list excluding that index, and take the maximum of that.
```
IEθ⎇⁼ιηζη
```
Output that value for the maximum values in the list, and the maximum for the other values.
By comparison a fully golfed version would be ~~19~~ 9 bytes:
```
IEθ⌈Φθ⁻μκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQR8E3sSIztzRXwy0zpyS1CCySmVdarJGro5CtCQbW//9HRxvqKBjpKBjHxv7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Runs in O(n²) time. Explanation: For each element, creates a new list without that element, and takes the maximum of that list.
[Answer]
# APL(NARS), 119 chars
```
r←f w;a;b;n;i;t
n←≢w⋄i←2⋄a←b←w[1]
→4×⍳i>n⋄→3×⍳∼b<t←w[i]⋄a←b⋄b←t
i+←1⋄→2
i←1⋄r←⍬
t←w[i]⋄→6×⍳∼t=b⋄r,←a⋄→7
r,←b
→5×⍳n≥i+←1
```
15+17+29+7+7+23+4+10 +7=119
2 pass of the array, one for to find the maxs, and one for build the result array.
Test&how to use. one not difficult solution but possible the more long and lazy.
```
f 1 2 3
3 3 2
f 1 1
1 1
f ,1
1
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=max,first -a`, 81 bytes
```
$m=max@F;$i=first{$F[$_]==$m}@t=0..$#F;$;=max@F[grep$i-$_,@t];say$_-$i?$m:$;for@t
```
[Try it online!](https://tio.run/##JY2xDsIgFEV/hcQ3FkI1LBAiUycdnZqGMLTmJUUIvEFj/HWx6nSHc3JunsuqWoNoY7i7wQDaBUulJwwj@MlaiC9HVgoBu42avzZey5wBOfjO0WRqeIDngEeIGsySiqPWerZnB6aYeqdMmG618bMSspfbnrCS1hfC9dvrfo@Nhw8 "Perl 5 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~72~~ 66 bytes
```
def f(A):B=len(A)*[A.pop(i:=A.index(max(A)))];B[i]=max(A);return B
```
[Try it online!](https://tio.run/##RY/bCoMwDIbvfYrcrR2poE4YSgf6GqUXHiorbLXUDtzTu1rBhQSS/F9CYr/@OZvibt22jWqCiTS0avlLmZBcRZPa2RJd8SbVZlQreXdrECiVdSu05EdZO@U/zkC7ebX4hYNIIJgQGUKJwAqEG0IuEUQZ0/JwKfEP5gjFTgS42OFTY0Fk@bGGZTsSO2dImcgkmWYHHfagDcQjqjg9AA8vdTQW1mnjSYcXxh4X7HEIOOcw0O0H "Python 3.8 (pre-release) – Try It Online")
First, observe that `B` contains the second largest value of `A` at position `i` iff the largest value in `A` exists exactly once, at that very position. In all other cases (largest value exists more than once or `A` holds only one value), `B` consists solely of `max(A)`. So all we have to handle is that one special case.
Ungolfed:
```
def f(A):
l = len(A)
m = max(A)
B = l * [m]
i = A.index(m)
A.pop(i)
B[i] = max(A)
return B
```
As `max` and `index` are linear operations and `len`, `pop` and assignment are constant time, the runtime is `O(3n) = O(n)`
[Answer]
# APL+WIN, 22 bytes
Prompts for vector. Index origin = 0
```
⌈/0 1↓(⍳⍴n)⌽(2⍴⍴n)⍴n←⎕
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3t/6OeDn0DBcNHbZM1HvVuftS7JU/zUc9eDSMgC8IBEkDVQF3/geq5/qdxGSqYKhxab6xgomDEBeIZKRgD6UPrDYGiRmAZIBsA "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
In 1.13, Minecraft language files were switched from being a simple multi-line key=value format to [JSON](https://en.wikipedia.org/wiki/JSON).
# Challenge
Write a program converting from the original format returning a JSON string. Input can be taken using any standard input method, output must be json from any standard output method
The original format contains lines with key=value pairs, for example
```
tile.dirt.name=Dirt
advMode.nearestPlayer=Use "@p" to target nearest player
build.tooHigh=Height limit for building is %s blocks
```
Should be converted to one large JSON object with key=value
```
{
"tile.dirt.name": "Dirt",
"advMode.nearestPlayer": "Use \"@p\" to target nearest player",
"build.tooHigh": "Height limit for building is %s blocks"
}
```
## Some details
* Any valid JSON is allowed as long as it contains only the correct key/value pairs. Trailing commas are allowed because Minecraft allows them.
* The only things that must be escaped are quotes. (No newlines, backslashes, or other json-breaking things existed in the language file prior to 1.13)
* Empty lines should be ignored
* Lines contain exactly one equals
# Test Cases
Input:
```
tile.dirt.name=Dirt
advMode.nearestPlayer=Use "@p" to target nearest player
build.tooHigh=Height limit for building is %s blocks
```
Output:
```
{
"tile.dirt.name": "Dirt",
"advMode.nearestPlayer": "Use \"@p\" to target nearest player",
"build.tooHigh": "Height limit for building is %s blocks"
}
```
Input:
```
translation.test.none=Hello, world!
translation.test.complex=Prefix, %s%2$s again %s and %1$s lastly %s and also %1$s again!
translation.test.escape=%%s %%%s %%%%s %%%%%s
translation.test.invalid=hi %
translation.test.invalid2=hi % s
translation.test.args=%s %s
translation.test.world=world
```
Output:
```
{
"translation.test.none": "Hello, world!",
"translation.test.complex": "Prefix, %s%2$s again %s and %1$s lastly %s and also %1$s again!",
"translation.test.escape": "%%s %%%s %%%%s %%%%%s",
"translation.test.invalid": "hi %",
"translation.test.invalid2": "hi % s",
"translation.test.args": "%s %s",
"translation.test.world": "world",
}
```
Input:
```
stat.mineBlock=%1$s Mined
stat.craftItem=%1$s Crafted
stat.useItem=%1$s Used
stat.breakItem=%1$s Depleted
```
Output:
```
{
"stat.mineBlock": "%1$s Mined",
"stat.craftItem": "%1$s Crafted",
"stat.useItem": "%1$s Used",
"stat.breakItem": "%1$s Depleted"
}
```
[Answer]
# Python 3, ~~91~~ 77 bytes
*-14 Bytes thanks to OM·ó∫*
I thought that the printout of a Python dictionary would be close enough to JSON to make it a very competitive language for this challenge. However, the string representation of python dictionaries is different enough from JSON that I had better luck using python's built-in JSON library. I'll bet this can be done more succinctly in JavaScript.
```
import json
f=lambda x:json.dumps(dict(i.split("=")for i in x.split("\n")if i))
```
[Try it Online!](https://tio.run/##ZY8xawMxDIV3/wr1aOAOiiF0Kxg6ZEiHQpdObQdfrMup0dnGUtLcr786oZm6iKenpw8pzzqm@LjQlFNRkFlu8ltSNINjP/XBw/np0ttwnLK0gXbakpXMpG3jmm5IBQgowvlmfsamowGo65ZcKGo7tJVtfdmfPtZf1V2UGG2gojb6Cd2mKuPD6TUFtBF9QdE39jMW9y4IzXNuQBNoJaDCXwDyNWFMfyQOVlPa0n50W6xVgWkihctt1zHFPZDASqDntDuIMVp8FPZK9TOtOBtTxLrNnB7gJxUOd/8zFE@eKbiRYGWMqFfbF/SHF8XJrdb3AhvMjIrhFw)
---
Edit:
# Bash + Sed, ~~68~~ 63 bytes
*Bug fix thanks to OM·ó∫ and Night 2*
*-5 Bytes thanks to OM·ó∫*
I realized that it might be more byte efficient to directly convert the text to JSON without bundling it in an object, as was my approach for the python solution. Per byte, sed is the most powerful language for regex replacement that I know of.
```
echo {`echo "$1"|sed 's/"/\\\"/g;s/\(.*\)=\(.*\)/"\1":"\2",/'`}
```
[Try it Online!](https://tio.run/##LYq7CgIxEEX7/YphUHwgCVoqCxYWNoKNXQqzZtwNZjeSGQVRvz3KanPPhXMqy03OdGoiPI89cDDHF5ODEWvUxhjU9Yq1GaupmZQ/aDRzXKJZ4EyPju@cs/hAyvkkqrMtlZvvK6y776Ij1ZFNxLIP9kGpPDABrq8IEkFsqkngH8C1L4qiuvnglMS49XVTbum7AsG3XuAcE/TadzV4hiFDFeLpwh8)
## Explanation
```
echo {` # prints the leading curly brace
echo "$1"|sed # feeds the input into sed
's/"/\\"/g; # replaces " with \"
s/\(.*\)=\(.*\)/"\1":"\2",/' # surrounds the left and right hand sides of the equals with quotes and joins them with a colon
`} # prints the closing curly brace
```
[Answer]
# Vim, 44 bytes
```
O{*<Esc>*:%s/"/\\"/g|%s/\v(.*)\=(.*)/"\1":"\2",
o}
```
Explanation:
```
O{*<Esc>* Prepend {
:%s/"/\\"/g Escape all "
|%s/\v(.*)\=(.*)/"\1":"\2", Json-ify lines
o} Append }
```
[Answer]
# [Rust](https://www.rust-lang.org/), 150 bytes
```
|s:String|s.replace('"',"\\\"").split('\n').filter(|l|l.len()>0).map(|l|format!("\"")+&l.replace('=',"\":\"")+"\",").fold(format!("{{"),|r,n|r+&n)+"}"
```
[Try it online!](https://tio.run/##RVDBSsQwEL3nK8YsbhO2BM8rFQ8e9iII4q0g2W1ag9OkTGYFafvtNS2icxiGmfcebx5dEy9tgN76oDSMAnKhY2ihgmVKx1cmH7opGXID2otThSxKWde1lNqkAT2rog6FNq1HdqQmnNCgy2IPd9r0dlg3baTe8o2SK@uwx3@xahWTx22fhzKLthEb9ccYR6nLicow0WEfMmiWy/3mcsjGGMOKmWXZKtpJwR6daTyxCbZ31VOehG2@nmPjTHCWXOIXtN@OqrfkQD4OEjgCW@ryy78AGDaEEOerx8ZwjCfffVQnlzsD@t7ndCLBds7ZgE9wm@CM8fKZhNxlxnvaUlNaazEvPw "Rust – Try It Online")
Is it longer than Java?
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes
```
"
\"
=
": "
G`.
.+
"$&",
^
{¶
$
¶}
```
[Try it online!](https://tio.run/##LYpBCsIwEADP7iuWUL0oeYAQ8CDYi@DFm4ipXetimpRkFUT8Vh/Qj8VSvAwDM5GEvc1ZwUmBAbVGBbuLBr2EmSoWagVn@Aw9FDD035yFHemao2hvWzLb0cDWr32oSXuykZIcnH1TNMdEqDadQgkoNjYk@B@wmw6A6smu1hJCyc3dlDRS0HHLgrcQccrsG@SE84SVC9dH@gE "Retina 0.8.2 – Try It Online") Would be 34 bytes in Retina 1 as you can use `L$`.+` instead of `G`.` and `.+`. Explanation:
```
"
\"
```
Escape the quotes.
```
=
": "
```
Fix up the key/value separator. (If the value might contain a `=`, use `1`=` at a cost of 2 bytes.)
```
G`.
```
Remove empty lines.
```
.+
"$&",
```
Wrap each line in quotes. (The inner quotes were added earlier.)
```
^
{¶
$
¶}
```
Wrap the entire output in `{}`s.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 bytes
String manipulation is not really Husk's strength, but it did pretty well:
```
`J"{}"J',mȯJ':msx'=fI¶
```
[Try it online!](https://tio.run/##LYoxCsIwFED3nuITkC6SAwgBB4daEFzcOpia3/bTpCnJryjimdw8gJO3iqW4PB68102xT@lcisdTlPnafV9lvnHxlqtm/3mnlASTRWkosBy0Q7WbLdPmevAG5YA6YOSj1XcM6hQRKrEdKwHsgXVokeG/wLg8WVZPZI1k7wtqO1XgTAZLjhgaH2DJNLRAEVYRausvfRQ/ "Husk – Try It Online")
```
¶ -- split on newlines
fI -- filter by identity (ie. remove empty strings)
m( ) -- with each line
x'= -- | split on '='
ms -- | show each (ie. enclose in quotes and escape quotes)
J': -- | join with ':'
J', -- join these with ','
`J"{}" -- join the string "{}" with the result
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 56 bytes
```
->x{x.split(?\n).map{|i|i.split(?=)}.to_h.to_json}
```
+6 bytes for `-rjson` interpreter flag.
[Try it online!](https://tio.run/##dZFBTwIxEIXv@ytGY7OSQBM5U7lo4sl4V2NGtgslw3TtdHUJ8NvX3QInlstL@r03k8xrqL@3bVVHgZw9rMVzDjWTFYFgf2oXLOSJZgVGBAOzWf78@pRnMSALYXSedbQSNXu25sUS@TH8@UDFzWVm4TcV2ca8BVu6ZgxK1PROAJfouHsAcgHqoSOEEml7RkjijzwlBxZbWWBljeoG1ElOquQy7fgXyRVm5UBddafJBhiYx7AU0@8f8NLpJult1jWVlWDayWOza7RU5OL9/INHeoPVbu/27szM6KCj/1r10td9OP5J@d63/tm2k9DTfw "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-nl -M5.010`, ~~58~~ 54 bytes
```
BEGIN{say'{'}s'"'\"'g;/=/&&say qq|"$`": "$'",|}{say'}'
```
[Try it online!](https://tio.run/##LcpBDwExEAXg@/6KSYNeKA4uZBMRggNxcXPQtWNNVLvaIRH2r6vNxuXl5b2vRG9GMc4Wy/X2HfRLvmUVpJAHIYtJP@13OvUI9/tHtI5iDKIlRfdTNbKSMTIZVDl5VlbfMJ3XLdH5c@NyVBa1x8A7o1/o031AENNSADtg7Qtk@AMoG5Ek2YNMrti5FRWXdIV1Mhi6EcPZeWhusgVQgHaAzLjTNXxdyeRsiL3NSA2Gg9iz5gc "Perl 5 – Try It Online")
---
58 byte version:
```
BEGIN{say'{'}s'"'\"'g;s/(.*)=(.*)/"$1": "$2",/;END{say'}'}
```
[Try it online!](https://tio.run/##LcpBa8JAEIbhe37FsFi2lbpRIRclUIpSezD00puXTTPGoWt22ZkWJOSvd9XQy8sH3xMwuiKl1@3be9WzveheD6yVPijdrjl/NNOn8p5cTRZqBWqyVM/5elttRjzoISUhh6ahKKazZyw3t5XZ5nfvGzQd2ogsH85eMJafjKBeggLxIDa2KPAPIIwiy@ofco0R73fUnsod3irg6EwCRx9hvKlrgRgeGGrnv775zwch33Ga7QszX8whzcIV "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~75~~ 71 bytes
-4 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) (using do-notation over list-comprehension)!
Works with multiple `=` on one line:
```
f s='{':do{(a,_:b)<-span(/='=')<$>lines s;show a++':':show b++","}++"}"
```
[Try it online!](https://tio.run/##LY7BasMwEETv/opFpCjBqXt3o9JDDrkUcsm5rKONvUSWjHbbEkK@3RGml@HBPJgZUK4UwjxfQJy929an@xq332232b3KhHH95qyzm93qI3AkAXmXIf0B1rVtbbtwV9dmax4lH2YekSM44KiU8axwmZUDNZ6zNhFHcvtCFfrfr@SpiYSZRI8Bb5TdSQjM52RAEyjmnhT@BZgWo6q6Hw6@0ZQO3A/uQCUVAo9cllKGpebYlwcvAl1I56s8AQ "Haskell – Try It Online")
## Explanation
The term `span(/='=')<$>lines s` splits the string on the first `=`, leaving us with `("<initial part>","=<remaining line>")`. Doing a pattern-match `(a,_:b)` ensures that the line was not empty and at the same time removes the leading `=`.
Now we only need to `show` both `a` and `b` (enclosing it in quotes and escaping quotes), do some formatting (`:` and `,` characters) and finally enclose it in `{}`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 243 219 bytes
Thanks to ceilingcat for the suggestion.
I decided to use a state machine to handle the three cases (newline, key, value) and it turned out pretty well. Also, I got to abuse the fall-through feature of `switch` and the macro stringizing operator!
Although the challenge didn't require it, I also escaped the `\` character [per the JSON spec.](http://json.org/) If that character will never be in the input, then `&&c-92` can be removed for 5 more bytes.
```
#define p(s)printf(#s,c)
#define a(i)case i:
c,s;f(){for(p({);(c=getchar())>0;)switch(s){a(0)if(c<11)break;s++,p(\42);a(1)c==61?s++,p(":"):p(%c);break;a(2)c-34&&c-92?c==10?p(\42\54),s=0:p(%c):p(\\%c);}s-2||p(\42);p(});}
```
[Try it online!](https://tio.run/##dVDNbsIwDL7zFBksEIuCaMcmjS7juuMeoBcvTSFaSKO6AqbCs3ehHSfYxZa/v9hRs41SbTvKdWGcZl4Q@Mq4uhAjihQMrgQKAwpJM7MaqIjSQkBTlJXwooFUKLnRtdpiJQDeFynQwYQxZDUoFmAKod7iGL4qjd8pTaeRF9kygRRFDErKl3jdg8PVEFZecAVpr0WRgJo9LcdjNXtN1kEbL9adOXteQkRy0ctDzbKL7Uyz5HT6i/fiHJA2XMN2aJzYlyYH1rCwe8rObV2hI4u1Kd281lTPXem0/NDWlhE7lJXNHwY3GlXuvNVH@VmFfzlGjBNPHonhJjwQBoYuZzwOiEWq7c8VQktlj3fKO8GaFHoth5zTkPFQswm/tMllCP3WYdwercnl1jD@L5t0NGN3/FhtSIb97mV358uu/gI "C (gcc) – Try It Online")
---
## Original submission: 243 bytes
The original submission kept unneeded spacing as in the provided JSON examples.
```
#define p(s)printf(s,c)
#define a(i)case i:
c,s;f(){for(p("{\n");(c=getchar())>0;)switch(s){a(0)if(c<11)break;s++,p(" \"");a(1)c==61?s++,p("\": \""):p("%c");break;a(2)c-34&&c-39?c==10?p("\",\n"),s=0:p("%c"):p("\\%c");}s==2&&p("\"\n");p("}");}
```
[Try it online!](https://tio.run/##dVDNcsIgEL77FDQtGRijk6SdztSUeu2xD5DLlpDIFCHDZtROxmdPEfWkvXyw38@yi1x0Uk7TY6NabRXpGfLeazu0DDPJZ1cemOYSUBG9mskMq5bxsXWe9SwZa5vwiknRqUFuwDPOP/KK416HMrQbgeVct0y@FwX/9gp@KpzPs5AkpE5CFFjBpRCvxfrC18kqKqtwpzI4zilgJZeL55c0Dfi2DpEiX0d7dhohQ5FfE6ezrmP2iEKUaRp9cdJwO574KWxJtqAt2zndcDKSsFRFjtPgwaKBQTu7HBQOS@usEp/KGJeRvfOmeZjdeKTb9kYdxJcPH3bICEVaPiGBLjwQCgK2IbQIjAEczO@VAoPuzEfnncYKJfRK0BCgF7ggxVu3tjswuhEbTei/ahllQu7kwXcoTv3vaHF1EfEP "C (gcc) – Try It Online")
[Answer]
# JavaScript, ~~66~~ ~~63~~ 62 bytes
```
s=>JSON.stringify(o=/(.+)=(.+)/g,s.replace(o,(_,a,b)=>o[a]=b))
```
```
f=
s=>JSON.stringify(o=/(.+)=(.+)/g,s.replace(o,(_,a,b)=>o[a]=b))
console.log(
f(`tile.dirt.name=Dirt
advMode.nearestPlayer=Use "@p" to target nearest player
build.tooHigh=Height limit for building is %s blocks`)
)
```
*-3 bytes thanks to [@redundancy](https://codegolf.stackexchange.com/questions/170296/minecraft-language-files-updater/170341?noredirect=1#comment411492_170341)*
*-1 byte thanks to [@l4m2](https://codegolf.stackexchange.com/questions/170296/minecraft-language-files-updater/170341?noredirect=1#comment421174_170341)*
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes
```
¶¶
¶
"
\"
=
": "
m`$|^
"
m`^
$
¶}
^
{¶
```
[Try it online!](https://tio.run/##dU9LCsJADN3nFLF0diLYpTB7lx5AiqEddSCdKZPBD@q1eoBerI5VV9YQXsj7BBJMtI6Goe/6DlJnsM1AQ7bCDJpdfi/hNUvAVJAnxwNKuPXdMMRATpii9W4RjcSF887otWH2czz7wPUMfjyVb1o2F70JZm8vc1SiilyQDmRdWpBcjWqZGCaJfP1SxOLf/OicOGykotZolQLqAx9U8uu27kRsa320qP6qxSgjTuQpHES/7k9o4@t6xCc "Retina 0.8.2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 48 bytes
```
{to-json %(.lines.grep(?*)>>.split("=",2).flat)}
```
*2 bytes less if we can assume exactly 1 equals sign on a non-empty line.*
[Try it online!](https://tio.run/##hVLBTtwwEL3nK4aoQbvV1oggcSgyrVpWogckLpW4ziaTMMWxU89AWVX9KT6BH9s62V0hsYvwYWTPe@N5fp6eojtddUs4bMDC6q@GT78keCgmxrEnMW2kfvLl4/T83EjvWCe5zWfl1DQOdfpvdZZlgktoJr8/azia3xwfTc8yZUem5qjGY0f2Iu0yrB@uQk3GE0YSvXa4pGh/CkH@tc9BAyjGlhQ2BOhHRpYt7tnVRkO45PbWXlKKCo47VmhChBFm3wILFAILF6o7yZKQtbDcblf@Wmo5So3oJT2Fgzea2hofPKUuzoUZ/AnR1Qe7nCp0vaNHex2p4cdZ6luUHwSwRfaDCPQ1FMcp41DULbcpdBLW@ZG552KSCnuyRSooNmETC9lls39Ax7W9ZSjeRMsRBthTn/wWO9y/Bxufbse4C87ZixJ7O08z01XPT8nv8l2/Twa/RVFNlybr2/BRdnTjKh3rNVJFbPSHUrdGvg/HLXYv9IKkwdmkF5Hw7gW4oPQ1Q01quPoP "Perl 6 – Try It Online")
Ungolfed:
```
{ # An anonymous block, taking 1 string which ends in $_.
to-json # Convert a Perl 6 number, string, list or hash to JSON and return it.
%( # Force to hash (dictionary)
.lines # Break $_ (implicitly assumed) into a list of lines.
.grep(?*) # Pick only those that are True (non-empty).
>>. # For each element in the list, call the following method ...
split("=",2) # ... split the string at =, making at most 2 chunks.
.flat # That gives a list of 2-element lists. Flatten it.
) # List is converted into the hash like this: { first element => second element, third => fourth, ... }
} # Implicitly return
```
By the way, the `to-json` routine is deprecated, as the compiler will tell you, but who cares.
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
lambda s:'{'+re.sub(r'(.*)=(.*)',r'"\1":"\2",',re.sub('"',r'\"',s))+'}'
import re
```
[Try it online!](https://tio.run/##LY6xagMxEER7fcWyYHQXG0FcGgQpUrgxBEy6a3TR@iyik8RqHTAh337ROWkeM8wrptzlmtN@udhhiW4evYN60N96y2TqbexYd@aptyv0jjUOz3jAYY@71v4MjeswNNa@3@ofrcJcMgswLWeLiEpCJOMDi0luJvvaknL@65Q9mUSOqcpbdHdi@14J8KUgSAZxPJHAvwDlYSg13kL0RnI@hulqj9QoEMMcBC6Z4TGHNEGosKkwxvzxWdX6QhUOqUnduV9@AQ "Python 2 – Try It Online")
[Answer]
## Ruby, 59 + 5 = 64
Needs `-rjson` (+5)
```
->c{Hash[*c.split(?\n).map{|l|l.split ?=}.flatten].to_json}
```
Explanation:
```
->c{ } # anonymous function with param c
Hash[* ] # converts ["a", "b", "c", "d"] into {"a": "b", "c": "d"}
c.split(?\n) # splits c into lines
.map{|l| } # map lines so each element represents
l.split ?= # an array of itself but split by =
.flatten # merges 2d array to 1d (also gets rid of empty elements for newlines
.to_json # converts hash to json
```
[Answer]
# JavaScript (ES6), 66 bytes
```
s=>`{${s.replace(/"/g,'\\"').replace(/(.*)=(.*)/g,'"$1":"$2",')}}`
```
Assumes there's only one `=` per line
## Testing snippet
```
f=s=>`{${s.replace(/"/g,'\\"').replace(/(.*)=(.*)/g,'"$1":"$2",')}}`
```
```
<textarea id="i" onkeyup="o.innerText=f(i.value)"></textarea><pre id="o">
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 30 bytes
```
O{␛Í"/\\"
ggòeÉ"vyf=Plp$pa,òo}
```
Expects one input at a time. The TIO snippet runs all given test cases as a
single input.
I'm new to V's extended mappings, so tips are always welcome!
[Try it online!](https://tio.run/##dZGxbsIwEIZ3v0KXa0Q2lKrslqqWgQ6oLN1YDnwJFo6d2kcKqvoAHfoyvEIeLHVCEAPUw8l333@/fOe6bd@@7prf5GG5TERRNEdqfpL6kMuFqUYVjpuj@25b1oYypT1nFkuS03gTqOq5U5RZQk@BFwYP5OV7IEieqgTYAaMviGEQQNUrhFjttFEZOzfTxUbOKEYGo0vNkDsPPda2AB0gDbAybr0NQgj2aINB1s5mHP0y6yzFdmPcGD6dN@r@WrN2ZWVoLxeecr0fR8N0MgqABWrbuaNVkD7GisHA5nAuoQnuVO@VN4wprLEimcaGdAhDTMO1WtsajVZyoyH9l056DHCjPy4yyM7/ButHl32MWwqMnJXa0nO3N9nPMI@pOpG1x5xfmcoTeenSM9sFupD4j0N55Qm3FzCluNCuR4iPnYsvkEl3/gA "V – Try It Online")
## Explanation
```
O{‚êõ # insert { on a new line above
Í # global substitution across all lines
"/\\" # " => \"
gg # go to first line
ò # recursively...
e # forward to end of word; if at end of line, applies to next word below
É" # prepend " to first non-whitespace char
vy # copy current character (i.e. ")
f=Plp # paste " before and after the next =
$pa, # paste " at end of line and append ,
ò # ...end
o} # insert } on a new line below
```
[Answer]
# R, 118 bytes
```
function(s){cat(paste("{",gsub("(.*)=(.*)","\"\\1\":\"\\2\",",gsub("\"","\\\\\"",gsub("\n{2,}","\n",s)),perl=T),"}"))}
```
[Try it online!](https://tio.run/##PY8xa8QwDIV3/wohOM4ubqA3lgY63HBLoUO7eXESJTX12cFSCiXkt6fJcVTDk/jeg4fK2sPL49pPqZWQk2Yzt1706FlI44x24KnRqKsHU@@CFh069@Twed8nt4F7xuFu7oP/KM0nu@w4oWVj7Egl1h/G4oLGLCtv3XCUEKnqQpEq@SvV5@1Svvt5yx1ViXwhlvfof6nUn0yAryOCZBBfBhK4B2C8JZRqphC7SnK@hOGrvtCmAjFcg0CfC9zskAYIDAeGJub2m49K9dvn6x8 "R – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 119 bytes
```
#define p(s)printf(#s,c)
s;f(c){for(p({);~(c=getchar())|s;)c<11?s=s&&!p(", "):c-61?s++||p(\42),p(\\u%04x):p(":");p(});}
```
[Try it online!](https://tio.run/##dU/BbsIwDN2ZrzBlgVgUNBDagS7adcd9AJcoTUukkERxxpgo@/UudNoJdvGT33v2s9WiVarvJ7VujNMQOGGIxqWGT6hUOKKq4QrPjY888DNW31yJVie1l5EjdlShelmtXknQdDoOvCgfCtyqxXOm5vOuC3y3WWOZYffBnjYn3GbPtsAq8AtWlz4nwUEax4/e1AhnaDhWcOlTlI6sTMa7ZdKUls47Ld60tb6ETx9tPR7deJQ/BKtP4j3mZ04lMGLrRwLZ5oDcgHQ1sFVmrKRkv/4oacn/8oPzzmJNSgYtCsaoAJbrbsauMLs2GUe3I8YdpTW12Btg/6rrQQagW4eMLYl8ILujDf@Lof4A "C (gcc) – Try It Online")
[Answer]
# PHP, 87 bytes
```
preg_match_all("/^(.*)=(.*)$/m",$argn,$m);echo json_encode(array_combine($m[1],$m[2]));
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/4d368a114db508924abbc9f55ebd43218311cba1).
Insert `\s` before `$/m` for Windows linebreaks; `\s*` if linebreaks are uncertain.
Insert `U` after `$/m` if values contain `=`.
[Answer]
# [Dart](https://www.dartlang.org/), ~~142~~ ~~114~~ 108 bytes
```
f(s)=>"""{${s.replaceAll('"','\\"').replaceAllMapped(RegExp(r'(.*)=(.*)'),(m)=>'"${m[1]}":"${m[2]}",')}}""";
```
[Try it online!](https://tio.run/##dVLBauMwED2vv2JqYiwvRtAcG7R0d1voHgJlYU9NDxNrnIjKkpGm2ZSQb8/KrguBZn14zMx788YaSWPg06kVsVLf8jw/zA5RBuotNvTdWlHmZV2uVnlZnVWX2PekxW/a3O97EUohv1ZqgLKqRZeMynx26J6un4/5zRjNU1SX1fGYJixOOwzAoOApZRkbS1KbwNJhR@ouRRnq3dJrko4wUORHi28U1J9IkN/2ObAHxrAhhkkA/ajI0rd@NVZL9v7BbLbqgRIyWNMZhtYHGGnjNmAiFBHW1jcvMRv@ox6RA7pokY13kpOzdN5RsrHW1/DXB6uvPmsa3/WW9uoxUGv2dTIu5qtZBNygccMYdBqK66FkMbJ9@6ihjX4iRu0Fb4oN9qSK1FFMMGERP6uN26E1Wm0NFP9l5yMNcKE/bTWqwf8CN55ejXi2sMjIsjOOfgyrVO@HWaZcv1NNwJZ/MXUT9XPIP8jXSGdUut@pvg6EL2fMXXp5NHQNE58XWbbzRkOXNiaqQ/aFZbrae2y2Quj0@PpgHIs2xVW1yI6nfw "Dart – Try It Online")
- -28 bytes by getting rid of the json.encode function and using regular string building
- -6 bytes by removing the 'new' keyword and a few spaces
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~172~~ 170 bytes
```
#define p(s)printf(#s,c)
c,s;f(){for(p({);read(0,&c,1);)s-2?c>10|s&&(s||(s+=p(\42)),c==61?s++,p(":"):p(%c)):c-34&&c-92?c==10?s=!p(\42\54):p(%c):p(\\%c);s-2||p(\42);p(});}
```
[Try it online!](https://tio.run/##dU9BbsIwELzzChPqYAsHkZRWKpbLtcc@IBfLcaglY1veiFIR3p6a0J6Ay4x2dmd2VxU7pYZh1ujWOI0CARqicV1LZsAUnSgGvCX01PpIAjlRHrVsyIrlipWUUyiqrXovVz3kOYG@J7AQgdTrilKmhHgtt7BYsECyTUY3gWBF6UYVz@s8V8VbsgpRrrYgpqOnfln/DSWs68Q85ff9NZAHcqb8PKTj0F4aRw7eNBSdUDqPo/PQRenAys54t@w0dEvnnRYf2lrP0LePtplObmaU3werj@Izpv@PDGHA1RMguUsLUoGkaxAuk2IldPbnX5IW/FUfJ@8Ea1AyaJFhDBnCCes5vtD8UiS@dRh3kNY04ssg/LBbjW2E7vhl3IFI993LHt8XI/4C "C (gcc) – Try It Online")
Based on @ErikF's implementation but without `switch/case`.
Slightly ungolfed version
```
#define p(s)printf(#s,c)
c,s;
f(){
for(p({);read(0,&c,1);)
s-2?
c>10|s&&(
s||
(s+=p(\42)),
c==61?
s++,
p(":")
:
p(%c)
)
:
c-34&&c-92?
c==10?
s=!p(\42\54)
:
p(%c)
:
p(\\%c);
s-2||p(\42);
p(});
}
```
] |
[Question]
[
# Expand a number
Your task is to expand an integer greater than 0 in the following manner:
Split the number into decimal digits and for each digit generate a list according to these rules:
* if the digit is odd, the list starts with the digit and goes down to 1;
* if the digit is even, the list starts with the digit and goes up to 9.
* if the digit is 0, the list is empty.
Write down the lists for the odd numbers below the digits, and above for the even ones. Then top-align the columns and collect the digits in each row to make integers. As a final step add up the numbers to find the expansion of the number.
Here's an example of the above rules applied to 34607:
```
9
8
79
68
57
346 7 -> 399 7 -> 3997 -> 9418
2 6 288 6 2886
1 5 177 5 1775
4 66 4 664
3 5 3 53
2 4 2 42
1 1 1
```
Here are the test cases:
```
1: 1
2: 44
3: 6
44: 429
217: 1270
911: 947
2345: 26114
20067: 3450
34875632: 70664504
9348765347634763: 18406119382875401
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answers in bytes in each language win.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Dḟ0RrḂ?€9UZḌS
```
A monadic link taking and returning positive integers.
**[Try it online!](https://tio.run/##y0rNyan8/9/l4Y75BkFFD3c02T9qWmMZGvVwR0/w////jQwMzMwB "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8/9/l4Y75BkFFD3c02T9qWmMZGvVwR0/w/6N7DrcDue7//0cb6hjpGOuYmOgYGZrrWBoCucYmpjpGBgZm5jrGJhbmpmbGRjqWIJaZqbGJuRkYxwIA "Jelly – Try It Online").
### How?
```
Dḟ0RrḂ?€9UZḌS - Link: positive integer e.g. 702
D - cast to a decimal list [7,0,2]
0 - literal zero 0
ḟ - filter discard [7,2]
9 - literal nine
€ - for each:
? - if:
Ḃ - ...condition: bit (modulo by 2) 1 ,0
R - ...then: range ([1,...n]) [1,2,3,4,5,6,7],n/a
r - ...else: inclusive range ([n,...9]) n/a ,[2,3,4,5,6,7,8,9]
U - upend [[7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2]]
Z - transpose [[7,9],[6,8],[5,7],[4,6],[3,5],[2,4],[1,3],2]
Ḍ - cast from decimal lists [79,68,57,46,35,24,13,2]
S - sum 324
```
[Answer]
# [Perl 6](https://perl6.org), ~~68~~ 66 bytes
```
{sum roundrobin(.comb».&{$_%2??($_...1)!!(9...+$_) if +$_})».join}
```
[Try it](https://tio.run/##TY7daoNAEIXv5ykmwQbF1Oyu6/pHmt72vpcFaXQDFl3Fn9IiPlnv@mJ2TAPtxTDDOd85TKu7Si1jr/FdeXkK9Sfu8qbQeFymfqyxa0ZTdM25NLaXN/X5@8vbTVZ2J04n28o8z@POZmPHdLhW5mB5QdqzQ9hbU5p5ob7HQfcDJkesSqN7ctYe@/BSuIeVezJDCusDz4Sl0FavBt1rJgW4NN0tf/@AtlWadhz2aOmPVueDLhycALHscX35Zjv//D1uf8XkT9vCvPAEOYgEpQQ/QQVS0i1iEDwkR4QMYk5MLEMQvgwSFIpzCYIxRQApDHwZhYHyqSRkSpEiIV41FfgyVNehqkgySsZ@JIiWjP8A "Perl 6 – Try It Online")
```
{sum roundrobin(.comb».&{[R,] $_%2??1..$_!!$_..9 if +$_})».join}
```
[Try it](https://tio.run/##VY7LTsMwEEX38xXTKlSJWlzbcZyXStmyRewARTRxpaDWifJAoKhfxo4fC5NSCVhYss4999q1aQ567FuDb5rlKRw/cJFXhcHNOLT9EZuqt0VT7Urrsrw67r4@2WJ4vF89o5Ndye1WMOZks5mTMRZjucelk508kl6r0p5GWrvtTNthssFDaU1LybTirp@K5Xry7myXwvT8A2kp1IcXi8tzJwXYV82lf32DrlPauu9W6Jj32uSdKTwcALEocPrwJfZSQmX7D/2prHD@A5NfNofTKBIUIBNUCvwENShFdxmDFCElMuQQC3JiFYL0VZCg1EIokJxrEohw8FUUBtqnkZBrTURBPDEd@CrU50NTkeLUjP1Ikq24@AY "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
sum
roundrobin( # grab from the sub lists in a round robin fashion
.comb\ # split the input into digits
».&{ # for each digit do this
[R,] # reduce with reversed &infix:«,» (shorter than reverse)
$_ % 2 # is the digit not divisible by 2?
?? 1 .. $_ # from 1 to the digit
!! $_ .. 9 # from the digit to 9
if +$_ # only do the above if the current digit isn't 0
# (has the effect of removing 0 from the list)
}
)».join # join each of the sub-lists from roundrobin
}
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 39 bytes
Full program body. Prompts for input from STDIN. Prints result to STDOUT.
```
+/10⊥¨0~⍨¨↓⍉↑{2|⍵:⌽⍳⍵⋄×⍵:⌽⍵,⍵↓⍳9⋄⍬}¨⍎¨⍞
```
[Try it online!](https://tio.run/##XY3PSsQwEMbvfYq562LSpOl273pefINo3SVQm2IrKP45Sf2bRRHxpDehB2/LHr2sbzIv0p1WEJrAhPl@830zushG6bnO7LzFxdvePtbPPBzHgO4DqBkdmArSo0NzrDOYZVZXZUC@6ZR8QgL0vuLE5BWcFlBZIJiaualKsDMaULI0Ng/w7nb3rNB52m7tcIYPX@uGXaNr1g3Wr@jusX65CC/RrSb49INuSR0@3vy@/5PVdoc67zKhCbrvK8q6Rfd9trS@hf79XQmEVCwOBogPZTiUYiil9Nzc25Zwf5@QkUcYU15KyHEcKeHdTjqsIiFj1dcG "APL (Dyalog Unicode) – Try It Online")
To display the last test case correctly, `⎕FR` (**F**loating-point **R**epresentation) has been set to 128-bit Decimal and `⎕PP` (**P**rint **P**recision) has been set to 34 digits.
`⍞` prompt for text input from STDIN
`⍎¨` execute each (gets each digit as a number)
`{`…`}¨` for each element, apply the following function where the argument is represented by `⍵`:
`2|⍵:` if odd (lit. "if" division remainder when divided by 2), then:
`⌽` reverse
`⍳` the **ɩ**ntegers from 1 until
`⍵` the argument
`⋄` else
`×⍵:` if the argument is positive (lit. "if" signum), then:
`⌽` reverse
`⍵` the argument
`,` followed by
`⍵` argument
`↓` elements dropped from
`⍳9` the the **ɩ**ntegers from 1 until 9
`⋄` else
`⍬` empty list
`↑` mix (combine) this list of lists into a single matrix, padding with zeros on the right
`⍉` transpose
`↓` split this matrix into a list of lists
`0~⍨¨` remove all zeros from each list
`10⊥¨` convert each from base-10 to normal numbers (this collects the digits)
`+/` sum the numbers
[Answer]
# JavaScript (ES6), ~~88~~ ~~83~~ 82 bytes
```
f=(n,k=0)=>k<9&&+[...n+''].map(x=>+x&&(x=x&1?x:9-k<x||9)>k?x-k:'').join``+f(n,k+1)
```
### Note
`9 - k < x || 9` saves a byte over `9 - k >= x && 9` but generates `1` instead of `0` if the inequality is verified. It would be a problem if it leaded to `1 > k`, triggering the wrong path in the outer ternary. But it would mean that `k = 0` and therefore `9 - k = 9`, so we can't possibly have `9 - k < x` at the same time.
### Test cases
NB: Removed the last test case which exceeds JS number precision.
```
f=(n,k=0)=>k<9&&+[...n+''].map(x=>+x&&(x=x&1?x:9-k<x||9)>k?x-k:'').join``+f(n,k+1)
console.log(f(1)) // 1
console.log(f(2)) // 44
console.log(f(3)) // 6
console.log(f(44)) // 429
console.log(f(217)) // 1270
console.log(f(911)) // 947
console.log(f(2345)) // 26114
console.log(f(20067)) // 3450
console.log(f(34875632)) // 70664504
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
```
ì f ®òZu ª9 wÃy xì
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=7CBmIK7yWnUgqjkgd8N5IHjs&input=MzQ4NzU2MzI=)
[Answer]
# Java 11, ~~210~~ ~~209~~ ~~191~~ 181 bytes
```
n->{long r=0;var a="0".repeat(9).split("");for(int d:(n+"").getBytes())for(int k=0,x=d-48,y=9;x>0&(k<1||(d%2<1?y-->x:x-->1));a[k++]+=d%2<1?y:x);for(var q:a)r+=new Long(q);return r;}
```
Ok, this took quite a while (mainly because I made a mistake at first, so had to write down each step to better understand what I did wrong). Can most likely be golfed some more.
-18 bytes thanks to *@ceilingcat*.
**Explanation:**
[Try it here.](https://tio.run/##XVJNj4IwEL37KyYku2mDEBBEoeIme3a9eDQeulANgkVLZSHqb3cLsofuodO8N52PN9Mjral1TPNnUtCqgi@a8dsIIOOSiT1NGKw7CFCU/AAJ6i@OieIeI2UqSWWWwBo4xPDk1vLWvxCxQ2oqgMaGY9iCnRmVKMR2dS4yiQwDk30pkCoCaYS4qQj7wORnK1mFMP7z5bEzbuLU8ufjNg5Js3TeUb5w73eUvk0W7kdrWcsmapR1MSZ0m5vmzowHX9S8inRtXCKKhRlz9gMr1R66YCKYvAoOgjyepBNyvn4XSsigpy6zFE5qFmgjRcYP2x1Q/BqEalEid9WPYEATDXka8n39qTvTcOj@S@X5U51wnEAP8fzA0ZmJP59NA09vI/QUG0w9fxb0ZzUsDaBTK7KaSqbJ7aP67RWD1E1bSXayy6u0VQCXBUeFaURgmNxWXwEPGR/PXw)
```
n->{ // Method with long as both parameter and return-type
long r=0; // Result-long `r`, starting at 0
var a="0".repeat(9).split(""); // String array `a`, filled with nine String zeroes
for(int d:(n+"").getBytes()) // Cast the input to a String,
// and loop over its codepoints as integers:
for(int k=0, // Row-index `k`, starting at
x=d-48, // Temp integer `x`, set to the current digit
y=9 // Temp integer `y`, set to 9
; // Inner loop, if:
x>0 // The current digit is not a 0,
&(k<1 // and if this is the first iteration,
||(d%2<1? // or if the digit is even:
y-->x // And `y` is larger than the digit
// (and afterwards decrease `y` by 1 with `y--`)
: // or if the digit is odd:
x-->1)); // And `x` is larger than 1
// (and afterwards decrease `x` by 1 with `x--`)
a[k++]+= // Append the current row with:
// (and afterwards increase `k` by 1 with `k++`)
d%2<1? // If the digit is even:
y // Append the row with `y`
: // Else (the digit is odd):
x); // Append the row with `x`
for(var q:a) // Loop over the String rows in the array:
r+=new Long(q); // Convert it to a long, and add it to the result-sum
return r;} // Return the result
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 28 bytes
```
J_MS(RV{a?a%2?\,aa,tl}Ma)ZDx
```
[Try it online!](https://tio.run/##K8gs@P/fK943WCMorDrRPlHVyD5GJzFRpySn1jdRM8ql4v///8YmZgbmAA "Pip – Try It Online")
### Explanation
```
Ma Map this function to the digits of the 1st cmdline arg:
a? If digit != 0:
a%2? If digit is odd:
\,a Inclusive-range(digit)
a,t Else (digit is even), range from digit to 10 (exclusive)
l Else (digit is 0), empty list
RV{ } Apply reverse to the result before returning it
This gives us a list of lists like [9 8 7 6] or [3 2 1]
( )ZDx Zip, with a default value of empty string
J_MS Use map-sum to join each sublist and sum the results
Autoprint (implicit)
```
How the steps proceed with `34607` as the argument:
```
34607
[[1 2 3] [4 5 6 7 8 9] [6 7 8 9] [] [1 2 3 4 5 6 7]]
[[3 2 1] [9 8 7 6 5 4] [9 8 7 6] [] [7 6 5 4 3 2 1]]
[[3 9 9 "" 7] [2 8 8 "" 6] [1 7 7 "" 5] ["" 6 6 "" 4] ["" 5 "" "" 3] ["" 4 "" "" 2] ["" "" "" "" 1]]
[3997 2886 1775 664 53 42 1]
9418
```
[Answer]
# Pyth - 23 bytes
```
siRT.Tm*!!d@,}9d}d1dsMz
```
[Test Suite](http://pyth.herokuapp.com/?code=siRT.Tm%2a%21%21d%40%2C%7D9d%7Dd1dsMz&test_suite=1&test_suite_input=1%0A2%0A3%0A44%0A217%0A911%0A2345%0A20067%0A34875632%0A9348765347634763&debug=0).
[Answer]
# [Haskell](https://www.haskell.org/), ~~106~~ 104 bytes
```
import Data.List
f n=sum$map read$transpose$[reverse$[[c..'9'],['1'..c]]!!mod(read[c])2|c<-show n,c>'0']
```
[Try it online!](https://tio.run/##XY3NasMwEITv@xQbCDgBWehnLVmi6anH9gmMD8JxiEn8g@y2h7bP7sqBXnpYmJ3d@eYa5lt7v69r109jXPAlLIG/dvMCFxxO83u/78OEsQ3n/RLDME/j3O6r2H60cRNVw3nmsppVmcw4b@p6t@vH82ELVE19VN/NUz5fx08cWPOciaxe@9ANeMKEfcPDFLthQY6XI1aSKaYZEVPSMifTqqlgSghjmabSFkYr5jZlCk3WPKaGrxykRwnKIxFojwaIklYOEihdlBWQcB4dWdiYHpWRkuCB9pgcAX8FHq0wJjkE/6sSqiSRkk6XKn2TkJD/rL8 "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~153~~ 146 bytes
```
function(n,m=n%/%10^(nchar(n):0)%%10)sum(strtoi(apply(sapply(m[m>0],function(x)c(r<-"if"(x%%2,x:1,9:x),rep("",9-sum(r|1)))),1,paste,collapse="")))
```
[Try it online!](https://tio.run/##PYzRCsIgFEB/JQThXrgjrSg2tn4kCkQmCepEHRj077YIOi8HzsNJzezGrpk16GKXAIH8FPieS/GAoJ8qQcBBIN8C5tVDLqksFlSM7gX5J3/zV3Gn/6OihjR2zBoGlfMD1UFSP1SkNEdgjPruu0pviRskKapcZtKLcyrmeWJsy83A8XQWF2wf "R – Try It Online")
~~Sometimes, I can't tell if I'm just garbage at golfing, or if R is....~~ It's definitely me, saved 7 bytes thanks to user2390246, who reminded me of another way to extract digits (that I suggested myself).
You may replace `strtoi` with `as.double` to get `18406718084351604` for the last test case (which is wrong); R only has 32-bit integers.
[Answer]
# [Perl 5](https://www.perl.org/), 120 + 1 (`-a`) = 121 bytes
```
$p=y/01357/ /r;$n=y/02468/ /r;map{$p=~s/9/ /g;$p=~s/\d/$&+1/ge;$n=~s/\d/$&-1/ge;$n=~s/0/ /g;@F=($p,@F,$n)}0..7;say for@F
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lwLZS38DQ2NRcX0G/yFolD8Q1MjGzAHNzEwuqgSrqivUtgfx0awg7JkVfRU3bUD89FaQeJqCLJGAAVu3gZquhUqDj4KajkqdZa6CnZ25dnFipkJZf5OD2/7@hkbGJqZm5haXBv/yCksz8vOL/ur6megaGBv91EwE "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 131 bytes
```
lambda n:sum(int(''.join(`n`for n in l if n))for l in map(None,*[range(n and(n%2*n or 9),(n%2<1)*~-n,-1)for n in map(int,`n*10`)]))
```
[Try it online!](https://tio.run/##PY3BDoIwDIbve4peDCsphrEBYtRH8AXUhBlEZ6AQ1IMXXx03Dx7atN//9@/4ft4GzuZ2e5w7258bC7x@vHrp@CmjaHkfHMua63aYgMExdOBaYMQAugB6O8r9wBeKD5Pl60UyWG4kL7KYwZsqpLBsFMafhClR@M8Kp/4P1RyrtMYT4hw057WDIpGR0CSM8ZMqSVQqMG1y39O08ESbVZkX2vuqMBa5NmXxK3FaCxgnHw6OIEp2EUErHc5f "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0KεDÈi9ŸëL]íõζJO
```
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//zBLzrVEw4hpOcW4w6tMXcOtw7XOtkpP//8zNDYwNw) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/A@9zW10Od2RaHt1xeLVPbe3htYe3ntvm5f9f53@0oY6RjrGOiYmOkaG5jqUhkGtsYqpjZGBgZq5jbGJhbmpmbKRjCWKZmRqbmJuBcSwA).
Or alternatively:
```
0KεDÈ8*>Ÿ{R}õζJO
0Kε9Ÿ¬L‚yèR}õζJO
```
**Explanation:**
```
0K # Remove all 0s from the (implicit) input-integer
ε # Map each digit to:
D # Duplicate the digit
Èi # If it's even:
9Ÿ # Pop and push a list in the range [digit, 9]
ë # Else (the digit is odd):
L # Pop and push a list in the range [1, digit]
] # Close both the if-else statement and map
í # Reverse each inner ranged list
ζ # Zip/transpose, swapping rows and columns,
õ # with an empty string as filler
J # Join each inner list together
O # And sum that list
# (after which the result is output implicitly)
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 39 bytes
```
riXX:nz{J2dv{{9r@}{ro}}che!<-}m[tp)im++
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KDMiwiqvqtrLKKWsutqyyKG2uii/tjY5I1XRRrc2N7qkQDMzV1v7/39jEzMDcwA "Burlesque – Try It Online")
```
ri #Read as int
XX #Return list of digits
:nz #Filter for non-zero
{
J2dv #Divisible by 2?
{
{9r@} #Range a, 9
{ro} #Range 1, a
}che! #Run based on if divisible
<- #Reverse the range
}m[ #Apply to each digit
tp #Transpose digits
)im #Join each list into single int
++ #Sum each int
```
] |
[Question]
[
In this challenge you'll be using be [distributing](https://en.wikipedia.org/wiki/Distributive_property) a product over sums and differences of numbers, as explained [here](http://www.coolmath.com/prealgebra/06-properties/05-properties-distributive-01).
[](https://i.stack.imgur.com/S6gRB.png)
## Examples
```
Input | Output
-------------|-------------
23(12+42) | (23*12)+(23*42)
9(62-5) | (9*62)-(9*5)
4(17+8-14) | (4*17)+(4*8)-(4*14)
15(-5) | -(15*5)
2(3) | (2*3)
8(+18) | +(8*18)
8(-40+18) | -(8*40)+(8*18)
```
## Specification
The input will be a string of the form `n(_)`, with a single positive unsigned integer `n` followed by a parenthesized expression `_`. This expression `_` will consist of sums and difference of one of more positive-integer terms separated by `+` and `-` signs. The first term may be preceded by a `+` sign, a `-` sign, or by no sign.
In the output, the initial number `n` should be distributed to multiply each of the terms. Each term of `a` should be left-multiplied by `n` to produce the parenthesized expression `(n*a)`, and these new terms should be combined with `+` and `-` signs in exactly the same way as the original terms were.
## Invalid Inputs
These are examples of inputs you don't have to handle.
```
3(5 plus 3)
6(5 13)
(5+8)(6+6)
(5+3)8
```
## Winning
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
[Answer]
# JavaScript 65 bytes
```
s=>(q=s.split(/[()]/))[1].replace(/(\D?)(\d+)/g,`$1(${q[0]}*$2)`)
```
This will take the input. Get the + or -, then the digits, then replace it in the correct order.
## Explanation
```
s=> // Function with argument "s"
(q= // Set q to...
s.split(/[()]/) // Splits on parenthesis, returns array
)
[1] // Gets second match or text inside brackets
.replace(/ // Replaces string
(\D?) // Try to match a non-digit, the +-/* (group 1)
(\d+) // Then match one or more digits (group 2)
/,
// $1 is group 1 and $2 is group 2 q[0] is the text before the parenthesis
`$1(${q[0]}*$2)`
)
```
## Usage
This only works in Firefox and Safari Nightly *maybe Edge?* because it uses ES6 features. You can run it by:
```
**var t=**s=>(q=s.split(/[()]/))[1].replace(/(\D?)(\d+)/g,`$1(${q[0]}*$2)`)
**t(**"5(-6+7+3-8+9)"**);** // -(5*6)+(5*7)+(5*3)-(5*8)+(5*9)
```
[Answer]
## Python 2.7, ~~110~~ 108 Bytes
```
import re
p=re.findall('([+-]?)(\d+)',raw_input())
print"".join("%s(%s*%s)"%(e[0],p[0][1],e[1])for e in p[1:])
```
The program takes input from stdin, searches for matches against - `([+-]?)(\d+)` regex and creates the output string.
Testing it -
```
<< 23(12+42)
>> (23*12)+(23*42)
<< 9(62-5)
>> (9*62)-(9*5)
<< 4(17+8-14)
>> (4*17)+(4*8)-(4*14)
<< 15(-5)
>> -(15*5)
<< 2(3)
>> (2*3)
<< 8(+18)
>> +(8*18)
<< 8(-40+18)
>> -(8*40)+(8*18)
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 40 bytes
```
+`(\d+)\((\D)?(\d+)
$2($1*$3)$1(
\d+..$
<empty line>
```
Each line should go to its own file but you can run the code as one file with the `-s` flag. E.g.:
```
>echo -n "8(-40+18)"|retina -s distributing_numbers
-(8*40)+(8*18)
```
The first two lines push the multiplier next to every number in the expected form:
```
8(-40+18)
-(8*40)8(+18)
-(8*40)+(8*18)8()
```
The last two lines remove the unnecessary trailing part:
```
-(8*40)+(8*18)8()
-(8*40)+(8*18)
```
[Answer]
# sed, 105 bytes
Just wanted to see if this can be done with sed.
Maybe a bit old school, but it works.
```
$ cat distnum.sed
s@\([0-9]*\)(\([0-9]*\)\([+-]*\)\([0-9]*\)\([+-]*\)\([0-9]*\))@(\1*\2)\3(\1*\4)\5(\1*\6)@
s@([0-9]*\*)@@g
$ cat distnum.txt
23(12+42)
9(62-5)
4(17+8-14)
15(-5)
2(3)
8(+18)
8(-40+18)
$ sed -f distnum.sed distnum.txt
(23*12)+(23*42)
(9*62)-(9*5)
(4*17)+(4*8)-(4*14)
-(15*5)
(2*3)
+(8*18)
-(8*40)+(8*18)
```
[Answer]
# Pip, 28 bytes
```
DQaUnxWa^'(xR`\d+`'(.n.`*&)`
```
Explanation:
```
a is first cmdline arg (implicit)
DQa Remove (DeQueue) the closing paren from a
UnxWa^'( Unify n and x with a split on open paren--Python equivalent
n,x=a.split("(")
n is thus the number to be distributed, and x is the
addition/subtraction expression
xR In x, replace...
`\d+` ... regex matching numbers...
'(.n.`*&)` ... with the replacement pattern (n*&), where n is the
appropriate number and & substitutes the complete match
Print result (implicit)
```
Pip's Pattern objects mostly follow Python regex syntax, but the `&` replacement pattern is borrowed from sed.
Read more about Pip at the [Github repository](https://github.com/dloscutoff/pip)
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 77 bytes
```
$$d=(?<!\))([+-]?)(\d+)
+$d\($d([+-])/\3(\1\2*\4)\5\1\2(
$d\($d\)/\3(\1\2*\4)
```
[Live demo and all test cases.](http://kirbyfan64.github.io/rs/index.html?script=%24%24d%3D%28%3F%3C!%5C%29%29%28%5B%2B-%5D%3F%29%28%5Cd%2B%29%0A%2B%24d%5C%28%24d%28%5B%2B-%5D%29%2F%5C3%28%5C1%5C2*%5C4%29%5C5%5C1%5C2%28%0A%24d%5C%28%24d%5C%29%2F%5C3%28%5C1%5C2*%5C4%29&input=5%282%2B8%29%0A23%2812%2B42%29%0A9%2862-5%29%0A4%2817%2B8-14%29%0A15%28-5%29%0A2%283%29%0A8%28%2B18%29%0A8%28-40%2B18%29)
This is the first time rs's macros have actually been used!
[Answer]
# [REGXY](http://esolangs.org/wiki/REGXY), 45 bytes
Uses REGXY, a regex substitution based language.
```
/(\d+)\((\D)?(\d+)/\2(\1*\3)\1(/
//
/\d+\(.//
```
[Answer]
# Perl, 36 bytes
35 bytes code + 1 byte command line
```
($a,$_)=split/[()]/;s/\d+/($a*$&)/g
```
Usage:
```
echo "4(17+8-14)" | perl -p entry.pl
```
[Answer]
# Pyth, 39 38 bytes
A terrible regex solution:
```
P:eJcz\("([+-]?)(\d+)"X"\\1(_*\\2)"3hJ
```
[Answer]
# Ruby, 94 bytes
```
gets.scan(/(\d+)\(([[-+]?\d+]+)/){|a,b|b.scan(/([-+]?)(\d+)/).map{|c,d|$><<"#{c}(#{a}*#{d})"}}
```
[Answer]
# CJam, 50 bytes
```
l__'(#_@<'*+@@)>);'+/'-f/\ff{1$'(@@++')+L?}'-f*'+*
```
[Try it online](http://cjam.aditsu.net/#code=l__'(%23_%40%3C'*%2B%40%40)%3E)%3B'%2B%2F'-f%2F%5Cff%7B1%24'(%40%40%2B%2B')%2BL%3F%7D'-f*'%2B*&input=8(-40%2B18))
CJam does not have regex support, or anything beyond string searching and splitting that is very convenient for parsing expressions. So there's some labor involved here.
Explanation:
```
l__ Get input and push 2 copies for splitting.
'(# Find index of '(.
_ Copy index, will be used twice.
@< Get one copy of input to top, and slice to get first multiplier.
'*+ Append '* to first multiplier.
@@ Get another copy of input and '( index to top.
)> Increment and slice to get everything after '(.
); Remove trailing ').
'+/ Split at '+.
'-f/ Split each part at '-.
\ Swap first multiplier to top.
ff{ Apply block to nested list of second multipliers.
1$ Copy term. Will use this copy as condition to skip empty second multipliers
that result from unary + or -.
'( Opening parentheses.
@@ Get first and second multiplier to top.
++ Concatenate it all.
')+ Concatenate closing parentheses.
L Push empty string for case where term is skipped.
? Ternary if to pick term or empty string.
} End of loop over list of second multipliers.
'-f* Join sub-lists with '-.
'+* Join list with '+.
```
[Answer]
# gawk - 60 58
```
$0=gensub(/(.*\()?(+|-)?([0-9]+))?/,"\\2("$0+0"*\\3)","G")
```
Phew... haven't worked with regexp in quite a while.
[Answer]
# Perl 5, ~~70~~ ~~60~~ ~~55~~ 44 Bytes + 1 penalty
A perl solution that only uses split and 1 regular expression.
Also calculates the longer inputs.
```
($a,$_)=split/[()]/;s/(\D?)(\d+)/$1($a*$2)/g
```
### Test
```
$ echo "8(9-10+11-12+13-14)"|perl -p distnums.pl
(8*9)-(8*10)+(8*11)-(8*12)+(8*13)-(8*14)
```
### A version that takes a parameter
```
($a,$_)=split/[()]/,pop;s/(\D?)(\d+)/$1($a*$2)/g;print
```
# A version that only uses regular expressions.
```
s/(\d+)\((.*)\)/$2:$1/;s/(\D?)(\d+)(?=.*:(\d+)).*?/$1($3*$2)/g;s/:.*//
```
This one works via a capture group within a positive lookahead and lazy matching. Probably would have used a positive lookbehind if Perl 5 supported it, but alas. Took me a while to figure out that this kinda thing is possible with regex.
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~50~~ ~~51~~ 43 bytes
I think this *may* be my first Retina program. If not, it's my first Retina program that's this complex (not that complex, really.) Each line goes in its own file.
```
+`(\d+)\((\D?)(\d+)
$1($'$2($1*$3)
.+?\)
$'
```
I didn't actually test this with Retina, I tested it using a regex-replace tester multiple times, but it should work.
### Description for first example:
Since there are an even number of files, Retina uses replace mode. The first replace (first two files) removes a number to be distributed and adds that distribution pair `(23*12)` to the end, giving `23(+42)(23*12)`. `+`` at the start tells Retina to repeatedly replace until the pattern doesn't match, and since this is matched again, the pattern replaces this with `23()(23*12)+(23*42)`. This doesn't match anymore, so the next 2 files are used for the next replace. This time, it merely removes the `23()`. This works nicely: since products are appended to the end, I don't have to do anything weird if a number doesn't have a sign, since the only one that can be without a sign is the first number.
EDIT: `$'` in replacement represents the rest of the string after the match, so I can removing the trailing `(.*)`s.
[Answer]
# k, 98 bytes
Not very golfed.
```
{,/(*x){(s#y),("*"/:(x;(s:(*y)in"+-")_y))/:$"()"}/:1_x@:&~~#:'x:((0,&~x in .Q.n)_x){x_'x?'y}/"()"}
```
Split on non-digit, remove parens, remove empty strings, then holding `x` constant as the first string, combine with `*` with each remaining string `y`, parenthesize, and move sign to the beginning if present; flatten output into a single string.
] |
[Question]
[
We've had [powerful numbers](https://codegolf.stackexchange.com/q/263438/66833), yes, but what about [*highly* powerful numbers](https://en.wikipedia.org/wiki/Highly_powerful_number)?
### Highly powerful numbers
Let \$n\$ be a positive integer in the form
$$n = p\_1^{e\_{p\_1}(n)}p\_2^{e\_{p\_2}(n)}\cdots p\_k^{e\_{p\_k}(n)}$$
for distinct, increasing primes \$p\_1, p\_2, ..., p\_k\$ and, where \$e\_{p\_i}(n)\$ is a positive integer for all \$i = 1, 2, ..., k\$. Note that we don't include zero exponents here.
Now, for such an \$n\$, define
$$\operatorname{prodexp}(n) = \begin{cases}
1, & n = 1 \\
\prod^k\_{i=1} e\_{p\_i}(n), & n > 1\end{cases}$$
Such an \$n\$ is said to be *highly powerful* if, for all \$1 \le m < n\$, \$\operatorname{prodexp}(m) < \operatorname{prodexp}(n)\$.
For example, \$n = 8\$ is a highly powerful number as we have \$\operatorname{prodexp}(n) = 3\$ and
| \$m\$ | \$\operatorname{prodexp}(m)\$ |
| --- | --- |
| \$1\$ | \$1\$ |
| \$2\$ | \$1\$ |
| \$3\$ | \$1\$ |
| \$4\$ | \$2\$ |
| \$5\$ | \$1\$ |
| \$6\$ | \$1\$ |
| \$7\$ | \$1\$ |
All of which are strictly less than \$3 = \operatorname{prodexp}(8)\$. Whereas \$n = 7\$ is not highly powerful as \$\operatorname{prodexp}(7) = 1 < 2 = \operatorname{prodexp}(4)\$.
The first few highly powerful numbers are
```
1, 4, 8, 16, 32, 64, 128, 144, 216, 288, 432, 864, 1296, 1728, 2592
```
This is [A005934](https://oeis.org/A005934) on OEIS.
---
This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. You may choose whether to
* Take a positive integer \$n\$ and output the \$n\$th highly powerful number (you may choose between 0 and 1 indexing)
* Take a positive integer \$n\$ and output the first \$n\$ highly powerful numbers
* Output all highly powerful numbers indefinitely
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest answer in bytes in each language wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
1ÆEP$ÐṀḢ=Ɗ#
```
[Try it online!](https://tio.run/##y0rNyan8/9/wcJtrgMrhCQ93Njzcscj2WJcyUMwQAA "Jelly – Try It Online")
Prints the first n numbers. -1 thanks to Jonathan Allan.
Brownie points acquired.
```
1 # Starting from 1
# # Find the first n integers where...
--------Ɗ # Last three elements as a monad
= # Where the number equals
·∏¢ # The first of
ÐṀ # The indicies of maximal elements by...
---$ # Last two elements as a monad...
P # Product of
ÆE # Exponents of prime factorisation of the number.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
ɾ‡∆ǐΠ∴=)ȯ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLJvuKAoeKIhseQzqDiiLQ9KcivIiwiIiwiMTAiXQ==) Outputs the first n highly powerful integers. -1 thanks to lyxal.
```
ȯ # First n positive integers
-------) # Where...
∴ # Maximum of...
…æ # Range from 1 to n
‡--- # By...
Π # Product of
∆ǐ # Prime exponents
= # Is equal to the number?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ ~~12~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
‚àû íDL√ìPZk-
```
Outputs the infinite sequence.
-3 bytes thanks to *@JonathanAllan*.
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8U5NcfA5PDojK1v3/HwA)
**Explanation:**
```
‚àû # Push an infinite list of positive integers: [1,2,3,...]
í # Filter it by:
D # Duplicate the current value
L # Pop one, and push a list in the range [1,value]
Ó # Get the exponents of each inner integer's prime factorizations
# (which will include 0s, but this doesn't matter for the results)
P # Get the product of each inner list
Z # Push the maximum (without popping the list)
k # Pop the maximum and list, and push the first (0-based) index of this max
- # Subtract this 0-based index from the duplicated current value
# (only 1 is truthy in 05AB1E)
# (after which the filtered infinite list is output implicitly as result)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 60 bytes
```
p=n=0;while(1,if(p<q=vecprod(factor(n++)[,2]),p=q;print(n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN20KbPNsDazLMzJzUjUMdTLTNApsCm3LUpMLivJTNNISk0vyizTytLU1o3WMYjV1CmwLrQuKMvNKNPI0NTUhZkCNghkJAA)
Outputs all highly powerful numbers indefinitely.
---
## 57 bytes but would stack overflow
```
f(p,n)=f(if(p<q=vecprod(factor(n++)[,2]),print(n);q,p),n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNy3TNAp08jRt0zQygSybQtuy1OSCovwUjbTE5JL8Io08bW3NaB2jWE2dgqLMvBKNPE3rQp0CTaAWiAGL0zSgLJiRAA)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 9 bytes
```
Ňᵖ{Rƒᵐ∏Ɔ<
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FpuOtj_cOq066Nikh1snPOroP9Zms6Q4Kbl4WW2ioVFIHUQRTDEA)
```
Ňᵖ{Rƒᵐ∏Ɔ<
Ň Any natural number
ᵖ{ Check that:
R Range from 1 to the number
ƒ Factor each number
ᵐ Map:
‚àè Take the product of exponents
Ɔ< Check that the last result is the largest
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes
```
NθW‹Lυθ«→≔ⅈη≔¹ζ≔¹εW⊖η«≦⊕ε≔⌕⮌X⁰↨ηε⁰δ≧÷Xεδη¿δ≧×δζ»¿⬤υ›ζκ⊞υζ»Iⅈ
```
[Try it online!](https://tio.run/##XZDBTsMwEETPyVfscS0ZKb3SU6EqqkRRVHHgapIltkic1nZSqajfHtapqYCDLc36zXjsSitX9aqdpq09DOFl6N7J4VEs85M2LQE@k/e82SZoHISEoxDwlWe7fiS835tGB2azlfemsfiGTOhfg4WE819JUabsNVWOOrKBatTX3GynDgne2ttpsv3EbIytcU8jOU9Y9iduXEh4UKx0RAW3KHjVs@mWOLfl2LA2o6lJwtVKEUy1M/MBWAv453k1HXnG0msu@cyt2hYHCU@OVOCcs4RPvhrKwes4j@glL52xAR@VD/F3hFhO06KY7sb2Gw "Charcoal – Try It Online") Link is to verbose version of code. Eventually outputs the 1-indexed `n`th highly powerful number (avoid `n>15` on TIO). Explanation:
```
Nθ
```
Input `n`.
```
W‹Lυθ«
```
Repeat until `n` record prime factorisation exponent product records have been found.
```
→≔ⅈη≔¹ζ≔¹ε
```
Increment the trial number and start to factorise it.
```
W⊖η«
```
Repeat until the trial number has been factorised.
```
≦⊕ε
```
Try the next potential factor.
```
≔⌕⮌X⁰↨ηε⁰δ
```
Find its multiplicity.
```
≧÷Xεδη
```
Divide the trial number by the prime power.
```
¿δ≧×δζ
```
Multiply the exponent product by the current exponent, if any.
```
»¿⬤υ›ζκ⊞υζ
```
If this is a record exponent product then save it.
```
»Iⅈ
```
Output the number with the `n`th record exponent product.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 70 bytes
Output all highly powerful numbers indefinitely, as suggested by **[@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)**.
```
for(x=p=0n;;p<s&&(p=s,console.log(x)))for(d=s=++x;d;)x%d+d--**x%x&&--s
```
[Try it online!](https://tio.run/##FcpRCoAgDADQ0yQuW/RvO4w0iyKcuIjd3uh9vyu9Sbd21geLcO59l@aNKi0lxrqqc76STpsUlTvPtxzeAOBfTEohWOQINnBgxHG0wZxD1N4/ "JavaScript (Node.js) – Try It Online")
## [JavaScript (Node.js)](https://nodejs.org), 72 bytes
Takes a positive integer \$ n \$ and returns the \$ n \$-th highly powerful number (1-indexed).
```
n=>eval('for(x=p=0n;n;p<s&&(p=s,n--))for(d=s=++x;d;x%d+d--**x%x&&--s)x')
```
[Try it online!](https://tio.run/##FYpBCsMgEADvfYWHxLixlvRstm@JRC0tskoMQQh5u7WnGZj5msPkdfukXVG0rnqshC93mCAGHzdRMOFEmnSaM@ciYb6TUgD/ZjGjlEVbXXorrVLjWPrCuVIZygC1PUwEtzNiyJ66YW6cmkgJN8bWSDkG9wjxLRYjupMuaGd3ekFwLaDrDw "JavaScript (Node.js) – Try It Online")
[Answer]
# Python3, 234 bytes
```
R=range
def P(n):
d=[]
while n>1:
for i in R(2,n+1):
if(i<3or all(i%j for j in R(2,i)))and 0==n%i:n//=i;d+=[i]
r=1
for i in{*d}:r*=d.count(i)
return r
def f():
n=0
while(n:=n+1):
if all(P(m)<P(n)for m in R(1,n)):print(n)
```
[Try it online!](https://tio.run/##PY9LDoJADED3nKIbkqkSAd2YkXoG45a4IA4jNVjIBGKM8ew4g59t@/L62j@GppPNtnfTdCRXyaWOTG3hoAR1BIbKUwT3htsaZJ/7CdjOAQMLHNU6kWUeMAC2iouNX1Vtqzi@ztj1hzEiVmIgI5KYtaQp8c4sqWRvd5RHf@tzYV7aLciszt0og2L0QD2MTsDNYVaFg0LZN0uJpl8F2/n8Qd2wCA8E6e3TkCeCqHvH3ik4ecv0Bg)
Prints the sequence indefinitely.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
.fqh.M*FhMr8PZS
```
[Try it online!](https://tio.run/##K6gsyfj/Xy@tMEPPV8stw7fIIiAq@P9/QwMA "Pyth – Try It Online")
Outputs the first \$n\$ terms in the sequence.
### Explanation
```
.fqh.M*FhMr8PZSZZQ # implicitly add ZZQ
# implicitly assign Q = eval(input())
.f Q # Take the first Q items which are truthy over lambda Z
SZ # range(1,Z+1)
.M # filter this for elements which maximize lambda Z
PZ # prime factors of Z
r8 # length encode
hM # take just the lengths
*F # reduce over multiplication
h # first element
q Z # is equal to Z
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 17 bytes
```
⟨┅⟨ḋ_v2%Π⟩¦ṅ¤⌉>⟩#
```
[Try it online!](https://tio.run/##S0/MTPz//9H8FY@mtALJhzu648uMVM8teDR/5aFlD3e2HlryqKfTDshT/v/f0AAA "Gaia – Try It Online")
Returns the first (1-indexed) `n` all-high-powerful numbers.
There's a quirk with numeric mode `ḋ` where it returns a list `[prime,exponent]` for `n<4` and for `n>3` it returns a list `[[prime1,exponent1],...]`. I suppose that's what I get for golfing in a language that hasn't been updated in 6 years.
```
; implicit input, n
‚ü® ‚ü©# ; find the first n positive integers where the following is truthy:
ṅ¤⌉> ; is the last element of the following list the unique maximum?
; (literally, is the last element greater than the max of the remaining elements)
ḋ_v2%Π ; the product of the exponents in the prime factorization
┅⟨ ⟩¦ ; for each integer in the range 1..i (where i is the positive integer we're on now)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 75 bytes
Prints infinitely.
```
p m=e=1
2.step{|x|d=x.prime_division.reduce(1){_1*_2[1]};m,e=p(x),d if d>e}
```
[Attempt This Online! (50ms timeout)](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7E3totTC0syiVAX1EqBAfmmJOlcIhGFlBRXRMNAzMNVUSMlfWlqSpmtx07tAIdc21daQy0ivuCS1oLqmoibFtkIPbGJ8SmZZZnFmfp5eUWpKaXKqhqFmdbyhVrxRtGFsrXWuTqptgUaFpk6KQmaaQopdai3EyMWpeSkQ1oIFEBoA)
```
# -rprime imports Prime as a command line flag
p m=e=1 # Print 1 while also setting m (current most powerful)
# and e (current highest exponent product)
2.step{|x| # Count up infinitely starting from 2, store as x
x.prime_division # Get prime factors of x
.reduce(1){_1*_2[1]} # Multiply the exponent component of each factor together
d= # Set that value as d
m,e=p(x),d if d>e # if d > e, print x, set m to x, and set e to d
} # End loop structure
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 72 bytes
[Try it online!](https://tio.run/##BcG9CoAgEADgB1LoZ1XBKRAaGoIGcTjiSiEvtXt/@74MHDEDpxN6L4bMqI6YHvSTniUJoarZU8bP2hU@HuwCJ7/NEeONzVNQ7vJFV1lMVVtLxJZC6P0H)
```
p=n=0;While[1<2,n++;q=Times@@Last/@FactorInteger[n];If[p<q,p=q;Print@n]]
```
] |
[Question]
[
In this challenge, given a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) file as a string, you'll return the data contained as a 2d array of strings.
**Spec:**
* The input consists of one or more **records**, delimited with `\r\n` (CRLF), `\n` (line feed), or some other reasonable newline sequence of your choice
* A record consists of one or more **fields**, delimited with `,` (commas), `;` (semicolons), `\t` (tabs), or some other reasonable delimiter of your choice. You may assume each record contains the same number of fields
* A field can either be quoted or un-quoted. An un-quoted field will not contain a field delimiter, newline sequence, or quote character, but may otherwise be an arbitrary non-empty string (within reason; you can assume things like invalid UTF-8, null characters, or unpaired surrogates won't appear if doing so is justifiable)
* A quoted string will be delimited on both sides by a quote character, which will be `"` (double quotes), `'` (single quotes), ``` (backticks), or some other reasonable delimiter of your choice. This character will be escaped within the string by being repeated twice (the string unquoted `a"bc` would be represented as `"a""bc"`). Quoted strings may contain field delimiters, newline sequences, escaped quote characters, and any other sequences of characters which may appear in an unquoted field. Quoted strings will always be non-empty
* You may choose to ignore the first record (as if it is a header record)
**Output:**
You may represent a 2d array in any reasonable format (excluding CSV or any of it's variants for obvious reasons).
**Scoring:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) per language wins.
**Test cases:**
In:
```
1,2
abc,xyz
```
Out:
```
[["1","2"],["abc","xyz"]]
```
In:
```
"abc",xyz
"a""bc",""""
",",";"
"
"," "
```
Out:
```
[["abc","xyz"],["a\"bc","\""],[",",";"],["\n"," "]]
```
In:
```
"\
,"""
```
Out:
```
[["\\\n,\""]]
```
$$$$$$$$
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 113 bytes
```
s=>s.match(/"([^"]|"")*"|\n|[^,\n]+/g).map(v=>v<' '?t.push(r=[]):r.push(v.replace(/^"|"("?)/g,'$1')),t=[r=[]])&&t
```
[Try it online!](https://tio.run/##ZZHBUsMgEIbvPAWz4zRgkUw9tqY9OB70oAePIR0xYo2TkgzQWLU@e10SnXaUyy777/cDy6vutC9d1YYz2zyZfaudN5e@o9neZ3Mv1zqULywFli@h2AHwU9gpu8uXQtlinK44drSsy@bdRUKTRZDtxr8wl@UFn7ph00ln2lqXhqVL2AGDBU9XIjmZJJyLkOWxueCjUdgH4wPN6H1wlV1Jp98eyLWdEjIR50Q/lmL7/kHI3SZgKc9hAgLOoRA5oIY5qlAUZECGWgRAA/Q6LoJBwAxjzCgcuR15REc1MAr67UDFTNkePJyjSHQ@MlJKWRG5w1UI3gBEeXyasirWoIx9DxJfvGZc@rauAo4JuZN0zeVzVQfj2JZmc7odRj3kf4FoHAlEGnel8ctYXglqCh7bPwnF1eBof7@XVT8OvJcMSjf3d7ey15kZqmVjfVMbWTcrxnrZ9z9TPb@zBo1/mEPRcE7HNJnSBMM/gM/IF5/tvwE "JavaScript (Node.js) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 15 bytes
```
ConvertFrom-Csv
```
[Try it online!](https://tio.run/##bY5Ba8JAEIXv8yuGIWCCu4ekxxKIhHropQcDvQiyWRZUoiu7W1ut/vY4Gy1W8F3msXzv7dvZb@P80nRdnwTjg1beeCyxSqEaQVPni9p2ubiZAnJRgGq1@DkcYVTBFSr@oOIKERM0IKSIoicW8BH0yjc6pHv@ZcgDzSGC8T0DSILmHTn8m3XCqXVvSi/lR7s2OuCvSJMFnvrabvfGhamzG1n7fZ@dn7CALCqjsOFOjKWYpCn/NB5nGZaPoiEQ@2PVRgXZqLYzKCdfwc5WR3afTu3u1G1FY@W7t1s49xc "PowerShell – Try It Online")
Finally something where a rather verbose language like PowerShell can make use of a built-in function.
`ConvertFrom-Csv` covers all the tricky cases.
The test cases in the TIO have an added header record, based on "*You may choose to ignore the first record (as if it is a header record)*"
Output in the TIO both as a table and JSON to show that the input was correctly parsed.
[Answer]
# [Factor](https://factorcode.org/) + `csv`, 10 bytes
```
string>csv
```
[Try it online!](https://tio.run/##dY4xC8IwEIX3@xXH4VgEHVt00aIuCoqTOsQQSyCtMbmKVfztMVEnwbe8x33v4J2E5LML281iOcuxbg1roxuF1inmzjrdMBrNygnjUforenVpVSOVxwKg94B5uS6nq0mOoyQYZEMQR5ndujt8Lr8NipjenARRyhQF0TIqoqeE9O95D6n@pU/cQfAcR1bjuC0csBYW@@EF "Factor – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 48 bytes
```
mM!`"([^"]|"")*"|[^,¶]+|$
"(([^"]|"")*)"
$1
""
"
```
[Try it online!](https://tio.run/##K0otycxL/P8/11cxQUkjOk4ptkZJSVNLqSY6TufQtljtGhUuJQ2EuKYSl4ohl5ISl9L//0qJSclKOhWVVVxKiUpKILaSEkhGBwitgTSIpQAkE4Hqk5R0kgE "Retina 0.8.2 – Try It Online") Retina doesn't have an array type, so I'm just listing each string on its own line with records double-spaced from each other. Explanation:
```
mM!`"([^"]|"")*"|[^,¶]+|$
```
Extract all of the fields, plus insert a blank line at the end of each record.
```
"(([^"]|"")*)"
$1
```
Remove the outer quotes from quoted fields.
```
""
"
```
Unquote the inner quotes.
39 bytes in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1:
```
mL$`"(([^"]|"")*)"|([^,¶]+)|$
$1$3
""
"
```
[Try it online!](https://tio.run/##K0otycxLNPz/P9dHJUFJQyM6Tim2RklJU0tTqQbI0Tm0LVZbs0aFS8VQxZhLSYlL6f9/pcSkZCWdisoqLqVEJSUQW0kJJKMDhNZAGsRSAJKJQPVJSjrJAA "Retina – Try It Online") Explanation: Retina 1's `$` flag makes a substitution of the listed matches, collapsing the first two stages of my Retina 0.8.2 program into one.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 21 bytes
```
#~ImportString~"CSV"&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@1@5zjO3IL@oJLikKDMvvU7JOThMSe1/YGlmaolDAFCoJDokHyIXrayj4JlXUFrill@UG6uga6cAl0lzQJGLVVBT0HdQqOZSMtQx4kpMStapqKxS0uFSilECcmKUQFwuIDsGKADmgxggyAVmA5E1mA3hKsQoQfTGxHBBVSrV/gcA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/products.htm), 10 bytes
```
{⎕CSV⍵'S'}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8EqK7_E3NTigsTk1KWlJWm6FuuqH_VNdQ4Oe9S7VT1YvXZJcVJy8c356imZxQXqCiCpSAX1lLS8YnUurrRHbRMe9fY96mo2fNQ2GSgXHOQMJEM8PIO5SlKLS4oVgAoUqsGSHV0aQKlQ52AFQwNNnUMrgMbXHlqhcXj6o94ljzoXAQW62h51LdKsftQ7rxYkvdnQkAvkFKARILsV0hQgWhTAJnNxWbnmpaA5fcFNG0MdI67EpGSdisoqLi4lIEsJzFRKVFICsZWAgAtI6ShZA2kQS0EJqC6GCyQDMQQA)
Builtins ftw. If a filename would a valid input format, just `⎕CSV` would do. The `'S'` indicates input from a [S]tring.
[Answer]
# Bash + [ShellShoccar-jpn/Parsrs](https://github.com/ShellShoccar-jpn/Parsrs), 9 bytes
```
parsrc.sh
```
Trivial answer.
## Test runs
```
~/wkdir $ parsrc.sh i.1|cat -A
1 1 1$
1 2 2$
2 1 abc$
2 2 xyz$
~/wkdir $ parsrc.sh i.2|cat -A
1 1 abc$
1 2 xyz$
2 1 a"bc$
2 2 ""$
3 1 ,$
3 2 ;$
4 1 \n$
4 2 $
~/wkdir $ parsrc.sh i.3|cat -A
1 1 \\\n,"$
~/wkdir $
```
[Answer]
# [Go](https://go.dev), 112 bytes
```
import(."encoding/csv";S"strings")
func f(s string)[][]string{o,_:=NewReader(S.NewReader(s)).ReadAll()
return o}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZBfSgMxEMbf5xRhpJBAXNEnaVnBC4jYx25pYposi91kSbL1z7In8aUoHsKjeBuTbtF5-X4zCd83yftH7Q7fnVRPstaklY2Fpu2cjwWaNuJXH8359U83zWiB2iq3bWx9ocIeF0sM0acuIAPTW0UMDWQasdV6tZ5wcHwzL-_084OWW-3psvjnwFiR8Xa3owy8jr23xI2n3M-jad6KMjJAygxkXpI_Y3HJr0A-Kv7y-ia4wISYGVAiZsZUkITjImkmgvliBflIjADGebLhKtt6adMfHEMGuE8B0VAUsyAqS1KVN2R2tq8scqJ4eqliDEY4rXo4TPoL)
Uses the CSV reader from the standard library.
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 66 bytes
```
g=χ'
```
```
gk$(g*>my((g<*g)#|nχ '\'')<*g)#|rX"[^,\n]*"$|$ʃ","$|$ʃ NL
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRMDS0pI0XYubLum259vVudJs07NVNNK17HIrNTTSbbTSNZVr8s63K6jHqKtrQrhFEUrRcToxebFaSio1KqealXQgtIKfD9SsebmJmXkKtgop-VwKCgVFCioKaQpK6jpAqIQskKiunqSukwykdfLyYvJMdNSNUBQY6hjF5CUmJetUVFahakxKVgcJxuSBzQBy1IEAyANZYQ1igNkKqNbFxMTkgRQqQVy5YAGEBgA)
Uses `'` as a quote delimeter
# [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), ~~[71](https://codegolf.stackexchange.com/revisions/260064/4)~~, 68 bytes
```
g=χ '"'
```
```
gk$(g*>my((g<*g)#|nχ '"')<*g)#|rX"[^,\n]*"$|$ʃ","$|$ʃ NL
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRMDS0pI0XYubbum259sV1JXUudJs07NVNNK17HIrNTTSbbTSNZVr8iBymhBeUYRSdJxOTF6slpJKjcqpZiUdCK3g5wM1bX9uYmaegq1CSj6XgkJBkYKKQpqCUoySDhgpoYglxgCJJKBEMpitk5cXk2cCVGWEqtBQxygmLzEpWaeisgrNgCSgTpBwTB7MtGSwPVCYB7PXGsKBCiigOyQmJiYPqksJ4o0FCyA0AA)
Uses `"` as a quote delimiter.
## Explanation
First we set up a parser to parse a single quote. We are going to use this a bunch of times:
```
g=χ '"'
```
Now we build a parser for unquoted fields:
```
rX"[^,\n]*"
```
This parses any number of characters that aren't either a comma or a newline using a regex.
Next we have quoted fields, which are parsed with:
```
g*>my((g<*g)#|nχ '"')<*g
```
`g*>...<*g` means it has to start and end with a quote and that those quotes do not contribute to the value.
`g<*g` parses two quotes but returns a single one. `nχ '"'` parses anything other than a quote character. We combine them to get a parser which either parses two quotes or a single non-quote character, but never a single quote. We use `my` to repeat this an arbitrary number of times.
Next we combine these two parsers with `#|`. `#|` means that it will try the first one (quoted field) and then try the second iff the first failed. That means if it finds a legal quoted field it won't bother with unquoted fields. This makes the field parser.
To make a record parser we just interleave `,`s, by adding `$|$ʃ","`. To make the CSV parser we just interleave newlines into our record parser with `$|$ʃ NL`.
Finally once we have a parser we use `gk` to request the first complete parse.
## Reflection
This is very long. There's lots to improve here:
* `χ '"'` and `ʃ"\""` and `χ Nl` and `ʃ NL` should all exist. These are common characters for code golf and it's ridiculous that I have to build these parsers manually.
* In an earlier version I used `kB<fE` to parse any character not in a blacklist. It ended up being shorter to use a regex for this. That means this should definitely exist! And to be honest, I'm a bit shocked it doesn't.
* There should be a version of `cM` which uses `(#|)`. I really feel like there might be, but I can't find it.
* Should probably be something like `sqs x y = x *> y <* x`. This is comes up pretty frequently.
* Regex does help save a couple of bytes here, but it could save way more. The unquoted field parser is a good deal bloated. The suggestions above would help trim things down, but it would be nice if we could have replaced it with a regex. But we can't, because hgl-regex currently can't do what that parser needs to do. The issue is that a hgl regex can only really take a chunk off the front of a string. It can't manipulate that chunk at all. That means `g<*g`, a parser which consumes 2 `"`s but returns only 1, is impossible to express in a regex. I have two solutions to this:
+ Add a `_` modifier to the regex which causes the the group to be ignored from the output. So `(ab)_cd` parses `abcd` but only returns the `cd`. This could be extended to include not just silencing a particular part but also replacing it with a new value. With this the parser could be:
```
rX"\"_(\"_\"|^\")*\"_"
```
or if we chose to use `'` as the quote delimiter:
```
rX"'_('_'|^')*'_"
```
Both options are shorter than the parser we have right now.
+ Add a way to pass a custom parser to be referenced inside a regex:
```
rXw(i$>g)"/p(/p\"|^\")*/p"
```
or if we chose to use `'` as the quote delimiter:
```
rXw(g$>i)"/p(/p'|^')*/p"
```
Both would save bytes, but not compared to the last solution, however this method is way more flexible than the previous solution, since non-regex parsers can be made to do basically anything.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~69~~ 59 bytes
```
lambda d:print([*csv.reader(io.StringIO(d))])
import csv,io
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHFqqAoM69EI1orubhMryg1MSW1SCMzXy@4BCic7umvkaKpGavJlZlbkF9UogBUo5OZ/z9NQ11dXSkxKVlJp6KyikspUUkJxFYCAi4gpaNkDaRBLAUloELN/wA "Python 3 – Try It Online")
-10 with thanks to @Neil
Not sure if the output format is valid as it does not exactly match the test cases (uses single quotes around each element). Please comment if not and I can fix it with a `json.dumps()`
] |
[Question]
[
For this challenge a "binary tree" is a rooted tree where each node has 0 children (leaf) or 2. The children of a node are unordered, meaning that while you might *draw* the tree with left and right children there isn't a distinction between them and mirroring the tree or a sub-tree does not produce a new tree.
In this challenge you will be given an integer \$n\$ and you will be asked to determine the number of binary trees with each node labeled from \$1\$ to \$2n+1\$ such that no child node is less than its parent.
For example the following tree with 7 nodes is valid:
```
1
2 7
3 4
5 6
```
but the following tree is not:
```
1
2 7
6 4
5 3
```
Since `3` is a child of `4`.
# Task
Given \$n\$ calculate the number of binary trees labeled from \$1\$ to \$2n+1\$ such that no child node is less than its parent.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
# Test cases
I've calculated the first 11 solutions on my own:
```
1, 1, 4, 34, 496, 11056, 349504, 14873104, 819786496, 56814228736, 4835447317504
```
and the OEIS has more terms at: [A002105](https://oeis.org/A002105)
[Answer]
# [Python](https://www.python.org) NumPy, 72 bytes
```
lambda n:(mat(tril(cumsum(r_[1:n+3]),1),"O")**n)[0,0]
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3PXISc5NSEhXyrDRyE0s0SooyczSSS3OLS3M1iuKjDa3ytI1jNXUMNXWU_JU0tbTyNKMNdAxiudKK8nMV8kpzCyoVMnML8otKtCDm7UvLL1LIU8jMUyhKzEtP1TAy0LQqKMrMK9FI08jT1IQoWrAAQgMA)
Same as below but as a function (no outer loop):
# [Python](https://www.python.org) NumPy, 85 bytes
```
from numpy import*
a=1,
for s,in r_:print((mat(tril(a,1),"O")**s).A1[0]);a+=a[s]+s+2,
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NYyxCsIwFEX3fMWjU5LGkjhJpYKjk5NTKRKwwYBJSl4K9ltcuug_9W-Uti733OHc-_p0Q7oHP04n67oQE-CAJHTR-lTNSW6tgblRZCUBawAPSnKupCx_ctE-baKMQPhL7z6ZzW66mBgc-N51AyzfnOhKCWJCBBTWQ7yWy4Y6nWiK9kG1UExk54xxjqw4qlo2bK_zStfY5JhvxXI-rlj5BQ)
Uses the production matrix approach from the OEIS page. Preamble doctors `print` to cut short the infinite loop (otherwise ato swallows the output).
Uses [this](https://codegolf.stackexchange.com/a/237487/101374) trick to set up the infinite loop.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~85~~ 80 bytes
```
def f(n,s=1,*a):
for _ in"__"*~-n:a=s,*[s:=s+x for x in a[::-1]]
print(s>>~-n)
```
[Try it online!](https://tio.run/##HcyxCoAgEIDhvac4mswMkpY4sBeJEKGslku8hlp6dbPm/@MP97kd1PUhpjQvHrwgxUYr6SoswB8RLOxUWlvKpyF0hpUcGQ3X11@vXMGNiI2epgJC3OkUPAwZV@kD9IHoaF2EVqDbfytyfAE "Python 3.8 (pre-release) – Try It Online") Link includes test cases. Explanation: Based on the relation `A002105(n) = A000111(2n-1)/2ⁿ⁻¹`, calculates A000111 using @dingledooper's approach to [Count alternating permutations](https://codegolf.stackexchange.com/q/248143/). Edit: Saved 5 bytes with help from @pexger.
[Answer]
# [SageMath](https://www.sagemath.org/), ~~44~~ ~~42~~ 36 bytes
```
lambda n:2*(-2)**n*polylog(1-2*n,-1)
```
[Try it online!](https://sagecell.sagemath.org/?z=eJyFT8tugzAQvCPxD3uzcY0UGwMmEv2RpgdKlgSVGASO1Bbx713TtNdaa2lnHzOzXX2Ko6G5vZ0bcEcteKoTIZyYxuFzGC9cpVo4maokjuC_F0f4MWHr8Qw1cCWBwkjI6JuqIKgOeRFwlR-opowtMxUyq6rSFvtMXlhltKYOAWOz3BgaKmmBHHhc_ELcc-MuGAQGdPxXM4EnCDbbK7bvOAcL7HTXpWmZhD1TGaN-N87gJULv4Kuf-M4p4Y_l-HNokOm4f5w9zb3zvGOr3yB9hnXZYH3ovGBdL68bS74BSu5RXA==&lang=sage&interacts=eJyLjgUAARUAuQ==)
*Saved ~~2~~ 8 bytes thanks to [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)!!!*
Uses a port of the Mathematica code by Vladimir Reshetnikov on the [OEIS A002105](https://oeis.org/A002105) page.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 23 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
Based on Peter Luschny's Sage function on OEIS.
```
1⊑(0∾2×+`∘⌽⍟2)⍟⊑∘⥊÷2×ט
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkDHiipEoMOKIvjLDlytg4oiY4oy94o2fMinijZ/iipHiiJjipYrDtzLDl8OXy5wKCgpGwqgxK+KGlTEw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
Nθ⊞υ¹F⊖⊗θ≔⊞O⮌EυΣ…υ⊕λ⁰υI÷§υ⁰X²⊖θ
```
[Try it online!](https://tio.run/##TY7BCsIwDIbvPkWPKUxQwdNOsl12UIc@QddFV@jaLW2nPn1td9FAyE/I/@WXgyBphY6xMVPwlzB2SDDzctMGN0Ao2D7phyUGNUrCEY3HHmobOp3mzDlnJ@fU00A2XCck4S3BDRckh3AWU4bcwwjVR2qsBrsuGvODaZ6rYLvUIX8mZTxUwnlojK/VonqEk29Mj@/szXetfaWch4L9p5pXUBnjMW4X/QU "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Combining two formulas on A110501 gives A002105 in terms of A000111, which we did a couple of days ago: `A002105(n) = A000111(2n-1)/2ⁿ⁻¹`.
```
Nθ
```
Input `n`.
```
⊞υ¹F⊖⊗θ≔⊞O⮌EυΣ…υ⊕λ⁰υ
```
Calculate `A000111(2n-1)`. See my answer to [Count alternating permutations](https://codegolf.stackexchange.com/q/248143/).
```
I÷§υ⁰X²⊖θ
```
Divide by `2ⁿ⁻¹`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 21 bytes
```
EulerE[2#-1,0](-2)^#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737U0J7XINdpIWddQxyBWQ9dIM05Z7X9AUWZeSbSygq6dQlq0cmysmoK@g0JQYl56qoKDgqHhfwA "Wolfram Language (Mathematica) – Try It Online")
This is basically the Mathematica code by Vladimir Reshetnikov on OEIS, but golfed down.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 27 bytes
```
n->(-2)^n*eulerpol(2*n-1)%x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWu_N07TR0jTTj8rRSS3NSiwryczSMtPJ0DTVVKyAqbqqk5Rdp5CnYKhjqKBga6CgUFGXmlQAFlBR07YBEmkaepqYmRO2CBRAaAA)
Based on the Mathematica code by Vladimir Reshetnikov on OEIS.
[Answer]
# [Python](https://www.python.org), 125 bytes
```
C=lambda n,k:n==k or C(n-1,k)*n//(n-k)
def f(n):
s=i=0
while(i<n)*n:j=n-i-1;s+=f(i)*f(j)*C(2*n,2*i+1);i+=1
return s//2or 1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY47DoMwEERrfIotbQMCU0WQrTgJETgskAUZUEiRk6ShSe6U24T8uhlpRu_dHsNlqnte1_s82XD3vObYFadDWQAHbcqILfQOcsmhCVqlOYq22CpRVhasZJUKb0TCWHjnmrpK0p63VdoghxSabPTRSlLaykbpXCaag0STb1RGPhrhuWqaHcMYRcmGMT8JbbfCQAyu4GMlTfzmLIAfpPAGRzxJDmBR38df_wU)
[Answer]
# [Python 2](https://docs.python.org/2/), 99 bytes
```
D=[1]
i=0
while 1:exec"D[::-1]=D\nfor k in range(i):D[k+1]+=D[k]\n"*2;D+=0,;print(D[i]<<i)/-~i;i+=1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN5NdbKMNY7kybQ24yjMyc1IVDK1SK1KTlVyirax0DWNtXWLy0vKLFLIVMvMUihLz0lM1MjWtXKKztQ1jtW2BdGxMnpKWkbWLtq2BjnVBUWZeiYZLdGasjU2mpr5uXaZ1pratIcQqqI0wmwE)
-14 bytes thanks to @ovs
Based on [Peter Luschny](https://oeis.org/wiki/User:Peter_Luschny)'s program on the OEIS page.
Full program which prints the sequence infinitely.
`exec"..."*2` performs two cumulative sums on `D`, first backwards, then forwards.
A backwards cumulative sum is equivalent to:
```
D.reverse()
D.normal_cumulative_sum()
D.unreverse()
```
Since "unreverse" is the same as reverse, the overall sequence of operations becomes:
```
D.reverse()
D.normal_cumulative_sum()
D.reverse()
D.normal_cumulative_sum()
```
and this can be extracted into a snippet of code which we just call twice.
`D[::-1]=D` is a horrible way of reversing `D` in-place, which is two bytes shorter than `D.reverse()`. Unlike the more obvious `D=D[::-1]`, it doesn't reassign `D` (it mutates it in-place), which means it can be done in a function without having to use the `global` keyword.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 51 bytes
```
f=(n,s=0,l=1)=>n?s*f(n-=.5,s-1,l+1)+l*f(n,s+1,l):!s
```
[Try it online!](https://tio.run/##FYzBCsIwEETv/YoVesiapDQHQVpXf6WhNqKEjXTFS8i3xwgDwxse8/JfL@v@fH8sp/tWA7UoNkKjieSQrnyTY1BsaTgZsc5E7VDH/2REN8TpIDWkXTEQjDMwXODcSmuE3AGsiSXFbYjpoRav@swFm9nn9oBlwbkr9Qc "JavaScript (Node.js) – Try It Online")
This program output `true` for `n=0`. 1 more byte is required to convert it into `1`.
```
f=(
n, // nodes: `2*n` is number of nodes remaining
s=0, // slots: how many nodes with 1 child currently
l=1 // leaves: how many leaf nodes currently
)=>
n? // is all nodes placed on the tree?
s*f(n-=.5,s-1,l+1)+ // chose a non-leaf node, place it as an child
l*f(n,s+1,l): // chose a leaf node, place it as an child
!s // make sure all non-leaf nodes have 2 children
```
[Answer]
# [Python](https://www.python.org), ~~58~~ 56 bytes
-2 [jezza\_99](https://codegolf.stackexchange.com/users/110555/jezza-99)
```
lambda n:2*(-2)**n*polylog(1-2*n,-1)
from mpmath import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3LXISc5NSEhXyrIy0NHSNNLW08rQK8nMqc_LTNQx1jbTydHQNNbnSivJzFXILchNLMhQycwvyi0q0IPpXFxRl5pVopGmYaWpCRBYsgNAA)
Ported from code by Vladimir Reshetnikov from the OEIS page ([A002105](https://oeis.org/A002105))
[Answer]
# JavaScript (ES6), ~~66~~ 65 bytes
Returns the \$n\$-th term, 0-indexed.
Uses [@Neil's method](https://codegolf.stackexchange.com/a/248214/58563).
```
n=>(g=a=>i<2*n?g([s,...a.map(_=>s+=a[--j],j=i++)]):s>>n)([i=s=1])
```
[Try it online!](https://tio.run/##DcqxDoIwEADQna@4geFOoFEnI1z9EELkgkBK4EqocSF8e2V6y5vkJ6Hb3Pot1H/6OHBUtjiysHXV/aKvEeuQG2PELLLim23IWOqimJp8Ypdl1NAzWKuEtePAt4bi4DdUYLiWoFDB4@R8sCcAndfg597MfsRWMN31oHOm@4BKR0tlcsQ/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.extras`, ~~54~~ 51 bytes
```
[| n | n 2^ 4 n ^ 1 - * n 2 * bernoulli abs * n / ]
```
[Try it online!](https://tio.run/##LYlBCsIwFET3PcWsRSsRV3oAceNGXJUWfkKqgfQnJr@g4N1jW13Mm8dMT0ZCKrfr@XI6YCB5LKjtSxLlnyfiu/17P7IRFzgj2@do2UyHD4Z8RkxW5B2TY8GxqpRCo9a6Lc0HjDm7DvupOihssJqHidomDqP3DqTzsm7RloEi6vIF "Factor – Try It Online")
Uses the following formula from the title of OEIS [A002105](https://oeis.org/A002105):
$$\large\frac{2^n\times(2^{2n}-1)\times|\text{bernoulli}(2n)|}{n}$$
-3 bytes from peeking at @Noodle9's [SageMath answer](https://codegolf.stackexchange.com/a/248217/97916) which combines \$2^{2n}\$ into \$4^n\$.
[Answer]
# [R](https://www.r-project.org), ~~55~~ 51 bytes
```
\(n){for(i in 2:(2*n))T=rev(diffinv(T));T[1]/2^n*2}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3jWM08jSr0_KLNDIVMvMUjKw0jLTyNDVDbItSyzRSMtPSMvPKNEI0Na1Dog1j9Y3i8rSMaiFad8I1GVoZGmgqFGfkl2ukaWRqakLkFyyA0AA)
Uses the `A002105(n) = A000111(2n-1)/2ⁿ⁻¹` trick found by [@Neil](https://codegolf.stackexchange.com/a/248213/55372), and [my answer](https://codegolf.stackexchange.com/a/248152/55372) to [Count alternating permutations](https://codegolf.stackexchange.com/questions/248143/count-alternating-permutations) (calculating A000111).
] |
[Question]
[
You have to write a function/program that takes input via the `stdin`/command-line arguments/function arguments, mixes up characters in a string, and then output the final string via the `stdout`.
Input will first contain a string (not empty or `null`), a space, and then an even number of non-negative numbers all separated by spaces. If input is taken via function arguments, the string will be the one of the arguments while the integers, which are seperated by a space, will be the other. You must swap the characters of the string at the indices corresponding to consecutive pairs of numbers.
For instance:
```
Hello_world! 0 6
```
must result in
```
wello_Horld!
```
## Assumptions
* You may choose between 0-based and 1-based indexing, and may assume that the given indexes will always be in range.
* The string will not be longer than 100 characters and will only contain ASCII characters in range `!` to `~` (character codes 0x21 to 0x7E, inclusive). See [ASCII table](http://c10.ilbe.com/files/attach/new/20150514/377678/1372975772/5819899987/f146bf39e73cde248d508e5e1b534865.gif) for reference.
* The two indices in a pair *may* be identical (in which case, nothing is swapped in that step).
## Scoring
This is code golf, so the shortest submission (in bytes) wins.
## Test Cases
```
Hello_world! 0 6 => wello_Horld!
First 1 2 1 0 0 4 => tFisr
(Second!$$) 8 7 10 1 => ()econd$!$S
~Third~ 0 0 6 6 0 6 6 0 => ~Third~
```
[Answer]
# Python 3, ~~89~~ 86 bytes
```
[*s],*L=input().split()
while L:a,b,*L=map(int,L);s[a],s[b]=s[b],s[a]
print(*s,sep="")
```
Unpack all the things. (3 bytes saved thanks to @potato)
[Answer]
# CJam, 11 bytes
```
rr{irie\r}h
```
**How it works**
This is a slightly different approach, in which I simply run a do-while loop till I have pairs of numbers left in the input.
```
r e# Read the first string
r e# Read the first number of the first number pair in the input
{ }h e# Do a do-while loop
i e# Convert the first number from the pair to integer
ri e# Read the second number from the pair and convert to intger
e\ e# String X Y e\ works by swapping the Xth index with the Yth index in the
e# String
r e# This is our exit condition of the do-while loop. If we still have
e# a number on the input left, that means there are more pairs to swap.
e# Otherwise, we exit the loop and the result is printed automatically
```
[Try it online here](http://cjam.aditsu.net/#code=rr%7Birie%5Cr%7Dh&input=First%201%202%201%200%200%204)
[Answer]
# CJam, 13 bytes
```
r[q~]2/{~e\}/
```
[Test it here.](http://cjam.aditsu.net/#code=r%5Bq~%5D2%2F%7B~e%5C%7D%2F&input=(Second!%24%24)%208%207%2010%201)
## Explanation
```
r e# Read the first token, i.e. the string.
[q~] e# Read the rest of the input, eval it and wrap it in an array.
2/ e# Split the array into pairs of consecutive elements.
{ }/ e# For each pair.
~ e# Unwrap the array.
e\ e# Swap the corresponding elements in the string.
```
[Answer]
## C (137 b)
```
f(char*T,int*V,int L){int C=0;for(int j=0;j<strlen(T);C=++j){for(int i=L-1;i+1;i--)if(C==V[i]){C=V[i-i%2*2+1];i-=i%2;}printf("%c",T[C]);}}
```
---
Explanation is coming ...
## Arguments
T = a word of type **char\***.
V = an array of an even number of integer elements.
L = length of V
## Output
mixed string
**How does it work ?**:
sweeps numbers of array V vice versa , and puts the nth element of the string after tracking all its progress until the actual point . **Example**
**input=** T="First" , V={1,2,1,0,0,4}
V inversed={4,0,0,1,2,1}
```
V[0] = 4th element -> index 0
0 -> 1
1->2
4th element 't' receives the second = 'r'
V[1] = 0 -> index 4
4 isnt mentionned after so , no changes
0 element='F' receives the fourth= 't'
V[3] = 1st element -> index 0
no changes
V[4] = 2 -> index 1
no changes after ..
```
## Try it [here](http://rextester.com/RDIX65870)
[Answer]
# Python 3 - ~~161~~ 149
```
import sys
t=sys.stdin.read().split()
q=list(t[0])
c=1
i=int
while c<len(t):n=q;a=i(t[c]);b=i(t[c+1]);n[a]=q[b];n[b]=q[a];q=n;c+=2;
print(''.join(q))
```
Golfed more by swapping around some variables, and using `;` as in Tim's comment.
I expected it to come out looking golfed, just not this much.
[Answer]
# C, 109 ~~107~~ 102 bytes
```
i;f(l){l=sizeof(a)/sizeof(*a);char t;for(;i<l;i+=2){t=s[a[i]];s[a[i]]=s[a[i+1]];s[a[i+1]]=t;}puts(s);}
```
Note: `s` and `a` needs to be declared as global arrays. `s` is the string which you want to swap and `a` is an array of `int` with all the number values.
If the above code does not work, try using `void f(){...}` instead of `f(){...}`
Ungolfed code:
```
int a[]={1, 2, 1, 0, 0, 4};//Integer elements
char s[]="First"; //String to be swapped
i; //Auto initialized to 0 and defaults to type int
void f(l){ //Variables defaults to type int
l=sizeof(a)/sizeof(*a); //Gets number of elements in array a
char t;
for(;i<l;i+=2){
t=s[a[i]];
s[a[i]]=s[a[i+1]];
s[a[i+1]]=t; //Swap each character
}
puts(s); //Print the final char array
}
```
# Test it [here](http://rextester.com/TSHLW7403)
[Answer]
# C, 70 bytes
Given that the input string is at most length 100 I decided to make the 'NULL' byte indicating the end of the integer array be the unambiguous `0xFF`. Presumably this doesn't count as extra input, though for a cost of ~~(at most) 7~~ 3 bytes it can be made into 1-based indexing and use `'\0'` as the end of the array.
```
f(s,i,t)char*s,*i;{for(;~*i;)t=s[*i],s[*i]=s[*++i],s[*i++]=t;puts(s);}
```
Pretty much just does regular swapping with a tmp variable and uses that the comma operator introduces sequence points to have defined behaviour (unlike some manifestations of xor swaps that would have a lower character count but lead to undefined behaviour).
Edit: As requested you can test it out: <http://rextester.com/OVOQ23313>.
[Answer]
## Dart - 123
Assumes input on the command-line is automatically split at spaces. Otherwise it needs an initial `x=x[0].split(' ');` to split the string into text and indices.
```
main(x,{c,i:1,a,t}){c=x[0].split("");n()=>a=int.parse(x[i++]);for(;i<x.length;t=c[n()],c[a]=c[n()],c[a]=t);print(c.join());}
```
With more whitespace:
```
main(x,{c,i:1,a,t}){
c=x[0].split("");
n()=>a=int.parse(x[i++]);
for(;i<x.length;t=c[n()],c[a]=c[n()],c[a]=t);
print(c.join());
}
```
Run/test this on [dartpad.dartlang.org](https://dartpad.dartlang.org/bdd3540a5b908c560e6a).
[Answer]
# Rebol - 71
```
s: take i: split input" "foreach[a b]i[swap at s do a at s do b]print s
```
Ungolfed:
```
s: take i: split input " "
foreach [a b] i [swap at s do a at s do b]
print s
```
[Answer]
# Python 3, 135
```
x=input().split()
y=list(x[0])
z=[int(i)for i in x[1:]]
while z:p,c=y[z[0]],y[z[1]];y[z[0]],y[z[1]]=c,p;del z[0],z[0]
print(''.join(y))
```
Explanation:
```
x=input().split() # Split the input into a list at each space
y=list(x[0]) # First item in list (the word) into a list of chars
z=[int(i)for i in x[1:]] # Make the list of numbers, into integers
while z: # Loop untill the list z is empty
p,c=y[z[0]],y[z[1]] # Assign p to the first char and c to the second
y[z[0]],y[z[1]]=c,p # Swap around using p and c
del z[0],z[0] # Remove the first 2 items in the list of integers
print(''.join(y)) # Print out the altered list as a string
```
[Answer]
# C, 143 bytes
```
main(a,v,i)char** v;{i=2;char s[101],t;strcpy(s,v[1]);for(;i<a;i+=2){t=s[atoi(v[i])];s[atoi(v[i])]=s[atoi(v[i+1])];s[atoi(v[i+1])]=t;}puts(s);}
```
The above program takes input from command-line arguments, copies the string into an array, swaps corresponding characters and then, outputs the modified string.
Ungolfed code:
```
main(int a,char** v,int i){ //Arguments of main
i = 2;
char s[101],t;
strcpy(s,v[1]); //Copy string literal into an array
for(;i<a;i+=2){
t=s[atoi(v[i])];
s[atoi(v[i])]=s[atoi(v[i+1])];
s[atoi(v[i+1])]=t; //Swap each character
}
puts(s); // Output the final string
}
```
[Answer]
# JavaScript (ES6), 95
95 bytes with a single string input (function f below)
75 bytes with 2 parameters, string and number array (function g below)
(EcmaScript 6, Firefox only)
```
f=i=>
(
n=i.split(' '),
s=[...n.shift()],
n.map((v,i)=>i&1?[s[v],s[w]]=[s[w],s[v]]:w=v),
s.join('')
)
g=(s,n)=>
n.map((v,i)=>i&1?[s[v],s[w]]=[s[w],s[v]]:w=v,s=[...s])
&&s.join('')
// TEST
out=x=>O.innerHTML+=x+'\n'
;[['Hello_world! 0 6', 'wello_Horld!']
,['First 1 2 1 0 0 4','tFisr']
,['(Second!$$) 8 7 10 1','()econd$!$S']
,['~Third~ 0 0 6 6 0 6 6 0','~Third~']]
.forEach(t=>{
u=f(t[0]),
ok=u==t[1],
out('Test '+(ok?'OK: ':'FAIL: ')+t[0]+'\n Result:' +u + '\n Check: '+t[1]+'\n')
})
```
```
<pre id=O></pre>
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
$⌈⌊2ẇ(n~İṘȦ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwiJOKMiOKMijLhuocobn7EsOG5mMimIiwiIiwiXCJIZWxsb193b3JsZCFcIiwgXCIwIDZcIiA9PiB3ZWxsb19Ib3JsZCFcblwiRmlyc3RcIiwgXCIxIDIgMSAwIDAgNFwiID0+IHRGaXNyXG5cIihTZWNvbmQhJCQpXCIsIFwiOCA3IDEwIDFcIiA9PiAoKWVjb25kJCEkU1xuXCJ+VGhpcmR+XCIsIFwiMCAwIDYgNiAwIDYgNiAwXCIgPT4gflRoaXJkfiJd)
[7 bytes by taking the string and then a list of lists of the indices to swap](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwiJChufsSw4bmYyKYiLCIiLCJcIkhlbGxvX3dvcmxkIVwiLCBbWzAsNl1dID0+IFwid2VsbG9fSG9ybGQhXCJcblwiRmlyc3RcIiwgW1sxLCAyXSwgWzEsIDBdLCBbMCwgNF1dID0+IHRGaXNyXG5cIihTZWNvbmQhJCQpXCIsIFtbOCwgN10sIFsxMCwgMV1dID0+ICgpZWNvbmQkISRTXG5cIn5UaGlyZH5cIiwgW1swLCAwXSwgWzYsIDZdLCBbMCwgNl0sIFs2LCAwXV0gPT4gflRoaXJkfiJd)
## Explained
```
$⌈⌊2ẇ(n~İṘȦ
$⌈ # Push the numbers split on spaces then the string.
⌊2ẇ # eval each number in the rest and wrap into lists of size 2
( # to each pair:
n~İ # without popping anything, index the pair into the string
Ṙ # reverse that
Ȧ # assign back to the string, vectorises
```
] |
[Question]
[
# Introduction
An [abstract syntax tree (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree) is a tree of tokens that shows their connection to each other and syntactical meaning. They are commonly used in compilers and static analysis tools, as parsing a language into an AST helps remove any ambiguity and can be helpful for optimizations. Many ASTs are large and complex, but in this thread, your task is to create a basic parser to convert an arithmetic expression into a basic AST.
# Challenge
The main part of this challenge is resolving the order of operations. In this challenge, assume PEMDAS so that multiplication is before division and addition is before subtraction. Also, assume left associativity. Every node in the tree should either be an operator or a number. Operators with other operators as children resolve their children first, so nodes at the bottom of the tree resolve first. Number nodes should have no children. Your solution may assume the input is valid, all numbers are positive, and that the input contains no parentheses (unless you'd like to add support for fun).
The input will be a string with only the characters `0123456789+-*/` (and optionally `()`). Your program/function may return nested objects/dictionaries, nested arrays/lists, or even a built-in data structure; as long as your output can be interpreted as a tree you're OK (note: if you are going to abuse this rule by using weird formats, then explain how it represents a tree).
### Test cases
`1+2+3*5-7` -> `['-', ['+', ['+', 1, 2], ['*', 3, 5]], 7]`, where the first element of the array is the operator, and the second and third are the children.
`13*7+9-4+1` -> `{op: '-', left: {op: '+', left: {op: '*', left: 13, right: 7}, right: 9}, right: {op: '+', left: 4, right: 1}}`
`8/2*6+4-1` -> `['-', ['+', ['/', 8, ['*', 2, 6]], 4], 1]`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!
[Answer]
# [Python](https://www.python.org), ~~69~~ 68 bytes
```
f=lambda x:[*([i,*map(f,x.split(i,1))]for i in'-+/*'if i in x),x][0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXISc5NSEhUqrKK1NKIzdbRyEws00nQq9IoLcjJLNDJ1DDU1Y9PyixQyFTLz1HW19bXUM9PAHIUKTZ2K2GiDWKhJOgVFmXklGmkaSobaRtrGWqa65kqamlwIUWMtc21LXRNtQ6AwRM-CBRAaAA)
[Answer]
# [sed](https://www.gnu.org/software/sed/), 96 bytes
```
s/^/x_/
:a
s/([^*/+-]*)\*([^*/+-]*)/['_',\1,\2]/
ta
y#/+-_SAD#*/+SADM#
/xM/!ba
s///
y#MDAS#*/+-#
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3E4r14_Qr4vW5rBK5ivU1ouO09LV1Y7U0Y7QQbP1o9Xh1nRhDnRijWH2ukkSuSmWgRHywo4syUAWQ8lXm0q_w1VdMApmhrw-U93VxDAZJ6ipD7IFat2CfobaRtrGWqa45l6Gxlrm2pa6JtiGXhb6Rlpm2ia4hRBUA)
[Answer]
# [Wolfram Language](https://www.wolfram.com/language/) 99 bytes
Wolfram Language have built-in tools for working with AST, for example
```
FullForm@MakeExpression@"1-(4/2)+3*(5+7)"
```
produce
```
HoldComplete[Plus[1,Times[-1,Times[4,Power[2,-1]]],Times[3,Plus[5,7]]]]
```
and
```
TreeForm@MakeExpression@"1-(4/2)+3*(5+7)"
```
produce
[](https://i.stack.imgur.com/IFIKs.png)
But firstly it looks like cheating. Secondly, it's a bit difficult to obtain the required form from WL output.
Maybe someone can do it, it will be interesting.
Here is a solution based on more common functions.
```
If[StringLength@#1 == 1,#1,#0/@StringSplit[#1, x__ ~~ # ~~ y__ :> {#,x,y}&/@ {"-", "+", "/", "*"}, 2][[2]]]&
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 82 bytes
```
f=(x,i=5,b,j=x.split(b=' */+-'[--i]))=>i?j[1]?[f(j.pop()),b,f(j.join(b))]:f(x,i):x
```
[Try it online!](https://tio.run/##FcyxDoIwFEDR3a9w63tAa4gaI6ayO@jgSDpQoOQ1pG0oMfj1VcY7nGvbTxu7mcLCne@HlIyEtSB5LnRh5SpimGgBLdk@O@ScNZyTQpR3qm1TqroxYEXwARD/YAvryYFGVJXZRlit6bbrvIt@GsTkR3i8X08Rl5ncSOYLBlh5zC75lZ/ykiFi@gE "JavaScript (Node.js) – Try It Online")
Seem not that golfed but anyway
Output is reversed
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) ~~44~~ 23 bytes
```
λ`+-:*`(n~ḟ0>[:∇ẇWfvx|_
```
Thanks to @emanresuA for full refactoring, I began to understand better how lambda works.
```
λ # Open lambda
`+-:*`( # Open loop over operators
n~ḟ0> [ # If there is such operator
:∇ẇWf # Split and wrap into list
vx # Recursive call lambda as map
|_ # If there is no continue
# ]); Closing If, loop and lambda
expected but not required
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes
```
≔⟦S⟧θ⊞υθF-+/*FΦυ№§κ⁰ι«≔E⮌⪪⊟κι⟦λ⟧ζFζ⊞υλW⊖Lζ⊞ζ⟦ι⊟ζ⊟ζ⟧F⊟ζ⊞κλ»⁻⭆¹θ'
```
[Try it online!](https://tio.run/##NY/BasMwEETP8VcsvnQ3lmnTUnrIKaQUAg2Y5hh8MM7WFlZkV5bS4tJvd63Iuax2pOGNpqwLU7aFGsdN38tK43GnO2cP1khdIeUCvmgdZa6v0YX9szWAcZrcL2OCq3iTyrLx79vWaYsbu9Mn/sFGwAMJkEQEv9FiDtgXHX7whU3PeOiUtJi1HTbBKOCo8mkOU9DiCh8IbunKX37XUjHgK5eGz6wtn/CddWXryUmzd5gwUoDnDnQ7c5qJQc7WJmD/omwqbHEvtesxtPcfXfnOAuK7mGg9jqvkMXlaPqcvY3pR/w "Charcoal – Try It Online") Link is to verbose version of code. Outputs values in one-element sublists and operators in three-element sublists. Explanation:
```
≔⟦S⟧θ
```
Wrap the input string in a list.
```
⊞υθ
```
Push it to the list of lists to be processed.
```
F-+/*
```
Loop over the operators in ascending order of precedence.
```
FΦυ№§κ⁰ι«
```
Loop over the terms that contain this operator.
```
≔E⮌⪪⊟κι⟦λ⟧ζ
```
Remove the term from its list, split it on the operator, and wrap all of the resulting terms in lists.
```
Fζ⊞υλ
```
Push all of those lists to the list of lists to be processed.
```
W⊖Lζ⊞ζ⟦ι⊟ζ⊟ζ⟧
```
Build up consecutive terms into a nested structure.
```
F⊟ζ⊞κλ
```
Re-insert the top-level terms back into the original list.
```
»⁻⭆¹θ'
```
Pretty-print the final list.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 53 bytes
```
+0`(\w+)\*(\w+)
aUb$1b$2c
4}T`V*/+-`_o
T`abcV`[,]*/+-
```
[Try it online!](https://tio.run/##HcixDkAwEADQ/b7DwJ2Gq1L@AwviWjFYSERi8u0Vppe8c7223XEIlEs83pSM@AOu8xH7SC9gnlZ6zEjJfEArzi@9DOn0TQhMmgoslQUu0FKjDDHUmcaKjOIX "Retina – Try It Online") Link includes test cases. Explanation: Port of @Jiří's sed answer.
```
(\w+)\*(\w+)
aUb$1b$2c
```
Replace (parameter)`*`(parameter) with `[*,`(parameter)`,`(parameter)`]`, except encoding `*` with `U`, `[` with `a`, `,` with `b` and `]` with `c` as they are all letters and will therefore be treated as part of the same parameter in subsequent replacements (both with the current operator and with subsequent operators of lower precedence).
```
0`
```
Only perform one replacement at a time.
```
+`
```
Repeat the above replacement until no more changes can be made.
```
T`V*/+-`_o
```
Step the operators and their encodings in sequence so that `-` becomes `+` etc. allowing each operator in turn to be encoded as a `U`, but those then in turn get stepped to previous vowels.
```
4}`
```
Repeat the whole of the above four times, once for each operator.
```
T`abcV`[,]*/+-
```
Translate all of the letter placeholders back to the characters they represent.
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 61 bytes
```
z#y=Fe<Rv<sQ[y<*χ z,z#y,p3 z]++y
```
```
gk$bkw$rF(#)(p<rv<dg_)"-+/*"
```
## Explanation
This takes input as a string and outputs as a `Free List String`. In haskell a list can only contain one type of thing. A free list of strings is basically a list that is allowed to contain strings or other free lists of strings. That makes it the perfect sort of structure for this challenge.
A good deal of the machinery here is devoted to making things left associative. *Right* associativity would be quite easy, but if we naively modify the algorithm to be left associative it creates recursion without a base case. So what we do instead is that we actually just do right associativity but parse the entire thing backwards. Of course this means we have to do a bunch of extra reversing things, but that's how it goes.
For reference here's a right associative version:
```
z#y=Fe<sQ[pp[z],y<*χ z,z#y]++y
```
```
gk$rF(#)(p<dg_)"-+/*"
```
It's 9 bytes shorter.
The actual code is quite extensible. We do a fold over a list of operations, and adding new operations is as simple as adding their symbol in the right spot (later entries have higher precedence).
## Reflection
This is pretty alright, there could be some improvements.
* `m p` should get a shorthand. I keep thinking it already exists, but I can't find it, so I should make it.
* I wasn't able to use `(*:*)`, but if it had a prefix version I could.
* Although I use `p3`, I did at one point have a chain of 4 `p`s, so I guess `p4` has a potential use.
* `bkw` doesn't save any bytes here over just using `Rv`. It's a nice little function and I was excited to use it here, but it seems of limited use. Probably not deserving of a 2 byte name though.
[Answer]
# [Go](https://go.dev), 79 bytes
```
import(."go/parser";."go/ast")
func f(s string)Expr{e,_:=ParseExpr(s)
return e}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY_LasMwEEX38xVCK8mv4CRtXnjZLttAtoVEBMmI2LKRxrQQ8hlddWMK_aj8TSXbWc3j3rk6-vktm_5etOJ8EaUktdAGQNdtYzGjDq02paPTgqoaHz1BWjYzbC7S0L8OVbq-v48Ky4LSCuukpbthEA4pB9WZM1HMkTGWv3y19iqT47bYB3MYmeNgJXbWEHmbYr-HuwDGOLmCNo5sC3LK43m8iJ7SFeSLaBVv0mWcw3o2j57jZZqfQDWWHBNtgtkK4_92aCuNzN8n9MPQkCX9k0FXfsth76mQYfYmP191JQ8SGU9I8Hj2GrNBrzwF3GCC6_ux_gM)
Returns an `ast.Expr` from `go/ast` in Go's standard library, which represents a Go expression.
] |
[Question]
[
# The task
Given a positive integer `c`, output two **integers** `a` and `b` where `a * b = c` and each `a` and `b` is closest to `sqrt(c)` while still being integers.
# Test cases
```
Input: 136
Output: 17 8
```
```
Input: 144
Output: 12 12
```
```
Input: 72
Output: 9 8
```
```
Input: 41
Output: 41 1
```
```
Input: 189
Output: 21 9
```
# Rules
1. `a`, `b` and `c` are all positive integers
2. You may give `a` and `b` in any order, so for the first case an output of `8 17` is also correct
3. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte count wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
Given an input \$ c \$, it outputs \$ a \$ and \$ b \$ as a list in increasing order. If \$ c \$ is a square, it outputs a single integer (which according to the OP is allowed).
```
ÑÅs
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MTDrcX//xsamwEA "05AB1E – Try It Online")
## Explanation
```
Ñ # All divisors
Ås # Middle elements
```
[Answer]
# JavaScript (ES7), 35 bytes
```
f=(n,d=n**.5)=>n%d?f(n,-~d):[d,n/d]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfFNk9LS89U09YuTzXFPg0ooluXomkVnaKTp58S@z85P684PydVLyc/XSNNw9DYTFOTC03MxARDzNwIQ8jEEFOnhaWm5n8A "JavaScript (Node.js) – Try It Online")
### How?
If \$n\$ is a square, \$d=\sqrt{n}\$ is an integer which obviously divides \$n\$, so we immediately have an answer. Otherwise, the first `-~d` will act as \$\lceil{d}\rceil\$ and the next ones as \$d+1\$. Either way, we stop as soon as \$n\equiv 0\pmod{d}\$ which in the worst case (i.e. if \$n\$ is prime) happens when \$d=n\$.
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
i=n=input()
while(i*i>n)+n%i:i-=1
print n/i,i
```
[Try it online!](https://tio.run/##HctbCoAgEAXQ/1mFCEFPYkp6gW0mhC7EJGFUqzfq@3D8E9Zdmnit2Jziyd1u0VpHWLEQf4Y0o99S5JglKyTBhMoy@QMSlNQoEb/BbUdsDPUNGSYexhc "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆDżṚ$SÞḢ
```
A monadic Link accepting a positive integer which yields a list of two positive integers.
**[Try it online!](https://tio.run/##ARwA4/9qZWxsef//w4ZExbzhuZokU8Oe4bii////MTM2 "Jelly – Try It Online")**
### How?
```
ÆDżṚ$SÞḢ - Link: positive integer, X e.g. 12
ÆD - divisors of X [1,2,3,4,6,12]
$ - last two links as a monad:
Ṛ - reverse [12,6,4,3,2,1]
ż - zip [[1,12],[2,6],[3,4],[4,3],[6,2],[12,1]]
Þ - sort by:
S - sum [[3,4],[4,3],[2,6],[6,2],[1,12],[12,1]]
Ḣ - head [3,4]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
Z\J2/)Gy/
```
[Try it online!](https://tio.run/##y00syfn/PyrGy0hf071S//9/Q2MzAA "MATL – Try It Online")
### Explanation
```
Z\ % Implicit input. Array of divisors
J2/ % Push imaginary unit, divide by 2: gives 0.5j
) % Index into the array. When used as an index, the imaginary unit means "end".
% Thus the index 0.5j for [1 2 3 6] would give the 2nd entry (end=4th entry,
% end/2 = 2nd entry, indexing is 1-based), whereas for [1 2 3 6 12] it would
% give the "2.5-th" entry. This index is rounded up, so the result would be
% the 3rd entry
G % Push input again
y % Duplicate second-top element in stack (that is, the selected entry)
/ % Divide
% Implicitly display stack contents
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
```
i;f(a,c)int*a;{for(i=0;i*i++<c;)c%i||(*a=i);c/=*a;}
```
[Try it online!](https://tio.run/##RYtBCsIwEEX3nkIClZk0otVQlTE3cZOOJMzCKKW7tGePqRs3/8Hjfd5H5lKEAnjDKGnSnnJ4jyDuSKKlbe9MyI3MM2jvBIkPrjZLiZDMgPkz1lMA1Ty3ygTYDSYh0t8@kqoZLZuXlwSYI3TnHqnC2hWX07q2@6nrrZblCw "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
f=lambda n,v=1:[n/v,v]*(n/v-v<1>n%v)or f(n,v+1)
```
A recursive function.
**[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU@nzNbQKjpPv0ynLFZLA0jrltkY2uWplmnmFymkaQDltQ01/6cBOSWpxSUKmXkKGoY6CobGZkDCxERHwdxIR8EEJGJhqWnFpQAEBUWZeSVg1ToK6rp26jpAY0A8zf8A "Python 2 – Try It Online")**
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
Nθ≔⊕⌈Φ₂θ¬﹪θ⊕ιηI⟦÷θηη
```
[Try it online!](https://tio.run/##TYy9CsIwFEZ3nyLjDcRBBJdOoggdWkRHcYjJxV7IT5veFN8@pk5@y1nO@cygk4naldKGMXOf/QsTTLLZHOeZ3gHaYBJ6DIwWOv0hnz1cyHG17lPWCW8xcg2U6Cu7aLOLMCnx35H8TYmh/l4TBYaTnhkebeAzLWRxLYZVeErZlLLbH8p2cV8 "Charcoal – Try It Online") Link is to verbose version of code. Technically only works up to `a=2⁵³`, but would be stupidly slow well before then anyway. Explanation:
```
Nθ
```
Input `c`.
```
≔⊕⌈Φ₂θ¬﹪θ⊕ιη
```
List all of the factors of `c` that do not exceed its floating-point square root, and take the largest `b`.
```
I⟦÷θηη
```
Calculate and output `a` and `b`.
[Answer]
# [Julia](https://julialang) 54 bytes
## [Try it](https://tio.run/##yyrNyUw0rPiflmb7P0/XLik1PTNPIdM2LTMvJS2zqLhEo0LXriLOyM42T00tT7XC1tZAx9AqT9M6Uyfv8PZM69S8lP8OxRn55QppaRqGJiaa/wE)
```
n->begin i=findfirst(x->x^2>=n&&n%x==0,1:n);i,n÷i;end
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~52~~ 48 bytes
```
f=lambda c,i=1:i*i>=c>c%i<1and(i,c/i)or f(c,i+1)
```
[Try it online!](https://tio.run/##VczBCoMwEATQe79ioQhGA7JpUCPGf4kR6UIbRbz49XH1oHiYwzyGmbf1OwUV42h/7t8PDrwkiw1l1Fnf@YRadGFISfqCxLTAmPIgRxHnhcLKFT@lgDdgJQHq16Van6ok59JKCWAF89hqPFUjK94PtTke1KEm7g "Python 2 – Try It Online")
Simply increments `i` until it satisfies
```
i*i>=c and c%i==0
```
Then returns the pair `(i, c/i)`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes
```
.+
$*
(?<-2>(^(1)+?|\1))+$
$.1 $#1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLS8PeRtfITiNOw1BT274mxlBTU1uFS0XPUEFF2fD/f0NjMy5DExMucyMuE0MuQwtLAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert `c` to unary.
```
(?<-2>(^(1)+?|\1))+$
```
The `(1)+` matches a minimal substring `a` of `1`s individually into the `\2` stack, where they are popped off as the entire substring `\1` is repeatedly matched `b` times until it reaches `c`. This popping mechanism thus prevents `b` from exceeding `a`, but as `a` is minimal it must therefore be the smallest factor not less than the square root. Excitingly, .NET allows you to populate the `\2` stack on the first iteration of the `(?<-2>)` loop. (On the remainder of the loops, the `^` no longer matches, so the `\1` alternative is used.)
```
$.1 $#1
```
Output `a` and `b`.
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 68 bytes
```
f(X)->Y=lists:max([I||I<-lists:seq(1,X),X rem I==0,I*I=<X]),[Y,X/Y].
```
[Try it online!](https://tio.run/##JcixCsMgEADQPV/heFfOtIFMIWb3DxRxkGLKQUxTFdoh/24LfeOLeQv7Q8Zyz3zU1rUVDMrFqo1LLVMKH3D6PPUs/1HiCwYySEbkmIRW6kb6otVsPJKzZK7W9y0F3sF5FHLpxA8/p3fmGmGFYRwR@/YF "Erlang (escript) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 52 bytes
```
n->{int i=n;for(;i*i>n|n%i>0;)i--;return n/i+","+i;}
```
[Try it online!](https://tio.run/##VY/PTsMwDMbvewqrUqV0WwOFin9hPSJxQBx2RBxCl04emVslbqVp7Dl4IB4spGNCcLAs27/v@@SNHnS@Wb0H3HatY9jEWfaMVjY91Ywtyama1FZ7D08aCfYTgK5/s1iDZ82xDS2uYBtvYskOaf3yCtqtfXZEAR6JH05W9z9ABQ0sAuXVHokBF6Sa1gmFU6zog1KszlWGea6c4d4R0BnOknkyQ3UI6mgZcRCDdsDG892/NIBxT7AYc83aODlo25vnRoxspv5AzvjeciQbqbvO7gRl0pnO6tqImDeHBL4@IfnVLHeezVa2PcsuvsGNSNJVlKc@pUjT/OR4EhwmYx1CKC6vQlGW4foilEUobm6/AQ "Java (JDK) – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 39 bytes
```
[d_3R/fq]sE?ddvd[_3R%0=E1-rd3RdlFx]dsFx
```
[Try it online!](https://tio.run/##S0n@/z86Jd44SD@tMLbY1T4lpSwlGshVNbB1NdQtSjEOSslxq4hNKXar@P/f0MISAA "dc – Try It Online")
Or [verify the test cases](https://tio.run/##RY5NC4JAEIbv8yuGpY5mm9IXVieFToJXkVidNQVTW7X895va12Vgnvd9holFk@lEtHisVXVV4oaOw1zfYzqkixWY6T1q3BPRg8JhnS8PLjcUWQEVXh9R4/V6KAM8s7yQqKQgzMu6awGRqmEgyiSr8DyyPc6@2Qf7XTvyCVCCRooL8/@Gg@wtsJ8xnS2l5tYauG3DZgU2B77dwQs).
---
**How it works:**
```
Command Stack (top on the right)
[ # Macro starts with stack at:
# n d
# Prints n/d and d, and then quits.
d # n d d
_3R # d n d
/ # d n/d
f # Prints stack.
q # Quit this macro and the macro which called it.
]sE # End macro and save it in register E.
? # n (Input values and push it on stack.)
dd # n n n
v # n n d
# d is a potential divisor of n;
# it's initialized to int(sqrt(n)).
d # n n d d
[ # Start macro to be used as a loop.
_3R # n d n d
% # n d n%d
0=E # n d If d divides n, call macro E to end.
1- # n d New d = d - 1.
r # d n
d # d n n
3R # n n d
d # n n d d
# The stack is now set up correctly to
# go back to the top of the loop, with
# d now one step lower.
lFx # Call macro F to go back to the top of the loop.
]dsFx # End macro, save it as F, and execute it.
```
[Answer]
# [R](https://www.r-project.org/), ~~48~~ ~~46~~ ~~45~~ 41 bytes
```
x=scan();b=1:x;a=b[!x%%b&b^2>=x][1];a;x/a
```
[Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTOsnW0KrCOtE2KVqxQlU1SS0pzsjOtiI22jDWOtG6Qj/xv6GxGRfXfwA "R – Try It Online")
Finds first (`[1]`) divisor (`which(!x%%b)`) that is equal-to or greater than square-root (`b^2>=x`); returns this & reciprocal (`a;x/a`).
[Previous approach (46 bytes)](https://tio.run/##K/r/v8K2ODkxT0PTOtG2PCMzOUMj00ZXsUJV1dCqQjO6uDRXI1PfSFPbMNY60bpCP/G/obEZF9d/AA) found divisor closest to centre of list-of-divisors, but couldn't be golfed-down so effectively.
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 37 bytes
```
$_=0|sqrt;$_--while"@F"%$_;say"@F"/$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tagpriwqMRaJV5XtzwjMydVycFNSVUl3ro4sRLE1FeJ///f0MTkX35BSWZ@XvF/XV9TPQNDg/@6BTmJAA "Perl 5 – Try It Online")
[Answer]
# Python 3, 73 60 59 bytes
Not the shortest or best solution by any means, but I think it's a creative approach. Prints the two factors without separator between them and only (consistently) works for inputs up to 1008.
```
r=range(1000)
f=[a*b*(a*a>=a*b)for a in r for b in r].index
```
[Try it online!](https://tio.run/##jY/BbsIwEETv@xUrcbEDRDFELSCl39B71YMjbGoVryPjSOnXu@sEOHN7s7OanR3@0k@gfc6xi5ouRqimaSTY7ktXfSV0pT86JmlDRI2OMGLBfsbv2tHZTHmIjpKwQu3fpISHOh4axRJW@Fkm6PXk/OiRRt@biLdxGEJM5swLrjY1LqfX4u4HixRoy2ne3FDbxLOl3BU7fKkeFJ5mfv62mUNKzgnQWbYppLJyZY1L92mrJIs@Gv2b@SlQbQvvO2gVqMMx/wM "Python 3 – Try It Online")
# Python 3, 57 bytes
Still not the shortest solution, but it's at least somewhat expressive and clear what's going on.
```
lambda n:max((x,n/x)for x in range(1,n+1)if n%x<(x*x<=n))
```
[Try it online!](https://tio.run/##Nck9DoMwDEDh3afwUslukYpLVH4EN@mSqg1EKgZFDOb0KQvj@966b9OiVQ7DK//8/P541G72RmSF3o3DktAwKiav45ek0JtwDKgX68mu1g/KnNcUdaNAUj2Z4ay2KeWYB4I4B/UDnIA0bf4D "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
def g(s):x=[[a,s/a]for a in range(1,s)if s%a==0];print x[len(x)/2]
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr@wl2IWgLOhQ@BLxsJCaEJuogb3eZtJXr0eW3k/nIWChvWljeCwTW/9kYIgCmSU4VGOh6KEMrPVsj5SjVGjmdoKNpsX2gFHSW5Goq3X7AQ "Python 2 – Try It Online")
[Answer]
# [SageMath](http://doc.sagemath.org/html/en/index.html), ~~63~~ 60 bytes
```
def f(n):
d=divisors(n)
while len(d)>2:d=d[1:-1]
return d
```
[Try it online!](https://sagecell.sagemath.org/?z=eJwVjMEKwjAQBe_5ikdPCWwPW0PVgP0R8ZYsLpRUtlUPpf9unNswMLkIxNeQHPIt60fXxdbmDt-nzgVzqT6HaUit3jn1_HCwsr2tIjtZDAqt8HwaiWOk80CRiS9X4vH_bLxM6-al2_VAP2EXr-Howg9i9SG5&lang=sage&interacts=eJyLjgUAARUAuQ==)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 7 bytes
```
─h½§_@/
```
[Try it online!](https://tio.run/##y00syUjPz0n7///RlIaMQ3sPLY930P8f@9/Q2IzL0MSEy9yIy8SQy9DC8j8A "MathGolf – Try It Online")
## Explanation
```
─ get a list of all divisors
h½§ get the divisor at the middlemost index
(if length is equal returns the smallest of the two middle elements)
_ duplicate TOS
@ rrot3 (pops input again and places it as the second item from the top)
/ divides the input number by the extracted divisor, giving the other divisor
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~14~~ 12 bytes
```
fsIJcQTs@Q2J
```
[Try it online!](https://tio.run/##K6gsyfj/P63Y0ys5MKTYIdDI6/9/Q2MzAA "Pyth – Try It Online")
* `s@Q2` Starting from the floor of the square root of the input:
+ `f` find the first integer \$T\$ such that:
+ `sIcQT` \$T\$ divides the input
* `cQT` gives the input divided by \$T\$ (ie. the other divisor) so we assign that value to `J`
* The two divisors `T` and `J` are then implicitly printed
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 108 bytes 103 bytes
```
#import<iostream>
int n,a,b,i;main(){for(std::cin>>n;i*i++<=n;)n%i<1?a=i,b=n/i:0;std::cout<<a<<' '<<b;}
```
[Try it online!](https://tio.run/##JcpNDsIgEAbQvadoYpq2FqONSRcw4FkAf/ItGAgdV41nx4Vv/WIp53eMrR2RSq5CyJvUp0/uAJaOlVdBwSQPHqf9leu4yUPrCHaODU6YZ7JsJu5By91bqGD5An01/5c/QuSJhm4gCubb2nJbfw "C++ (gcc) – Try It Online")
`Thanks to callingcat, for -5 bytes`
] |
[Question]
[
Maybe some of you already know this game: you have a collection of jelly beans of different colors. For every color, the bean can have different tastes, some are good and some are bad, and you cannot tell them apart. You have to pick a bean of a given color, and pray you have select a good one.
So, write the shortest program that receives a color of your choice (from a given list), and randomly returns the taste selected. The taste has to be picked from a built-in list. The possible list of inputs and outputs are:
```
Input Output choices [only one from the list]
--------------------------------------------------
green lawn clippings, lime, mucus, pear
yellow rotten eggs, buttered popcorn
blue toothpaste, blue berry
orange vomit, peach
brown canned dog food, chocolate
white stinky socks, tutti-frutti, baby diapers, coconut
```
Rules:
* You can assume that the input is going to be always a color from the input choices.
* Case and trailing spaces and/or newlines do not matter.
* Output must be uniformly random: succesive program executions must yield different results, and the chances of getting a given taste must be the same for all tastes in a list.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program win!
[Answer]
# C#, ~~418~~ ~~313~~ ~~305~~ 271 bytes
```
s=>{var a="lawn clippings,lime,mucus,pear|rotten eggs,buttered popcorn|toothpaste,blue berry|vomit,peach|canned dog food,chocolate|stinky socks,tutti-frutti,baby diapers,coconut".Split('|')["eluaoi".IndexOf(s[2])].Split(',');return a[new System.Random().Next(a.Length)];}
```
Too long even for C# but I can't see how to get it any shorter.
Full/Formatted version:
```
using System;
class P
{
static void Main()
{
Func<string, string> f = s =>
{
var a = "lawn clippings,lime,mucus,pear|rotten eggs,buttered popcorn|toothpaste,blue berry|vomit,peach|canned dog food,chocolate|stinky socks,tutti-frutti,baby diapers,coconut"
.Split('|')["eluaoi".IndexOf(s[2])].Split(',');
return a[new System.Random().Next(a.Length)];
};
Console.WriteLine(f("green"));
Console.WriteLine(f("yellow"));
Console.WriteLine(f("blue"));
Console.WriteLine(f("orange"));
Console.WriteLine(f("brown"));
Console.WriteLine(f("white"));
Console.ReadLine();
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 126 bytes
```
¨¤.•4Õ!Õ•.•QCQΓ^ïTÁÕ#HвΘÊÓΘñ…~çÌùY$J*shÉÉk‹Ú&žвZÍζö<^'¢βŽÚq¡eζd`Ãó¨₅γ!i"v_Ym¤ÓδVË5¥vżQЉøΣγ9∞\L‰,ǝ¦8VÜUт:x+sм•'x'-:'q¡'j¡€.R‡
```
Explanation:
```
¨¤ Get the second to last character of the string
.•4Õ!Õ• Compressed string: "eougwt"
.• .. • Compressed base-27 string
'x'-: Replace "x" with "-" (for tutti-frutti)
'q¡ Split on 'q'
'j¡ Split each on 'j'
€ For each...
.R Select a random element
‡ Transliterate
```
If anyone's wondering, here's the uncompressed string:
```
lawn clippingsjlimejmucusjpearqrotten eggsjbuttered popcornqtoothpastejblue berryqvomitjpeachqcanned dog foodjchocolateqstinky socksjtuttixfruttijbaby diapersjcoconut
```
I can probably compress it more using some clever tricks and the dictionary, though.
[Try it online!](https://tio.run/##AeMAHP8wNWFiMWX//8KowqQu4oCiNMOVIcOV4oCiLuKAolFDUc6TXsOvVMOBw5UjSNCyzpjDisOTzpjDseKApn7Dp8OMw7lZJEoqc2jDicOJa@KAucOaJsW@0LJaw43OtsO2PF4nwqLOssW9w5pxwqFlzrZkYMODw7PCqOKChc6zIWkidl9ZbcKkw5POtFbDizXCpXbDhcK8UcOQ4oCww7jOo86zOeKInlxM4oCwLMedwqY4VsOcVdGCOngrc9C84oCiJ3gnLTonccKhJ2rCoeKCrC5S4oCh//93aGl0ZfVuby1jYWNoZQ "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), 235 bytes
I need to figure out how to compress strings in JS!
```
c=>(a="lawn clippings,lime,mucus,pear|rotten eggs,buttered popcorn|toothpaste,blue berry|vomit,peach|canned dog food,chocolate|stinky socks,tutti-frutti,baby diapers,coconut".split`|`["eluaoi".search(c[2])].split`,`)[new Date%a.length]
```
If that's not "random enough" for your tastes then add 7 bytes replacing `new Date` with `Math.random()`.
```
c=>(a="lawn clippings,lime,mucus,pear|rotten eggs,buttered popcorn|toothpaste,blue berry|vomit,peach|canned dog food,chocolate|stinky socks,tutti-frutti,baby diapers,coconut".split`|`["eluaoi".search(c[2])].split`,`)[Math.random()*a.length|0]
```
---
## Try it
```
f=
c=>(a="lawn clippings,lime,mucus,pear|rotten eggs,buttered popcorn|toothpaste,blue berry|vomit,peach|canned dog food,chocolate|stinky socks,tutti-frutti,baby diapers,coconut".split`|`["eluaoi".search(c[2])].split`,`)[Math.random()*a.length|0]
r=(d=document).createElement("input");r.name="i";r.type="radio";l=d.createElement("label");j="Kiwi,sour_lemon,berryBlue,OrangeSherbet,rootBeer,Coconut".split`,`;for(s in e="green,yellow,blue,orange,brown,white".split`,`){r=r.cloneNode();l=l.cloneNode();l.setAttribute("for",r.id=r.value=e[s]);l.style.backgroundImage=`url(https://cdn-tp1.mozu.com/9046-11441/cms//files/${j[s]}.jpg)`;g.prepend(r,l);}onchange=_=>o.innerText=(v=(i=d.querySelector(":checked")).value)+": "+f(v,i.checked=0)
```
```
body{align-items:center;background:#eee;display:flex;flex-wrap:wrap;height:100vh;justify-content:center;margin:0;text-align:center;}#g{background:#fff;box-shadow:5px 5px 5px #ccc;padding:10px;}input{display:none;}label{background-repeat:no-repeat;background-size:contain;cursor:pointer;display:inline-block;height:64px;margin:10px;width:75px;}#o{font-family:monospace;font-size:18px;margin:10px auto;text-align:center;width:100%;}
```
```
<div id=g><pre id=o>click a jelly bean</pre></div>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~101~~ 100 bytes
```
3ị“©ȷ#Ȧ-»iị“'æLṬẏeṃɼẹ-N0ṁH)A“¬ɗ-ṃȥḞ“I$aṇṾjð4“£Ʋṛ÷pḶƥƑL]p“÷Hnøgİỵ£@ḥEḶƑƤi÷Ḃ\oŻẆ#ụqU½b“ḥĠḄĿĖṇ⁻Œḳ-¬"»ỴX
```
[Try it online!](https://tio.run/##y0rNyan8/9/44e7uRw1zDq08sV35xDLdQ7szIQLqh5f5PNy55uGu/tSHO5tP7nm4a6eun8HDnY0emo4g9WtOTtcFSpxY@nDHPCDfUyXx4c72hzv3ZR3eYAKSX3xs08Odsw9vL3i4Y9uxpccm@sQWAIUPb/fIO7wj/ciGh7u3Hlrs8HDHUleQ/MRjSzIPb3@4oykm/@juh7valB/uXloYemhvElALUM2RBQ93tBzZf2Qa0IpHjbuPTnq4Y7PuoTVKh3Y/3L0l4v///5VAv@SXf83L101OTM5IBQA "Jelly – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 148 146 bytes
```
`È}hpŠ1½ue ¼rry
lawn c¦ppÄ1Ò˜1muc«1pe‡
vÇ1pea®
ÐXky socks1ÉÍi-frÔk1baby ¹ap€s1¬¬n©
¯nšd ºg food1®o¬ÓŠ
Î eggs1瘪 pop¬rn`·g`uÁ4`âUg2¹q1 ö
```
[Try it online!](https://tio.run/##DcwxT8JAGAbgxPEWd6cv7Awf4a@YOPY4jitW786WQjqYgCFBSTRGHYijg0atuGkwurzfb2KubM/0HOs4appELs/TKBdYMv5KS/jN80qd6Ikng@cYZb7PcocVn5YG7xwtFmosi4OdNNZKbo@yiopgsoLlSq6H7UEuDxn3dK8ibHTEtGDUqD1eFT49HvuEH0eDEPqMdUAt91gqucEHZmSd2zUvWOFtj2KIqHOf4Nslpcy6iTwdug42Z0zy1TStSToc2dbWh7bRJrX/ "Japt – Try It Online")
Saved 6 bytes thanks to Shaggy and ETHproductions
[Answer]
# [Python 2](https://docs.python.org/2/), ~~301~~ 258 bytes
```
lambda x:choice({'e':'lawn clippings,lime,mucus,pear','l':'rotten eggs,buttered popcorn','u':'toothpaste,blue berry','a':'vomit,peach','o':'canned dog food,chocolate','i':'stinky socks,tutti-frutti,baby diapers,coconut'}[x[2]].split(','))
from random import*
```
[Try it online!](https://tio.run/##FY6xbsMwDET3foU224XSIWOAfkkaBJJM20RkUqCoJkbRz@7s0hOJu8fjlU0XpvM@fX7tOaxxDO51SQtjgv6ng@7S5fAklzKWgjRXn3EFv7bUqi8QpPNdNkhYFcjBbERstguMrnBJLGRIM0SZdSmhKviYG7gIIpt5wbxvXlGPvLSYwqakQGQRI89uYh69VUqcg4L5aH5VpMfmKqdH9Wof8TTJMXwMcXMjhgJSfbIratr9Xl/X8@32UUtG7S1jGN4m4dVJoNEGroVF3/ciSOqmXsLzjlSa9sOwH3X/iE/J6sE/ "Python 2 – Try It Online")
Saved very many bytes by shortening the keys to use the 2nd index of the input, as suggested by @TheLethalCoder, and by splitting on commas instead of using a direct list.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~95~~ 94 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OḄị“÷Hnøgİỵ£@ḥEḶƑƤi÷Ḃ\oŻẆ#ụqU½b““¬ɗ-ṃȥḞ“'æLṬẏeṃɼẹ-N0ṁH)A“ḥĠḄĿĖṇ⁻Œḳ-¬"““I$aṇṾjð4“£Ʋṛ÷pḶƥƑL]p»ỴX
```
A monadic link accepting a list of (lowercase) characters and returning a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8/9//4Y6Wh7u7HzXMObzdI@/wjvQjGx7u3nposcPDHUtdH@7YdmzisSWZh7c/3NEUk39098NdbcoPdy8tDD20NwmoBYgOrTk5XffhzuYTSx/umAfkqx9e5vNw55qHu/pTgaIn9zzctVPXz@DhzkYPTUegNNDUIwuAVh7Zf2Taw53tjxp3H530cMdm3UNrlCDmeaokAsUf7tyXdXiDCcj8xcc2Pdw5@/D2ApBjlh6b6BNbcGj3w91bIv7//59elJqa9zUvXzc5MTkjFQA)** or eat a [packet of 48](https://tio.run/##JU89S8NQFP0vKohDwMHBUQexQtFJcNAhKY@0JSQ1KKGbrWKHDlIHHfxAqHHKUNSa9/KqwntJsD/j5D84xxuEC@eec@899942c5xuWe6BX0AOi7N7Hddcze10AjlV4w3wcAv8Ix/lzy0dg/cPvUwiuVyEDI/31adFIxQqmt8aEOc/Ifgj8WX9UoeIkFwxUuczJMLYXYXo1VY2qUyu6ROtTL/TG4hB0ZPZNfiboaKFf7@dJZN0iK@2nqxV/uP8FeJOx53qmDAf1Y86SkK@H5RUtX3GXMIuPeMFlFjOKSPwfNO1q8TyvaBqCJqtE@IPSIbraprN9KDoR9vlr@sZDbPRZH8).
### How?
Eighty-nine of the ninety-four bytes are a compressed list of eight strings. Two of these are empty strings and the other six are each newline separated flavours for one of the colours:
```
“...““...“...“...““...“...»
“...““...“...“...““...“...»
“ » - a compression of dictionary words & or strings
““ “ “ ““ “ - list separations
^ ^ - the two empty lists of characters
...^ ... ... ...^ ... ... - bytes used to encode the data
wht org grn ylw^ blu brn - with the colours indicated. For example:
1 2 3 4 5 6 7 0 - “ḥĠḄĿĖṇ⁻Œḳ-¬"» is a compression of:
- word + word + string + word + word
- "rotten" + " egg" + "s\n" + "buttered" + " popcorn"
- and is at the fifth index, relating to "yellow"
```
The rest of the program parses the input to decide which list to use, splits the chosen list by newlines and picks a random element:
```
OḄị“...»ỴX - Main link:s e.g.: "blue" "yellow" "brown" "white" "orange" "green"
O - cast to ordinals [98,108,117,101] [121,101,108,108,111,119] [98,114,111,119,110] [119,104,105,116,101] [111,114,97,110,103,101] [103,114,101,101,110]
Ḅ - from binary 3276 7125 1151 6899 3272 3489
ị - index into - 1 based and modular with 8 items so...
- indexes: 3276%8=4 7125%8=5 1151%8=7 6899%8=3 3272%8=0 3489%8=1
Ỵ - split at newlines (gets the list of flavours for the chosen colour)
X - random choice (gets one of those flavours at random)
```
[Answer]
# Java, 288 bytes
```
s->{String[]a="lawn clippings,lime,mucus,pear#rotten eggs,buttered popcorn#toothpaste,blue berry#vomit,peach#canned dog food,chocolate#stinky socks,tutti-frutti,baby diapers,coconut".split("#")["eluaoi".indexOf(s.charAt(2))].split(",");return a[new java.util.Random().nextInt(a.length)];}
```
[Test it yourself!](https://tio.run/##dZFBi9swEIXv@ysG@2ITR5Q9NpuFsrDQQyl0jyEHWZZtJfKMkEbJmiW/PZUdZ9tDe3pC8@ab0dNBnuSanMZDc7y6WFujQFkZAvyQBuHjAWC5DSw5yYlMA0OqFW/sDXa7PUjfhXK2AhwST0Q2VrQRFRtC8bocnm4N1U2eoYXtNayfP@4cuc2sPGMab5xLN6GyZtDVEFUMldPS556YNYLuUq2O6ex1A46cIo85E3HvZGBd1TZqqLX3Y36iwfDUrfpcScTU0FAHLVFTqZ4UWck6D2zwOEIgdQwVJ7JZt36Sqpb1CI2RTvtQqeTHyJkIzhousjwrd5m2UZLJhMFGv/9siyBUL/03Lh7Lcn93Vlm58ZqjR5A71Oe/cvolsaGhKAXqd/6OXEhhNXbcl/vN5TplupmTbcnDkjmktcl/hazzOuUxamvpDPOryUvs0uM9pSTPvWH9uS1k5f2XAN7GFNQgKLJwCckWi@xlocLqNqDcLOZ5dDKBgS182SR5gsdJV6s/xH8zYca1Qjpnx@KG/eRe/r/M4pkcl4fL9Tc)
Could be golfed by using a `char[]`.
However the random part can't be "uniformly distributed" without the explicit use of `Random.nextInt(int)`. Even `(int)(Math.random()*a.length)` isn't uniformly distributed.
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 311 bytes
```
</"y"/\_ _
v\i-?\x"sgge nettor"
v/"l"/\"nrocpop derettub"
v\i-?\x"etsaphtoot"
v/"o"/\"yrreb eulb"
v\i-?\x"etalocohc"
v/"n"/\"doof god dennac"
v\i-?\x"timov"
v/"n"/\"hcaep"
v\i-?\>x\/~~"srepaid ybab"
v"lime" x"sgnippilc nwal"
v"pear"x _"sucum"
v \~__>x\
v"coconut" x"skcos yknits"
>l?!;/\ \x_"itturf-ittut"
```
[Try it online](https://tio.run/##Vc/NboQgEAfw@z7FdO7GB2iz@yIkBsdRyCJDAF29@NY9WzBpN@VCwv/HfIw2mfP8anHHVnUA3W1VtnmoDdM0MXjOWSLe1hZdAeijUJAAA8eSLD3@cc5JB5NF8qWl6j1G7oEX989pJySGLuYrG0RGmGQoVb3X9LbZzrK@nSHN4Te9b6o9DkyRg7YD7L2uTdDZmRHq9N6GYB2Bf2lXk8A64lY2xLTQMpcnKEcdXVdKlZzKVH7J1@cnSYL96W1OeLu7x8dnq4rdOrRl6zg29cp4ni9jM397aUiT4R8 "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)
Featuring SK cosy knits and Doof God Dennac!
Explanation: The fish's first task is to figure out what the input word is by zig-zagging down the left hand side. The fish can only read one letter at a time, and it takes fewer bytes to do this destructively. First, the fish reads the first letter and asks if it's `"y"` — if it is, the word is "yellow", otherwise it moves on. It then reads the second letter — if it's `"l"`, the word is "blue", otherwise it moves on; and so on. If it reads five letters and they don't match `"y"` (**Y**ellow), `"l"` (b**L**ue), `"o"` (br**O**wn), `"n"` (ora**N**ge) or `"n"` (gree**N**) respectively, then the colour must have been "white".
Next comes the random bit. For the colours with two possible outputs, this is pretty straightforward — for yellow, for example, the fish enters the following code at the `x`:
```
/\
\x"sgge nettor"
\"nrocpop derettub"
```
The `x` sets the direction randomly: if it's up or left, the fish swirls around the mirrors back to the `x`, but if it's right or down, it reads "rotten eggs" or "buttered popcorn" (in reverse).
The four-way splits (for white and green) are messier, but they follow the same general principal — the first is:
```
>x\
"lime" x"sgnippilc nwal"
"pear"x "sucum"
__
```
Note that if the fish swims up from the first `x`, it passes through eight `"`s, which toggle string mode on and off four times, then it hits a mirror and swims back down.
To get to the last four-way split, the fish has to swim through the `e` and `r` of "lime" and "pear", which add `e = 14` to the stack (and reverse it), so we first have to delete that with `~`. One of the four branches also involves swimming through a junk string, `"> "`, which we delete with `~~`.
```
\ /~~"srepaid ybab"
e "
r _
\~ >x\
"coconut" x"skcos yknits"
\x_"itturf-ittut"
_
```
Finally, after adding one of the bean flavours to the stack, the fish reaches the stream of `v`s in the leftmost column, which sends it to
```
v \
v o
>l?!;/
```
which prints characters (using one of the `o`s in "coconut") until there are none left.
[Answer]
# T-SQL, ~~432 423 375 367 336~~ 295 bytes
Finally, a set-based operation!!
```
SELECT TOP 1 SUBSTRING(value,2,99)
FROM t,STRING_SPLIT('elawn clippings-elime-emucus-epear-lrotten eggs-lbuttered popcorn-utoothpaste-ublue berry-avomit-apeach-ocanned dog food-ochocolate-istinky socks-itutti-frutti-ibaby diapers-icoconut','-')
WHERE SUBSTRING(c,3,1)=LEFT(value,1)
ORDER BY NEWID()
```
(Line breaks are for display and are not counted in total.)
Input is via column **c** in named table **t**, [per our guidelines](https://codegolf.meta.stackexchange.com/a/5341/70172).
I'm simply joining our input table to a table full of the valid color/flavor combinations, then selecting a random row. `ORDER BY NEWID()` is [a common way to randomize sort order in SQL](https://dba.stackexchange.com/questions/955/what-is-the-best-way-to-get-a-random-ordering). Depending on how strict you are, you might not consider it perfectly uniformly random, but it should be sufficiently random for jelly bean selection.
**EDIT 1:** Saved 9 bytes by using only the 3rd character of the color, inspired by other answers.
**EDIT 2:** Saved **48** bytes by putting the color flag and flavor in a single column. Lots of characters saved in the INSERT.
**EDIT 3:** Saved 8 bytes by replacing `INSERT INTO b(o)` with `INSERT b`
**EDIT 4:** Saved 31 more bytes by joining straight to the virtual table of `VALUES` and therefore eliminating the `CREATE TABLE` and `INSERT`.
**EDIT 5:** Save 41 bytes by upgrading to SQL 2016-only `STRING_SPLIT` function, which allows me to eliminate the variable and dynamic SQL execution.
[Answer]
# [PHP](https://php.net/), 242 bytes
```
<?=($a=explode(_,[e=>'lawn clippings_lime_mucus_pear',l=>'rotten eggs_buttered popcorn',u=>'toothpaste_blue berry',a=>vomit_peach,o=>'canned dog food_chocolate',i=>'stinky socks_tutti-frutti_baby diapers_coconut'][$argn[2]]))[array_rand($a)];
```
[Try it online!](https://tio.run/##HY@xbsMwDET3fIUQBFAMKEvX1M6HGIZAS4wtRCYFSmrrD@/sKp1I8N7xcGlNx@cjrel0AVmoPy@CSOf76TG0e3@9QI8/KbLHqzUj9oOO8E3KxZBSoCXbGDa0W3U124Qg2sTGCJeCpHBpwFzbLuhV4uRYSJvaiMJc1gS5oJ1jRTWjyK4N9MMXb6G8f7nVcCMdEDW350U9mb11KzuOUFCb0ORcAr12ldm9si0tK9ye8h52hnlXPkBCydY1E9Wip/G/5/gxTV03ggjsVoB8K9pN9@P4Jb65Fo1/ "PHP – Try It Online")
[Answer]
# Mathematica, 247 bytes
```
R=RandomChoice
green=R@{lawn clippings,lime,mucus,pear}
yellow=R@{rotten eggs,buttered popcorn}
blue=R@{toothpaste,"blue berry"}
orange=R@{vomit,peach}
brown=R@{canned dog food,chocolate}
white=R@{stinky socks,tutti-frutti,baby diapers,coconut}
#&
```
**Input** form
>
> [green]
>
>
>
[Answer]
# Clojure, 231 bytes
```
#(rand-nth({\e["lawn clippings""lime""mucus""pear"]\l["rotten eggs""buttered popcorn"]\u["toothpaste""blue berry"]\a["vomit""peach"]\o["canned dog food""chocolate"]\i["stinky socks""tutti-frutti""baby diapers""coconut"]}(get % 2)))
```
Same idea as the others, I can just save some space compared to other languages. Compressing strings seems like a lost cause.
] |
[Question]
[
I often forget what I wanted to say when the teacher calls on me to speak. Can you make me a tool to solve this?
Requirements:
* The program must loop as follows:
+ First, take in input
+ If the input is empty, print the last stored question.
+ Otherwise, store the input as a question.
Notes:
* The input will never be empty if there are no questions stored.
Clarification: **The program does not need to store multiple questions.** I originally wanted it to store multiple, but I changed it after many people misunderstood the question.
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.
[Answer]
# Perl, ~~13~~ ~~17~~ 14 +1 = 15 bytes
```
/./?$;=$_:say$
```
+1 for the `-n` flag
(saved 4 bytes thanks to @Dada)
As long as the input is not equal to the carriage return, it stores the input in `$;`. If it is equal to the carriage return, it prints what's already in `$;`.
This assumes that all input can be characterized as questions, even if grammatically, they are not such.
[Answer]
# 05AB1E, ~~12~~ ~~11~~ 10 bytes
Thanks @daHugLenny and @Adnan for 1 byte!
Thanks @Emigna for 1 byte!
```
[IDõQiX,ëU
```
[Answer]
## Haskell, 49 bytes
```
g s=getLine>>=(#s)
""#s=putStr s>>g s
l#s=g l
g""
```
How it works: start with `g ""`. The parameter `s` of function `g` is the question in store. `g` reads the next line from stdin and passes it (and also s) to `#`. If the line is empty, `#` prints the store and calls `g` again. If the line is not empty, `g` is called with the line as the new store.
[Answer]
# JavaScript, ~~36~~ ~~34~~ 31 bytes
```
for(;;b?a=b:alert(a))b=prompt()
```
An infinite loop keeps asking for input and stores it in `b`. It the input is not empty it's then stored in `a`, otherwise the value of `a` is printed.
Saved 2 bytes thanks to @ETHproductions
[Answer]
# Mathematica, 44 bytes
```
If[(b=InputString[])=="",Print@a,a=b]~Do~∞
```
Full program. The Unicode character is U+221E INFINITY for `\[Infinity]`.
[Answer]
## Python 3, 31 bytes
```
while 1: I=input()or I;print(I)
```
[Try it out!](http://ideone.com/6B90xU)
-1 byte thanks to Flp.Tkc
[Answer]
# reticular, 12 bytes
```
id""E[$dp]~*
```
[Try it online!](http://reticular.tryitonline.net/#code=aWQiIkVbJGRwXX4q&input=SGVsbG8_CldoZXJlIGFtIEk_CmlkawoKb2gsIHRoYW5rcwp3ZWxsLCBzbyB0aGVyZSdzIHRoYXQKaHVoPyB3aGF0J3MgcmV0aWN1bGFyPwoKb2gsIHRoYXQncyBteSBxdWVzdGlvbi4gY29vbC4KCi4uLiE)
## Explanation
```
id""E[$dp]~*
i take a line of input [input]
d""E push equality with "" [input, input == ""]
[$dp] push that func [input, input == "", [$p]]
~* execute it iff equal
on equal:
$ drop empty input
dp duplicate then print the TOS
this wraps around to the beginning, taking another line of input
```
[Answer]
## Pyke, 6 bytes
```
z=z~zr
```
[Try it here!](http://pyke.catbus.co.uk/?code=z%3Dz%7Ezr&input=%3F%3F%3F%0A%0A%0Ahi%0Awhat%3F%0A%0A%3F)
```
r - while 1:
z - input() or z.contents
=z - z.contents = ^
~z - z.contents
```
[Answer]
# Python3 - 49 bytes
```
s=""
while 1:
b=input()
if b:s=b
else:print(s)
```
[Answer]
## Python 3, 34 bytes
```
s=""
while[print(s)]:s=input()or s
```
[Answer]
# Python 3, 60 bytes
```
q=[]
while 1:
s=input()
if''<s:q+=[s]
else:print(q.pop())
```
[Answer]
# CMD, 37 bytes
Sadly `set` does not take empty input:(
```
set/p a=
if %a%.=. echo b
set b=%a%
c
```
in a file names `c.cmd` or
```
set/p a=
if %a%.=. echo b
set b=%a%
%0
```
in any file. Working(Use `-` as empty):
```
set/p a=
if %a%.=-. echo b
set b=%a%
c
```
[Answer]
# APLX, 19 bytes
```
a←⍞⋄→(0=⍴a)/1⋄a⋄→1
```
### Explanation:
```
⍝ Note: the ⋄ symbols are statement separators, so I've replaced them here with newlines
a←⍞ ⍝ get an input string (⍞) and store it in variable a
→(0=⍴a)/1 ⍝ if the length of a (⍴a) is 0, goto (→) the start of this program (1)
a ⍝ else, print a
→1 ⍝ goto the start of the program (1)
```
[Answer]
# C, ~~73~~ 63 bytes
```
g(){char a[99],x;for(;;){gets(a);if(*a)x=*a;else*a=x,puts(a);}}
```
Only uses 1 buffer and a single char for handling the logic. If user inputs nothing, only the first char in the buffer gets overwritten by `'\0'`, in that case it gets restored from `x` and printed, otherwise copy the first letter into `x` for later use.
Previous code:
```
main(){char a[99],b[99];for(;;){gets(a);if(*a)strcpy(b,a);else puts(b);}}
```
[Answer]
# Java 7, ~~189~~ ~~187~~ 178 bytes..
```
class M{public static void main(String[]a){String s="",x;do{x=new java.util.Scanner(System.in).nextLine();if(x.isEmpty())System.out.println(s);else s=x;}while(1>0);}}
```
-9 bytes by using `new java.util.Scanner` directly, thanks to *@cliffroot*.
Probably the first time I used a `do-while` in a codegolf challenge..
When functions are allowed instead of programs, it's **135 bytes** (still many times more than most other answers..)
[Answer]
# sed, 10 bytes
```
/./{x;d};g
```
Explanation:
```
(implicit at start of program) read input, overwriting old input
/./{ If the input is nonempty
x; swap the input with the hold space
d then restart, without any implicit printing of input
}; end if statement
g Append the hold space to the [empty] input
(implicit at end of program) print the input, then restart
```
Nice to see an exoteric (i.e. "not esoteric") language tying with some of the golfing languages!
] |
[Question]
[
*Inspired by [this question](https://stackoverflow.com/q/37462443/670206) and refined by [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo).*
## Challenge
Given a 2D matrix of integers, each row has a maximum value. One or more elements of each row will be equal to the maximum value of their respective row. Your goal is to determine which column(s) contain the most entries which are equal to their respective row's maximum value as well as the number of row-wise maxima found in these columns.
## Input
* The input will be a non-empty `M` x `N` matrix (`M` > 0 and `N` > 0) in whatever form is well-suited to your language of choice.
## Output
* Your program should return the *index* of each column containing the maximum number of row-wise maxima (either as separate values or a list). Either 0- or 1-based indexing can be used (specify in your description).
* Your program should also return the number of maxima that were present in these columns (a single number).
* The order/format of the output is flexible but should be explained in the text accompanying your answer.
## Additional Information
* All entries in the input matrix will be positive integers.
* If the maximum value of a row is shared by multiple elements in that row, all
occurrences of that value count towards their columns' total.
* If multiple columns contain the same number of maxima, you should return a list of *all* columns
which had this number of maxima.
## An Example
Consider input
```
7 93
69 35
77 30
```
Row 1 has maxium 93, which occurs only once, namely at column 2. Row 2: occurs at column 1. Row 3: also at column 1. So the winner column is 1, with 2 maxima. Thus the output will be `[1] [2]`. If we change the input to
```
7 93
69 35
77 77
```
the output will be `[1 2] [2]`, because both columns have 2 maxima.
## Test Cases
```
input => output ( [1-based index array], [nMaxima] )
----------------------------------------------
7 93
69 35 => [1], [2]
77 30
7 93
69 35 => [1 2], [2]
77 77
1 2 3 4 => [4], [2]
5 6 7 8
16 2 3 13
5 11 10 8 => [1 2 4], [1]
9 7 6 12
1 1 1 1 => [1 2 3 4], [1]
25 6 13 25 => [1 4], [1]
1
2
3 => [1], [4]
4
100 => [1], [1]
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. Tiebreaker goes to the earlier answer.
## Leaderboard
Below is a stack snippet for analyzing all entries.
```
var QUESTION_ID=80788,OVERRIDE_USER=51939;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]
## J, 27 bytes
```
((I.@:=;])>./)@(+/@:=>./"1)
```
This is a monadic verb, used as follows in the case of the second example:
```
f =: ((I.@:=;])>./)@(+/@:=>./"1)
m =: 3 2 $ 7 93 69 35 77 77
f m
+---+-+
|0 1|1|
+---+-+
```
The output consists of two boxes, and uses 0-based indexing. [Try it here!](http://tryj.tk/)
## Explanation
```
((I.@:=;])>./)@(+/@:=>./"1) Input is m.
( )@( ) Composition: apply right hand side, then left hand side.
>./"1 Take maximum of each row of m.
= Replace row maxima by 1 and other values by 0,
+/@: then take sum (number of maxima) on each column.
The result is the array of number of row maxima in each column.
>./ Compute the maximum of this array
( ;]) and put it in a box with
I.@:= the indices of those entries that are equal to it.
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
="Ṁ€SµM,Ṁ
```
Input is a 2D list, output is a pair: a list of 1-based indices and the maximal number of maxima.
[Try it online!](http://jelly.tryitonline.net/#code=PSLhuYDigqxTwrVNLOG5gA&input=&args=W1sxNiwgICAyLCAgIDMsICAxM10sCiBbIDUsICAxMSwgIDEwLCAgIDhdLAogWyA5LCAgIDcsICAgNiwgIDEyXV0) or [verify all test cases](http://jelly.tryitonline.net/#code=PSLhuYDigqxTwrVNLOG5gArDh-KCrOG5hOKCrOG5m-KAnA&input=&args=W1s3LDkzXSxbNjksMzVdLFs3NywzMF1dLCBbWzcsOTNdLFs2OSwzNV0sWzc3LDc3XV0sIFtbMSwyLDMsNF0sWzUsNiw3LDhdXSwgW1sxNiwyLDMsMTNdLFs1LDExLDEwLDhdLFs5LDcsNiwxMl1dLCBbWzEsMSwxLDFdXSwgW1syNSw2LDEzLDI1XV0sIFtbMV0sWzJdLFszXSxbNF1dLCBbWzEwMF1d).
### How it works
```
="Ṁ€SµM,Ṁ Main link. Argument: M (matrix)
Ṁ€ Apply maximum to each row.
=" Zipwith equal; compare the entries of the nth row with its maxmium.
S Sum; reduce across columns to count the maxima in each row.
µ Begin a new, monadic link. Argument: A (list of maxima)
M Yield all indices with maximal value.
Ṁ Yield the maximum of A.
, Pair the results to both sides.
```
[Answer]
# MATL, 17 bytes
```
vH3$X>G=XstX>tb=f
```
The first output is the max number of maxima and the second output is the columns in which this occured (1-based indexing).
[**Try it Online!**](http://matl.tryitonline.net/#code=dkgzJFg-Rz1Yc3RYPnRiPWY&input=WzE2IDIgMyAxMzsgNSAxMSAxMCA4OyA5IDcgNiAxMl0K)
**Explanation**
```
v % Vertically concatenate everything on the stack (nothing), yields []
% Implicitly grab the input
H % Push the number 2 to the stack
3$X> % Compute the maximum value of each row (along the second dimension)
G % Explicitly grab input again
= % Compare each row of the input to the row-wise max (automatically broadcasts).
Xs % Sum the number of matches in each column
t % Duplicate the array
X> % Determine the max number of maxima in all columns
t % Duplicate this value
b=f % Find the index of the columns which had the maximum number of maxima
% Implicitly display stack contents
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
!tvX>!G=5#fFTT#XM
```
Input is a 2D array, with rows separated by semicolons. So the inputs for the test cases are
```
[7 93; 69 35; 77 30]
[7 93; 69 35; 77 77]
[1 2 3 4; 5 6 7 8]
[16 2 3 13; 5 11 10 8; 9 7 6 12]
[1 1 1 1]
[25 6 13 25]
[1; 2; 3; 4]
[100]
```
Output is: first the maximum amount of maxima, then one or more column indices.
[**Try it online!**](http://matl.tryitonline.net/#code=IXR2WD4hRz01I2ZGVFQjWE0&input=WzE2IDIgMyAxMzsgNSAxMSAxMCA4OyA5IDcgNiAxMl0K)
### Explanation
This uses a different approach from [Suever's answer](https://codegolf.stackexchange.com/a/80799/36398).
First a matrix of logical values (`true` and `false`) is computed, where `true` indicates the presence of a row-maximum. Then the column indices of the `true` values are extracted into a vector. Finally, the mode of that vector is computed (maximum number of maxima), along with all values that are the most frequent (desired column indices).
```
! % Implicit input. Transpose
tv % Duplicate. Concatenate vertically. This forces next function (max)
% to work along columns even if input is a row vector
X> % Maximum of each column (gives row vector)
! % Transpose into column vector
G % Push input again
= % Test for equality, with broadcast. Gives matrix of true and false
5#f % Column indices of true values, as a column vector
FTT#XM % Mode of that vector, and all values that occur maximum number of times
% Implicit display
```
[Answer]
# Pyth, ~~20~~ ~~19~~ 17 bytes
1 byte thanks to [@Suever](https://codegolf.stackexchange.com/users/51939/suever).
1 byte thanks to [@Jakube](https://codegolf.stackexchange.com/users/29577/jakube).
```
{MC.MhZrSsxLeSdQ8
```
[Test suite.](http://pyth.herokuapp.com/?code=%7BMC.MhZrSsxLeSdQ8&test_suite=1&test_suite_input=[[7%2C93]%2C[69%2C35]%2C[77%2C30]]%0A[[7%2C93]%2C[69%2C35]%2C[77%2C77]]%0A[[1%2C2%2C3%2C4]%2C[5%2C6%2C7%2C8]]%0A[[16%2C2%2C3%2C13]%2C[5%2C11%2C10%2C8]%2C[9%2C7%2C6%2C12]]%0A[[1%2C1%2C1%2C1]]%0A[[25%2C6%2C13%2C25]]%0A[[1]%2C[2]%2C[3]%2C[4]]%0A[[100]]&debug=0)
Output is 0-indexed.
Order is reversed.
### All inputs
```
[[7,93],[69,35],[77,30]]
[[7,93],[69,35],[77,77]]
[[1,2,3,4],[5,6,7,8]]
[[16,2,3,13],[5,11,10,8],[9,7,6,12]]
[[1,1,1,1]]
[[25,6,13,25]]
[[1],[2],[3],[4]]
[[100]]
```
### All outputs
```
[[2], [0]]
[[2], [0, 1]]
[[2], [3]]
[[1], [0, 1, 3]]
[[1], [0, 1, 2, 3]]
[[1], [0, 3]]
[[4], [0]]
[[1], [0]]
```
## How it works
```
{MC.MhZrSsxLeSdQ8
Q Yield input.
L For each array in input (as d):
eSd Yield maximum of d.
x Yield the 0-indexed indices of the maximum in d.
s Flatten.
S Sort.
r 8 Run-length encoding.
Now the array is:
[number of maxima in column, index of column]
for all the columns
.MhZ Yield the sub-arrays whose first element is maximum.
The first element of each sub-array
is "number of maxima in column".
Now the array is:
[number of maxima in column, index of column]
for all the required columns
C Transpose.
Now the array is:
[[number of maxima in each column],
[index of each required column]]
Note that every element in the
first sub-array is the same.
{M Deduplicate each.
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), ~~38~~ ~~35~~ 31 bytes
*2 bytes fewer thanks to @FryAmTheEggMan, with help also from @quartata. Thanks also to @Dennis for removing 4 more bytes.*
```
q~_::e>.f=:.+_:e>_@f{=U):Ua*~}p
```
Input is of the form
```
[[7 93] [69 35] [77 77]]
```
Output is an array of 1-based column indices and a number.
[**Try it online!**](http://cjam.tryitonline.net/#code=cX5fOjplPi5mPTouK186ZT5fQGZ7PVUpOlVhKn59cA&input=W1sxNiAgIDIgICAzICAxM10gWzUgIDExICAxMCAgIDhdIFs5ICAgNyAgIDYgIDEyXV0K)
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~18~~ ~~16~~ ~~19~~ 16 bytes
```
SṠ·e;¥▲mΣTmṠom=▲
```
[Try it online!](https://tio.run/##yygtzv7/P/jhzgWHtqdaH1r6aNqm3HOLQ3KBAvm5tkDe////o6PNdSyNY3WizSx1jE2BtLm5jrFBbCwA "Husk – Try It Online")
Probably my best use of combinators in Husk.
-2 bytes from Jo King.
+3 bytes after satisfying first test case.
-3 bytes from Jo King(again!)
## Explanation
```
§eṠoW=▲o;▲mΣTmṠom=▲
m map each row to the following:
Ṡ hook: Ṡ f g x = f (g x) x
m= map each element of the row by equality
▲ to the maximum of the row
T transpose the matrix
mΣ map each column to its sum
§ fork: § f g h x = f (g x) (h x)
e create two element list from:
Ṡ hook: Ṡ f g x = f (g x) x
oW= indices of elements wich equal
▲ maximum, and:
o;▲ number of maxima
```
[Answer]
## Pyke, 17 bytes
```
FDSeRmq),AsDSe
R%
```
[Try it here!](http://pyke.catbus.co.uk/?code=FDSeRmq%29%2CAsDSe%0AR%25&input=%5B%5B7%2C93%5D%2C%5B69%2C35%5D%2C%5B77%2C77%5D%5D)
[Answer]
# Python 2, 106 bytes
```
x=map(sum,zip(*[map(max(r).__eq__,r)for r in input()]))
m=max(x);print[i for i,n in enumerate(x)if n==m],m
```
Input is a 2D list of floats, output is a pair: a list of 0-based indices and an integer.
Test it on [Ideone](http://ideone.com/AMM9Sk).
[Answer]
# Julia, 54 bytes
```
f(x,m=maximum,t=sum(x.==m(x,2),1))=find(t.==m(t)),m(t)
```
Input is a matrix, output is a pair: a list of 1-based indices and the maximal number of maxima.
[Try it online!](http://julia.tryitonline.net/#code=Zih4LG09bWF4aW11bSx0PXN1bSh4Lj09bSh4LDIpLDEpKT1maW5kKHQuPT1tKHQpKSxtKHQpCgpmb3IgeCBpbiAoWzcgOTM7NjkgMzU7NzcgMzBdLFs3IDkzOzY5IDM1Ozc3IDc3XSxbMSAyIDMgNDs1IDYgNyA4XSwKWzE2IDIgMyAxMzs1IDExIDEwIDg7OSA3IDYgMTJdLFsxIDEgMSAxXSxbMjUgNiAxMyAyNV0sWzE7MjszOzRdLFsxMDBdKQogICAgcHJpbnRsbihmKHgpKQplbmQ&input=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 (or 12) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εZQ}øOZ©Qƶ0K®‚
```
Outputs in the format `[[1-indexed columns-list], maxima]`.
[Try it online](https://tio.run/##yy9OTMpM/f//3NaowNrDO/yjDq0MPLbNwPvQukcNs/7/j442NNMx0jHWMTSO1Yk21TE01DE00LEAsi11zHXMdAyNYmMB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1ujAmsP7/CPOrQy8Ng2A@9D6x41zPqv8z86Otpcx9I4VifazFLH2BRIm5vrGBvExuooYJMxN4fIGOoY6RjrmAAFTXXMdMx1LKDCZmBxQ2OwhKGhjqEBUEon2hKoxEzH0AimGQwhHCOQAYbGOkamUEmgciMgBhlhAhUyALonFgA).
If it's allowed to have items `0` in the columns-list which we ignore, it could be 2 bytes less by removing the `0K`:
[Try it online](https://tio.run/##yy9OTMpM/f//3NaowNrDO/yjDq0MPLbt0LpHDbP@/4@ONjTTMdIx1jE0jtWJNtUxNNQxNNCxALItdcx1zHQMjWJjAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1ujAmsP7/CPOrQy8Ni2Q@seNcz6r/M/OjraXMfSOFYn2sxSx9gUSJub6xgbxMbqKGCTMTeHyBjqGOkY65gABU11zHTMdSygwmZgcUNjsIShoY6hAVBKJ9oSqMRMx9AIphkMIRwjkAGGxjpGplBJoHIjIAYZYQIVMgC6JxYA).
**Explanation:**
```
ε # Map each row in the (implicit) input-matrix:
Z # Get the maximum of the row (without popping)
Q # Check for each value in this row if its equal to the row-maximum
}ø # After the map: zip/transpose the matrix; swapping rows/columns
O # Take the sum of each inner list (the truthy/falsey values of the columns)
Z # Get the maximum column-sum (without popping)
© # Store it in the register (without popping)
Q # Check for each column-sum if its equal to this maximum
ƶ # Multiply each truthy/falsey value in the list by its 1-based index
0K # Remove all 0s
®‚ # Pair the resulting list with the maximum we stored in the register
# (and output the result implicitly)
```
[Answer]
## JavaScript (ES6), 111 bytes
```
a=>[m=Math.max(...a=a[0].map((_,i)=>a.map(a=>c+=a[i]==Math.min(...a),c=0)|c)),[...a.keys()].filter(i=>a[i]==m)]
```
Returns an array of two elements; the first is the maximum count of maxima, the second is the array of zero-indexed columns with that count.
[Answer]
# Octave, ~~47~~ 46 bytes
```
@(r){m=max(s=sum(r==max(r,0,2),1)),find(s==m)}
```
This creates an anonymous function that automatically assigns itself to `ans` and can be run using `ans([1 2 3; 4 5 6])`. It returns a two-element cell array where the first element is the maximum number of maxima and the second is the 1-based index of the columns containing these maxima.
[**All test cases**](http://ideone.com/hyzjZH)
[Answer]
# Python 3, 142 bytes
The algorithm here is basically, go through each row and increase the score of columns that have the max of that row. Then find the max of the scores and find the columns that have that max score and return them. Columns are 1-indexed. I tried one-lining this into a lambda, but with generating the scores column by column it was 153 bytes.
```
def f(r):
s=[0]*len(r[0]);e=enumerate
for x in r:
for i,j in e(x):
s[i]+=(0,1)[j==max(x)]
m=max(s);return[i+1for i,j in e(s)if j==m],m
```
---
## Test Cases
```
x=[[7, 93],
[69, 35],
[77, 30]]
print(f(x)) #=> [[1], 2]
x=[[ 7, 93],
[69, 35],
[77, 77]]
print(f(x)) #=> [[1 2], 2]
x=[[1, 2, 3, 4],
[5, 6, 7, 8]]
print(f(x)) #=> [[4], 2]
x=[[16, 2, 3, 13],
[5, 11, 10, 8],
[9, 7, 6, 12]]
print(f(x)) #=> [[1 2 4], 1]
x=[[1, 1, 1, 1]]
print(f(x)) #=> [[1 2 3 4], 1]
x=[[25, 6, 13, 25]]
print(f(x)) #=> [[1 4], 1]
x=[[1],
[2],
[3],
[4]]
print(f(x)) #=> [[1], 4]
x=[[100]]
print(f(x)) #=> [[1], 1]
```
[Answer]
## Clojure, 150 bytes
```
(fn[M](let[F(dissoc(frequencies(mapcat(fn[r](map-indexed #(if(=(apply max r)%2)%)r))M))nil)m(apply max(vals F))][(map first(filter #(#{m}(% 1))F))m]))
```
Man that is long, I've got a feeling this could be simplified a lot. At least it produces the correct output.
```
[(f [[ 7 93][69 35][77 30]])
(f [[ 7 93][69 35][77 77]])
(f [[16 2 3 13][5 11 10 8][9 7 6 12]])]
[[(0) 2] [(1 0) 2] [(0 1 3) 1]]
```
] |
[Question]
[
# Introduction
[hackertyper.net](http://hackertyper.net/) is a website that simulates "hacking" (as the media portrays it) by outputting complicated code from the crypto section of the Linux kernel onto the screen as you type at a rate of 3 characters per one inputted.
# Challenge
Your program/function should either accept a file as a command-line argument, have the file path hard-coded, or accept the text [that would be in the file] as a command-line or function argument, and mimic [hackertyper.net](http://hackertyper.net) by outputting 3 characters onto the screen (STDOUT or equivalent) from the file for each one received through STDIN or equivalent.
Once EOF is reached, the program should start outputting characters from the beginning of the file again (wrap).
# Specs
For the purposes of simplicity, you can assume that STDIN has already been set to no buffer and no echo mode, that is not waiting until the user presses enter before passing input to your program and not displaying the characters you type.
The file can contain newlines, while the input will **not contain newlines**.
For a small example written in C (not golfed) that demonstrates how this works, see [this](http://pastie.org/10818441).
Green text and a black background are not required.
# Example input and output
The file:
```
#include <stdio.h>
int main() { }
```
Input:
```
hello world
```
Output:
```
#include <stdio.h>
int main() { }
```
---
The file:
```
hello
```
Input:
```
hello world
```
Output:
```
hellohellohellohellohellohellohel
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẋ3ṁ@
```
[Try it online!](http://jelly.tryitonline.net/#code=4bqLM-G5gUA&input=&args=J2hlbGxvIHdvcmxkJw+J2hlbGxvJw)
### How it works
```
ẋ3ṁ@ Main link. Arguments: s (input string), t (file string)
ẋ3 Repeat s three times.
ṁ@ Mold; reshape t like the previous result.
This repeats the elements of t over and over until the length matches that
of s repeated thrice.
```
[Answer]
# [J](http://tryj.tk), 7 bytes
```
$~(3*#)
```
Takes two arguments, the text to be repeated and the user's input text.
## Usage
The input text is formatted where `,` means to join and `LF` is the newline character.
```
f =: $~(3*#)
('#include <stdio.h>', LF, 'int main() { }') f 'hello world'
#include <stdio.h>
int main() { }
'hello' f 'hello world'
hellohellohellohellohellohellohel
```
[Try it online. (tryj.tk)](http://tryj.tk)
[Answer]
# Jelly, 9 bytes
```
⁴L×3
ẋ¢ḣ¢
```
[Try it online!](http://jelly.tryitonline.net/#code=4oG0TMOXMwrhuovCouG4o8Ki&input=&args=ImhlbGxvIg+ImhlbGxvIHdvcmxkIg)
```
⁴L×3 Define nilad as ¢:
L length of
⁴ second argument
×3 tripled
ẋ¢ḣ¢ Main chain:
the first argument (implicit)
ẋ repeated
¢ ¢ many times
ḣ¢ then get the first ¢ characters of it.
```
[Answer]
# Python 3.5, 77 65 63 bytes:
```
lambda g,f:''.join((g*len(f))[i:i+3]for i in range(0,len(f)*3,3))
```
Simple enough. An anonymous function which takes in two arguments, the first one being the "file" (`g`), and the second being the characters typed in by the user (`f`). Then this creates a generator containing every three characters in `g`, which are found by indexing for every `i` and then `i+3` characters in `g`, where `i` is in the range of `0=>(length of f)*3`. Finally, it returns each object in the generator joined into one big string. You call this function by assigning a variable to it, and then calling the variable wrapped inside a `print()` expression. So if the function's name was `q`, it would be executed like `print(q(<byte array here>))`.
[Try it online! (repl.it)](https://repl.it/CLjL/0)
[Answer]
# Pyth, 10 bytes
```
[[email protected]](/cdn-cgi/l/email-protection)*3l
```
[Try it online!](http://pyth.herokuapp.com/?code=s%40Ljb.z*3l&input=%22hello+world%22%0Ahello&debug=0)
[Answer]
## JavaScript (ES6), 40 bytes
```
(s,t)=>s.repeat(l=t.length*3).slice(0,l)
```
Where `s` is the data string and `t` is the user string. Assumes `s` is nonempty and repeats it `l` times to ensure that its length is at least `l` so that it can return the first `l` characters, where `l` is three times the length of `t`.
[Answer]
# Haskell, 25 bytes
First argument is what's "typed", the second the source to display
```
(.cycle).take.(3*).length
```
Or non-pointfree, for (possibly) better readability:
```
h a=take(3*length a).cycle
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes
Code:
```
3×g©×®£
```
Explanation:
```
3× # Multiply the input string three times.
g # Take the length.
© # Copy that to the register.
× # Multiply by the second input.
® # Retrieve the length from the register.
£ # Only keep [0:length * 3] from the new string.
```
[Try it online!](http://05ab1e.tryitonline.net/#code=M8OXZ8Kpw5fCrsKj&input=aGVsbG8gd29ybGQKaGVsbG8).
[Answer]
# Jolf, 10 bytes
```
]*iγl*I30γ
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=XSppzrNsKkkzMM6z)
## Explanation
```
]*iγl*I30γ
*i repeat string 1
l*I3 the length of the other string * 3
γ γ = (^)
] 0γ (^).slice(0, γ)
```
[Answer]
# Ruby, 39 bytes
In Ruby, `$<` reads from the supplied file in the command line arguments instead of `$stdin` if one is given. (If you forget to supply a file, you get a blank output because it reads everything out of `$stdin` in `$<.read` and thus `STDIN.read.size` will be 0.)
```
$><<($<.read*s=3*STDIN.read.size)[0,s]
```
] |
[Question]
[
Let's make a little stupid program that simulates the meme "[Mr. incredible becoming uncanny](https://www.google.com/search?q=mr%20incredible%20uncanny&rlz=1C1ONGR_esES970ES970&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjs2e34ka_1AhXa_7sIHaP3BNIQ_AUoAXoECAEQAw&biw=1920&bih=969&dpr=1)", but in this case, our little ASCII friend is going to react to our code length.
**Objective:**
Create a program that takes anything (preferably a program) as input and outputs this:
```
Pov:
<face> you score X on codegolf
```
Where `X` is the length of the input and the face depends on the value of X:
```
X < 20 = \(^-^)/
20 ≤ X < 50 = -(o_o)-
50 ≤ X < 100 = /(¬_¬)\
100 ≤ X < 250 = /(º-º)\
250 ≤ X < 500 = /(ª@ª)\
X ≥ 500 = /(x_x)\
```
**Example:**
I have made my own ungolfed version in C#: [Try it online!](https://tio.run/##7ZKxisJAEIZr8xRDql1kNSekOa84sFUQrrjCaFjWdW8h7sDOKsrhC4lPYJkXyyVwzYGxkHQnTDf//38z8CsSCr2uqh1ZZ@DjSEFvx5EqJBHMPRovt/Ad9SjIYBXs0a5hJq1jFHxtWCxBekO8kfQm6AgLPfj0NuipdZrFc9y/xnwc1Vu7YY10kSwHU@1M@II3GCW8Md5yZhlbiRUfAsARd0DNlRD3/0b0Y0AHCtfaYLH5BZ10QRpu4dJ2nGCYIxdd0l6SdtyQlZe8vPAs65I4Su8Sr6K8dkxM7/94fi/PjxPbgw/54bHYqJ5T9Wz7s@3/pu0/)
```
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine("Pov:");
if(args[0].Length < 20){
Console.WriteLine("\\(^-^)/ you score "+args[0].Length+" on codegolf");
}else if(args[0].Length < 50){
Console.WriteLine("-(o_o)- you score "+args[0].Length+" on codegolf");
}else if(args[0].Length < 100){
Console.WriteLine("/(¬_¬)\\ you score "+args[0].Length+" on codegolf");
}else if(args[0].Length < 250){
Console.WriteLine("/(º-º)\\ you score "+args[0].Length+" on codegolf");
}else if(args[0].Length < 500){
Console.WriteLine("/(ª@ª)\\ you score "+args[0].Length+" on codegolf");
}else{
Console.WriteLine("/(x_x)\\ you score "+args[0].Length+" on codegolf");
}
}
}
```
If the program takes itself as input, it will output:
```
Pov:
/(x_x)\ you score 741 on codegolf
```
**Rules:**
* The output must have exactly three spaces betwen the face and the text.
* The shortest code in bytes wins.
* Input length should be counted in characters, not bytes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~106~~ ~~102~~ ~~96~~ ~~94~~ 85 bytes
```
PPov:DP✂⁺”|ecT#F>”xªº´¬o^_@--_-ΣEI⪪”←⧴⟲º"Q⪫+R” ‹Lθιφ⁶←‖B”↶±=⧴KCX≕‹#”ILθ”↶←∨^⁹⁰y↔]
```
[Try it online!](https://tio.run/##TVC9SgNBEO59imUtsoc5jAEtFEXUzgRCYiH4x3Hu6cGaPe8nGLDIWQTtLNRKEfw3WkQJwYSt7gHiO@wL7COccxeImWZmvvm@4ZsxDw3X5AaL42LAfNtx7apPcInX5rG2MLEWHDkE8tiswmyTkhILPIKnIfTtbZIGziJ8ErWifvTJd/eWdX1Px1oWVYIjUjQcsmp4IHaYDetnczmUn82hGciQ8rlEi7AG9AL1PFKg1QP/kBxDb2sJamXRnJb44DVK5gvU8qEpU4tR018JfJ@6FqsnRktD/wihOg@QZ3KXIjzCUw@j5doYn1eRyffpAWcW0ON4K6NEO/mCEk9QydszGfZl4@6UmhuTSrwsQT08tvN/7uBRiWcl3mWrBWPZvJSvHXn/HfWxEl@y9TFVBhjJRk@Jz8HPoPfblGE3oTVulHhIJd3oaxFU60o8bsqLa@BOAg47U8mQkijO33Zl2JNhuy6bVzuZnVivsT8 "Charcoal – Try It Online") Link is to verbose version of code. Note that the deverbosifier miscalculates the length of characters in the ISO-8851 code page; non-ASCII characters should count 3 bytes instead of 1. Explanation:
```
PPov:D
```
Print `Pov:` without moving the cursor (so it gets overwritten below), and output that on its own line.
```
P✂⁺”|ecT#F>”xªº´¬o^_@--_-ΣEI⪪”←⧴⟲º"Q⪫+R” ‹Lθιφ⁶
```
Concatenate the compressed string `////-\((((((` with the incompressible string `xªº¬o^_@--_-` (Charcoal can only compress ASCII strings), slice that with a starting offset depending on how many of the numbers in the compressed string `500 250 100 50 20` are greater than the length of the input and a step of 6, and print without moving the cursor.
```
←‖B
```
Butterfly the canvas, leaving the cursor after the face.
```
”↶±=⧴KCX≕‹#”
```
Print the compressed string `you score` .
```
ILθ
```
Print the length of the input as a string.
```
”↶←∨^⁹⁰y↔]
```
Print the compressed string `on codegolf`.
[Answer]
# Excel, 151 bytes
```
=LET(x,LEN(A1),"Pov:
"&IFS(x<20,"\(^-^)/",x<50,"-(o_o)-",x<100,"/(¬_¬)\",x<250,"/(º-º)\",x<500,"/(ª@ª)\",1,"/(x_x)\")&" you score "&x&" on codegolf")
```
Input is in the cell `A1`. Output is wherever the formula is.
Everything I try that seems more clever than this simple approach ends up adding a few bytes.
[Answer]
# [Python 3](https://docs.python.org/3/), 158 bytes
```
x=len(open(0).read())
print("Pov:\n"+r"////-\((((((xªº¬o^_@-__-xªº¬o^))))))\\\\-/"[sum(x<q*10for q in[2,5,10,25,50])::6],f" you score {x} on codegolf")
```
[Try it online!](https://tio.run/##7cdPCoJAHIbhfacYZjVTY47aWElBR2ivJuGfEmx@Omoo0YWiE7T0YiYugu7gs/h4v7ytriCtvm/2WSwJ5MNwulTxOSKUznKVyorgI9wdT@KFwvpA88io6V7dp3vDKThoQaD9Lh15A03HblnfSLMr5gZPQKECpdI1mWAGZ6ZggvvUcWyfJRihFmpUhqBi9GieCCQKIYovkCWY9r1hWithrzdbPtVU//UF "Python 3 – Try It Online")
-1 byte thanks to pxeger
-9 bytes thanks to Kateba
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 139 bytes
```
s`.+
Pov:¶$.&$*_ you score $.& on codegolf
_{500,}
/(x_x)\
_{250,}
/(ª@ª)\
_{100,}
/(º-º)\
_{50,}
/(¬_¬)\
_{20,}
-(o_o)-
_+
\(^-^)/
```
[Try it online!](https://tio.run/##K0otycxL/P@/OEFPmysgv8zq0DYVPTUVrXgFBYXK/FKF4uT8olQFoJBCfp5Ccn5Kanp@ThpXfLWpgYFOLZe@RkV8hWYMkG9kCuEfWuVwaBVYxBCq4tAu3UO7wCIwJWviD62BaAIJ6Grkx@dr6nLFa3PFaMTpxmnqDy7XAAA "Retina 0.8.2 – Try It Online") Explanation:
```
s`.+
Pov:¶$.&$*_ you score $.& on codegolf
```
Get the length of the input and substitute it into the output string, plus also insert that many underscores for the face checking.
```
_{500,}
/(x_x)\
_{250,}
/(ª@ª)\
_{100,}
/(º-º)\
_{50,}
/(¬_¬)\
_{20,}
-(o_o)-
_+
\(^-^)/
```
Replace the underscores with the appropriate face.
[Answer]
# [Zsh](https://www.zsh.org/), 138 bytes
```
f='\(^-^)/-(o_o)-/(¬_¬)\/(º-º)\/(ª@ª)\/(x_x)\'
<<<"Pov:
${f:$[i=$#1/50+($#1>19),i>9?5:i>3?3+i/5:i]*7:7} you score $#1 on codegolf"
```
[Try it online!](https://tio.run/##HcpBCsIwEEDRfU4xaMGMNTRVSmloq0dwb7ULbTQQHFCUqngh8QQuc7EYXf23@PfzwWuO3Otq1PCN2GAiOLWEIuHu3bo3NgEf4T5/vBbu9UPf9tiMWFmWgyVdFYseWkUrU0XDNMlkzEPrtMCJqYt5pkw9m89ikwStx7nKnwBwowuct3TqILxAR9jSrtuT1QOPjGk6gQWeSphKyCSkMij78W@JoCF6cKuswqf/Ag "Zsh – Try It Online")
Fancy ternaries, let's go through them:
```
i=$#1/50+($#1>19) # div by 50, add one if at least 20
i>9?5: # if i > 9, then $#1 was at least 500
i>3?3+i/5 # else if i > 3, then $# was between 100 and 500
:i # else i is correct
```
---
```
${f:$[ ... ]*7:7} # string slice starting from $[ ]*7 of length 7
<<<"..${f:$[ ... ]*7:7}...$#1.." # substitute in string. Embedded newlines are fine
```
[Answer]
# [Rust](https://www.rust-lang.org/), ~~192~~ 191 bytes
```
|x:&str|print!("Pov:
{} you score {} on codegolf",match x.len(){0..=19=>r"\(^-^)/",0..=49=>"-(o_o)-",0..=99=>r"/(¬_¬)\",0..=249=>r"/(º-º)\",0..=499=>r"/(ª@ª)\",_=>r"/(x_x)\"},x.len())
```
[Try it online!](https://tio.run/##1ZBBboMwEEX3nGLKAtkSkLTKInFKVPUEVRddRbEQ2C0q2MjYDRXhQlFOkCUXoyYE7tCNPf/5z4z8lal0byoGlU4JySQhr4a/szjdOlxAEWcCYWggZxp41J9q4lVanUqVCf2A3Df5Q5ymBYBfaaBKpGJgpRSQyJR9ypy7fhHr5AvqMGd2VLMMw@hxE@2Uu0eH4IAXrj@glUVugCSVOBjJ5mZaoO5Cuwvej/BpNdFr0F0nupq955fuPFA66prWVrX@fTnut87wkcJoyERpzwg@WELIs1nvCBHsiPDooPZlDsQWQwphLpNveykbDjVCZzla@uDNw@6tt5rakKYRtiSEK1lQo/kaeaM5NOKo4nJY6HA0N1nZ/veU/wA "Rust – Try It Online")
*-1 byte thanks to [Aiden4](https://codegolf.stackexchange.com/users/97691/aiden4)*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~118~~ ~~113~~ ~~112~~ 80 bytes
*-32 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).*
```
’ƒËŠˆ’Ig•ȼŸò8Ãx°иšü•"(\^-)/-o_¬ºª@x"Åв6ä•Û³™•51вT*ÅΔIg›}èJ.º“Pov:
ÿ €îŒÂ ÿ€‰ ÿ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcPMY5MOdx9dcLoNyPRMf9Sw6HDHoT1HdxzeZHG4ueLQhgs7ji48vAcorKQRE6erqa@bH39ozaFdh1Y5VCgdbr2wyezwEpCe2Yc2P2pZBGSZGl7YFKJ1uPXcFJBhu2oPr/DSO7TrUcOcgPwyK67D@xUUHjWtObzu6KTDTQqH9wPZjxo2ABn//yspKQ0WxwCdAgA "05AB1E – Try It Online") Beats all other answers.
[Answer]
# JavaScript (ES6), 155 bytes
```
f=(s,i=0)=>[.4,1,2,5,10,n=s.length][i]*50>n?`Pov:
${"/-\\"[q=2>>i]}(${(c="^o¬ºªx"[i])+"-__-@_"[i]+c})${"\\-/"[q]} you score ${n} on codegolf`:f(s,i+1)
```
[Try it online!](https://tio.run/##hY4xboMwGEb3nMKyGOxiHIPKEsmkR6jUEShBrk2pkP8Eu1EqxIWqnqAjF6Mwdgnjp6f39H3U19qpvj37yMKbnmcjiWOtFFRmOX9kMUtYymLBrHS807bx72Xelg@pyOzx9AzXwy4Y8D4qCpxfZJJlbTmSYCBK4leYfqbf6fuGF4GGOKqq6KlaR6hGulhFEe0XqxwRQl/wiZyCXqNgsCMCi9Ryp4HOnA5mfRTGdFZgHXSad9AQQwz38OL71jaEUrr7D/EN816fde1JLO7i5D5OxUZ8o55u5Vc@/wE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 89 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“µð1|ż‘Ḥ‘>@LS‘ị“\-/“(“^oḄṾȥx“-__-@_‘ŒḄ‘6¦U7¦0ịxɗ€6a"ƊZỌ¤
L⁶;“£ṭṛẇṣLe“¦ŒɱṣṀ^Tż»jṭÇ“Pov:¶”;
```
A full program accepting a (Python formatted) string argument that prints the result.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDWw9vMKw5uudRw4yHO5YASTsHn2AQZ3c3UDZGVx9IagBxXP7DHS0Pd@47sbQCyNONj9d1iAcqOzoJKAykzQ4tCzU/tMwAqK3i5PRHTWvMEpWOdUU93N1zaAmXz6PGbdYguxY/3Ln24c7ZD3e1P9y52CcVJLTs6KSTG4G8hzsb4kKO7jm0Owuo5nA7UCogv8zq0LZHDXOt////r66uPkQcC3QpAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9Rw5xDWw9vMKw5uudRw4yHO5YASTsHn2AQZ3c3UDZGVx9IagBxXP7DHS0Pd@47sbQCyNONj9d1iAcqOzoJKAykzQ4tCzU/tMwAqK3i5PRHTWvMEpWOdUU93N1zaAmXz6PGbdYguxY/3Ln24c7ZD3e1P9y52CcVJLTs6KSTG4G8hzsb4kKO7jm0Owuo5nA7UCogv8zq0LZHDXOt/wP5TWsi//@PVrdX18pTSMsvUshTyMxT0DDQUTC01FEwAtImQNoUSFsCaUMDIMMIJGJkCpYCyxloxgIA "Jelly – Try It Online").
### How?
```
“...‘Ḥ‘>@LS‘ị“...‘ŒḄ‘6¦U7¦0ịxɗ€6a"ƊZỌ¤ - Helper: list of characters, X
“...‘ - list of numbers = [9,24,49,124,249]
Ḥ - double = [18,48,98,248,498]
‘ - increment = [19,49,99,249,499]
>@L - length of X greater than? (vectorises)
S - sum
‘ - increment -> our "face index"
¤ - nilad followed by link(s) as a nilad:
“...‘ - list of lists of numbers
...the ordinals of the characters:
"\-/", "(", "^o¬ºªx", "-__-@_"
ŒḄ - bounce
...this appends:
"^o¬ºªx", "(", "\-/"
‘6¦ - increment the sixth - 2nd "(" -> ")"
U7¦ - reverse seventh - 2nd "\-/" -> "/-\"
Ɗ - last three links as monad:
6 - literal six
ɗ€ - for each - f(list, 6):
0ị - get the last one
x - repeat it six times
a" - zip with logical AND
...effectively extend the lists to
length six using the rightmost
ordinal.
Z - transpose
Ọ - convert the integers to characters
...a list of the faces
ị - "face index" index into "faces"
L⁶;“...»jṭÇ“Pov:¶”; - Main Link: list of characters, X
L - length of X
⁶; - prefix with a space
“...» - compressed list of strings = " you score", " on codegolf"
j - join with the score
Ç - call the helper link, above with X as the argument -> face
ṭ - tack the face to the front
“Pov:¶” - "Pov\n"
; - concatenate
- implicit, smashing print
```
[Answer]
# [C# (.NET 6)](https://www.microsoft.com/net/core/platform), ~~190~~ \$\cdots\$ ~~172~~ 170 bytes
```
int l=args[0].Length;Console.Write($"Pov:\n{(l<20?"\\(^-^)/":l<50?"-(o_o)-":l<100?"/(¬_¬)\\":l<250?"/(º-º)\\":l<500?"/(ª@ª)\\":"/(x_x)\\")} you score {l} on codegolf");
```
*Golf of example code in OP*
Passing the program text as the first command line argument outputs:
```
Pov:
/(º-º)\ you score 170 on codegolf
```
Works on `.Net 6` but not on TIO.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 88 bytes
```
`Pov:
`»ẆḞẏǒ×Ȯ<§Jṙ¾»»ƛḂ}Ṁ≥⌐$ǍJ₄p∞wj»₁dτCτ6/»⋏∑ṗ»51τ₀*≬⁰L>ḟuJhiøM3`λ• ßµ `꘍?L` on ¬⋎»₅`Wṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgUG92OlxuYMK74bqG4bie4bqPx5LDl8iuPMKnSuG5mcK+wrvCu8ab4biCfeG5gOKJpeKMkCTHjUrigoRw4oied2rCu+KCgWTPhEPPhDYvwrvii4/iiJHhuZfCuzUxz4TigoAq4oms4oGwTD7huJ91Smhpw7hNM2DOu+KAoiDDn8K1IGDqmI0/TGAgb24gwqzii47Cu+KChWBX4bmFIiwiIiwiXCJgUG92OlxcbmDCu+G6huG4nuG6j8eSw5fIrjzCp0rhuZnCvsK7wrvGm+G4gn3huYDiiaXijJAkx41K4oKEcOKInndqwrvigoFkz4RDz4Q2L8K74ouP4oiR4bmXwrs1Mc+E4oKAKuKJrOKBsEw+4bifdUpoacO4TTNgzrvigKIgw5/CtSBg6piNP0xgIG9uIMKs4ouOwrvigoVgV+G5hVwiIl0=)
] |
[Question]
[
## Introduction
>
> In computer science, a literal is a notation for representing a fixed value in source code. Almost all programming languages have notations for atomic values, some also have notations for elements of enumerated types and compound values. [Wikipedia](https://en.wikipedia.org/wiki/Literal_%28computer_programming%29#%3A%7E%3Atext%3DIn_computer_science%2C_a_literal%2Cfixed_value_in_source_code.%26text%3DAn_anonymous_function_is_a%2Cbeing_constrained_not_to_change.?wprov=sfla1)
>
>
>
For example `1` usually represent an integer value, `"Hello"` a string, `[9,5,11]` an array and `1..9` a range.
The range notation is special because we have just two values in the literal but the actual value includes all elements in between.
We can say that a range expands to an array or a list of values. So the expansion of the range `1..9` is `[1,2,3,4,5,6,7,8,9]`.
In this challenge you are given a **Cartesian literal** as input and you have to output its expansion.
## Notation format rules
* consider only non negative integers values.
* this notation could work for products of any degree but in this challenge you have to handle only products of two sets, so we get a list of pairs.
* we can have one or more groups of products.
Every group is terminated by the `/` symbol and generates its own list which is then concatenated to the others groups.
* each group has 2 sets: A and B and they are separated by the `:` symbol.
* each set is composed of ranges and/or atomic values separated by `,`.
Ranges are in the form `start-end` for example `0-10`.
Values must be sorted without overlaps, for example `1-5,5,4` can not appear.
* every group contains non empty sets.
## Example
The literal `1-2,5:10-12/0:1-3/` is composed of two groups.
The first group (`1-2,5:10-12`) has the sets:
```
A=[1,2,5]
B=[10,11,12]
```
and generates the product
```
[1,10],[1,11],[1,12],[2,10],[2,11],[2,12],[5,10],[5,11],[5,12]
```
the second group generates `[0,1],[0,2],[0,3]` which is appended to the first so the output is:
```
[[1,10],[1,11],[1,12],[2,10],[2,11],[2,12],[5,10],[5,11],[5,12],[0,1],[0,2],[0,3]]
```
## Test cases
```
"0:0/" -> [[0,0]]
"1-3:2/" -> [[1,2],[2,2],[3,2]]
"4:5-6/" -> [[4,5],[4,6]]
"9,10,11:9-11/" -> [[9,9],[9,10],[9,11],[10,9],[10,10],[10,11],[11,9],[11,10],[11,11]]
"100:0-1,2,3-4/1:2/" -> [[100,0],[100,1],[100,2],[100,3],[100,4],[1,2]]
"1:2/3:4/5:6/7:8/9:10/" -> [[1,2],[3,4],[5,6],[7,8],[9,10]]
"11-13:2/" -> [[11,2],[12,2],[13,2]]
```
## Rules
* 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.
* You can assume the input will always be a valid literal, you don't have to handle invalid literals.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¯I¤¡¨vy':¡ε',¡ε'-¡Ÿ}˜}`â«
```
Pretty straight-forward approach.
[Try it online](https://tio.run/##yy9OTMpM/f//0HrPQ0sOLTy0oqxS3erQwnNb1XXApO6hhUd31J6eU5tweNGh1f//G@oa6ZhaGRroGhrpG1gZ6hrrAwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Q@srDy05tPDQirJKdatDC89tVdcBk7qHFh7dUXt6Tm3C4UWHVv@v1fkfrWSoa6RjamVooGtopG9gZahrrK@ko2RgZQCigDwrIxDDxMpU1wzEsNQxNNAxNLSy1DU0BKswACrVNdQx0jHWNdE3hKgGUcZWJvqmVmb65lYW@pZA4/WVYgE).
**Explanation:**
```
¯ # Start with an empty list []
I # Push the input-string
¤ # Push its last character (without popping): "/"
¡ # Split it on "/"
¨ # Remove the trailing empty string
vy # Foreach over the parts:
':¡ '# Split the part on ":"
ε # Map over each smaller part:
',¡ '# Split it on ","
ε # Inner map yet again:
'-¡ '# Split on "-"
Ÿ # Convert this pair (or single integer) to a ranged list
}˜ # After the inner-most map: flatten
}` # After the outer map: pop and push the lists separated to
# the stack
â # Create pairs of the two lists with the cartesian product
« # Merge this list of pairs to the result-list
# (after the loop, the result is output implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 23 bytes
```
ṣṪṣ”:ṣ”,⁾-ry$€VFƲ€ŒpƊ€Ẏ
```
[Try it online!](https://tio.run/##y0rNyan8///hzsUPd64Cko8a5lpBKJ1Hjft0iypVHjWtCXM7tglIHZ1UcKwLSD/c1ff/4e4th9vBYg93zgDSkf//G@oa6ZhaGRroGhrpG1gZ6hrrcxlYGehzAVlWRvpcJlamumb6XJY6hgY6hoZWlrqGhkA5A6ASXUMdIx1jXRN9Q5A6EGFsZaJvamWmb25loW8JNFIfAA "Jelly – Try It Online")
-2 bytes from reading Kevin Cruijssen's answer.
```
ṣṪṣ”:ṣ”,⁾-ry$€VFƲ€ŒpƊ€Ẏ
ṣ Split on
Ṫ last character, removing it from the string
Ɗ€ For each:
ṣ”: Split on ":"
Ʋ€ For each:
ṣ”, Split on ","
$€ For each:
y Replace
⁾-r "-" with "r"
V Evaluate as Jelly programs (r = range)
F Flatten
Œp Cartesian product
Ẏ Tighten (shallow flatten)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~98~~ 87 bytes
```
p`dd`.gsub(/\d+-/,'*\00..').split(?/).flat_map{|x|eval"[%s].product([%s])"%x.split(?:)}
```
[Try it online!](https://tio.run/##KypNqvz/vyAhJSVBL724NElDPyZFW1dfR10rxsBAT09dU6@4ICezRMNeX1MvLSexJD43saC6pqImtSwxRylatThWr6AoP6U0uUQDxNFUUq2AabDSrP3/39DAwMpA11DHSMdY10Tf0MpIHwA "Ruby – Try It Online")
#### Explanation
```
`dd`.gsub(/\d+-/,'*\00..') # input and replace "number-" with "*number-0..", ruby syntax for ranges
.split(?/).flat_map # split on "/" and map block, then concat
{|x|eval"[%s].product([%s])"%x.split(?:)} # string interpolate and eval
p # print
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~131 118~~ 110 bytes
```
->s{eval"[#{s.gsub(/(\d+)-/,'*\1..').gsub(/([^\/:]+)/,'[\1]').gsub(/:([^\/:]+)/,'.product(\1)').tr ?/,?+}[]]"}
```
[Try it online!](https://tio.run/##XZDBboMwEETv/QpEDoGyxl7bkGCpyYcYV0qappdKjSBUqqJ8O10bU9pe9lkzs9KOu@H4NZ6fRrbrb6@fh/fUrm59@dYPx4xn7anIGYf1Y4tluc5n2T633LgiJ8e26H4M89spL93HaXi5Zi3mlLh2yZ7Dvrhb59L7eEnONkUmoTIoGEouDDLFU/cQHGEEvVcJ2yXWChAu6pQxcnEQpAMrw1Q0Y0qbitVLSkNFvoZ69htAAYimYYhLrIGGYt6bgATKNROCGtY8cZIxyujl@URBxzO6DBTTHP@cK3wVCMRIGakitedSxe8ro3llar4xW97Qd/3vr8JSRf3AbmA7l3DjNw "Ruby – Try It Online")
I tried to parse the expression and apply the single operations, but the shortest solution is to just convert the string into a Ruby expression, and evaluate it.
[Answer]
# [Python 3](https://docs.python.org/3/), 188 bytes
```
from itertools import*
f=lambda s:[q for x in s.split("/")[:-1]for q in product(*([w for z in y.split(",")for w in range(*map(eval,(z+"-"+z+"+1").split("-")[-2:]))]for y in x.split(":")))]
```
[Try it online!](https://tio.run/##TVDLboMwEDw3X2H5ZId18fJIgqV8CeJAG2iRABNwm8fPU9tA1MvOemZWO97hYb51H89zPeqONKYajdbtRJpu0KPZ7@pzW3Yfl5JMKr@SWo/kTpqeTO/T0DaG0ZDyXAksnHJ1yjDqy8@nYXuW37z/6djH5gfKHXlz5Fj2XxXbd@XAqt@yBfYMqKCBrQFSvk0Iu0FEquDcL3m4yfsmKsotP5tqMhM5k5xRqWRIwXYSJC84EEZRxCpaSISIA4t8jW1dDIlKxWExJJBaKYHDKmWAEhBVJhAXRwaZdTh@AbRgPdkCnvUjDnGhcaXR0WsmaYMKGwdikYT4yiddbPCIK0YrxismDl/Z3WiskjBVh/CoTmGmUP7/a@z9qf0QsCOctugFL3bunA1od1B/QLV7G8amN6zhW1fb/vXQfP4D "Python 3 – Try It Online")
Uses a lot of nested list comprehensions. The hardest parts are the ranges. `(z+"-"+z+"+1").split("-")[-2:]` converts a range of form `"a-b"` to `["a","b+1"]` and a single integer `"a"` to `["a","a+1"]`. These are then evaluated and fed directly to `range`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~36~~ 27 bytes
```
ṫ/ƛ\:/ƛ⌐ƛ\-/k≈•⌊÷ṡ;f;÷Ẋ;f2ẇ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B9%AB%2F%C6%9B%5C%3A%2F%C6%9B%E2%8C%90%C6%9B%5C-%2Fk%E2%89%88%E2%80%A2%E2%8C%8A%C3%B7%E1%B9%A1%3Bf%3B%C3%B7%E1%BA%8A%3Bf2%E1%BA%87&inputs=%221-2%2C5%3A10-12%2F0%3A1-3%2F%22&header=&footer=)
*-9 thanks to Kevin*
With colour:
[](https://i.stack.imgur.com/IOnO4.png)
## Explained
```
ṫ/ƛ\:/ƛ⌐ƛ\-/k≈•⌊÷ṡ;f;÷Ẋ;f2ẇ
ṫ/ # Split the input string on its last character ("/") - returns groups
ƛ # To each group G:
\:/ # Split G on ":" - returns sets
ƛ # To each set S:
⌐ # Split S on commas - returns values
ƛ # To each value V:
\-/ # Split V on "-" - returns items in range
kť # Mold that to the shape of [0, 1] - honestly idk what this does, but it works and it's genius. (it seems to make it so that each list is of length 2, even if it's a single item list)
⌊÷ṡ # Generate an inclusive range between the two numbers
; # End map over each V
f # and flatten that - returns a flat list of all numbers to cartesian product
; # End map over each S
÷Ẋ # Cartesian product of the sets
; # End map over each G
f2ẇ # flatten and place back into pairs
```
[Answer]
# [Zsh](https://www.zsh.org), 96 bytes
```
for x (${(s:/:)${1//(#m)<->-<->/\{${MATCH/-/..}\}}})eval print -l \{${x/:/,z\},\{z,}\}|grep -v z
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjW7SSbr6SjoJSakVJal5Kakp6Tn6SUuyCpaUlaboWNxPS8osUKhQ0VKo1iq30rTRVqg319TWUczVtdO10gVg_plql2tcxxNlDX1dfT682pra2VjO1LDFHoaAoM69EQTdHAaSiQt9KX6cqplYnprpKB6ioJr0otUBBt0yhCmIP1DqgYwx1jXRMrQwNdA2N9A2sDHWN9eGOAQA)
Zsh seems like it was *made* for this challenge!
*not*.
---
Explanation:
* `${1//(#m)<->-<->/\{${MATCH/-/..}\}}`: replace all instances of `A-B`, where `A` and `B` are numbers, with `{A..B}`
* `for x (${(s:/:)})`: split that on `/` and loop:
+ `${x/:/,z\},\{z,}` replace `:` with `,z},{z,`
+ This constructs strings that follow Zsh's pattern of brace expansion, which is the easiest way to do a Cartesian product
+ By `eval`ing them, they are expanded properly, and `print -l` prints them newline-separated.
+ The `,z`s are to work around the fact that things of the form `{0}` are treated as literal strings, and don't just expand to a 1-element list. They are removed again by the `|grep -v z`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~79~~77 bytes
```
->s{eval"[#{s.gsub(?:,'].product([').gsub(/\d+-/,'*\00..').gsub ?/,'])+['}]"}
```
[Try it online!](https://tio.run/##VZDLbsIwEEX3fEUUFoEyjmdiJ@CRCh9ivCildFOpiDSVKsS3p35FaVdHOnNtzZ3bcPoZL8@j2Pf3t@@Xj9Iu73393g@n1YGhcvX19nkeXr9WtlonLY/njZBQPR0R6zrb4uCNW29s9XDlY7wWF1sioyzdshD7wloEdG4RPZEgxc08I4LGgaUmQXnkqOZWdHNQQ@sDGrppboAQiNgIojlmwPhYmCVQ@BWjDHHMjJqSpqwp6GlP9A2E3w2U0JL@bYyhD0RSZpOpMnXgXCW8V6xly53c8k4apj/nSRdQ8VHr@4Hdwm4q4RbjLw "Ruby – Try It Online")
* Saved 2 thanks to @G B
The literal already has a structure we can use, we just have to substitute a few symbols and then we evaluate it
```
[ prepend a [
#{s.gsub(..).gsub(... transform input by replacing:
`:` => '].product(['
`/(\d+)-/` => '*\1..' here \1 is the captured number
`/` => '])+[' we add next square
] which we close empty if there's no group available.
```
Here is an example with **adds** and `substitutions` :
100 `:` `0-` 1 , 2 , `3-` 4 `/` 1 `:` 2 `/`
**[** 100 `].product([` `*0..` 1,2, `*3..` 4 `])+[` 1 `].product([` 2 `])+[` **]**
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 79 bytes
```
!_S`/
%(+`\b(\d+)-(\1\b|())
$1$#3*$(,$.(*__)-
Lw$`\b(\d+)\b.*:.*\b(\d+)\b
$1,$2
```
[Try it online!](https://tio.run/##PcqxDcIwEIXh/rZAOMh2bJ8vTgK5BdLQUWIUE0FBQ4GQaJiLAVjMJEVonvTrfY/r83Y/Uy5kn/JqOCSEQpYpjjJeSmVlpDi@pVIgSKyDFtIIJ/UwKAv7l1hcHJ1mp/81aSOqrPoEroSj2Jzg@wGzRPbsEcgGrhBqbmyL0Bnyhog7SzR9fiKWTGWCrZFmN0/gGhtuccs77Jg8/gA "Retina – Try It Online") Outputs each pair on its own line but link includes test suite that joins the lines back together for convenience. Explanation:
```
!_S`/
```
Split on `/`s, but drop empty entries.
```
%(`
```
Separately for each split:
```
\b(\d+)-(\1\b|())
$1$#3*$(,$.(*__)-
```
Expand a range: if it has already expanded to the form `n-n` then simply delete the `-n` otherwise replace it with `n,n+1-m`.
```
+`
```
Repeat until all ranges have been completely expanded.
```
Lw$`\b(\d+)\b.*:.*\b(\d+)\b
$1,$2
```
Take the Cartesian product of both sets by considering overlapped matches of one number from each of the sets.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
F⪪S/¿ι«≔⟦⟧θF²FE⪪§⪪ι:¬κ,I⪪λ-F…·§λ⁰⊟λ¿¬κ⊞θμFθ⟦⁺⁺μ,ν
```
[Try it online!](https://tio.run/##Pc9La8MwDADgc/srRE4S2OQxdklPZaccNsJ6LD2YzE1NXedhpwzGfrunZt4uNpKlT1Z3UXM3KBvjeZgBD6M1ARs3LuEQZuN6JAFZnhGBOQMagq/tZu@96R0eTwIm2m03a2dFsN6vakzKPjTuQ3@myLBTZ6y9DQGv9GDFI3xRPqQSyznJo5LUuM4u3tz1u3K9/ue4quC@dhjRUvpXMqFd/AUnATfagbZe/0ITP/AuAY8tg7get7/5jk68w3eMpazEc10Wsqzyoi7lUx7l3f4A "Charcoal – Try It Online") Link is to verbose version of code. Would be 1 byte shorter if the product could be output in a different order. Explantion:
```
F⪪S/¿ι«
```
Split the input on `/`s and loop over non-empty groups.
```
≔⟦⟧θ
```
Prepare to collect the second set.
```
F²
```
Loop over each set.
```
FE⪪§⪪ι:¬κ,I⪪λ-
```
Split the group on `:`, extract the desired set, then split that on `,`, then split that on `-`, then cast to integer.
```
F…·§λ⁰⊟λ
```
Loop over each of the resulting ranges. (Where there was no `-` in that range, the same integer will be used as the start and end of the range, resulting in a range of that integer.)
```
¿¬κ
```
If this is the second set (which is being processed first), then...
```
⊞θμ
```
... save this integer for later, otherwise...
```
Fθ⟦⁺⁺μ,ν
```
... for all integers from the second set, pair the current integer from the first set with it.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU coreutils, 126 bytes
```
tr :/ \\n|sed -Ee 's/([0-9]+)-([0-9]+)/{\1..\2}/g' -e 's/.+,.+/{\0}/'|while read s&&read t;do eval printf %s\\\\n $s\\ $t;done
```
[Try it online!](https://tio.run/##NYrBDoIwEER/ZQ9INWW7bYkH8exXWA@YrkJCqqGNHoRvr0jiXN7kzVzb2OWcRmgInAtTZA94YhCRtmeNh4vc4b/QxxmlnJ3pLgDXj5KVkovXM4np3fUDw8ith1iWK9PRP4Bf7QDPsQ/pBpvolgQoFkLxmwPnbNBW@8ZoNJZ0Y7CmLw "Bash – Try It Online") Takes input on STDIN without a trailing newline. Explanation:
```
tr :/ \\n|
```
Split the input on both colons and slashes. This results in a trailing newline but `read` eats that anyway.
```
sed -Ee 's/([0-9]+)-([0-9]+)/{\1..\2}/g' -e 's/.+,.+/{\0}/'|
```
Expand numeric ranges and wrap lists in braces.
```
while read s&&read t;do eval printf %s\\\\n $s\\ $t;done
```
Read two sets at a time and generate their Cartesian product.
[Answer]
# [Python 3](https://docs.python.org/3/), 187 bytes
```
import itertools as t
[k for b in s.split('/')[:-1] for k in t.product(*[[j for x in m.split(',') for j in range(*[int(x.split('-')[0]),int(x.split('-')[-1])+1])] for m in b.split(':')])]
```
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/), ~~223~~ ~~213~~ 205 bytes
```
IFS=/
for i in $1
do
l=
IFS=:
for j in $i
do
while [[ $j =~ ([0-9]*)-([0-9]*) ]]
do
set -- ${BASH_REMATCH[@]}
j=${j/$1/"{$2..$3}"}
done
k=${j##*,*}
l=$l\\\ ${k:-"{$j}"}
done
eval printf %s\\\\n ${l:2}
done
```
[Try it online!](https://tio.run/##PY7BCoJAEIbv@xSDbVDitq7SoQUhi6IOXbKbShQp7rpoZNRB7NW3tajb8P3fzPznU1NovV1HAUV5fQMBogLM0KVGKkA95x8uP1z0/FkIlUEcA5YQvGAUu2SW2mPyGyBNe63J7kAI4HYRRpvjfrULD8tNPE87JAPcSooZtVrsTSbY76zObFQZKvtkMLAduzPvsUqSxBwoOTGm/FvZ46TgehPVPYdhY5zEVGsV97651poRz5ly5hLmUZcz4tM3 "Bash – Try It Online") Takes input as a command-line parameter. Edit: Saved 10 bytes thanks to @pxeger. Explanation:
```
IFS=/
for i in $1
do
...
done
```
Split the input on `/`s. (The last empty string gets ignored.)
```
l=
```
Start building up the sets.
```
IFS=:
for j in $i
do
...
done
```
Split the group on `:`s.
```
while [[ $j =~ ([0-9]*)-([0-9]*) ]]
do
set -- ${BASH_REMATCH[@]}
j=${j/$1/"{$2..$3}"}
done
```
Expand numeric ranges.
```
k=${j##*,*}
l=$l\\\ ${k:-"{$j}"}
```
Wrap lists in braces and concatenate the sets.
```
eval printf %s\\\\n ${l:2}
```
Generate the Cartesian product of the sets.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 54 bytes
```
~]'/;;{':;;{',;;{J'-~[{'-;;)ti^pr@}qtiIE}\m}MPcp}\m}MP
```
[Try it online!](https://tio.run/##JYq9DoIwFEb3vkhj0pvbSwvaWwcXB01M3P0ZNAwkYABhasqrVxqH73zDOa95bOvvMNep/ewhpOUh0fsgOUOtOEtYbkGC95upefbjIQ5TczrGexcv13f//5SnWaMgMFygsFxChcIp0oqIHRCtTq8JkCqUAYuUuwzDFkuucMs7dEwafw "Burlesque – Try It Online")
```
~] # Drop final /
'/;; # Split on /
{
':;; # Split on :
{
',;; # Split on ,
{
J'-~[ # Contains -
{
'-;; # Split on -
{ti}MP # Map to int and force onto stack
r@ # Range from low to high
}
{ti} # To int
IE # If else
}\m # Map and concatenate
}MP # Map and push
cp # Cartesian product
}\m # Map and concatenate
}MP # Map and push
```
[Answer]
# [R](https://www.r-project.org/), 196 bytes
```
function(x,`[`=sapply,t=strsplit,d=do.call)apply(matrix(t(x,'/')[t,":"][t,","][t,"-"][lapply,function(j)as.list(scan(t=j)+!3:4)][function(i)unlist(i[d,w=`:`])],2),2,function(l)d(outer,c(l,paste)))
```
[Try it online!](https://tio.run/##RY/NCoMwEAafpbk0Szf@tpdAniQIhmghkqokK7VPb62KPc1h5xvYsFgTyDtSy3PqLbmh5zPWulbRjKP/IKlIIY6rgY1qhsQa72E78Zeh4GZO6@CaXkETMsmqH3CHWOH3zBnvwMTEu0g8WtNzUh3cLqW8Q6VPx8HUb4rTDb5VLesKKiwAi3/HQ8OHidqAlnscTaQWAJZjeDzFWS4KfMg8E3mRZjIXZcpW6ws "R – Try It Online")
Outputs a list of each 'group of products' (separated by `/` in the input), containing space-separated pairs of elements.
[+8 bytes](https://tio.run/##RY/LCoMwEEW/pdk0Qyc@200gXxIEQ7QQSVWSkdqvt1bRzuZs7j2XCYs1gbwjtTyn3pIbej5jrWsVzTj6D5KKFOK4JrBRzZBY4z1MvXeR@JbgL0PBzZzW3jW9giZkklU/4A6xwu@2c6MDE5NNEq3pOakObpdS3qHSZ8YdO043@Fa1rCuosAAs/h4PDR8magNa7nE0kVpY7/iKs1wU@JB5JvIizWQuypTB8gU) to output as a flat vector.
**Ungolfed:**
```
a=
sapply( ... strsplit(x,'/'), # split input on '/
sapply( ... strsplit(x,':'), # split that on ':'
sapply( ... strsplit(x,','), # split that on ','
sapply(strsplit(x,'-')) # and finally split that on '-'
b=lapply(a,function(j)as.list(rep(j,2)[1:2]))
# double any lists of one item
c=sapply(b,function(i)unlist(s(i,do.call,what=`:`)))
# and apply ':' (range) using
# 2-element lists as arguments,
# concatenating (unlist) the results
m=matrix(c,2) # put the output into 2-row matrices
apply(m,2,function(l)do.call(outer,c(l,paste)))
# and, for each column, paste togethe
# the elements of each of the two rows
```
[Answer]
# JavaScript (ES10), 150 bytes
This seems quite long...
```
s=>s.replace(/(\d+)-(\d+)/g,g=(_,a,b)=>a-b?a+[,g(_,-~a,b)]:a)[S='split']`/`.map(s=>s?(g=k=>s[S]`:`[k][S]`,`)(0).map(a=>g(1).map(b=>[a,b])):[]).flat(2)
```
[Try it online!](https://tio.run/##dZHNbsIwEITvfQrEBVus42x@gFhyeAiOrtUYCBElJRFBPfbVU9tJ1Z/QHHas0X4rzeTVvJvucDu3d3ZtjmV/kn0n8y64lW1tDiXh5Pm4pMxPXkElyQsY2FOZG7bfmqWCyjrsw3laGKp2ctG19fm@0AUvgjfTEndvSyp5sap2uhCFumj3gIKSkPodI/OK4PDey1zZc5pSoTQNTrW5k4j2h@baNXUZ1E1FTmQeipDPKZ1NPs5nSoUQav30B0EWi@gR5BGESIOK/IztnOCJSNnqXzyB1IIJrKZgBhgCosgY4i/egxlkFnQ7g6AVu58N4l2PO8XBxtFGZ09jhrYbZuNAzBKO35GHmKHrBrziqNGo8aiJ00cVuGOxSHgqVnwtNjwTOPyFHw3GHk9tEaDWsPnKpvtP "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
List all of the combinations with replacement (or combinations with repetition) of size *k* from a set of *n* elements.
A combination with replacement is an unordered multiset that every element in it are also in the set of *n* elements. Note that:
* It is unordered. So a previously printed set with a different order shouldn't be printed again.
* It is a multiset. The same element can (but isn't required to) appear more than once. This is the only difference between a combination with replacement and a normal combination.
* The set should have exactly *k* elements.
Alternatively, it is also a size-*k* subset of the multiset which contains each of the *n* elements *k* times.
The input should be either *n* and *k*, where the elements are the first *n* positive or non-negative integers, or the *n* elements and *k*, where you can assume the *n* elements are all different from each other.
The output should be a list of all the combinations with replacement with size *k* from the given set. You can print them and the elements in each of them in any order.
You may not use builtins generating combinations with replacement. But you can use builtins to generate normal combinations, permutations, tuples, etc.
This is code-golf, shortest code wins.
## Example
```
Input: 4 2
Output: [0 0] [0 1] [0 2] [0 3] [1 1] [1 2] [1 3] [2 2] [2 3] [3 3]
```
[Answer]
## Jelly, 4 bytes
*Thanks to Sp3000 for saving 2 bytes.*
```
ṗṢ€Q
```
Input is `n` and `k` as command-line arguments in that order. Uses elements `1` to `n`.
[Try it online!](http://jelly.tryitonline.net/#code=4bmX4bmi4oKsUQ&input=&args=NA+Mg)
### Explanation
```
ṗ # Get k-th Cartesion power of n.
Ṣ€ # Sort each tuple.
Q # Remove duplicates.
```
[Answer]
## CJam (8 bytes)
```
{m*:$_&}
```
[Online demo](http://cjam.aditsu.net/#code=4%202%0A%0A%7Bm*%3A%24_%26%7D%0A%0A~%60)
### Dissection
```
{ e# Declare block (anonymous function); parameters are n k
m* e# Cartesian product, which implicitly lifts n to [0 1 ... n-1]
:$ e# Sort each element of the Cartesian product, to give them canonical forms
_& e# Deduplicate
}
```
[Answer]
## Mathematica, ~~31~~ 29 bytes
*Thanks to A Simmons for saving 2 bytes.*
```
{}⋃Sort/@Range@#~Tuples~#2&
```
An unnamed function taking `n` and `k` as integer arguments in that order and returning a list of lists. The elements will be `1` to `n`. Works the same as Peter's CJam answer.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 11 bytes
(There's a [9-byte solution](http://matl.tryitonline.net/#code=OmlaXiFTIVh1&input=NAoy) based on Cartesian power, but Peter Taylor [already did that](https://codegolf.stackexchange.com/a/74607/36398). Let's try something different).
Combinations with replacement can be reduced to combinations without replacement as follows. We want `n Cr k`, for example with `n=3`, `k=2`:
```
0 0
0 1
0 2
1 1
1 2
2 2
```
We can compute `n+k-1 C k`:
```
0 1
0 2
0 3
1 2
1 3
2 3
```
and then subtract `0 1 ... k-1` from each row:
```
+q:2GXn2G:-
```
Explanation:
```
+q % take two inputs n, k and compute n+k-1
: % range [1,2...,n+k-1]
2G % push second input, k
Xn % combinations without replacement
2G: % range [1,2,...,k]
- % subtract with broadcast. Display
```
The code works in [release 13.1.0](https://github.com/lmendo/MATL/releases/tag/13.1.0) of the language/compiler, which is earlier than the challenge.
You can [**try it online!**](http://matl.tryitonline.net/#code=K3E6MkdYTjJHOi0&input=NAoy) Note that the online compiler has been updated to release 14.0.0, so `Xn` needs to be changed to `XN`.
[Answer]
## JavaScript (Firefox 30-57), 71 bytes
```
f=(n,k)=>k?[for(m of Array(n).keys())for(a of f(m+1,k-1))[...a,m]]:[[]]
```
I get to use `keys()` for once.
[Answer]
## Ruby, ~~56~~ 55 bytes
Two solutions, surprisingly both the same length:
```
->n,k{[*1..n].repeated_permutation(k).map(&:sort).uniq}
->n,k{(a=[*1..n]).product(*[a]*(k-1)).map(&:sort).uniq}
```
Hey, you *did* say we could use permutation builtins...
This simply generates all repeated *permutations* (the second one generates repeated Cartesian products) and removes ones that aren't in sorted order.
Thanks to Martin for saving a byte with `0...n` -> `1..n`!
[Answer]
## Pyth, 7 bytes
```
{SM^UQE
```
Uses the same algorithm as Peter's answer.
```
UQ range(input())
E input()
^ repeated Cartesian product of ^^, ^ times
SM map(sort)
{ uniq
```
[Answer]
## Python, 63 bytes
```
f=lambda n,k:n*k and[l+[n]for l in f(n,k-1)]+f(n-1,k)or[[]][k:]
```
A recursive method. To make a multiset of `k` elements, `1` to `n`, we choose to either:
* Include another instance of `n`, and it remains to make a multiset of `k-1` elements from `1` to `n`
* Don't include another instance of `n`, and it remains to make a multiset of `k` elements from to `1` to `n-1`
We terminate when either `k` or `n` reaches `0`, and if it `k` reached `0`, we give a base case of the empty list. If not, we have the wrong number of elements, and so give the empty list.
[Answer]
# Python 3, 81 80
Recursive solution:
```
t=lambda n,k,b=0:[[]]if k<=0 else [[i]+l for i in range(b,n)for l in t(n,k-1,i)]
```
The function `t(n, k, b)` returns the list of all `k`-element multi-subsets of the range from `b` to `n`. This list is empty if `k <= 0`. Otherwise, we break the problem down based on the smallest element of the multi-subset, which we denote by `i`.
For each `i` in the range from `b` to `n`, we generate all of the `k`-multi-subsets with smallest element `i` by starting with `[i]` and then appending each `(k-1)`-multi-subset of the range from `i` to `n`, which we obtain by recursively calling `t(n, k-1, i)`.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 22 bytes
```
{∪{⍵[⍋⍵]}¨↓⍉⍺⊥⍣¯1⍳⍺*⍵}
```
Requires `⎕IO←0`, which is default in many APL systems. Takes k as left argument, n as right argument.
`⍳⍺*⍵` 0 1 2 ... kⁿ
`⍺⊥⍣¯1` convert to base k
`⍉` transpose
`↓` make matrix into list of lists
`{⍵[⍋⍵]}¨` sort each...
`∪` the unique
[Answer]
# J, 18 bytes
```
[:~.#~<@/:~@#:i.@^
```
Similar approach used in @Adám's [solution](https://codegolf.stackexchange.com/a/74620/6710).
Another approach using Cartesian product `{` for 24 bytes. Takes `k` on the LHS and `n` on the RHS.
```
~.@:(/:~&.>)@,@{@(#<@i.)
```
## Usage
```
f =: [:~.#~<@/:~@#:i.@^
4 f 2
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│0 0│0 1│0 2│0 3│1 1│1 2│1 3│2 2│2 3│3 3│
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
```
## Explanation
```
[:~.#~<@/:~@#:i.@^ Input: n on LHS and k on RHS
^ Compute n^k
i.@ Create a range [0, 1, ... n^k-1]
#~ Create k copies on n
#: On each value in the range above, convert each digit to base-n
and take the last k digits of it
/:~@ For each array of digits, sort it in ascending order
<@ Box each array of digits
[:~. Take the distinct values in the array of boxes and return it
```
[Answer]
## Clojure, 94 bytes
```
(defn f[k n](if(= 1 k)(for[i(range n)][i])(sort(set(for[i(f(dec k)n)j(range n)](conj i j))))))
```
Note the changed parameter order: 1st is `k` and 2nd is `n`. This saved 1 byte in `(f(dec k)n)`.
[Answer]
# Mathematica, 36 bytes
```
{##}&~Array~Table@##~Flatten~(#2-1)&
```
*Please* tell me there's a 1/6 bonus for using no []s...Or maybe for the many uses of ##?
] |
[Question]
[
# Introduction
In this challenge you will be solving diagonal Burrows-Wheeler transforms. Here is a general overview of what a diagonal Burrows-Wheeler transform is. To encode a message, you first must guarantee that it is odd in length (i.e. 5, 7, 9, etc.). Then you make a grid, `n` by `n`, where `n` is the length of the message. The first row is the original message. Each row after that is the row above it, but shifted 1 character left with the first character moving to the back. For example:
```
Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
WorldHello
WorldHello
orldHello W
rldHello Wo
ldHello Wor
dHello Worl
```
Then you take each letter on the NW to SE diagonal and put that into a new string:
```
Hello World H
ello WorldH l
llo WorldHe o
lo WorldHel W
o WorldHell r
WorldHello d
WorldHello e
orldHello W l
rldHello Wo (space)
ldHello Wor o
dHello Worl l
```
Your encoded message is `HloWrdel ol`. To decode, first take the length of the encoded message, add 1, and divide by 2. Lets call this number `x`. Now that we know `x`, starting at the first letter, each letter is `x` after the last, looping around. For example:
```
H l o W r d e l o l
1
Then...
H l o W r d e l o l
1 2
And again...
H l o W r d e l o l
1 3 2
Until you get...
H l o W r d e l o l
1 3 5 7 9 11 2 4 6 8 10
```
Now just rearrange the letters in the correct order to get `Hello World`!
# Challenge
Your challenge is to write either two programs, functions, or one of each. However, both must use the same language. The first program will accept a string as input via STDIN, program arguments, or function parameters and *encode* it using this method. The second program will accept a string as input via STDIN, program arguments, or function parameters and *decode* it using this method.
# Requirements
### First Program/Function
* A single string input using any method listed above.
* Must encode the string using a diagonal Burrows-Wheeler transform style.
### Second Program/Function
* A single string input using any method listed above.
* Must decode the string using a diagonal Burrows-Wheeler transform style.
# Constraints
* You cannot use any built-in or external functions that accomplish this task.
* Standard loopholes are not allowed.
* Both programs/functions must be in the same language.
# Scoring
This is code golf, so shortest program in *bytes* wins.
If I need to add more information, leave a comment!
[Answer]
# CJam, (4 + 8 = ) 12 bytes
Encoding program:
```
q2/z
```
[Try it online here](http://cjam.aditsu.net/#code=q2%2Fz&input=Hello%20World)
Decoding program:
```
q_,2/)/z
```
[Try it online here](http://cjam.aditsu.net/#code=q_%2C2%2F)%2Fz&input=HloWrdel%20ol)
**How (or rather, why) they work**:
The Diagonal Burrows-Wheeler transform is basically every other character of the string, with wrapping from the end. If we treat the String as a 2D matrix of 2 columns, it simply boils down to taking the transform of the matrix. Example:
```
Hello World
```
Is represented as 2D matrix as
```
He
ll
o
Wo
rl
d
```
Now, simply reading it column wise, give:
```
HloWrdel ol
```
Which is the Burrows-Wheeler transform.
Decoding is simply reverse of the process, write the string as a 2 row 2D matrix and read column wise.
**Code expansion**:
Encoder:
```
q "Read the input";
2/ "divide it into sub arrays of 2 characters";
z "Take transform";
```
Decoder:
```
q_, "Read the input, take copy and get length of copy";
2/ "Divide the length by 2";
)/ "Increment and split the input into two rows";
z "Take transform";
```
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
E=lambda x:(x+x)[::2]
D=lambda y:(-~len(y)/2*y)[::len(y)/2+1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/39U2JzE3KSVRocJKo0K7QjPaysoolssFJlpppaFbl5Oap1GpqW@kVQmShvG0DWP/F9sqeaTm5OQrhOcX5aQocRUUZeaVKLhqFGtCmS4aII7mfwA "Python 2 – Try It Online")
*Thanks to l4m2 for 4 bytes.*
`E` encrypts and `D` decrypts. I'm not counting the `E=` and `D=` for the score.
The decryption takes every `n`'th character wrapping around, where `n` is half the string length round up. The reason this inverts is that `2` and `n` are inverses modulo the length of the string, so taking every `n`th character inverts taking every `2`nd one.
If using a single function were allowed, I could do 44 bytes
```
def F(x,b):n=1+len(x)**b>>b;return(n*x)[::n]
```
The encrypts when `b` is `False` and decrypts when `b` is `True`. The expression `1+len(x)**b>>b` is equal to `[2,len(x)/2+1][b]`.
[Answer]
# J, 10 + 10 = 20
```
({~#|2*i.@#) 'Hello World'
HloWrdel ol
(/:#|2*i.@#) 'HloWrdel ol'
Hello World
```
(Surrounding braces are not counted into the score as they are not part of the function definition.)
Thanks for [FUZxxl](https://codegolf.stackexchange.com/users/134/fuzxxl) for a 3-byte improvement.
Now it is nicely shown that the two functions are inverses as the first one takes characters from positions defined by the list `#|2*i.@#` and the second function arranges back the characters using the same list as ordering.
[Try it online here.](http://tryj.tk/)
[Answer]
# Pyth - 5 + 11 = 16 bytes
I noticed a pattern! ~Does happy dance~ The transform is just really just looping through the string picking every other elements. It only works on odd since otherwise it would never get half the elements. This is equivalent to rotating a 2 wide matrix.
### Encoder:
```
%2*2z
```
Python's step slicing doesn't loop around so I repeated the string.
```
%2 Take every other elements
*2z Double input string
```
### Decoder:
```
K/hlz2%K*Kz
```
Again no wrap-around for step-slicing.
```
K/hlz2 K=length of (input+1)/2
%K Every kth element
*Kz From K*the input
```
[Answer]
# GNU sed -r, (20 + 104 + 1) = 125
The extra +1 in the score is for the -r option to sed. Odd length input strings are assumed.
### Encoder:
```
s/.*/&&/
s/(.)./\1/g
```
* Double up the input string
* Drop every odd (counting from 1) character
### Decoder:
The decoder makes use of `:` as a temporary marker character, so if it appears in the input string, you'll get undefined behaviour. If the input string is restricted to the 95 ASCII characters, then these markers can be replaced with something outside the ASCII range (e.g. BEL 0x7) to fix this.
```
s/.*/:&:/
:l;s/:(.)(.+)(.):/\1:\2:\3/;tl
s/:(.*)/\1:/
:m;s/(.)(.*):(.?)(.*):(.*)/\2:\4:\5\1\3/;tm
s/://g
```
* Put `:` markers at the start and end of the input string
* Shuffle the first `:` forward and second `:` backward one character at a time until the `:` markers are either side of the middle character
* Remove the first `:` and add another `:` to the end leaving "A:B:", where A is the string composed of odd characters from the plaintext input and B is the string composed of the even characters
* Riffle the characters of A and B together after the last `:` to reassemble the plaintext input
* Remove the remaining `:` markers
[Answer]
# JavaScript ES6, 41 + 49 = 90 bytes
### Encoder
```
(t=>t.replace(/./g,(_,o)=>t[o*2%t.length]))('Hello World')
```
### Decoder
```
(t=>t.replace(/./g,(_,o)=>t[-~(l=t.length)/2*o%l]))('HloWrdel ol')
```
These are anonymous functions, so I only counting the code inside the parentheses because that is the whole function definition. Try it out with the snippet below: (modified to use ES5)
```
E=function(t){
return t.replace(/./g,function(_,o){
return t[o*2%t.length]
})
}
D=function(t){
return t.replace(/./g,function(_,o){
return t[-~(l=t.length)/2*o%l]
})
}
i=prompt();
alert('Encoded: '+E(i)+'\nDecoded: '+D(i))
```
[Answer]
# Python 3 - 34 + ~~176~~ 167 + ~~11~~ 16(math) = ~~221~~ 217
Messy, but I coded it all by myself:
```
import math as m
def a(x):
return x[::2] + x[1::2]
def b(x):
if len(x) % 2 == 0:
x += " "
c=""
for i in range(m.floor(len(x)/2)):
c+=x[i]
c+=x[i+m.floor((len(x)+1)/2)]
c+=x[m.floor((len(x)-1)/2)]
return c
```
Edit 1: (*literally as I write this, I realised how to shave off 4 bytes*)
The encoder just takes every other character and combines them, and the decoder is the inverse of that (takes every n/2th character) in the most messy way possible.
(Also formatted)
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
A=lambda x:(x+x)[::2]
def B(x):t=1+len(x)>>1;return(x*t)[::t]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/39E2JzE3KSVRocJKo0K7QjPaysoolislNU3BSaNC06rE1lA7JzUPyLSzM7QuSi0pLQJytEpA6kpi/xcUZeaVaDhqKHmk5uTkK4TnF@WkKGlqckHEnYDiOfnhRSmpOQr5OUDx/wA "Python 3 – Try It Online")
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 18 + 51 = 69 bytes
## Encoder, 18 bytes
```
o<esc>kqqlxjpkl@qq@qgJ
```
[Try it online!](https://tio.run/##K/v/P98mtTjZLruwMKciqyA7x6Gw0KEw3ev/f4/UnJx8hfD8opyU/7plAA "V (vim) – Try It Online")
Moves every other character to the next line, and joins the two.
## Decoder, 51 bytes
```
YpC<c-r>=strlen('<c-r>"')/2+1
<esc>Dk@"li
<esc>jdd{qqld$}o<esc>pk0@qq@q
```
[Try it online!](https://tio.run/##K/v/P7LA2SZZt8jOtrikKCc1T0MdzFNS19Q30jbkskktTrZzyXZQysmEsLNSUqoLC3NSVGrzwfyCbAOHwkKHwv//PXLyw4tSUnMU8nP@65YBAA "V (vim) – Try It Online")
Uses a recursive macro to delete till the end and use it as a flatten-transpose. This took a while to figure out.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 + 3 = 5 bytes
## Encoder
```
Œœ
```
[Try it online!](https://tio.run/##y0rNyan8///opKOT////7wHk5SuE5xflpAAA "Jelly – Try It Online")
Split the input into odd and even indices. The two strings are then implicitly concatenated.
## Decoder
```
ŒHZ
```
[Try it online!](https://tio.run/##y0rNyan8///oJI@o////e@TkhxelpOYo5OcAAA "Jelly – Try It Online")
Split into two halves, transpose, implicitly concatenate.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 2+7=9 bytes
## Encoder
```
y+
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=y%2B&inputs=HloWrdel%20ol!&header=&footer=)
## Decoder
```
:½h$½tY
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%3A%C2%BDh%24%C2%BDtY&inputs=HloWrdel%20ol!&header=&footer=)
] |
[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 9 years ago.
[Improve this question](/posts/38499/edit)
My family has an e-commerce business. On our own site, we force people to choose their state from a dropdown menu when they enter their address, but through some other channels we use, customers can enter anything they want into the box.
My mom loves the invoice templates I made for her, which are automagically generated. But because they're so pretty and balanced, she can't stand it when people WRITE OUT the names of their states, or worse, write something like "new jersey." She says it ruins the look.
My dad likes code to be lightweight. So rather than using a switch-case block, he wants a leaner solution.
So the challenge is to make a short function that takes the possible inputs and returns a two letter abbreviation (capitalized, for Mom). We're going to make a (faulty) assumption that our users can spell and always put a space in the name (where needed) or pass in the correct abbreviation. The scope is the 50 US states.
* New York
* new york
* NY
* ny
are all acceptable inputs for New York, and should output NY.
If something like New Yrok is passed in, the function can return the original value.
You can use any common language. This is a popularity contest, so the one with the most votes at the end of a week wins. I assume that this will favor novelty and utility.
**EDIT:** The description is story fluff, but I was working a similar project and thought that there must be a more interesting way to do it. I can do the project myself (already did) but I thought this was a good place for a more interesting challenge. By "Any common language" I was excluding custom languages/libraries designed for this challenge - I was trying to look for novel methods, rather than free code help. I figure everyone has done this at some point, but it would be fun to do it in an unusual way. I find that the most interesting projects are the ones where you tackle everyday tasks in new and interesting ways - that's why this is a popularity contest rather than golf.
[Answer]
# Ruby
Thought it would be interesting to extract the state abbreviations without writing any of the names or abbrevations explicitly. This one does not take misspelling of the input into consideration, because we don't care about such thing here on codegolf.SE, *rihgt*?
```
def f(s)
[
/(.).* (.)/, # two words
/^([CDGHKLPV]).*(.)$/, # first and last letter
/^(.).*([ZVX])/, # unique letter
/^([NFOUW])(.)/, # two first letters
/^(.)([DNR])/, # unique second letter
/^(.).*(L|N)\2/, # double letters
/^(.).SS(A|O)/, # double S before the one used
/^(.).*?[SNW](.)/, # identified by the letters before them
/(.)(.)/ # two first letters
].find { |r| r =~ s.upcase }
$1+$2
end
```
It took a conciderable time to figure out clever patterns to match all the states. The order of the patterns is important -- each consecutive pattern applies to the remaining states that were not matched by a previous pattern:
All states with two words in them use the initial letters of the two words:
>
> **N**ew **H**ampshire, **N**ew **J**ersey, **N**ew **M**exico, **N**ew **Y**ork, **N**orth **C**arolina, **N**orth **D**akota, **R**hode **I**sland, **S**outh **C**arolina, **S**outh **D**akota, **W**est **V**irginia
>
>
>
All states beggining with any letter in {`CDGHKLPV`} use the first and last letter in the name:
>
> **C**aliforni**a**, **C**olorad**o**, **C**onnecticu**t**, **D**elawar**e**, **G**eorgi**a**, **H**awai**i**, **K**ansa**s**, **K**entuck**y**, **L**ouisian**a**, **P**ennsylvani**a**, **V**irgini**a**, **V**ermon**t**
>
>
>
Of the remaining states, the letters {`ZVX`} are unique:
>
> **A**ri**z**ona, **N**e**v**ada, **T**e**x**as
>
>
>
All remaining states beginning with {`FNOUW`} use the two first letters.
>
> **Fl**orida, **Ne**braska, **Oh**io, **Ok**lahoma, **Or**egon, **Ut**ah, **Wa**shington, **Wi**sconsin, **Wy**oming
>
>
>
Then, {`DNR`} are unique as second letters:
>
> **Ar**kansas, **In**diana, **Id**aho
>
>
>
It's really getting hard to make general patterns, but...
Only three remaining states use double `N` or `L`, and the double letter is used in the state abbreviation:
>
> **T**en**n**essee, **M**in**n**esota, **I**l**l**inois
>
>
>
`A` or `O` after double *S* is unique to
>
> **M**ass**a**chusetts and **M**iss**o**uri
>
>
>
Whenever {`SNW`} appear *before* other letters in the remaining state names, the letters *after them* are used in the abbreviations:
>
> **A**las**k**a, **M**arylan**d**, **M**ain**e**, **M**is**s**issippi, **M**on**t**ana, **I**ow**a**
>
>
>
Two left. These use the two first letters:
>
> **Al**abama, **Mi**chigan
>
>
>
---
It can be golfed of course:
# Ruby 2 – ~~191~~ ~~165~~ 154 characters
Another 26 characters off by uglifying the regexes a bit. Also, one of the original regexes turned out to be redundant!
```
gets;[/.* (.)/,/^[CDGHKLPV].*(.)$/,/.*([ZVX])/,/^[NFOUW](.)/,/^.([DNR])/,/.*(L|N)\1/,
/.*SS(A|O)/,/.*?[SNW](.)/,/.(.)/].find{|r|$_.upcase=~r}
puts $&[0]+$1
```
[Answer]
# C#
I used characters already in the states for the abbreviations to shorten up the state string.
```
public string GetAbbr(string state)
{
var states =
new[] {
"AlasKa", "ALabama", "AriZona", "ARkansas", "CAlifornia", "COlorado", "ConnecticuT",
"DElaware", "FLorida", "GeorgiA", "HawaiI", "IDaho", "ILlinois", "INdiana", "IowA", "KansaS",
"KentuckY", "LouisianA", "MainE", "MarylanD", "MAssachusetts", "MIchigan", "MinNnesota",
"MiSsissippi", "MissOuri", "MonTana", "NEbraska", "NeVada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota", "OHio", "OKlahoma", "ORegon",
"PennsylvaniA", "Rhode Island", "South Carolina", "South Dakota", "TeNnessee", "TeXas", "UTah",
"VermonT", "VirginiA", "WAshington", "washington D.C.", "West Virginia", "WIsconsin", "WYoming"
};
var all = states.ToDictionary(st => string.Concat(st.Where(char.IsUpper)));
var wanted = all.FirstOrDefault(pair => state.ToUpper().Equals(pair.Value.ToUpper()) || state.ToUpper().Equals(pair.Key));
return wanted.Key ?? state;
}
```
[Answer]
# JavaScript (E6)
Here the bulk is the list of names, using the [camelCase](https://codegolf.stackexchange.com/questions/35435/spell-out-numbers-in-french/35483#35483) trick to shorten a bit. Golfed, 617 bytes.
```
F=i=>
"AkAlAzArCaCoCtDeFlGaHiIdIlInIaKsKyLaMeMdMaMiMnMsMoMtNeNvNhNjNmNyNcNdOhOkOrPaRiScSdTnTxUtVtVaWaWvWiWyAlaskaAlabamaArizonaArkansasCaliforniaColoradoConnecticutDelawareFloridaGeorgiaHawaiiIdahoIllinoisIndianaIowaKansasKentuckyLouisianaMaineMarylandMassachusettsMichiganMinnesotaMississippiMissouriMontanaNebraskaNevadaNew hampshireNew jerseyNew mexicoNew yorkNorth carolinaNorth dakotaOhioOklahomaOregonPennsylvaniaRhode islandSouth carolinaSouth dakotaTennesseeTexasUtahVermontVirginiaWashingtonWest virginiaWisconsinWyoming"
.match(/.[^A-Z]*/g).map((w,q)=>U(w,U(w)==U(i)?p=q%50:p),U=s=>s.toUpperCase(),p=-1)[p]||i
```
[Answer]
## Python
Decided just to do this as a code-golf challenge. Got it down to ~~906~~ ~~713~~ 694 chars with the help of daniero and hsl:
```
s='AK,AL,AZ,AR,CA,CO,CT,DE,FL,GA,HI,ID,IL,IN,IA,KS,KY,LA,ME,MD,MA,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,OH,OK,OR,PA,RI,SC,SD,TN,TX,UT,VT,VA,WA,WV,WI,WY,ALASKA,ALABAMA,ARIZONA,ARKANSAS,CALIFORNIA,COLORADO,CONNECTICUT,DELAWARE,FLORIDA,GEORGIA,HAWAII,IDAHO,ILLINOIS,INDIANA,IOWA,KANSAS,KENTUCKY,LOUISIANA,MAINE,MARYLAND,MASSACHUSETTS,MICHIGAN,MINNESOTA,MISSISSIPPI,MISSOURI,MONTANA,NEBRASKA,NEVADA,NEW HAMPSHIRE,NEW JERSEY,NEW MEXICO,NEW YORK,NORTH CAROLINA,NORTH DAKOTA,OHIO,OKLAHOMA,OREGON,PENNSYLVANIA,RHODE ISLAND,SOUTH CAROLINA,SOUTH DAKOTA,TENNESSEE,TEXAS,UTAH,VERMONT,VIRGINIA,WASHINGTON,WEST VIRGINIA,WISCONSIN,WYOMING'.split(",")
x=input().upper()
print(s[s.index(x)%50]if x in s else x)
```
However, if modules are allowed (like the [us module](https://pypi.python.org/pypi/us)), I can get it down to 130 chars:
```
import us
i=raw_input()
x=us.states.lookup(i)
print x.abbr if x else i
```
And if you didn't have to return the original value when the state doesn't exist I could get it down to 50 chars:
```
import us
print us.states.lookup(raw_input()).abbr
```
[Answer]
## bash + sed, 291 bytes
Shameless conversion of Daniero's Ruby solution to sed:
```
echo $*|tr a-z A-Z|sed -e\
"/\(.\).* \(.\).*/b1;/^\([CDGHKLPV]\).*\(.\)$/b1;/^\(.\).*\([ZVX]\).*/b1;\
/^\([NFOUW]\)\(.\).*/b1;/^\(.\)\([DNR]\).*/b1;/^\(.\).*\([LN]\)[LN].*/b1;\
/^\(.\).*SS\([AO]\).*/b1;/^\(.\).*\([ED])\)$/b1;/^\(.\).*[SNW]\(.\).*/b1;\
/\(.\)\(.\).*/b1;:1 s//\1\2/"
```
[Answer]
## Golfscript - 750 653
The bulk is in the state names and abbreviations.
```
{.96>32*-}%.,2>{"ALABAMA,AL,ALASKA,AK,ARIZONA,AZ,ARKANSAS,AR,CALIFORNIA,CA,COLORADO,CO,CONNECTICUT,CT,DELAWARE,DE,FLORIDA,FL,GEORGIA,GA,HAWAII,HI,IDAHO,ID,ILLINOIS,IL,INDIANA,IN,IOWA,IA,KANSAS,KS,KENTUCKY,KY,LOUISIANA,LA,MAINE,ME,MARYLAND,MD,MASSACHUSETTS,MA,MICHIGAN,MI,MINNESOTA,MN,MISSISSIPPI,MS,MISSOURI,MO,MONTANA,MT,NEBRASKA,NE,NEVADA,NV,NEW HAMPSHIRE,NH,NEW JERSEY,NJ,NEW MEXICO,NM,NEW YORK,NY,NORTH CAROLINA,NC,NORTH DAKOTA,ND,OHIO,OH,OKLAHOMA,OK,OREGON,OR,PENNSYLVANIA,PA,RHODE ISLAND,RI,SOUTH CAROLINA,SC,SOUTH DAKOTA,SD,TENNESSEE,TN,TEXAS,TX,UTAH,UT,VERMONT,VT,VIRGINIA,VA,WASHINGTON,WA,WEST VIRGINIA,WV,WISCONSIN,WI,WYOMING,WY"","/.@?)=}{}if
```
Explanation:
```
{ }% Map this to every character in the input string:
.96>32*- Subtract 32 from the ASCII value if it's from "a" onwards.
This turns every lowercase letter into an uppercase letter.
.,2> Check if the input length is greater than 2.
{ } If it is, they inputted the full name.
"..." Our string is in the form "STATE NAME,STATE ABBREVIATION".
","/ We split the string at every comma to turn it into an array.
.@? Then we see where the input string is in the array...
)= ...then we return the value right next to it.
{} If not, they inputted the abbreviation.
...do nothing.
if EndIf
(implied) Print the abbreviation
```
[Answer]
# PHP
My attempt, which was not as successful as I had hoped, uses string length and some specific character placement to extract the abbreviation from the state name. Probably some better sequencing of name elimination is possible.
```
function findAbb ($state) {
$first = substr($state, 0, 1);
$last = substr($state, -2,1);
$state = strtolower($state);
if (strlen($state) < 4) {
return strtoupper($state);
}
if (strpos($state, ' ')) { //if it's a space, return the first letter of each word.
$space_index = strpos($state, ' ');
$state = explode(' ', $state);
return strtoupper(substr($state[0], 0, 1) . substr($state[1], 0, 1));
}
if (startsWith($state, 'io')) { //iowa is annoying, get rid of it.
return strtoupper($first . $last);
}
if (startsWith($state, 'w,i')) { //if it starts with a W, return the first 2.
return strtoupper(substr($state, 0, 2));
}
if (strlen($state) < 7 && strpos($state, 'm')===false) { //matches texas, ohio, and utah.
return strtoupper($first . substr($state, -4,1));
}
if (strlen($state) < 7 && substr($state, 0, 1) > 'j' && substr($state, 0, 1) < 'n') { //matches maine, kansas, and hawaii
return strtoupper($first . $last);
}
if (startsWith($state, 'c,d,k,l,p,v,g,h')) { //some unique states
return strtoupper($first . $last);
}
if (strpos($state, 'sk')) {
return strtoupper ('ak');
}
if (startsWith($state, 'k,l', 1)) {
return strtoupper(substr($state, 0, 2));
}
if (startsWith($state, 'n')) {
return strtoupper($first . substr($state, 2, 1));
}
if (startsWith($state, 'n', 2) || startsWith($state, 'z', 3)) { //montana, tennessee, minnesota, and arizona
return strtoupper($first . substr($state, 3, 1));
}
if (startsWith($state, 'm') && ($last == 's') || ($last == 'n')) {
return strtoupper(substr($state, 0, 2));
}
if (strpos($state,'o')) {
return strtoupper($first . 'o');
}
if (strpos($state,'y')) {
return strtoupper($first . 'd');
}
if (strpos($state,'r')) {
return strtoupper($first . 'r');
}
if (strpos($state,'ss')) {
return strtoupper($first . 's');
}
return $state; //otherwise return the name of the state (it was mispelled).
}
function startsWith ($state, $letters, $index = 0) { //takes a comma separated array and finds contents.
$letters = split(',',$letters);
for ($q = 0; $q<count($letters); $q++) {
if (strpos($state,$letters[$q]) === $index) {
return true;
}
}
return false;
}
```
Of course, it can be golfed. This is my first golfing attempt, so insight appreciated. (911)
```
function t($s){$s=u($s);$f=b($s,0,1);$l=b($s,-2,1);
if(strlen($s)<4)return $s;if(strpos($s,' '))$s=split(' ',$s);
return b($s[0],0,1).b($s[1],0,1);
if(w($s,'IO'))return $f.$l;
if(w($s,'W,I'))return b($s,0,2);
if(strlen($s)<7 && strpos($s,'M')===false)return $f.b($s,-4,1);
if(strlen($s)<7 && b($s,0,1)>'I' && b($s,0,1)<'N')return $f.$l;
if(w($s,'C,D,K,L,P,V,G,H'))return $f.$l;if(strpos($s, 'SK'))return 'AK';
if(w($s,'K,L',1))return b($s,0,2);if(w($s,'N'))return $f.b($s,2,1);
if(w($s,'N',2) || w($s,'Z',3))return $f.b($s,3,1);
if(w($s,'M') && ($l=='S') || ($l=='N'))return b($s,0,2);
if(strpos($s,'O'))return $f.'O';
if(strpos($s,'Y'))return $f.'D';if(strpos($s,'R'))return $f.'R';
if(strpos($s,'SS'))return $f.'S';return $s;}function w($s,$l,$i=0){$l=split(',',$l);
for($q=0;$q<count($l);$q++)if(strpos($s,$l[$q])===$i)return 1;return 0;}
function u($z){return strtoupper($z);}
function b($v,$x,$y){return substr($v,$x,$y);}
```
[Answer]
# Javascript
I know this isn't code golf, but I want to golf it anyway. :)
```
var r=new XMLHttpRequest
r.open("GET","https://gist.githubusercontent.com/mshafrir/2646763/raw/f2a89b57193e71010386a73976df92d32221d7ba/states_hash.json",0)
r.send()
var o=r.responseText,m=prompt(),a=m
o=JSON.parse(o)
for(var i in o)if(o[i].toLowerCase()==m.toLowerCase())a=i
alert(a)
```
Yay for new things! (Stack Snippets)
] |
[Question]
[
Given a 20×20 grid of non-negative integers, find a 3×3 sub-grid where the
product of the sums of the individual lines hits the maximum. Spoken in
formulas:
Given the 3×3 sub-grid
$$\mathfrak{U} = \left(\begin{matrix}
x\_{11} & x\_{12} & x\_{13} \\
x\_{21} & x\_{22} & x\_{23} \\
x\_{31} & x\_{32} & x\_{33}
\end{matrix}\right)$$
the function to maximize is
$$\begin{align}
f(\mathfrak{U}) & = \left(\begin{matrix}
\underbrace{(x\_{11} + x\_{12} + x\_{13})}\_\cdot \\
\overbrace{\underbrace{(x\_{21} + x\_{22} + x\_{23})}}\_\cdot \\
\overbrace{(x\_{31} + x\_{32} + x\_{33})} \\
\end{matrix}\right) \\
& = (x\_{11} + x\_{12} + x\_{13}) \cdot (x\_{21} + x\_{22} + x\_{23}) \cdot (x\_{31} + x\_{32} + x\_{33})
\end{align}$$
Per line the sum is calculated and the individual sums are then
multiplied.
An example (only 5×5):
$$\begin{matrix}
40 & 30 & 42 & 22 & 74 \\
294 & 97 & \color{red} {35} & \color{red}{272} & \color{red}{167} \\
52 & 8 & \color{red}{163} & \color{red}{270} & \color{red}{242} \\
247 & 130 & \color{red}{216} & \color{red} {68} & \color{red}{266} \\
283 & 245 & 164 & 53 & 148 \\
\end{matrix}$$
The part highlighted in red is the part where the value of the function
\$f(\mathfrak{U})\$ is largest for the entire grid:
>
> \$(35 + 272 + 167) ⋅ (163 + 270 + 242) ⋅ (216 + 68 + 266) = 175972500\$
>
>
>
**Input**
Input is given on standard input and consists of 20 lines, each containing
20 numbers, separated by a space character (U+0020). The numbers are small
enough that a 32-bit signed integer is sufficient to compute the result.
You may assume input to be given redirected from a file.
**Output**
Output is the result of the function \$f(\mathfrak{U})\$ for the 3×3 sub-grid that
gives the largest result. In above example this would have been
\$175972500\$.
**Sample input 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 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 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 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 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 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 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 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 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 1 5 5 5 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 5 5 5 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 5 5 5 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 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 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 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
```
**Sample output 1**
```
3375
```
**Sample input 2**
```
40 30 42 222 74 265 93 209 115 274 139 177 7 274 12 15 103 36 236 91
294 97 35 272 167 126 18 262 292 48 8 296 85 93 245 4 4 240 276 153
52 8 163 270 242 224 142 72 99 240 199 26 224 198 96 242 295 70 56 247
247 130 216 68 266 142 93 214 30 8 12 163 59 84 40 287 233 65 30 242
283 245 164 53 148 282 73 186 296 3 9 233 184 30 205 221 92 96 5 101
132 228 43 91 228 37 266 140 159 109 10 230 40 114 264 3 266 164 219 283
70 207 218 28 299 78 279 30 179 118 196 138 61 229 110 55 203 73 124 112
16 232 28 187 292 78 194 70 65 203 255 227 176 21 32 225 11 15 92 151
58 237 261 41 213 171 170 111 4 209 99 194 40 108 267 137 179 31 35 221
184 209 264 275 163 268 261 40 198 185 45 188 280 273 54 79 270 286 273 121
208 83 66 156 104 62 188 68 53 194 46 279 280 170 266 148 272 285 178 245
210 130 213 118 165 210 213 66 54 189 166 193 57 213 14 101 143 109 172 101
80 193 287 4 140 65 208 111 8 206 107 285 109 29 211 78 170 247 290 193
148 123 15 164 28 153 222 67 156 165 6 163 114 77 165 17 143 209 278 100
3 102 58 148 82 181 84 29 2 236 231 195 118 278 252 257 179 123 276 287
143 141 254 142 200 243 171 32 164 195 235 260 269 191 190 46 65 166 82 146
69 194 65 220 234 110 45 135 125 208 138 20 233 291 256 162 148 216 247 138
10 53 164 107 2 270 226 227 88 206 193 13 41 130 218 249 76 35 207 91
199 36 207 256 58 215 28 277 234 29 198 148 219 244 136 16 30 258 219 264
183 118 48 218 15 125 279 103 73 8 86 113 9 157 239 273 146 208 50 86
```
**Sample output 2**
```
328536000
```
**Sample input 3**
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
```
**Sample output 3**
```
185193
```
**Sample input 4**
```
242 248 292 60 9 45 94 97 294 202 219 118 115 243 207 81 288 289 241 232
236 225 205 227 242 85 139 63 5 162 170 121 208 133 22 235 125 288 209 270
31 182 108 170 88 268 297 66 249 158 285 157 267 117 150 18 44 66 117 223
205 32 93 132 33 99 209 282 222 272 255 1 80 270 202 54 117 35 139 273
87 74 113 146 177 14 154 92 282 4 192 60 171 286 66 299 89 276 138 289
60 16 143 277 202 284 77 296 215 96 200 10 226 143 136 131 218 246 254 20
244 118 299 218 81 195 129 93 205 202 264 141 196 150 214 72 231 136 243 192
236 157 176 187 104 182 134 29 151 234 81 143 22 119 45 241 17 225 197 7
156 284 92 13 131 60 113 77 228 65 200 83 3 63 83 88 241 113 115 198
62 101 242 270 121 122 119 78 105 273 55 7 239 236 37 252 66 164 56 44
70 57 100 87 34 298 140 259 36 257 1 204 110 299 245 56 43 121 192 10
240 36 272 255 10 194 143 66 27 131 22 78 57 71 128 5 1 155 236 122
281 160 42 147 272 151 196 240 291 280 209 245 271 46 103 35 85 145 78 140
155 74 232 205 235 223 147 39 171 240 56 187 184 70 28 81 293 125 283 159
297 203 75 46 221 77 106 12 268 94 220 156 78 97 266 208 228 137 212 49
4 157 69 51 225 23 61 202 19 23 41 260 161 218 142 251 299 187 283 158
118 136 71 77 21 199 110 87 103 120 153 157 213 234 155 141 135 24 120 199
16 204 292 245 54 260 294 159 254 15 209 41 154 54 231 167 87 291 31 26
212 274 99 199 170 184 47 227 64 2 117 275 67 84 143 214 143 125 24 61
205 250 133 88 210 112 4 160 3 287 54 143 293 94 287 42 105 94 76 169
```
**Sample output 4**
```
311042813
```
For the interested, the lengths of the submissions we got in our contest:
>
> 120 – AWK
>
> 124 – C
>
> 133 – Haskell
>
> 174 – C
>
> 270 – VB.NET
>
>
>
And our own (unranked) solutions:
>
> 55 – Golfscript
>
> 118 – [Ruby](https://codegolf.stackexchange.com/questions/1159/numbers-sums-products/1191#1191)
>
> 192 – [PowerShell](https://codegolf.stackexchange.com/questions/1159/numbers-sums-products/1187#1187)
>
>
>
[Answer]
# Python - 146 characters
```
g=[map(int,raw_input().split(' '))for i in' '*20]
r=range(18)
print max(reduce(int.__mul__,[sum(v[j:j+3])for v in g[i:i+3]])for j in r for i in r)
```
[Answer]
## J, 38
```
":@(>./@,@(3*/\3+/\"1".;._2))&.stdin''
```
Sample use:
```
$ jconsole nsp.ijs <g1
3375
$ jconsole nsp.ijs <g2
328536000
$ jconsole nsp.ijs <g3
185193
```
Rough explanations:
* `".;._2` converts raw input to matrix, `":` converts the result to raw output
* `3+/\"1` sums column-wise, 3 by 3
* `3*/\` multiplies row-wise, 3 by 3
* `,` flattens the result
* `>./` extracts the maximum
* `&.stdin''` makes a filter out of it
[Answer]
# C#, ~~324~~ ~~321~~ 308 chars
```
using System;using System.Linq;class X{static void Main(){int m=0,v,x=0,y;Func<int[],int>f=t=>t[x]+t[x+1]+t[x+2];var a=Console.In.ReadToEnd().Trim().Split('\n').Select(l=>l.Split(' ').Select(int.Parse).ToArray()).ToList();for(;x<18;x++)for(y=0;y<18;m=m>v?m:v)v=f(a[y])*f(a[++y])*f(a[y+1]);Console.Write(m);}}
```
## Readable:
```
using System;
using System.Linq;
class X
{
static void Main()
{
int m = 0, v, x = 0, y;
Func<int[], int> f = t => t[x] + t[x + 1] + t[x + 2];
var a = Console.In.ReadToEnd().Trim().Split('\n').Select(l =>
l.Split(' ').Select(int.Parse).ToArray()).ToList();
for (; x < 18; x++)
for (y = 0; y < 18; m = m > v ? m : v)
v = f(a[y]) * f(a[++y]) * f(a[y + 1]);
Console.Write(m);
}
}
```
14 characters could be shaved off by removing both calls to `.Trim()` if you can guarantee that the input will only use `\n` (no `\r`) and there is no newline after the last row of numbers.
### Edits
* **(333 → 324 chars)** Realised I could add `x, y` to the declaration at the top instead of declaring each in the `for` statement; that I could change *one* of the `ToArray`s to `ToList`; that I could increment `y` inside the call to `f` and thus get rid of it in the `for`.
* **(324 → 321 chars)** Move the assignment to `m` into the `for` statement, getting rid of a semicolon and two curlies.
* **(321 → 308 chars)** Joey’s suggestions in the comments. Thanks!
[Answer]
# Java, 299 Chars
```
class M{public static void main(String[]a){java.util.Scanner s=new java.util.Scanner(System.in);int i,j,k,p,m,t=20,x[][]=new int[t][t];for(i=m=0;i<t*t;i++)x[i/t][i%t]=s.nextInt();for(i=0;i<18;i++)for(j=0;j<18;j++,m=p>m?p:m)for(p=1,k=i;k<i+3;k++)p*=x[k][j]+x[k][j+1]+x[k][j+2];System.out.print(m);}}
```
[Answer]
## Python (202)
```
import sys;g=map(lambda l:map(int,l.split()),sys.stdin.readlines())
r=range(18)
for j in range(20):l=g[j];g[j]=[sum(l[i:i+3])for i in r]
g=[g[i][j]*g[i+1][j]*g[i+2][j]for i in r for j in r]
print max(g)
```
**Edit:** Fixed r to be range(18) instead of 17.
[Answer]
# Ruby - 78 chars
```
g=*$<
p (0..324).map{|i|eval g[i/18,3].map{|r|eval r.split[i%18,3]*?+}*?*}.max
```
[Answer]
# Ruby, 106 characters
```
k=$<.read.split.map &:to_i;p (0..358).map{|a|a%20>17?0:(0..2).map{|i|k[20*i+a,3].inject:+}.inject(:*)}.max
```
Yet another straightforward solution.
* Edit: Previous solution produced incorrect results for some edge cases.
* Edit: (114 -> 106) Use a flat array, check `index%20` to prevent overflows into the next row.
[Answer]
# Windows PowerShell, 116 ~~117~~ ~~124~~ ~~152~~ ~~170~~
```
$g=-split$input
(0..359|?{$_%20-le17}|%{$i=$_
(0..2|%{$g[($a=$i+20*$_)..($a+2)]-join'+'|iex})-join'*'|iex}|sort)[-1]
```
Fairly straightforward, actually.
[Answer]
# C ~~184~~ 171 Characters
```
#define f(i,b)for(i=0;i<b;i++)
i,j,k,l,m,M,s,a[400];main(){f(i,400)scanf("%d",a+i);f(i,18)f(j,18){m=1;f(k,3){s=0;f(l,3)s+=a[(i+k)*20+j+l];m*=s;}M=m>M?m:M;}printf("%d",M);}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 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")
Complete program.
```
⌈/,{×/+/⍵}⌺3 3↑⍎20⍴'⎕'
```
[Try it online!](https://tio.run/##7Zc9rh1FEIXzWUVnDgC9qe7pv@VYQiKxxEsRIgUHtiUHiI1AQspO7kbM@U6NRUqEhPV4WPfemer6OfV3@vXzm2@@/eH1m@@/@/R4@8vzp8e7t09f//jXb09fPT3e//HT492frbTHzx8f7z/U8/H@91ePD7@@QvRT8X/PR5R/9fci94XJdf/993L/N/w@98l1lnaWq5Zaa5lXqaOX3Uo9d4nopepRNH2fs8z8VYuex6kGHKXq346j7qvsWRryej2mpEaJJW1SvGu5VtGPPcpK7Vcvl/6qrNcpyd6OXiUSQy@nHtohGdOnNO5t0eBz5Iu9itRZbveiI51f89A/OSwNMcrAgWElGI2LUJcjkJ2@y5ITEl2KrLWiyJtNH3WljzGu0psUSNGSJ/q6huNoZftMLCutp0KvURSqXgKPMtGIYZVLsuFvbd7@KBRZDzDWWfDXkwB8aUsZfashG6sd4HHqKHiC4i5TH3NjOCZ5UkwyG22VgSUeCRC5pCzhNIBFPYKEVZQEIcvZyckL@EZKV05VQaisKB6HoHCCnG8yH0eXcUcS5ZK1kP6p95MQgqQqLPmIXsI6SQI5mXa2hcukCp@VsgRdZ8/cO2Xhgxs3VSd6s4icUlHW5O3OGiEVjk4FKCvKGcCpDuK8igqPY9JHAvFlGDP04GsmYrlgq8wEmF79qEIu66clsAAT@VtHZD6WguO0aqrPFLzIuD5aJpUmUAVgisIT2JezbpCXcZK1E09nWgcH/a8XpMQdQIas4MDPqM19B1iLhnHDAiwBS/EwgFSRWpUHMe2QIUbpeR64V4sSiMYFQkEPYNmtXJWd2N2Bc6aqKWvPxOEAvapoDgdK8nu2aD1xOAuhVTuJmkqmB1hTDqg@SQO@CT/sX@MYWSpAU2mGy8VL1nU66o1YAy93XKWZHHPNBIYbH5GDqm9pHmCzTDwxZlk34kqIMibnM8tkXQ01XJU6pGnGmAEMVMgQ9c4kBJJpB2mwvW7rjCZmJB55FPT76bhU4llEFlzOHwGBZnamsqBzwTQJaqntLGmKVWF3jatx/ENpqqaDJpJyrXiKpwetWctdgwDrvNPW0vBy5OXIy5Ev4cjnGWDCwzjRMtZk3QzKJF9wsKrpzuzx4mJmef7LhCx6hzKsAhJweNx7uubCRzGLSBMIbpTjlZ0uFpATmI3jke4Z5nHqRXywNBjmZ24u3rDG5dMYnq7BSEQ5I46VRWSabUzGy0tbD2ptB840kzXIkyxC@LCykp96WXfouNnA6YDZQWHyGTk@D@1biGrkIIW6GtMLBoMqtpPhY19BI/BTpoBnJo8SVAcCI3cogx9sl7crBJCVwMd5msPVFPQaaHHvleEFqex5Q0RyN16te81qkZhr99TO3mIxweX6acJKwOBLttC/M3PRk6LB42A7xv/eTD28pFbyEaEW4TIh88ZZhpUbbXEo8zIqQCUzRKyvhKh1Z7ZywqsaNaFPUosWcyPUrGOY6iQRv8slbpsmHT1ZWy/3dpPzkEcRi5vlyonrguMSEuaUSgJZZky15y7mpbxJcmAYFRFHW5okBnA@Lf25TE5TC2AgwzNTY9YrfZBWRenLHawXWCvcX7@Hr0QBB5tmvU6KryvQD6rvTB@q1FBk3Ie6O0gPp50/UMuVChZ93nQIGie1vlKFNfY7jcs8vLo6Ki3gNoP17YNmMpnv5rGKmKKGzlQ3G71fT3NB2d55z6BtySPUu0rw2sflyhHlokjQ33xjUPExZkyLqss@S9jcDlH4PFcGuyOexTvhNe2H8c87h8sR109T1Lj5sVkdCTHtohRTZG/fSc7L88wpvZIxkjal3gSzG2yO6hcCNITGiO8wwY2ijoMAuZ765rFzdHG9m55usOacMkKQo1kVdJjbttqnEZ5AldHUsto9mD0x5FVS@X6fVYqAHXJfXehcpKjp/Tc "APL (Dyalog Unicode) – Try It Online")
`20⍴'⎕'` reshape the character `⎕` (which stands for evaluated input from stdin) to length 20
`⍎` execute that (gives use 20 lists)
`↑` mix the lists into a matrix
`{`…`}⌺3 3` on each 3-by-3 sub-matrix:
`+/⍵` sum the rows
`×/` multiply the sums
`,` flatten the matrix of sums
`⌈/` find the maximum
[Answer]
## J+tr, 84+10
```
y=:20 20$".(1!:1)3
s=:3 :'(y&((][;.0~3 3,:~[)~))"1(,."0/~i.18)'
>./,([:*/+/"1)"2 s y
```
runs like this `< golfdata tr \\n ' '| ./test.ijs` so I consider the `tr \\n ' '` part as part of the program.
```
y=: 40 30 43 ...
>./,([:*/+/"1)"2 s y
328536000
z =: 20 20 $>:i.20
>./,([:*/+/"1)"2 s z
185193
```
[Answer]
## Haskell, 129 characters
```
import List
t f z@(_:y@(_:x))=zipWith3((f.).f)z y x
main=interact$show.maximum.(t(*)=<<).transpose.map(t(+).map read.words).lines
```
[Answer]
## Golfscript, 48 chars
```
n%"{~}%:^,,{^>3<}%":|~{{+}*}%20/zip|~{{*}*}%$)p;
```
previous one
```
n%{' '%"{~}%:^,,{^>3<}%":|~{{+}*}%}%zip|~{{*}*}%$)p;
```
Some explanations, but I am still newbie in golfscript, some might not be correct, please correct me, if you see something wrong.
```
n% #.lines
{ #.each
' '% #.split ' '
" #"... literal string start
{~}% #.flatten
:^ #assign to variable ^
, #.size
, #.times
{ #.each
^> #^[n:]
3< #[:3]
}% #.map end
" #..." literal string end
:| #assign literal string to variable | to reuse later
~ #eval
{ #.each
{+} #sum
* #.fold
}% #.map end
}% #.map end
zip #.zip
|~ #eval variable | against result of .zip
{ #.each
{*} #product
* #.fold
}% #.map end
$ #.sort
) #uncons / .pop
p #puts
; #discard top item from stack
```
Tests
```
$ cat sample-1159-1.txt | golfscript codegolf-1159.gs
3375
$ cat sample-1159-2.txt | golfscript codegolf-1159.gs
328536000
$ cat sample-1159-3.txt | golfscript codegolf-1159.gs
185193
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
ƈLпḊỴḲ€V+3\€×3\FṀ
```
[Try it online!](https://tio.run/##y0rNyan8//9Yh8/hCYf2P9zR9XD3loc7Nj1qWhOmbRwDpA5PN45xe7iz4f9/QwWiINeouuGlzhQM6a9uiIUfAA "Jelly – Try It Online")
Takes input from STDIN, space and newline separated
---
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
+3\€×3\FṀ
```
[Try it online!](https://tio.run/##7Zc7riVFEERtahWl8RAYnVVdvw2wBBwGEwexATyEwxLYBBbCAGHOSoaNPOJENhoXC2nQ05vRvbc7Kz@Rv6hvv/nuu@9fXj7rb//68Zd3P/e3X7z/44eX93/@9v73X/Xky3c/ffry8lX55M2bN1H/1V95lft/yQ3//fdyHxl@6pDPixvlvmq/6t1qa62uu7Y56um1XadGjNr0KLq@r1VX/mpVz@Pqtc/a9P9EaeeuZ9WOvF7PJalZY0ubFJ9W713148y6U/s96q2/JuttSXL0MppEYurl0kM7JGP6lMZzLBp8znxxdpU6y51RdWTwaxX9l8PSELNOHJhWgtG4CXU7AtkZp245IdGtyHqvirzbdGk7fYx519GlQIq2PNHXPR1Hr8dnYltpuxR6i6pQ9RJ4lIpODLvekg1/6@vxR6HIeoCxzoK/ngTgS1vK6FsL2di9gMelo@AJiqcufayD4VjkSTHJbPRdJ5Z4JEDkkrKE0wAWrQQJaygJQpazi5M38M2UbpxqglBZUTwOQeEEOT9kPsqQcUcS9Za1kP6l94sQgqQqLPmIXsK6SAI5WXa2h8ukCZ@dsgTd1sjcO2Xhgwc3VSd6s4mcUlHW5O3JGiEVjk4FKCvKGcCpDuK6qwqPY9JHAvFlGjP04GsmYrtgm8wEmN6jNCGX9dMTWICJ/K0jMh9bwXFaNTVWCt5kXB89k0oTqAIwReEJ7NtZN8jbOMnahacrrYOD/ukFKXEHkCErKPgZrbvvAGvTMG5YgCVgKZ4GkCpSq/Iglh0yxCi9roJ7rSqBaNwgFPQAlt3KTdmJMxw4Z5qaso1MHA7Qq4qmOFCSP7JF24XDWQi92UnUNDI9wZpyQPVFGvBN@GH/nmVmqQBNoxluFy9Z1@loD2IdvNxxjWZyzC0TGG58RApV39M8wGaZeGKsuh/ElRBlTM5nlsm6Gmq6KnVI04wxAxiokCHqnUkIJMsO0mBnP9YZTcxIPPIoGM/TeavEs4gsuJ0/AgLN7ExlQeeCaRLUUj9Z0hSrwh4aV/PDrFbgGg8aSUq2AqoeH/Rmq08RgqwTT19LRXk98nrk9cjHf@TDEDDlYaBoHWu2HkZl0i9YWNN8Z/p4dTG1vAFkQya9RRlXAQ0oHvier7nyUcwq0gyCHeWAZauLB@QMZud4qHuKeaB6FRfWBuP8yt3FGxa5fJrT8zUYiihnyLG0CE3Tjdl4e23rQWu94Ew3XYM@ySKUDys7GarX9YCRmw9cDpgtFKafkQO0aONCVSNHKeTVoN5wGFSxnwwfGwsigZ8yBTwrmZSgKgjM3KKMfrDd3q9QQJYCH9dlFtdS0Iugx7NZplekMu4dEcneeLWfRatVYrY9Ujubi9UEmxuXKSsBgy/ZQv/JzMVIkgaTg@8Y/2c3jfCa2slIhFqEy4TMG2cZVm60xyHN26gAlcwQsb4Sohae@coFs@rUhD5JLVrMjlCzyzTZSSr@lEs8Nk07RvK2UZ/9Juehj6IWD8@VE/cNyyUkzCmVBLLNmdrIbcxLeZP0wDAqIo72NEkM4HxZ@p8yuUwugIEMr0yNea/0QVsVpe938F5gbbB//Z6@FAUsbJn3Oim@sEBAqL4rfWhSQ5FxIxruID1cdr6glksVPPp6CBFETmp9qQprHE8at5l4c3U0WsBtBu87hWYynR9msoqYoobQNDcbvd8us0HZPnnToG3JI@S7SfA@5XbliHRRJOjvvjOo@JgzJkbNZZ8lbHaHKIyeS4PdEdPinfBa9sP4563D5Yjrl0lqPAzZvI6EmHhRiilyjm8l1@155pTeyRlJm1JvijkMNkf1CwEaQmPEt5jgTtFmIUAuqL57nBxdXPCWpxu8OaeMEORoVgUd5rZt9mmGJ1BjNPWsdk9mTwx5lWR@PGeVImCH3jcXOlcpavpoTpfy9d8 "Jelly – Try It Online")
Takes a 20x20 matrix of integers as input. [+4 bytes](https://tio.run/##7Zc5jiZFEIVt8hSpccGoyKzcLsARcBhMHDQXwEM4HIFLYCEMEOacZLhI874XhcbFQhrU@rtVW2YsL7aX33377t33Ly8f/vztw@@//vXjL1993t/q8v7n/vbLD3/88PL@Jz29vHxdPnvz5k3Uf/Urr@v@X@uGf//9uk8MP1XIF8WFcl@1X/VutbVW113bHPX02q5TI0ZtehVd92vVlU@t6n1cvfZZm/5PlHbuelbtrNfnubRq1tiSJsGn1XtXPZxZd0q/R731a9LellaOXkbTkpj6uPTSBkmZrpJ4jpcG15kfzq4S53VnVG0ZPK2ifxksCTHrxIBpISiNG1e3PZCeceqWEVq65VnvVZ53qy5tp40x7zq6BEjQliW63dN@9Hq8J7aFtkuut6hyVR@BR6Ho@LDrrbXhu74ee@SKtAcYay/4600AvqTlGt21kI7dC3hc2gqeoHjq0mUdFMciTvJJaqPvOtHEKwEikxQljAawaCUIWENI4LKMXey8gW/m6sauJggVFfljF@ROEPND5KMMKbcnUW9pC8lf@r5wIQiq3JKNyMWtiyAQk2VjezhNmvDZuRan2xoZe4csvPFgpvJEXzaekyqKmqw9mSOEwt4pAaVFMQM45UFcd1XisU3yCCC2TGOGHGzNQGwnbJOaANN7lCbkMn96Agswkc/aIvWx5Ry7lVNj5cKbiOvSM6gUgTIAVSSewL4ddYO8jZO0XVi6Ujs46E8fCIkrgAhZQMHOaN11B1ibgnHBAiwOS/A0gGSRSpUXsWyQIUbodRXMa1UBROIGoaAG0OxSbopOnGHH2dNUlG1k4DCAWpU3xY4S/JEl2i4MzkTozUYiphHpCdakA6IvwoBtwg/99ywzUwVoGsVwO3mJunZHexDr4OWKaxSTfW4ZwHDhs6SQ9T3VA2ymiTvGqvtBXAFRxGR8Rpmoq6Cms1Kb1M1oM4CBCCki3@mEQLJsIAV29qOd1kSPxCK3gvG8nbdSPJPIC7fjh0OgmZWpKGhf0E2CXOonU5pkldtD7Wp@7NVyXO1BLUnBlkPV7YPabPVJQpB14KlriSivW163vG759Ld8bAKmPDQUjWP11kOrTPoFC2vq73Qfjy66lieAdEilpyjtKqABxQ3f/TVHPoIZRepBsKNssEx18YDswcwcN3V3MTdUj@LC2KCdXzm7@MIgl01zur8GTRHhNDmGFq6pu9Ebb49tvWitF4zppmvQJ2mE8qFlJ0P1uB4wcvOByw4zhcL0M7KBFk1cqGpkK4W8GtQbDoMo5pPhY2JBJLBTqoBnJZMSVIUFM6corR9st@crFJChwOW6zOJaLvQg6PFMlukRqYh7RkSyNz7tZ9BqlJhtj5TO5GI0webGZcqKw@BLtJB/MnIxkqTB5OA7xv@ZTSM8pnYyEqEW4TQh8sZZihUbzXFI8zYqQCU1eKxbXNTAM1@5YFadnNCV0CLF7Agxu0yTnaTiT7rEo9O0YyRvG/WZbzIe@ihq8fBcGXHfsFxcQp1CiSPbnKmNnMZ8lDVJDwyjPGJrT5X4AM6XV/@TJpfJBTAQ4ZWhMe@VPGirvPT5Dt4LrA32r@fpQ1HAwpZ5r4PiAwsEhOy70oYmMSQZJ6LhCtLLZeMLYjlUwaOvhxBB5CTWh6qwxPGEcZuJN2dHowRcZvC@Uygm0/lhJiuPSWoITXOxUfvtMhuU7pMnDcqWOEK@mxbep9zOHJEukgT53WcGJR99xsSoOe0zhc3uWAqj59Bgc8S0@Ca8lu0w/nnqcDpi@mWSGg9DNq8jICZepGIuOcenkut2P3NI7@SMhE2hN8UcBputemIBBaE24lNMcKZos@AgB1SfPU62Lg54y90N3pxdRgiyNbOCCnPZNts0wx2o0Zp6Zrs7szuGrEoyP569ChGwQ@@bE52jFDl91KdL@eZv) to input as a space and newline separated grid
## How it works
```
+3\€×3\FṀ - Main link. Takes a matrix M on the left
€ - Over each row r:
3\ - Over each overlapping triple:
+ - Take the sum
3\ - Over each overlapping triple:
× - Take the product
F - Flatten
Ṁ - Take the maximum
```
[Answer]
# Powershell, 103 bytes
```
(($x=-split($args-replace'(\d+)(?= (\d+) (\d+))','$1+$2+$3')|iex)|%{$_*$x[$j+20]*$x[$j+++40]}|sort)[-1]
```
Explanation:
* The regexp transforms each string like `1 2 3 4 5 6` to the string like `1+2+3 2+3+4 3+4+5 5 6`;
* Then the script splits the string `1+2+3 2+3+4 3+4+5 5 6` by spaces and evaluates each element by `iex` (alias for [Invoke-Expression](https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-Expression)). A result is an array like `6,9,11,5,6`;
* Finally, the script concatenates all arrays to one, calulates a products and returns a maximum.
It is essential that we need a *maximum* of products of sum of *non-negative integers*. So we don't need to filter out the last 2 values in each row and last 2 rows.
## Less golfed test script
```
$f = {
$x=-split($args-replace'(\d+)(?= (\d+) (\d+))','$1+$2+$3')|iex
($x|%{$_*$x[$j+20]*$x[$j+++40]}|sort)[-1]
}
@(
,( 3375,
"1 2 3 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1",
"4 3 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1",
"4 3 3 3 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 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",
"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 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 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 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 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",
"1 1 1 1 1 1 1 1 1 1 1 1 5 5 5 1 1 1 1 1",
"1 1 1 1 1 1 1 1 1 1 1 1 5 5 5 1 1 1 1 1",
"1 1 1 1 1 1 1 1 1 1 1 1 5 5 5 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 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 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 1",
"1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1")
,( 328536000,
"40 30 42 222 74 265 93 209 115 274 139 177 7 274 12 15 103 36 236 91",
"294 97 35 272 167 126 18 262 292 48 8 296 85 93 245 4 4 240 276 153",
"52 8 163 270 242 224 142 72 99 240 199 26 224 198 96 242 295 70 56 247",
"247 130 216 68 266 142 93 214 30 8 12 163 59 84 40 287 233 65 30 242",
"283 245 164 53 148 282 73 186 296 3 9 233 184 30 205 221 92 96 5 101",
"132 228 43 91 228 37 266 140 159 109 10 230 40 114 264 3 266 164 219 283",
"70 207 218 28 299 78 279 30 179 118 196 138 61 229 110 55 203 73 124 112",
"16 232 28 187 292 78 194 70 65 203 255 227 176 21 32 225 11 15 92 151",
"58 237 261 41 213 171 170 111 4 209 99 194 40 108 267 137 179 31 35 221",
"184 209 264 275 163 268 261 40 198 185 45 188 280 273 54 79 270 286 273 121",
"208 83 66 156 104 62 188 68 53 194 46 279 280 170 266 148 272 285 178 245",
"210 130 213 118 165 210 213 66 54 189 166 193 57 213 14 101 143 109 172 101",
"80 193 287 4 140 65 208 111 8 206 107 285 109 29 211 78 170 247 290 193",
"148 123 15 164 28 153 222 67 156 165 6 163 114 77 165 17 143 209 278 100",
"3 102 58 148 82 181 84 29 2 236 231 195 118 278 252 257 179 123 276 287",
"143 141 254 142 200 243 171 32 164 195 235 260 269 191 190 46 65 166 82 146",
"69 194 65 220 234 110 45 135 125 208 138 20 233 291 256 162 148 216 247 138",
"10 53 164 107 2 270 226 227 88 206 193 13 41 130 218 249 76 35 207 91",
"199 36 207 256 58 215 28 277 234 29 198 148 219 244 136 16 30 258 219 264",
"183 118 48 218 15 125 279 103 73 8 86 113 9 157 239 273 146 208 50 86")
,( 185193,
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20")
,( 311042813,
"242 248 292 60 9 45 94 97 294 202 219 118 115 243 207 81 288 289 241 232",
"236 225 205 227 242 85 139 63 5 162 170 121 208 133 22 235 125 288 209 270",
"31 182 108 170 88 268 297 66 249 158 285 157 267 117 150 18 44 66 117 223",
"205 32 93 132 33 99 209 282 222 272 255 1 80 270 202 54 117 35 139 273",
"87 74 113 146 177 14 154 92 282 4 192 60 171 286 66 299 89 276 138 289",
"60 16 143 277 202 284 77 296 215 96 200 10 226 143 136 131 218 246 254 20",
"244 118 299 218 81 195 129 93 205 202 264 141 196 150 214 72 231 136 243 192",
"236 157 176 187 104 182 134 29 151 234 81 143 22 119 45 241 17 225 197 7",
"156 284 92 13 131 60 113 77 228 65 200 83 3 63 83 88 241 113 115 198",
"62 101 242 270 121 122 119 78 105 273 55 7 239 236 37 252 66 164 56 44",
"70 57 100 87 34 298 140 259 36 257 1 204 110 299 245 56 43 121 192 10",
"240 36 272 255 10 194 143 66 27 131 22 78 57 71 128 5 1 155 236 122",
"281 160 42 147 272 151 196 240 291 280 209 245 271 46 103 35 85 145 78 140",
"155 74 232 205 235 223 147 39 171 240 56 187 184 70 28 81 293 125 283 159",
"297 203 75 46 221 77 106 12 268 94 220 156 78 97 266 208 228 137 212 49",
"4 157 69 51 225 23 61 202 19 23 41 260 161 218 142 251 299 187 283 158",
"118 136 71 77 21 199 110 87 103 120 153 157 213 234 155 141 135 24 120 199",
"16 204 292 245 54 260 294 159 254 15 209 41 154 54 231 167 87 291 31 26",
"212 274 99 199 170 184 47 227 64 2 117 275 67 84 143 214 143 125 24 61",
"205 250 133 88 210 112 4 160 3 287 54 143 293 94 287 42 105 94 76 169")
) | % {
$expected, $a = $_
$result = &$f @a
"$($result-eq$expected): $result"
}
```
## Output
```
True: 3375
True: 328536000
True: 185193
True: 311042813
```
---
# Powershell, 105 bytes, no-regexp alternative
The tribute to the smart expression `|?{$_%20-le17}` in the Joey's [answer](https://codegolf.stackexchange.com/a/1187/80745):
```
(($x=($y=-split$args)|?{$i++%20-le17}|%{+$y[$i-1]+$y[$i]+$y[$i+1]})|%{$_*$x[$j+18]*$x[$j+++36]}|sort)[-1]
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
┬░╩íΩ{\ë╔B_m♦½─Γe╧¼
```
[Run and debug it](https://staxlang.xyz/#p=c2b0caa1ea7b5c89c9425f6d04abc4e265cfac&i=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+5+5+5+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+5+5+5+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+5+5+5+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1&m=1)
Input is given directly, no quotes.
## Explanation
```
L{eL3B{|+mmM{3B{:*mm$|M Input: STDIN, auto split on newlines, pushed to stack
L listify the stack
{ m map each line to:
{e m evaluate it
L listify the stack
3B overlapping slices of length 3
{|+m map those to their sums
M transpose
{ m map to:
3B overlapping slices of length 3
{:*m mapped to products
$ flatten
|M maximum
```
] |
[Question]
[
I wrote a code that separates the numbers from 1 to 9999 by comma
```
void p(n){printf("%d,",n);if(n<9999){p(n+1);}}main(){p(1);}
```
Is there a way to make this short code without using a repeat statement?
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 40 bytes by Sisyphus, exit by stack overflow
```
i;main(){main(dprintf(i++<9999,"%d,"));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOjcxM09DsxpMpRQUZeaVpGlkamvbWAKBjpJqio6SpqZ17f//AA "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 41 bytes by dingledooper
```
i;main(){++i<1e4&&main(printf("%d,",i));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOjcxM09Ds1pbO9PGMNVETQ3MLyjKzCtJ01BSTdFR0snU1LSu/f8fAA "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 42 bytes, original
```
main(i){i<1e4&&main(i+1,printf("%d,",i));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1OzOtPGMNVETQ3C1TbUKSjKzCtJ01BSTdFR0snU1LSu/f8fAA "C (gcc) – Try It Online")
`main` can be used to recurse
[Answer]
# [C (gcc)](https://gcc.gnu.org/) (Linux only), 31 bytes
```
main(){system("seq -s, 9999");}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6uLK4JDVXQ6k4tVBBt1hHwRIIlDSta///BwA "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 30 bytes by Karl Knechtel
```
print(*range(1,10000),sep=',')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ6soMS89VcNQx9AACDR1ilMLbNV11DX//wcA "Python 3 – Try It Online")
# [Python 3](https://docs.python.org/3/), 36 bytes by onetoinfinity
```
print(str(list(range(10000)))[4:-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Eo7ikSCMns7hEoygxLz1Vw9AACDQ1NaNNrHQNYzX//wcA "Python 3 – Try It Online")
# [Python 3](https://docs.python.org/3/), 39 bytes by UndoneStudios
```
i=0
while i<1e5:print(end='%d,'%i);i+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9PWgKs8IzMnVSHTxjDV1KqgKDOvRCM1L8VWXTVFR101U9M6U9vW8P9/AA "Python 3 – Try It Online")
# [Python 3](https://docs.python.org/3/), 40 bytes by Lemon
```
print(",".join(map(str,range(1,10000))))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0lHSS8rPzNPIzexQKO4pEinKDEvPVXDUMfQAAg0geD/fwA "Python 3 – Try It Online")
[Answer]
# C# 71 bytes
~~`Console.WriteLine(string.Join(",",Enumerable.Range(1, 999).ToList()));`~~
Saved 14 bytes thanks to Jupotters comment
```
Console.Write(string.Join(",",Enumerable.Range(1,9999)));
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 15 bytes
```
1..9999-join","
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPzxIIdLPyM/OUdJT@/wcA "PowerShell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~36~~ 35 bytes
```
main=putStr.init.tail$show[1..9999]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRILzMvs0SvJDEzR6U4I7882lBPzxIIYv//BwA "Haskell – Try It Online")
## Old version
```
main=putStr.init.tail.show$[1..9999]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRILzMvs0SvJDEzR684I79cJdpQT88SCGL//wcA "Haskell – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
```
Range@9999~StringRiffle~","
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H6xg@z8oMS891cESCOqCS4oy89KDMtPSclLrlHSU/gcA@SXRwbH/AQ "Wolfram Language (Mathematica) – Try It Online")
`Range@9999` (10 bytes) almost does it...
] |
[Question]
[
Given an integer \$N\$ consider a permutation \$p=p\_1,p\_2,p\_3,\ldots\$ of \$1,\ldots,N-1\$. Let \$P = p\_1 , p\_1+p\_2 \bmod N, p\_1+p\_2+p\_3 \bmod N, \ldots\$ be its prefix sums modulo \$N\$. Sometimes \$P\$ will be a permutation of \$1,\ldots,N-1\$ itself.
For example, \$N=4: p=3,2,1 \rightarrow P=3,1,2\$
Negative examples: \$p=2,3,1 \rightarrow P=2,1,2\$ is not a permutation ;
\$p=3,1,2 \rightarrow P=3,0,2\$ is a permutation but not of \$1,\ldots,3\$
Your task is to write a program or function that takes \$N\$ and returns the number of permutations \$p\$ of \$1,\ldots,N-1\$ such that \$P\$ is also a permutation of \$1,\ldots,N-1\$.
Rules:
You may return integers or integer-valued numbers.
You may return the \$N\$-th term, the first \$N\$ terms or the entire series.
You may ignore/skip odd \$N\$. If you choose to do so you may take \$N\$ or \$N/2\$ as the input.
Other than that default rules and loopholes for integer sequences apply.
This is code-golf, so shortest code in bytes wins. Different languages compete independently.
First few terms:
\$
\begin{align}
2 &\rightarrow 1 \\
4 &\rightarrow 2 \\
6 &\rightarrow 4 \\
8 &\rightarrow 24 \\
10 &\rightarrow 288
\end{align}\$
[OEIS](http://oeis.org/A141599) has more.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes
```
Count[Sort/@Mod[Accumulate/@Permutations[r=Range@#-1],#],r]&
```
[Try it online!](https://tio.run/##DcvBCsIwDADQXwkMPGXMeZ9U9CoMPYYcQu10YFOI6Un89rr7e1n8lbL4GqUtMLVzqep0L@ZDuJYHnWKsub7F0xDmZLn6Zot@yKab6DOFrh8ZO0bjXbsUmm3dvkJ/hIWUGeGrCAeEcf/j9gc "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
1#.!(=&#[:=#|+/\)@A.&i.]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1FDVs1ZSjrWyVa7T1YzQdHPXUMvVi/2typSZn5CukKWkrGCmYKJgpWPwHAA "J – Try It Online")
Straightforward brute force.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
ɽ:Ṗv¦⁰%vs^O
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvTrhuZZ2wqbigbAldnNeTyIsIiIsIjYiXQ==)
## How?
```
ɽ:Ṗv¦⁰%vs^O
ɽ # exclusive range from 0; range(1, N)
: # duplicate top of stack
Ṗ # get permutations
v¦ # vectorized cumulative sum
⁰ # push N to top of stack
% # modulo (vectorizes)
vs # vectorized sort
^ # flip stack (so range(1, N) is now on top)
O # count number of instances
```
[Answer]
# JavaScript (ES7), 88 bytes
```
f=(n,m=z=2**n-2,p=o=0,x,g=i=>(q=1<<++i)>m?o+=x==z:g(i,m&q&&f(n,m^q,i+=p,x|1<<i%n)))=>g``
```
[Try it online!](https://tio.run/##ZcvRCoIwGIbh8@4j2e9@Q0eEhJ/dSSimY@E2zYgh3fuqw/D04X3v7atduoeZnpnztz7GAcKxxQqVpi5TPMEj58AaBrWYUVSVlIZqe/ESAVjPWhi2yZwkw@@8zmwkJg7vb2n2johQ66aJnXeLH/vD6LUYhCLa/ctxI6eNlBspcqL4AQ "JavaScript (Node.js) – Try It Online")
### How?
We compute the bitmask \$z=2^n-2\$ where the bits \$1\$ to \$n-1\$ are set (e.g. \$n=4\$ gives \$z=14=1110\_2\$).
We start with \$m=z\$ and \$x=0\$. We recursively clear the bits of \$m\$ in all possible orders while keeping track of the sum of said bit indices in \$p\$ and setting the bits \$p \bmod n\$ in \$x\$. (Note that we do not need to keep track of the permutation itself.)
We have a solution whenever we end up with \$x=z\$, in which case the output value \$o\$ is incremented.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
S#omȯOm%¹∫Ptŀ
```
[Try it online!](https://tio.run/##yygtzv7/P1g5P/fEev9c1UM7H3WsDig52vD//38LAA "Husk – Try It Online")
```
t # tail: all except the first element of
ŀ # the sequence 0..N-1;
S#o # now, how many times does this occur among
P # get all permutations of this
mȯ # and for each of them
∫ # get the cumulative sums
m%¹ # each modulo the input
O # and sort the results
```
---
**Alternative, also 13 bytes**
```
LSnm(†%¹∫)Pḣ←
```
[Try it online!](https://tio.run/##ASAA3/9odXNr//9MU25tKOKAoCXCueKIqylQ4bij4oaQ////OA)
```
← # decrement the input by 1
ḣ # get the sequence 1..N
P # and get all permutations of this;
Sn # now get all common elements between this and
m( ) # for each permutation
∫ # get the cumulative sums
†%¹ # each modulo the input
L # how long is the resulting list of common elements?
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 23 bytes
```
{+/~^a?x!+\'a:?>'+!x#x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rW1q+LS7SvUNSOUU+0srdT11asUK6o5eJKU1cwUjBRMAMAsswI8Q==)
`+!x#x` All length x combinations of `0 1 ... x-1`.
`a:?>'` The unique results of grading up each combination. This gives all permutation, assign these to `a:`.
`x!+\'` Cumulative sum of each permutation, modulo x.
`a?` Find each row in the result in the list of permutations. This gives nulls for non-permutations.
`+/~^` Count the non-null values.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
’Œ!ðÄ%f⁸L
```
A monadic Link that accepts an integer and yields the count of permutations summing to permutations.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw8yjkxQPbzjcopr2qHGHz////y0A "Jelly – Try It Online")**
### How?
```
’Œ!ðÄ%f⁸L - Link: integer, N
’ - decrement -> N-1
Œ! - all permutations of [1..N-1]
ð - start a new dyadic chain, f(permutations, N)
Ä - cumulative sums (of each of the permutations)
% - modulo N
f⁸ - filter keep if in (the permutations)
L - length
```
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 71 bytes
```
[| n | n [1,b) <permutations> [ dup cum-sum [ n mod ] map ⊂ ] count ]
```
[Try it online!](https://tio.run/##LU0xbgIxEOzvFdMiBQQoQhFEtCgNTZTqRGF8C7E4rx3vukAkDSXPzEcOW1CMNDM7M3swVkMavj4/tpsl@mBNL/BGvyfJ8JGe3Aa/d2xK0lnBiRJT/7iIGnWi1a4aQj@Z2JaikApiItVzTI71kc/sbOgIq6a5YI5XLPCG2RR/zdD@glHRzl72I7xHSj7X@cCyRosuR9jsx5J9UQwfOuzKasT/7VqYDbl82Q3VmQx3 "Factor – Try It Online")
* `n [1,b) <permutations>` Get all the permutations of [1..n) as a virtual sequence.
* `[ ... ] count` Count how many of them...
* `dup cum-sum [ n mod ] map ⊂` ...are supersets of their cumulative sum modulo n.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 30 bytes
```
J-.ror@Jbcjm{q++pa}x/.%q~[Z]++
```
[Try it online!](https://tio.run/##SyotykktLixN/V9daFBcXpT530tXryi/yMErKTkrt7pQW7sgsbZCX0@1sC46KlZb@39teM5/IwVDLhMFIy4zBRMuCwUjEy4A "Burlesque – Try It Online")
```
J # Dup
-. # Decrement
ro # Range 1..N-1
r@ # Permutations
J # Dup
bc # Infinite cycle
j # Swap
m{ # Map
q++ # Sum
pa # Partial
}
x/ # Reorder stack
.% # Modulo
q~[Z] # Zip with contained in permutations
++ # Sum (count)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L¨œεηOI%{āQ}O
```
[Try it online](https://tio.run/##yy9OTMpM/f/f59CKo5NPTTq33d9TtfpIY2Bt@v//FgA) or [verify all test cases](https://tio.run/##ATMAzP9vc2FiaWX/VMOFw4jCpnZ5PyIg4oaSICI/ecKp/0zCqMWTypLOt0/CriV7xIFRfWf/LP8).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
¨ # Remove the last item to make the range [1,input)
œ # Get all its permutations
ʒ # Filter the permutations by:
η # Get all prefixes of the current permutation
O # Sum each prefix
I% # Modulo the input
{ # Sort it
ā # Push a list in the range [1,length] (without popping)
Q # Check if both lists are the same
}g # After the filter: pop and push the length
# (which is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org), 116 bytes
```
from itertools import*
f=lambda n:(r:=set(range(1,n)))and sum({sum(x[:i])%n for i in r}==r for x in permutations(r))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5BCsIwEEX3nmJAhETiQhEpgZykdBFpooFmEiZTqIgncdON3snbaMX6Fx8ePPj__swXPiccx0fPflO92FOKENgRp9QVCDEn4vXCm87GY2sBtSBtimNBFk9ObBVKKS22UPoorlMNtQ6NXCH4RBAgINDNGPriMGF2FHu2HBIWQVL-tpd_od6pvTqoqtEL-CRTQBZeDLM6330D)
[Answer]
# [Haskell](https://www.haskell.org), 102 bytes
```
import Data.List
f n=length$filter((`elem`p).tail.map(`mod`n).scanl(+)0)p where p=permutations[1..n-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc2xDQIxDADAnilSUCRCb_EdzXeUbICQYoFDIhwnSvxiGJpvEDOxDQVwC9zjFbHfiHlZnrOGYfcOKdfS1OxREQ6p6yoYmZjkqnEdEis1az0xZV8dKCaGjNX6XC5eHPQzCtuN27pq7pEamTpVanlW1FSkH0cAGcbTd_ul__wD)
] |
[Question]
[
# Challenge
Given a left- or right-stochastic matrix where the limit as x approaches infinity of the matrix to the power of x approaches a matrix with all finite values, return the matrix to which the matrix converges. Basically, you want to keep multiplying the matrix by itself until the result no longer changes.
# Test Cases
```
[[7/10, 4/10], [3/10, 6/10]] -> [[4/7, 4/7], [3/7, 3/7]]
[[2/5, 4/5], [3/5, 1/5]] -> [[4/7, 4/7], [3/7, 3/7]]
[[1/2, 1/2], [1/2, 1/2]] -> [[1/2, 1/2], [1/2, 1/2]]
[[1/3, 2/3], [2/3, 1/3]] -> [[1/2, 1/2], [1/2, 1/2]]
[[1/10, 2/10, 3/10], [4/10, 5/10, 6/10], [5/10, 3/10, 1/10]] -> [[27/130, 27/130, 27/130], [66/130, 66/130, 66/130], [37/130, 37/130, 37/130]]
[[1/7, 2/7, 4/7], [2/7, 4/7, 1/7], [4/7, 1/7, 2/7]] -> [[1/3, 1/3, 1/3], [1/3, 1/3, 1/3], [1/3, 1/3, 1/3]]
```
# Rules
* Standard Loopholes Apply
* You may choose whether you want a right- or a left-stochastic matrix
* You may use any reasonable number type, such as floats, rationals, infinite precision decimals, etc
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission in bytes for each language is declared the winner for its language. No answer will be accepted
[Answer]
# [R](https://www.r-project.org/), ~~44~~ 43 bytes
```
function(m){X=m
while(any(X-(X=X%*%m)))0
X}
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jV7M6wjaXqzwjMydVIzGvUiNCVyPCNkJVSzVXU1PTgCui9n@aRm5iSVFmhUayhrmOiY6xjpmmvqGBjhEQJlUW5ZfbhmhqciEpMgIrMtTUN8WtRs9UE7ekIVgKaIAxqpr/AA "R – Try It Online")
Just keeps multiplying until it finds a fixed matrix. Apparently `X!=(X=X%*%m)` does the comparison, then reassigns `X`, so that's neat.
Thanks to @Vlo for shaving off a byte; even though crossed out 44 is still regular 44.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~45~~ ~~42~~ 35 bytes
```
@(A)([v,~]=eigs(A,1))/sum(v)*any(A)
```
[Try it online!](https://tio.run/##VY9RC4IwFIXf9yvu4xZDm1qDhpC/Q3yQmhaUgltCiP31tV3LaA@Hb5xzz936k61H7Zo8iiJ3pAWj5chfVa6vraEFF4zF5nGnI9vU3dPbzmpjDeQwEfCnlLHYcsi8KkiR914rvrgiTjh4UfClnxOyCWqK0xnybu1QH15axV@rDKMy7JVqpRCSaiWMVGRWhDT9AFerB/9scbjprrUXiv9gWNgslylEZkZ0d3Zv "Octave – Try It Online")
Saved 3 bytes thanks to Giuseppe, and 7 more thanks to Luis Mendo!
This uses that the eigenvector corresponding to the eigenvalue 1 (also the maximum eigenvalue) is the column vector that is repeated for each value of the limiting matrix. We have to normalise the vector to have sum 1 for it to be stochastic, then we simply repeat it to fill out the matrix. I'm not too well versed in golfing Octave, but I haven't been able to find a functional way to do repeated multiplication, and a full program seems like it will always be longer than this.
We can use `any(A)` since from the restrictions we know that the matrix must describe an irreducible Markov chain, and so each state must be reachable from the other states. Therefore at least one value in each column must be non-zero.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
Output floats:
```
N@#//.x_:>x.#&
```
[Try it online!](https://tio.run/##RY7BCoMwDIZfJVjw1Jm1tSsMJj7B2F1kyJjMgx5GD0Lps3dNq@4S/i9/8ifzYD/vebDTawgj3CDcW4ZYrc9rs1asDI/vtNiOcSjg1EDBYexY30MJ2IJzzqA4c6hj9RycSnQhInQSNZk6e1GLqJMjUBJJgkNvjuIgURFI0rGxO5QuU1XbxTqR/t@NPX1M0PL@i0BDy4YeMjk8axoyOSvrNOa9Dz8 "Wolfram Language (Mathematica) – Try It Online")
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
Output fractions:
```
Limit[#~MatrixPower~n,n->∞]&
```
[Try it online!](https://tio.run/##RY5BCoMwEEWvMii4iqQmpllVeoAW3IuLUJRmoQUJtBB03VP0cL1ImknUbob/5s/8mUGZezcoo2/K9XACd9GDNk26XJWZ9Kt@PLtpGcmYV9/3p81cPenR2wQSyCtICPRN2raQAT2DtVbS4kCg9HUmYHmgIxKiZVSgKaLndeF1cArKkBjCrleHE2CUIzDUvrE5mM5C5evFMpD43/U9sU/g8vZLQSUuS3xIxvCocUjGrKjD2DzP7gc "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
æ×³$ÐL
```
This is a full program.
[Try it online!](https://tio.run/##y0rNyan8///wssPTD21WOTzB5////9HRhvrmOgpGIMJE3zxWRyEaxtZRMIQIwNhgZbGxAA "Jelly – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~18~~ 6 bytes
*12 bytes saved thanks to @H.PWiz*
```
+.×⍨⍣≡
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRtvcPTH/WueNS7@FHnQqCQgpGC0aPeLeYKJgrGCmaHtxsaAAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# k/q, 10 bytes
k/q because the program is identical in both languages. The code is really just idiomatic k/q.
```
{$[x]/[x]}
```
### Explanation
`{..}` is out lambda syntax, with `x` as an implicit parameter
`$[x]` has $ as the binary matrix multiplication operator, providing only one parameters creates a unary operator that left multiplies by the Markov Matrix
`/[x]` applies the left multiplication until convergence, starting with x itself.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~207~~ ~~192~~ ~~190~~ ~~181~~ 176 bytes + 2 flag bytes `-lm`
* Saved ~~fifteen~~ ~~seventeen~~ twenty-two bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
* Saved nine bytes; removing `return A;`.
```
float*f(A,l,k,j)float*A;{for(float B[l*l],S,M=0,m=1;fabs(m-M)>1e-7;wmemcpy(A,B,l*l))for(M=m,m=0,k=l*l;k--;)for(S=j=0;j<l;)m=fmax(m,fdim(A[k],B[k]=S+=A[k/l*l+j]*A[k%l+j++*l]));}
```
[Try it online!](https://tio.run/##pZLfa8IwEMef9a8oHUKiV@2PaR@ybFinb8LAR9eHrhqxNirq2Ib4r6@7NFqnk7EhlO/dJXf53HGNrUkcZ5lIF9GmKkgbUphBQnXcZluxWJE8MIJhWk1DGECf2yC5w0T0sibS6tN7Z2z57E2OZbz8wCcCwExKVWmfS8y1YcbxiM0si@XHA55wmyV3KaOSCxm9EwliNJWkPZyFEKDwQY1j0MCyWhJW0a2gU6thC5SyXXYzGovpfGw8qZbpcjWdbwQxDcMwKVMEjI09A8FYWORUBJjQHiYhZcvXzZqYWFGW0XRO6LZc2g/OBdFjD0O69esNxwbjVhtPm5YyO3CxuKSaQOdA4A8GQg7f89wELPW1eAdRdRoWnMDceqOpUpsqqwkOSkEJrqB0Tij4rAunUlA6v1MulB4pj@cUD9xCVFhQHq@gdM8puBA3V70cvalmrq1vvr519OY83UdXOZf7OPtUW676Fzz7h221LlvPv2iPo/TOR/HVJPs1Hj3n1FMXxQS9f03gHDbxB8H3d9lnLNJoss6sVH4B "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~75~~ 61 bytes
```
f=lambda n:n if allclose(n@n,n)else f(n@n)
from numpy import*
```
[Try it online!](https://tio.run/##nZDBisMgEIbvfYqBXuISsNEkwsLCvof14O5GGjAm2OwhT5862qbNEhbay/jP@PszfsM0nnrHZ/NxnK3uvn40uHcHrQFt7bftz03mPl3uSGPPDRhsyM74vgP32w0TtN3Q@/FtHnzrxsxk2ns9ZVIKWhxyKENVOUgeuxo7RQiBPUhZUoEGke6DDkWp3d8gRiu0VckWdBH0syEFZfiQoW3RS8j27UYIz4FRjjaGOgxeCEESLFZ@pVPGrrozCrNqcWDSIzcW0HLMWJ34pq7TZH1GNFfv@txcT@B2d6g3jVuItGzS0fb4/QQkUYkM/h2o@QI "Python 3 – Try It Online")
In test cases there are float inaccuracies, so the values may differ by a bit from the exact fractions.
PS. `numpy.allclose()` is used because `numpy.array_equal()` is longer and prone to float inaccuracies.
-14 bytes Thanks HyperNeutrino ;) Oh yes I forgot the @ operator ;P
[Answer]
# Java 8, ~~356~~ 339 bytes
```
import java.math.*;m->{BigDecimal t[][],q;RoundingMode x=null;for(int l=m.length,f=1,i,k;f>0;m=t.clone()){for(t=new BigDecimal[l][l],i=l*l;i-->0;)for(f=k=0;k<l;t[i/l][i%l]=(q!=null?q:q.ZERO).add(m[i/l][k].multiply(m[k++][i%l])))q=t[i/l][i%l];for(;++i<l*l;)f=t[i/l][i%l].setScale(9,x.UP).equals(m[i/l][i%l].setScale(9,x.UP))?f:1;}return m;}
```
-17 bytes thanks to *@ceilingcat*.
Definitely not the right language.. Damn floating point precision..
**Explanation:**
[Try it online.](https://tio.run/##zVVdb9owFH3Pr7h7mJQEYz5aVq1pWgHhS1q7qt1ehqIpTRzq4iQQnK4I8dvZDaEtRYOpUYuKguRrn3vO8c21c@fcO8VoxMI7b7jgwSiKJdzhHA0ceUt1A/BXKsGlg/ORD/KWwc1UsqIbJaFUXOFMJnDu8HCmAPBQsth3XAYXaQjQ4AOLuTxwRN/u2@CqGxOBZiBujn98JtKR3IULCMGERVA8nT2jQaZ4MjauUNbj4eA88hg8mGEihOFHsYrSIMyAChYO5C3xzQrhZGj4p2UjMCV1RRQyVdNmKVaaIfuz7k3Y@BBuCl0YvFjEHC3F@ebQLBvDE2HIPi8hiH8WtqmOPy1lz8bHY/qrdfVdo47nqUEGGdo0SITkIzHFqWGhkGVpmjY211iWno1CgZ@kmpq/vkYnTF67jmDqV/JAf15qlI0TR0weJf6J0c7844oxj5lM4hACY74wFKWkK8r5yg3WDBzAlxrzh2NF6ffrBBo2AR2ehmY61OuFht4kUNcbOLBsokAfQ8u20xf6YohQK4U2EWoh1FZgxYtza9RZ9MxuFZp651GhhUE3DZoYtDHoLSUtAi0CbcxLpTYiZGkhSztlsZClhSztlAXtoJM2BhkLruNsb2V4I0KWLrL0UpYOsnSRpZeydJCliyw9ZLEVRS9l/TlKbgT256pN7yPuYTl5qF5jScMBdrOjZV1/PZ1IFtAokXSES1KE6vJEJZILWo9jZzqhHmOjH1GWqobUVTdaErs9IwOYvVxSj3yNevyee2wjSa2UfU0jqzTYWDzcnTYnW@QO8sl9@Y/cHI@EsY9yVbcaqeWqVi1fsXaJVXaL7a1U231Uc7mv7irVu4h9gFJhC5Bamax/qGi3/q39G2/pbbuq5mLbWtrqm5rLt9WP8Cp2XlDVfGkHOa/Rw3xytfe5fbe5rL1LUV7fWXv@Rmw3cvSmpzkP22Euthx3w/7Mvb4fcm31I5h72x55OhFzZb74Cw)
```
import java.math.*; // Required import for BigDecimal and RoundingMode
m->{ // Method with BigDecimal-matrix as both parameter and return-type
BigDecimal t[][],q; // Temp BigDecimal-matrix
RoundingMode x=null; // Static RoundingMode value to reduce bytes
for(int l=m.length, // The size of the input-matrix
f=1, // Flag-integer, starting at 1
i,k; // Index-integers
f>0; // Loop as long as the flag-integer is still 1
m=t.clone()){ // After every iteration: replace matrix `m` with `t`
for(t=new BigDecimal[l][l],
// Reset matrix `t`
i=l*l;i-->0;) // Inner loop over the rows and columns
for(f=k=0; // Set the flag-integer to 0
k<l // Inner loop to multiply
; // After every iteration:
t[i/l][i%l]=(q!=null?q:q.ZERO).add(
// Sum the value at the current cell in matrix `t` with:
m[i/l][k] // the same row, but column `k` of matrix `m`,
.multiply(m[k++][i%l])))
// multiplied with the same column, but row `k` of matrix `m`
q=t[i/l][i%l]; // Set temp `q` to the value of the current cell of `t`
for(;++i<l*l;) // Loop over the rows and columns again
f=t[i/l][i%l].setScale(9,x.UP).equals(m[i/l][i%l].setScale(9,x.UP))?
// If any value in matrices `t` and `m` are the same:
f // Leave the flag-integer unchanged
: // Else (they aren't the same):
1;} // Set the flag-integer to 1 again
return m;} // Return the modified input-matrix `m` as our result
```
] |
[Question]
[
**This question already has answers here**:
[Different Way Forward](/questions/47005/different-way-forward)
(31 answers)
Closed 7 years ago.
*[Related](https://codegolf.stackexchange.com/questions/94519/output-a-strings-cumulative-slope)*
# Explanation
Given a string such as `DCBA`, convert it to ASCII ordinals, such as `68 67 66 65`. Then, take the differences between each value, eg `67 - 68 = -1, 66 - 67 = -1...` giving `-1 -1 -1` Now as long as there is more than 1 left over value, repeat getting the differences.
For a 3 letter string, your pathway should be similar to
```
A F G
65 70 71
-5 -1
-4
```
And for a 5 letter string...
```
B A C E D F
66 65 67 69 68 70
1 -2 -2 1 -2
3 0 -3 3
3 3 -6
0 9
-9
```
# The Challenge
Take a string input through any [Standard IO Method](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and output the value of the cumulative delta as described above.
# Test Cases
```
input: cows
output: 8
input: helloworld
output: 905
input: aaaaaa
output: 0
input: abcdef
output: 0
input: ghfie
output: 20
input: CODEGOLF
output: 185
```
# Rules
* [Standard Loopholes Apply](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* The input will only consist of ASCII letters that are either all uppercase or all lowercase
* Your code MUST work for both lower and upper case.
* The input will contain at least 2 characters.
* The output may be positive or negative, as long as its absolute value matches the absolute value of the cumulative delta.
* This is marked as [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), as such, shortest answer in bytes wins!
[Answer]
# Python 3, 71 bytes
```
s=input();k=r=0
for c in s:r=ord(c)-r*k/(len(s)-k);k+=1
print(round(r))
```
Test it on [Ideone](http://ideone.com/QIbBwz).
### Alternate version, 58 bytes (inexact)
If an approximate result is enough – e.g., **-904.9999999999993 ≈ -905** for input **helloworld** – then the following solution works as well.
```
f=lambda s,k=1:len(s)and-~-len(s)*f(s[1:],k+1)/k+ord(s[0])
```
Test it on [Ideone](http://ideone.com/y6QJQf).
### Background
**Proposition** *Let* **f** *be a variadic function that maps the code points* **s0, ⋯, sn** *to their cumulative delta with sign* **(-1)n**, i.e.,

*Then*

**Proof** The statement is clearly true when **n = 0**. Suppose that it holds for **n - 1**, where **n > 0**.
By the recursive definition of **f** and the hypothesis,

By induction, the statement holds for all non-negative values of **n**.
### How it works
Since

we can rewrite the proposition as follows.

The iterative implementation does precisely this. Numerators are computed by incrementing **k**, denominators by subtracting **k** from the length of the input string **s**, i.e., **n+1**.
Unfortunately, not all fractions will evaluate to integers, so the result is computed using floating point arithmetic and finally rounded to the nearest integer.
The recursive implementation does roughly the same, but it keeps track of the denominator via the auxiliary variable **k** and computes the numerator by subtracting **1** from the length of the remaining string (`~-len(s)`).
[Answer]
# MATL, 5 bytes
```
`dtnq
```
[**Try it Online!**](http://matl.tryitonline.net/#code=YGR0bnE&input=J2hlbGxvd29ybGQn) or here is a slightly modified version for [all test cases](http://matl.tryitonline.net/#code=YApgZHRucQpdRFQ&input=J2Nvd3MnCidoZWxsb3dvcmxkJwonYWFhYWFhJwonYWJjZGVmJwonZ2hmaWUnCidDT0RFR09MRic).
**Explanation**
```
% Implicitly grab the input as a string
` % Do....while loop
d % Compute the difference between all consecutive ASCII codes
tnq % Determine the current length and subtract 1
% Implicit end of do...while. Evaluate (and consume) stack element and break out
% of loop if it's 0.
% Implicit end of loop and display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 bytes thanks to @Dennis (implement a while loop)
```
OIṖ¿
```
**[TryItOnline](http://jelly.tryitonline.net/#code=T0nhuZbCvw&input=&args=ImhlbGxvd29ybGQi)**
[RunAllTestCases](http://jelly.tryitonline.net/#code=T0nhuZbCvwrFvMOH4oKsWeKCrFk&input=&args=Wydjb3dzJywnaGVsbG93b3JsZCcsJ2FhYWFhYScsJ2FiY2RlZicsJ2doZmllJywnQ09ERUdPTEYnXQ)
### How?
```
OIṖ¿ - Main link: s
O - cast to ordinals
Ṗ¿ - while, ¿, pop last value, Ṗ, evaluates to True:
I - find increments between consecutive values
```
[Answer]
# J, 15 bytes
```
<:@#2&(-/\)3&u:
```
## Usage
```
f =: <:@#2&(-/\)3&u:
f 'cows'
8
f 'helloworld'
_905
f 'aaaaaa'
0
f 'abcdef'
0
f 'ghfie'
_20
f 'CODEGOLF'
_185
```
## Explanation
```
<:@#2&(-/\)3&u: Input: string S
3&u: Ordinal of each char
# Get the length of S
<:@ Decrement it
2&( ) Repeat len(s)-1 times on x = ordinal(S)
2 \ For each pair of values
-/ Reduce using subtraction
Return that as the next value of x
Return the final x as the result
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes
```
ÇDgG¥}`
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w4dEZ0fCpX1g&input=aGVsbG93b3JsZA)
**Explanation**
```
Ç # convert to list of ascii codes
DgG } # length-1 times do:
¥ # take deltas
` # pop the single value left in the list and output
```
[Answer]
# Python 2, ~~80~~ 73 bytes
Saving 7 bytes thanks to Dennis.
```
L=map(ord,input())
while L[1:]:L=[x-y for x,y in zip(L,L[1:])]
print L[0]
```
Requires input to be given in quotes, e.g. `"helloworld"`
[Answer]
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 17 Bytes
```
►Sb]L1-1\1:[d}P
```
## Explination
```
► # Spaceless segment
Sb # Convert the input to a stack, convert the stack of strings to a stack of ordinals.
]L # Push a duplicate of that stack, pop it and push the length in its place
1- # Subtract 1 from the length.
1\1 # Push a one, slide it under the top value, push another one, such that 1 LENGTH 1
: } # For (i=1; i<=LENGTH; i+=1)
[d # Pop the iterator, pop the current stack, push the delta stack representing it.
P # Pop the top value of the stack, push it to the reg stack, and implicitly print.
```
I used (A version of) this script to test the question itself. I thought I might as well share it.
[Try It Online!](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%E2%96%BASb%5DL1-1%5C1%3A%5Bd%7D%2B&input=cows)
[Answer]
## Racket 147 bytes
```
(let p((l(map char->integer(string->list s))))(if(= 1(length l))(car l)(p
(for/list((i(range 1(length l))))(-(list-ref l(- i 1))(list-ref l i))))))
```
Ungolfed:
```
(define (f s)
(let loop ((lst (map char->integer (string->list s))))
(if (= 1 (length lst))
(first lst)
(loop (for/list ((i (range 1 (length lst))))
(- (list-ref lst (sub1 i))
(list-ref lst i))
)))))
```
Testing:
```
(f "AFG")
(f "BACEDF")
(f "cows")
(f "helloworld")
(f "abcdef")
(f "aaaaaa")
(f "ghfie")
(f "CODEGOLF")
```
Output:
```
-4
-9
8
-905
0
0
-20
-185
```
[Answer]
## Haskell, ~~51~~ 47 bytes
```
g[x]=x
g x=g$zipWith(-)=<<tail$x
g.map fromEnum
```
Usage example: `g.map fromEnum $ "CODEGOLF"`-> `185`.
`map fromEnum` turns the string into a list of ascii values. If it has only a single element, return it, else build neighbor differences and check again.
[Answer]
## JavaScript (ES6), 116 bytes
Good that the input is more than 1 char so I can use `s.length` for both Arrays and Strings!
Snippet referenced from [Neil's answer on another question](https://codegolf.stackexchange.com/a/96085/59806) :P
```
d=k=>/\d/.test(k)?k:k.charCodeAt(0);r=x=>(a=[...x],a.pop(),a.map((c,i)=>d(c)-d(x[i+1])));f=s=>s.length-1?f(r(s)):s[0]
```
```
<input oninput=o.textContent=this.value&&f(this.value)><pre id=o>
```
[Answer]
# [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 97 bytes
```
([][()]<>){<>([][()]){({}[()]<({}[({})]<>)><>)}{}{}<>([]){({}[()]<({}<>)<>>)}{}<>({}<>[()])}<>
```
[Try it online!](http://brain-flak.tryitonline.net/#code=KFtdWygpXTw-KXs8PihbXVsoKV0peyh7fVsoKV08KHt9Wyh7fSldPD4pPjw-KX17fXt9PD4oW10peyh7fVsoKV08KHt9PD4pPD4-KX17fTw-KHt9PD5bKCldKX08Pg&input=Y293cw&args=LWE)
This is 97 bytes of code, plus 3 bytes for the `-a` flag, which enables ASCII input.
This would be a lot simpler if we didn't have to worry about the difference between characters sometimes being zero. Instead, we have to muck around with reversing the stack and pushing stack height several times.
Explanation:
```
Push the stack height onto the alternate stack
([][()]<>)
While this stack is non-empty:
{
Move back
<>
Push the height of the stack minus one
([][()])
While true
{
Decrement the stack height counter
({}[()]
Move the difference over to the other stack
<({}[({})]<>)><>)
}
Pop the last value and the left-over counter
{}{}
Move on to the other stack
<>
Move everything back
([]){({}[()]<({}<>)<>>)}
Pop the counter
{}<>
Move the step number minus one back
({}<>[()])
End
}
Move back one last time
<>
```
[Answer]
## R, 58 bytes
```
x=rev(utf8ToInt(readline()));while(length(x)>1)x=diff(x);x
```
`diff()` in R works differently than the difference defined in this challenge. Therfore we have reverse the vector (using `rev`) prior to taking the difference the first time.
] |
[Question]
[
# Problem
Create a program or function that can calculate the result of a matrix raised to the *n*th power. Your code will take an arbitrary square matrix *A* and a non-negative integer *n*, and return a matrix with the value *A**n*.
## Restrictions
Built-in functions that compute the matrix power and matrix product are not allowed.
The rest of the standard rules for code-golf apply.
# Explanation
Given a square matrix *A*, the value of *A**n* = *A A ⋯ A* (repeated matrix product of *A* with itself, *n* times). If *n* is positive, the standard just mentioned is used. When *n* is zero, the identity matrix with the same order of *A* is the result.
# Goal
This is code-golf and the shortest code wins.
# Test Cases
Here, *A* is the input matrix, *n* is the input integer, and *r* is the output matrix where *r* = *A**n*.
```
n = 0
A = 62 72
10 34
r = 1 0
0 1
n = 1
A = 23 61 47
81 11 60
42 9 0
r = 23 61 47
81 11 60
42 9 0
n = 2
A = 12 28 -26 3
-3 -10 -13 0
25 41 3 -4
-20 -14 -4 29
r = -650 -1052 -766 227
-331 -517 169 43
332 469 -1158 -53
-878 -990 574 797
n = 4
A = -42 -19 18 -38
-33 26 -13 31
-43 25 -48 28
34 -26 19 -48
r = -14606833 3168904 -6745178 4491946
1559282 3713073 -4130758 7251116
8097114 5970846 -5242241 12543582
-5844034 -4491274 4274336 -9196467
n = 5
A = 7 0 -3 8 -5 6 -6
6 7 1 2 6 -3 2
7 8 0 0 -8 5 2
3 0 1 2 4 -3 4
2 4 -1 -7 -4 -1 -8
-3 8 -9 -2 7 -4 -8
-4 -5 -1 0 5 5 -1
r = 39557 24398 -75256 131769 50575 14153 -7324
182127 19109 3586 115176 -23305 9493 -44754
146840 31906 -23476 190418 -38946 65494 26468
42010 -21876 41060 -13950 -55148 19290 -406
44130 34244 -35944 34272 22917 -39987 -54864
1111 40810 -92324 35831 215711 -117849 -75038
-70219 8803 -61496 6116 45247 50166 2109
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Z×'³S€€
LṬ€z0Ç¡
```
[Try it online!](http://jelly.tryitonline.net/#code=WsOXJ8KzU-KCrOKCrApM4bms4oKsejDDh8Kh&input=&args=W1sgMTIsICAyOCwgLTI2LCAgM10sIFstMywgLTEwLCAtMTMsICAwXSwgWyAyNSwgIDQxLCAgIDMsIC00XSwgWy0yMCwgLTE0LCAgLTQsIDI5XV0+Mg)
Permalinks with grid output: [test case 1](http://jelly.tryitonline.net/#code=WsOXJ8KzU-KCrOKCrApM4bms4oKsejDDh8KhCsOHRw&input=&args=W1s2MiwgNzJdLCBbMTAsIDM0XV0+MA) | [test case 2](http://jelly.tryitonline.net/#code=WsOXJ8KzU-KCrOKCrApM4bms4oKsejDDh8KhCsOHRw&input=&args=W1syMywgNjEsIDQ3XSwgWzgxLCAxMSwgNjBdLCBbNDIsICA5LCAgMF1d+MQ) | [test case 3](http://jelly.tryitonline.net/#code=WsOXJ8KzU-KCrOKCrApM4bms4oKsejDDh8KhCsOHRw&input=&args=W1sgMTIsICAyOCwgLTI2LCAgM10sIFstMywgLTEwLCAtMTMsICAwXSwgWyAyNSwgIDQxLCAgIDMsIC00XSwgWy0yMCwgLTE0LCAgLTQsIDI5XV0+Mg) | [test case 4](http://jelly.tryitonline.net/#code=WsOXJ8KzU-KCrOKCrApM4bms4oKsejDDh8KhCsOHRw&input=&args=W1stNDIsIC0xOSwgIDE4LCAtMzhdLCBbLTMzLCAgMjYsIC0xMywgIDMxXSwgWy00MywgIDI1LCAtNDgsICAyOF0sIFsgMzQsIC0yNiwgIDE5LCAtNDhdXQ+NA) | [test case 5](http://jelly.tryitonline.net/#code=WsOXJ8KzU-KCrOKCrApM4bms4oKsejDDh8KhCsOHRw&input=&args=W1sgNywgIDAsIC0zLCAgOCwgLTUsICA2LCAtNl0sIFsgNiwgIDcsICAxLCAgMiwgIDYsIC0zLCAgMl0sIFsgNywgIDgsICAwLCAgMCwgLTgsICA1LCAgMl0sIFszLCAgMCwgIDEsICAyLCAgNCwgLTMsICA0XSwgWyAyLCAgNCwgLTEsIC03LCAtNCwgLTEsIC04XSwgWy0zLCAgOCwgLTksIC0yLCAgNywgLTQsIC04XSwgWy00LCAtNSwgLTEsICAwLCAgNSwgIDUsIC0xXV0+NQ)
### How it works
```
LṬ€z0Ç¡ Main link. Arguments: A (matrix), n (power)
L Get the length l of A.
Ṭ€ Turn each k in [1, ..., l] into a Boolean list [0, 0, ..., 1] of length k.
z0 Zip; transpose the resulting 2D list, padding with 0 for rectangularity.
This constructs the identity matrix of dimensions k×k.
Ç¡ Execute the helper link n times.
Z×'³S€€ Helper link. Argument: B (matrix)
Z Zip; transpose rows and columns of B.
³ Yield A.
×' Spawned multiplication; element-wise mutiply each rows of zipped B (i.e.,
each column of B) with each row of A.
This is "backwards", but multiplication of powers of A is commutative.
S€€ Compute the sum of each product of rows.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 20 bytes
```
XJZyXyi:"!J2$1!*s1$e
```
[**Try it online!**](http://matl.tryitonline.net/#code=WEpaeVh5aToiIUoyJDEhKnMxJGU&input=Wy00MiAtMTkgIDE4IC0zODsgLTMzICAyNiAtMTMgIDMxOyAtNDMgIDI1IC00OCAgMjg7IDM0IC0yNiAgMTkgLTQ4XQo0)
### Explanation
This avoids the matrix multiplication by doing it manually, using element-wise multiplication with broadcast followed by vectorized sum. Specifically, to multiply matrices `M` and `N`, both of size *s*×*s*:
1. Transpose `M`. Call the resulting matrix `P`.
2. Permute the dimensions of `N` such that `N` is "turned" with a rotation axis along the first dimension, giving an *s*×1×*s* 3D array, say `Q`.
3. Multiply each element of `P` times each element of `Q`, with implicit broadcast. This means that `P` is automatically replicated *s* times along the third dimension, and `Q` is replicated *s* times along the second, to make them both *s*×*s*×*s*, before the actual element-wise multiplication takes place.
4. Sum along the first dimension to yield a 1×*s*×*s* array.
5. Squeeze the leading singleton dimension out, to produce an *s*×*s* result.
Commented code:
```
XJ % take matrix A. Copy to clipboard J
ZyXy % generate identity matrix of the same size
i: % take exponent n. Generate range [1 2 ... n] (possibly empty)
" % for each element in that range
! % transpose matrix with product accumulated up to now (this is step 1)
J % paste A
2$1! % permute dimensions: rotation along first-dimension axis (step 2)
* % element-wise multiplication with broadcast (step 3)
s % sum along first dimension (step 4)
1$e % squeeze out singleton dimension, i.e. first dimension (step 5)
% end for. Display
```
[Answer]
## APL, 32 31 chars
```
{⍺=0:(⍴⍵)⍴1⍨1+≢⍵⋄+.×⍨⍣(⍺-1)⊣⍵}
```
Left argument the power to raise to, right argument the matrix. The hardest (most space consuming) bit is building the identity matrix for the case where the desired exponent is 0.
The actual computation is based on the fact that the generalised inner product (`.`) with `+` and `×` as operands is effectively the matrix product. This combined with the power `⍣` operator ("repeat") forms the meat of the solution.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes
```
{y(+/x*)'/=#x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJzFkDsOwkAMRPs9xUgU+aDV/j/E4iSINrlCECJnx86GAnEAGmv8PLJHnqfnoz+bdRw6cz2tL6WWRrp1NNNwMDXf+uxRPDmLEAeCvWPD8kt3a4GFDqjQCRk6E9cCBy9dgCfuKnvYVZGkD6xlHmUeqSkHXaCbqHRsvEDzyR0Li3KDDZb3iOAQ6Yj27xT7KxwcMWfgPi/7Qm+9Tki+)
-2 bytes thanks to [@coltim on the k tree](https://chat.stackexchange.com/transcript/message/58285845#58285845). The inner train multiplies x on the right side of the current matrix (instead of left side).
Why `(+/x*)'` is also a matmul:
```
(+/(e f;g h)*)' (a b;c d)
( (+/(e f;g h)*) a b; (+/(e f;g h)*) c d )
( +/ (ae af;bg bh) ; +/ (ce cf;dg dh) )
((ae+bg) (af+bh); (ce+dg) (cf+dh))
```
# [K (ngn/k)](https://codeberg.org/ngn/k), 16 bytes
```
{y(+/'x*\:)/=#x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJwtTkkOgkAQvPOKSjwImg7TszAjHV+iXHkDxvh3qsFLp7Z01Tp/P/19vG639zyMz8v267r11U8RNZoGpDwYwuJaRYAkNEjBBJmMt0IRnSVEI2vMMNVQnCdi97P72U6kkAo5QbP/xweEjYfsWvYOBgL/OOCGcmxQqFEm17DsxpsjnQ==)
Original solution. Takes `[matrix; n]` and computes `matrix^n`.
### How it works
```
{y(+/'x*\:)/=#x} x:matrix; y:n
=#x Identity matrix of size of x
y( )/ Repeat y times:
x*\: Multiply each row of x to each column of current matrix
+/' Sum each to get the matrix product
```
Why `+/'*\:` is a matmul:
```
(a b;c d) *\: (e f;g h)
multiply-eachleft expands to
(a b * (e f;g h) ; c d * (e f;g h))
atomic application gives
((ae af
bg bh)
(ce cf
dg dh))
so applying +/' on this will give the result of matmul.
```
[Answer]
## Sage, 112 bytes
```
lambda A,n:reduce(lambda A,B:[[sum(map(mul,zip(a,b)))for b in zip(*B)]for a in A],[A]*n,identity_matrix(len(A)))
```
[Try it online](http://sagecell.sagemath.org/?z=eJxdjsFOxCAQhu8kvMMkXqDhoGg02YQDG9-CEEO31CUBSiio69MLtq7G08z8_z_fzCy8CeNkQLJ4yHaqJ0uuyvGg1FoDCSaRUD37dIkYNlJK5yXDCC5Cl4Yj1V0wXZCaKamHyNxkY3Hl8hJMye6DeBuJbKsYYXTTkqkW2CwgZgX-DN6tpdlSKPXI2RNvpLtbdv-g9e9GWt5txigK3rXXxc-Q7Vp9wahVEDATyTjt5g4fq_PFRYyCbPb-jPxO7NaVEDZEkMMQtzffbHbzBcrZlL_HOuZ0buH_hJRdLH1iP5daT0E0aGu-APksck0=&lang=sage)
Explanation:
The inner lambda (`lambda A,B:[[sum(map(mul,zip(a,b)))for b in zip(*B)]for a in A]`) is a straightforward implementation of matrix multiplication. The outer lambda (`lambda A,n:reduce(...,[A]*n,identity_matrix(len(A)))`) uses `reduce` to compute the matrix power by iterated matrix multiplication (using the aforementioned homemade matrix multiplication function), with the identity matrix as the initial value to support `n=0`.
[Answer]
# Julia, ~~90~~ ~~86~~ 68 bytes
```
f(A,n)=n<1?eye(A):[A[i,:][:]⋅f(A,n-1)[:,j]for i=m=1:size(A,1),j=m]
```
This is a recursive function that accepts a matrix (`Array{Int,2}`) and an integer and returns a matrix.
Ungolfed:
```
function f(A, n)
if n < 1
# Identity matrix with the same type and dimensions as the input
eye(A)
else
# Compute the dot product of the ith row of A and the jth column
# of f called on A with n decremented
[dot(A[i,:][:], f(A, n-1)[:,j]) for i = (m = 1:size(A,1)), j = m]
end
end
```
[Try it online!](http://julia.tryitonline.net/#code=ZihBLG4pPW48MT9leWUoQSk6W0FbaSw6XVs6XeKLhWYoQSxuLTEpWzosal1mb3IgaT1tPTE6c2l6ZShBLDEpLGo9bV0KCmZvciBjYXNlIGluIFsoWzYyIDcyOyAxMCAzNF0sIDApLAogICAgICAgICAgICAgKFsyMyA2MSA0NzsgODEgMTEgNjA7IDQyICA5ICAwXSwgMSksCiAgICAgICAgICAgICAoWzEyICAyOCAtMjYgIDM7IC0zIC0xMCAtMTMgIDA7IDI1ICA0MSAgIDMgLTQ7IC0yMCAtMTQgIC00IDI5XSwgMiksCiAgICAgICAgICAgICAoWy00MiAtMTkgIDE4IC0zODsgLTMzICAyNiAtMTMgIDMxOyAtNDMgIDI1IC00OCAgMjg7IDM0IC0yNiAgMTkgLTQ4XSwgNCldCiAgICBwcmludGxuKGYoY2FzZVsxXSwgY2FzZVsyXSkgPT0gY2FzZVsxXV5jYXNlWzJdKQplbmQ&input=) (includes all but the last test case, which is too slow for the site)
Saved 18 bytes thanks to Dennis!
[Answer]
# Python 2.7, ~~158~~ 145 bytes
The worst answer here, but my best golf in Python yet. At least it was fun learning how to do matrix multiplication.
Golfed:
```
def q(m,p):
r=range(len(m))
if p<1:return[[x==y for x in r]for y in r]
o=q(m,p-1)
return[[sum([m[c][y]*o[x][c]for c in r])for y in r]for x in r]
```
Explanation:
```
#accepts 2 arguments, matrix, and power to raise to
def power(matrix,exponent):
#get the range object beforehand
length=range(len(matrix))
#if we are at 0, return the identity
if exponent<1:
#the Boolean statement works because Python supports multiplying ints by bools
return [[x==y for x in length] for y in length]
#otherwise, recur
lower=power(matrix,exponent-1)
#and return the product
return [[sum([matrix[c][y]*lower[x][c] for c in length]) for y in length] for x in length]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
L=þ`Zḋþ³ƊƓ¡
```
[Try it online!](https://tio.run/##y0rNyan8/9/H9vC@hKiHO7oP7zu0@VjXscmHFv7/b/Q/OlrB0EhHQcHIQkdB18gMyDKO1VGI1jUGcg0NQASQpWAAElMwMgUyTQyBhAJI2gSs0AisyAQoqAskjCxjYwE "Jelly – Try It Online")
A more modern update to [Dennis' answer](https://codegolf.stackexchange.com/a/78763/66833), be sure to give that an upvote.
Additionally, [this](https://tio.run/##y0rNyan8/9/28L6ohzu61R81bj3WdWzyoYX//xv9NwHC6GgFQyMdBQUjCx0FXSMzIMs4VkchWtcYyDU0ABFAloIBSEzByBTINDEEEgogaROwQiOwIhOgoC6QMLKMjQUA) is a 9 byte answer that takes the dimensions of the matrix as the first 2 command line args and the matrix as the third.
Both take the power via STDIN.
## How it works
```
L=þ`Zḋþ³ƊƓ¡ - Main link. Takes A on the left
L - Length of A, L
` - Using L as both arguments:
þ - Create an LxL matrix, where the element at (i,j) is:
= - Does i = j?
This creates an identity matrix LxL
Ɠ - Read an integer from STDIN, n
Ɗ ¡ - Do the following n times:
Z - Transpose
³ - Yield A
þ - Pair all rows of the transposed matrix with the rows of A and, over each row:
ḋ - Dot product
```
[Answer]
## Julia, 27 24
```
a$n=round.(exp(log(a)n))
```
I am not sure what is allowed, but...
```
julia> a
5×5 Matrix{Int64}:
35 18 40 37 77
31 5 45 23 73
62 67 29 85 97
20 9 83 70 65
2 13 53 59 52
julia> round.(exp(log(a)5)) ≈ a^5
true
```
24 thanks to @MarcMush.
[Answer]
## JavaScript (ES6), 123 bytes
```
(n,a)=>[...Array(n)].map(_=>r=m(i=>m(j=>m(k=>s+=a[i][k]*r[k][j],s=0)&&s)),m=g=>a.map((_,n)=>g(n)),r=m(i=>m(j=>+!(i^j))))&&r
```
I had a 132 byte version using `reduce` but I was just mapping over `a` so often that it turned out to be 9 bytes shorter to write a helper function to do it for me. Works by creating the identity matrix and multiplying it by `a` longhand `n` times. There are a number of expressions that return `0` or `1` for `i == j` but they all seem to be 7 bytes long.
[Answer]
# [Python 3](https://docs.python.org/3/), 147 bytes
```
def f(a,n):
r=range(len(a));r=[[i==j for j in r]for i in r]
for i in range(n):r=[[sum(map(int.__mul__,x,y))for y in zip(*a)]for x in r]
return r
```
[Try it online!](https://tio.run/##jVPNjpswED6Hp5jb2pWJwBjIbsWTIIRQA7uOAkGGaJO@fDozNtuoe@nB6PPMfD@DYL6vH5cpezyO/QCD6NQk3yJwleum916c@0l0Uv50VV3bqjrBcHFwAjuBawhaDyP4e2EeihBluY5i7GZhp3XftuP13Lbqpu5S0vidxn/bWfzoJIvdNjHXr1eHkDPNDtntu7NH0TnX3THejgFUgA6rI3XRT6tDXc7BmLUunw1XENCdaU20@7TH9QPpY3cTdGpa0yt8F5BgBxboz0sPyTc9@RyHmXt3ui6rYJf/TPRvCXfc8eLiBV72p4udBLaljKK1X9Zf3dIvVR3t6kThoy60glI3iKFOEwWZaRq61Sm3daagSBWY0o8cEKd4isTfDdLhFU8SaJppkFJdHxTEukCU@WmIUS4mmzjNmOTLOseLQVmcxJ7x5VjzoMFyjA/9GiwMW8RkHafknZJPdgisjJTJ1Xtkaagbruekf@BwwTwzW0oSw2awyf0mJeVUnBzIh6KSeBHoRKQZSq9Dj51Cv/Q80mAdwvlTPwu9jW8C32zvJtSwH5eK3wTjr3VDLsqufRae2frGZyYO@@T@xCmv2UQRf2S3WY3d6iz/R1/fCX5KT7/QIPyIwmkpH38A "Python 3 – Try It Online")
[Answer]
# R, 49 bytes
```
f=function(m,n)`if`(n,m%*%f(m,n-1),diag(nrow(m)))
```
Recursive function that takes a `m`atrix and the power `n` to raise it to. Recursively calls `%*%`, which computes the dot-product. The initial value for the recursion is the identity matrix of the same size as `m`. Since `m %*% m = m %*% m %*% I`, this works just fine.
[Answer]
# [Python 3](https://docs.python.org/3/), 128 bytes
```
def f(A,n):r=range(len(A));return n and[[sum(A[i][j]*x[i]for i in r)for j in r]for x in f(A,n-1)]or[[i==j for i in r]for j in r]
```
[Try it online!](https://tio.run/##TYzNDoIwEITP8hR7bE1JaEHjTzjwHE0PJLRaogupkODT12096GVn9svMzO/lPmEd42AdONYJ5JfQhh5vlj0sso7za7DLGhAQehy0fq1P1mlv9Gj2G6mbAnjwCIEnO2ab6ZZs3iwlN1PQ2rftCL@C@SvEOXhcmGO62GmpBKiTgFIdBdRGECpremWVDrkqM3UQ0EhKEG2@KZUTTQI0cTaFIeE8fgA "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 131 bytes
```
f=lambda M,n:n and[[sum(map(int.__mul__,r,c))for c in zip(*f(M,n-1))]for r in M]or[[0]*i+[1]+[0]*(len(M)+~i)for i in range(len(M))]
```
[Try it online!](https://tio.run/##LY1NDoIwEIXXcopZtlAMLWjUxCNwgqZpKj/aBEpTYaELr45TdDPz5pv3ZvxrfkxOrGt/Hcx4aw3UzF0cGNdK@VxGMhpPrJv3Wo/LoDULrKG0nwI0YB28rSdpTzCTc0pV5CHyWk1BykKlNpNcZVGRoXOkptnHbnEbbcG4e/dfULX6gJ9IT2Syk1wwECcGuTgyKBVDlJc48iIWVMXGxIFBxdGBtPq5xOaoIsATZ5UobJSuXw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
²āDδQ¹Føδ*O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0KYjjS7ntgQe2ul2eMe5LVr@/2MPLXc5PedR05r0wwuyDu3@b8QVHW1opGNkoaNrZKZjHKsTrWuso2toAMTGOgZArpGpjomhDlDMBCRnBJIwAXJ0jCxjYwE "05AB1E – Try It Online") Footer formats output as a grid.
`²āDδQ` pushes the identity matrix to the stack:
`²ā` range from 1 to the length of the second input
`DδQ` equality table with itself
`¹F` iterate first input times:
`øδ*O` multiply current matrix with input matrix:
`ø` transpose current matrix
`δ*` 3d multiplication table with input and transposed matrix
`O` sum along last axis
] |
[Question]
[
This is yet another challenge about the Fibonacci numbers.
The goal is to compute the 20'000'000th Fibonacii number as fast as possible. The decimal output is about 4 MiB large; it starts with:
>
> 28543982899108793710435526490684533031144309848579
>
>
>
The MD5 sum of the output is
>
> fa831ff5dd57a830792d8ded4c24c2cb
>
>
>
You have to submit a program that calculates the number while running and puts the result to `stdout`. The fastest program, as measured on my own machine, wins.
Here are some additional rules:
* You have to submit the source code and a binary runnable on an x64 Linux
* The source code must be shorter than 1 MiB, in case of assembly it is also acceptable if only the binary is that small.
* You must not include the number to be computed in your binary, even in a disguised fashion. The number has to be calculated at runtime.
* My computer has two cores; you are allowed to use parallelism
I took a small implementation from the Internet which runs in about 4.5 seconds. It should not be very difficult to beat this, assuming that you have a good algorithm.
[Answer]
**Sage**
Hmm, you seem to assume that the fastest is going to be a compiled program. No binary for you!
```
print fibonacci(2000000)
```
On my machine, it takes 0.10 cpu seconds, 0.15 wall seconds.
edit: timed on the console, instead of the notebook
[Answer]
**Haskell**
This is my own try, although I did not wrote the algorithm by myself. I rather copied it from [haskell.org](http://haskell.org/haskellwiki/The_Fibonacci_sequence#Fastest_Fib_in_the_West) and adapted it to use `Data.Vector` with its famous stream fusion:
```
import Data.Vector as V
import Data.Bits
main :: IO ()
main = print $ fib 20000000
fib :: Int -> Integer
fib n = snd . V.foldl' fib' (1,0) . V.dropWhile not $ V.map (testBit n) $ V.enumFromStepN (s-1) (-1) s
where
s = bitSize n
fib' (f,g) p
| p = (f*(f+2*g),ss)
| otherwise = (ss,g*(2*f-g))
where ss = f*f+g*g
```
This takes around 4.5 seconds when compiled with GHC 7.0.3 and the following flags:
```
ghc -O3 -fllvm fib.hs
```
[Answer]
**C with GMP, 3.6s**
Gods, but GMP makes code ugly. With a Karatsuba-style trick, I managed to cut down to 2 multiplies per doubling step. Now that I'm reading FUZxxl's solution, I'm not the first to have the idea. I've got a couple more tricks up my sleeve... maybe I'll try 'em out later on.
```
#include <gmp.h>
#include <stdio.h>
#define DBL mpz_mul_2exp(u,a,1);mpz_mul_2exp(v,b,1);mpz_add(u,u,b);mpz_sub(v,a,v);mpz_mul(b,u,b);mpz_mul(a,v,a);mpz_add(a,b,a);
#define ADD mpz_add(a,a,b);mpz_swap(a,b);
int main(){
mpz_t a,b,u,v;
mpz_init(a);mpz_set_ui(a,0);
mpz_init(b);mpz_set_ui(b,1);
mpz_init(u);
mpz_init(v);
DBL
DBL
DBL ADD
DBL ADD
DBL
DBL
DBL
DBL ADD
DBL
DBL
DBL ADD
DBL
DBL ADD
DBL ADD
DBL
DBL ADD
DBL
DBL
DBL
DBL
DBL
DBL
DBL
DBL /*Comment this line out for F(10M)*/
mpz_out_str(stdout,10,b);
printf("\n");
}
```
Built with `gcc -O3 m.c -o m -lgmp`.
[Answer]
## [COW](http://esolangs.org/wiki/COW)
```
MoO moO MoO mOo MOO OOM MMM moO moO
MMM mOo mOo moO MMM mOo MMM moO moO
MOO MOo mOo MoO moO moo mOo mOo moo
```
Moo! (Takes a while. Drink some milk...)
[Answer]
Mathematica, interpreted:
```
First@Timing[Fibonacci[2 10^6]]
```
Timed:
```
0.032 secs on my poor man's laptop.
```
And of course, no binary.
[Answer]
# Ocaml, 0.856s on my laptop
Requires the zarith library. I used Big\_int but it's dog slow compared to zarith. It took 10 minutes with the same code! Most of the time was spent *printing* the damn number (9½ minutes or so)!
```
module M = Map.Make
(struct
type t = int
let compare = compare
end)
let double b = Z.shift_left b 1
let ( +. ) b1 b2 = Z.add b1 b2
let ( *. ) b1 b2 = Z.mul b1 b2
let cache = ref M.empty
let rec fib_log n =
if n = 0
then Z.zero
else if n = 1
then Z.one
else if n mod 2 = 0
then
let f_n_half = fib_log_cached (n/2)
and f_n_half_minus_one = fib_log_cached (n/2-1)
in f_n_half *. (f_n_half +. double f_n_half_minus_one)
else
let f_n_half = fib_log_cached (n/2)
and f_n_half_plus_one = fib_log_cached (n/2+1)
in (f_n_half *. f_n_half) +.
(f_n_half_plus_one *. f_n_half_plus_one)
and fib_log_cached n =
try M.find n !cache
with Not_found ->
let res = fib_log n
in cache := M.add n res !cache;
res
let () =
let res = fib_log 20_000_000 in
Z.print res; print_newline ()
```
I can't believe how much a difference the library made!
[Answer]
## Haskell
On my system, this runs almost as fast as [FUZxxl's answer](https://codegolf.stackexchange.com/questions/3191/write-the-fastest-fibonacci/3193#3193) (~18 seconds instead of ~17 seconds).
```
main = print $ fst $ fib2 20000000
-- | fib2: Compute (fib n, fib (n+1)).
--
-- Having two adjacent Fibonacci numbers lets us
-- traverse up or down the series efficiently.
fib2 :: Int -> (Integer, Integer)
-- Guard against negative n.
fib2 n | n < 0 = error "fib2: negative index"
-- Start with a few base cases.
fib2 0 = (0, 1)
fib2 1 = (1, 1)
fib2 2 = (1, 2)
fib2 3 = (2, 3)
-- For larger numbers, derive fib2 n from fib2 (n `div` 2)
-- This takes advantage of the following identity:
--
-- fib(n) = fib(k)*fib(n-k-1) + fib(k+1)*fib(n-k)
-- where n > k
-- and k ≥ 0.
--
fib2 n =
let (a, b) = fib2 (n `div` 2)
in if even n
then ((b-a)*a + a*b, a*a + b*b)
else (a*a + b*b, a*b + b*(a+b))
```
[Answer]
## C, naive algorithm
Was curious, and I hadn't used gmp before... so:
```
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int main(int argc, char *argv[]){
int n = (argc>1)?atoi(argv[1]):0;
mpz_t temp,prev,result;
mpz_init(temp);
mpz_init_set_ui(prev, 0);
mpz_init_set_ui(result, 1);
for(int i = 2; i <= n; i++) {
mpz_add(temp, result, prev);
mpz_swap(temp, result);
mpz_swap(temp, prev);
}
printf("fib(%d) = %s\n", n, mpz_get_str (NULL, 10, result));
return 0;
}
```
fib(1 million) takes about 7secs... so this algorithm won't win the race.
[Answer]
I implemented the matrix multiplication method (from sicp, <http://sicp.org.ua/sicp/Exercise1-19>) in SBCL but it takes about 30 seconds to finish. I ported it to C using GMP, and it returns the correct result in about 1.36 seconds on my machine. It's about as fast as boothby's answer.
```
#include <gmp.h>
#include <stdio.h>
int main()
{
int n = 20000000;
mpz_t a, b, p, q, psq, qsq, twopq, bq, aq, ap, bp;
int count = n;
mpz_init_set_si(a, 1);
mpz_init_set_si(b, 0);
mpz_init_set_si(p, 0);
mpz_init_set_si(q, 1);
mpz_init(psq);
mpz_init(qsq);
mpz_init(twopq);
mpz_init(bq);
mpz_init(aq);
mpz_init(ap);
mpz_init(bp);
while(count > 0)
{
if ((count % 2) == 0)
{
mpz_mul(psq, p, p);
mpz_mul(qsq, q, q);
mpz_mul(twopq, p, q);
mpz_mul_si(twopq, twopq, 2);
mpz_add(p, psq, qsq); // p -> (p * p) + (q * q)
mpz_add(q, twopq, qsq); // q -> (2 * p * q) + (q * q)
count/=2;
}
else
{
mpz_mul(bq, b, q);
mpz_mul(aq, a, q);
mpz_mul(ap, a, p);
mpz_mul(bp, b, p);
mpz_add(a, bq, aq); // a -> (b * q) + (a * q)
mpz_add(a, a, ap); // + (a * p)
mpz_add(b, bp, aq); // b -> (b * p) + (a * q)
count--;
}
}
gmp_printf("%Zd\n", b);
return 0;
}
```
[Answer]
## Java: 8 seconds to compute, 18 seconds to write
```
public static BigInteger fibonacci1(int n) {
if (n < 0) explode("non-negative please");
short charPos = 32;
boolean[] buf = new boolean[32];
do {
buf[--charPos] = (n & 1) == 1;
n >>>= 1;
} while (n != 0);
BigInteger a = BigInteger.ZERO;
BigInteger b = BigInteger.ONE;
BigInteger temp;
do {
if (buf[charPos++]) {
temp = b.multiply(b).add(a.multiply(a));
b = b.multiply(a.shiftLeft(1).add(b));
a = temp;
} else {
temp = b.multiply(b).add(a.multiply(a));
a = a.multiply(b.shiftLeft(1).subtract(a));
b = temp;
}
} while (charPos < 32);
return a;
}
public static void main(String[] args) {
BigInteger f;
f = fibonacci1(20000000);
// about 8 seconds
System.out.println(f.toString());
// about 18 seconds
}
```
[Answer]
# Go
It's embarrasingly slow. On my computer it takes a little less than 3 minutes. It's only 120 recursive calls, though (after adding the cache). Note that this may use a lot of memory (like 1.4 GiB)!
```
package main
import (
"math/big"
"fmt"
)
var cache = make(map[int64] *big.Int)
func fib_log_cache(n int64) *big.Int {
if res, ok := cache[n]; ok {
return res
}
res := fib_log(n)
cache[n] = res
return res
}
func fib_log(n int64) *big.Int {
if n <= 1 {
return big.NewInt(n)
}
if n % 2 == 0 {
f_n_half := fib_log_cache(n/2)
f_n_half_minus_one := fib_log_cache(n/2-1)
res := new(big.Int).Lsh(f_n_half_minus_one, 1)
res.Add(f_n_half, res)
res.Mul(f_n_half, res)
return res
}
f_n_half := fib_log_cache(n/2)
f_n_half_plus_one := fib_log_cache(n/2+1)
res := new(big.Int).Mul(f_n_half_plus_one, f_n_half_plus_one)
tmp := new(big.Int).Mul(f_n_half, f_n_half)
res.Add(res, tmp)
return res
}
func main() {
fmt.Println(fib_log(20000000))
}
```
] |
[Question]
[
[Inspiration](https://codegolf.stackexchange.com/q/32451/66833)
Given a positive integer \$1 \le n \le 9\$, output all positive \$n\$-digit integers \$i\$ for which the following is true:
* Each digit from \$1\$ to \$n\$ appears exactly once in \$i\$. Therefore, \$i\$'s digits are a permutation of the digits from \$1\$ to \$n\$.
* \$i\$ is divisible by \$n\$
* Removing the rightmost digit from \$i\$ yields another integer \$i\_{\text{trunc}(1)}\$ which is divisible by \$n-1\$
* Removing the rightmost digit from \$i\_{\text{trunc}(1)}\$ yields another integer \$i\_{\text{trunc}(2)}\$ which is divisible by \$n-2\$
* And so on, until \$i\_{\text{trunc}(n-1)}\$, which is divisible by 1.
For example, for \$n = 3\$, one such integer is \$321\$, as \$321\$ is divisible by \$3\$, \$32\$ by \$2\$ and \$3\$ by 1.
For \$n = 4, 5, 7\$, there are no such integers. In this case, you may output anything that cannot be confused with a possible output (e.g. `0`, `[]`, nothing, etc.). For \$n = 3, 6\$, you may output the two numbers in any format in which the two numbers are clearly separated from one another.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
If you use a lookup table method, brownie points\${}^\dagger\$ are awarded if you also include a version that calculates the correct output.
\${}^\dagger\$Brownie points may or may not be in the form of an upvote
## Test cases
These cases are exhaustive, so you will never receive (or have to handle) an input not included here.
```
n -> i
1 -> [1]
2 -> [12]
3 -> [123, 321]
4 -> []
5 -> []
6 -> [123654, 321654]
7 -> []
8 -> [38165472]
9 -> [381654729]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
LœJʒηāÖP
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f5@hkr1OTzm0/0nh4WsD//2YA "05AB1E – Try It Online")
**Commented**:
```
L # push [1..n]
œ # push all permutations
J # join each permutation into a number
ʒ # filter those numbers on:
η # each prefix ...
Ö # ... is divisible ...
ā # ... by its index
P # take the product (all)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
```
lambda n:[`s`[:n]for s in 321654,381654729,123654][380712>>n*2&3::2]
```
[Try it online!](https://tio.run/##VY7NDoIwEITP7lP0ZMDUhG75bSIvUjcBoyiJLgS4@PTVYjl4@mYymcyM7@UxMLrudHbP9nW5toKNbebGGqZumMQsehYaVZ6lUpceBVZSof4qsrpMCoV1zQfca2OQnO@w70wt32@RkiqJDezGqedFsBRdxLFjcaxFD8rDKgL8CSTQQWnpRwnS1RNkgfmW@z/hF0ER0nLldpOg@vMVfQA "Python 2 – Try It Online")
Outputs a list a strings.
---
**71 bytes**
```
lambda n:[0,1,12,[123,321],0,0,[123654,321654],0,38165472,381654729][n]
```
[Try it online!](https://tio.run/##VY7BDoJADETP9it6hGRN2C4gkOiPrD1gFCXRQggXv36luJiYHubNNGlnfM@PQSh0x3N4tq/LtUVpfGassWS8JWccWTbZMurKItdgEc1cpXSgH9TshUM3TCjYC06t3G/JcipLG9iNUy8zisEukTQI7k/Yg1XxloG@QAwukjOovyFfPUMRtdz2WgZjGzjEbbXqVoih/vM1fwA "Python 2 – Try It Online")
Just a boring straight hardcode. Outputs a single number, or a list of two numbers, or 0 for no output.
None of the other methods I tried seemed likely to be shorter than this. For instance, one idea is to generate numbers as prefixes of a single number, generating like `123654/10**(6-i)`.
An object method gives the same length. Unfortunately we can't use the much shorter `.pop` because it make the function not reusable because it modifies the list with each call.
```
[0,1,12,[123,321],0,0,[123654,321654],0,38165472,381654729].__getitem__
```
[Try it online!](https://tio.run/##VY7BDoIwEETP7lfsEZLV0BYETPRHsGk8APbgQkgvfn1lsZiYPcybmWQz8zs8J9ZxuN5jV5AipalT2pDRylKxnrhzVUqwimSmEar1D1p7cm7sgw/9y7k4TAsyesblwWOfrT@L/AKHefEckAmHjPPIeLyhByXSKQv6C9qCSWQIZQSUm7dQJT3vvazCNAvq1Dab7ssstH@@tR8 "Python 2 – Try It Online")
Aliasing the longest constant also gives the same length:
```
lambda n,c=381654729:[0,1,12,[123,321],0,0,[123654,321654],0,c/10,c][n]
```
[Try it online!](https://tio.run/##VU7LDoJADDzbr@gRkjXSXd4J/sjaA6IoiRZCuPj16y7CwTTpzPQ502d5jqJd31zcq31fby2K6hpTUp6lha5qmyhSpJUlbZTRxCrxEZQfCAUPodadyCe2wq4fZxQcBOdWHvfIrydxDYdpHmTx17GPJHaCxzMOQAEsMegf0QxmY0Zh@AfpqhmyDfO9Hwzg5gCKrVuuuPtnqP50xV8 "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 42 37 bytes
Calculates the numbers.
```
0({:#~0=[:+/#\|])@|:i.@!10&#.\@A.1+i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DTSqrZTrDGyjrbT1lWNqYjUdaqwy9RwUDQ3UlPViHBz1DLUz9f5rcnGlJmfkK2hYp2kqGShogAQtNf8DAA "J – Try It Online")
* `1+i.` 1…n
* `i.@!…@A.` all possible permutations of 1…n
* `10&#.\` convert every prefix of a permutation to a number
* `0(…)@|:` transpose the matrix and …
* `#\|]` 1…n mod the prefixes, e.g. `1 2 3 | 1 12 123`
* `0=[:+/` sum the result; is it 0?
* `{:#~` then take the last prefix of the permutation (the permutation itself)
[Answer]
# Scala, ~~81~~ 80 bytes
```
| =>1.to(|).mkString.permutations.filter{i=>1 to|forall(r=>i.take(r).toInt%r<1)}
```
[Try it in Scastie](https://scastie.scala-lang.org/OAhzYdiDSzaHYbcXI4ykNw)
Explanation:
```
| => //n, the input
1.to(|) //Range to n
.mkString //Turn it into a string
.permutations //Get all permutations
.filter{ i => //Filter them
1 to | forall(r => //For every r from 1 to n
i.take(r).toInt //The number made from i's first r digits
% r < 1 //Should be divisible by r
)
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
NθΦEXχθIι⬤…·¹θ›№ιIλ﹪I…ιλλ
```
[Try it online!](https://tio.run/##LYzBCsIwEETvfkWPG6hg8diTBJQeKsU/WGOwgTWbpknFr4/b6mUY5s2MGTEaRiql8yGna37dbYRJtbshOp/g7ChJ0GOAgd/imkNdTaquNM4JnJgTEXTeUJ7dYm/onxaaX@USLa5jzVme3H9DSlDPj0wMW6A/hqweOayVjYoo1ZZyLPuFvg "Charcoal – Try It Online") Link is to verbose version of code. Too slow for `n>5` on TIO. Explanation:
```
Nθ
```
Input `n`.
```
ΦEXχθIι
```
List all integers `i` up to `10ⁿ`, such that...
```
⬤…·¹θ
```
... for each integer `l` from `1` to `n`...
```
›№ιIλ﹪I…ιλλ
```
`l` is a digit of `i` and the `l`-character prefix of `i` is divisible by `l`.
Slightly faster 28-byte version:
```
NθΦEX⊕θθ⍘ι⊕θ⬤…·¹θ›№ιIλ﹪I…ιλλ
```
[Try it online!](https://tio.run/##VY0xDsIwDEV3TtExkcrAwtIJIoE6FFVwApNabSQ3CWlSxOmDUyYGW5b/e7aeIGgHlHNrfYq3ND8xiJdsdn0wNoqLociLDrzo3Zun1uqAM9qIA2N1VeoMCz4i86MwdfVPSM5PRMWjtJgV72BHFIefeQ0I5b5yiZ@xrGCJgorUuSGRE9tCfTShmpwvyJZyk7LJ@Zj3K30B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Generates the digits in base `n+1` instead of base `10`, thus making it possible to complete `n=6` on TIO.
Fastest 29-byte version using a compressed lookup table:
```
§⪪”)‴a3HSGS⸿Dπ¬Z⦄O<ε≔<πUθ8”0N
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCI7ggJ7NEQ8nYwtDM1MTcyNLA0MDQCIiMY/KMjQwNDEBMoAyYB6QNDGAqlXQUlAyUNHUUPPMKSkv8SnOTUos0NDU1rf//N/uvW5YDAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 78 bytes
```
(f=FromDigits)/@Select[Permutations@Range[s=#],f@#[[;;k]]~Mod~k~Sum~{k,s}<1&]&
```
[Try it online!](https://tio.run/##Tcq7CsIwFADQ3a8QCkWhIPUtNZBB3IRix3CHUNMYYhpIbicxvx6d5G5nOE7iUzmJppdZs7wY2DV4dzHaYFyueKdeqkfRquAm/C0/Rn6Xo1YisgKqgRdCNI0FSDf/SDZ1k0tvW8XPuS6hzG0wI865FjXM/l4Tb4i3xDviPfGB@Eh8gpy/ "Wolfram Language (Mathematica) – Try It Online")
-8 bytes from @att
[Answer]
# [C (gcc)](https://gcc.gnu.org/) -lm, ~~67~~ ~~101~~ 96 bytes
Added 34 bytes to fix a bug kindly pointed out by [xnor](https://codegolf.stackexchange.com/users/20260/xnor).
Saved 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
f(n){write(1,"321654",n-3&&n-6?0:n);n=n<4?123/exp10(3-n):n>7?381654729/exp10(9-n):n-6?0:123654;}
```
[Try it online!](https://tio.run/##hVHbbsIwDH3nK6xKoARa0SRcVkrhYdpXDB5QSKEaBNQirRrtr69zeoECD4uS1rHPObZj6eykLIqQaHr9jqOLIsy2BGeT8ciytSN6Pe1Mlu5MU18Hej5aMi6GKj0zlwhH05leTJfizcCn3KsDXhkoaYjGkJ8Xkb7AcRNpQjvXDuAyDoQreVFb9rmGAK7MBsbNETa45a7opdkkuVte7r8o8Qcl7KNRqlr6R0nuN3Ff7pX8UjEKGSVrlX7wVeq94xlbNrTvwqp54SkGYsqI9FalSHP92pxDEv2oU0hurdJh7enfXT4MBiWeQvU4TVsatSqhATD/FjrHGAyJ1d2CswCsCqfzwEuQZ0ba8uI1CESW4XdCGwHs54mpGFLvcymTr58gvAXhL5BWcd1kpTFHYkPzqEkQKJZl5sfXdeq8kxe/MjxsdknhHI5/ "C (gcc) – Try It Online")
Total lookup based solution. If there are two solutions: outputs one to `stdout`, and returns the other. If there's only one answer it's simply returned. Returns \$0\$ if there's no answer.
## Bonus round for brownie points
# [C (gcc)](https://gcc.gnu.org/), ~~232~~ 212 bytes
Saved a whopping 20 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
p;m;j;char b[9],c[9];d;i;f(n){for(d=0,i=n;i;)d+=9*d+i--;for(sprintf(c,"%d",d);d/++i;)if(sprintf(b,"%d",i),qsort(b,n,1,L"\xf06be0f\xd02917beǃ"),!strcmp(b,c)){for(p=0,m=n,j=i;j;j/=10)p|=j%m--;p||printf("%d ",i);}}
```
[Try it online!](https://tio.run/##hVLLUoMwFN37FZGZzpASpiT4woguHHfO@AFtFzQPTZUUgQVjy8qP86/Em5a@dCFDmJP7OOfmBBE@C9F1Bc/5nIuXrESzcTIlAj5ccsO1b/FSL0pfphExqYUQlkGaDGVgwpC7TFWUxtbaF8QbSI9IzOUoCKDO6F1utskZTN6rRVnD3hJKHr1Jo6OLmYr0pJERS@jlTH19epicVnUp8gLqBN7oF6Cfp5bMUwOTzkcpjXCxSueDHMYoVqteCGSQ0@Ft2@WZsT5eniB4IIlUUyhRK0nHU5SiJSWIMrdigqL1C/Di/GwN4ysK8JLtUdLyP0zsiClmdMsE8H8mZ/dQvCjxqkogckxgyAObNMk9rHOPoMN97PV9YAfy3RjGStVAW8R7eIMq86EW2t8dFY/6yHAf4giux9VjtDFneywLXBuiAFG@Sx1YG96Cu8hiftRXQZ/7UY6jikJ47/maePqrhB2UsD8lvbCioWJ3ng/6A4kn1rt22AECIr1qe9J230K/Zc9VFz7prKq78EM1SlR1Jl5/AA "C (gcc) – Try It Online")
Computes the correct numbers through calculation and outputs them to `stdout`. Outputs nothing if there's no answer. Times out on TIO for \$n=9\$ but does all of them in `3m36.499s` on my laptop.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833)!
This is a naive method, there could be a more terse one.
```
Œ!JḍḌƤẠƲƇḌ
```
A monadic Link accepting \$n\$ which yields `0` if none are found or a list of valid numbers.
**[Try it online!](https://tio.run/##y0rNyan8///oJEWvhzt6H@7oObbk4a4FxzYdawey////bwYA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///oJEWvhzt6H@7oObbk4a4FxzYdawey/1sebn/UtOY/AA "Jelly – Try It Online").
### How?
```
Œ!JḍḌƤẠƲƇḌ - Link: n
Œ! - all permutations of [1..n]
Ƈ - filter keep those (p for p in Œ!) for which:
Ʋ - last four links as a monad f(p):
J - range of length = [1..n]
Ƥ - apply to prefixes (of p):
Ḍ - un-decimal
ḍ - divides? (vectorises)
Ạ - all truthy?
Ḍ - un-decimal
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
mdföΛIṠz¦ŀmdḣPḣ
```
[Try it online!](https://tio.run/##yygtzv7/Pzcl7fC2c7M9H@5cUHVo2dGG3JSHOxYHAPH///@NAQ "Husk – Try It Online")
Almost the same as the other question, except with parameters.
[Answer]
# [Perl 5](https://www.perl.org/), 64 bytes
```
sub{grep"@_"==y///c,1,12,123,321,123654,321654,$x=38165472,$x.9}
```
[Try it online!](https://tio.run/##FcaBCsIgEIDhVzkOGRvcTtRWjTB6kEAoZizKiStoRM9uE374vzikR5efi/A2z@/L95aGiCeH1i5SyispUnrNkNGFZtttCsvEx5p90U6v5v6XDxDTGF6AwkHbHgH5Po2hRgKkSvhauKZhPAcEPyVQzH3@Aw "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes
```
f[s_:0,l_:0]=0!=##2&&l∣s&&If[l<#,##~f[10s+i,l+1]~i~Do~{i,#},Print@s]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8tujjeykAnB0jE2hoo2iorG6mp5TzqWFyspuaZFp1jo6yjrFyXFm1oUKydqZOjbRhbl1nnkl9XnamjXKsTUJSZV@JQHKv2P7A0M7UkOi061kHLNTkjv86xqCixss4y9j8A "Wolfram Language (Mathematica) – Try It Online")
Call as `f[][n]`. Prints the results.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 97 bytes
A recursive function that computes and prints the matching integers.
```
f=(n,s='987654321'.slice(-n),d,p)=>p%d?0:s?[...s].map(v=>f(n,s.replace(v,''),-~d,[p]+v)):print(p)
```
[Try it online!](https://tio.run/##JYxLDoIwGIT3nuLfmLZpacAngoUbeAHCouGRYLD@aUk3Rq9eq6xmMvPN3LXXrrMTLonPQxgVNcIpcsnPp@Nhv8uIdPPUDTQxTPQCmapw29dp4epGSula@dBIvarG307aAWcdaS8IYSL59KLBlnvGCrSTWSiyMD4tNaAgK8HAFbI0KucMXhuAFSI3RYCDYWWM4u9f1yrad/gC "JavaScript (V8) – Try It Online")
---
# JavaScript (ES6), 59 bytes
Hard-coding is obviously shorter.
```
n=>[,1,12,[321,123],,,[321654,123654],,q=38165472,q+[9]][n]
```
[Try it online!](https://tio.run/##HYpBDsIgEEX3PcXsgDA1AmrVikfwAoRFU4vRNINtjRvj2RFcvfdf/qN7d0s/35@vmuJ1SMEmsmeHCpVGZ3Sh8Yh/3203ZWbkMlmzL6XROEl38N6RTyHOnMCCaoHgBGqdKaWATwXQR1riOKzGeOPsYhnI/JHAjgwhcBKirb7pBw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
║è[⌐•^∩╖[ª╫√°
```
[Run and debug it](https://staxlang.xyz/#p=ba8a5ba9075eefb75ba6d7fbf8&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&m=2)
Same brute force algorithm. Nothing clever.
[Answer]
# Excel, 64 bytes
```
=CHOOSE(A1,1,12,"123,321",,,"123654,321654",,38165472,381654729)
```
Input is in `A1`. Hard-coded answer is shorter than calculation would be.
[](https://i.stack.imgur.com/LysX5.png)
] |
[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/148911/edit).
Closed 6 years ago.
[Improve this question](/posts/148911/edit)
A Sumac sequence starts with two integers: t1 and t2.
The next term, t3, = t1 - t2
**More generally, tn = tn-2 - tn-1**
The sequence ends when tn < 0.
Your challenge: Write a program or function that prints the length of a Sumac sequence, starting with t1 and t2.
* t1 and t2 are integers within your language's range.
* Standard loopholes apply.
**Test cases**
```
t1 t2 sumac_len(t1,t2)
120 71 5
101 42 3
500 499 4
387 1 3
```
Bonus street cred:
```
3 -128 1
-314 73 2
```
This is code-golf, so shortest answer in bytes wins.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
→V<¡oG-↔
```
Takes input as a 2-element list.
[Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/j9omhdkcWpjvrvuobcr///@jDY0MdMwNY7miDQ0MdUyMgAxTAwMdE0tLIMvYwlzHMBYA "Husk – Try It Online")
## Explanation
```
→V<¡oG-↔ Implicit input, say p=[101,42]
¡ Iterate on p:
↔ Reverse: [42,101]
oG- Cumulative reduce by subtraction: [42,59]
Result is infinite list [[101,42],[42,59],[59,-17],[-17,76],[76,-93]...
V< Find the first index where adjacent pairs are lexicographically increasing.
In our example [42,59] < [59,-17], so this gives 2.
→ Increment: 3
```
[Answer]
# [Haskell](https://www.haskell.org/), 22 bytes
```
a#b|b<0=1|c<-a-b=1+b#c
```
[Try it online!](https://tio.run/##Vc6xCsMgFIXh3ae4kA5KEbxqSVLi0jfRNFCJ1RJTuuTdrRk948c/nJfN6xJCKbZzh5uEwWOeuOXO4NV1c3lbH8HAMxGo@2w@7nABlAI66LFFgRW1bPAmzlKPY6Nq6KsiIZwDPFL85iUDzbsPAX5pWzO7t32tKUc5sIYpV6jZ@USVPw "Haskell – Try It Online")
I really wish there was a way to pattern match for a negative number...
## Explanation
```
a#b|b<0=1|c<-a-b=1+b#c
a#b -- define a function (#) that takes two arguments a and b
|b<0 -- if b is negative...
=1 -- return 1
| -- otherwise...
c<-a-b -- assign a-b to c...
= b#c -- and return the result of (#) applied to b and c...
1+ -- incremented by 1
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes
```
V<0t¡ȯF-↑2↔
```
[Try it online!](https://tio.run/##yygtzv7/P8zGoOTQwhPr3XQftU00etQ25f///9GGRgY65oaxAA "Husk – Try It Online")
Takes the bonus street cred for whatever that's worth.
### Explanation
```
¡ȯ Repeatedly apply the function to the right to the list of all
previous values and collect the results in an infinite list.
↔ Reverse the list of previous results.
↑2 Take the first two values (last two results).
F- Compute their difference (using a fold).
t Discard the first element.
V<0 Find the first index of a negative value.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 29 bytes
```
->a,b{(1..a).find{a<b=a-a=b}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6law1BPL1FTLy0zL6U60SbJNlE30TaptvZ/QWlJsUJatKGRgY65YSwXlGuso2toZBH7HwA "Ruby – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
`yy-y0<~]N2-&
```
This handles negative inputs (last two test cases).
[Try it online!](https://tio.run/##y00syfn/P6GyUrfSwKYu1s9IV@3/f0MjAy5zQwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D@hslK30sCmLtbPSFftf4SLn0pFyH9DIwMuc0MuQwNDLhMjLlMDAy4TS0suYwtzLkMuYy5dQyMLLl1jQxMuc2MA).
### Explanation
```
` % Do...while
yy % Duplicate top two elements. Implicit inputs first time
- % Subtract
y % Duplicate from below: push previous term
0<~ % Is it 0 or greater? This is the loop condition
] % End. Proceed with next iteration if top of the stack is true
N % Push number of elements in stack
2- % Subtract 2
& % Specify that the next function, namely implicit display, should
% only display the top of the stack
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~142~~ 90 bytes
```
((()){{}<(({}({}))[({}[{}])({})])([(({})<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}>}<>)
```
[Try it online!](https://tio.run/##FYoxCoBADAS/YpktBM/GJuQjxxVaCKJY2C55e0wgTBh2jm@/3vl89jtCRADSVYSeB/Rkpw@UJXst0OoMQ9SyrxZQczpFlG5l9PR6lkTE1qa2Lj8 "Brain-Flak – Try It Online\"/PGpOiaDyU9ZYNo@OmSom5ugJhrknlwjv7LMbYylXX5AA \"Brain-Flak – Try It Online")
Not very short. Takes input backwards.
# Explanation
```
(
(()) #Push 1
{ #Until 0
{} #Pop (+1 to counter)
<(({}({}))[({}[{}])({})]) #tn = tn-1 - tn-2
([(({})<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}> #Greater than 0?
} #End loop
<> #Get rid of everything
) #Push result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
[DŠ-D0‹#]NÌ
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2uXoAl0Xg0cNO5Vj/Q73/P9vbshlaGQAAA "05AB1E – Try It Online")
**Explanation**
Takes input as `t2, t1`
```
[ # start a loop
DŠ # duplicate top of stack and move it down 2 positions
- # subtract the top 2 values
D0‹# # if a copy of the top value is negative, break loop
] # end loop
NÌ # push iteration index+2
```
[Answer]
# Mathematica, 55 bytes
```
(t=1;While[Last@LinearRecurrence[{-1,1},#,t++]>0];t-2)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X6PE1tA6PCMzJzXaJ7G4xMEnMy81sSgoNbm0qCg1Lzk1ulrXUMewVkdZp0RbO9bOINa6RNdIU@1/QFFmXolDWnS1oZGBjrlhbSwXQsTAUMfECFnE1MBAx8TSElnI2MIcaGzsfwA "Wolfram Language (Mathematica) – Try It Online")
and now the regular boring approach by @totallyhuman
# Mathematica, 25 bytes
```
If[#2<0,1,1+#0[#2,#-#2]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98zLVrZyMZAx1DHUFvZAMjWUdZVNoqNVfsfUJSZV6LgoJAWbWhkoKNgbhjLhSRkYKijYGKELGRqAFRlYmmJLGZsYa6jYBj7HwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 22 bytes
```
[:#({:,-/)^:(0<{:)^:a:
```
How it works:
```
^:a: - Repeat until the result stops changing, store the results in a list
^:(0<{:) - repeat if the second term is positive
({:,-/) - makes a tuple (second, first minus second)
[:# - number of elements in the list ([: caps the fork)
```
[Try it online!](https://tio.run/##PYpBCoMwFET3OcVgFypo@n@SEv3UkxQUKQ3ixkWW0rPHbOJshvdm9hTipEEQUPrIozml65/tLA29T8m9SmpVpVGHSdfo8BeEqNTvux0IYEOA5xuJAWcKviivbhwL28ED99kiZ2EzFLFYdvAW6QI "J – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~32~~ ~~27~~ 26 bytes
*-5 bytes thanks to totallyhuman's abuse of gcc (seems to work on tcc too)*
*-1 byte thanks to PrincePolka*
```
f(a,b){a=b<0?:1+f(b,a-b);}
```
[Try it online!](https://tio.run/##bc3fCoIwHIbhc6/ihxFstMWmhpp/upFONtdqUDPKOhGvfRkWNOn05eH7GnpsGrcwtjk/1AHKe6dMuz7VTiNBJO5FJUu22/KVRpIIKnExOGM7uAhj0bM1CkMfAFxvY9Qo5BEjkHKoaliqvQ0JaPRpGBe/kHECSeTDqc3gn8UNG1uS576Ms5SAD6c0YwQojzLfTc2HNObJeB178hvfdAico@oF "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 29 bytes
```
f=lambda a,b:b<0 or-~f(b,a-b)
```
[Try it online!](https://tio.run/##Tcw7CoAwEEXR3lVMmYEJZJKIH3QxGSQo@ENsbNx6TCVpD/e987nnY7cpxXENm0wBAkkvg4Hj0m9UQkELpvNa9ltFxdYQNIxY/WKYwNtCapMb33UFubYhKFeOQLNtC9GOfb52iOkD "Python 2 – Try It Online")
Returns [True instead of 1](https://codegolf.meta.stackexchange.com/a/9067/58563).
[Answer]
# JavaScript (ES6), 24 bytes
Returns [true instead of 1](https://codegolf.meta.stackexchange.com/a/9067/58563).
```
f=(a,b)=>b<0||1+f(b,a-b)
```
### Test cases
```
f=(a,b)=>b<0||1+f(b,a-b)
console.log(f(120, 71 )) // 5
console.log(f(101, 42 )) // 3
console.log(f(500, 499 )) // 4
console.log(f(387, 1 )) // 3
console.log('Bonus street cred:')
console.log(f(3, -128)) // 1
console.log(f(-314, 73 )) // 2
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
This is a recursive function that takes two arguments, `G` and `H`. The link is slightly modified in order to actually call the function on the given input.
```
M|<H0hgH-GH
```
**[Test suite.](https://pyth.herokuapp.com/?code=M%7C%3CH0hgH-GHgF&test_suite=1&test_suite_input=120%2C+71%0A101%2C+42%0A500%2C+499%0A387%2C+1&debug=0)**
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 23 bytes
```
2∘{0>-/⍵:⍺⋄(⍺+1)∇-⍨\⌽⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSjRx0zqg3sdPUf9W61etS761F3iwaQ0jbUfNTRrvuod0XMo569QLlaoHIFQyMDBXNDLiDDwFDBxAjIMDUwUDCxtASyjC3MFQwB "APL (Dyalog Unicode) – Try It Online")
**How?**
`2∘` - with an initial accumulator of 2,
`-/⍵` - if the next term
`0>` - is below 0,
`⍺` - return the accumulator. otherwise,
`(⍺+1)` - increase the accumulator
`∇` - and recurse with
`-⍨\⌽⍵` - the last two items reversed and differenced.
```
{⍵} 8 2
8 2
{⌽⍵} 8 2
2 8
{-⍨\⌽⍵} 8 2
2 6
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 44 bytes
```
int f(int a,int b){return b<0?1:1+f(b,a-b);}
```
[Try it online!](https://tio.run/##VVDLasMwELz3K4aAwaJSsGyHJE1Iv6CnHEsPkh9BaSIbax0owd/uyg@Ke5mFYWd2Zq/qoURVF/aaf/d1q28mQ3ZTzuFDGYvnC@BIkcl6YwllOKDiA2r2bApqGwt9jN7lm3wtQ82V0OzQ9V42m01qPCqT4@4twzM1xl4@v6Cai2PjBYAKR6GMI46tZIcFFUmONF5Sm8hvpfv9kkt2W45/woRDyHi3pEQiU@@fjFz3V2yKNm5M5TC1m5OdfxwV93XV0rr2wakMV0Gac3iAOCHIA7vig0pz/55hsvlA1/8C "Java (OpenJDK 8) – Try It Online")
### Shortest iterative I found (50 bytes)
```
(a,b)->{int c=1;for(;b>=0;c++)b=a-(a=b);return c;}
```
[Try it online!](https://tio.run/##VZBBa8MwDIXv@xWiUHCoE5Imoy0mge22w9ihx7GD7CTFXeoEWymU0t@eOWk3sossPp70nnXEM4ZtV5lj@T10vWy0AtWgc/CO2sD1CcARkla@OXpt1JNuoro3inRrojdDr9qgvXx0lUVqLdT5wJDLICyu2hCoPBF1a5mQRR4LtVoFMseQYS4DYSvqrQElboPw6x/udzs4t7qEk8/A9mS1OXx@AdqDC6ZIAFQ5Ysk65rBJAjFDccIhW8/Rc@xV2W43Z@l2w@HfYMohTNbbOQrTJPP704nd/i5xjzYpxh8ih/GRv8n2F0fVKWp7ijofnGq2WGYlB18gLGBZLs2Cj1OSQx1h1zWXF@fvyEYUPLxuww8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 24 bytes
```
?[dsb-1rlbrd0<a]dsaxz1-p
```
[Try it online!](https://tio.run/##S0n@b2hkoGBu@N8@OqU4SdewKCepKMXAJjE2pTixospQt@D/fwA "dc – Try It Online")
### Explanation
```
? # read input | 71 120
[dsb-1rlbrd0<a] # push string | [string] 71 120
dsa # copy top to register a | [string] 71 120
x # execute the string | -5 27 1 1 1 1
z # push length of stack | 6 -5 27 1 1 1 1
1- # decrement top by 1 | 5 -5 27 1 1 1 1
p # print top
# string in register a:
dsb # copy top to register b | 71 120
- # subtract | 49
1 # push 1 | 1 49
r # swap top two elements | 49 1
lb # load register b | 71 49 1
r # swap top two elements | 49 71 1
d0<a # if top < 0 execute register a
```
[Answer]
# Z80 Assembly, 10 bytes
This version attempts to do the "street cred" version of the task. However, for the suggested test case where t1=-314, t2=73 this program produces answer "0", which, frankly, makes a little bit more sense than "2".
```
SumacLen:
xor a ; HL = t[1], DE = t[2], A is the counter
Loop: bit 7,h
ret nz ; stop if HL is negative
inc a
sbc hl,de ; HL = t[3], DE = t[2]
ex de,hl ; HL = t[2], DE = t[3]
jr Loop
```
The test program for ZX Spectrum 48K written using Sjasmplus assembler can be downloaded [here](http://introspec.retroscene.org/codegolf/sumaclen.asm). A compiled snapshot [is also available](http://introspec.retroscene.org/codegolf/sumaclen.sna).
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~85~~ 75 bytes
```
(b,c)->{int d,k=1;for(;;){if(c<0)break;else{d=c;c=b-c;b=d;k++;}}return k;};
```
[Try it online!](https://tio.run/##fZDBboMwEETP8BV7tBWDMKRKoi39g@aSY9WDbUzlQAwyJlKF@HZqq72Wy65G@zQz2rt4imwYtb033aZ6MU3wLoxd0sRYr10rlIZrUFGCJnFKBnEpimmypsnkhTcKrmCh3ohkimZvSwQa1tUc28ERRLqYlqjXgkqnRYe6n/TS1ApVLTOFsm6wOxxwXZ32s7PQ4YpbMs6yD85/Ac/BNPAI3cjNO2O/Pj5B0Njs9j15/ciH2edjOPjeEptrwsuCwYnTWPNfpuAMjuUu81IEn@PlsgtV5xOD/ayKQcbL8y6TVfwYSlf097fr9gM "Java (OpenJDK 8) – Try It Online")
ungolfed:
```
(b,c)->{
int d,k=1;
for(;;){
if(c<0)
break;
else{
d=c;
c=b-c;
b=d;
k++;
}
}
return k;
};
```
[Answer]
# Common Lisp, ~~59~~ 42 bytes
```
(defun f(a b)(if(< b 0)1(1+(f b(- a b)))))
```
[Try it online!](https://tio.run/##LY3RCsIwFEN/JQzEFBn0tpV14M9s1kJhrsPN1/16XdU8hMAJnPuU1qUUhkd8z4gcMCqmyBtGaCWUCyNGtqigpnDKecGw4vtFmnEmxWh0okDRAmeOcdUaru@PZX2HiixaMV6xteLQWaUQMhjz6zls2NDsLgC/8mE/NVV58L@5fAA)
[Answer]
# [Perl 6](https://perl6.org), ~~24~~ 19 bytes
*-5 bytes thanks to Brad Gilbert b2gills.*
```
{+(|@_,*-*...^0>*)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WlujxiFeR0tXS09PL87ATkuz9r81V3FipUKahqGRgY65oaa1goKygilMzMBQx8QIImYMFTM1MNAxsbQECiormEDFjC3MdQzBIsb/AQ "Perl 6 – Try It Online")
**Explanation**: The whole thing in the parentheses is exactly the sequence in question (`|@_` are the first 2 terms (= the two parameters), `*-*` is a function that takes two arguments and returns their difference, and `* <0` is the stopping condition (term less than 0). We omit the last term with `^` after the `...`). We then force the numerical context by the `+` operator, which yields the length of the sequence.
] |
[Question]
[
Given a nonzero polynomial with integer coefficients and roots that are on the imaginary and on the real line such that if `a` is a root then so is `-a`, return another polynomial with the roots rotated by 90 degrees.
### Details
The polynomial can be given in any reasonable format, e.g. as a list of coefficients. The symmetry condition that `a` is a root if and only if `-a` is a root too enforces the rotated polynomial to have real integer coefficients as well.
### Examples
In the following the polynomials are given as a list of coefficient of the monomials in descending degree. (i.e. the constant comes last)
The polynomial `x^2-1` has roots `{1,-1}`. Rotating them by `90°` means multiplying by `i` (the imaginary unit), so the output polynomial should have the roots `{i,-i}`, which is `x^2 + 1`.
```
Input / Output
[1 0 10 0 -127 0 -460 0 576] [1 0 -10 0 -127 0 460 0 576]
[1 0 -4 0] [1 0 4 0]
[1] [1]
```
[Answer]
## Mathematica, 10 Bytes
Pure function which takes a function of x and substitutes in ix.
```
#/.x->I*x&
```
Alternative with only 7 bytes but not quite sure if it counts. Pure function which takes in a pure function and returns a function of x.
```
#[I*x]&
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Jı*Ċ×
```
[Try it online!](https://tio.run/nexus/jelly#@@91ZKPWka7D0////x9tqKNgoKNgaACmdA2NzCEMEzOIiKm5WSwA "Jelly – TIO Nexus")
## How it works
Multiplies the first element by `1`, the third element by `-1`, etc.
```
Jı*Ċ× argument: z
J [1,2,...,len(z)]
ı i (the imaginary unit)
* to the power of (each element)
Ċ imaginary part
√ó multiply by input (vectorize)
```
## Proof of algorithm
Let the polynomial be `f(x)`.
Since we are guaranteed that if `x` is a root then so is `-x`, so `f` must be even, meaning that its coefficient for the odd powers must be `0`.
Now, rotating the roots by `90°` is essentially `f(ix)`.
Expanding then comparing coefficients proves the algorithm.
[Answer]
## JavaScript (ES6), 25 bytes
```
a=>a.map((e,i)=>i%4?-e:e)
```
The original polynomial has solutions of the form `x = ±a` where a lies on the real or imaginary line. Except when `a = 0` (in which case `x` is a factor of the polynomial), this means that `x² - a²` is a factor of the polynomial (which means alternate terms are always zero). Now when we rotate the roots, the factor changes to `x² + a²`. Since all the factors change at the same time, the third term of the polynomial, which is the sum of all the `-a²` terms, changes sign, the fifth term, which is the sum of products of pairs of `-a²` terms, keeps the same sign, etc. alternating every other term.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 27 bytes
```
@(x)round(poly(roots(x)*j))
```
[Try it online!](https://tio.run/nexus/octave#S7PV09P776BRoVmUX5qXolGQn1OpUZSfX1IMFNLK0tT8n6YRbahgoGBoACR0DY3MQZSJGYhnam4Wq/kfAA "Octave – TIO Nexus")
This directly applies the definition: compute roots, multiply by `j`, convert back from roots to polynomial. A final rounding is necessary because of floating-point numerical errors.
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
f=lambda x,s=1:x and[0,x[0]*s]+f(x[2:],-s)
```
[Try it online!](https://tio.run/nexus/python3#NYzNCoAgEIRfZY9ZK6j0A4JPInswRAjKIjvs21sUnb6Zj2FqcmvY5hiAsThtGUKOXiF7RW2hLjXsjSWURdS0n8CwZPAaQSFo9UJqM32hHz8zTCPhv5L9g7eSheNc8tU8p0LUGw "Python 3 – TIO Nexus")
[Answer]
# [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), ~~71~~ 66 bytes
```
readIO
b=i
lbla
readIO
d=c
d&2
i=i*(1-d)
printInt i
b-1
c+1
if b a
```
[Try it online!](https://tio.run/##Lcc7CoAwEEXR/q0ilfghkBHRKgtI5RryURgIKib7H1PY3MMtnO8i8h4@uR3BMnLIHv8nG5G6GWx57EmnAc/LV3VXVYygCXEi8KmC8iKyCYkRMi2a5q2xrOYD "S.I.L.O.S – Try It Online")
~~I have no clue what wizardry @Leaky Nun did here to save 5 bytes.~~
Took me a second to figure out, but The second bit of C will alternate like we want. Therefore @Leaky Nun exploited this to save the bits we need.
[Answer]
# TI-Basic, 20 bytes
```
seq(real(i^X/i)Ans(X),X,1,dim(Ans
```
If stored in `prgmA`, run with:
```
{1, 0, 3, 0, 1}:prgmA
```
`seq(` just had to be the *one*\* command that doesn't support complex numbers. :)
\*: Exaggeration
[Answer]
# Casio-Basic, 8 bytes
```
n|x=ùëñx
```
Unnamed function, using Ian Miller's Mathematica approach. The imaginary ùëñ from the Math2 keyboard needs to be used (counts as 2 bytes, char code 769), and the polynomial should be entered as an equation of `x`.
7 bytes for the code, 1 byte to specify `n` as a parameter.
**Explanation**: Takes the equation `n`, then simply replaces all instances of `x` with `ùëñx`.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 16 bytes
```
p->x=I*x;eval(p)
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8L9A167C1lOrwjq1LDFHo0Dzf0FRZl6JRppGRZyFgraCoYFWRZyZgq6CoZE5kGUCZJmYgcSMgJKm5maamv8B "Pari/GP – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Æ[]▐↨
```
[Run and debug online!](https://staxlang.xyz/#p=925b5dde17&i=%5B1+0+10+0+-127+0+-460+0+576%5D%0A%5B1+0+-4+0%5D%0A%5B1%5D&a=1&m=2)
Port of the Jelly answer.
Uses ASCII representation to explain:
```
mih|1*
m Map each element with rest of program, print mapped results on individual lines
i Current 0-based loop index
h Floor(i/2)
|1 (-1)^(i/2)
* Multiply with current element
```
If there can be leading zeros, they need to be trimmed first and it can be done at the cost of another byte.
] |
[Question]
[
**This question already has answers here**:
[Polygonal Numbers!](/questions/99688/polygonal-numbers)
(9 answers)
Closed 6 years ago.
# Explanation of the challenge
Given an input, return what shapes it could be. There are only a couple options.
1. Square
2. Triangle
---
**Square**
A square is in the following format:
```
XXXX
XXXX
XXXX
XXXX
```
So, in this example, the input would be:
```
16
```
And the output would be:
```
1 or "Square"
```
**Triangle**
We are only checking for equilateral triangles:
```
X
X X
X X X
X X X X
```
So, in this example, the input would be:
```
10
```
And the output would be:
```
2 or "Triangle"
```
---
# Rules for input and output
Input must be a number.
Output can be an integer list or string list as long as you specify how your output works in your post. The output will be either a **triangle, square, or both**; never neither.
---
# Test Cases
```
36 -> 1,2 or 3 or ["Square","Triangle"] or "Both"
15 -> 2 or "Triangle"
4 -> 1 or "Square"
```
---
# Leaderboard
```
var QUESTION_ID=118960,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/118980/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]
# [Japt](https://github.com/ETHproductions/japt), ~~18 15~~ 11 bytes
```
[U8*UÄ]®¬v1
```
[Try it online!](https://tio.run/nexus/japt#@x8daqEVergl9tC6Q2vKDP//NzQAAA "Japt – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes
```
×8‘,µÆ²
```
[Try it online!](https://tio.run/nexus/jelly#@394usWjhhk6h7Yebju06f///8ZmAA "Jelly – TIO Nexus")
Outputs [1,1] for both, [0,1] for square, [1,0] for triangle, [0,0] for neither.
**Explanation**
```
×8‘,µÆ² - main link, input a
, - a list of the following two:
×8‘ - a×8+1 (which is square when a is triangle)
- (implicit) a
µÆ² - On the previous, check if each is a square
```
[Answer]
# JavaScript (ES7), ~~40~~ 32 bytes
Returns 1 for square, 2 for triangle, 3 for both or 0 for neither.
```
n=>!(n**.5%1)+2*!((8*n+1)**.5%1)
```
* 8 bytes saved in collaboration with [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) and [Neil](https://codegolf.stackexchange.com/users/17602/neil).
---
## Try It
Displays "Square/Triangle/Both/Neither" for clarity
```
f=
n=>!(n**.5%1)+2*!((8*n+1)**.5%1)
i.addEventListener("input",_=>o.innerText=["Neither","Square","Triangle","Both"][f(+i.value)])
```
```
<input id=i type=number><pre id=o>
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~49~~ ~~48~~ 37 bytes
EDIT:
* -1 byte: @xnor suggested parametrizing on `k`.
* -11 bytes: And then turned it all inside out...
`f` takes an integer and returns a list: `[3]` for square, `[2]` for triangle, and `[2,3]` for both (or `[]` for neither.)
```
f n=[k|k<-[2,3],0<-scanl(-)n[1,k..n]]
```
[Try it online!](https://tio.run/nexus/haskell#y03MzLPNzCtJLUpMLlEpzcvJzEst1stNLNAozsgv10vTK0pNTNHUAwv/T1PIs43Orsm20Y020jGO1TGw0S1OTszL0dDVzIs21MnW08uLjf3/39iMy9CUy4QLAA "Haskell – TIO Nexus")
This uses that triangular numbers are sums `1+2+3+4+...+i` while square numbers are sums `1+3+5+7+...+i`, thus by starting with `n` and using `scanl(-)` to subtract either the range `[1,2..n]` or the range `[1,3..n]` consecutively, each of those cases will eventually hit 0.
[Answer]
# PHP, 67 bytes
Returns 2 for square, 1 for triangle, 3 for both and 0 for none
```
<?=(($q=sqrt($i=$argn))==($q^0))*2+(2*$i==($x=sqrt(2*$i)^0)*$x+$x);
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTaz/p@anJGvoaFSaFtcWFSioZJpC5bS1LS1BQrGGWhqahlpaxhpASWAAhUQVSCuJlBOS6VCW6VC0/r/fwA "PHP – TIO Nexus")
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), ~~15~~ 7 bytes
```
D8*≥«Æ²
```
[Try it online!](https://tio.run/nexus/ohm#@@9iofWoc@mh1YfbDm36/98EAA "Ohm – TIO Nexus")
**EDIT**: Saved 8 bytes thanks to [this Jelly answer](https://codegolf.stackexchange.com/a/119018/65298).
Outputs `[true, true]` if square and triangle, `[true, false]` for square, and `[false, true]` for triangle.
Explanation:
```
D8*≥«Æ² Main wire, input integer a
D Duplicate input
8*≥ Multiply duplicate by 8, increment
« Pair
Ʋ Check if perfect square
```
[Answer]
# TI-BASIC, ~~30~~ 23 bytes
-7 for more flexible output requirements.
```
:Prompt X //Get input
:{√(X),.5+√(2X+.5 //Compute the square root of X, and the inverse of the triangular number function: X(X-1)/2
:Ans=int(Ans //Create a list of booleans for whether the values are whole or not, then print
```
Takes input as an iteger.
This returns a list of integers, either `0` or `1`, first for being square, then for being triangular.
[Answer]
# Pyth - 16 bytes (possibly 13)
```
+*2sI@Q2sI@h*8Q2
```
Prints 2 if square, 1 if triangle, 3 if both, 0 if neither
[Try it](https://pyth.herokuapp.com/?code=%2B%2a2sI%40Q2sI%40h%2a8Q2&input=35&test_suite=1&test_suite_input=36%0A15%0A4%0A7&debug=0)
Also, ~~19~~ ~~18~~ 17
```
sI@Q2sI@h*8Q2
```
The first line is 1 if the number is square, 0 if not. The 2nd line is
1 if number is triangle, 0 if not.
[Try it](https://pyth.herokuapp.com/?code=sI%40Q2sI%40h%2a8Q2&input=35&test_suite=1&test_suite_input=36%0A15%0A4%0A7&debug=0)
[Answer]
## JavaScript (ES7), 52 bytes
Returns `1` for square, `2` for triangle, `3` for both (and `0` for none, although irrelevant).
```
f=(n,t=0,s=(n**.5|0)**2==n)=>t<n?f(n-++t,t,s):2*!n|s
```
### Demo
```
f=(n,t=0,s=(n**.5|0)**2==n)=>t<n?f(n-++t,t,s):2*!n|s
console.log(f(7))
console.log(f(15))
console.log(f(25))
console.log(f(36))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
lambda n:[`x**.5%1==0`for x in 8*n+1,n]
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZxWdUKGlpWeqamhra5CQll@kUKGQmadgoZWnbaiTF/sfJJIHEilKzEtP1TDUMTbQtOLiLCjKzCtRyNNJ08jT/A8A "Python 2 – TIO Nexus")
Outputs like `["True", "False"]` for triangle then square. Probably could be shorter if allowed output format is clarified.
[Answer]
## Batch, 120 bytes
```
@set/ar=i=j=k=0
:g
@if %j%==%1 set/ar+=1
@if %k%==%1 set/ar+=2
@set/aj+=i+=1,k=i*i
@if %j% leq %1 goto g
@echo %r%
```
Outputs 1 for triangular numbers, 2 for squares, 3 for both, 0 for neither.
[Answer]
# Python 3, ~~49~~ 42 bytes
```
lambda i:(i**.5%1==0)+2*((1+8*i)**.5%1==0)
```
Returns:
* 1 for Triangle
* 2 for Square
* 3 for Both
[Answer]
## C#, 61 bytes
```
s=n=>System.Math.Sqrt(n)%1==0;n=>(s(n)?1:0)+(s((8*n)+1)?2:0);
```
Could be a lot shorter if there was (or I knew) an alternative to `System.Math.Sqrt`.
Formatted version with test cases:
```
Func<int, bool> s = n => System.Math.Sqrt(n) % 1 == 0;
Func<int, int> f = n => (s(n) ? 1 : 0) + (s((8 * n) + 1) ? 2 : 0);
Console.WriteLine(f(36));
Console.WriteLine(f(15));
Console.WriteLine(f(4));
Console.WriteLine(f(2));
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 25 bytes
```
*M`(^1|1\1)+$
(^1|11\1)+$
```
Takes input in unary, outputs `t` and `s` on separate lines, where `t` and `s` are `0` or `1` indicating whether the shape is a triangle and/or square, respectively.
[Try it online!](https://tio.run/nexus/retina#JczJDYNAFATRe8WBJQwSmv49axDOAFkE4tzHyL69S9VjvY6dZZvb@brWtz469dwXfvx7ThGYTKHS6AyUkFAgo4wKqqihjgaRiLsJwkQmClGJRnRi4ISF76VxxgVX3HDHg5y@ "Retina – TIO Nexus") (Contains an additional `\` to put both outputs on the same line to make the test cases more easily distinguishable.)
### Explanation
Triangular numbers are the sums of consecutive integers starting from one. Square numbers are the ums of consecutive odd integers starting from one. Both of those are fairly easy to match with forward references.
```
*M`(^1|1\1)+$
```
This prints 0 or 1 depending on whether the given regex matches, but it doesn't actually modify the string (the `*` indicates a dry run). The regex either matches the initial one with `^1` or it matches exactly one more `1` than in the previous iteration with `1\1` (the `\1` refers to what `(^1|1\1)` matched last time).
```
(^1|11\1)+$
```
This is basically the same, except that we don't need a dry run and `M` is implicit. To go up by odd integers instead of all integers, we simply add two `1`s on each iteration with `11\1`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~11~~ 10 bytes
```
t:UmGt:Ysm
```
Outputs two values `0` or `1` separated by newline. The first indicates if the input is square, and the second indicates if it is triangular.
[Try it online!](https://tio.run/nexus/matl#@19iFZrrXmIVWZz7/7@xGQA "MATL – TIO Nexus")
### Explanation
Consider input `4` as an example.
```
t % Implicit input. Duplicate
% STACK: 4, 4
: % Range
% STACK: 4, [1 2 3 4]
U % Square, elementwise. This gives square numbers
% STACK: 4, [1 4 9 16]
m % Ismember
% STACK: 1
Gt % Push input again. Duplicate
% STACK: 1, 4, 4
: % Range
% STACK: 1, 4, [1 2 3 4]
Ys % Cumulative sum. This gives triangular numbers
% STACK: 1, 4, [1 3 6 10]
m % Ismember. Implicitly display
% STACK 1, 0
```
[Answer]
# Python 3, ~~72~~ 67 bytes
```
x=input()
k=int((x*2)**.5)
print((x==int(x**.5)**2)+2*(2*x==k*k+k))
```
A bit longer than wanted. This is a full program that takes input from STDIN and outputs to STDOUT. STDERR should be empty as long as there isn't an I/O Exception and the input isn't invalid.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 38 bytes
```
@(x)~mod(x^.5,1)+2*any(x==cumsum(1:x))
```
Outputs `1` for square, `2` for triangular, `3` for both, `0` for neither.
[Try it online!](https://tio.run/nexus/octave#@@@gUaFZl5ufolERp2eqY6ipbaSVmFepUWFrm1yaW1yaq2FoVaGp@T8xr1jD2EzzPwA "Octave – TIO Nexus")
] |
[Question]
[
*Inspired by [this](http://chat.stackexchange.com/transcript/240?m=26561376#26561376) conversation in chat.*
Your goal in this challenge is to emulate a ninja and count how many deaths he has left.
## Specs
You ninja starts out with 9 deaths left. He also gets an integral starting health as an input.
Then, he takes as input a list of events in his life that alter his health. These can be negative, positive, or zero integers.
At any point, if his health reaches at or below zero, he loses a life and his health goes back to the starting health.
Your program should report the number of deaths he has left. If he has zero or less left, you should output `dead` instead.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
## Test Cases
```
3, [] -> 9
100, [-20, 5, -50, 15, -30, -30, 10] -> 8
10, [-10, -10, -10, -10] -> 5
10, [-10, -10, -10, -10, -10, -10, -10, -10, -10] -> dead
0, [] -> dead
0, [1] -> dead
100, [10, -100] -> 9
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~30~~ ~~28~~ 26 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
»0o⁴+
;@ñ\<1S_9«0N“dead”×?
```
[Try it online!](http://jelly.tryitonline.net/#code=wrswb-KBtCsKO0DDsVw8MVNfOcKrME7igJxkZWFk4oCdw5c_&input=&args=Wy0yMCwgNSwgLTUwLCAxNSwgLTMwLCAtMzAsIDEwXQ+MTAw)
### How it works
```
;@ñ\<1S_9«0N“dead”×? Main link. Input: e (events), h (initial health)
;@ Prepend h to e.
ñ\ Reduce the resulting array by the next, dyadic link.
This returns the array of intermediate results.
<1 Check each intermediate value for non-positivity.
S Sum. This calculates the number of event deaths.
_9 Subtract 9 from the result.
«0 Take the minimum of the result and 0. This yields 0 if no
lives are left, the negated amount of lives otherwise.
? Conditional:
× If the product of the minimum and h is non-zero:
N Return the negated minimum.
“dead” Else, return "dead".
»0o⁴+ Dyadic helper link. Arguments: x, y
»0 Take the maximum of x and 0.
This yields x if x > 0 and 0 otherwise.
o⁴ Take the logical OR of the result and the second input (h).
+ Take the sum of the result and y.
```
[Answer]
# Japt, ~~40~~ ~~39~~ 32 bytes
```
U¬©(9-Vf@T=X+(T¬²ªU)<1} l)¬²ª`Ü%
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=VaypKDktVmZAVD1YKyhUrLKqVSk8MX0gbCmssqpg3CU=&input=MTAsIFstMTAsIC0xMCwgLTEwLCAtMTAsIC0xMCwgLTEwLCAtMTAsIC0xMCwgLTEwXQ==)
### How it works
While trying to golf this last night (away from a computer, no less), I ran across an interesting replacement for `>0`: `¬`. On numbers, this takes the square root, which returns `NaN` for negative numbers. `NaN` is falsy, so this returns exactly the same truthily/falsily as `>0`.
Extending this trick a little further, we can reset T to U iff it's `>=0` in only five bytes: `T¬²ªU`. How does this work? Let's take a look:
```
T ¬ ² ªU
sqrt square if falsy, set to U (JS's || operator)
4 2 4 4
7 ~2.646 7 7
0 0 0 U
-4 NaN NaN U
-7 NaN NaN U
```
As you can see, `T¬²` returns `NaN` if `T` is negative; otherwise, it returns `T`. Since `NaN` and `0` are both falsy, this provides an easy way to reset the ninja's health with `ªU`. This trick is also used to return the ninja's lives left if that number is positive, or `"dead"` if negative.
Putting this all together:
```
// Implicit: U = starting health, V = events, T = 0
U© // If U is positive,
Vf@ } // Filter out the items X in V that return truthily from this function:
T=X+ // Set T to X plus
(T¬²ªU) // If T is positive, T; otherwise, U.
// This keeps a running total of the ninja's health, resetting upon death.
<1 // Return (T < 1).
9- l) // Take the length of the resulting array and subtract from 9.
// This returns the number of lives the ninja has left.
¬² // If the result is negative, set it to NaN.
ª`Ü% // If the result of EITHER of the two parts above is falsy, return "dead".
// (`Ü%` is "dead" compressed.)
// Otherwise, return the result of the middle part (lives left).
// Implicit: output last expression
```
If the input is guaranteed to be non-negative, or even positive, we can golf of 1 or 4 bytes:
```
U©(9-Vf@T=X+(T¬²ªU)<1} l)¬²ª`Ü% // U is non-negative
9-Vf@T=X+(T¬²ªU)<1} l)¬²ª`Ü% // U is positive
```
[Answer]
## JavaScript ES6, ~~62 60~~ 58 bytes
*Saved 4 bytes thanks to @ETHproductions*
```
(a,b,d=9,l=a)=>b.map(i=>l=l+i<1?d--&&a:l+i,a)|d<1?"dead":d
```
[Try it online](http://vihanserver.tk/p/esfiddle/?code=f%3D%20(a%2Cb%2Cd%3D9)%3D%3E(b.reduce((l%2Ci)%3D%3El%2Bi%3C1%3F(d--%2Ca)%3Al%2Bi%2Ca)%2Cd%3C1%3F%22dead%22%3Ad)%3B%0A%0Af(%20100%2C%20%5B-20%2C%205%2C%20-50%2C%2015%2C%20-30%2C%20-30%2C%2010%5D%20)) (All browsers work)
## Explanation
```
(a,b, // a = 1st input, b = 2nd input
d=9)=> // Lives counter
(b.reduce((l,i)=> // Loop through all the health changes
l+i<1 // If (health + health change) < 1
?(d--,a) // Decrease life, reset health
:l+i // Return new health
,a) // Sets starting health to `a`
,d<1? // Lives is less than 1
"dead":d); // Output "dead" otherwise lives left
```
[Answer]
# CJam, 35 bytes
```
q~_@{+_1<{W$}&}/](\,_A<@*A@-"dead"?
```
[Try it online!](http://cjam.tryitonline.net/#code=cX5fQHsrXzE8e1ckfSZ9L10oXCxfQTxAKkFALSJkZWFkIj8&input=Wy0yMCA1IC01MCAxNSAtMzAgLTMwIDEwXSAxMDA)
[Answer]
## Haskell, ~~81~~ ~~77~~ 75 bytes
```
p l i h a|l<1="dead"|i<1=p(l-1)h h a|[]<-a=show l|x:y<-a=p l(i+x)h y
p 10 0
```
Usage example: `p 10 0 100 [-20, 5, -50, 15, -30, -30, 10]` -> `"8"`
[Answer]
# Pyth, 32
```
u+?>GZG&=hZQH+E0Q?&Q<Z9-9Z"dead
```
Note that there is a leading space. This probably isn't the best approach, but it was the first thing that came to mind. It reduces over input by adding the values to the ninja's health, and incrementing a counter and resetting the health when it drops below zero. We add a zero to the end of the list to count if the last change kills the ninja, and then just do some checking to see if the ninja is dead. The zero starting health case is hard coded.
[Test Suite](https://pyth.herokuapp.com/?code=%20u%2B%3F%3EGZG%26%3DhZQH%2BE0Q%3F%26Q%3CZ9-9Z%22dead&input=3%0A%5B%5D&test_suite=1&test_suite_input=3%0A%5B%5D%0A100%0A%5B-20%2C%205%2C%20-50%2C%2015%2C%20-30%2C%20-30%2C%2010%5D%0A10%0A%5B-10%2C%20-10%2C%20-10%2C%20-10%5D%0A10%0A%5B-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%5D%0A0%0A%5B%5D%0A0%0A%5B1%5D%0A100%0A%5B10%2C%20-100%5D&debug=0&input_size=2)
[Answer]
# MATL, 32
```
9yi"@+t0>~?x1-y]]g*wxt0>~?x'dead'
```
## Explanation
```
9 # push 9
y # duplicate 2nd value to top (there is none -> get it from input first)
i # get input and push it
```
The stack now looks like this (for input `100, [-20, 5, -50, 15, -30, -30, 10]`):
```
100 9 100 [-20, 5, -50, 15, -30, -30, 10]
reload deaths health
value left
```
Pop the array and loop
```
" ] # loop
@+ # add to health
t0>~? ] # if health is zero or less
x1-y # delete health counter, decrement life counter, reload health
```
If the health is zero, set death counter to zero. Special case handling for `initial health = 0`.
```
g # health to bool
* # multiply with death counter
```
Delete the reload value from stack
```
wx
```
If the death counter is zero or less, delete it and print 'dead' instead.
```
t0>~?x'dead'
```
[Answer]
# [TeaScript](http://github.com/vihanb/teascript), ~~36 34~~ 31 bytes
```
yR#l+i<1?e─·x:l+i,x);e≥0?e:D`Ü%
```
Similar to my JavaScript answer. the last 4 characters are the decompression of the string "dead".
TeaScript's online interpreter doesn't support array input so you're going to need to open the console, and run this by typing:
```
TeaScript( `yR#l+i<1?(e─,x):l+i,x);─e>0?e:D\`Ü%` ,[
10, [-10, -10, -10, -10]
],{},TEASCRIPT_PROPS);
```
### Explanation
```
// Implicit: x = 1st input, y = 2nd input
yR# // Reduce over 2nd input
l+i<1? // If pending health is less then 1
(e─,x): // then, decrease life counter, reset health
l+i // else, modify health
,x); // Set starting health
─e>0? // Ninja is alive?
e: // Output lives left
D`Ü% // Decompress and output "dead"
```
[Answer]
## Python 2.7, 82 66 55 106 bytes
*Thanks to @RikerW for -16 bytes.:(*
*Thanks to @Maltysen for -11 bytes. :(*
```
i=input;h=[i()]*9;d=i()
if 0==h[0]:print'dead';exit()
for x in d:
h[0]+=x
if h[0]<=0:h=h[1:]
y=len(h)
print['dead',y][y!=0]
```
First type health, then enter, then events in list form.
[Answer]
## C# 207
```
class P{static void Main(string[]a){int h=int.Parse(a[0]),H=h,l=9,i=1;if(a.Length!=1){for(;i<a.Length;i++){H+=int.Parse(a[i]);if(H<=0){l--;H=h;}}}System.Console.Write(h==0?"dead":l<=0?"dead":l.ToString());}}
```
Takes the input through argument stream. The first argument is the amount of health and all the rest is the list of events.
Readable / ungolfed version
```
class Program
{
static void Main(string[]a)
{
int health = int.Parse(a[0]);
int Health = health;
int lives = 9;
if(a.Length!=1)
{
for (int i = 1;i < a.Length;i++)
{
Health += int.Parse(a[i]);
if (Health <= 0)
{
lives--;
Health = health;
}
}
}
System.Console.Write(health == 0 ? "dead" : lives <= 0 ? "dead" : lives.ToString());
}
}
```
Examples:
* CSharp.exe 3 => 9
* CSharp.exe 100 -20 5 -50 15 -30 -30 10 => 8
(Psst.) CSharp.exe is name used as an example. You have to call like this in reality: [program\_name.exe] arguments, without the square parentheses.
] |
[Question]
[
The challenge is to find the maximum number you can get from a list of integer using basic arithmetic operators (addition, substraction, multiplication, unary negation)
**Input**
A list of integers
**Output**
The maximum result **using every integer** in the intput.
The input order doesn't matter, result should be the same.
You do not need to output the full operation, just the result.
**Examples**
```
Input : 3 0 1
Output : 4 (3 + 1 + 0)
Input : 3 1 1 2 2
Output : 27 ((2+1)*(2+1)*3))
Input : -1 5 0 6
Output : 36 (6 * (5 - (-1)) +0)
Input : -10 -10 -10
Output : 1000 -((-10) * (-10) * (-10))
Input : 1 1 1 1 1
Output : 6 ((1+1+1)*(1+1))
```
**Rules**
* Shortest code wins
* [Standard "loopholes"](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply
* You may only use + \* - operators (addition, multiplication, substraction, unary negation)
* The code should work as long as the result can be stored on a 32 bit Integer.
* Any overflow behaviour is up to you.
I hope this is clear enough, this is my first Code Golf challenge suggestion.
[Answer]
# C - 224 bytes - Running time O(n)
```
o=0,w=0,n[55],t,*m=n,*p=n;main(r){for(;scanf("%d",++p);t<3?--p,w+=t/2,o+=t&1:t<*m|m==n?m=p:9)t=*p=abs(*p);t=o<w?o:w;o-=t;w-=t;t+=o/3;for(o%3?o%3-2?t?t--,w+=2:++*m:w++:9;t--;)r*=3;for(r<<=w;--p>n;)r*=*p;printf("%d",r>1?r:o);}
```
It was amusing to see only exponential-time solutions for a linear-time problem, but I suppose it was the logical way to proceed since there were no bonus points for actually having an algorithm, which is an anagram of logarithm.
After converting negative numbers to positive and discarding zeroes, clearly we are mostly interested in multiplication. We want to maximize the logarithm of the final number.
log(a + b) < log(a) + log(b) except when a = 1 or b = 1, so ones are the only case in which we are interested in adding anything together. In general it is better to add a 1 to a smaller number, because that causes a bigger increase in logarithm, i.e. a larger percentage increase, than adding 1 to a big number.
There are four possible scenarios, ordered most to least preferable, for utilizing ones:
1. Adding one to a 2 gives +log .405 [log(3) - log(2)]
2. Combining ones into threes gives +log .366 per one [log(3) / 3]
3. Making a 2 out of ones gives +log .347 per one [log(2) / 2]
4. Adding one to a number 3 or higher gives +log .288 or less [log(4) - log(3)]
The program keeps track of the number of ones, the number of twos, and the minimum number greater than 2, and goes down the list of the most to least preferable ways of using the ones. Finally, it multiplies all the remaining numbers.
[Answer]
# Haskell, 126 characters
this is just brute-forcing, with the exception of ignoring the sign of the input and ignoring subtraction and unary negation.
```
import Data.List
f[x]=abs x::Int
f l=maximum$subsequences l\\[[],l]>>= \p->[f p+f(l\\p),f p*f(l\\p)]
main=interact$show.f.read
```
this code is extremely slow. the code recursively calculates f on each subsequence of the input **four times** (except for [] and the input itself). but hey, it's code golf.
[Answer]
# SWI-Prolog - 250
Oh boy, I spent way too long on this.
```
o(A,B,A+B).
o(A,B,A-B).
o(A,B,A*B).
t([],0).
t([A,B|T],D):-t(T,Q),o(A,B,C),o(C,Q,D).
t([A|T],C):-t(T,Q),o(A,Q,C).
a(A):-t(A,B),n(C),B>C,retract(n(C)),assert(n(B)).
m(A):-assert(n(0)),\+p(A),n(R),R2 is R,write(R2).
p(A):-permutation([0|A],B),a(B),0=1.
```
Called from command line (e.g.):
```
> swipl -s filename.pl -g "m([1, 1, 1, 1, 1])" -t halt
6
```
*(For no particlar reason, I found it awesome that my golfed function names spell "tomato pot.")*
**Ungolfed version:**
```
% Possible operations
operation(Left, Right, Left + Right).
operation(Left, Right, Left - Right).
operation(Left, Right, Left * Right).
% Possible ways to transform
transform([], 0).
transform([A, B|T], D) :- transform(T, Q), operation(A, B, C), operation(C, Q, D).
transform([A|T], C) :- transform(T, Q), operation(A, Q, C).
% Throw the given array through every possible transformation and update the max
all_transforms(A) :- transform(A, B), n(C), B>C, retract(n(C)), assert(n(B)).
% Find all the permutations and transformations, then fail and continue execution.
prog(A) :- assert(n(0)), !, permutation([0|A], B), all_transforms(B), fail.
% End the program
finished :- n(R), write(R), nl, R2 is R, write(R2), nl.
% Run the program
main(A) :- ignore(prog(A)), finished.
```
**Explanation:**
1. Take in an array as an argument.
2. Get all permutations of the array.
3. Find some arrangement of operators to add to the array. (This is done via dynamic programming, seeing whether it's better if we combine the first two elements or not.)
4. Check this against our current max value. If it's better, replace it.
5. Tell the program we failed so that it keeps checking, but then negate that (using `ignore` or `\+`) to let the predicate overall return `true` and continue.
6. We're given a string of predicates, instead of a number, so assign it using `is` and then write it.
[Answer]
# Scala, 134
```
print(args.map(Math abs _.toInt)./:(Seq(Array(0)))((l,a)=>l.map(a+:_)++l.flatMap(_.permutations.map{r=>r(0)+=a;r}))map(_.product)max)
```
Ungolfed & commented:
```
print(
args
.map(Math abs _.toInt) // to int, ignoring -
.foldLeft(Seq(Array(0))){ (list,num) => // build up a list of sums of numbers
list.map(num+:_) ++ // either add the new number to the list
list.flatMap(_.permutations.map{ copy =>
copy(0)+=num // or add it to one of the elements
copy
})
}
.map(_.product) // take the maximum of the the products-of-sums
.max
)
```
A slightly different approach, from realizing that the biggest answer can always be expressed as a product of sums.
So close, but a bunch of library stupidity (permutations returns an Iterator instead of a Seq, horrible type inference on empty sequences, Array.update returning Unit) did me in.
[Answer]
## Python 278 (O(n!))
```
from itertools import*
def f(n):
f,n,m=lambda n:[(n,)]+[(x,)+y for x in range(1,n)for y in f(n-x)],map(abs,map(int,n.split())),0
for p,j in product(permutations(n),f(len(n))):
i=iter(p)
m=max(m,reduce(lambda e,p:e*p,(sum(zip(*zip([0]*e,i))[1])for e in j)))
return m
```
## Explanation
1. Unary Negate should be judiciously used to convert all negative numbers to positive
2. Find all possible permutations of the numbers
3. Using Integer partition to find all power-sets of a given permutation
4. Find the product of the sums
5. Return the maximum of the product of the sums
[Answer]
# Haskell - 295 290 265 246 203 189 182 bytes
---
Finally works! Also now it is a brute force rather than a dynamic solution.
---
Thanks to proudhaskeller for some of the golfing tips.
This is probably **not** a fully golfed solution because I actually suck at golfing, but it is the best I can come up with (and it looks complicated, so I got that going for me):
```
import Data.List
main=interact$show.g.read
g x=maximum[product$a#b|a<-sequence$replicate(length x-1)[0,1],b<-permutations x]
(a:b)#(c:d:e)|a>0=b#(c+d:e)|0<1=c:b#(d:e)
_#x=x
```
New test cases:
```
[1,1,1,2,2]
12
[1,1,3,3,3]
54
[1,1,1,1,1,1,1,1,5,3]
270
```
Solution explanation:
The `main` function just gets an input and runs `g` with it.
`g` takes the input and returns the maximum of all possible combinations of sums and list orders.
`#` is the function which calculates the sums in a list like this:
```
a = [1,0,0,1]
b = [1,1,1,2,2]
a#b = [2,1,4]
```
[Answer]
## GolfScript (52 chars)
```
~]0-{abs}%.1-.1,or@,@,-,-1%{!\$.0=3<@+{()}1if+}/{*}*
```
[Online demo](http://golfscript.apphb.com/?c=IyMgVGVzdGluZyBmcmFtZXdvcmsKOyczIDAgMQozIDEgMSAyIDIKLTEgNSAwIDYKLTEwIC0xMCAtMTAKMSAxIDEgMSAxCjEKMiduL3sKIyMgCgp%2BXTAte2Fic30lLjEtLjEsb3JALEAsLSwtMSV7IVwkLjA9MzxAK3soKX0xaWYrfS97Kn0qCgojIyBUZXN0aW5nIGZyYW1ld29yawpwfS8KIyM%3D)
[feersum's analysis](https://codegolf.stackexchange.com/a/37086/194) is pretty good but it can be taken further if the goal is golfing rather than efficiency. In pseudo-code:
```
filter zeros from input and replace negatives with their absolute value
filter ones to get A[]
count the ones removed to get C
while (C > 0) {
sort A
if (A[0] < 3 || C == 1) A[0]++
else A.append(1)
C--
}
fold a multiply over A
```
] |
[Question]
[
A [Kaprekar number](http://mathworld.wolfram.com/KaprekarNumber.html) is an n-digit number *k* that, when the first *n* or *n-1* digits of k^2 are added to the second *n* the digits of N^2, the result is N.
Examples:
```
9^2 = 81. 8+1 = 9.
45^2 = 2025. 20+25 = 45.
297^2 = 88,209. 88+209 = 297
```
The Kaprekar sequence begins at 1.
Write a program that calculates and outputs the first *n* Kaprekar numbers, with *n* being in the range, but not limited to the range, of 1 to 100. Each Kaprekar number must be separated with whitespace and nothing else.
More Kaprekar numbers can be found [here](http://oeis.org/A053816) to check your program against, but this resource MAY NOT be used in any way to help with the calculation - in other words, no hard-coding, reading from this source, or using it in any other exploitive way - all the numbers must be generated by your program.
Shortest code wins.
[Answer]
## Perl - 63 bytes
```
#!perl -l
map{1while$l=length++$_,$_**2=~/.{$l}$/,$`+$&^$_;print}($_)x<>
```
Counting the shebang as one byte. Input is taken from `stdin`.
This has an acceptable runtime for *n ≤ 50*, after that it gets a bit slow.
Sample usage:
```
$ echo 20 | perl kaprekar.pl
1
9
45
55
99
297
703
999
2223
2728
4950
5050
7272
7777
9999
17344
22222
77778
82656
95121
```
[Answer]
# C, 109 106
```
long long i=1;x=10,n;main(){scanf("%d",&n);for(;n;x*=x<=++i?10:1)(i-i*i/x-i*i%x)||printf("%lld ",i,n--);}
```
* with `n` up to 17 it would be ok to remove the `long long`,
* The exceeding printf parameter is abused:)
* Why it is not possible to use empty statement in the ternary operator? the two `1` are silly...
* Thank to Josh for aditional 3 characters...
[Answer]
# Mathematica ~~144~~ 154
```
k@m_:=((x=m^2)-(w=FromDigits[Take[IntegerDigits@x,y=-IntegerLength@m]]))*10^y+w==m;
g@n_:=(s={};i=0;While[Length@s<n,If[k@i,s=Append[s,i]];i++];s)
```
Test
```
g[14]
```
>
> 0
>
> 1
>
> 9
>
> 45
>
> 55
>
> 99
>
> 297
>
> 703
>
> 999
>
> 2223
>
> 2728
>
> 4950
>
> 5050
>
> 7272
>
>
>
[Answer]
## Javascript 96
```
for(i=0,n=prompt(s='');n;i++){t=''+i*i;if(t.substr(0,l=t.length/2)==i-t.substr(l))n--,s+=i+' '}s
```
Output :
```
0 1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778 82656 95121 99999 142857 148149 181819 187110 208495 318682 329967 351352 356643 390313 461539 466830 499500 500500 533170 538461 609687 643357 648648 670033 681318 791505 812890 818181 851851 857143 961038 994708 999999
```
[Answer]
# python - 98
I used some nice python slicing to shave a few characters off.
```
i=n=0
while n<20:
i+=1;s=str(i**2);l=-len(str(i))
if int("0"+s[:l])+int(s[l:])==i:print(i);n+=1
```
[Answer]
C# - 255 Characters.
```
int x=100;decimal k=0;while(x>0){k++;decimal d=k*k;string s=d.ToString("n").Replace(",","").Split('.')[0];int g=k.ToString().Length;int h=s.Length;if(k==d||(h!=g&&long.Parse(s.Substring(h-g))+long.Parse(s.Substring(0,h-g))==k)){Console.Write(k+" ");x--;}}
```
x is the number of Kaprekar numbers you wish the code to find. This has been tested in the range of 1 to 100 but should support a lot more than this. 100 numbers took two and a quarter hours to return although the first 50 only took about 1 second - things slowed down gradually after that.
Output:
```
1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778
82656 95121 99999 142857 148149 181819 187110 208495 318682 329967 351352 356643
390313 461539 466830 499500 500500 533170 538461 609687 643357 648648 670033
681318 791505 812890 818181 851851 857143 961038 994708 999999 4444444 4927941
5072059 5555556 9372385 9999999 11111112 13641364 16590564 19273023 19773073
24752475 25252525 30884184 36363636 38883889 44363341 44525548 49995000 50005000
55474452 55636659 61116111 63636364 69115816 74747475 75247525 80226927 80726977
83409436 86358636 88888888 91838088 94520547 99999999 234567901 332999667
432432432 567567568 667000333 765432099 999999999 1111111111 1776299581 2020202020
3846956652 3888938889 4090859091 4132841328 4756047561
```
Laid out this code is as follows;
```
int x = 100;
decimal k = 0;
while (x > 0)
{
k++;
decimal d = k * k;
string s = d.ToString("n").Replace(",", "").Split('.')[0];
int g = k.ToString().Length;
int h = s.Length;
if (k == d || (h != g && long.Parse(s.Substring(h - g)) + long.Parse(s.Substring(0, h - g)) == k) )
{
Console.Write(k + " "); x--;
}
}
```
I'd love to know if this can be shortened further.
[Answer]
# C, ~~90~~ ~~76~~ 75 bytes
```
long long d,r=1;k(n){for(;++d/r?r*=10:--n;d-d*d/r-d*d%r||printf("%d ",d));}
```
[Answer]
# Python 2.7, 144 (including newlines)
```
def c(c):
l="1";i=2;u=1
while u<c:
r=str(i**2);w=len(r)
if w>1:
if i==int(r[:w/2])+int(r[w/2:]):
l+=" "+str(i);u+=1
i+=1
print l
```
Output for c = 10:
```
1 9 45 55 99 297 703 999 2223 2728
```
Output for u = 20:
```
1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778 82656 95121
```
[Answer]
### R, 99 characters
```
k=n=0;N=scan();while(n<N){k=k+1;j=k^2;i=10^ceiling(nchar(j)/2);if(k==j%/%i+j%%i){cat(k," ");n=n+1}}
```
With `i` being half the number of digits of `k^2` rounded up, the evaluation of wether k is a Kaprekar number is performed here by adding the quotient and the remainder of the integer division of `k^2` by `10^i` (the quotient being the left half of the digits rounded down and the remainder the right half rounded up).
[Answer]
# bash+sed, 75 characters
Bash does integer-only arithmetic and represents numbers as decimal strings; these attributes are helpful for golfing this challenge. Also undeclared/unassigned variables are assumed to have a value of 0 when doing arithmetic.
```
for((;s=++i*i,l=${#s}/2,1;));{
((${s:0:l}+10#${s:l}-i))||echo $i
}|sed $1q
```
It irked me to put the `10#` in there, but something like this is necessary if the second half of the split starts with a `0`. When doing arithmetic, [bash](/questions/tagged/bash "show questions tagged 'bash'") treats such numbers as octal, unless the base is explicitly stated.
```
$ ./kaprekar.sh 10
1
9
45
55
99
297
703
999
2223
2728
$
```
[Answer]
## Python 3.3 - 117 characters
```
n=int(input())
p=1
while n>0:
v=str(p**2)
l=len(v)
if p==int(v[l//2:])+int('0'+v[:l//2]):
print(p)
n-=1
p+=1
```
---
Each level of indentation, and each newline except the final one, all count for 1 character. I think that is fair for Python code. The script expects the user to input the number of Kaprekar numbers to compute.
[Answer]
# J - 64
Kinda ugly, but still. It checks all numbers up to one million then takes `n` of them, so it works only for n<=50.
```
n{.}.I.(]=+/&;&:(10&#.&.>)&(<.@-:@#({.;}.)])&(10&#.inv@*:))i.1e6
```
`n` is where to put the input
] |
[Question]
[
## Background
You have again, again been given the task of calculating the number of landmines in a field. But this time, the field is foggy.
You must calculate the landmine score given a list/string of numbers, the landmine number, and the land distance (all are numbers).
The landmine number tells you where landmines are.
For each digit in the landscape (first number), if the digits left and right add to the landmine number, add the digit in focus to the landmine score.
Note: The very first and last numbers cannot have landmines because they have no numbers to the left and right of them respectively.
Because the field is foggy however, we need to clear the fog and expand the landscape. This is done by repeatedly adding the last two digits of the given landscape and appending it to the end. If the result of the addition has two digits, append the ones digit. This is done until the length of the landscape is equal to the land distance.
## Your Task
* Sample Input: The landscape, the landmine number, and the land distance. It is given that the land distance is greater than or equal to the length of the number landscape. It is also given that the landscape contains at least two digits.
* Output: Return the landmine score.
**Explained Examples**
Note: Expansions are grouped in 5 for demonstration.
```
Input => Output
178 9 11 => 16
When expanded, the landscape is:
17853 81909 9
Of these:
178 => 1+8 = 9, so add 7
099 => 0+9 = 9, so add 9
7+9 = 16
```
```
Input => Output
012 7 21 => 16
Expanding:
01235 83145 94370 77415 6
Of these:
235, 2+5 = 7, add 3
314, 3+4 = 7, add 1
077, 0+7 = 7, add 7
156, 1+6 = 7, add 5
3+1+7+5 = 16
```
```
Input => Output
10 10 10 => 0
Expanding:
10112 35831
Of these, there are no landmines.
```
```
Input => Output
090909 0 10 => 18
Expanding:
09090 99875
Of these:
090, 0+0=0, add 9
090, 0+0=0, add 9
9+9=18
```
**Test Cases**
```
Input => Output
178 9 11 => 16
012 7 21 => 16
10 10 10 => 0
090909 0 10 => 18
00 0 99 => 0
00 99 99 => 0
91900 18 42 => 1
123121 10 15 => 18
1111111111 2 10 => 8
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins.
...
**Landmine Number Series**
* [Previous, LN II](https://codegolf.stackexchange.com/questions/262553/landmine-number-ii)
* [Next, LN IV](https://codegolf.stackexchange.com/questions/262746/landmine-number-iv)
* [All LN Challenges](https://docs.google.com/document/d/1XU7-136yvfoxCWwd-ZV76Jjtcxll-si7vMDhPHBKFlk/edit?usp=sharing)
[Answer]
# [Python 3.8+](https://docs.python.org/3/), ~~91~~ ~~85~~ ~~84~~ ~~82~~ ~~80~~ 78 bytes
```
f=lambda s,n,d:d-1and f((s:=s+[sum(s[-2:])%10])[1:],n,d-1)+s[1]*(s[0]+s[2]==n)
```
[Try it online!](https://tio.run/##bY3BCoJAEIbvPsVcQjdH2DFIE/bQcyxzMFYp0G1xtkNPb1qQBF3@Gfi@nz884/XuD3WY5rk3QzteXAuCHl3jCmq9gz7LpDGSW3mMmdiibFjtSLOy1PAqFqRyscT7hWpe3pKN8WpuRbopLn1LCBVgzQgnBCIFxgAdk03QSFguuEIo/@K1uCW/D@mPWSc/S5pX9MU6CdPNxyw9DwPETqJAWH2XqvkF "Python 3 – Try It Online")
Takes a list of `int` digits, the landmine number and then the land number
## Explanation
Recursive implementation where `f` is called `d-1` times. In every call, the digit `sum(s[-2:])%10` is appended to `s`. This may add extra digits to the landscape, but the function will terminate before reaching them so this is not a problem. Additionally, the recursive call removes the first digit of the landscape (`(...)[1:]`) so that extra parameters are avoided, and so that `s[1]*(s[0]+s[2]==n)` can use single digit numbers to index the list, saving bytes.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 96 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 12 bytes
```
‡+tdḞẎ3lƛy$∑⁰=*
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJkfj0iLCIiLCLigKErdGThuJ7huo4zbMabeSTiiJHigbA9KiIsIiIsIlsxLDcsOF0sMTEsOSA9PiAxNlxuWzAsMSwyXSwyMSw3ID0+IDE2XG5bMSwwXSwxMCwxMCA9PiAwXG5bMCw5LDAsOSwwLDldLDEwLDAgPT4gMThcblswLDBdLDk5LDAgPT4gMFxuWzAsMF0sOTksOTkgPT4gMFxuWzksMSw5LDAsMF0sNDIsMTggPT4gMVxuWzEsMiwzLDEsMiwxXSwxNSwxMCA9PiAxOFxuWzEsMSwxLDEsMSwxLDEsMSwxLDFdLDEwLDIgPT4gOCJd)
I do love a good opportunity to use a generator. Takes landmine digits as a list of digits, land area number, then landmine number.
## Explained
```
‡+tdḞẎ3lƛy$∑⁰=*­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁤​‎‏​⁢⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣⁢​‎‏​⁢⁠⁡‌­
‡ dḞ # ‎⁡A generator where each term:
t # ‎⁢ is the tail of
+ # ‎⁣ the sum of the last 2 terms
# ‎⁤The generator takes the landmine digits as the initial list of terms and works from there.
Ẏ # ‎⁢⁡Take the first land-area digits of the generator
3lƛ # ‎⁢⁢And to each overlapping window of size 3:
y$ # ‎⁢⁣ Uninterleave and swap so that the first and last item of the window are on the top of the stack in a list
⁰= # ‎⁢⁤ Check whether the sum of that list is equal to the landmine number
* # ‎⁣⁡ And multiply the middle of the window by that. If the sum was equal, this will return the number as-is. Otherwise, it will return 0.
# ‎⁣⁢The d flag flattens the result of the map before summing the list.
üíé Created with the help of Luminespire at https://vyxal.github.io/Luminespire
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
NθNηFη≔⁺ζI﹪Σ…⮌ζ²χζIΣΦ✂ζ¹⊖η¹⁼θΣ⁺§ζκ§ζ⁺²κ
```
[Try it online!](https://tio.run/##TU7NDoIwDL7zFDuWBBOH8eSJoCYcNEafAEcV4thgP0Z5@dkRDzTpz9f2@1rR1kboWoZQqcG7s@/vaGBMd8kSt4Qf2jAqWGFt91Rwkd7ClLGytg5OuvFSw833UH6FxLLVA1zxjcYiTGnG8pQCX6cxTSR2MZ1yMHMj6dhJR2dushMYRXnG9igM9qgcNnSVWuSH0dfSwpixSJo/KFylGvxE0os2FnAe57H9t10IfJ3wbcLzDc95WL3lDw "Charcoal – Try It Online") Link is to verbose version of code. Takes the landmine number and field length as the first two inputs. Explanation:
```
NθNη
```
Input the landmine number and field length.
```
Fη≔⁺ζI﹪Σ…⮌ζ²χζ
```
Extend the field so it's at least as long as the required length.
```
IΣΦ✂ζ¹⊖η¹⁼θΣ⁺§ζκ§ζ⁺²κ
```
Slice out the part that can have landmines, then filter out those digits whose neighbours have the wrong sum, then take the digital sum of the result.
[Answer]
# [Mathematica](https://www.wolfram.com/wolframscript/), 164 bytes
Golfed version. [Try it online!](https://tio.run/##dc9JS8QwFADgu7/iHXXyBpK4Nc5E9CIII3gQPIRHSW1rA12GsZ6G/vaapkwLg4WQhXxvq2xbZJVt3Zft@9yUMVYxpjE96Lcm/S0zc7S6xETzDj8L59@7rP5uC2Npm@Lzfp/V6UdjLHptdvan9R/sNZ/Vo0BrzFoSIScUnIg2L83BOC3RbUf2ZNExhj7MU7cWRGy4MH/RusKE6eFJQ2hC/fvB1a3JzVEg3CNEHYJCEB5vAC5XIO5gdXUxKe7/EGQXsFxSnvgJQQyanww/T@TrzHsXjlmL6JzzkSi1mHAQSi0TFZofC4b@IoQbOVU8H0EiXI/j@v00zu1CgyLI/1c3pphmC5H9Hw)
```
f[l_,m_,d_]:=Module[{a=l,b=0},While[Length[a]<d,AppendTo[a,Mod[Last[a]+If[Length[a]>1,a[[-2]],0],10]]];For[i=2,i<Length@a,i++,If[a[[i-1]]+a[[i+1]]==m,b+=a[[i]]]];b]
```
Ungolfed version. [Try it online!](https://tio.run/##jVFNa4NAEL37K96xjRtQ@xWbWuilULCl0EIPyxIkbpuFqCGaU/C329nZxLQlDYqM7s57M2/eFFmz0EXWmHnWdWlW5oUp9du8Wmu5pFM9z1Z6lpq6EbCZl00xE8jpPFO4TeA9V/lmqeXWgpGg5wjUtghdBa3wgI@FIViqy69mwZUV7riOTQJPn79z9wgFOGOfh9VKl/l7xUkB6inTrG52WJ@7SjmOlBIIA4r/MXfAUCnFEBvVlMJjtZaGxEYChoT91EI3vr8TQzJdCYMxqErf29CfPSfJ3qZevvPBT/bIv6057ynP817Xpmzk7yVsyYcbgUkrENNw1GMKnI0QXmN0fpwRCGte1DIxGsIgOG2JrHP2OXxwqgFpOcSWPwdmODlFDRw8jgc1sug4HgaPeXAniueZCFxGvapT49PeL5xtFPdWXA0YKGTW8bd15XpfuErXfQM)
```
LandmineScore[landscape_List, mineNum_, dist_] :=
Module[{land = landscape, score = 0},
While[Length[land] < dist,
If[Length[land] > 1,
AppendTo[land, Mod[Last[land] + land[[-2]], 10]],
AppendTo[land, land[[-1]]]
]
];
For[i = 2, i < Length[land], i++,
If[land[[i - 1]] + land[[i + 1]] == mineNum,
score += land[[i]]
]
];
score
]
Print[LandmineScore[{1, 7, 8}, 9, 11]]; (* 16 *)
Print[LandmineScore[{0, 1, 2}, 7, 21]]; (* 16 *)
Print[LandmineScore[{1, 0}, 10, 10]]; (* 0 *)
Print[LandmineScore[{0, 9, 0, 9, 0, 9}, 0, 10]]; (* 18 *)
Print[LandmineScore[{0, 0}, 0, 99]]; (* 0 *)
Print[LandmineScore[{0, 0}, 99, 99]]; (* 0 *)
Print[LandmineScore[{9, 1, 9, 0, 0}, 18, 42]]; (* 1 *)
Print[LandmineScore[{1, 2, 3, 1, 2, 1}, 10, 15]]; (* 18 *)
Print[LandmineScore[{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 2, 10]]; (* 8 *)
```
[Answer]
# Excel, 172 bytes
Named variable `z` defined as:
```
=LAMBDA(x,n,
IF(n=LEN(x),x,z(x,n-1)&MOD(SUM(0+MID(z(x,n-1),n-{1,2},1)),10))
)
```
Formula within the worksheet:
```
=LET(
a,z(A1,C1),
b,SEQUENCE(LEN(a)-2),
SUM(IF(MMULT(0+MID(a,b+{0,2},1),{1;1})=B1,0+MID(a,b+1,1)))
)
```
Landscape, landmine number and land distance in `A1`, `B1` and `C1` respectively.
Fails in some cases (e.g. `00|99|99`), perhaps due to IEEE 754 precision on the return from `MOD`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
λ£₂+θ}Ц¦+IQ0šÏO
```
Inputs in the order *landscape, land distance, landmine number*, where *landscape* is a list of digits.
[Try it online](https://tio.run/##ATAAz/9vc2FiaWX//867wqPigoIrzrh9w5DCpsKmK0lRMMWhw49P//9bMSw3LDhdCjExCjk) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WGZSg5JOYl1KcnFiQaqWgZG@vZK2QAxTIzcxLVcgrzU1KLUIWVkjJLC5JzEuGqlV41DYJyKhMCC3@f273ocWPmpq0z@2oPTzh0LJDy7QjAg2OLjzc7/9f5390dLShjrmORayOoaGOZayOQnS0gY6hjlGsjhFQHMw31DEAygJFDaDSljpQDBaGiQJpS0s0niXEREugiSANQEETIx1DC6ixRjrGIKt0DIHmmMKMN9TBgGBrjGJjAQ).
**Explanation:**
```
λ # Start a recursive environment,
£ # to generate the first second (implicit) input amount of items,
# Starting with a(0),a(1),...,a(l) at the first (implicit) input-list
# And where every following a(n) is calculated as:
# (implicitly push a(n-1))
‚ÇÇ # Push a(n-2)
+ # Add them together
θ # Pop and leave just its last digit
} # Close the recursive environment,
# (we now have the expanded landscape as a list of digits)
Ð # Triplicate the resulting list
¦¦ # Remove the first two items of the top copy
+ # Add the values at the same positions together (ignoring the last two)
IQ # Check which values are equal to the third input
0š # Prepend a 0 to these checks
Ï # Only keep the values at the truthy indices
O # Sum them together
# (after which the result is output implicitly)
```
[Answer]
# Q, 61 bytes
```
{while[z>(#:)x;x,:sum[-2#x]mod 10];sum x(&:)y=next[x]+prev x}
```
**ungolfed**:
```
{ [x; y; z]
while[ z>count x;
x,: (sum -2#x) mod 10
];
: sum x where y=next[x] + prev[x]
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 28 bytes
```
sm*@d1qQs%2d.:<u+Ges>2GKEEK3
```
[Try it online!](https://tio.run/##K6gsyfj/vzhXyyHFsDCwWNUoRc/KplTbPbXYzsjd29XV2/j/f0suQ0OuaEMdcx2LWAA "Pyth – Try It Online")
Takes three inputs: landmine number, length, and starting sequence as a list.
### Explanation
```
KE # K = second input
u E # repeat lambda G K times, with third input as the starting value
+G # append to G
e # the last digit of
s # the sum of
>2G # the last two elements of G
< K # first K elements of the last value of G
.: 3 # all length 3 sublists
m # map this to lambda d
*@d1 # middle element of d times
qQs%2d # Q == sum of first and last elements of d
s # sum all terms
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 127 bytes
```
lambda s,n,d:(s:=(g:=lambda w:w if d==len(w)else g(w+[(w[-1]+w[-2])%10]))(s))and sum(z*(x+y==n)for x,y,z in zip(s,s[2:],s[1:]))
```
[Try it online!](https://tio.run/##bVHtbsIwDPyfp7CQpibQTXVgo62UvUjoj9APFqmEqi4q8PIsYYVJbEl08p3PTqx05@Hr4JZp118btbm2Zr@tDFDs4irnlCu@y9UkjvkItoFKqbZ2fBR1SzXs@LjQfNSvWCw8ykK8YFIIwUkI4yqg455f5vy0OCvlRHPo4RSf4wtYBxfbcYpJy7zwiLmvupaGalKz2QzXKWSACOoT8IMlKGEN8k4xgZ/jacKSLGy4C5iyJPEsy6b0LbyzDDMvYAoreTMzlEv0jUO/96kcHwvk1DT1b3qjrrUDjzYuEswored703HrhthOKaH97AWEMW0Y8TZOwbZKexf/dWEh/pjKZ5P8x3Q4DvTsW/3jYw@hN25X8/BjRoicgSGq@wEabrQt4m2A0oNQKvT2EWNdHy6I6FiWNVEkrt8 "Python 3.8 (pre-release) – Try It Online")
So I have Python 3.10.0 installed on my computer (and it works) but it doesn't work on TIO's "Python 3"? IDK at least it works on this version.
So there are two parts to this function, chained by the `and` operator. The first part expands the landscape to the proper length using a recursive lambda function. The second part uses `zip` to loop over every pair of elements and checks to see if they sum to the landmine number. And finally, `sum` is used to add up all the landmine scores found to get the answer.
Defining the second lambda function is really costly so I wouldn't be surprised is someone else found a better way to generate the new landscape.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 127 bytes
```
\G\d|\d+
$*_,
+`^((_*,)*(_*),(_*,))(¶.*¶(?<-2>_)*(?(2)^)___)
$1$3$4$5
+`^(.*)_{10}
$1
M!`(?<=(_*),)(_*)(?=,(_*))(?=,.+¶\1\3,)
_
```
[Try it online!](https://tio.run/##PYwxDsIwDEV3n8JIQYrTUsVpqzYSpSMTE2vUFKkMLAyIDbhWD9CLlSRI2Jb99K3/H9fn7X5Zt/I84uqObnq7KQOhfA7ZOEjpVU4qbMoTklzmQi2z7Pc7c/Dh1UtDA3nvCQSLUlSiTs5CkX@x/gQVTpsxGLoUQ3HLvot5lKDIltmxK3MCv67ctGiRGTQbbNAwsMY0oG1s/LEO19p4rY1g2QbmFisDbEo2nFw18L/QBOkL "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on spaces for convenience. Explanation:
```
\G\d|\d+
$*_,
```
Convert to unary.
```
+`^((_*,)*(_*),(_*,))(¶.*¶(?<-2>_)*(?(2)^)___)
$1$3$4$5
```
Extend the field until it reaches the distance.
```
+`^(.*)_{10}
$1
```
Keep only the ones digits of the field.
```
M!`(?<=(_*),)(_*)(?=,(_*))(?=,.+¶\1\3,)
```
Match only the landmines.
```
_
```
Take their sum.
[Answer]
# Swift 5.9, 113 bytes
```
while l.count<d{l+=[(l[l.count-2]+l.last!)%10]};return(1...l.count-2).reduce(0){$0+(l[$1-1]+l[$1+1]==n ?l[$1]:0)}
```
Where the function header is:
```
func landmineScore(landscape l: inout [Int], mineNumber n: Int, distance d: Int) -> Int
```
Ungolfed version (plus header):
```
func landmineScore(landscape: inout [Int], mineNumber: Int, distance: Int) -> Int {
while landscape.count < distance {
landscape += [(landscape[landscape.count - 2] + landscape.last!) % 10]
}
return (1...(landscape.count - 2)).reduce(0) { result, index in
result + (landscape[index - 1] + landscape[index + 1] == mineNumber ? landscape[index] : 0)
}
}
```
I chose to make `landscape` an `inout` because that prevents me from having to declare `var m=l` at the beginning, saving 8 bytes total. I also used `Array.reduce` instead of a `for`-`in` loop or `Array.forEach`, saving a fair amount of bytes (since it also allowed me to eliminate using a separate `score` variable).
Using `l.count` instead of `l.endIndex` saved 3 bytes per use (both values are always the same).
The space before the `?` is needed to prevent Swift from trying to optional-chain.
[Answer]
# JavaScript (ES13), 74 bytes
Expects `(number)(landscape)(distance)`, where `landscape` is given as a string.
```
n=>s=>g=k=>k>2&&g(--k,s+=-(-s.at(-1)-s.at(-2))%10)+s[k-1]*!(n-s[k-2]-s[k])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PU9LTsMwEN3nFEMlGpvEwTafJiCHFSzYdtlmEbVOiBIciN0FQtwACSGxA6QKwR24BAfothfgCjhpiscavzfz5mn8-qnquVx-ZOJrYTISri6ViLWIc1GKuIz5cJgjQkpfe4IgooPUIMJwDzjGu4xiT09KwpK9HaRIC3nSPgnuHX8aebsoGokGmR7goJHp_KKo5PhOzRDFganHpilUjnCgb6rCoMFUWVlWN-fp7App04CI4d4BqKSBCWgflA-lD_XCQAICrCK4To3V7k_n3n6OT3ttI7VtZ8hTGGmMvLLrzGql60oGVZ2jVuGBa8ODjgjR2Z6B-_v9tH57sdmFE3DX748utuMP_aeWq2c2CiECxtrt2LFDGYcR8C1lFDbXUurQqA3YFljoUGpZFPXtDm5ZxCJbYCEc8k7sMH7ArHHrd9SPs_8DvDcNN5v9AQ)
### Commented
```
n => // n = landmine number
s => // s = landscape string
g = k => // k = land distance
k > 2 && // if k is greater than 2:
g( // do a recursive call:
--k, // decrement k
s += -( // append to s:
-s.at(-1) - // the sum of the last digit in s
s.at(-2) // and the penultimate digit
) % 10 // modulo 10
) // end of recursive call
// the code below is executed once all recursive
// calls have been initiated, which means that s
// is now guaranteed to be long enough
+ s[k - 1] * !( // add s[k - 1] to the final result if:
n // n is equal to
- s[k - 2] // the sum of s[k - 2]
- s[k] // and s[k]
) //
```
---
# JavaScript (ES6), 64 bytes
Same input format as above. Due to limited IEEE 754 precision, this version cannot see very far in the fog...
```
n=>s=>g=k=>--k>1&&g(k,s+=(+s+s/10)%10|0)+s[k-1]*!(n-s[k-2]-s[k])
```
[Try it online!](https://tio.run/##PY5LTsMwEED3OcVQicbG@dhBQAtyWMEFumyziBInhAS72C4SAm6AxIZluQfn6QU4QnBCy8xovm9Gc58/5abQzdqGUpWir3gveWp4WvOWp2HYpmw6rVEbGMIRMcTEjOJjRl8pJmbZhiw7OUIyHNIkG0KGey0eN40WaFKZCY60yMvbphOLZ1kgiiOrFlY3skY4MuuusWiykg6rlL7JiztkrAaewosH0AkLSzAByADaANTGQgYcHBE95Nax8aokcY2v9qwWxo0rRCRGBiPSjpNCSaM6EXWqRgNBwHdKYCw4H89eg//z/bHbfjrvwyX4u693H7v1N9yzixnMgbHhK3buMQp/5krq0fmgcGiwmceSU5awkTk7tP4Fkj04@wU "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~94~~ 88 bytes
```
f(*a,m,n,l,*s){for(;*s=m<n;)a[m++]=(a[m-2]+a[m-1])%10;for(;--m>1;)*s+=*a+a++[2]-l?0:*a;}
```
[Try it online!](https://tio.run/##dZTbjpswEIbv9ymsSKk4GJVDSEhZthdVnyLhgiVmGxWcFWbVqFFevemYMcZOUwRMPN/M@PfYpA7qtuJvt1vjeBXtKKct9YR7aU69k3ui6J557la7zvfLwgEbxKUvTVS6yyjMx7Ag6F6i3PWEX3iVX/n@Li6D9mv4xavy6@3IB9JVR@645PJE4JKOgYkh3JWkIJeIkg0l2TXXIEIQUgIsNkCsM0LDm@jwLQD9NiJWOsLMSx961@jdjpNjKRNvtISYkgQVwtuIyHTEf@9rbjWiwwxx/M1OjTO2xv2sRh4OKTFoZNPIprFNY5smNk1surLpyqapTVObrm26tunGphubZjbN3LsOtXpT4KhEIe4KbI/cpQw98V0KV9sgNyjCkEilyGcldy2VvjnPGxMFJo59p3ge0cRoEjQrNCmaNZoNmszQws7vrB7YQcmBQPmEKByXEeFgyqpPXAyk/lH1HrxZ/ZP1mLzYn7/H@/P2GzzpghJznCxUNnyRxJETH/mBnSEtzNXP56njk6S56dqTE98fo6ePdW4NlML2jLzMTUy4ovwR9cjrR9NARF217al2OFXzAnNdu1CnCnX/FJoXphYFC@pGva6OmTXLS866O8rWDWByi733UKpxFssDNFIFGlKulqhWiWofrl0YGh1ZSv2NfhJ3a2NQRh@H@0qTILI8yDt4GX@IPQd9LSUcvheqj4MoCjbJRak9Gz56Dn15ut7@1E1bvYlb8Osv "C (clang) – Try It Online")
*Saved 6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
[Answer]
# [Scala](https://www.scala-lang.org/), 147 bytes
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=jZLNSgMxEMfBo08xCEKGzepm_eq2bsGjUE_FU-khdrc1kmZlEysqfYoevehBLz6RPo2zSaUIggvhP_n6_Wcy5PndTqSWBx-jndhU97I2O-OvrVV1dVNOHFxIZeBpG6AopzCnBZP1zHbhrK7lw2joamVmY-zCpVEOcn8T4JZ2nTZMS1PMlSmHk6ou2UBZxwSHEw4d5JBxEAIRYH8fxPF_XEK3OaTo8bQ9R1BCkGj4pKE8l7RIR_VtFH3wDk3aTgs-CUyWhaxt0zZYlm24NljmmxNK9a_tcDhMPd9U26JHKYeD0GHSn34dtX2t8OjfA4PnunON1XKbZCE1_HLqAgPvNjo3bsyB1AvmfVJA-lxvd24adz5XTPM5L-jgaSFrGOS610SbJ737a6Wppj2rHsvTAgfdKGdqut7oC6SZltZFgz1F_9XPcVckUGpbQjjD3rSqmTqNQYCrIKBxio0NU7HAiEIkMM_naKOcFtizy1Da6zq-vIT4DQ)
```
(l,m,d)=>{var L=l;var s=0;while(L.size<d)L:+=(if(L.size>1)(L.last+L.init.last)%10 else L.last);for(i<- 1 to L.size-2)if(L(i-1)+L(i+1)==m)s+=L(i);s}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=jVTLTsJAFF244yvOxqQTBmjBB23AxKWJujGuCIsKUxhTBtIOGmP4Ejds9KP8Bj_CO7ctj8TEJs20995zzn10Zj6-8kmcxr3t9nNtk1b_--Rn-fSsJhZ3sTZ4bwBTlWBBhhdnszzCdZbFb6MHm2kzG4sIj0ZbDBkJrMhrU-OlsZkutFEPk2WmvFudWy-QuJToC4lQIgiEADodBBf_8XxCS3QF07v1eUTyiRQ4vu9YzPNrpKP69qvgFyu4tP0afL_ghGGRtW5aRwvDPa8OLeThFKVyt32Jsy7zXbU1ZtSV6BUTprWa13ndbgOm_v2IQrOcnJPaNMrtdKzkLNqFKxXBiY5ujB1LuPj9ehGBTIkpBfhT8LrbcC9xxmrk2MnsArmTp4jfYNfrXKcKnK6dKjOzcwxYWJRiOJRC1ISnk2P8FbVVeeLcosnQtqYzwA6BU-oYKs0VdijB4puiiGSZkSwGLQRYG6tTHOq3nH5VTJWc4OwvkpHVdNZwWI1oz0DZcnNYQkUZ2ByWwBj-HZvi0Jdnv7oDfgE)
```
object Main {
def main(args: Array[String]): Unit = {
println(landmineScore(List(1, 7, 8), 9, 11)) // 16
println(landmineScore(List(0, 1, 2), 7, 21)) // 16
println(landmineScore(List(1, 0), 10, 10)) // 0
println(landmineScore(List(0, 9, 0, 9, 0, 9), 0, 10)) // 18
println(landmineScore(List(0, 0), 0, 99)) // 0
println(landmineScore(List(0, 0), 99, 99)) // 0
println(landmineScore(List(9, 1, 9, 0, 0), 18, 42)) // 1
println(landmineScore(List(1, 2, 3, 1, 2, 1), 10, 15)) // 18
println(landmineScore(List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), 2, 10)) // 8
}
def landmineScore(landscape: List[Int], mineNum: Int, dist: Int): Int = {
var land = landscape
var score = 0
while (land.length < dist) {
land = land :+ (if (land.length > 1) (land.last + land.init.last) % 10 else land.last)
}
for (i <- 1 until land.length - 1) {
if (land(i - 1) + land(i + 1) == mineNum) {
score += land(i)
}
}
score
}
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 110 bytes
```
/ (\d+) /;$_=$`;$l=$';$n=$&;/(.)(.)$/,$_.=($1+$2)%10while y///c<$l;/(.)(.)(.)(?{$s+=$2if$1+$3==$n})^/g;$_=$s|0
```
[Try it online!](https://tio.run/##PU7RbsIwDHzvV/jBGy0ddRxgNAqBH0EUiTGolJVqQUII@HVCWlrse/CdzyfXu3879X8XdNoRmEU2JNKeIF79pAmQxsLgRqM1ONBYGfzUFGdJANIXFpmJkVOUyQeL86G0O7gQ0XaOtrc1WF7RpQZl@duYx8ZgdU/WtG/D3U14z7McFDCHB4C/I8ESZiB7ygJeCFREQjUNvcB5JERgSnXrduyZYhUEzmEiW3PEcswhuMmbduf8LpBdaP441qfyWDk/svUT "Perl 5 – Try It Online")
] |
[Question]
[
This is the companion question for [Code Crosswords](https://codegolf.stackexchange.com/q/40304/26997). Robber answers go here.
See [Where should we put robbers?](https://codegolf.meta.stackexchange.com/questions/2334/where-should-we-put-robbers) for meta-info.
[Answer]
# Solution to [es1024's C puzzle](https://codegolf.stackexchange.com/a/40316/30688)

I had to fudge a bit on 7-Down by invoking undefined behavior. *es1024 has indicated that this use of UB was the intended solution.* It will work on most people's computers though. I came up with various expressions achieving the desired result such as `-1 << 30`, `3 << 30`, `6 << 29`, and `~(~0U/4)` but all of them made it impossible for me to get 5-Across. So I used the Intel architecture-specific property that only the least significant 5 bits are used to determine the size of a left shift.
Note that it needs to be `~_` and not `~1` so that the amount to shift by is not a compile-time constant.
I tested the expressions with the following code:
```
#define T(X) _ = c; _ = X; printf("%d\n", _);
z[4] = {9};
int main(c)
{
int _;
T("01"[0])
T(-8)
T(-2)
T(11<-328111)
T(+2+71)
T(9+0)
T(0**z)
T(5;)
T(0<-000)
T(2+~3)
T(!91)
T(!_)
T(2**z)
T('_T;')
T("11"?5*9:2)
T(15<<9)
T(0+22)
T(-211*0-97;)
T(-17*0)
T(3+0<<~_)
T(8+000)
T(+0)
T(42)
T(+!z)
T(~_)
}
```
[Answer]
## [professorfish, CJam, 41 darks](https://codegolf.stackexchange.com/a/40323/8478)
*(This solution actually requires several spaces, so it's not the one professorfish was looking for.)*
```
#K###I#'32
#HDJ*s\ ##
2##2#`#`#-
4Zm*`##L#3
m##6##]`'
f####e#`#'
`#0#'d1+eu
## #!####9
## '{;'"'m
C5(#}####q
```
That was great fun. Note that the `#` beneath the `6` is actually code and not a dark cell. Let's go through this:
### Across
Hint 2: `[[4 3]]`. This was one of the trickier ones, because I really got stuck on trying `4Z]]`` or similar. Turns out you can use the Cartesian product `m*` on stuff that isn't an array, and it will make an array for you. So here it is:
```
4Zm*`
```
Hint 4: `24717`. By the time I got to this, the `H`, `J`, `s` and trailing space were already in place. The `H` gave away that I could probably just reuse the `17` and do `\` at the end. The `J` pushes a `19` and `247 == 13 * 19`, so:
```
HDJ*s\
```
Hint 7: `32`. There are a bunch of ways to do this: `Y5#`, `3 2`, `ZY`, `YZ\`, `4(2`, `2)2`, `'32`. I went with the last one, because starting with a character seemed promising for 7-down, and that turned out to be right.
Hint 8: `E`. I already had the `'d` when I got there, so it was between choosing `'d1+eu`, `'deu1+` or a variant where I used `)` and a space instead of `1+` (for the non-CJam people, this taking the `d` character and increment and upper-casing it, in either order). However, the `u` in the final column looked useful for A-down. So I picked the first of those. In the end, `'d) eu` would have worked, too.
Hint 9: `""`. Well, this had to be "empty string, get string representation, push a space". But also needed the ` for string representation in 7-down, and a space in A-down seemed useful, too, so I chose
```
]`'
```
Note that `]` might also have been one of `LMOQR`.
Hint B: `"m`. I just really had to fit this one in with the rest, but there were few characters that mattered. I already had the `{` and the `m`. So instead of using a block, I turned `{` into a character, discarded it, and then pushed the two required characters:
```
'{;'"'m
```
Hint D: `124`. I solved this one together with C-down, which was easiest with a decrement at the end. So I push a 12, a 5, and decrement the latter:
```
C5(
```
### Down
Hint 1: `[2 2 2 3]`. That looked too suspiciously like a prime factorisation for it not to be one. :)
```
24mf`
```
Hint 3: `3010936384`. Factoring this showed that it's actually 386. The only question was how to get the `38` in compliance with 2-across. In the end I needed a `*` in the third place, so doubling `19` it was:
```
J2*6#
```
Hint 5: `2017`. Two characters for such a large number? Just use built-in two-digit variables:
```
KH
```
Hint 6: `"18"`. I think there's only a single way to do this in 3 characters. Use the built-in 18, convert it to a string, and then to its string representation.
```
Is`
```
Hint 7: `' "\"\""`. Probably the hardest part of the puzzle. In particular, I needed to get the `"\"\""` in only three characters. The trick was to get the string representation of the empty string twice. That led to:
```
' `L``+
```
THe `+` isn't necessary, but was needed by 8-across.
Hint 8: `!{}`. The block needed to go in the code, so that left only two characters for `!`, which meant using another literal:
```
'!{}
```
Hint A: `-3u3`. With the `u` in place from 8-across, I started to put `-3` and `3` in the corners where no other hint cared about them. But then I needed an `m` at the bottom. I think there are multiple ways to get a `3` with `_m_`, but the simplest was taking the square root of 9:
```
-3 'u9mq
```
Hint C: `-1`. I already had the decrement there, so I just put a `0` where no one else cared about:
```
0 (
```
Hint E: `Stack: ""`. Well that was the simplest one. Just call the debugger:
```
ed
```
[Answer]
[COTO, Javascript ES4, 37 Darks](https://codegolf.stackexchange.com/a/40309/16869)
```
__________
|{}=51###6#|
|a##.#I-9<4|
|:##-##"#<#|
|5+Math.PI#|
|}##+##.#+#|
|["9"+0][0]|
|'##p##"###|
|a+-a#a=-10|
|'##c##=###|
|]##"\x48I"|
¯¯¯¯¯¯¯¯¯¯
```
* 6 across is `5+Math.PI` or `Math.PI+5`; but the latter would leave 'M' and 'h' crossing over into other expressions, seemed unlikely.
* A across had to be a string; with 4 in the middle it looked like an escape, the only way you have room for that is with `"\x48I"`.
* 2 down now ends in a string, so probably is "pac" appended to a number; we'll come back to that.
* 8 ac is now `xxxa`, evaluating to zero, so -a+a? a+-a? 3+-a? `a+-a` looked best since it gave me what looked like a char in a string in 1dn.
* 1 down contained :5, which could only be legal grammar in `{x:5}xxa'x`. Since the value returned is 5, it must be pulling it out of the object, so `{x:5}['a']`, which means the final missing character is also a: `{a:5}['a']`
* 1 across now has { at the start. I guessed this was a red herring assignment, tried `t={}=51`, and it worked. Did not know that!
* 2 down now has `5xxax"pac"`=>"2pac". This has to be `5-a+"pac"`, somehow, so the second char has to be '.' for the floating point literal.
* 7 ac is now `[xx"xxxx]`, returning "90". So this has to be an array literal with the value pulled out; there's only room for one value so we have `[xx"xx][0]`. There's not room for two strings in there, but either `"9"+0` or `9+"0"` fit.
* 3 dn; 3072 is 3\*1024; the power of 2 is suspicious, and I already had 'I' in there blocking other ways of getting large numbers (like 1eX). So, guessed bitshift; `6<<I` turned out to be the answer, leaving +0 to add on to the end.
* 4 ac now contained a comparison operator; and the second char had to be a valid unary operator (to fit in after both 't=' and 'I'). I guessed '-', and there's several possible solutions left (`I-I<4`, `I-6<4`, etc)
* 5 dn now contained `-x..]xxx4`. The ".." threw me - there's only a couple of ways that can be legal syntax and is why I asked if ES4 is what was intended - was this some odd feature of that abandoned spec? But then I saw that this was a red herring; `-""` is NaN, so `-"..]"xx4` must be what's there - a comparison to NaN, returning false; '==' will do, but need to look at the last answer for confirmation...
* 9ac had several possible solutions, but the restriction on characters that would be allowed for 5dn made me think this was yet another red herring assignment; something `=-10`. To be honest I also looked at the earlier version of 9dn, and realised that must be something `=top` (to get a Window back). The variable assigned to could be a or I, it doesn't matter.
Tricky puzzle!
[Answer]
# [grc's Python puzzle](https://codegolf.stackexchange.com/a/40307/30688)

For all the lengthy floating-point expressions, I made a C++ program to generate Python mathematical expressions by force and evaluates them. It assumes all numbers are floating-point and only supports operators +, -, \*, /, //, \*\*, and ~. I used it to get every clue longer than 5 characters except `a**9*27%b` and the hash. With 6 or less blanks it finishes within a couple of seconds, while there is a bit of a wait for 7.
[Answer]
# Solution to [COTO's MATLAB puzzle](https://codegolf.stackexchange.com/a/40358/30688)
I guess I golfed this one pretty well, as there are 14 spaces.

This test script:
```
g=4;
o=magic(3);
D=@disp;
D(max([ 2]));
D( i^3);
D(o^0);
D(6 -7+eye );
D((i));
D(.1 ^5* g );
D(~2);
D(diag(~o) );
D(asin (1)*i);
D((93+7) +~g);
D( 10e15);
D(2*ones (2));
D(02 ^ 9 );
D(-i );
D(~o);
```
produces the following output:
```
2
0 - 1.0000i
1 0 0
0 1 0
0 0 1
0
0 + 1.0000i
4.0000e-05
0
0
0
0
0 + 1.5708i
100
1.0000e+16
2 2
2 2
512
0 - 1.0000i
0 0 0
0 0 0
0 0 0
```
] |
[Question]
[
In this challenge, you must take two numbers (separated by a space) as input and output an ASCII right triangle, made up of `x`s.
The first number will be the width and height of the triangle you should output. The second number will be which corner the right angle will be in. The corners are numbered 1 to 4, starting in the top left and going in English reading order:
```
1 2
3 4
```
For example (inputs and their respective triangle outputs):
```
INPUT | 3 1 | 3 2 | 3 3 | 3 4
------+-----+-----+-----+----
OUT- | xxx | xxx | x | x
PUT | xx | xx | xx | xx
| x | x | xxx | xxx
```
Your program's output must match these examples exactly for their respective inputs.
The input will always be valid: the first number will be an integer ≥1, and the second number will be 1, 2, 3, or 4.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code (in character count) wins.
[Answer]
## APL (30)
```
{' x'[1+(⍎⍵⌷'⌽+⍉⊖')≤/¨⍳2⍴⍺]}/⎕
```
Explanation:
* `{`...`}/⎕`: reduce given function over the input (so if the input has 2 numbers, just calls the function with those two numbers, `⍺` being the left number and `⍵` the right number)
* `≤/¨⍳2⍴⍺`: Make an `⍺`-by-`⍺` coordinate matrix and set those positions where the X coordinate is not greater than the Y coordinate, giving a bitfield.
* `(⍎⍵⌷'⌽+⍉⊖')`: select a transformation function given by `⍵` to put the triangle right-side-up.
* `' x'[1+`...`]`: add one to the bitfield, and use the result as an index into the string `' x'`, so putting space for 0 and `x` for 1.
[Answer]
## Ruby, ~~116~~ ~~115~~ ~~109~~ 96
I shall start with my own solution.
```
i=gets.split
s=i[0].to_i
(i[1]<?3?s.downto(1):1..s).map{|x|t=?x*x
puts /2|4/=~i[1]?t.rjust(s):t}
```
I just know that I'll get beat by a 30 character GolfScript solution almost instantly :P
Thanks to minitech for shaving off 19 characters (wow)!
[Answer]
## GolfScript (34 33 chars)
```
~\:^,{)' x'^*$>^<0(2$?%}%\(2&(%n*
```
It's a shame that the corners aren't numbered in rotation, because that would allow a more elegant approach of building one array and then rotating it `n` times:
```
~\:^,{)' x'^*$>^<}%{-1%zip}@)*n*
```
[Answer]
## C# - 195
```
using System;class P{static void Main(string[]a){int G=int.Parse(
a[0]),O=int.Parse(a[1]),L=O<3?0:G+1,F=O<3?-G:1;G=O%2>0?-G:G;for(;
F<L;F++)Console.Write("{0,"+G+"}\n","".PadRight(F<0?-F:F,'x'));}}
```
Formatted:
```
using System;
class P
{
static void Main(string[] a)
{
int G = int.Parse(a[0]),
O = int.Parse(a[1]),
L = O < 3 ? 0 : G + 1,
F = O < 3 ? -G : 1;
G = O % 2 > 0 ? -G : G;
for(; F < L; F++)
Console.Write("{0," + G + "}\n", "".PadRight(F < 0 ? -F : F, 'x'));
}
}
```

[Answer]
# Golfscript, ~~39 36~~ 35 characters
```
~\:y,{' '*'x'y*+y<0~2$?%}%-1@2>?%n*
```
live demo: <http://golfscript.apphb.com/?c=OyczIDInCn5cOnkseycgJyoneCd5Kit5PC0xIDIkPyV9JS0xQDI%2BPyVuKgo%3D>
too bad it's not 30 characters as [requested](https://codegolf.stackexchange.com/a/12378/7209)
[Answer]
# Mathematica 122 (104?)
```
g@s_ := ({w, p} = ToExpression@StringSplit@s;
Array[If[Switch[p, 1, # <= (w + 1 - #2), 2, # <= #2, 3, # >= #2, 4, # > (w - #2)],
"X", ""] &, {w, w}]) // Grid
```
---
```
GraphicsGrid[{{g["12 1"], g["12 3"]}}]
```

---
Under a liberal interpretation of "output", the following (104 chars) will work.
```
f@s_ := ({w, p} = ToExpression@StringSplit@s;
Graphics[Polygon@Delete[{{w, 0}, {0, 0}, {w, w}, {0, w}}, p], Axes -> True])
f["50 4"]
```

---
If input in the form of a list were permitted, the following (75 chars) would suffice:
```
f[{w_, p_}] :=
Graphics[Polygon@Delete[{{w, 0}, {0, 0}, {w, w}, {0, w}}, p], Axes -> True]
```
---
[Answer]
## J, 59 55 42 38 37 36 characters
If it's permitted to have the input at the end of the program:
```
(|:@|.@]^:([:|[+_7*2<[)[:[\'x'$~])~/
```
If not (for an extra 3 characters):
```
t=.(|:@|.@]^:([:|[+_7*2<[)[:[\'x'$~])~/
```
Usage:
```
(|:@|.@]^:([:|[+_7*2<[)[:[\'x'$~])~/3 4
x
xx
xxx
```
or
```
t 3 4
x
xx
xxx
```
I think this could be a fair bit shorter since most of the characters are brackets and caps to keep it in an implicit style.
**Edit**
Using a gerund and the agenda verb has chopped off a few characters, but there's still too many caps in there for my liking.
**Edit 2**
That's a bit more like it. Dumping the agenda for a list of how many rotations are required gets rid of most of the extra brackets and a few caps.
**Edit 3**
Got rid of the last extraneous cap and a pair of brackets in the process. Need to find a cheaper way of encoding the number of rotations required.
**Edit 4**
Use prefix instead of suffix to chop off a character. Enables a different way of creating the list which doesn't save any characters. Bugger.
**Edit 5**
Using a formula to chop off another character. Still feel this bit could be shorter.
[Answer]
Python 106 Characters
```
w,d=map(int,raw_input().split())
for e in range(1,w+1)[::d/3*2-1]:print('%'+'-+'[d%2]+str(w)+'s')%('*'*e)
```
[Answer]
## Python 3, 91
Based on Abhijit's answer.
Modified the creation of the output string to avoid the sum of strings and the ugly `1`s in the `range`.
Python 3 gets rid of the `raw_` in `raw_input`, but makes necessary to use `//` for integer divison and to add parantheses for `print`, so that saves only one character.
```
w,d=map(int,input().split())
for e in range(w)[::d//3*2-1]:print('%*s'%(w-d%2*2*w,'x'*-~e))
```
[Answer]
# [Kitten](https://github.com/evincarofautumn/kitten), 140
```
def s{><replicate}
getLine{' 'neChar}span{readInt fromSome}toBoth->{w n}
w 0 if(n 2>){><}..
{<>w>< -{'X's}{' 's}both if(n 2%0=){><}cat say}each
```
Ungolfed:
```
getLine
{' ' neChar} span
{readInt fromSome} toBoth
->{ width corner }
width 0
if (corner 2 >):
swap
..
{ ->index
'X' index replicate
' ' (width index -) replicate
if (corner 2 % 0 =):
swap
cat say
} each
```
Evidence that I need to implement overloading and flesh out the standard library.
] |
[Question]
[
Write a program that displays a moving ASCII ball `*` inside a rectangle (20 by 10 chars including border). The ball must not cross the rectangle, e.g. bump off when it hits the wall. The scene must be cleared and redrawn every 0.1 seconds and the ball must move 1 char in x and y direction every frame. The shortest program written in any language wins.
**Example output (frame 1)**
```
+------------------+
|* |
| |
| |
| |
| |
| |
| |
| |
+------------------+
```
**Example output (frame 2)**
```
+------------------+
| |
| * |
| |
| |
| |
| |
| |
| |
+------------------+
```
**Example output (frame 8)**
```
+------------------+
| |
| |
| |
| |
| |
| |
| |
| * |
+------------------+
```
**Example output (frame 9)**
```
+------------------+
| |
| |
| |
| |
| |
| |
| * |
| |
+------------------+
```
[Answer]
## Ruby 1.9, 115 characters
The movement logic is quite similar to [Danko](https://codegolf.stackexchange.com/users/1308/danko-durbic)'s [answer](https://codegolf.stackexchange.com/a/5658/84).
This version has been tested on Linux only.
```
p=0
loop{u=(?|+?\s*18+"|
")*8
u[165-21*(7-p%14).abs-(17-p%34).abs]=?*
p+=1
puts"\e[2J",r=?++?-*18+?+,u,r
sleep 0.1}
```
[Answer]
## Powershell, 144 characters
Based on Joey's [excellent answer](https://codegolf.stackexchange.com/a/5655/1308), using the fact that the ball coordinates are a function of the frame index (i), so if you have something like `x=n-abs(n-(i mod (2*n)))`, x will go from 0 to n, back to 0, and so on...
```
for(){cls
($l="+$('-'*18)+")
7..0|%{$j=$_
"|$(-join(17..0|%{'* '[$j-[Math]::abs(7-$i%14)-or$_-[Math]::abs(17-$i%34)]}))|"}
$l;$i++;sleep -m 100}
```
[Answer]
## Python 2, 234
I'm sure this can be golfed more, but I gotta go so here's what I have sofar. will work more on it later
```
import os,time
a,b,c,d,e,n='+- |*\n'
w=d+c*18+d+n
s=a+b*18+a+n
x,y=0,0
g,h=17,7
j,k=1,1
while 1:
if 0>x or x>g:j*=-1;x+=j
if 0>y or y>h:k*=-1;y+=k
os.system('cls');print s+w*y+d+c*x+e+c*(g-x)+d+n+w*(h-y)+s;x+=j;y+=k;time.sleep(0.1)
```
note: works on Windows command console. Other operating systems may use a different command than `cls` to clear the screen, such as `clear`
[Answer]
## Ruby (179 174 147)
**EDIT** got rid of some more chars:
```
l=?++?-*18+?++?\n
c=?|+?\s*18+?|+?\n
p=22
u=v=1
loop{f=l+c*8+l
f[p]=?*
puts"\e[2J"+f
p+=(u=f[p+u]==' '?u:-u)+21*(v=f[p+21*v]==' '?v:-v)
sleep 0.1}
```
**EDIT** shaved off some chars, now 174:
```
l="+#{'-'*18}+\n";f=l+"|#{' '*18}|\n"*8+l;x=y=u=v=1
loop{f[21*y+x]='*';$><<"\e[2J\e[f"+f;f[21*y+x]=' '
u=f[21*y+x+u]==' '?u:-u;v=f[21*(y+v)+x]==' '?v:-v
x+=u;y+=v;sleep 0.1}
```
Ungolfed:
```
l="+#{'-'*18}+\n" # top and bottom lines
f=l+"|#{' '*18}|\n"*8+l # complete box as string
x=y=u=v=1 # x,y position; u,v next move
loop { #
f[21*y+x]='*' # add ball to box
$> << "\e[2J\e[f"+f # clear screen and print box with ball
f[21*y+x]=' ' # remove ball from box
u=f[21*y+x+u]==' '?u:-u # next move in x direction
v=f[21*(y+v)+x]==' '?v:-v # next move in y direction
x+=u # perform move
y+=v # --"--
sleep 0.1 # .zZZ...
} #
```
[Answer]
## JavaScript (275 283)
```
s=Array(19).join(' ');n='\n';z=Array(9).join('|'+s+'|'+n).split(n,8);
x=y=0;a=b=1;t='+'+s.replace(/ /g,'-')+'+';
setInterval(function(){u=z[y];z[y]=u.replace(eval('/( {'+x+'}) /'),'$1*');
$('#o').text(t+n+z.join('\n')+n+t);z[y]=u;x+=a;y+=b;if(!x|x==17)a=-a;if(!y|y==7)b=-b},100)
```
Demo: <http://jsfiddle.net/eKcfu/2/>
I wrote this up pretty quickly so I'm sure there's still quite a bit of room for improvement. Suggestions are welcome :)
**Edit 1**: Remove unnecessary separate function call, embed directly in `setInterval`.
[Answer]
## Haskell, 212 characters
```
import System
main=mapM_ f$s 19`zip`s 9
s n=[2..n]++[n-1,n-2..3]++s n
f p=r"clear">>putStr(unlines[[" |-+*"!!(19#i+2*(9#j)+4*e((i,j)==p))|i<-[1..20]]|j<-[1..10]])>>r"sleep 0.1"
b#n=e$n<2||n>b
e=fromEnum
r=system
```
Uses a more functional approach for calculating the coordinates, by making the infinite sequence for each coordinate separately and then zipping them together (lines 2 and 3). The rest is drawing code.
[Answer]
### PowerShell, 184 ~~185~~ ~~215~~
Only semi-golfed as my brain isn't working properly when I'm sick ...
A few nice tricks in it, though.
```
for($a=$b=1){cls
($l="+$('-'*18)+")
0..7|%{$j=$_
"|$(-join(0..17|%{'* '[$j-$y-or$_-$x]}))|"}
$l
$x+=$a;$y+=$b
if(-1,18-eq$x){$a*=-1;$x+=2*$a}if(-1,8-eq$y){$b*=-1;$y+=2*$b}sleep -m 100}
```
[Edit]: Looping over the field is much shorter.
[Answer]
## QBasic (QB64), ~~178~~ 173 bytes
```
a$="+------------------+
?a$
for c=1to 8
?"| |
next
?a$
do
x=19-abs(17-(i mod 34))
y=9-abs(7-(i mod 14))
locate y,x
?"*
_delay .1
locate y,x
?" "
i=i+1
loop
```
-5 bytes thanks to DLosc
[Answer]
## Perl 5, 141 characters
```
print"\e[H\e[2J",$h="+"."-"x18 ."+
",(map{"|".$"x$q,(abs$t%14-7)-$_?$":"*",$"x(17-$q),"|
"}0..7),$h,select'','','',0.1while$q=abs$t++%34-17,1
```
Does not start on the upper left corner as the example output does, but that is not stated as a requirement.
[Answer]
## Ruby 1.9, 162 characters
35 chars shy of @Ventero's answer, but I was impressed that I could get it down this far while still using a relatively straightforward approach to the actual logic. The ^[ is a literal ESC (1 char).
```
x=y=0
v=h=1
s=' '
loop{puts"^[[2J"+b="+#{?-*18}+",*(0..7).map{|i|"|#{i!=y ?s*18:s*x+?*+s*(17-x)}|"},b
y+=v
y+=v*=-1if y<0||y>7
x+=h
x+=h*=-1if x<0||x>17
sleep 0.1}
```
[Answer]
## R, 233 characters
```
s=c("\n+",rep("-",18),"+");for (j in 1:8){cat(s,sep="");cat(rep(c("\n|",rep("",17),"|"),j-1));cat(c("\n|",rep(" ",j-1),"*",rep(" ",18-j),"|"),sep="");cat(rep(c("\n|",rep("",17),"|"),8-j));cat(s,sep="");Sys.sleep(0.1);system("clear")}
```
[Answer]
**Another bash entry - ~~213~~ 204 chars**
Not really a prize winner, but it was fun nonetheless. It uses vt100 char sequences for the drawing. (the code reported here uses 215 chars for readability, 2 chars can be removed by escaping, e.g. '\*' -> \\*
```
e(){ printf "\e[$1";}
e 2J;e H
h='+------------------+'
echo $h
for((;++j<9;));do printf '|%18s|\n';done
echo $h
e '3;2H*'
while :;do
e 'D '
((i/17%2))&&e D||e C
((++i/7%2))&&e A||e B
e 'D*'
sleep .1
done
```
[Answer]
# Powershell, 139 bytes
*Inspired by Danko Durbić's [answer](https://codegolf.stackexchange.com/a/5658/80745).*
```
for(){cls
,"+$('-'*18)+
"*2-join("|$(' '*18)|
"*8-replace"^(\W{$(21*[Math]::abs(7-$i%14)+[Math]::abs(17-$i++%34))}.) ",'$1*')
sleep -m 100}
```
This script uses the `-replace` operator to draw `*` inside the rectangle.
Less golfed script to explain how it works:
```
for(){
cls
$y=[Math]::abs(7-$i%14)
$x=[Math]::abs(17-$i++%34)
$b="+$('-'*18)+`n"
$m="|$(' '*18)|`n"*8-replace"^(\W{$(21*$y+$x)}.) ",'$1*'
,$b*2-join($m) # draw it
sleep -m 100
}
```
[Answer]
### Bash 278 300, 296
```
h="+------------------+"
w="| |"
g(){
echo -e "\e[$2;$1H$3"
}
g 1 1 $h
for i in {1..8}
do
echo "$w"
done
echo $h
x=4
y=4
p=1
q=1
for((;;))
do
((x==19&&p==1||x==2&&p==-1))&&p=-$p
((y==9&&q==1||y==2&&q==-1))&&q=-$q
x=$((x+p))
y=$((y+q))
g $x $y \*
sleep .1
g $x $y " "
done
```
The \e in the line `echo -e "\e[$2;$1H$3"` can be produced by
```
echo -e "\x1b"
```
to replace it. As binary 0x1b it is 3 chars shorter; I count just 1 for "\e", because only the layouting software forces me to use `\e`.
[Answer]
# TI Basic, ~~169~~ 167 bytes
```
1→X
1→Y
1→S
1→T
While 1
ClrHome
Output(Y,X,"*
S(X>1 and X<20)+(X=1)-(X=20→S
T(Y>1 and Y<10)+(Y=1)-(Y=10→T
X+S→X
Y+T→Y
For(N,1,20,19
For(O,1,10,9
Output(O,N,"+
End
End
For(N,2,19
For(O,1,10,9
Output(O,N,"-
End
End
For(O,2,9
Output(O,1,"|
Output(O,20,"|
End
End
```
Horribly slow, but it works.
[Answer]
# PHP, ~~196 186~~ 148 bytes
I removed avoiding an integer overflow to save 6 bytes. It will run for 29 billion years before overflow; still 6.8 years on a 32 bit system. I´d say that´s acceptable.
Calculating the position instead of adjusting it saved a lot, preparing the complete template at once another lot.
```
for(;++$i;$s[-3-21*abs($i%14-7)-abs($i%34-17)]="*",print$f(_,9e5,"
").$s.$z,usleep(1e5))$s=($f=str_pad)($z=$f("+",19,"-")."+
",189,$f("|",19)."|
");
").$z;
```
Run with `-nr`. Requires PHP 7.1.
**breakdown**:
```
for(;++$i; # infinite loop:
# 2. set asterisk at appropriate position
$s[-3-21*abs($i%14-7)-abs($i%34-17)]="*";
# 3. clear screen: print 900k newlines
print$f(_,9e5*0+2,"\n")
.$s.$z, # 4. print field
usleep(1e5)) # 5. sleep 100000 microseconds
# 1. create template
$s=($f=str_pad)($z=$f("+",19,"-")."+\n",189,$f("|",19)."|\n");
```
] |
[Question]
[
# Challenge
Given a Youtube playlist, output the number of videos in it.
# I/O
The playlist will be given as an URL; for example, `https://www.youtube.com/playlist?list=PL_3jnZNPYn7qUatgDYBS5NShkfXoehSRC` (this is a playlist a friend sent me to try to get me to listen to K-Pop because she's obsessed with it and I don't like it :P)
The link to a playlist is of the form `https://www.youtube.com/playlist?list=<id>`. The input is the URL, not the ID.
The output is to be a single integer indicating how many videos are in this playlist. You can either output the total number of videos or the number of non-deleted videos, whichever one is more golfy for you.
# Test Cases
```
https://www.youtube.com/playlist?list=PL_3jnZNPYn7qUatgDYBS5NShkfXoehSRC -> 12
https://www.youtube.com/playlist?list=PLIEbITAtGBebWGyBZQlkiMXwt30WqG9Bd -> 114 OR 1
```
Feel free to add more test cases.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
Assumes that the **URL** is passed *without* the `https://`.
### Code:
```
.w’®Ã-ƒ¢’¡`"<li>"¡2è#¬
```
Uses the **05AB1E** encoding. Cannot be tried online, because of internet access.
### Explanation:
```
.w # Receive implicit input and read all data from the url
’®Ã-ƒ¢’¡ # Split on the string "header-details"
` # Flatten once which leaves the last element on top of the stack
"<li>"¡ # Split on the string "<li>"
2è # Get the third element
# # Split on spaces
¬ # Retrieve the first element
```
This is what I get when running in the command line:
[](https://i.stack.imgur.com/6pa8D.png)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
*Thanks to [Hyper Neutrino](https://codegolf.stackexchange.com/users/42649/hyper-neutrino) for finding a mistake, now corrected.*
```
Xi'wner">\n'XXn
```
The input is a string enclosed with single quotes. The output is the number of undeleted videos.
Here's an **example run** with the two test cases. As of June 13, 2017 the number of undeleted videos in the playlists are 12 and 1 respectively.
[](https://i.stack.imgur.com/sXKua.gif)
### How it works
```
Xi % Read string containing URL and get contents as a string
'wner">\n' % Push this string
XX % Regexp matching. Gives a cell array with the matched strings
n % Number of elements. Implicitly display
```
[Answer]
# Scala 2.12, 138 bytes
```
print("""<li>.*?</li><li>(\d+).*?</li>""".r.findFirstMatchIn(scala.io.Source.fromURL(args(0),"utf-8").getLines.mkString("")).get.group(1))
```
Save it to `something.scala` and run by `scala something.scala {url}`.
[](https://i.stack.imgur.com/OKyB7.png)
[Answer]
# bash + curl + gnu grep, 32 bytes
Finally giving Code Golf a go:
```
curl -s $1|grep -Po \\d+(?= vid)
```
* Use `curl -s` to download without any extra output.
* Pipe the output to grep (perl regex) which will output only the match
+ Match the first number that proceeds " vid"
This is golfed from how I would do this practically.
[Answer]
# JS (ES6), 68 bytes
```
x=>fetch(x).then(x=>x.text()).then(x=>alert(x.match(/(\d+) vi/)[1]))
```
Paste this in to your console on youtube.com to try:
```
(x=>fetch(x).then(x=>x.text()).then(x=>alert(x.match(/(\d+) vi/)[1])))(prompt("Enter the URL"))
```
[Answer]
## PowerShell, 55 Bytes
```
"$(iwr "$args")"-match'(?s)(\d+) vid'>$null;$matches[1]
```
Browse to the site. Convert the object to a string which is the html source. Parse out the string that has a number preceding "vid" with regex.
Logic works with both test cases.
[Answer]
# Haskell 161 bytes
```
import Network.Curl.Download
import qualified Data.ByteString.Char8 as B
z=do u<-getLine;(Right b)<-openURI u;putStrLn$show$length$B.findSubstrings(B.pack"<tr")b
```
] |
[Question]
[
The goal is really simple. Receiving a string as input, parse all the HTML entities that correspond to the following characters (including their uppercase variants):
```
áàãâäéèêëíìîïóòõôöúùûüýÿ
```
Parsing rules:
* Each entity starts with `&` and ends with `;`
* The first character after the `&` will be the modified character (letter case is important!)
* The remaining characters refer to the name of the accent to use (`acute`, `grave`, `circ`, `tilde` and `uml`). The accent name **MUST** be in lowercase! \*
* Any HTML entity that produces a character that isn't on that list, or that is invalid, should be left untouched (E.g.: `&`, `&etilde;`, `&a;`)
* Numeric entities should be ignored, since they don't fit in the rules above
This change was introduced as of 18-02-2016. All the existing answers that accept HTML entities with uppercase accent names are valid. Any future answer must follow this rule.
**Examples:**
```
á //á
Téhèh //Téhèh
an & //an &
```
**Output:**
The output can be in ISO-8859-*X* (1-15), windows-1252 or UTF-8/16/32.
You can pick **one and only one** of the valid encodings and use it for **any** output. You can safely assume that the input will be in ASCII.
Any of the following is a valid output for `á`:
* `á` (ISO-8859-1/15 or windows-1252, equivalent to `\xE1`)
* `á` (UTF-8, equivalent to `\xC3\xA1` or `\u00E1`)
* `aÌ` (UTF-8, equivalent to `a\xCC\x81` or `a\u0301`)
* Any combination of diacritics, without using HTML entities.
The output has to be visually similar, when rendered/displayed, to the characters on the list.
---
Remember, all the standard loopholes *and built-ins* \* are **disallowed**. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer wins.
\* This change was made due to the great disapproval of bonuses and penalities, and at the time of writting, doesn't invalidate any answer
[Answer]
# JavaScript (ES6), ~~141~~ ~~122~~ 134 bytes
```
a=>a.replace(/&([aeiouyAEIOUY](acute|uml)|[aeiouAEIOU](grave|circ)|[aoAO]tilde);/g,b=>b[1]+{g:"̀",a:"́",c:"̂",t:"̃",u:"̈"}[b[2]])
```
Followed daavko's example using diacritical marks, and I feel like an idiot for not thinking of using it sooner. Actually gets surprisingly short for JavaScript.
EDIT: Neil caught some bad cases of undefined, which are now fixed.
[Answer]
# [Retina](https://github.com/mbuettner/retina "Retina"), 115 bytes
I'm new to code-golf, but I think this might work.
This version was made before the rule, which doesn't allow replacing uppercase html entities (for example `&AACUTE;`) was introduced.
```
i`&([aeiouy])acute;
$1́
i`&([aeiou])grave;
$1̀
i`&([ao])tilde;
$1̃
i`&([aeiou])circ;
$1̂
i`&([aeiouy])uml;
$1̈
```
Quite simple search and replace. Uses UTF-8.
Uses [letter]\xCC\x[diacritical mark hex code] approach. Diacritical mark is added after every relevant letter.
For some reason, the default Droid Sans Mono font in the interpreter can't render the "circ" and "uml" letters properly. If you change it through developer tools to something like DejaVu Sans, it shows just fine. I think this is a limitation of the font, not the program. But if it's program's fault, I'll try to fix it.
Here is a 129 byte version, which doesn't replace uppercase HTML entites (for example `&AACUTE;`)
```
&([aeiouyAEIOUY])acute;
$1́
&([aeiouAEIOU])grave;
$1̀
&([aoAO])tilde;
$1̃
&([aeiouAEIOU])circ;
$1̂
&([aeiouyAEIOUY])uml;
$1̈
```
[Try it online!](http://retina.tryitonline.net/#code=aWAmKFthZWlvdXldKWFjdXRlOwokMcyBCmlgJihbYWVpb3VdKWdyYXZlOwokMcyACmlgJihbYW9dKXRpbGRlOwokMcyDCmlgJihbYWVpb3VdKWNpcmM7CiQxzIIKaWAmKFthZWlvdXldKXVtbDsKJDHMiA&input=JmFhY3V0ZTsmZWFjdXRlOyZpYWN1dGU7Jm9hY3V0ZTsmdWFjdXRlOyZ5YWN1dGU7CiZBYWN1dGU7JkVhY3V0ZTsmSWFjdXRlOyZPYWN1dGU7JlVhY3V0ZTsmWWFjdXRlOwomYWdyYXZlOyZlZ3JhdmU7JmlncmF2ZTsmb2dyYXZlOyZ1Z3JhdmU7JnlncmF2ZTsKJkFncmF2ZTsmRWdyYXZlOyZJZ3JhdmU7Jk9ncmF2ZTsmVWdyYXZlOyZZZ3JhdmU7CiZhdGlsZGU7JmV0aWxkZTsmaXRpbGRlOyZvdGlsZGU7JnV0aWxkZTsmeXRpbGRlOwomQXRpbGRlOyZFdGlsZGU7Jkl0aWxkZTsmT3RpbGRlOyZVdGlsZGU7Jll0aWxkZTsKJmFjaXJjOyZlY2lyYzsmaWNpcmM7Jm9jaXJjOyZ1Y2lyYzsmeWNpcmM7CiZBY2lyYzsmRWNpcmM7JkljaXJjOyZPY2lyYzsmVWNpcmM7JlljaXJjOwomYXVtbDsmZXVtbDsmaXVtbDsmb3VtbDsmdXVtbDsmeXVtbDsKJkF1bWw7JkV1bWw7Jkl1bWw7Jk91bWw7JlV1bWw7Jll1bWw7 "Try it online!")
[Try it online! 129-byte version](http://retina.tryitonline.net/#code=JihbYWVpb3V5QUVJT1VZXSlhY3V0ZTsKJDHMgQomKFthZWlvdUFFSU9VXSlncmF2ZTsKJDHMgAomKFthb0FPXSl0aWxkZTsKJDHMgwomKFthZWlvdUFFSU9VXSljaXJjOwokMcyCCiYoW2FlaW91eUFFSU9VWV0pdW1sOwokMcyI&input=JmFhY3V0ZTsmZWFjdXRlOyZpYWN1dGU7Jm9hY3V0ZTsmdWFjdXRlOyZ5YWN1dGU7CiZBYWN1dGU7JkVhY3V0ZTsmSWFjdXRlOyZPYWN1dGU7JlVhY3V0ZTsmWWFjdXRlOwomYWdyYXZlOyZlZ3JhdmU7JmlncmF2ZTsmb2dyYXZlOyZ1Z3JhdmU7JnlncmF2ZTsKJkFncmF2ZTsmRWdyYXZlOyZJZ3JhdmU7Jk9ncmF2ZTsmVWdyYXZlOyZZZ3JhdmU7CiZhdGlsZGU7JmV0aWxkZTsmaXRpbGRlOyZvdGlsZGU7JnV0aWxkZTsmeXRpbGRlOwomQXRpbGRlOyZFdGlsZGU7Jkl0aWxkZTsmT3RpbGRlOyZVdGlsZGU7Jll0aWxkZTsKJmFjaXJjOyZlY2lyYzsmaWNpcmM7Jm9jaXJjOyZ1Y2lyYzsmeWNpcmM7CiZBY2lyYzsmRWNpcmM7JkljaXJjOyZPY2lyYzsmVWNpcmM7JlljaXJjOwomYXVtbDsmZXVtbDsmaXVtbDsmb3VtbDsmdXVtbDsmeXVtbDsKJkF1bWw7JkV1bWw7Jkl1bWw7Jk91bWw7JlV1bWw7Jll1bWw7CiZBVU1MOw "Try it online! 129-byte version")
[Answer]
# Japt, ~~81~~ 75 bytes
```
Ur`&([%vYy](ac©e|uml)|%v(g?ve|circ)|[AaOo]Èìe);`@Yg +'Ì+"?????"g"gutca"bYgJ
```
The six `?`s represent unprintable chars. [Test it online!](http://ethproductions.github.io/japt?v=master&code=VXJgJihbJXZZeV0oYWOpZXx1bWwpfCV2KGefdmV8Y2lyYyl8W0FhT29dyOxlKTtgQFlnICsnzCsigIGCg4giZyJndXRjYSJiWWdK&input=IlQmZWFjdXRlO2gmZWdyYXZlO2gi)
Note: This outputs the third encoding option; that is, the letter followed by the raw UTF-8 encoding of the corresponding combining diacritical mark.
### How it works
```
Ur"&( );" // Replace each ampersand and semicolon that have one of these between them:
([%vYy](acute|uml) // A vowel or Yy followed by "acute" or "uml",
|%v(grave|circ) // or a vowel followed by "grave" or "circ",
|[AaOo]tilde // or "a" or "o" followed by "tilde";
@ // replace each match X and its middle Y with this function:
""g"gutca"bYgJ // Take the unprintable at index (index of the second char in Y in "gutca") in this string.
Yg +'Ì+ // Concatenate the first char in Y and "Ì" to the beginning.
// Implicit output
```
Hexdump of the code:
```
00000000: 55 72 60 26 28 5b 25 76 59 79 5d 28 61 63 a9 65 Ur`&([%vYy](ac©e
00000010: 7c 75 6d 6c 29 7c 25 76 28 67 9f 76 65 7c 63 69 |uml)|%v(g.ve|ci
00000020: 72 63 29 7c 5b 41 61 4f 6f 5d c8 ec 65 29 3b 60 rc)|[AaOo]Èìe);`
00000030: 40 59 67 20 2b 27 cc 2b 22 80 81 82 83 88 22 67 @Yg +'Ì+"....."g
00000040: 22 67 75 74 63 61 22 62 59 67 4a "gutca"bYgJ
```
[Answer]
# JavaScript (ES6), 288 bytes
```
a=>(z=(b,c=1,d=2,e=3,f=0,g=4)=>({b:b+191,grave:c,acute:d,circ:e,tilde:f,uml:g}),y={a:z(0,1,2,3,4,5),e:z(8),i:z(12),o:z(18,1,2,3,4,5),u:z(25),y:z(28,0,2,0)},a.replace(/&\w+;/gi,b=>(x=y[b[1].toLowerCase()])&&(w=x[b.slice(2,-1)])?String.fromCharCode(x.b+w+32*(b[1]>'_')+153*/Yu/.test(b)):b))
```
Creates a character map object (with the base numeric code for each character), and uses offsets (or 0 if non-existent) to determine if an entity should be converted and what it's character code is. Symmetry in the cases means adding 32 if lowercase, except for `Ÿ`, where it uses a different offset for UTF8.
] |
[Question]
[
## Rocket Bots
The year is 3024. People have become too scarce a resource to risk in war, so combat has shifted to the robots. Your task is to construct a bot like no other, who's rockets will rain destruction down on your foes and shoot down all incoming threats.
## Gameplay
### Bots
Gameplay takes place on a 10x15 grid. Your bot is located off the bottom edge, and has three slots at spots 6,7 and 8 of the grid. Your opponent is located at the top of the grid, with three slots directly opposite yours.
### Rockets
From any of these slots, you can fire a rocket, assuming the slot has not been destroyed. A rocket consists of a list of directions that is given to it when created, and once fired these directions cannot be changed. Each turn, the rocket will consume the top of the list, and move in that direction. Rockets move simultaneously. If two rockets end in the same tile, they will both explode. If a rocket runs out of commands, it will explode. If a rocket runs out of fuel, after 100 moves, it will explode. When a rocket explodes, it will remain in that tile for 5 turns, causing any other rockets that move there to explode as well.
*Note:* Because of the simultaneous movement, two rockets can pass each other without exploding, as long as they do not both end a turn in the same tile.
### Goal
The goal of each match is to destroy your opponents slots while keeping yours alive. A rocket can be fired from any live slot you have, and is given a path designated by you before it is fired. **You fire a rocket every second turn, meaning rockets will move twice before you can fire another one.** A duel lasts for 200 turns, or until one bots slots are all destroyed.
### Scoring
At the end of the match, you get one point for each live slot you have, and one point for each opponents slot you destroyed. This means it is a zero-sum game, and 6 points will be awarded each match.
A round robin will be run so that each bot faces each other bot once. If any bots use RNGs, then each matchup will be 1000 duels instead.
## Implementation
Code for the competition can be found here: <https://github.com/Cain93/RocketBots>
Each submission should extend the `Bot` class. You must override the `fireRocket` method. This method receives a grid array of Rockets, `Rocket[][]`, that represents the gameboard. You are always located at the bottom of the grid, with slots at spots `[-1][6]`, `[-1][7]`, `[-1][8]`. On the grid, unoccupied spots will be represented with `null`. If a rocket exists in a tile, you can identify who it belongs to by accessing the `dis` field. "^" is your rocket, and "v" is your opponents.
You must return a LinkedList of Integers that gives the instructions for your rocket. To move up, use 0. To move up and right, use 1, just right, use 2, etc all the way to 7 for up and left. The rocket will move in the order you push Integers. For example, the following code will make the rocket move upwards a few turns, zig-zag a few turns and then detonate.
```
LinkedList<Integer> moves = new LinkedList<Integer>();
moves.push(0);
moves.push(0);
moves.push(0);
moves.push(1);
moves.push(7);
moves.push(1);
moves.push(7);
```
To change which slot to fire the rocket from, change the `curSlot` field. 0 is your leftmost slot, and 2 is your rightmost. To check if a slot is destroyed, use `getSlot(int slotNumber)`.
If a rocket ends a turn on a slot, that slot will be destroyed. You do not need to manually detonate the rocket.
*Note:* Rockets spawn at the location of the slot fired from, but will move once before collisions are evaluated. So if you fire a rocket from slot 0, and the first move is right (2), then you will destroy your own middle slot. However, up and right (1) is a safe move.
If you want to name your bot, override the `name()` method.
Bots will be re-built for each duel, so any static variables will be reset.
## Good Luck!
May your rockets fly true and your opponents be nothing but smoldering scraps of metal.
Hint:
>
> Purposefully detonating rockets to create explosions is an easier way to defend than trying to shoot down opponents rockets.
>
>
>
## Example Bot
```
package bots;
import java.util.LinkedList;
import mechanics.*;
public class SimpleBot extends Bot {
public String name(){
return "Simple";
}
public LinkedList<Integer> fireRocket(Rocket[][] g){
LinkedList<Integer> l = new LinkedList<Integer>();
for(int i = 0; i < 12; i++){
l.push(0);
}
return l;
}
}
```
# Scores
Scores from 6-24
```
Simple: 900
Zigzagoon: 3654
Wall-E: 3606
Tortoise: 2248
3 Shot: 2334
HatTrickBot: 4287
Sniper: 2973
SideShooter: 2491
Terminator: 4835
StraightShot: 3378
Defender: 4570
MoreDakka: 4324
```
[Answer]
# Zigzagoon
The outer slots go (slightly) wide, then head forward and come back in toward the enemy slots. The middle slot shoots a zigzag pattern up the middle.
Every other round (3 turns), it goes into defense mode and just explodes some rockets near my own slots. Attack mode rockets then go around them. Nothing too fancy, just something to get the contest up and running.
```
package bots;import java.util.*;import mechanics.*;
public class Zigzagoon extends Bot{
String[] evenMoves = {"7000000001","0170710170","1000000007"};
String[] oddMoves = {"0","00","0"};
boolean even = true;
public String name(){return "Zigzagoon";}
public LinkedList<Integer> fireRocket(Rocket[][] g){
curSlot = (curSlot+1)%3;
if(curSlot<1)even=!even;
String[] moves = even?evenMoves:oddMoves;
LinkedList<Integer> command = new LinkedList<Integer>();
for(int i=0;i<moves[curSlot].length();i++)
command.push(moves[curSlot].charAt(i)-'0');
return command;
}
}
```
[Answer]
## Terminator
I'm proud to present Terminator !!!
Each rocket move far left/right from the middle and return on a enemy slot. Every two turns, a defense rocket is launched straight and explode near slot to protect it.
```
package bots;
import java.util.LinkedList;
import mechanics.Bot;
import mechanics.Rocket;
public class Terminator extends Bot {
int n = 0;
String[] moves = {"000", "0111107777", "00", "0077700111", "00", "0777701111"};
public String name() {
return "Terminator";
}
@Override
public LinkedList<Integer> fireRocket(Rocket[][] g) {
curSlot = (n+1) % 3;
LinkedList<Integer> commands = loadCommands(moves[n % moves.length]);
n++;
return commands;
}
protected LinkedList<Integer> loadCommands(String commands) {
LinkedList<Integer> linkedList = new LinkedList<Integer>();
for (int i = 0; i < commands.length(); i++) {
linkedList.push(commands.charAt(i) - 48);
}
return linkedList;
}
}
```
[Answer]
# Defender
Defender uses a new type of defense: The rockets *are patrolling* in front of the slots. This gives a huge advantage, since rockets live for 100 turns instead of 5 turns (like explosions).
```
package bots;
import java.util.LinkedList;
import mechanics.*;
public class Defender extends Bot {
int turn = 0;
@Override
public String name() {
return "Defender";
}
@Override
public LinkedList<Integer> fireRocket(Rocket[][] grid) {
LinkedList<Integer> command = new LinkedList<Integer>();
for (int i = 0; i < 3; i++) {
if ((grid[0][6+i] == null || grid[0][6+i].getDis().equals("v")) && (grid[1][6+i] == null || grid[1][6+i].getDis().equals("v")) && getSlot(i)) {
curSlot = i;
command.push(0);
for (int j = 0; j < 50; j++) {
command.push(0);
command.push(4);
}
break;
}
}
if (command.isEmpty()) {
if ((grid[0][9] == null || grid[0][9].getDis().equals("v")) && (grid[0][10] == null || grid[0][10].getDis().equals("v")) && (grid[1][10] == null || grid[1][10].getDis().equals("v")) && getSlot(2)) {
curSlot = 2;
command.push(1);
command.push(1);
command.push(4);
for (int i = 0; i < 50; i++) {
command.push(6);
command.push(2);
}
} else if ((grid[0][5] == null || grid[0][5].getDis().equals("v")) && (grid[0][4] == null || grid[0][4].getDis().equals("v")) && (grid[1][4] == null || grid[1][4].getDis().equals("v")) && getSlot(0)) {
curSlot = 0;
command.push(7);
command.push(7);
command.push(4);
for (int i = 0; i < 50; i++) {
command.push(2);
command.push(6);
}
}
}
if (command.isEmpty()) {
if (turn % 2 == 0 && getSlot(0)){
curSlot = 0;
command.push(7);
command.push(7);
for (int i = 0; i < 7; i++) {
command.push(0);
}
command.push(2);
for (int i = 0; i < 2; i++) {
if (Math.random() < 0.2) command.push(2);
}
command.push(1);
} else {
curSlot = 2;
command.push(1);
command.push(1);
for (int i = 0; i < 7; i++) {
command.push(0);
}
command.push(6);
for (int i = 0; i < 2; i++) {
if (Math.random() < 0.5) command.push(6);
}
command.push(7);
}
}
turn++;
return command;
}
}
```
[Answer]
# HatTrickBot
I had DoubleTapBot for CodeBot 3, who was hitting twice on a turn, here comes HatTrickBot : Hitting all the 3 spots at the same time !
It is always possible to prevent a rocket to hit if you know where it will fall.
But I don't think there's many bot that will be able to protect their slots against a 3 rocket attack.
By the way, yes, it's horrible to see such elseif with repeated switch. I could have created a var to switch on with unique values for each combination of the status of slots and the turnConter. But it would be harder to read (I would have to keep the meaning of the values in a comment... boring !) :)
```
package bots;
import java.util.LinkedList;
import mechanics.*;
/*
* HatTrickBot always tries to destroy all the enemy slots at once
* In order to achieve this, each slot needs extrem concentration and coordination
* It explain why they need some turns to re-synchronized the rockets after one of them dies.
*/
public class HatTrickBot extends Bot
{
// Default moves are at [0]
// moves at [1] are used when there's only 2 slots remaining
// moves [2-4] are here for when there's only 1 slot remaining
// it panicks, and can't establish how to fire to do a hat trick.
// So he will just spamm every ennemy position, one at a time
String[] rightSlot = { "770002000020",
"0000000001",
"0000000000",
"0000000001",
"0000000011"};
String[] midSlot = { "0000000000",
"11000060000",
"0000000000",
"0000000010",
"0000000700"};
String[] leftSlot = { "11000060007",
"777702000020",
"0000000000",
"0000007000",
"0000077000"};
int turnCounter=-1;
public String name(){return "HatTrickBot";}
public LinkedList<Integer> fireRocket(Rocket[][] g)
{
turnCounter=(turnCounter+1)%3;
String[][] moves = {rightSlot,midSlot,leftSlot};
LinkedList<Integer> ll = new LinkedList<Integer>();
boolean slotL=getSlot(0),slotM=getSlot(1),slotR=getSlot(2);
int movePoint=0;
if(slotL&&slotM&&slotR)
{
switch(turnCounter)
{
case 0: curSlot=0;
break;
case 1: curSlot=2;
break;
case 2: curSlot=1;
break;
default:break;
}
movePoint=0;
}
else if(!slotM&&slotL&&slotR)
{
switch(turnCounter)
{
case 0: curSlot=0;
movePoint=0;
break;
case 1: curSlot=2;
movePoint=0;
break;
case 2: curSlot=0;
movePoint=1;
break;
default:break;
}
}
else if(!slotL&&slotM&&slotR)
{
switch(turnCounter)
{
case 0: curSlot=0;
movePoint=0;
break;
case 1: curSlot=1;
movePoint=1;
break;
case 2: curSlot=0;
movePoint=1;
break;
default:break;
}
}
else if(!slotR&&slotM&&slotL)
{
switch(turnCounter)
{
case 0: curSlot=2;
movePoint=1;
break;
case 1: curSlot=1;
movePoint=1;
break;
case 2: curSlot=1;
movePoint=0;
break;
default:break;
}
}
else
{
if(slotR)curSlot=0;
if(slotM)curSlot=1;
if(slotL)curSlot=2;
movePoint = 2+turnCounter;
}
for(int i=0;i<moves[curSlot][movePoint].length();i++)
ll.push(Integer.parseInt(moves[curSlot][movePoint].charAt(i)+""));
return ll;
}
}
```
[Answer]
# Tortoise
If I protect all my bases, I have 3 points. Bases can only be attacked from 5 locations if I get the grid well. Rocket lasts 5 turn on the field...
This bot uses all of this to match its goal : surviving with at least 50% of the points in the pocket. It shoots 3 rockets, then cover itself
```
package bots;
import java.util.LinkedList;
public class Tortoise extends Bot
{
int turnCounter=-1;
boolean attacked=false;
int[] moves={7,0,0,0,1};
public String name(){return "Tortoise";}
public LinkedList<Integer> fireRocket(Rocket[][] g)
{
LinkedList<Integer> rocket = new LinkedList<Integer>();
turnCounter++;
if(!attacked)
{
curSlot=turnCounter;
for(int i=0;i<11;i++)
rocket.push(0);
if(turnCounter==2)
attacked=true;
return rocket;
}
turnCounter%=5;
switch(turnCounter)
{
case 0:
case 1:curSlot=0;break;
case 2:curSlot=1;break;
case 3:
case 4:curSlot=2;break;
default:break;
}
rocket.push(moves[turnCounter]);
return rocket;
}
}
```
[Answer]
# SideShooter
First shoots via the first ( rightmost ) turret in one of two different ways. Then, it shoots via the last ( leftmost ) turret in one of two different ways. Then it makes a "wall" with the second ( middle ) turret by exploding rockets in front of each turret. This process is repeated.
If the game lasts for more than 30 turns, SideShooter grows bored and changes in a small way. Instead of making a "wall" with the second ( middle ) turret, it shoots straight. The rest of the turrets behave the same way.
```
import java.util.LinkedList;
public class SideShooter extends Bot {
int[] launcher = new int[]{1, 3, 2, 2, 2};
String[] right = {"1100000077", "100000007"};
String[] left = {"7700000011", "700000001"};
int position = -1;
int turns = 0;
public String name(){
return "SideShooter";
}
public LinkedList<Integer> fireRocket(Rocket[][] g){
LinkedList<Integer> directions = new LinkedList<Integer>();
if(getSlot(0) || getSlot(1) || getSlot(2))
do{
position = (position + 1) % 5;
curSlot = launcher[position] - 1;
}while(!getSlot(curSlot));
if(position == 0)
{
String shoot = left[((int) (Math.random() * left.length))];
for(int i=0; i < shoot.length(); i++)
directions.push(shoot.charAt(i)-'0');
}else if(position == 1)
{
String shoot = right[((int) (Math.random() * right.length))];
for(int i=0; i < shoot.length(); i++)
directions.push(shoot.charAt(i)-'0');
}else
{
if(turns < 30)
{
if(position == 2 )
directions.push(0);
else if(position == 3)
directions.push(1);
else if(position == 4)
directions.push(7);
}else
for(int i=0; i < 10; i++)
directions.push(0);
}
turns ++;
return directions;
}
}
```
[Answer]
# Sniper
Sniper first blocks its two sides and then starts shooting straight.
```
import java.util.LinkedList;
public class Sniper extends Bot {
int[] launcher = new int[]{1, 3, 1, 2, 3};
String[] moves = {"7", "1", "0000000000", "0000000000", "0000000000"};
int position = -1, move = 0;
public String name(){
return "Sniper";
}
public LinkedList<Integer> fireRocket(Rocket[][] g){
LinkedList<Integer> directions = new LinkedList<Integer>();
if(getSlot(0) || getSlot(1) || getSlot(2))
do{
position = (position + 1) % launcher.length;
curSlot = launcher[position] - 1;
}while(!getSlot(curSlot));
for(int i=0; i < moves[move].length(); i++)
directions.push(moves[move].charAt(i)-'0');
move = (move + 1) % moves.length;
return directions;
}
}
```
[Answer]
# Three Shot
We got some weird shots flying. No true defense, but the pattern is such that it will be hard to get a shot past this bizarre hail of missiles. (or that is the idea. it most likely will not work.)
```
package bots;import java.util.*;import mechanics.*;
public class ThreeShot extends Bot{
public String name(){state = 0;return "3 Shot";}
private int state;
public LinkedList<Integer> fireRocket(Rocket[][] g){
LinkedList<Integer> command = new LinkedList<Integer>();
if(state < 2){
state++;
return fireLeft();
}
if(state < 4){
state++;
return fireCenter();
}
state=(state+1)%6;
return fireRight();
}
LinkedList<Integer> fireCenter(){
LinkedList<Integer> command = new LinkedList<Integer>();
curSlot = 1;
while(command.size()<90){
command.push(1);
command.push(7);
command.push(6);
command.push(1);
}
return command;
}
LinkedList<Integer> fireRight(){
LinkedList<Integer> command = new LinkedList<Integer>();
curSlot = 2;
command.push(1);
for(int i=0;i<8;i++){
command.push(0);
}
command.push(7);
return command;
}
LinkedList<Integer> fireLeft(){
LinkedList<Integer> command = new LinkedList<Integer>();
curSlot = 0;
command.push(7);
for(int i=0;i<8;i++){
command.push(6);
command.push(1);
}
command.push(1);
return command;
}
}
```
Note
[Answer]
# [MoreDakka](http://tvtropes.org/pmwiki/pmwiki.php/Main/MoreDakka)
MoreDakka shoots in five directions without a stop (until turrets gets wrecked by other missiles).
```
import java.util.LinkedList;
public class MoreDakka extends Bot
{
String[] moves={"70000000001", "0000000000", "0000000000", "0000000000", "1000000007"};
int[] launcher = new int[]{0, 0, 1, 2, 2};
int position = -1;
public String name(){
return "MoreDakka";
}
public LinkedList<Integer> fireRocket(Rocket[][] g)
{
LinkedList<Integer> directions = new LinkedList<Integer>();
if(getSlot(0) || getSlot(1) || getSlot(2))
do{
position = (position + 1) % launcher.length;
curSlot = launcher[position];
}while(!getSlot(curSlot));
for(int i=0; i < moves[position].length(); i++)
directions.push(moves[position].charAt(i)-'0');
return directions;
}
}
```
[Answer]
# StraightShot
Just fire right at them.
```
package bots;import java.util.*;import mechanics.*;
public class StraightShot extends Bot{
public String name(){return "StraightShot";}
public LinkedList<Integer> fireRocket(Rocket[][] g){
LinkedList<Integer> command = new LinkedList<Integer>();
curSlot = (curSlot+1)%3;
for(int i=0;i<100;i++)
command.push(0);
return command;
}
}
```
[Answer]
Here's my own entry
# WallE
Shoots some offset rockets, and builds walls on his edges and center.
After 100 turns, starts targeting the middle slot.
```
package bots;
import java.util.LinkedList;
import java.util.Random;
import mechanics.*;
public class WallE extends Bot {
int turn = 2;
public String name(){
return "Wall-E";
}
public LinkedList<Integer> fireRocket(Rocket[][] g){
turn++;
LinkedList<Integer> moves = new LinkedList<Integer>();
curSlot = 1;
switch(turn%4){
case 0:
//Check the right wall
if(getSlot(2)){
curSlot = 2;
moves.push(1);
return moves;
}
case 1:
//Check the left wall
if(getSlot(0)){
curSlot = 0;
moves.push(7);
return moves;
}
case 2:
//Check the center wall
if(getSlot(1)){
curSlot = 1;
moves.push(0);
return moves;
}
break;
default:
//Fire a sneaky rocket
Random rand = new Random();
int direction = rand.nextInt(2);
int back = 0;
if(direction == 0 && getSlot(2)){ direction = 1; back = 7; curSlot = 2;}
else{ direction = 7; back = 1; curSlot = 0; }
moves.push(0);
moves.push(direction);
moves.push(direction);
for(int i = 0; i < 5; i++){
moves.push(0);
}
//Go for the center after turn 100
if(turn > 104){
moves.pop();
moves.push(back);
}
moves.push(back);
moves.push(back);
}
return moves;
}
}
```
] |
[Question]
[
Draw something that looks like this:

In more precise terms, draw a circle of radius r, with n evenly-spaces tangent lines of length l. Connect the ends of these lines to form a new n-sided regular polygon.
## Rules
r = circle radius
n = number of tangent lines - must be evenly spaced around circle (n>=3)
l = side length of tangent lines
Create a program that accepts the arguments { r, n, l } and draws the required output.
Units are in pixels.
There is no restrictions to the location of the drawing, as long as all of it is visible.
The picture is pretty self-explanatory.
This is code-golf, so shortest code in bytes wins!
[Answer]
# Python, 133 bytes
*The only answer so far to comply with the "Units are in pixels" rule...*
```
from turtle import*
c=circle
r,n,l=input()
lt(90)
exec'c(r,360/n);fd(l);bk(l);'*n
fd(l)
lt(towards(-r,0)-180)
c(distance(-r,0),360,n)
```
Add `exitonclick()` to the end if you don't want the window to close immediately.
### Output:
`python tangentpoly.py <<< "20, 6, 30"`:

`python tangentpoly.py <<< "100, 8, 200"`:

[Answer]
## T-SQL ~~440~~ 483
Not going to win any prizes with this one, but I like drawing pictures :)
**Edit** Expletive! Just noticed I messed up for polygons drawn across the circle. Fixed at a cost.
```
SELECT Geometry::UnionAggregate(Geometry::Point(0,0,0).STBuffer(@r).STExteriorRing().STUnion(Geometry::STGeomFromText(CONCAT('LINESTRING(',@r*SIN(a),' ',@r*COS(a),',',@r*SIN(a)+@l*SIN(b),' ',@r*COS(a)+@l*COS(b),')'),0))).STUnion(Geometry::ConvexHullAggregate(Geometry::Point(@r*SIN(a)+@l*SIN(b),@r*COS(a)+@l*COS(b),0)).STExteriorRing())p FROM(SELECT RADIANS(360./@*N)a,RADIANS((360./@*N)-90)b FROM(SELECT TOP(@)row_number()OVER(ORDER BY(SELECT\))-1N FROM sys.types a,sys.types b)t)r
```
Executed with the following variables
```
declare @r float = 1.0
declare @ int = 10
declare @l float = 3.0
```
Run in Sql Server Management Studio 2012+ it will return the following in the spatial results tab.

With
```
declare @r float = 1.0
declare @ int = 360
declare @l float = 3.0
```

with
```
declare @r float = 10.0
declare @ int = 3
declare @l float = 10.0
```

Expanded out
```
SELECT Geometry::UnionAggregate( --group together lines
Geometry::Point(0,0,0) --Set origin
.STBuffer(@r) --Buffer to @r
.STExteriorRing() --Make it a line
.STUnion( --Join to the floowing tangent
Geometry::STGeomFromText( --Create a tangent line
CONCAT('LINESTRING(',@r*SIN(a),' ',@r*COS(a),',',@r*SIN(a)+@l*SIN(b),' ',@r*COS(a)+@l*COS(b),')'),0)
)
).STUnion( --Generate polygon around exterior points
Geometry::ConvexHullAggregate(Geometry::Point(@r*SIN(a)+@l*SIN(b),@r*COS(a)+@l*COS(b),0)).STExteriorRing()
)
p
FROM(
SELECT RADIANS(360./@*N)a, --calclate bearings
RADIANS((360./@*N)-90)b
FROM( --make enough rows to draw tangents
SELECT TOP(@)row_number()OVER(ORDER BY(SELECT\))-1N
FROM sys.types a,sys.types b
)t
)r
```
[Answer]
## Mathematica, ~~135~~ ~~132~~ ~~131~~ 123 bytes
```
{r,n,l}=Input[];Graphics[{{0,0}~Circle~r,Line[Join@@Array[{b=(a=r{c=Cos[t=2Pi#/n],s=Sin@t})-l{s,-c},a,b}&,n+1]]},Axes->1>0]
```
This code expects the input (via a prompt) exactly as specified in the question: e.g. `{100, 6, 150}`. It produces a vector graphic, so I'm including an axis, as specified in the comments by the OP.
Both the tangents and the polygon are actually a single line strip, by traversing "polygon-corner, tangent point, polygon-corner, next polygon-corner, tangent point, polygon-corner..."

If it wasn't for the axis, I could even do this in 107 bytes:
```
{r,n,l}=Input[];Graphics@{Circle[],Line[Join@@Array[{b=(a={c=Cos[t=2Pi#/n],s=Sin@t})-l/r{s,-c},a,b}&,n+1]]}
```
Additional savings (apart from `Axes->1>0`) come from the fact that I can now rescale everything by `r`, which simplifies the call to `Circle` yielding a unit circle.
[Answer]
# MATLAB - 233 bytes
```
function C(n,r,l),t=2*pi/n;c=cos(t);s=sin(t);M=[c,s;-s,c];F=@(y)cell2mat(arrayfun(@(x){M^x*y},1:n));P=F([0;r]);Q=F([l;r]);v='k';t=1e3;t=2*pi/t*(0:t);R=[1:n 1];q=Q(1,R);s=Q(2,R);plot(r*cos(t),r*sin(t),v,[P(1,R);q],[P(2,R);s],v,q,s,v);
```
Sample function output for `n = 8, r = 4, l = 6` (axes included to indicate unit length):

Sample function output for `n = 1024, r = 4, l = 2`:

[Answer]
# HTML + JavaScript (E6) 298
To test, save as an html file and open with FireFox.
Insert the parameters r,n,l into the input field, comma separated, then tab out.
Or try [jsfiddle](http://jsfiddle.net/prca5uy3/)
```
<input onblur="
[r,n,l]=this.value.split(','),
z=r-~l,t=D.getContext('2d'),w='lineTo',
D.width=D.height=z*2,
t.arc(z,z,r,0,7);
for(C=1,S=i=0;i++<n;)
t[w](x=z+r*C,y=z+r*S),
t[w](x-l*S,y+l*C),
C=Math.cos(a=6.283*i/n),
S=Math.sin(a),
t[w](z+r*C-l*S,z+r*S+l*C);
t.stroke()">
<canvas id=D>
```
Sample output

] |
[Question]
[
## Goal
Create a program or pair of programs that collectively disrupt and fix files with the intent of preventing LZMA2 from working effectively. The disrupt and fix routines must be reciprocal, so you can recover the original file exactly.
## Targets
* The collected works of Shakespeare in [plain UTF-8 (5,589,891 bytes)](http://www.gutenberg.org/ebooks/100.txt.utf-8)
* Wikimedia Commons 2013 Picture of the Year at [full resolution (1,659,847 bytes)
](https://upload.wikimedia.org/wikipedia/commons/b/bc/Gl%C3%BChwendel_brennt_durch.jpg)
## Compression Methods
* Ubuntu/related: `xz -kz5 <infile>`
* Windows: `7z.exe a -txz -mx5 <outfile> <infile>`
* Other: Use a LZMA2 compressor with compression level 5 that compresses the works of Shakespeare to 1570550 bytes ± 100 bytes.
## Scoring; sum of (everything is in bytes, `ls -l` or `dir` it):
* Program(s) size (whatever it takes collectively to reversibly "break"/fix the file)
* Difference in size (absolute) between:
+ Raw collected works of Shakespeare and your modified (uncompressed) copy.
+ Raw photo and your modified (uncompressed) copy.
* Difference in size or 0, whichever is greater between:
+ Raw collected works of Shakespeare minus your modified, LZMA2 compressed copy.
+ Raw photo minus your modified, LZMA2 compressed copy.
## Example
Poorly scoring, lazily-golfed, but compliant Python 2.x example:
```
import sys
x = 7919 if sys.argv[1] == 'b' else -7919
i = bytearray(open(sys.argv[2], 'rb').read())
for n in range(len(i)):
i[n] = (i[n] + x*n) % 256
o = open(sys.argv[2]+'~', 'wb').write(i)
```
Running...
```
$ python break.py b pg100.txt
$ python break.py f pg100.txt~
$ diff -s pg100.txt pg100.txt~~
Files pg100.txt and pg100.txt~~ are identical
$ python break.py b Glühwendel_brennt_durch.jpg
$ python break.py f Glühwendel_brennt_durch.jpg~
$ diff -s Glühwendel_brennt_durch.jpg Glühwendel_brennt_durch.jpg~~
Files Glühwendel_brennt_durch.jpg and Glühwendel_brennt_durch.jpg~~ are identical
$ xz -kz5 pg100.txt~
$ xz -kz5 Glühwendel_brennt_durch.jpg~
$ ls -ln
-rw-rw-r-- 1 2092 2092 194 May 23 17:37 break.py
-rw-rw-r-- 1 2092 2092 1659874 May 23 16:20 Glühwendel_brennt_durch.jpg
-rw-rw-r-- 1 2092 2092 1659874 May 23 17:39 Glühwendel_brennt_durch.jpg~
-rw-rw-r-- 1 2092 2092 1659874 May 23 17:39 Glühwendel_brennt_durch.jpg~~
-rw-rw-r-- 1 2092 2092 1646556 May 23 17:39 Glühwendel_brennt_durch.jpg~.xz
-rw-rw-r-- 1 2092 2092 5589891 May 23 17:24 pg100.txt
-rw-rw-r-- 1 2092 2092 5589891 May 23 17:39 pg100.txt~
-rw-rw-r-- 1 2092 2092 5589891 May 23 17:39 pg100.txt~~
-rw-rw-r-- 1 2092 2092 3014136 May 23 17:39 pg100.txt~.xz
```
Score
* = 194 + *abs*(5589891 − 5589891) + *max*(5589891 − 3014136, 0) + *abs*(1659874 − 1659874) + *max*(1659874 − 1646556, 0)
* = 194 + 0 + 2575755 + 0 + 13318
* **2,589,267 bytes.** Bad, but doing nothing to the files yields a score of 4,635,153 bytes.
>
> ## Clarification
>
>
> This is golf, so you are trying to *minimize* your score. I'm not sure if the comments are point out a legitimate hole in my scoring or if they are because I made it too complicated. In any case, you want the **SMALLEST**:
>
>
> * source code
> * difference between the uncompressed modified file and original file (e.g. if you modify it by appending a trillion 0's on the end, your score just went up a trillion bytes)
> * difference between the compressed modified file and original file (e.g. the more incompressible the files become, the higher your score). A perfectly incompressible file that grows slightly or not at all will score 0.
>
>
>
[Answer]
## Python, score = 120
```
import sys,hashlib
i=0
for c in sys.stdin.read():sys.stdout.write(chr(ord(c)^ord(hashlib.md5(str(i)).digest()[0])));i+=1
```
Makes a one-time pad using md5 in [counter mode](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29). xors the file with it. This has the advantage that the original and disrupted files are the same size, and that the disruptor and fixer are the same program.
The compressed disrupted files are larger than the originals.
[Answer]
# C, 51=51+0+0+0+0
```
main(c){for(;c=~getchar();putchar(~c^rand()>>23));}
```
Under the [golf tricks](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c), this program loops for each byte in standard input, and does exclusive-or with an infinite pad from rand(). I tested this with rand() in libc of OpenBSD 5.5.
Usage:
```
./scramble <orig >scrambled
./scramble <scrambled >orig.copy
```
To test my program, I wrote a [shell script *test.sh* (57 lines)](https://gist.github.com/kernigh/db4e610e10b592286d86) to compile my program and calculate my score.
```
$ sh test.sh
[1/4] Compiling scramble...
/tmp//ccbcB43x.o(.text+0x6): In function `main':
: warning: rand() isn't random; consider using arc4random()
[2/4] Scrambling files...
[3/4] Compressing scrambled files...
[4/4] Checking descrambler...
SCORE: 51=51+0+0+0+0
You may wish to rm -rf tmp.9Tjw89dgCs
$ ls -l tmp.9Tjw89dgCs/
total 43032
-rw-r--r-- 1 kernigh kernigh 1659874 May 28 17:23 filament.jpg.cp
-rw-r--r-- 1 kernigh kernigh 1659874 May 28 17:23 filament.jpg.sc
-rw-r--r-- 1 kernigh kernigh 1660016 May 28 17:23 filament.jpg.sc.xz
-rw-r--r-- 1 kernigh kernigh 5589891 May 28 17:23 pg100.txt.cp
-rw-r--r-- 1 kernigh kernigh 5589891 May 28 17:23 pg100.txt.sc
-rw-r--r-- 1 kernigh kernigh 5590232 May 28 17:23 pg100.txt.sc.xz
-rwxr-xr-x 1 kernigh kernigh 8564 May 28 17:23 scramble
```
## Notes about rand() and the right shift
Any compression algorithm can't compress random data. I can disguise *pg100.txt* and *filament.jpg* as random data if I scramble them with a [stream cipher](https://duckduckgo.com/?q=stream%20cipher).
My first idea was to exclusive-or *plaintext* with *pad* to make *ciphertext*, then store both *ciphertext* and *pad* in the scrambled file. This would increase the size of the file, and increase my score. The obvious choice is to use the same *pad* for every file, and store only *ciphertext* in the scrambled file. If I just call rand(), it uses a default seed of 1 and makes the same *pad* every time.
OpenBSD 5.5 defines rand() in [stdlib.h](http://www.openbsd.org/cgi-bin/cvsweb/src/include/stdlib.h?rev=1.56) and [rand.c](http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/stdlib/rand.c?rev=1.10):
```
/* from stdlib.h */
#define RAND_MAX 0x7fffffff
/* from rand.c */
static u_int next = 1;
int
rand_r(u_int *seed)
{
*seed = *seed * 1103515245 + 12345;
return (*seed % ((u_int)RAND_MAX + 1));
}
int
rand(void)
{
return (rand_r(&next));
}
```
This is a [linear congruential generator](http://rosettacode.org/wiki/Linear_congruential_generator). The big flaw is that low bits have short periods. The 1st bit has a period of 2: if you flip a coin with `rand()&1`, it would go heads, tails, heads, tails, and so on. The nth bit has a period of 2n. There are 31 bits, so the whole sequence has a period of 231.
LZMA2 can find patterns in short periods and compress them. The shortest code `~c^rand()` takes the low 8 bits and does not prevent compression. The right shift in `~c^rand()>>9` helps, but not enough. I use `~c^rand()>>23`.
* `~c` SCORE: 4227957=40+0+0+4019391+208526
* `~c^rand()` SCORE: 2474616=47+0+0+2463735+10834
* `~c^rand()>>9` SCORE: 350717=50+0+0+350667+0
* `~c^rand()>>23` SCORE: 51=51+0+0+0+0
[Answer]
# [BrainFuck](http://en.wikipedia.org/wiki/BrainFuck): 129 (129+0+0+0+0)\*
random.bf (linefeeds added for readability)
```
,+[->>>>++[<++++++++[<[<++>-]>>[>>]+>>+[-[->>+<<<[<[<<]<
+>]>[>[>>]]]<[>>[-]]>[>[-<<]>[<+<]]+<<]<[>+<-]>>-]<[-<<+
>>]<<.,+[->]>>>]]
```
To create `unrandom.bf` you need to change the last + in the second line.
Most of the code is based on Daniel B Cristofani's [Rule30 based random number generator](http://www.hevanet.com/cristofd/brainfuck/random.b) adapted to add the number to each input and to terminate when there is no more input.
\*I've tested the bytes it has processed so far 212992 (processed after 12 hours) and both files turns into a 213064 compressed file. I guess it might be done by the end of the week for know for sure but I don't want to wait with posting. I'll update the score if it's wrong, but keep the solution since Rule30 rocks!
Trivia: [Rule 30](http://en.wikipedia.org/wiki/Rule_30) was discovered by Stephen Wolfram in 1983 and according to Wikipedia it's used to produce random integers in Mathematica.
**Compilation and running:**
It uses exponential time and space (iterates over 32 more cells per char processed) so it requires a BrainFuck runtime that has at least 178,876,517 cells to encode the Shakespear file, do not treat non ascii as unicode, has wider than 8 bits cells and uses -1 as eof (to differ between 255 and -1). I usually use others peoples interpreters but this time I need to be a plug and promote my own:
```
jitbf --eof -1 -b 16 -c 200000000 random.bf < pg100.txt > pg100.txt.ran
jitbf --eof -1 -b 16 -c 200000000 random.bf < Glühwendel_brennt_durch.jpg > Glühwendel_brennt_durch.jpg.ran
```
jitfb compiles BrainFuck to optimized C and abuses perl Inline::C to run it. It's bundles with my [Extended BrainFuck compiler](http://sylwester.no/ebf/). With the cell size and width in the argument it will allocate about 400MB.
[Answer]
# CJam, 22 bytes
```
G,~q{5$H$+255%_@^o}/];
```
This uses a [lagged Fibonacci generator](https://en.wikipedia.org/wiki/Lagged_Fibonacci_generator) with recurrence relation **sn = (sn-5 + sn-16) % 255** (which I selected by mistake, but it works nevertheless) and a trivial seed to generate a pseudo-random stream of bytes, which it then XORs with the input.
I've tested my code with [CJam 0.6](https://sourceforge.net/projects/cjam/files/cjam-0.6/), which was published on May 1, 2014.
### How it works
```
G,~ e# Dump 0, 1, ... and 15 on the stack.
q e# Read from STDIN.
{ }/ e# For each character in the input.
5$H$ e# Copy the sixth and 19th element from the stack.
+255% e# Push their sum modulo 255.
_@ e# Duplicate and rotate the character on top.
^o e# XOR and print.
]; e# Clear the stack.
```
### Score
```
$ LANG=en_US
$ alias cjam='java -jar /usr/local/share/cjam/cjam-0.6.jar'
$ cjam thwart.cjam < pg100.txt > pg100.txt~
$ cjam thwart.cjam < pg100.txt~ > pg100.txt~~
$ diff -s pg100.txt pg100.txt~~
Files pg100.txt and pg100.txt~~ are identical
$ cjam thwart.cjam < Gluehwendel_brennt_durch.jpg > Gluehwendel_brennt_durch.jpg~
$ cjam thwart.cjam < Gluehwendel_brennt_durch.jpg~ > Gluehwendel_brennt_durch.jpg~~
$ diff -s Gluehwendel_brennt_durch.jpg Gluehwendel_brennt_durch.jpg~~
Files Gluehwendel_brennt_durch.jpg and Gluehwendel_brennt_durch.jpg~~ are identical
$ xz -kz5 pg100.txt~ Gluehwendel_brennt_durch.jpg~
$ wc -c thwart.cjam pg100.txt* Gluehwendel_brennt_durch.jpg*
22 thwart.cjam
5589889 pg100.txt
5589889 pg100.txt~
5589889 pg100.txt~~
5590232 pg100.txt~.xz
1659874 Gluehwendel_brennt_durch.jpg
1659874 Gluehwendel_brennt_durch.jpg~
1659874 Gluehwendel_brennt_durch.jpg~~
1660016 Gluehwendel_brennt_durch.jpg~.xz
28999559 total
```
[Answer]
# shell script, 203
```
id|gpg --batch --passphrase-fd 0 --personal-compress-preferences Uncompressed $1 $2
```
Running it:
```
% sh break.sh -c pg100.txt
% sh break.sh -d pg100.txt.gpg > pg100.txt-original
gpg: CAST5 encrypted data
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected
% diff -s pg100.txt pg100.txt-original
Files pg100.txt and pg100.txt-original are identical
% sh break.sh -c Glühwendel_brennt_durch.jpg
% sh break.sh -d Glühwendel_brennt_durch.jpg.gpg > Glühwendel_brennt_durch.jpg-original
gpg: CAST5 encrypted data
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected
% diff -s Glühwendel_brennt_durch.jpg Glühwendel_brennt_durch.jpg-original
Files Glühwendel_brennt_durch.jpg and Glühwendel_brennt_durch.jpg-original are identical
% xz -kz5 Glühwendel_brennt_durch.jpg.gpg
% xz -kz5 pg100.txt.gpg
% ls -ln
total 28340
-rw-r--r-- 1 1000 1000 84 May 24 04:33 break.sh
-rw-r--r-- 1 1000 1000 1659874 Jan 19 17:22 Glühwendel_brennt_durch.jpg
-rw-r--r-- 1 1000 1000 1659943 May 24 04:46 Glühwendel_brennt_durch.jpg.gpg
-rw-r--r-- 1 1000 1000 1660084 May 24 04:46 Glühwendel_brennt_durch.jpg.gpg.xz
-rw-r--r-- 1 1000 1000 1659874 May 24 04:46 Glühwendel_brennt_durch.jpg-original
-rw-r--r-- 1 1000 1000 5589891 May 24 03:55 pg100.txt
-rw-r--r-- 1 1000 1000 5589941 May 24 04:43 pg100.txt.gpg
-rw-r--r-- 1 1000 1000 5590284 May 24 04:43 pg100.txt.gpg.xz
-rw-r--r-- 1 1000 1000 5589891 May 24 04:43 pg100.txt-original
```
Not very portable, but could be made at the cost of a couple of bytes. Requires PGP (an implementation with OpenSSL would be possible, too). The ~50 byte difference between encoded file and original can probably be saved.
**Scoring:**
84 + abs(1659874 - 1659943) + max(1659874 - 1660084, 0) + abs(5589891 - 5589941) + max(5589891 - 5590284, 0) = **203**
[Answer]
# PHP, 117 + 0 + 0 + 0 + 0 = 117
Because would you really entrust the task of mangling your data beyond recognition to any other language?
```
<?=substr(gmp_export(gmp_invert(2*gmp_import($s=stream_get_contents(STDIN))+1,$m=2*gmp_pow(256,strlen($s)))/2+$m),1);
```
While all the other solutions are based on “secure” constructions like “random number generators” or “military-grade cryptography”, this one simply interprets strings as representing odd numbers modulo 2⋅256^length, and computes their [modular inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse).
Demo:
```
$ php thwart.php < 100.txt.utf-8 > 100.txt.utf-8~
$ php thwart.php < 100.txt.utf-8~ > 100.txt.utf-8~~
$ diff -s 100.txt.utf-8 100.txt.utf-8~~
Files 100.txt.utf-8 and 100.txt.utf-8~~ are identical
$ php thwart.php < Glühwendel_brennt_durch.jpg > Glühwendel_brennt_durch.jpg~
$ php thwart.php < Glühwendel_brennt_durch.jpg~ > Glühwendel_brennt_durch.jpg~~
$ diff -s Glühwendel_brennt_durch.jpg Glühwendel_brennt_durch.jpg~~
Files Glühwendel_brennt_durch.jpg and Glühwendel_brennt_durch.jpg~~ are identical
$ xz -kz5 100.txt.utf-8~ Glühwendel_brennt_durch.jpg~
$ wc -c *
5589889 100.txt.utf-8
5589889 100.txt.utf-8~
5590232 100.txt.utf-8~.xz
5589889 100.txt.utf-8~~
1659874 Glühwendel_brennt_durch.jpg
1659874 Glühwendel_brennt_durch.jpg~
1660016 Glühwendel_brennt_durch.jpg~.xz
1659874 Glühwendel_brennt_durch.jpg~~
117 thwart.php
28999654 total
```
[Answer]
# Python, score=183+7+6+0+0=196
The scoring penalizes you for making the file completely uncompressible, since then the compressed file is larger from the compression overhead. Thus my program makes them slightly less than totally uncompressible:
```
import sys
from random import randint as J,seed
x=sys.stdin.read()
seed(ord(x[1]))
n=int(2362*J(1,2)**2.359)
sys.stdout.write(x[:n]+''.join(chr(ord(c)^J(0,255))for c in x[n:]))
```
Result:
```
Laxori@Laxori-PC /cygdrive/f/Programming/lzkill
$ cat photo.jpg | python break.py > photo.jpg~; cat photo.jpg~ | python break.py > photo.jpg~~; diff photo.jpg photo.jpg~~; xz -kz5 photo.jpg~
Laxori@Laxori-PC /cygdrive/f/Programming/lzkill
$ cat pg100.txt | python break.py > pg100.txt~; cat pg100.txt~ | python break.py > pg100.txt~~; diff pg100.txt pg100.txt~~; xz -kz5 pg100.txt~
Laxori@Laxori-PC /cygdrive/f/Programming/lzkill
$ ls -l
total 28337
----------+ 1 Laxori mkpasswd 183 2014-05-24 13:43 break.py
----------+ 1 Laxori mkpasswd 5589891 2014-05-23 19:19 pg100.txt
-rw-r--r--+ 1 Laxori mkpasswd 5589891 2014-05-24 13:45 pg100.txt~
-rw-r--r--+ 1 Laxori mkpasswd 5589884 2014-05-24 13:45 pg100.txt~.xz
-rw-r--r--+ 1 Laxori mkpasswd 5589891 2014-05-24 13:45 pg100.txt~~
----------+ 1 Laxori mkpasswd 1659874 2014-05-23 19:19 photo.jpg
-rw-r--r--+ 1 Laxori mkpasswd 1659874 2014-05-24 13:44 photo.jpg~
-rw-r--r--+ 1 Laxori mkpasswd 1659880 2014-05-24 13:44 photo.jpg~.xz
-rw-r--r--+ 1 Laxori mkpasswd 1659874 2014-05-24 13:44 photo.jpg~~
Laxori@Laxori-PC /cygdrive/f/Programming/lzkill
$ python
Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 183 + abs(5589891-5589884) + abs(1659874-1659880)
196
```
] |
[Question]
[
**This question already has answers here**:
[Find the Squarish Root](/questions/167149/find-the-squarish-root)
(36 answers)
Closed 5 years ago.
Just a simple code golf function for fun, intentionally left open with few rules to see what creativity comes up.
**Input:** An integer representing the area of a rectangle.
**Output:** Two integers representing the side lengths of the rectangle that have the least perimeter for the area. (In any order.)
**Test cases:**
```
25 => 5, 5
53 => 53, 1
4294967295 => 65537, 65535
```
[Answer]
# Mathematica ~~34~~ 26
Besides the explicit search there is a nice convergent series:

```
n = 27
{i=√n//.i_:>n/⌈n/⌊i⌋⌉,n/i}
```
>
> {3, 9}
>
>
>
Three previous approaches with 34 characters:
```
{#,n/#}&@FixedPoint[n/⌈n/⌊#⌋⌉&,√n]
For[i=√n,i>(i=n/⌈n/⌊i⌋⌉),];{i,n/i}
f@i_:=f[f@i=n/⌈n/⌊i⌋⌉]
{i=f@√n,n/i}
ClearAll[f]
```
Visualization:
```
p = FixedPointList[n/⌈n/⌊#⌋⌉ &, Sqrt[n]];
Plot[n/x, {x, 0, 11}, GridLines -> {Range@n, Range@n},
AspectRatio -> Automatic, PlotRange -> {{0, 10.2}, {0, 7.2}},
Epilog -> {Red, Thickness[0.005],
Arrow[Transpose[{{n/p, ⌈p⌉}, {n/p, ⌊p⌋}, {⌈n/⌊p⌋⌉, ⌊p⌋}}, {2, 3, 1}]],
PointSize[0.02], Black, Point[{n/p[[-1]], p[[-1]]}]}]
```

[Answer]
## GolfScript (21 chars)
```
:^,{)^\%!},.,2/=)^1$/
```
This takes the input as a number on the stack and leaves the result as two numbers on the stack.
For fair comparison with Howard's solution, taking input on stdin and giving output on stdout separated by newline is **23 chars**:
```
~:^,{)^\%!},.,2/=)n^2$/
```
It works because this problem is trivial: it's just looking for the pair of factors closest to `sqrt(area)`.
[Online demo for a square](http://golfscript.apphb.com/?c=OzI1CjpeLHspXlwlIX0sLiwyLz0pXjEkLwpdcA%3D%3D); [online demo for a non-square](http://golfscript.apphb.com/?c=OzEwNQo6Xix7KV5cJSF9LC4sMi89KV4xJC8KXXA%3D).
[Answer]
# Python 2 (~~63~~ 62)
```
n=input()
print[(i,n/i)for i in range(1,n)if i*i>=n/i*i==n][0]
```
This produces all pairs of integers (i, n/i) that could be the sides of the rectangle, starting from the first one greater or equal to the square root of n. It prints the first one.
[Answer]
### GolfScript, 30 characters
```
~:t,{[.t\/].~*t=1$~>!&\@if}*n*
```
Does a test on all numbers as many other solutions.
[Answer]
**Golfscript (~~46~~ ~~43~~ 40)**
```
~1{..*2$>!}{1$1$%!{.@@}*)}while;1$/p p];
```
No way to beat the math oriented languages at this challenge I suspect :)
Somewhat "long winded", it would be shorter to work with arrays, sadly they get a bit large with the last test case.
Basically what it does is similar to the Python solution, it loops from 1..sqrt(n), testing for an even multiplier, then just displaying the last value found.
[Answer]
**C# (178)**
```
int[] R(int n){var a=Enumerable.Range(1,n);var b=a.SelectMany(x=>a.SelectMany(y=>a.Select(_=>new{x,y}))).Where(f=>f.x*f.y== n).OrderBy(f=>f.x+f.y).First();return new[]{b.x,b.y};}
```
Pretty
```
int[] R(int n)
{
var a = Enumerable.Range(1, n);
var b = a.SelectMany(x => a.SelectMany(y => a.Select(_ => new { x, y }))).Where(f => f.x * f.y == n).OrderBy(f => f.x + f.y).First();
return new[] { b.x, b.y };
}
```
[Answer]
# C, 54 bytes
```
f(x,y){for(y=sqrt(x);x%y;y--);printf("%d, %d",y,x/y);}
```
Just some general silliness.
Test if you like:
```
int main() {
printf("Enter a number\n");
int a;
scanf("%d", &a);
f(a);
printf("\n");
return 0;
}
```
[Answer]
## Java 8, ~~73~~ 72 bytes
Saved one byte due to @ThomasKwa!
```
n->{for(int i=(int)Math.sqrt(n);;i--)if(n%i<1)return new int[]{n/i,i};};
```
Lambda function, test with:
```
public class Rectangle {
interface Test {
int[] run(int v);
}
public static void main (String[] args){
Test test = n->{for(int i=(int)Math.sqrt(n);;i--)if(n%i<1)return new int[]{n/i,i};};
int[] testCases = {1, 4, 8, 15, 47, 5040, 40320, 25, 53};
for (int i : testCases) {
int[] result = test.run(i);
System.out.println(i + ": " + result[0] + ", " + result[1]);
}
}
}
```
Finds the greatest divisor less than or equal to the square root of the area. Returns an `int[]`.
[Answer]
## C# 4.0: 79 characters
```
long[] P(long a){long r=0,s=0;while(++s<a/s)if(a%s==0)r=s;return new[]{r,a/r};}
```
If it weren't for the last test case, I could save 3 characters naming `long` to `int`.
In pretty format:
```
long[] Perimeter(long area)
{
long result = 0;
long side = 0;
while (++side < area / side)
{
if (area % side == 0)
result = side;
}
return new long[] { result, area / result };
}
```
[Answer]
## C, 71 bytes
Nothing fancy, find the pair of integers `(a, b)` closest to `sqrt(n)` such that `a*b==n`:
```
f;x;L(n,a,b)int*a,*b;{for(f=0,x=sqrt(n);x;--x)n%x||f++?:(*a=x,*b=n/x);}
```
If the function is allowed to work only on first invocation, then we can shrink it to 67 bytes:
```
f;x;L(n,a,b)int*a,*b;{for(x=sqrt(n);x;--x)n%x||f++?:(*a=x,*b=n/x);}
```
Test main:
```
#include <stdio.h>
int main() {
int testdata[] = {1, 4, 8, 15, 47, 5040, 40320};
int x,y;
for (int i = 0; i < 7; ++i) {
L(testdata[i], &x, &y);
printf("%5d > %dx%d\n", testdata[i], x, y);
}
}
```
The code was originally written for [another golf](https://codegolf.stackexchange.com/q/66488), which is a duplicate of this.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
÷Ɱ½ĖḞƑƇṪ
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//w7fisa7CvcSW4biexpHGh@G5qv/Dh@KCrP//WzEwMDAsMjYsMjUsNDld "Jelly – Try It Online")
Use a bunch of new quicks. (`ƇⱮƑ`)
---
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ọⱮ½TṪð,÷@
```
[Try it online!](https://tio.run/##ATAAz/9qZWxsef//4buN4rGuwr1U4bmqw7Asw7dA/8OH4oKs//9bMTAwMCwyNiwyNSw0OV0 "Jelly – Try It Online")
A port of my [other answer](https://codegolf.stackexchange.com/a/167160/69850).
] |
[Question]
[
Another problem from our internal golfing...this one around the holidays last year.
## PROBLEM
Andy, Barb, Carl, Didi, Earl, and Fran are buying gifts for each other. Draw names for a gift exchange.
1. Each person buys one gift and receives one gift.
2. Nobody buys their own gift.
3. Running the solution multiple times should produce different results (giver-receiver pair should not be predictable or identical from run to run).
## INPUT
None.
## OUTPUT
Formatted as in this example:
>
> Andy buys for Barb
>
> Barb buys for Carl
>
> Carl buys for Didi
>
> Didi buys for Earl
>
> Earl buys for Fran
>
> Fran buys for Andy
>
>
>
[Answer]
## J, 57
```
(,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'
```
eg
```
(,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'
Carl buys for Earl
Andy buys for Barb
Fran buys for Didi
Didi buys for Fran
Barb buys for Andy
Earl buys for Carl
```
[Answer]
# Japt -R, 41 bytes
```
`AÌ)B¼C¤E¤FÎÂDi¹`qe ö¬ê1 ò mq` ¿ys f
```
-2 bytes thanks to @Oliver!
[Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=YEHMKUKHvEOHpEWHpEbOwkRpuWBxZSD2rOoxIPIgbXFgIL95cyBmjiA=&input=LVI=)
This is the approach I took at a high level:
* uncompress a string containing participants names
* split string into an array
* shuffle it
* assign each person to the person with the next highest index
* the last person in the array gets assigned to the first
I have a little history with this problem as I created a "secret santa" program for my work years ago. We ended up asking a few job applicants to work through it as well :)
[Answer]
c99 -- 252 characters
```
#include <stdio.h>
#define G for(i=0;i<6;i++)
char*n="Andy\0Barb\0Carl\0Didi\0Earl\0Fran",*p[7];int i,j;int main()
{FILE*r=fopen("/dev/random","r");G p[i]=n+5*i;G{j=fgetc(r)%6;p[7]=p[j]
;p[j]=p[i];p[i]=p[7];}G printf("%s buys for %s\n",p[i],p[(i+1)%6]);}
```
Slight improvement by taking advantage of the circular nature of the permutation. This version *always* builds a loop-like buying strategy, so it is less random than the previous (271 character) version, but I believe it still meets the spec.
Requires a platform that has a working `/dev/random`. I ought to be able to knock about 8 off by omitting the `\0`s in the big string, but my libc doesn't seem to be dealing with `%4s` print specifiers the way the man page says.
The shuffle is bad, but doing it that way prevents me from having to check on *"Foo buys for Foo"* conditions.
**Readable:**
```
#include <stdio.h>
char *n="Andy\0Barb\0Carl\0Didi\0Earl\0Fran",
*p[7]; /* 7th cell for temp */
int i,j;
int main(){
FILE*r=fopen("/dev/random","r");
for(i=0;i<6;i++)
p[i]=n+5*i; /* Initialize the pointers */
for(i=0;i<6;i++){
j=fgetc(r)%6; /* Poor numeric properties. Cest le Code Golf */
p[7]=p[j];
p[j]=p[i];
p[i]=p[7];
}
for(i=0;i<6;i++)
printf("%s buys for %s\n",p[i],p[(i+1)%6]);
}
```
[Answer]
## Windows PowerShell, 83
```
$i=random 5
($n=-split'Andy Barb Carl Didi Earl Fran')|%{"$_ buys for "+$n[++$i%6]}
```
History:
* 2011-02-11 22:01 **(136)** – First attempt.
* 2011-02-11 22:05 **(130)** – Inlined a few things. Shuffling the names now, not the indexes.
* 2011-02-13 16:13 **(128)** – I don't need the modulus as `$i` will be recreated every time.
* 2011-02-13 16:20 **(87)** – Borrowed the idea from [Anon.](https://codegolf.stackexchange.com/users/45/anon)'s [C# solution](https://codegolf.stackexchange.com/questions/838/holiday-gift-exchange/840#840). Just generate a random offset and then just let them gift in circles.
* 2011-02-13 16:26 **(83)** – Changed random number generation and indexing. Pulled `$_` into the string to save the `+`.
[Answer]
# Haskell, 241 189 characters
```
import Data.List
import Random
main=randomRIO(0,719)>>=mapM_ putStrLn.f
f n=map(\(x,y)->x++" buys for "++y).zip(l n).tail$cycle$l n
l=(permutations(words"Andy Barb Carl Didi Earl Fran")!!)
```
Fully random output (that still satisfies the spec).
This generates all permutations of the list of the names, picks one at random (I *think* this is the shortest way in Haskell to shuffle a list - if anyone has anything smaller, I'd appreciate it), and then each person then buys a present for the next person in the list.
[Answer]
## Golfscript: ~~72 64~~ 57 chars
```
"AndyBarbCarlDidiEarlFran"4/{;9rand}${.n+\' buys for '}%(
```
Tests
```
$ golfscript codegolf-838.gs
Fran buys for Carl
Carl buys for Andy
Andy buys for Barb
Barb buys for Didi
Didi buys for Earl
Earl buys for Fran
$ golfscript codegolf-838.gs
Didi buys for Earl
Earl buys for Andy
Andy buys for Barb
Barb buys for Carl
Carl buys for Fran
Fran buys for Didi
```
* Thanks gnibbler for `"AndyBarbCarlDidiEarlFran"4/`, updated and got 7 chars less
* 57 chars solution is basically by Nabb :D, and also noticed that `;9rand` is more random than my `6rand*`
[Answer]
## Python - 118 chars
```
from random import*;L="Andy Barb Carl Didi Earl Fran".split()
for i in sample(range(6),6):print L[i-1],"buys for",L[i]
```
**Python - 120 chars**
```
import random as R;L="Andy Barb Carl Didi Earl Fran".split();R.shuffle(L)
for i in range(6):print L[i-1],"buys for",L[i]
```
[Answer]
**R - 85 characters**
```
paste(n<-sample(c('Andy','Barb','Carl','Didi','Earl','Fran')),'buys for',n[c(6,1:5)])
```
[Answer]
## Python - 154 chars
```
import random as R;L="Andy Barb Carl Didi Earl Fran".split();M=L[:]
while any(map(str.__eq__,L,M)):R.shuffle(M)
for i in zip(L,M):print"%s buys for %s"%i
```
[Answer]
# D: 233 Characters
```
import std.random,std.stdio;void main(){auto p=["Andy","Barb","Carl","Didi","Earl","Fran"];auto q=p.dup;o:while(1){for(int i;i<6;++i)if(p[i]==q[i]){randomShuffle(q);continue o;}break;}foreach(i,a;p)writefln("%s buys for %s",a,q[i]);}
```
More Legibly:
```
import std.random, std.stdio;
void main()
{
auto p = ["Andy", "Barb", "Carl", "Didi", "Earl", "Fran"];
auto q = p.dup;
o:while(1)
{
for(int i; i < 6; ++i)
if(p[i] == q[i])
{
randomShuffle(q);
continue o;
}
break;
}
foreach(i, a; p)
writefln("%s buys for %s", a, q[i]);
}
```
[Answer]
## Python (175)
```
import random as r
n=['Andy','Barb','Carl','Didi','Earl','Fran']
m=n[:]
r.shuffle(m)
b=' buys for '
for i in n:
h=m.pop()
while h==i:
m.append(h)
h=m.pop()
print(i+b+h)
```
[Answer]
# Scheme, 173
Gives one of two solutions.
```
(define(m lst)
(printf"~v buys for ~v~n"(car lst)(cadr lst))
(if(eq?(cadr lst)'Andy)0(m(cdr lst)))
)
(m((if(odd?(random 2))reverse values)'(Andy Barb Carl Didi Earl Fran Andy)))
```
[Answer]
## C#, 210 183 characters
```
using System;class a{static void Main(){var n="Andy Barb Carl Didi Earl Fran".Split();var c=0,i=new Random().Next(1,6);for(;c<6;c++)Console.WriteLine(n[c]+" buys for "+n[(c+i)%6]);}}
```
Heaps of boilerplate :(
This solution isn't totally random - there are always one or more "loops" of people e.g. A->C->E->A, and the offsets are always the same in the loops. However, it is not possible to predict the output of a particular run unless you have part of that output.
[Answer]
# Ruby - 89 chars
```
(a=%w(Andy Barb Carl Didi Earl Fran).shuffle).zip(a.reverse).each{|e|puts e*' buys for '}
```
Output:
```
Andy buys for Didi
Barb buys for Earl
Fran buys for Carl
Carl buys for Fran
Earl buys for Barb
Didi buys for Andy
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 41 bytes
```
"δ%è╘+µ√♂JÇ"2/$╦╕ää▐δáw_╪" buys for "+m+n
```
[Try it online!](https://tio.run/##AUsAtP9tYXRoZ29sZv//Is60JcOo4pWYK8K14oia4pmCSsOHIjIvJOKVpuKVlcOkw6TilpDOtMOhd1/ilaoiIGJ1eXMgZm9yICIrbStu//8 "MathGolf – Try It Online")
## Explanation
This is not guaranteed to produce each case with equal probability, but it does produce different results each run. One byte could be removed if I had a shuffle operator, but that's for another day.
```
"δ%è╘+µ√♂JÇ" push the string "δ%è╘+µ√♂JÇ"
2/ split into segments of two characters
$ transform to ordinals using base 256
╦ fetch dictionary words (['Andy', 'barb', 'Carl', 'Earl', 'Fran'])
╕ää Push "didi"
▐ append to end of list
δ capitalize all strings in list
áw sort by random character in each string (shuffle)
_ duplicate TOS
╪ right-rotate bits in int, list, str
" buys for " push the string " buys for "
+ Add to all strings in list
m+ zip add the two arrays
n join array with newline
```
] |
[Question]
[
Your task is to make a program which interprets the language it is run in, but also works in many languages.
Let's say you make a Brainfuck-Underload self-interpreglot, as it will be called. Run in Brainfuck, this program should be a Brainfuck interpreter; run in Underload, it should be a Underload interpreter.
Your program should work like the hypothetical given above: given a list of languages L1, L2, L3, L4... up to Ln, it should be an L1 interpreter in L1, an L2 interpreter in L2, an L3 interpreter in L3, up to being an Ln interpreter in Ln.
Your program can handle errors in any way. However, it must never output to STDERR (or closest equivalent) if the input given for interpretation has no errors.
It must output to STDOUT (or closest equivalent) and take input from STDIN (or again, closest equivalent).
You can choose any interpretation of a given language, e.g. if your polyglot works in Brainfuck, it can interpret Brainfuck with finite or unbounded tape. You must specify what interpretations you choose to use for each language.
Programs must have at least 2 characters for this challenge to prevent empty programs from competing.
Functions such as exec and eval are allowed.
Only a Turing-complete subset of a language has to be interpreted.
Different languages have to be interpreted, not different language versions.
Your score is C/(L^3), where C is code length, computed in bytes with UTF-8 encoding, and L is the amount of languages. The lowest score wins: if two winning answers have the same score the one posted earlier wins.
Have fun.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [05AB1E](https://github.com/Adriandmen/05AB1E), [GolfScript](http://www.golfscript.com/golfscript/) 8 bytes, score = \$\frac 8 {27} \approx 0.296\$
```
.Vq;~
ɠV
```
[Try it online Jelly!](https://tio.run/##y0rNyan8/18vrNC6juvkgrD//w21jQA "Jelly – Try It Online")
[Try it online 05AB1E!](https://tio.run/##yy9OTMpM/f9fL6zQuo7r5IKw//8NFYy0AQ)
[Try it online GolfScript!](https://tio.run/##S8/PSStOLsosKPn/Xy@s0LqO6@SCsP//DRWMtAE "GolfScript – Try It Online")
In all cases, takes a program in the relevant language from STDIN and executes it, with any output going to STDOUT.
[Answer]
## [GolfScript](http://golfscript.com/)/[MathGolf](https://github.com/maxbergmark/mathgolf)/[CJam](https://sourceforge.net/projects/cjam/)/[Paradoc](https://github.com/betaveros/paradoc)/[FlogScript](https://esolangs.org/wiki/FlogScript), 1 byte, score = 1/125 = 0.008
For all stack-based languages, [input may be implicitly pushed onto the stack](https://codegolf.meta.stackexchange.com/a/8493/92069).
The most boring (yet probably the optimal) answer.
Going forward to see what is the most common character choice for an evaluation operator...
```
~
```
[TIO for MathGolf](https://tio.run/##y00syUjPz0n7r2RopK30v@7/fwA)
[TIO for CJam](https://tio.run/##S85KzP1fbahgpF37v@7/fy4A)
[TIO for GolfScript](https://tio.run/##S8/PSStOLsosKPlfbahgpF37P6fu/38A)
## What other languages have `~` as an evaluation built-in?
* [Microscript II](https://github.com/SuperJedi224/Microscript-II)
Not adding this language to the polyglot. Because I'm too lazy.
## Explanation
```
~ Evaluate the input
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg) and [Python 3](https://docs.python.org/3/), 19 characters, score = \$ \frac{19}{8} \$
```
exec(input())
"ø¿ß"
```
[Try it online! (Keg)](https://tio.run/##y05N//8/tSI1WSMzr6C0RENTk0vp8I5D@w/PV/r/39hYGwA "Keg – Try It Online")
[Try it online! (Python 3)](https://tio.run/##K6gsycjPM/7/P7UiNVkjM6@gtERDU5NL6fCOQ/sPz1f6/9/YWBsA "Python 3 – Try It Online")
Uses the same approach as Nick first did, but with Keg instead.
I'll have to figure out how to add another language to get competitive again.
[Answer]
# Clojure/Common Lisp/scheme/bash/ksh/posix sh/zsh/csh/yash/tcsh, ~~34~~ 33 bytes, score = 33/1000 = 0.033
*as low as 0.000327480423 points, see comment*
```
"w";eval $SHELL;exit
(eval(read))
```
[Try it online!](https://tio.run/##S0oszvj/X6lcyTq1LDFHQSXYw9XHxzq1IrOESwMkolGUmpiiqfn/f0F5CgA)
Alternative for 31 bytes but does not work on clojure:
```
"w";eval $SHELL
#x1(eval(read))
```
Use (print "hoo") as input and it should work for all lisps.
Try pwd for shells.
## lisp
Simple. These lisp dialects seem to all be similar enough to all work for this.
Unfortunately, there is not a TIO for scheme. The only one of these I know is Common Lisp, which I am still learning.
Are the different implementations of CL different enough to be counted separate? Because then. . .
## shells
Just evaluates itself, then exits so it won't try to do the lisp part.
[Answer]
## [GolfScript](http://www.golfscript.com/golfscript/index.html)/[Keg](https://github.com/JonoCode9374/Keg), 6 bytes, score = 3/4 = 0.75
Do we have to use at least one practical language? It doesn't seem to say that in the spec.
```
ß.~\;
```
## Golfscript
```
ß # Odd undefined ops
. # Copy the input
~ # Evaluate it
\; # Discard the unevaluated copy
```
## Keg
```
ß # Take input & evaluate the input
. # Output the result as a number
~ # Push a random number
\; # Escape the ; character
```
[Answer]
# [PHP](https://php.net/)/[Python 3](https://docs.python.org/3/)/[Javascript](https://developer.mozilla.org/he/docs/Web/JavaScript), 130 bytes, score = 130/27 ~ 4.814
```
[1//eval(input())
];eval("\x24a=\"/\";eval(`\x24{\x24a}/bin/echo 'eval(fgets(fopen(\"php://stdin\",\"r\")));'`);eval(prompt());");
```
[Try it online - PHP](https://tio.run/##JY3BCsIwEETvfoXspVkUlogno/ZDXKFVUxvQZGnTIojfHtv0MjBv4I20ko6lTHnRRHasX8p5GaJCXF1N7sCf3b4@MRDDQqqZfDP@0c15svc2rIu8NU8be9UEsV4xTOIDUR8fzjNsGToGRDRFhYtJuvCW@cwAmlSeUzbpjTZ/ "PHP – Try It Online")
[Try it online - Python 3](https://tio.run/##Jc3BCsIwEATQu18he2kWhcXoyeCXuEKrpiagmyWNoojfHml7nDcwo58SkmxrPW6I/Ku7myj6LAZxcXJTBn7bXXdgIIZZ2lG@E//oHIX8JaRlM3X9zZfB9Em9GAYNuicayjUKw5ohMyCia1qclzSnh45nDtDVqjlKMXZl8Q8 "Python 3 – Try It Online")
For javascript run it in the browser's console, as prompt is not defined in node.
NOTE - you can also put a brainfuck+ook self interpreter in there but it's too big.
Explanation:
Python - the // operator is integer division, so the interpreter tries to calculate it, so it executes eval(input()), and then it errors out (which is allowed according to [Should submissions be allowed to exit with an error?](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error)).
Javascript - the // is interpreted as a comment, so it gets the array [1]. Then it evals
```
$a="/";eval(`${$a}/bin/echo 'eval(fgets(fopen("php://stdin","r")));'`);eval(prompt());
```
And, then
```
`${$a}/bin/echo 'eval(fgets(fopen("php://stdin","r")));'`
```
evaluates to `//bin/echo 'eval(fgets(fopen("php://stdin","r")));'`, which then gets executed and ignored (as a comment), and then it runs `eval(prompt())` to execute the input.
PHP - `//eval(input())` is interpreted as a comment, so it get's the array [1] like in JS and does nothing with it. Then it evals
```
$a="/";eval(`${$a}/bin/echo 'eval(fgets(fopen("php://stdin","r")));'`);eval(prompt());
```
but in here
```
`${$a}/bin/echo 'eval(fgets(fopen("php://stdin","r")));'`
```
Is executed from the shell, and translates to `//bin/echo 'eval(fgets(fopen("php://stdin","r")));'` which returns `eval(fgets(fopen("php://stdin","r")));`. Then that gets evaled, which executes the code from the input. then it tries evaluating `prompt()` which doesn't exist and errors out.
PS - This is my first post here, so if I've done anything wrong/missed something please let me know.
] |
[Question]
[
[The robber's thread is here](https://codegolf.stackexchange.com/q/175366/76162)
The cops task is to write a function or program that, when given an input of itself, outputs a finite deterministic string. If the program is given a different input, it should return a different output.
## Rules:
* Submissions consist of
+ Language name
- If any flags are used, they should be revealed.
+ Byte count of program
+ Byte count of output
+ Output
- If it is particularly long, please provide a pastebin or something similar
- If it contains unprintables, please provide a hexdump.
- Trailing newlines and whitespace should be included in the output
+ Where the input is coming from (STDIN, command line, [etc.](https://codegolf.meta.stackexchange.com/q/2447/76162))
* If applicable, you may assume that the byte representing EOF is not present in the input, unless you use that byte in your program.
* If your program is cracked, add a link to the corresponding answer in the robber's thread in your title.
* Your program is not safe until a week has passed and you mark it so.
* I disapprove of techniques like seeding random with the input or cryptographic hash functions. I can't stop them, but **I will not be accepting a solution that utilises either of these**. Also note that some of these techniques might have collisions, where a different string produces the same output.
* Your goal is to have the shortest output. The shortest safe solution posted within three weeks of posting this question wins!
The robber's task is to find a program of size equal to or less than the original, which also obeys the above rules.
If a robber cracks your program with a different solution than intended, then you have the opportunity to 'uncrack' it by proving that the robber's solution is incorrect. You can do this by finding an input to the robber's program that will produce the same output.
## Example Submission:
### brainfuck, 10 bytes, Score: 10
```
]<.[<],>[,
```
This solution is [,[>,]<[.<]](https://tio.run/##SypKzMxLK03O/v9fJ9pOJ9YmWs8mFpkNAA) which simply reverses the input
Good luck!
[Answer]
# [7](http://esolangs.org/wiki/7), 31 characters, score 30, safe but possibly broken?
A 7 program is normally just a number, but it can contain whitespace, splitting it into multiple numbers. This submission therefore consists of two numbers (which are implicitly concatenated by the 7 interpreter), and the program likewise takes two numbers as input, via standard input. (The "31 characters" in the header is the total length of the two numbers, plus one separating whitespace character; the digits that make up the numbers are interpreted as octal when used as a program, but decimal when used as an input, and it's the digits that are the same in the two cases, not the actual numbers. Note that it's irrelevant either when treated as a program, or when treated as an input, whether you separate them with a space or a newline; I hope that doesn't invalidate the submission.)
The expected output is the following number (expressed here in decimal, as that's the output format that the 7 interpreter uses):
```
238363505302130098723162537059
```
Note that the 7 interpreter linked from the Esolang wiki internally stores numbers in unary, meaning you're unlikely to have enough memory to actually run the program on itself to see what it does. I verified the program via working out its behaviour manually, and testing it on small inputs to verify that it did what I expected it to do. An alternative approach would be to write an interpreter that uses a more efficient method of storing numbers.
Avoiding cracks here was something of a pain, but I'm finally now satisfied that no two numbers other than those in the program itself are capable of producing 238363505302130098723162537059 as output. (*EDIT 1 week later: I may have been wrong, depending on how you interpret the question; see below.*)
## Solution
The original program was:
>
>
> ```
> 711170237403706
> 111723603700633
> ```
>
>
> This program takes two numbers \$x\$ and \$y\$, and calculates the result of the expression \$3xy-y-2\$ (i.e. \$y(3x-1)-2\$). If we perform this calculation at \$x=711170237403706\$ and \$y=111723603700633\$, [we get a result of \$238363505302130098723162537059\$ as required](https://tio.run/##K6gsycjPM/7/v0LBVsHc0NDQ3MDI2NzEwNjcwIyrEigGEjIyNgMJGJgZG3MVFGXmlWhUamkYa1XoGmrqGmn@/w8A).
>
>
>
It was intended that no other input will give the desired result because:
>
> The input must be chosen such that \$y(3x-1)-2=238363505302130098723162537059\$, i.e. \$y(3x-1)=238363505302130098723162537061\$ (adding 2 to both sides). This number is a semiprime, with only two factors: \$111723603700633\$ and \$2133510712211117\$. Only one of these numbers, \$2133510712211117\$, can be expressed in the form \$3x-1\$ (giving \$(3 \times 711170237403706)-1=2133510712211117\$). So we can uniquely identify which number is \$x\$ and which is \$y\$, meaning that only one input works.
>
>
>
However, depending on how you interpret the question, there may be a second input that produces the desired output (thus invalidating this solution):
>
> Unfortunately, there are two multiplicative partitions of a semiprime into two factors: one is to divide it into the two prime factors, but the other is the trivial partition consisting of \$1\$ and the number itself. \$1\$ cannot be written in the form \$3x-1\$ with integer \$x\$, but the desired output can be; thus a potential meta-crack involves giving the input as \$79454501767376699574387512354\$ and \$1\$. However, the first number here involves characters (\$8\$ and \$9\$) which are not in the character set for 7 programs. So if input is restricted to being in the same character set as the program, this solution is valid; but if input containing characters from outside the program's character set is allowed, this solution is invalid.
>
>
>
## Explanation
Here's how the intended solution functions:
>
>
> ```
> 711170237403706 111723603700633
> 7 7 7 Stack element separators
> 111 023 403706 111723603700633 Initial stack elements
> 111 Number 3, in unary
> 023 I/O DSL for "input a number"
> 403706 111723603700633 Main program
> (Implicit: execute a *copy* of the main program element, preserving the original)
> 40 Swap {023} above {program}, escaping it
> 3 Do I/O using {023}; pop {program}
> 0 I/O: numeric
> 23 Input a number, copying {111} that many times
> 706 Append "6" to the number (decrementing it)
> 11 Push two empty stack elements
> 17236 Push a stack element "23" (unescaped)
> 0 Escape {23}, consuming an empty element
> 3 Do I/O using {23}; pop {the element below}
> 23 Copy the top of stack *input* many times
> 7006 Append "66" (i.e. subtract 2)
> 3 Output {as a number}
> 3 Exit the program (due to low stack)
> ```
>
> The leading 7 and trailing 3 aren't necessary for the program's functionality, they're just there to get the prime factors of the output right. It helps to follow this program if you understand the numeric format; numbers are stored in a unary variant in which `1` and `7` increase the value by 1, and `0` and `6` decrease the value by 1 (thus appending `66` decreases the value by 2, repeating the number multiplies it, and so on). Input's done by repeating a stack element (thus if the stack element is `12345` and the input is \$3\$, the new stack element will be \$123451234512345\$).
>
>
>
[Answer]
# [Node.js v10.9.0](https://tio.run/#javascript-node), 40 bytes, Score: 40, [Cracked](https://codegolf.stackexchange.com/a/175441/58563)
### Input
This is a function taking exactly one parameter.
### Output
```
&`nij.9=j.,)r31n=+(=ooj`[o.o.)1.s](>=6>t
```
[Answer]
# [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree), 46 bytes of ASCII, score 0, [Cracked](https://codegolf.stackexchange.com/a/175965/76359)
Input is taken from standard input. The expected output (on standard output) is an empty string (i.e. when the program is given itself as argument, no output should be printed).
In other words, the challenge here is to write an A Pear Tree program that does not output anything on standard output when given itself on standard input, and which does output something on standard output when given something other than itself on standard input, using no more than 46 bytes. (I've managed to do this while holding the program to printable ASCII, too, despite A Pear Tree frequently using non-ASCII and unprintable characters.) This is effectively the task of writing a [self-identifying program](https://codegolf.stackexchange.com/questions/11370/write-the-shortest-self-identifying-program-a-quine-variant), with a specific output format (i.e. null string when self-identification succeeds); however, A Pear Tree has at least two twists that make the task somewhat more difficult than it looks when done in this specific language (which is why I chose it for my cop submission).
## My solution
My solution is a bit different from the crack:
```
eval(k=q(print$\=$_="eval(k=q($k))"ne$_;MZpa))
```
[Try it online!](https://tio.run/##S9QtSE0s0i0pSk39/z@1LDFHI9u2UKOgKDOvRCXGViXeVgkuqJKtqamUl6oSb@0bVZCoqUmqegA "A Pear Tree – Try It Online")
Instead of using `exit`, I instead set `$_` (implicit output) and `$\` (newline after output, including implicit output) to the null string if there's a match (and to `1` if there's no match). A `print` is still required because implicit output is only enabled if there's at least one byte of input (thus, we need to explicitly print something if we're given an empty string as input, which is distinct from the program).
Every A Pear Tree program needs to contain a checksum somewhere (that's the `MZpa` in this solution). Both my solution and the crack pick variable names (and vary other minor details of the code) in order to make the checksum consist entirely of ASCII letters.
[Answer]
# Perl 5 `-p0777`, 10 bytes, score 10, safe
```
W)9r46<(k
```
The last character here is "shift out", character code 14 (decimal) / 0E (hex). All the others are printable ASCII.
Because we're using Perl's implicit I/O argument `-p0777`, the input is coming from standard input, and the output going to standard output.
## Solution
The program does the following:
>
> NUL-pads the input to at least 10 characters, then XORs with the string `svgOUT_TOP`
>
>
>
which means that the program itself, the only input producing the desired output, is:
>
>
> ```
> $_^=abc|$^
> ```
>
>
>
>
[Try it online!](https://tio.run/##K0gtyjH9/18lPs42MSm5RiUOmf0vv6AkMz@v@L9ugYG5uTkA "Perl 5 – Try It Online")
### Explanation
>
> Perl has a number of special-purpose variables. For example, when using `-p0777` for implicit I/O, `$_` is input at the start of the program and output at the end of the program.
>
> Most of these variables have a very simple default value. However, the default value of `$^`, the currently selected top-of-page format, is the much longer string `STDOUT_TOP`. As such, we can use this as a very terse obfuscation method via XORing `$^` with the value we want to obfuscate (in this case, the program).
>
> In order to hide the telltale `_TOP` at the end, I padded the program itself out to 10 characters via adding in an `abc|`, meaning that all the characters of `STDOUT_TOP` would be XORed with something; the choice of `abc|` at the start was an easy way to keep the output mostly printable (and to make it harder to spot that I was XORing with a string made mostly of capital letters, because in ASCII, lowercase XOR uppercase is lowercase).
>
>
>
>
>
[Answer]
# Python 3, 50 bytes [cracked](https://codegolf.stackexchange.com/a/196430/60483)
Input and output from/to stdin/-out. Output is different for each and every different input. Unique output when given the source code:
```
218216195196222130136136132192197195196130241204136209197216206130201131244155157154215136138204197216138201138195196138195196218223222130131247131131
```
(That’s 150 digits)
Good luck!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 35 bytes, Score: 7
**Input:**
From `stdin`
**Output:**
`QÕ
Ƿe`
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 18 bytes, Score 18, safe
It's a shame that this challenge didn't get more attention, but that's the way it goes sometimes. I was going to leave this unsafe, but decided to post the solution before I forgot about it.
This should be quite easy to crack.
**Input** from `stdin`
**Output**
```
$`*2aJPJ#74(o);89
```
**Edit:** I should mention that this expects the source in it's shortened form ... and now I've noticed that there is a missing byte (unprintable) from the result that I broke when I posted. Should copy out now. The hex values are `24 60 2a 13 32 61 4a 50 4a 23 37 34 28 6f 29 3b 38 39`
The concept was to remove print the first character and then remove the inverse index from the character, eg [chars]-[0,len([chars])..2]
The code is
```
$r;#AoW\U-@</u.?;;
```
which maps onto the following cube
```
$ r
; #
A o W \ U - @ <
/ u . ? ; ; . .
. .
. .
```
[Try it here](https://ethproductions.github.io/cubix/?code=JHI7I0FvV1xVLUA8L3UuPzs7&input=JHI7I0FvV1xVLUA8L3UuPzs7&speed=20)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes, Score: 21, Safe
Both the program and output size are counted using Jelly codepage.
### Input
First command-line argument.
### Output
```
-§ḋẇ"*YdĖDƘ>Ẉed€Ç+æạɦ
```
---
### Solution
```
ØJiⱮÄÆNPḃØ⁵ịØJ
```
[Try it online!](https://tio.run/##y0rNyan8///wDK/MRxvXHW453OYX8HBH8@EZjxq3PtzdDRT/j1cWAA "Jelly – Try It Online")
[Answer]
# JavaScript Firefox, <10 bytes, Score: 52, from function argument input, [Cracked](https://codegolf.stackexchange.com/a/175395)
```
ZnVuY3Rpb24gYnRvYSgpIHsKICAgIFtuYXRpdmUgY29kZV0KfQ==
btoa
```
`btoa(btoa)` encodes the following string:
```
function btoa() {
[native code]
}
```
which gives:
```
"ZnVuY3Rpb24gYnRvYSgpIHsKICAgIFtuYXRpdmUgY29kZV0KfQ=="
```
just copied
[Answer]
# GCC 61->61 bytes
```
70 4F 92 73 08 D4 03 E7 65 DC D6 89 B5 AD BA 90
97 26 31 10 F6 FA 0A 30 8F 24 69 0A A7 8B 59 9E
A2 42 D5 67 B8 12 3A 1E 9D 25 80 F9 6B 25 32 C2
EE 46 3F 8D 7E 0C 73 0F F0 93 C6 68 50
```
Full program, take input from stdin and output to stdout
[Answer]
# Perl 6, 43 bytes, Score: 15, from stdin
```
49671296789805
```
[Answer]
# [Pepe](https://github.com/Soaku/Pepe), 23 bytes, score: 23, [cracked by MickyT](https://codegolf.stackexchange.com/questions/175366/transformers-in-disguise-robbers-thread/176552#176552)
**Input:**
standard
**Output:**
```
RDCbn@?K]<[G98765TSR^PO
```
[Answer]
# [J](http://jsoftware.com/), 26 bytes, Score: 52, Safe
The program is not a REPL, but a full script that accepts `stdin` and explicitly prints to `stdout`.
### Input
Standard input.
### Output
```
6fc42353c98217ef5a2908a3c63d090aa9a55b2558b61294e06a
```
No, it's not an encryption method.
---
### Solution
```
echo]hfd]257x#.3&u:stdin''
stdin'' Take the whole input
3&u: Convert to codepoints
257x#. Convert base 257 to integer
hfd] "Hex from Decimal"
echo] Print to stdout
```
[Try it online!](https://tio.run/##y/r/PzU5Iz82Iy0l1sjUvEJZz1it1Kq4JCUzT10dnxwA "J – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 6 bytes, Score: 6
**Input**
From `stdin`, using `?`
**Output**
```
5\x1c"\x1c"9
```
Mind you that those are escape sequences for unprintable bytes. Replace the escapes with the literal chars. [Raw text available here](https://tio.run/##K6gsycjPM/7/31RGSUbJ8v9/nWg7nVibaD2bWAA "Python 3 – Try It Online")
Good luck with this one! See y'all next week!
[Answer]
# Perl 6, 31 bytes, Score: 39, from stdin - Cracked
[**Cracked here**](https://codegolf.stackexchange.com/a/175440/66624)
```
().1111111111112222235abcegijkmnorstvy
```
Crude solution. Might survive.
] |
[Question]
[
An isolated character is a character (other than a newline) that doesn't have an adjacent character of the same type. Adjacent characters can be to the left, the right above or below, but not diagonals. For example in the following text `H` is isolated:
```
Ybb
YH%
%%%%
```
All the other characters are not isolated because each of them has at least one other character of the same type adjacent.
Your task is to write a program that takes a string as input and determines the number of isolated characters.
## Scoring
You answer will be scored by two metrics. The first is the number of isolated characters in your program. You should aim to minimize this. The second will be the number of bytes in your program. You should minimize this as well. Program size will act as a tie breaker for the first criterion.
## Additional Rules
* You should support input on the printable ascii range plus any characters you use in your program.
* You may consider a line break to either be a newline character or a newline followed by a line feed.
* You may take input in any reasonable format. This includes a list of lines.
## Test Cases
```
Ybb
YH%
%%%%
```
\$1\$
---
```
Aaaab
uuu
yyybbb
```
\$2\$
---
```
A
```
\$1\$
---
```
qqWWaaww
```
\$0\$
[Answer]
# [Python 2](https://docs.python.org/2/), 0 (~~350~~ ~~344~~ ~~314~~ ~~309~~ ~~301~~ ~~298~~ 291 bytes)
```
def f(tt):11
def f(tt):
tt=tt.split('\n')
r =0#.split('\n')
#r 0#
#for
for ii,ll in enumerate(tt):
for jj,cc in enumerate(ll):
##for+=1-(
r+=1-(cc in ll[(jj or 2)-1:jj+2:2] +''.join(ll[jj:
jj+1]for ll in tt[(ii or 2)-1:ii+2:2]))##+''.join(ll[jj:
# +1]for
#print r
print r
```
[Try it online!](https://tio.run/##7VHNasMwDL77KURNSUza0uQYyGG3PcCglKwHu3OojeekjkLJ02dKPLp2l73AfDCSvh/ZUjfipfXFNH3oBpoUUZR5zn4SBogV4q7vnME0efeJYBCg2vOnEg8Ae8540wYGdAEYs3EOjAfth08dJOpvvwW2dnM@P6POEcpnh6zKtykRAWIYmc7VqbVA4kJs89LarCiL08zKkmRnW@PJoraWWhCWn@Y28QWIdWrMXWnMohSC899KTmZRyXgXjEeg79yDqUlXq9VRKXZ8XbM1HUoFY0v5RUqp2DAMbBxHpdQj9BBfr4eDlLdbLEVrGuGb7hF67ZoymYmB4P@F/LmQeYjTFw "Python 2 – Try It Online")
-7 bytes, thanks to Jo King
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 0 (~~439~~ ... 415 bytes)
*-11 thanks to Ørjan Johansen*
Finally a challenge where I can score 0 with Clean!
(and normally it's *bad* at source-layout challenges!)
```
//module
module d
import StdEnv,ArgEnv,Data.List,Data.Maybe
import StdEnv,ArgEnv,Data.List,Data.Maybe
Start=sum[1\\i<-l&v<-[0..],_<-i&u<-[0..]|all((<>)(?u v))[?(u-1)v,?(u+1)v,?u(v-1),?u(v+1)]]
Start=sum[1\\i<-l&v<-[0..],_<-i&u<-[0..]|all((<>)(?u v))[?(u-1)v,?(u+1)v,?u(v-1),?u(v+1)]]
l=mklines[c\\c<-:getCommandLine.[1]]
l=mklines[c\\c<-:getCommandLine.[1]]
?x=mapMaybe(\k=k!?x)o(!?)l
?x=mapMaybe(\k=k!?x)o(!?)l
```
[Try it online!](https://tio.run/##tZFBa4NAEIXv/oqJh7BL1dRr0UpoeihYKOSoUkbdmMXdVXTXRuhvrzWac2kPPX3z3jyGYaYQDNW020HHWoEFA1siVzZ8cH0Gu7SBKxgb08GZYTnnZFMawcACuFXXuMVl23Qajrp8VoOz76orDqjRi3mv1@oVx5z9IXnU2OmwNzLx05QHrtgOgZvce17mvAcu35qb@kQhCAkeKYkMDJQmETGuTwdn5t1CQ4bZWDgbWfaPo8ESoawFV6xPijQtAvehYvqpkRJVGc@2l/jzAr8KRZdQYrscg6R1WG@iC23IJqLih9Y0TXtEzC1jjDWOY57nX8VJYNVP7ks8HUaFkhereBOoT00nF7G@4hs "Clean – Try It Online")
The TIO link uses `module main` due to the way Clean is implemented on TIO, but `module d` will work if you name the file `d.icl` instead of `main.icl` as TIO does.
One of the old lines explained (new version is the same thing in a different order):
```
Start // entry point
= let // define locals
l = mklines // `l` is argument split at newlines
[c \\ c <-: getCommandLine.[1]]; // the second command-line arg turned into a [Char]
? x y // function ? of coordinate (x,y)
= mapMaybe // if the argument isn't Nothing
(\k = k!?x) // try taking the `x`-th index
(l!?y) // of the `y`-th index of `l`
in // in the context of
sum [ // the sum of
1 // the integer one
\\ i <- l & v <- [0..] // for every index in `l`
, _ <- i & u <- [0..] // for every subindex in `l`
| all ( // where all of the second argument
(<>)(?u v) // doesn't equal the first argument
) [?(u-1)v, ?(u+1)v, ?u(v-1), ?u(v+1)] // over every adjacent element
]
```
[Answer]
# JavaScript (ES6), 0 (154 bytes)
*Saved ~~2~~ 4 bytes thanks to @ØrjanJohansen*
Takes input as an array of strings.
```
s =>
s//=>(s,y,a
.map((s,y,a)=>[...s]
.map((c,x )=>[...s]
&&//++c,x
s[x+1]==c|
s[x-1]==c|
(a[y-1]||0)[x]==c|
(a[y+1]||0)[x]==c||
i++),i=0)
&&i//),i=
```
[Try it online!](https://tio.run/##dZDNjsIgFEb3PAUbLQQK@gA0cecbmAnp4rajphO1OkzHkvTdKxZGqmNZfZz7Qzhf8Aum/K7OP@mp/tz2O9UbjFWGjJQqI4ZbDkgc4Ux8pirTQgiTB1jyFuMI53MpGXMQYaNbtsyVKrshpyET0NblrltQ3UbEnpAbwRVjlFdqQd3SSsp77sv6ZOrDVhzqPdkR7bqSj6JI@BDWMx9m7iQopxS9aV8BQBhomsYHa23htkyOTFYul80G4HqdbBhU@kdGPj14J3VceTbrKw@9/jpyHEE6Bv9tR/6iPGyI3v@eDPKHT/Y3 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 0 (~~41 27~~ 25 bytes)
```
ŒĠạþ`€Ẏ§CẠ€S
ŒĠạþ`€Ẏ§CẠ€S
```
[Try it online!](https://tio.run/##y0rNyan8///opCMLHu5aeHhfwqOmNQ939R1a7vxw1wIgO5gLt9T/h7u3HG7//19dXd3R0crRkcuJy9EJyAEA "Jelly – Try It Online")
Takes input as list of lines. The first line in the code never does anything and is only there to minimize isolated characters.
```
ỴŒĠạþ`€Ẏ§1eⱮCS
Ỵ Split the text on newlines.
ŒĠ Group the multidimensional indices by their value.
€ For each list of indices:
ạ Take the absolute difference...
þ` ...between each pair.
Ẏ Concatenate the lists of differences.
§ Sum the x & y differences. This computes the Manhattan distance.
At this point we have a list for each character in the text of
Manhattan distances between it and it's identical characters.
1eⱮ Is there a 1 in each of the lists? None for isolated characters.
C Complement: 0 <-> 1.
S Sum. Counts the isolated characters
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 0 (54 bytes)
```
TTTTf"Go@X!0JQJ&(d@_X!]***ggss
%%%%f"Go@X!0JQJ&(d@_X!]
```
Input is a cell array of strings, one for each line: `{'line 1', 'line 2', 'and line 3'}`.
[Try it online!](https://tio.run/##y00syfn/PwQI0pTc8x0iFA28Ar3UNFIc4iMUY7W0tNLTi4u5VIEAi/T//9XqkUlJ6joK6pEeqiAKpFC9FgA) Or [verify test cases and source code](https://tio.run/##y00syfmf8D8ECNKU3PMdIhQNvAK91DRSHOIjFGO1tLTS04uLuVSBAIv0f5eoipD/1eqRSUnqOgrqkR6qIAqkWL2Wq1rdMTExESxRWloKoiorK5OAKsFSYLKwMDw8MbG8HMzB7wSYwVhUqNcCAA).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 0 (101 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
žGçU|€SXζζD"εγεDgDisëXи]"©.V˜sø®.V€Sø˜‚øʒË}ʒXå≠}gq
žGçU|€SXζζD"εγεDgDisëXи]"©.V˜sø®.V€Sø˜‚øʒË}ʒXå≠}gq
```
[Try it online.](https://tio.run/##yy9OTMpM/f//6D73w8tDax41rQmOOLft3DYXpXNbz20@t9Ul3SWz@PDqiAs7YpUOrdQLOz2n@PCOQ@v0wkAqD@84PedRw6zDO05NOtxde2pSxOGljzoX1KYXclHXuP//I5OSuCI9VLlUgQAA)
This is one of the ugliest and longest 05AB1E programs I've ever written.. >.> This challenge is deceivingly hard in 05AB1E. I have no doubt in mind the byte-count can at least be halved or even three/four times as small by using a different approach (or even with a similar approach), but I currently don't see how. I'm just glad it's working right now.. If someone else posts a much shorter 05AB1E answer with some smart tricks I'll probably delete this answer out of shame... xD
**Explanation:**
```
žGç # Character with unicode 32768 ('耀')
U # Pop and store it in variable `X`
# (This character is not part of the printable ASCII, nor of my 05AB1E code)
| # Take the multi-line input as list
# i.e. "Ybb\nYH%\n%%%%" → ["Ybb","YH%","%%%%"]
€S # Convert each string to a list of characters
# i.e. ["Ybb","YH%","%%%%"] → [["Y","b","b"],["Y","H","%"],["%","%","%","%"]]
Xζζ # Zip with character `X` as filler twice to make the lines of equal length
# i.e. [["Y","b","b"],["Y","H","%"],["%","%","%","%"]]
# → [["Y","b","b","耀"],["Y","H","%","耀"],["%","%","%","%"]]
D # Duplicate this list
" " # Create a string
© # Which we store in the register (without popping)
.V # And execute that string as 05AB1E code
ε # Map each inner list to:
γ # Split in chunks of the same characters
# i.e. [["Y","b","b"],["Y","H","%"],["%","%","%","%"]]
# → [[["Y"],["b","b"]],[["Y"],["H"],["%"]],[["%","%","%","%"]]]
ε # Map each of those to:
D # Duplicate the current inner list
gDi # If its length is exactly 1:
s # Swap so the mapping keeps the duplicated single character (as list)
ë # Else:
Xи # Take character `X` repeated the length amount of times
# i.e. ["%","%","%","%"] (length 4) → ["耀","耀","耀","耀"]
] # Close the if-else and both maps
˜ # Flatten the list to a single list of characters
# i.e. [[["Y"],["耀","耀"],["耀"]],[["Y"],["H"],["%"],["耀"]],[["耀","耀","耀","耀"]]]
# → ["Y","耀","耀","耀","Y","H","%","耀","耀","耀","耀","耀"]
s # Swap so the duplicate list is at the top of the stack
ø # Swap its rows and columns
# i.e. [["Y","b","b","耀"],["Y","H","%","耀"],["%","%","%","%"]]
# → [["Y","Y","%"],["b","H","%"],["b","%","%"],["耀","耀","%"]]
®.V # Execute the same piece of code again that we've stored in the register
€S # Convert each to a list of characters
# i.e. [[["耀","耀"],["%"]],[["b"],["H"],["%"]],[["b"],["耀","耀"]],[["耀","耀"],["%"]]]
# → [["耀","耀","%"],["b","H","%"],["b","耀","耀"],["耀","耀","%"]]
ø # Swap its rows and columns back again
# i.e. [["耀","b","b","耀"],["耀","H","耀","耀"],["%","%","耀","%"]]
˜ # Flatten this list as well
‚ # Pair both lists together
# i.e. [["Y","耀","耀","耀","Y","H","%","耀","耀","耀","耀","耀"],
# ["耀","b","b","耀","耀","H","耀","耀","%","%","耀","%"]]
ø # Swap its rows and columns to create pairs
# i.e. [["Y","耀"],["耀","b"],["耀","b"],["耀","耀"],["Y","耀"],["H","H"],["%","耀"],["耀","耀"],["耀","%"],["耀","%"],["耀","耀"],["耀","%"]]
ʒË} # Filter out any inner lists where both characters are not equal
# i.e. [["耀","耀"],["H","H"],["耀","耀"],["耀","耀"]]
ʒXå≠} # Filter out any inner lists that contain the character `X`
# i.e. [["H","H"]]
g # Take the length as result
# i.e. [["H","H"]] → 1
q # Stop the program, making all other characters no-ops
# (and output the length above implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 0 (323 bytes)
```
def f(s,e=enumerate):S={(x,y,c)for y,l in e(s.split("\n"))for x,c in e(l)};return-sum(~-any((x+u,y+v,c)in S for u,v in[(1,0),(~0,0),(0,~0),(0,1)])for x,y,c in S)
def f(s,e=enumerate):S={(x,y,c)for y,l in e(s.split("\n"))for x,c in e(l)};return-sum(~-any((x+u,y+v,c)in S for u,v in[(1,0),(~0,0),(0,~0),(0,1)])for x,y,c in S)
```
[Try it online!](https://tio.run/##zY5Pi8IwEMXv@RQhIExwlNa9rfTgzXsPIrqHxE1RqFHzRzuI/erdaBVkYe87l8fwfu/xjhS2B/vRdd@m4hV4NIWxcW@cCkZ@lsUVGiTcyOrgOGHNd5Yb8GN/rHcBxNoK@bAa3PRWLW9TZ0J0duTjHtqRsgTQDCPS8Jx6ElTyeyLiOSVWkGMmEdrsIRm2veTy69lLfXMp2b9f2CnvjQtppBBiqTVbzgdskC69khcFzxl7R2ZKKc1ijIyItNYvbPIL@yN@Oi0WSl0uLzvrfgA "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), score 0, ~~237~~ 209 bytes
```
##->a{['',*a,''].each_cons(3).sum{|a,b,c|(0..b.size).count{|x|[[x>0&&b[x-1],a[x],b[x+1],c[x]]&[b[x
->a{['',*a,''].each_cons(3).sum{|a,b,c|(0..b.size).count{|x|[[x>0&&b[x-1],a[x],b[x+1],c[x]]&[b[x]]]==[[]]}}}
```
[Try it online!](https://tio.run/##tY3NCoJAFIX3PoVUaj/TZLQ2aNcbiFwvce@gFNSk2ZCmPrsNbYJad1bf@YFzM9wMeTSMx8sttRAEYk4iCFBmpI4HddXVdDOTlbm0HQkWqpuGUrKsTs9sJtXV6Hvb1R1AvQ19n6FerlEQ1CgsLywry@iDdY7r/vsCEaMIALHv@6FwcxglzKlO9l6qPauRrIrz6T5ZofNud0Rke2NMqpumYeafxXdQlnFM9Hh88uEF "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 0 (279 bytes)
```
s=>(b=s.map(Buffer)).map((x,i)=>x.filter((y,j)=>y-(g=(x,y)=>~~(b[x]&&b[x][y]))(i,j-1)&&y-g(i,j+1)&&y-g(i-1,j)&&y-g(i+1,j))).join``.length
//s=>(b=s.map(Buffer)).map((x,i)=>x.filter((y,j)=>y-(g=(x,y)=>~~(b[x]&&b[x][y]))(i,j-1)&&y-g(i,j+1)&&y-g(i-1,j)&&y-g(i+1,j))).join``.length
```
[Try it online!](https://tio.run/##zY5Bi8IwEIXv@RVeLBNsIp4lgp72H0jpCkncpKZkk9q0a3Pxr9dURFgP7nXnMHyP94Y3tfgR4diapiPOf6lRs3E2C2wDkgX6LRrY9VqrFuO7gCE3mG0Gqo3tVAsQ8zrpSKBiyYuJr1eQ5XDIsmmX8YAxmLwmK5xlkVQTL55MVun8wYuJU03tjeOcWuWq7oSWy3/zy7g@ehe8VdT6CjTwQkpUfMzRPA2nobGm45@OY7xGL8mtEEKivu9RjFFK@Uf6vX0@7/dCXC6/U@MN "JavaScript (Node.js) – Try It Online")
Receive input as array of lines.
] |
[Question]
[
Given 2 brainfuck code snippets `A` and `B`, output some brainfuck code `C` which has the same behavior as running `B` with the input of `A`s result. Note that `C` must work for any input that match the following assumptions, as if it were given to `A`.
You can assume:
1. Finite input.
2. both A and B halt.
3. EOF is consistently 0 or consistently -1.
4. Consistently allow or disallow cells to left
5. Unbounded tape (otherwise the requirement may be impossible)
6. Consistently 8-bit wrapping or unbounded integer
7. No stream(input or output for A or B) contain the byte representing EOF
8. Code A and B can contain characters that possibly appear in your C, and `+-[]<>,.`
E.g. (EOF=0)
```
A = ,[..,]
B = ,[...,]
C = ,[......,]
A = >,[>,]<[.<]
B = ,[...,]
C = >>>>,[[-<+<+<+>>>]>>>,]<<<<[.<]
A = >,[>,]<[.<]
B = ,[...,]
C = >,[>,]<[...<]
A = ,.
B = ,.
C = ,>,[,]<.
A = ,.
B = ,.
C = ,.
```
are valid tests
Shortest code in each language win. Winner in Brainfuck will be accepted.
[Answer]
## brainfuck, 526 bytes
```
-<+++++<+<+++++<-[+++++++[<++++++++>-]<--->>]<<--<--<+..<<<<,[[<+>>+<-]----[>-<-
---]>[+[++[++++++++++++++[++[[-]<]<<<[>-->>>-.>>>.<<<.>.>.<<.+>>--..>.<..<.>.>..
<++.<.>..>.<..<.>--.>>.<<.>.<..<.>.>.<.<.>++.<<.>.>.>.<.<.>..>.<..<.>>>.<<--.++<
<<]>>>>[<]<]>[<<<<[>]>[+>>>>>.>.<<<.>.<.>>>.<.[.<.>>>]<++[<<.<.>>.<<--.<<.>.>.++
>>>-]<<<<.>.>>.<.<<<.>>..>>.<<<.>--.>.<++...<<.>>--..>>.<.<..<.>.>>.<<++...>.<..
<.>>>.<<--...++<<[.>]<<<--.<<.>>++.<.>>>.<<--.++<<<]]<]>[<<<.>>]<]>[>>.>.<<<.>.>
>>.[<]]<]>[>>.>.<..<.>>>.[<]<<<+>->>]<<.[-]>,]
```
Formatted:
```
-<+++++<+<+++++<-[+++++++[<++++++++>-]<--->>]
<<--<--<+..<<<<
,
[
[<+> >+<-]
----[>-<----]>
[
not question mark
+
[
not greater than
++
[
not less than
++++++++++++++
[
not period
++
[
not comma
[-]<
]
<<<
[
comma B
>-->>> -.>>>.<<<.>.>.<<.+>>--..>.<..<.>.>..<++.<.>..>.<..<.>--.>>.<<
.>.<..<.>.>.<.<.>++.<<.>.>.>.<.<.>..>.<..<.>>>.<<--.++<<<
]
>>>>[<]<
]
>
[
period
<<<<
[
B
>
]
>
[
A
+>>> >>.>.<<<.>.<.>>>.<.[.<.>>>]<++[<<.<.>>.<<--.<<.>.>.++>>>-]<<<<.
>.>>.<.<<<.>>..>>.<<<.>--.>.<++...<<.>>--..>>.<.<..<.>.>>.<<++...>.<
..<.>>>.<<--...++<<[.>]<<<--.<<.>>++.<.>>>.<<--.++<<<
]
]
<
]
>
[
less than
<<<.>>
]
<
]
>
[
greater than
>>.>.<<<.>.>>>.[<]
]
<
]
>
[
question mark
>>.>.<..<.>>>.[<]
<<<+>->>
]
<<.[-]>,
]
```
With respect to A, B, and C: EOF = 0, cells left of start disallowed, 8-bit wrapping cells.
Expects A followed by `?` followed by B.
[Try it online](https://tio.run/##XVFRakMxDDtQYp/AuAcx/ugGg1Hox2DnTyU76daGx7PjWLKUfPxcv@9fv5@3tcQGl40dJUavsJ0MlzQRcU9D5DdUDWsGmtwBSpxLOA9F0mOA5RAdPnwBJpAYOkHnoviRSV0ZFWQiyhwDqqhQUemzKERpYZ5dxsjG3u7CH6YAAMKfWWLrAR3QaSWGgllsFc1cGI3O0ngfRbqZ9qRBnNBS7WuwVZceZ9RbLrRAbbAV6gH18btaLb2hvPcz0/s6Xg0dK0qlSP8ZYWfsji6fEVEvgcetd1U8jc9cy2cgYqrlZQY0zHwA)
(This answer can be made compliant with a brainfuck interpreter that doesn't allow going left of the start at the cost of one byte by transliterating `y/<>/></` and prepending a `>`.)
The basic idea is to use a series of string replacements in order to simulate the tapes of A and B using 2-cell nodes, with special attention given to replacing `.` in A and `,` in B so that the intermediate data stream is kept in a block of cells to the left of the simulated tape. The string replacement scheme is:
* Insert `>>` before A
* In both A and B, replace `>` with `>[-]+>` and `<` with `<<`
* In A, replace `.` with `>[-]-[>>]+[[>+<-]<[>+<-]<]>+[->>+]<[>>>-<<+[<<]<+>>>[>>]+<<<-]>[+<->]+</`
* Insert `>[>>]+>` after A and before B
* In B, replace `,` with `,[,]>,<<[<<]<[[>]>>[>>]<+<[<<]<[<]>-]>[>]>>[>>]+<*`
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 1287 bytes
```
++++++++++++++++[->+++>+++>++++>++++>++++++>++++++<<<<<<]>----->--->---->-->----->--->+<<<.....<<.>>....<<.>>.<<..>...>>>>[>+>,->[-]++++[-<-------->]+<[>>]>[<<-<-<<<..>.<.....>>.<<<.....>>.<<<<.>>..>>.<<<.>>>>.<<<...>>>.<<.<<<..>>>>.<<<..>>.....<<<..>>>>>.<<<<<.>>>>.<<<.>.....<<.>>>>>.<<<<.>>..>>>>>>>>]<<<-------------[>>]>[<<-<<<<..<<.>..>>.<<<.>.<<.>>>....<<<.>>>>.<<<.>.....<<.>>>>>.<<<<<.>>>>.<<<..>>.....<<<..>>>>>.<<<<..>..<<.>>>..<<<.>>>>.<<<.>.....<<.>>>>>.<<<<.>.<<..>>>>.<<<..>>.....<<<..>>>>>.<<<<..>..>>>.<<<.>>.<<<.>>.<<<.>>.>>>.<<....<<<.>>>>.<<<.>.....<<.>>>>>.<<<<<.>>>>.<<<..>>.....<<<..>>>>>.<<.....<<.>>>.<<<.>.....<<.>>>>>.<<<<.>.<<..>>>>.<<<..>>.....<<<..>>>>>.<<<<.>..>>>>>>>>>]<<<--------------[>>]>[<<-<<<<<...>>.<<<<.>>>>>.<<<<.>..>>>>>>>>>]<<<--[>>]>[<<-<<<<.......>.<<<<.>>>>>.<<<<.>..>>>>>>>>>]<<<<[+++++++[->++++++++<]>--.<]<]>>,[<+>>++++[-<--------->]+<+[>>]>[<<-<<<.<<<.>>>>.<<..<<.>>.>.<.....>>.<<<<<.>>>>.<<<.>.....<<.>>>>>.<<<<.>>...>.<<<.>...>>.<<.....>>>.<<....<<<.>>>>.<<<.>>.....<<<.>>>>>.<<<<.>..<<.>>>...>.<.....>>.<<<<<.>>>>.<<<.>.....<<.>>>>>.<<<<.>>...>>.<<..<<.>>>.<<.....>>>.<<....<<<.>>>>.<<<.>>.....<<<.>>>>>.<<<..>>>>>>>>>]<<<----------------[>>]>[<<-<<<<<.....>>>>>>>>>]<<<--[>>]>[<<-<<<<.....>>>>>>>>]<<<<[+++++++[->++++++++<]>--.<]>,]
```
[Try it online!](https://tio.run/##rVNbisMwDDzLfvtxAjEXEf7YFgploR8Le/6sbNmxnN0mJq0glq1Eo4lGvnx/3h@3n@vXsriNcYCs7THL6qhYQsiG@uTFRPJHMZs4oG9yNB8hxnDwARyS1qVQDckRAwlMJFHSJMUrGHar@DWcYet73emhh5VLjyqESURnjbGAWpJAsNaJFlCFWMEUqJXcq0KHLEvnGuAx6Tjz51HZtu5tXO3hG9ibjFcZGzH@qjHKQcOU7CBsRNTxOswjHu6MXo58LyIl8fBMDtgMd5luZwva5rZ7Mo77zIDG/rp3/JmAvbPj763jeqa@4X@GwK6s/wg7IeKsWPBpWUQu8cRy/vAs2T79Ag "brainfuck – Try It Online")
Here it is! The brainfuck code that composes two brainfuck codes. Use a "!" to separate the two input code snippets. For example snippet A: `>,[>,]<[.<]`, snippet B: `,[...,]`. Input for my program: `>,[>,]<[.<]!,[...,]`. It will not terminate if no "!" is found.
This does essentially the same as my VBA Version. The code that is generated is the same as in the VBA version (note that the examples in the VBA post were made before the latest change in the brainfuck snippets).
**Explanation**
This is my source code:
```
[
Tape: "+"(43) "-"(45) "<"(60) ">"(62) "["(91) "]"(93) readA(1) printInput(0) input else exitIf exitElse
]
++++ ++++ ++++ ++++ [->+++>+++>++++>++++>++++++>++++++<<<<<<]>----->--->---->-->----->--->+
<<<.....<<.>>....<<.>>.<<..>... print init routine
>>>>[ while readA
>+ set printInput = true
>, read character
->[-]++++[-<-------->] decrease input by 33 to check for "!"
+ set else flag
# A check for "!"
<[ if input not "!"
>> go to exitIf
]
>[ else
<<- set printInput = false
<- set readA = false
<<<..>.<.....>>.<<<.....>>.<<<< print routine between A and B
.>>..>>.<<<.>>>>.<<<...>>>.<<.<
<<..>>>>.<<<..>>.....<<<..>>>>>
.<<<<<.>>>>.<<<.>.....<<.>>>>>.
<<<<.>>..>>>
>>>>> go to exitElse
]
# A check for "dot"
<<<----- ----- --- decrease input by 13 (total 46) to check for dot
[ if input not dot
>> go to exitIf
]
>[ else
<<- set printInput = false
<<<<..<<.>..>>.<<<.>.<<.>>>.... print list storing routine
<<<.>>>>.<<<.>.....<<.>>>>>.<<<
<<.>>>>.<<<..>>.....<<<..>>>>>.
<<<<..>..<<.>>>..<<<.>>>>.<<<.>
.....<<.>>>>>.<<<<.>.<<..>>>>.<
<<..>>.....<<<..>>>>>.<<<<..>..
>>>.<<<.>>.<<<.>>.<<<.>>.>>>.<<
....<<<.>>>>.<<<.>.....<<.>>>>>
.<<<<<.>>>>.<<<..>>.....<<<..>>
>>>.<<.....<<.>>>.<<<.>.....<<.
>>>>>.<<<<.>.<<..>>>>.<<<..>>..
...<<<..>>>>>.<<<<.>..>>>>>
>>>> go to exitElse
]
# A check for "less than"
<<<----- ----- ---- decrease input by 14 (total 60) to check for "less than"
[ if input not "less than"
>> go to exitIf
]
>[ else
<<- set printInput = false
<<<<<...>>.<<<<.>>>>>.<<<<.>..>>>>> print A move left routine
>>>> go to exitElse
]
# A check for "greater than"
<<<-- decrease input by 2 (total 62) to check for "greater than"
[ if input not "greater than"
>> go to exitIf
]
>[ else
<<- set printInput = false
<<<<.......>.<<<<.>>>>>.<<<<.>..>>>>> print A move right routine
>>>> go to exitElse
]
# print remaining character
<<<<[ if printInput
+++++++[->++++++++<]>--.< print original character
]
< go to readA
]
>>, read next character
[ while input
<+ set printInput = true
# B check for comma
>>++++[-<----- ---->]+<+ decrement input by 44 to check for comma
[ if input not comma
>> go to exitIf
]
>[ else
<<- set printInput = false
<<<.<<<.>>>>.<<..<<.>>.>.<..... print B list reading routine
>>.<<<<<.>>>>.<<<.>.....<<.>>>>
>.<<<<.>>...>.<<<.>...>>.<<....
.>>>.<<....<<<.>>>>.<<<.>>.....
<<<.>>>>>.<<<<.>..<<.>>>...>.<.
....>>.<<<<<.>>>>.<<<.>.....<<.
>>>>>.<<<<.>>...>>.<<..<<.>>>.<
<.....>>>.<<....<<<.>>>>.<<<.>>
.....<<<.>>>>>.<<<..>>>>>
>>>> go to exitElse
]
# B check for "less than"
<<<----- ----- ----- - decrease input by 16 (total 60) to check for "less than"
[ if input not "less than"
>> go to exitIf
]
>[ else
<<- set printInput = false
<<<<<.....>>>>> print B move left routine
>>>> go to exitElse
]
# B check for "greater than"
<<<-- decrease input by 2 (total 62) to check for "greater than"
[ if input not "greater than"
>> go to exitIf
]
>[ else
<<- set printInput = false
<<<<.....>>>> print B move right routine
>>>> go to exitElse
]
# print remaining character
<<<<[ if printInput
+++++++[->++++++++<]>--.< print original character
]
>, input next character
]
```
[Answer]
# VBA, ~~512~~ ~~489~~ 479 bytes
```
Sub f(A,B):Debug.?">>>>>->>>>->--<<<"&Replace(Replace(Replace(A,"<","<<<[+]-<<"),">",">>>>>>>[+]-<<"),".",">>-<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>>+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]-<<")&">>[>>>>>]<<<<<[+<<[-]<<<]>++[-->>>>>++]+[-<<<<<+]->>"&Replace(Replace(Replace(B,"<","<<<<<"),">",">>>>>"),",","[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<"):End Sub
```
**Explanation**
The VBA code changes the brainfuck code in a way, that the output of snippet A will be stored in a list and the input of snippet B will be read from that list.
It first initializes some variables
```
>>>>>->>>>->--<<<
```
Then it reads snippet A and replaces every `<` by `<<<[+]-<<`, every `>` by `>>>>>>>[+]-<<` and every `.` by the storing routine
```
>>>>>>>[+]-<<"),".",">>->+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]--<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>+<<
```
after that it deletes the memory of snippet A and makes changes to the stored list, so it can be read as input for snippet B:
```
>>[>>>>>]<<<<<[+<<[-]<<<]>++[-->>>>>++]+[-<<<<<+]->>>>>-<<<
```
Then snippet B will be read, every `<` will be replaced by `<<<<<`, every `>` will be replaced by `>>>>>` and every `,` will be replaced by the list reading routine:
```
[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<
```
**Brainfuck source code**
This is my source for the brainfuck portions of the code. I will explain that in detail later.
```
[
Tape: tempMem data out/in dataAnchors outAnchors (all repeating)
dataAnchors of Snippet A: -1 = memory has been used, -2 = active memory cell for copying to out/in
dataAnchors of Snippet B: -1 = active memory cell for copying from out/in
outAnchors of Snippet A: -1 = start of list, -2 = next output position
outAnchors of Snippet B: -1 = character has been read (or start of input)
]
### Init
>> two blank data cells (for non wrapping pointer)
>>>- set start of input
>> >>- set first "used" flag
>-- set end of input
<<< return to first usable data cell
### A move right routine
>>>>> move to the next data cell
>>[+]- clear and set "used" flag
<< return to data cell
### A move left routine
<<<[+]- clear and set "used" flag of previous data cell
<< go to data cell
### A print routine
>>- set flag
<<[ while value greater 0
- decrement value
<+ increment tempMem
>>>>+[-<<<<<+] find start of input
+[-->>>>>++]-- find end of input
<<+ increment input
>>+[-<<<<<+]- find start of input
<++[-->>>>>++]--find flag
<< go to active data cell
]
<[->+<] move stored value back to data
>>>>+[-<<<<<+] find start of input
+[-->>>>>++] find end of input
>>>>>- set new end of input
[-<<<<<+]- return to start of input
<++[-->>>>>++]- return to and delete data flag
<< go to data cell
### After snippet A: Delete memory of A and configure out/in list
>>[>>>>>]<<<<< go to last used data
[+<<[-]<<<] delete each data
>++[-->>>>>++] find and delete end of input flag
+[-<<<<<+]- go to start of input
>> go to first data cell
### B move right routine
>>>>> go to next data cell
### B move left routine
<<<<< go to previous data cell
### B reading routine
[-] set cell = 0
>>- set flag
>[>>>>>]+[-<<<<<+]- find start of input
>>>[ if value greater 0
- decrement value
<<<[<<<<<]>>>> go to initial start of input (combined with next)
+[->>>>>+]- find mem cell flag
<<+ increment mem cell
>>>[>>>>>]+[-<<<<<+]->>> return to input cell
]
>>- set new start of input
[<<<<<]>>>> go to initial start of input (combined with next)
+[->>>>>+] find and delete mem cell flag
<< go to mem cell
```
Output for test case 1: `f ",[..,]",",[...,]"`
```
>>>>>->>>>->--<<<,[>>->+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]--<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>+<<>>->+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]--<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>+<<,]>>[>>>>>]<<<<<[+<<[-]<<<]>++[-->>>>>++]+[-<<<<<+]->>>>>-<<<[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<[...[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<]
```
[Try it online!](https://tio.run/##zU9LCkIxDDzQvPYEoadwF7JQUZAHLvycv2aSh/RB12IX7bTzyfT0ON7u1/d57b1xldxKEZFFCaHEIjBHQTfAUvylimBkaXcOcZ36qcBIThLMMxqEsyDyT10WPzVoC4uCM4it7axDZraUEPIvm3@viIvGg22FM8qy49zFvKnJs2qtPx1ovR8uz9cH "brainfuck – Try It Online")
Output for test case 2: `f ">,[>,]<[.<]",",[...,]"`
```
>>>>>->>>>->--<<<>>>>>>>[+]-<<,[>>>>>>>[+]-<<,]<<<[+]-<<[>>->+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]--<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>+<<<<<[+]-<<]>>[>>>>>]<<<<<[+<<[-]<<<]>++[-->>>>>++]+[-<<<<<+]->>>>>-<<<[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<[...[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<]
```
[Try it online!](https://tio.run/##vU9BDgIxCHwQti8gvMIb4aBGE7OJB3d9f2WgMW3SsxwaBmaG6fV9eb4en9vWmqBKPqUws2QpmaOTztCckK1CQAoFM5l3YSJElpa/VWEatzjiOwq41INB43LhYO4hxLhFwcpUjjOx9SFuoTeZLAbvTMtBxJ@6fmYE0BhYD55WllnXKvgtRe5Va/3rQWvtfN@PLw "brainfuck – Try It Online")
Output for test case 3: `f ",.",",."`
```
>>>>>->>>>->--<<<,>>->+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]--<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>+<<>>[>>>>>]<<<<<[+<<[-]<<<]>++[-->>>>>++]+[-<<<<<+]->>>>>-<<<[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<.
```
[Try it online!](https://tio.run/##bU/LCgIxEPug2P2CMF/hrcxBRUEWPLj6/bWZWaQL7aFkmsek1/fl@Xp8b2trplPyKoXkSQhVkIR3FKwBnto/VYiRlbtziHHqlwIjOUnwnmGgdoE0q0F6GCq0QdjtYBwSsyNDqJ/s/qMihhoPvtfNKM@Gc5fypiZyae183z4/ "brainfuck – Try It Online")
**Complex test case:**
Snippet A: Build alphabet triangle `>+++++[<+++++>-]<+[>>[>[.>]]>++++++++++.--[<++++++++>-]<[+.<]<-]>>,>[.>]++++++++++.[<[.<]>,>[.>]<]` [Try it online!](https://tio.run/##TYrBCYBADAQLikkFYRtZ8lBBEMHHgfVHjXk4n4WdWca8n9u1HpmQF3oNNFwIEDREfK4w1W46o5iHawBTxb@Uzsf175F5Aw "brainfuck – Try It Online")
Snippet B: Sort input in ascending order `>>,[>>,]<<[[-<+<]>[>[>>]<[.[-]<[[>>+<<-]<]>>]>]<<]` [Try it online!](https://tio.run/##DYjLCYAwEERbiecYKxi2Cm/DHqIoBsGDifWvw3x4vO2t7Tm//Y4wm6k5QBZkuFExBxcWvTgDIpeUhkesV@tJrWkcfUw/ "brainfuck – Try It Online")
Result:
```
>>>>>->>>>->--<<<>>>>>>>[+]-<<+++++[<<<[+]-<<+++++>>>>>>>[+]-<<-]<<<[+]-<<+[>>>>>>>[+]-<<>>>>>>>[+]-<<[>>>>>>>[+]-<<[>>-<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>>+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]-<<>>>>>>>[+]-<<]]>>>>>>>[+]-<<++++++++++>>-<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>>+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]-<<--[<<<[+]-<<++++++++>>>>>>>[+]-<<-]<<<[+]-<<[+>>-<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>>+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]-<<<<<[+]-<<]<<<[+]-<<-]>>>>>>>[+]-<<>>>>>>>[+]-<<,>>>>>>>[+]-<<[>>-<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>>+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]-<<>>>>>>>[+]-<<]++++++++++>>-<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>>+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]-<<[<<<[+]-<<[>>-<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>>+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]-<<<<<[+]-<<]>>>>>>>[+]-<<,>>>>>>>[+]-<<[>>-<<[-<+>>>>+[-<<<<<+]+[-->>>>>++]--<<+>>+[-<<<<<+]-<++[-->>>>>++]--<<]<[->+<]>>>>+[-<<<<<+]+[-->>>>>++]>>>>>-[-<<<<<+]-<++[-->>>>>++]-<<>>>>>>>[+]-<<]<<<[+]-<<]>>[>>>>>]<<<<<[+<<[-]<<<]>++[-->>>>>++]+[-<<<<<+]->>>>>>>>>>>>[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<[>>>>>>>>>>[-]>>->[>>>>>]+[-<<<<<+]->>>[-<<<[<<<<<]>>>>+[->>>>>+]-<<+>>>[>>>>>]+[-<<<<<+]->>>]>>-[<<<<<]>>>>+[->>>>>+]<<]<<<<<<<<<<[[-<<<<<+<<<<<]>>>>>[>>>>>[>>>>>>>>>>]<<<<<[.[-]<<<<<[[>>>>>>>>>>+<<<<<<<<<<-]<<<<<]>>>>>>>>>>]>>>>>]<<<<<<<<<<]
```
[Try it online!](https://tio.run/##1VRLDkIhDDwQ1hMQLtJ0oSYmxsSFiefHloIt@HBpeCwIpZ1h@gnn5@n2uL4u95yTLNANIMaYdGEgtoIs5FtndgFA5sTO0xk4WrJDLFwB5VnGE5@KkhQ4TBi9k6NHPzFHCpHmLJrdlGNQSfSdfE15Fb0AQzd@NAQX0v0RZfKA5vNy2Me8rDghNh@4Yvv32GavXn8yqimJXDlT6hicvOQWyshDo@iDioHloglXNtKMt1HCtwmyL/ff72pptD4NY5GVzomrpTxqIQVkvmBc1UsO6ODqy/kN "brainfuck – Try It Online")
[Answer]
# [Brainfuck](https://github.com/TryItOnline/brainfuck), 785 bytes
```
--->---->--->----->-->----->>++++[-<++++>]<[-<++++++<++++<+++<++++++<++++<+++>>>>>>]<<...<<<<.>.>>>>>>>,[[-<+<+>>]+++++++[-<------>]+<--[--[-[-------------[--[[-]>[-]<<.>]>[-<<<<.<..>..>.<<<<<.>>.<<.>.>>>>>>>]<]>[-<<<<.<..<<..<..>.>>>>>>>]<]>[-<<<<.<..>>.<..<<.<<.>.>>>>>>>>>+<<]<]>[->>>+<[>-<<<<<.>>>>>]>[-<<<<<<<...>.<<<<<.>>.>.<<..>>>>.<..<<.<..>>>>..<<<<<.>>>>.<.<<.>.<.>>>>.<<<<<.>>>>.<.<<.>.<.>.>>...<.>>.<<<<<.>>>>..<.<.<.>>>>.<<<<<.>>>>...<.<<....>>>>.<<<<..>.<.>>.>...>.<..<<.<.>.>>...<<<<.>>>>>.<<<<<.>...>>.>...<<.>.<<..<.>.>>>>>>>>>>>]<<<<]<]>[->>>+<[>-<<<<<<.<<<<<.>>.>>.<.<<..>>>>.<<<<..>.<..>>>>.<<<<.>.>>.>.<<<<<.>.>>.>.<<.<.>>>>.<<<<<.>>>>..>.<.<<.>>..>.<..<<.<.>>.<<.>>>>.<<<<..>.<.>>>>.<<<<.>.<.>.>>..>.<.<<.>>..>.<..<<.<<.>.>>>>>>>>>>]>[-<<<<<.>>>>>>]<<<<]<<[-]>>,]
```
[Try it online!](https://tio.run/##bVLhasYwCHygVvcC4osEf2yDwRh8PwZ7/s4z2iQloU01eqdn@vH7/v36@vv8uS4iUsotDOxp6OGrkeCjJmkdh9T29DWWiTCz@GLlfqRnA1o8wzoGvNTL2OFWw9NoXjhqZOovqGAEqbMrHuklYIxCJnMeOon0bRTQyJkJXLVIzwu7KVUhECRcQuPUQ3QROcWZHg80Z6XydgFwMaesO46EDYw7kHlEOPkxIh69FO8tpGgCyz2WIpZhxHVuByKT@FTwbGPytYa0ODtNNQ1d@u@3/FQ52EviDr0Kuq@QF32CX01Puy7/Wf0rjcXezuaTOe0f "brainfuck – Try It Online")
To split A from B I opted for `/`.
Explaination:
The actual code that generates this is just a read-loop with a flag for A/B and a switch that reduces the input to look for `>`, `<`, `/`, `,`, and `.` and otherwise just output the input. It is actually just a transpiler where the transpiled code lives within a data structure such that it don't interfere with the stored data from A or each other. The `/` just moves the active cell to the first unused cell. I originally cleaned it up, but that makes the program and output larger.
The program result has the following memory model:
```
|0|input*|cz|d0|c0|d2|c0|...
```
The `c` is crumble. `cz` is always `0` It points out where in my emulated BF data the pointer is. The active value is -1 while all visited cells will have `1`. In operations like `aprint` and `bread` some `c` get special meaning.
A-code print skips all cells 1 byte to leave room for one more byte input which is copies with a backup in the next bytes crumble to copy back.
B-code read fetches input from input. Here being destructive is ok and when you "read" the last byte you get 0 as EOF regardless of the implementation.
I started out as [Extended BrainFuck](http://sylwester.no/ebf/) code making EBF result. Most of the debugging was done on the result files and then updates to the source that generated it. Then i just run the operations independent to get BF output, but I noticed Dorian's answer, which beat me in length so I continued golfing EBF source for smaller BF output. The original source is quite readable and simple compared to other stuff I've done with it:
```
:bck
:i
:t
:z
:r
:rc
:rz
;;; outputs a header with most of the result logic
{cinit
|"
;; memory model of the result
ML/i/z/d/c
PTR=1/1/2
:iz:i:z:d:c:d2:c2
;; moves pointer back. Bad things will happen to
;; A output if out of bounds
{backward @d2 $c2++ $c-- $d
}
;; moves pointer forward
{forward $c++ $c2[-]- $d2 @d
}
;; stores the current cell in input a the start of bf data
{aprint
$c2(-)+ ; mark next cell as used even if it maybe
$c[$c2] ; go to the end of used data
$c((->+)$d(->+)@d2) ; as long as c is something move d and c one place right
@i$c+[->>+]@c ; go to active cell, zero it
$d(- ; copy:
$c2+ ; backup in c2
$z[<<]@z ; back to i
$i+ $c[>>]@c ; increement and back to zero carry
)
$c2-(- $d+)+ ; copy backup in c2 back to d
$c- ; mark active cell
$d ; move to d
}
;; removes all the data from A. And initializes for B
{aend
$c[$c2]
$c((-)<(-)<@c)@z
$c-$d
}
;; instead of read b fetched from input area
{bread
(-)>+@c2 ; clear d and c
$c[$z] ; go to z
$i<[<] @iz ; go to iz
$i(-$iz+) ; switch places between i and iz
$iz(- ; copy from iz to d
$z[>]@z ; move to z
$c[$c2] ; move to the current c
$d2+ ; increase d
$c[$z] ; back to z
$i[$iz] ; back to iz
@i ; but since we shave switched correct
)
$z[>]@z ; go back to z
$c[$c2]- ; move to active cell and make it -1
$d2 @d ; go to d
}
$c-$d ; init. Go to c t mark it active, then go to d
"
(-)
}
{cmain
&cinit
$t,(
(-$i+$bck+) ; pour to i and bck
;; switch ( $i ) cases '<>,./' using $t
$t+++++++(-$i------)+$i--; ,
($i--; .
($i-; /
($i-------------; <
($i--; >
((-) $t(-) $bck.)
$t (- |"&forward "(-) )
) $t (- |"&backward "(-) )
) $t (- |"&aend "(-) $r+ )
) $t (- $rc+$r[$rc-$bck.$rc]@r$rc[- |"&aprint "(-) $rz])
) $t (- $rc+$r[$rc-|"&bread "(-)]@r$rc[-$bck.$rz])
$bck (-) ; clear backup
$t, ; read into t
)
}
&cmain
```
[Answer]
## sed, 165 bytes
```
s > >[-]+> g
s < << g
1s \. >[-]-R+[[>+<-]<[>+<-]<]>+[->>+]<[>+>>-<L+>R+<<<-]>[<+>-]+< g
1s .* R&<R+>
2s , ,[,]>,<L[[>]R<+L[<]>-]>[>]R+< g
s L <[<<]< g
s R >>[>>] g
```
For flavors with EOF = 0, cells left of start disallowed, 8-bit wrapping cells.
Expects program A on the first line and B on the second line.
[Try it online](https://tio.run/##LY0xDkIxDEP3f4pMDCStBLPlE3TqGrKBurFUnL@E8qfEtvw8X88y3p@1plDoJZQyjikQIJ/blEfdfunqTkUJnCeoXkjdBlnQlF2BzOhQJutE1Kv0C3qij/sUE3MLGloCo0ObJ@tXSrUrU5rAgfiLLsyMIWMtmtNysSIO81qrxRc)
This uses 2-cell nodes to simulate the tapes of A and B, with A's output occupying contiguous cells to the left of the leftmost node.
Alternative 173-byte solution:
```
1i>>
s > >[-]+> g
s < << g
1s \. >[-]-[>>]+[[>+<-]<[>+<-]<]>+[->>+]<[>>>-<<+[<<]<+>>>[>>]+<<<-]>[<+>-]+< g
1a>[>>]+>
2s , ,[,]>,<<[<<]<[[>]>>[>>]<+<[<<]<[<]>-]>[>]>>[>>]+< g
```
[Try it online](https://tio.run/##NY07DgMxCET7PQU9YGlTj@YihCJSolWaNFbO72DvpgLefOivpx@f7xj7m9y6UBieSjnqgAC17F3ubXEPMjWCCk9cI6nhpE5AOqABJLSOZQfKxShQxavvcQrcbl1MLCxpwEpVd5456EXqwcz/@awYgxa0Ehtys2itWf4A)
Originally my design was based on a doubly infinite tape, which required significantly more work to move left (moving data when passing beyond the leftmost cell previously encountered) and to transition from A to B (clearing the data instead of just traveling past the rightmost cell previously encountered).
Thanks to Sylwester and Dorian for tricks and ideas.
] |
[Question]
[
# Introduction
[Briscola](https://en.wikipedia.org/wiki/Briscola) is one of Italy's most popular card games. It is a trick-taking card game, like Bridge. Briscola is well known for its bizarre point system. In this challenge, given two cards, you will output whether the first one scores more, less, or the same number of points as the second in Briscola's point system.
# Challenge
Briscola is played with a deck of Italian playing cards. There are forty cards in a deck, 1-10 in each of the four suits: cups, swords, clubs, and coins. We will be ignoring the suits for this challenge. Cards 2 - 7 are the numeric cards, and cards 8, 9, and 10 are the face cards. The ranking of the cards, from highest to lowest, are:
```
+------------------------+-------------+
| Cards, by Rank | Point Value |
+------------------------+-------------+
| Ace (1) | 11 |
| Three (3) | 10 |
| King (10) | 4 |
| Knight (9) | 3 |
| Jack (8) | 2 |
| Numeric Cards (2, 4-7) | 0 |
+------------------------+-------------+
```
*Thanks to Orphevs for the nice table! :)*
Your task is to create a full program or function which accepts two numbers 1-10 representing card ranks, and outputs (or returns) whether the point value of the first card is greater than, lesser than, or equal to the point value of the second card. Additional Notes:
* Your program may output any three values to indicate less than, greater than, and equal to, however, it must output the same value for each condition each time.
* Your program may use any [IO defaults](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
* Either a full function or a program is permitted.
* This question is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins.
* Here are some sample inputs and outputs:
```
1, 4 => more than (ace scores 11 points, 4 scores 0 points, first is more than second.
8, 3 => less than (8 scores 2, 3 scores 10, first is less than second.
5, 2 => equal (5 and 2 both score 0)
```
If you have any questions, don't hesitate to ask. Good luck!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
[DEXIl]&mdZS
```
Input is an array of two numbers. Output is `-1`, `0` and `1` respectively for *more than*, *equal to* or *less than*.
[Try it online!](https://tio.run/##y00syfn/P9rFNcIzJ1YtNyUqGMgzVDCJBQA)
### Explanation
Consider input `[1 4]` as an example.
```
[DEXIl] % Push [8 9 10 3 1]
% STACK: [8 9 10 3 1]
&m % Implicit input. Index (1-based) of membership, 0 if not member
% STACK: [5 0]
d % Consecutive difference
% STACK: -5
ZS % Sign. Implicit display
% STACK: -1
```
[Answer]
# JavaScript (ES6), 42 bytes
Takes the two ranks in currying syntax `(a)(b)`. Returns **1** for *more than*, **-1** for *less than* or **0** for *equal*.
```
a=>b=>Math.sign((s="05040000123")[a]-s[b])
```
[Try it online!](https://tio.run/##bco7DoMwDADQvaeImOwBCD@pS7hBT4AYDDWfKk1aHLh@WompUt/8HnSQjNv6Cqnzd46TiWTawbQ3Cksm6@wAxCS60bX@KsoqwY76VLqhxzh6J95yZv0MExQINaLKc/X0G6uwkLv8jitCdQ7LIv9Gg1Ceg9872fgB "JavaScript (Node.js) – Try It Online")
---
# Using a formula, 48 bytes
This is definitely longer than using a lookup table but also a bit more interesting.
Same I/O format.
```
a=>b=>Math.sign((g=n=>(1<<n&1802)*6%13)(a)-g(b))
```
[Try it online!](https://tio.run/##bcpBDoIwEADAu6/oRbNrAlhQw4HtD3zEgqVA6lZp9fv1wMnEOc/CH47DOj9TIeFu80iZyfRkbpymMs5OABwJGdBdJwfdnmo8Xve6QWAsHPSIeQgSg7elDw5G0AhnRFVV6hFWq9LEsvsdLUKzDW9j/DcuCPU27OvNPn8B "JavaScript (Node.js) – Try It Online")
### How?
Because many cards have a value of \$0\$, we first want to mask them out. Given a card rank \$n\$, we compute:
$$p=2^n\text{ and }(2^1+2^3+2^8+2^9+2^{10})$$
$$p=2^n\text{ and }1802$$
```
n (card) | 2**n | AND 1802
-------------+------+----------
1 (Ace) | 2 | 2
2 | 4 | 0
3 (Three) | 8 | 8
4 | 16 | 0
5 | 32 | 0
6 | 64 | 0
7 | 128 | 0
8 (Jack) | 256 | 256
9 (Knight) | 512 | 512
10 (King) | 1024 | 1024
```
We now want to transform the remaining non-zero values in such a way that they can be sorted in the correct order. We use:
$$q=6p \bmod 13$$
```
p (card) | 6p | MOD 13
---------------+------+--------
2 (Ace) | 12 | 12
8 (Three) | 48 | 9
256 (Jack) | 1536 | 2 --> Ace > Three > King > Knight > Jack
512 (Knight) | 3072 | 4
1024 (King) | 6144 | 8
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~25~~ ~~21~~ 16 bytes
* 1 => *more than*
* -1 => *less than*
* 0 => *equal*
---
```
£"78920"bXÉÃr- g
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=oyI3ODkyMCJiWMnDci0gZw==&input=WzEsNF0KCg==)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-g`, 13 bytes
Outputs `-1` for `>`, `1` for `<` and `0` for `===`.
```
m!b#ù991ìD)rn
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=bSFiI/k5OTHsRClybg==&input=WzEsNF0KLWc=) or [run multiple tests](https://ethproductions.github.io/japt/?v=1.4.6&code=bSFiI/k5OTHsRClybgpn&input=WwpbMSw0XQpbOCwzXQpbNSwyXQpdCi1tUg==) (The second line replicates the functionality of the `-g` flag to allow the flags to be used to process multiple inputs)
---
## Explanation
```
:Implicit input of 2 integer array
m :Map
#ù991 : 249991
ìD : Convert to array of base-13 digits = [8,9,10,3,1]
!b : Get the index of the current element in that
) :End map
rn :Reduce by subtraction
:Implicitly output the sign of the result
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
“®µ½¤¢‘iⱮIṠ
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xD6w5tPbT30JJDix41zMh8tHGd58OdC/4fbn/UtOb//2iuaCMd01gdrmhDHSMQZaRjCKIsdQwNwKIGEL4hjA/kcsUCAA "Jelly – Try It Online")
* -1 byte by using Luis Mendo's [method](https://codegolf.stackexchange.com/a/168494/75553).
Outputs `0` for equal, `-1` for greater than and `1` for less than. Uses the code-page index `“®µ½¤¢‘` which evaluates to `[8, 9, 10, 3, 1]`.
Takes input as a pair of cards. Use `1,2` as an example.
```
“®µ½¤¢‘iⱮIṠ
“®µ½¤¢‘ [8,9,10,3,1]
i index of
Ɱ each element in the input -> 5,0
I Finds the forward difference: 0-5 = -5.
Ṡ Sign -> -1.
When ranks are equal, Ṡ returns 0 and when the rank of the second
card is higher, Ṡ returns 1.
```
[Answer]
# [R](https://www.r-project.org/), 35 bytes
```
rank(c(6,0,5,1:4*0,1:3)[scan()])[1]
```
[Try it online!](https://tio.run/##jZDNasMwEITveoqBXOxijOWfYkySFwk5qPKGukkko5Xbvr27pk5SespFLKPh29kJ8xyMOyc2ec2KrMl0V78U8lbpga1xSXpMD/o4a1UrtcHXOwVCiSsZx9hn0Ou4lTFvsNstro@Jo5h8FDcicWREjzH4T4JosD4EstERM/xplXpCp9QTWVSrqueMjSrVkoe@R1lHPQLxdJE0ndqUADoMOeVywx413siaiQmJsQSWiMTQGqMfXORMDKtW3KXTEOTOgYGr/MgZxoHJetenaqMf/BZbVA9@eyOVmci3TcUf3mUp5h9Oyl1x0rKUe8c1MK5fBKn7l4YinX8A "R – Try It Online")
* -6 Bytes thanks to @JayCe suggestion to switch to full program instead of function
The program returns `2` for `'greater than'`, `1` for `'less than'`, `1.5` for `'equal'`
**Explanation :**
```
c(6,0,5,1:4*0,1:3)[v] # extract the score of each card in v (got from scan());
# cards in v are used as indexes in the cards rank
# vector, which is based on briscola scores vector
# c(11,0,10,0,0,0,0,2,3,4) but divided by 2 and rounded
# to integer preserving the original order
rank( )[1] # rank returns : c(1, 2) if v[1] < v[2]
# c(2, 1) if v[1] > v[2]
# c(1.5,1.5) if v[1] == v[2]
# and we select the first value
```
[Answer]
# Java 8, ~~69~~ 66 bytes
```
a->b->Math.signum("05040000123".charAt(a)-"05040000123".charAt(b))
```
Lambda taking parameters in currying syntax, port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168493/79343).
Returns `0.0` *equal*, `1.0` for *greater than*, and `-1.0` for *less than*. Try it online [here](https://tio.run/##jZBNa8MwDIbPya8QPcWwuOkXDNIGdhns0FOPYwcldRNnju3ZcqGM/vbMg@TWQ3WR9EqPJNTjFfP@/D3KwRpH0MecB5KKX4JuSBrN36egTFMbaiUbaBR6D0eUGn7TZBI9IUV3NfIMQyxlJ3JSt59fgK717L8zmUftPzSJVrgXeKAog1RVUDvpG6MQDjBiXtV5dUTquJetDkO2KHbFtoi2Wm8WvOnQvVGGLH@o14yNSVLGA043T2LgJhC38TpSOpv3cLRW3bIVm4ItYyUslzAYJ4A61E/hrzO@mXAl4quexnczvp5w8RNQpck9vY9/).
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 3 bytes.
[Answer]
# [MarioLANG](https://github.com/tomsmeding/MarioLANG), 578 548 530 bytes
```
) <
====================="
>-[!)
"==#)
>-[!)) )
"==#=) +
>-----[!))) + +
"======#== + +
>--[!))) ++++ -(- <
"===#=================== ====="
>-[!)))+++++ >) [!)+:
; "==#======================= "===#===
>[! )))[!((>[!)[!):
"=#==========================#====#==#===
!;(( < >)-:
#============================" "===
```
[Try it online!](https://tio.run/##fVC7DsMgDNz9FQYWLITUrEngR5gyVZX6kPr/EjVNSIlweguS7zjf@bG8b6/78rzmjIQCZsAgQYMgjj4pkggdgumJr5ywJ4o8EDpopAVFzuOW0GscEwL@iFilPGMczb31pVX9bIRyhdtbrinJ9U5bNEIWuBGmNbeMwz6ISaEIXpSUtczzSyPoU8Ma3WyWarIWzzDvWf0Ifxy5cXPXnIcLDh8 "MarioLANG – Try It Online")
Explanation:
* The first, big *castle* reads a card number as input and calculates its equivalent point value until it reads a `0` (no input). This supposes that there will be only two strictly positive values as input.
* Note that I don't actually set the proper point values as they aren't needed, I just set as point value a number between `[1-5]` to help calculate which card has the most point values.
* The second, small *castle* just compares the two calculated point values.
* It returns `1` if the first point value is greater than the second one, `-1` if the second point value is greater than the first one, and `0` if the point values are the same.
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
Outputs 1 for more than, -1 for less than, 0 for equal.
```
lambda a,b:cmp(s[a],s[b])
s="05040000123"
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqObdAozg6MVanODopVpOr2FbJwNTAxAAIDI2Mlf4XFGXmlSikaRjqmGjqpGlY6BiDKFMdI83/AA "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 57 bytes
Returns the usual [-1..1] for <, = and >, respectively.
```
char*s="-FAEAAAABCD";f(a,b){a=s[a];b=s[b];b=(a>b)-(a<b);}
```
[Try it online!](https://tio.run/##VU65DsIwDN37FVZQpaSkSHRh6CFxfgJL1cFJKUQqLeq1oH57cGAAPPj5Hbasw6vWdmEaXY/lBZJ@KE27umXen1QbRZrVN@yCPmXhaXvcUu32BxZXHKUST0z7HItYESgHHDMlQo6JEvFsTTPAHU3D3YDdVUt3C4KA5knA0wMwdIiMLPpQElw0xaE1zpjydSGk@uFRIeJ38NFRtOLsjPV4gbYCvwRfw/SlTKJkSZqx/PPtcl1Qd9uzN1u7sdEL "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ε78920S>sk}`.S
```
Returns `1`, `-1`, or `0` for more than; less than; or equal respectively.
[Try it online](https://tio.run/##MzBNTDJM/f//3FZzC0sjg2C74uzaBL3g//@jDXVMYgE) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/c1vNLSyNDILtirNrE/SC/@v8j4421DGJ1VGIttAxBlGmOkaxsQA).
**Explanation:**
```
ε # Loop over the input-array
78920S> # Convert 78920 to a list of digits, and increase each by 1,
# resulting in [8,9,10,3,1]
sk # Index this list with the input-number (-1 if not found)
# i.e. [1,4] → [4,-1]
} # Stop the loop
` # Put all items of the now mapped list separated onto the stack
.S # Take the signum (1 if a>b; -1 if a<b; 0 if a==b)
# i.e. 4 and -1 → 1
```
[Answer]
# [PHP](https://php.net/), ~~51~~ 45 bytes
```
<?=($m=_5040000123)[$argv[1]]<=>$m[$argv[2]];
```
[Try it online!](https://tio.run/##K8go@P/fxt5WQyXXNt7UwMQACAyNjDWjVRKL0suiDWNjbWztVHKhXKPYWOv///8b/zcEAA "PHP – Try It Online")
To run it:
```
php -n <filename> <card1> <card2>
```
Example:
```
php -n briscola_score.php 3 1
```
**Note:** This code uses [PHP 7's spaceship operator](http://php.net/manual/en/migration70.new-features.php#migration70.new-features.spaceship-op). So it won't work on any PHP version before 7.
---
# Output:
* 1 = more than (`card1 > card2`)
* 0 = equal (`card1 == card2`)
* -1 = less than (`card1 < card2`)
---
[Answer]
# Javascript ES2016+, 73 chars
Not the shortest, but I hope interesting due to math and overflow :)
```
(x,y)=>Math.sign((x&8?x:(16-(x**40|0)%7)^16)-(y&8?y:(16-(y**40|0)%7)^16))
```
And the other version with 74 chars, unfortunately:
```
(x,y)=>eval('(x>y)-(x<y)'.replace(/\w/g,'($&&8?$&:(16-($&**40|0)%7)^16)'))
```
## Test
Open browser console before running
```
f=(x,y)=>Math.sign((x&8?x:(16-(x**40|0)%7)^16)-(y&8?y:(16-(y**40|0)%7)^16))
console.table(Array(11).fill().map((x,i)=>Array(11).fill().map((x,j)=>f(i,j))))
```
[](https://i.stack.imgur.com/OSqCO.png)
] |
[Question]
[
The challenge here is simple, and not at all about byte-count. Your job is to output the first 50 characters of the previous quine's source code, concatenated with the first 50 characters of yours starting with the 50 characters I've placed below:
```
abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXY
```
So, lets take an example here, if you were to answer in 05AB1E, a solution to simply output the first 50 bytes would be:
```
ži50£
```
Which would mean you'd need to output:
```
abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXYži50£
```
If your program is shorter, simply use the first `x < 50` characters. If your program is longer only concatenate the first 50 characters, ending on the 50th character. The next person will then have to output the first 50 characters of your quine concatenated with their own code.
***Your code can be any size, but you should only output the first 50 characters of your code concatenated to the end of the first 50-bytes of the previous answer's code.***
---
# Restrictions:
This uses the definition of a [proper quine](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine), and, in addition to this, the following things:
* Comments are disallowed, entirely.
* ***PAY ATTENTION TO THIS SECTION, IT MAY EVOLVE IF ABUSIVE LOOPHOLES ARISE***
---
# How to Post a Chained-Answer:
1. Post a placeholder:
* Mention your answer number and the language you'll use.
2. Sort-by-date, if you notice someone else posted a placeholder 1 millisecond before you:
* Delete yours, wait for the next opportunity, sorry.
3. If you've secured the next spot, ***PLEASE ANSWER WITHIN 6 HOURS***:
* If you can't answer, remove your reserved space.
4. IF the space has been hogged for more than 6 hours.
* Vote to delete reserved space, I'll handle it.
---
# Your Post Format:
```
#[Answer #]:[Character Count] Characters, [Language Used]
{TIO MARKDOWN}
{LINE_SEPARATOR="---"}
{ADDITIONAL EXPLANATION OR INFORMATION}
```
---
# Some specific notes (Important for Ease-of-Competition):
* If the person before you has included newlines or non-ASCII characters in their source, you may STRIP them. This means that `x="a\nb"` becomes `ab`, where `x[0]=a;x[1]=b;`.
+ You must state the mutation you've applied to the previous source.
* All characters are counted as a single character, despite code-pages or language encoding. Please do not use byte-count, use character-count.
---
The accepted answer will be the `50th` answer, just because; I mean, it's SE afterall.
[Answer]
# 1: 96 Characters, [Haskell](https://www.haskell.org/)
```
abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXY:z=['`'..'z']++'A':['C'..'Y']
main=putStr$z++z
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orLK0dnF1c3dw9PL28fXzz8gMCg4JDQsPCLSqso2Wj1BXU9PvUo9Vltb3VHdKlrdGcSPVI/lyk3MzLMtKC0JLilSqdLWrvr/HwA "Haskell – Try It Online")
---
I was feeling silly, and saw nothing forbidding the first entry starting with the exact *same* 50 characters as the initial string.
* `['`'..'z']++'A':['C'..'Y']` is an expression evaluating to the string of those characters, with a ``` prepended.
* The result is pattern matched on,
making the variable `abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXY` equal to `'`'`, and `z` equal to the 50 characters.
* `main=putStr$z+z` then does the actual output.
[Answer]
# 2:119 Characters, Javascript
```
alert(eval(c="'abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXY'+`alert(eval(c=${JSON.stringify(c).substr(0,37)}`"))
```
[Try It Online](https://tio.run/##Ncw7DoIwAADQuxAT2qjExMHJwfhHBRW/G6UULJQW24Ki8ezVxfEtL0M1UljSUndVSWMiC8Fz0hiDBVeCEYeJFJAaMYCHlo0iHJMkvdEsZwUX5V0qXdWPZ/MajSfT2XyxdFfrjedvd/vgcDydL1e7HSJGpP4frbcb@J6jtKQ8pUkDMHRUFf0Mep3@AH5CC0Jjvg "Try It Online")(uses `console.log` instead of `alert` to output)
Based on [this JS quine.](https://codegolf.stackexchange.com/a/130317/70761)
## Old version(reads source code):
```
f=_=>`abcdefghijklmnopqrstuvwxyzACDEFGHIJKLMNOPQRSTUVWXYf=${(f+"").substr(0,48)}`;alert(f())
```
Based on [this JS quine](https://codegolf.stackexchange.com/a/60148/70761)
[Answer]
# 5:76 characters, [Emojicode](http://www.emojicode.org/)
```
üèÅüçáüç¶aüî§s=:'"alert(eval(c="''abcdefghijklmnopqrstuvwxyzACDüî§üòÄüç™aüî§üèÅüçáüç¶a‚ùåüî§üî§üî™a 0 45üç™üçâ
```
[Try it online!](https://tio.run/##S83Nz8pMzk9J/f//w/z@xg/ze9uBeFnih/lTlhTbWqkrJeakFpVopJYl5mgk2yqpqycmJaekpqVnZGZl5@Tm5RcUFhWXlJaVV1RWOTq7gHR9mD@jAWjEqkQIB8nMR3N7IGJgvCpRwUDBxBSkFIg7//8HAA "Emojicode – Try It Online")
---
Explanation:
```
üèÅüçá üë¥ start
üç¶ a üî§...üî§ üë¥ define variable a as that string
üòÄ üë¥ print:
üç™ üë¥ combine those strings:
a üë¥ a, and:
üî§üèÅüçáüç¶a‚ùåüî§üî§ üë¥ string literal. the ‚ùåüî§ works like \"
üî™a 0 45 üë¥ between indexes 0 and 45 of a
üç™
üçâ üë¥ end
```
[Answer]
# 8: 70 characters, [Stax](https://github.com/tomtheisen/stax)
```
"v->{String t=`"‚õΩas=:'\`"alert(eval(c=\`"''abcdefghijk"c'".`"R34|S50(+
```
[Run and debug online](https://staxlang.xyz/#c=%22v-%3E%7BString+t%3D%60%22%E2%9B%BDas%3D%3A%27%5C%60%22alert%28eval%28c%3D%5C%60%22%27%27abcdefghijk%22c%27%22.%60%22R34%7CS50%28%2B&i=&a=1)
## Explanation
```
"..."c'".`"R34|S50(+
"..." The string from last output
c'".`"R Escape all double quotes
34|S Surround with double quotes
50( Take the first 50 characters
+ Append to the string from last output
Implicit output
```
[Answer]
# 3:56 Characters, [SOGL](https://github.com/dzaima/SOGL/)
```
"alert(eval(c="'abcdefghijklmnopqrstuvwxyzACDEFGHIJ”1#Οj
```
---
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIyYWxlcnQlMjhldmFsJTI4YyUzRCUyMiUyN2FiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUNERUZHSElKJXUyMDFEMSUyMyV1MDM5Rmo_)
Explanation:
```
"...” push the first 50 bytes of the previous answer
1#Ο wrap a quote around with that
j take the last letter off, as my answer has one more byte for the starting quote.
```
The Javascript answer had a quote in it, so I had to add a starting quote, but as this isn't code-golf, it doesn't matter.
[Answer]
# 4:81 characters, [J](http://jsoftware.com/)
```
s=:'"alert(eval(c="''abcdefghijklmnopqrstuvwxyzACDEFGHI'
echo s,50{.'s=:',quote s
```
[Try it online!](https://tio.run/##y/r/v9jWSl0pMSe1qEQjtSwxRyPZVkldPTEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orLK0dnF1c3dw1OdKzU5I1@hWMfUoFpPHWSITmFpfkmqQvH//wA "J – Try It Online")
---
[Answer]
# 7: 137 characters, Java 8
```
v->{String t="‚õΩas=:'\"alert(eval(c=\"''abcdefghijklmnopqrstuvwxyzA";return t+("v->{String t=\""+t.replace("\"","\\\"")).substring(0,50);}
```
[Try it online.](https://tio.run/##VY9BTsMwEEX3nGLkTWy1jbphQxQkDkA3lbohLCaO2zp1nGCPDaXKSTgLl@EiwaXZIM1o9GdGX@@3GHHVD8q2zWmSBr2HZ9T2cgegLSm3R6lgc5UAW3LaHkDyXa8biKJI2zF1Kk9IWsIGLJQwxdXjZX6mkv18faMvH7KKoVGOuIpouCwrlmVYy0btD0fdnkxn@@HNeQrx/eP8@cQKpyg4C7Tg7J9hxdiCcqcGk9g4S3LJqioNIXIfav/3x9fL@7Uoxqm4AQ6hNglw5ozXAF3KyW@uL68o5oxnT6rL@0D5kC7EbS65DcaIOe44/QI)
**Explanation:**
```
v->{ // Method with empty unused parameter and String return-type
String t="‚õΩas=:'\"alert(eval(c=\"''abcdefghijklmnopqrstuvwxyzA";
// String containing the first 50 characters of the previous answer
return t // Return those first 50 characters
+"v->{String t=\""+t.replace("\"","\\\"")).substring(0,50);}
// Concatted with the first 50 characters of my answer
// with correct escape-slashes
```
[Answer]
# 6: 70 characters, [Emoji](https://esolangs.org/wiki/Emoji)
```
‚õΩas=:'"alert(eval(c="''abcdefghijklmnopqrstuvwxyzACüöòüë•üí¨‚õΩüí¨üîÄüë´üí¨0üí¨üì•üí¨-1üí¨üì•‚úÇüë´‚û°
```
[Try it online!](https://tio.run/##S83Nz8r8///R7L2JxbZW6kqJOalFJRqpZYk5Gsm2SurqiUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVlVWOzh/mz5rxYf7EpR/mT1oDNABEfZg/pQEotBrENoAITAbL6xrCeI/mNIFUPJq38P9/AA "Emoji – Try It Online")
It seems that it is impossible to make it not output the trailing newline. If that's not OK then I'll remove the answer.
**Explanation:**
```
‚õΩ ... üöò String literal
üë• Duplicate
üí¨‚õΩüí¨ Push ‚õΩ as a string
üîÄ Swap the top two strings. Stack: [long literal] "‚õΩ" [long literal]
üë´ Concatenate.
üí¨0üí¨üì•üí¨-1üí¨üì•‚úÇ Remove the last character
üë´ Concatenate.
‚û° Print.
```
[Answer]
# 12: 202 characters, [Ruby](https://www.ruby-lang.org/)
```
puts "21ipdgmtwkkke7ynvzpcnlzt7kl".to_i(36).to_s(7).gsub('0','>').gsub('1','+').gsub('2','-').gsub('3','<').gsub('4','[').gsub('5','.').gsub('6',']')+'puts "21ipdgmtwkkke7ynvzpcnlzt7kl".to_i(36).to_s(7'
```
[Try it online!](https://tio.run/##KypNqvz/v6C0pFhBycgwsyAlPbekPDs7O9W8Mq@sqiA5L6eqxDw7R0mvJD8@U8PYTBPEKNYw19RLLy5N0lA3UNdRt1OH8QyBPG04zwjI04XzjIE8GzjPBMiLhvNMgTw9OM8MyItV19RWJ91Z6v//AwA "Ruby – Try It Online")
---
Encodes the first fifty characters of the previous answer in base seven
* 0: >
* 1: +
* 2: -
* 3: <
* 4: [
* 5: .
* 6: ]
Then converts it to base 36 to get "21ipdgmtwkkke7ynvzpcnlzt7kl"
[Answer]
# 9: 55 characters, [Jelly](https://github.com/DennisMitchell/jelly)
```
“"v->{String t=`"as=:'\`"alert(eval(c=\`"''abcdefg”;”“;
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxylMl276uCSosy8dIUS2wSlxGJbK/UYIJ2TWlSikVqWmKORbAvkq6snJiWnpKalP2qYaw3EQK3W//8DAA "Jelly – Try It Online")
---
I removed the non-ASCII character `‚õΩ` from the the output since that is allowed and Jelly was ignoring it.
**Explanation**
This begins with the string literal of the first 50 characters (minus `⛽`) of the previous answer then appends the character `“` to it with `;”“` then appends the original string literal to the end again with the final `;`. Since a character was removed the first 50 characters of my source code are the 49 from the previous answer with a `“` in front which allows this program to be so short. (Yes I realize this is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") but why not golf it if you can?)
[Answer]
# 10:116 Characters, Python 3
```
print('''“"v->{String t=`"as=:'\`"alert(eval(c=\`"''abcdefgprint(\'\'\'“"v->{String t=`"as=:'\`"alert(eval(c=\`"''')
```
---
Simply prints a string consisting of the first 50 characters of answer 9, followed by the first 50 characters of its own source. No quine-like cleverness is needed, becuase the escaped quotes (`\'\'\'`) appear after the 50th character and hence don't need to be reproduced in the output.
This method will work in virtually any language - you'd just have to escape any quote characters that appear in the previous answer. Accordingly, I don't think there is much challenge in this challenge.
[Answer]
# 11: 723 Characters, Brainf\*\*\*
```
+[------->++<]>++.++.---------.+++++.++++++.+[--->+<]>+.-...-----.[----->++<]>++.--[++>---<]>-.---[-->+++<]>-.[->++<]>-.[--->++<]>+.[--->+<]>+++.--.---------.+++++.-------.-[--->+<]>--.---[->++++<]>.[-->+<]>+++.+++[-->+++<]>.[->+++<]>++.+[--->+<]>.--[--->+<]>--.+[-->+<]>+++.---.-[--->++<]>+.+[------>+<]>.++++.[->+++<]>++.+[--->+<]>.+++++++++++.-------.+++++++++++++.++.+[--->+<]>+.+[--->+<]>++.[--->+<]>-.[->+++<]>-.+++++++++++.[--->+<]>++++.+[--->+<]>.[--->++<]>-----.+[-->+++<]>-.++++.[->+++<]>++.[[-]<]++[------>+<]>.++[->++<]>+.-[-->+<]>.......---[-->+++<]>-.+[--->++<]>+..+[----->+<]>.++[-->+++<]>.[--->++<]>.+[--->++<]>+..+++.---..+++.-.........+.---.....+++.---......+++.---.++[->++<]>+.-[-->+<]>...---[-->+++<]>-.
```
Stripped unprintable `“` character. Almost completely generated by [Brainfuck Text Generator](http://copy.sh/brainfuck/text.html). Might as well be lazy, right?
[TIO](https://tio.run/##dVFbCsNACDyQ6AlCLiL5aAuFUuhHoeffuj52dUMkj9XMjDq5f2@vz/P3eLcGjBY7wHbIg@TCCElAS/ZixXUYIZHBiCsdkQF2qUiKHcL6ETRlxxnLOTRllX9qHxkOILpyZ/ScOCnIPXtay1htCBAWMeAywWhl84VHxtSRLlRhBpUdRnWxMZ2TDzj1C784VRrPcb1pdv00MTMe2wHrXjw2xvCDLJbfCNmdsGeqJO8DtlLcZjtQhBcpAXJyNeEyXWt/)
```
Print [print('''"v->{String t=`"as=:'\`"alert(eval(c=\`"] +[------->++<]>++.++.---------.+++++.++++++.+[--->+<]>+.-...-----------.++++++.[----->++<]>++.--[++>---<]>-.---[-->+++<]>-.[->++<]>-.[--->++<]>+.[--->+<]>+++.--.---------.+++++.-------.-[--->+<]>--.---[->++++<]>.[-->+<]>+++.+++[-->+++<]>.[->+++<]>++.+[--->+<]>.--[--->+<]>--.+[-->+<]>+++.---.-[--->++<]>+.+[------>+<]>.++++.[->+++<]>++.+[--->+<]>.+++++++++++.-------.+++++++++++++.++.+[--->+<]>+.+[--->+<]>++.[--->+<]>-.[->+++<]>-.+++++++++++.[--->+<]>++++.+[--->+<]>.[--->++<]>-----.+[-->+++<]>-.++++.[->+++<]>++.
Clear all cells to left until first empty cell [[-]<]
Print [+[------->++<]>++.++.---------.+++++.++++++.+[--->] ++[------>+<]>.++[->++<]>+.-[-->+<]>.......---[-->+++<]>-.+[--->++<]>+..+[----->+<]>.++[-->+++<]>.[--->++<]>.+[--->++<]>+..+++.---..+++.-.........+.---.....+++.---......+++.---.++[->++<]>+.-[-->+<]>...---[-->+++<]>-.
```
] |
[Question]
[
## Challenge
Hi, given a string as input, [remove any salutations](https://meta.stackexchange.com/a/93989/267184) found at the start of the string.
The program which performs the most correct substitutions in under 50 bytes wins.
## Salutations
Hey, a salutation is defined as one of the following words:
* hi
* hey
* hello
* dear
* greetings
* hai
* guys
* hii
* howdy
* hiya
* hay
* heya
* hola
* hihi
* salutations
The first letter may be capitalised.
There will always be a comma and/or a single space following the salutation which must also be removed. The comma and the space may be in any order (`,<space>` or `<space>,`) and both should be removed.
The greeting and the following word will only ever be separated by a comma and/or single space.
You must then capitalise the first letter of the word which would have followed the salutation. Even if no replacement has taken place, you should still capitalise the first word of the output.
Capitalisation only applies to lowercase alphabetical characters (`abcdefghijklmnopqrstuvwxyz`). You should leave any other character as it was.
The salutation will always be at the start of the string. You should not replace a salutation which is *not* at the start.
There may not always be a salutation.
Your code must be under 50 bytes.
## Examples
```
Input > Output
Salutations, what's going on? > What's going on?
hello i have quetions how does juice an avocado > I have quetions how does juice an avocado
How d'you do > How d'you do
Hey,You! > You!
hola cows eat hay > Cows eat hay
hey Hi there! > Hi there!
hihi ,guys > Guys
```
## Test battery
Hola, there are 1000 different inputs in total:
* The test battery can be found here where each input is separated by a newline: <https://github.com/beta-decay/Remove-Substitutions-Battery/blob/master/inputs.txt>
* The corresponding correct outputs are here: <https://github.com/beta-decay/Remove-Substitutions-Battery/blob/master/replaced.txt>
A Bash command to retrieve both the above is
```
wget https://raw.githubusercontent.com/beta-decay/Remove-Substitutions-Battery/master/{inputs,replaced}.txt
```
## Winning
Howdy, the program with the most correct substitutions from the 1000 inputs above wins.
You must put the percentage of the inputs your program handles correctly in your header like so:
```
# Language Name, percentage%
```
**I'm not completely sure why Jeff made this a thing, but it makes a nice challenge nevertheless.**
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~68%~~ 72.8% (old) ~~74.8%~~ 77.5% (new test battery)
```
i`^h(a[iy]|eya?|i(h?i|ya|)|ello)[ ,]+
T`l`L`^.
```
[Try it online!](https://tio.run/nexus/retina#nVzbihzJEX2fr0g/GGtx4l9YGgRqI79JMAzLLkprmqmy2mpZ3bNDgf5drop7RFbBRL3sznZXZ2XG9cSJyP3rm3effo6f/hjetN/G6fcfp6n9@mN8M/w6/pjaj19@nM7nyy@/lfr73@/uPn46f/rXpz/@8fPnh3Z@vrXbePl6reXpebrePVxq@Xa6fDuf7obTVOrny8u1nNqtDG26@3J5af9@/vrU6OFhLO77w/g03MrL5fv58e44Tq3U6fL8l7vjvBn6xVVfWCqu0UZ54/Jgqf@c1/rzVP73fMLnhstLebycruU/z@PnU2lfS/vz8rk9Xu7uh3b727U8f8P3TBd8yXHZ@OtXGRbZyInm3bgzvZs/li/n7b1@3eM4y6fS0ezBYbOzoOHfDWQGf8JGgsjv2/U6n49kusjqc7tdF920Moz4DveDWzt/KbdL@e8Jn5zoPagPXGf@tX/LC77Fr9TO35e9JSTJvyj0xgo7WCRIRjFvdt70cDk3/OqDNQf38sUs5kd5Y/OfB1wcT2UsEf77OEuaBYPKevp@mvf79elKAlNVHEfYxQG3iht7YUsqy1sXOaftB/eBKoQdvOMdBLk@ntr3mrAjeJ733kZRIpjX65cBNSynWywGRTKMKpOBtEUGhxq8vDxOdJp7lRA6GbzeHezhggurW2acxSgIBOqWpp3A8g0VB7swesMzLc@xUsFJ3DJzhKB3qHJIFiMtCMePxjiSzOVXEiMb7@o9W2QxupKdtIkNZLF9vynrBLN6zEKgrDETcmbHRue7D4Ihtb5@qVlUaATLDvj4EAvx78UqEzvD1IArGtlvyGHzCzwcK0kTyCKpJopH1wZHnpavVG2dI7JNUXBJCMiaXvAClBuYIgfuKePxLkuKh/rN22cysWqSFd8ucYUSW@fLqC968r1GWzgaRjBN2qQJWLAEvz0zCqAwqQ5Bv2fRw0Pu5BrnYmYC/XKub3uUVjkJ@5WXkOEF8VHy6U4NooGRyZJ9Up5EuTSNfCatJVAQLh1cC8ONWj6Ka/kHbmhxDciwYsZqqqwjyJOQN@Z/G0H0IgtaR1UDPplDMBsKxPDeysKPWTj@07fgq/OKywnIwea1WXAAKQBaQPyHN1NCw3fgkUS@hbK8jbdVs6LgyEZy44gj0LjLUE8@oRwZqSkOSXgpZbut6MjoxQSHlBeADOFcqlTMNuCufPgVXxa4JantXhGawD/albEYWBKhbqwDMqYOMV5qCgbSiNnQ5l6/lsmzGw5PgUuOFXClhEKGuyk4htKkXw6KFACmg5DfanqaQTy8fIrxaj78cna0eo9D6L8PNrwqMrNZHHGGl4IGEkKCs2FgrgB3p32ThIyiyTPZMNUrOLzAVtH7Yu4NBQDHITJ1eBb2S5ICJ3HeCS8/mBKkeS@ZQx6hdFMLwTIZExxrFvewKpx3vNWjTBf3KYOGRea6X58uURzXzfrJlIHqL1yZs0DMQyYpsCFWIyv@1r/E2porJyWnUEiVOArRlbehhQiFnAaWMUsjnDVVdDunLfouMdqJIr3Jja9ff4k2uOb7PbkaagJTj6tlKiAhHqZzdH7YZgKNPFry8HMzgjdOruLX7Ek7aRn7P7oKywQeg10EP1QXglIwNZnOcllkhJhHwAn2@HCp2SAgtl1d2VY9WCqqDZutMzb3YR/UH0NIB6C@ICiNyZA75jwk7le4pHLoHvV5M0hYSahUcQoYDY/fk2x9yogc0V4EbpEKZjuMNIMCPAgLadDNggDYpLGcUzK8S/AshjZ4@yi19ZDKJriq4OlzRvwA@iJyJ1eF7@rO8qZH/sLEMS4ryrIIQlBOlTXAXx4lNCFnZUjkLaQGL5ofiHAk4y4UGCGa6N5yUYtSy30oqkDjvlyAkyksdjXySuUDT2r5Eji5ukUN4LIamtfpfI1MAEqFRBcYanMGp28g14TSsoVIEai2Vhf2BXeJVACe7pDnZN7tKbYkebKnEs6FvSLu8f46G5sLSmu17xYYyxkkVpCQ3rjD0RXftgROtT0MPQmEvDtFIxz11lI9atberDoAQHmlGCbUOEJGBpHBRauCLCJACsr4pqgY/da8m2pWpXEhFDK61YaX5WuL9i4MtWyAfOYct1AJH3NFBIaAPdRkKjuXvixAcYARdOHLsSQ9seq4JSGflEJpkdUbmLFpJmN@DO0s1ILU@6K50VV5K0mp5JoRxiikcFqswtQTOcBpWMAO6WiVz2BU2IDR1N/aH5m6ZtlmZlTCVjFbV2lnhCNh2dR2O1gXEfCj0NBoVMEmhpF6VgnzJ2yWJWO4hAJrmV8KbqcZYA/LrC3MkIglia7w5QhD1nsWnKNM4MYtWp7aoBf404QfQr3C3rm@p@6bdPMAePUoPqeF/C2@7rZBD6Ofdj2pqOTYRaMDugZxqvbJPK6JLEiFfWaxCG2dU3vn3BiumvA2S@nmYClYMCHYZZkV3@@KNHH5Ku3y4iARAWYkPkfmVqAYt2FLujKbFKdUQSbZZ3qENd2mMOAq2QLHfh4hX3SqDcoST3PIs0dPoV1ylPYuknHeaqdGCgjR92jK59Ex45uMPilUgUw/NrIxnaFofBPcc9fENoIdHStVP/mpa69qB89uJodjaQcS8w9uUGTxqb3dUfGPLcCtXSHNMV3sS1uxMlwou@aS4jt71uPYTxO4lliN1K5FOpU6cNUnhSpcvCHG667mR266IM46dLlHNWqCXhS4N4Oyau1@vqOrslLU08EVloOUrgB9tLIz5XiSDFynxUPbtDuC6b5n53g0QXcDLTlGjlu8KwjeDqj10zhmlkxBEiU8EvSHtTmGNpWe6TNjSLgGbgzr7Vh9ViWzlWFiBij6kiOqpd2WHpxyjV@Dw@38VBCSGa/COpYpMNuakhjrOI8VZdjZKBEmYUsexvSfOu7dkgS@@7EymUn1cqy9cSBUyuKuXVf2UdqdeqVNpTXYMBpCEP5SpCgEu@33d5Wl8g8Z/1i07Yf5mDEV8bHhlcg98rny1cipl7yOFQLFppMjHNGqmd/wUwp@JE9JveI5RferYGHFDrFoh0phZzdWVywVI4MVRdCKfEgQ1rZoY5Tc19Q3neHazzFkyABLdMbxXElpAKSB@nPjLnWjMWrmOVWrIX6EgPJlo9u6uOWe2tQW4KUbkHFjS5VjcpWOYQ1QzlkP838Kk2SA2VCOsXDk8cBkO0/lAh0Wv3MFIbQFQWoMtS3LTTRMcqDOgGbhaesqKWxwXWropQc/lqS21Y4QVJJ7Wh8PkaUnebihBCnEhxzD9XCxmSF3Nk5f2det@2E3SrfHkuzAq1x1CLRMzAO5utlyTZvDrpqzNMrPZnv1A8MH53/GNeH5jq1Jo@aa69uvZi7fgTUhAPrwGpKwN5sdlavJNuiejpIdsMCUpXW91BCpKbz7LhIf1Rt0XAdZyI4jUn1bRiTVXxq0rVX6Fr/vcoGiXNdLWLBiUW61u2acb8bGDUAQgRZ70wM//RhbEIADXEQzP7ezbCtlTIdNzCyM6/wVNx2hrfHYn0zfiPEN1pWrN3L7SOoYc41qdaY6M3OkomMP3EWJSXu87PGfslbkByhvCEv4xhpg17NA3AT@HyZtderezTcQiDGjbkkhEvhh1N1CbbWsrUWxvYqAiCRgcH/5SUou6fwUX8HxgJgvRW1J28GpbBh1LQCsv0d7mQY@e1SkdFy5sDbITaKjygP3Zy8G6qy2aQ3aN7nBTgdVVu7HlU3uc4@hU1tzOVuo/VAH9ordOgEdYqXtdMUxfX/jR@Zqc81hd@OpZq8oeuvchiPVhPaqDcqy44Jg3/8xV0Cdup18FPTW7MSiiflMxCjbTuJ7kPsp7/1ow6N0Ah91GuZoxwyG3J3TD/F@yMHQQU869XSNPYK2Nio95iZYdZbcEJ7J7rhr1NvkhvKzELWjAs3kRWj6mXF4Rt3qjF226CD4Ss21Z0ZDB92LTKZZ6FHyV2K3Kvk4lb9yzUluXIShm5jTLYVaJVPtKaN3tmJc063PcFaRhjgyEyaZdBW7cUe@wImJM1JIs6drUmDMW32z1lwPrnJnWDpjOmniOhva75FrP8nwy@gUJ436S6@0Ayz9Xro61yRsaWSUte65jIrnxFztBH1uFrJ0t2b5XnjsB@X9aZbFg7uhCmJ6Hxr5tvkiN9C37m2VLQwRBvHrah@Wb6Bq1y8FLks19VQ/9xxStMm@exw8ju/JhS/bmdCU6P7nBDoQkU7B2VFanbNQmkPmFEp/icVS4F1fkgGnu/4aOfuVnob/BDaTxWbh/rxr9JQ@X9bcXITe1wsFw8rcZNiJQR7hRoyGNYPzbJo3IVB8UGl@c7vCBU5qulKA/T8 "Retina – TIO Nexus") Edit: Gained 4.8% (old) 2.7% (new) coverage with help from @MartinEnder's tips.
[Answer]
# GNU sed, ~~78%~~ 100%
```
/^\w*[wd]\b/!s/^[dghs][eruaio]\w*\W\+//i
s/./\U&/
```
(49 bytes)
The test battery is quite limited: we can count which words appear first on each line:
```
$ sed -e 's/[ ,].*//' inputs.txt | sort | uniq -ic
40 aight
33 alright
33 dear
33 g'd
41 good
36 greetings
35 guys
31 hai
33 hay
27 hello
33 hey
37 heya
43 hi
34 hihi
29 hii
35 hiya
45 hola
79 how
37 howdy
33 kowabunga
39 salutations
32 speak
34 sweet
40 talk
36 wassup
34 what's
38 yo
```
The salutations to be removed begin with `d`, `g`, `h` or `s` (or uppercase versions thereof); the non-salutations beginning with those letters are
```
33 g'd
41 good
79 how
32 speak
34 sweet
```
Ignoring lines where they appear alone, that's 220 false-positives.
So let's just remove initial words beginning with any of those four letters.
When we see an initial word beginning with any of those (`/ ^[dghs]\w*`), case-insensitively (`/i`), and followed by at least one non-word character (`\W\+`), then replace with an empty string. Then, replace the first character with its uppercase equivalent (`s/./\U&/`).
That gives us
```
s/^[dghs]\w*\W\+//i
s/./\U&/
```
We can now refine this a bit:
* The largest set of false-positives is `how`, so we make the substitution conditional by prefixing with a negative test:
```
/^[Hh]ow\b/!
```
* We can also filter on the second letter, to eliminate `g'd`, `speak` and `sweet`:
```
s/^[dghs][eruaio]\w*\W\+//i
```
* That leaves only `good` as a false positive. We can adjust the prefix test to eliminate words ending in either `w` or `d`:
```
/^\w*[wd]\b/!
```
## Demonstration
```
$ diff -u <(./123478.sed inputs.txt) replaced.txt | grep ^- | wc -l
0
```
[Answer]
# PHP, 60.6%
50 Bytes
```
<?=ucfirst(preg_replace("#^[dh]\w+.#i","",$argn));
```
[Try it online!](https://tio.run/nexus/php#xV3bjuPGEX3fr2iPF7AXbuQDsnEWgg1Iwb4EmAEGgu0EzEgWmR0PJyONBSHItztkk@yuy2mymwtqX3aHTfHWl7qcOlX9lw/P5fObX@uXffFQfvvTm59uNtWlMA/1@Wj2xcmUxeXG3vxAD3@xza/ui@Px9dle6tevmvP0yJ0uqkN5Ms/7@vlx35xf0UP3g7KqbDj/d3JmU1ysOdcvj7v2xu5/136o650pfj3tX57q@km@4XrkbP/AS2H/1hz/vjf/ed2fqvrpaMr6bHb1/mj@/Vo97E3xZIrf64diVzd3TP9t99r1Y2GWfEBZVLasmus2VXiiNayp3F8WfQc3N/hblJXpJ8HWj37zqmgEd/vixRxeL8d2vNr/XOtt8fh6KrrHq5NiWO3wA9TcTbzHFzfX7PD8FW/ou@nxsbYPxam91w/tf675PD6n3eurb@WvYg18w765m8ff7MyuuJjfitO@68q1aOnesT7vLlb3yF3x@MmcavPb3li/fkBjf5N2iqh3/lSfi3@9Ph2KoQ8@8oZuXJ73hb9pfwvd1s9E965gyMuqrPBqftk3U@7pcLRQCNBO8k9f68YgbKwQCCvd6H58JJ8wvNetahuGwBQv@7b/fCduVNvQA0OzyVl/866TE6EfRdniP2L3TXv/XR36egNa3c/9TPCdI1u6791fIuKbPc/gBzJN4ATnpL7xyzind2dcRB9m5WvhdiJSIhqNDLKXS6ARzHwlH4wXEJsKSIdOaiyoAejy8R97qxuDulDSp1uZfn6xQyRS@9mNWt3PT2Hau@66Y8dEDiqBT1SPUKTN/C5g97r7TE3WI7mvVmlU2ksrJnpOCM3I2nPqWWvYMDw2SzrNvJBYgIPoXpGj0JPqTdsGYyf7t9M36mqixfgdIie64Wguj3TnpQ7t25rP7P1lWWuve4BaO07uThvHXsqsYXs3K87NZMr6hNwrfP@aJQWSeykii9gxF@fBHxEtvbRadkSp5dDPXd3W9dmwzo02UkvnZ6iJ4bphkHC34SDI4esoBW8o3aq2oO3VymXKUPcNNfA3VQWur2xUzzi5Hv6WKmN43J1s8i8WzBaqu2XrsDyxKGnER6fL@z96@WKJfFGG@7SeaVxlMBWCdW@ichBYMM3b9G/oXzD83r@nagLip@/ztW70sxHp1tbv566lm@pA2nXaWS0NpxYS1EfZXg6c1os1V1r/wJm4yHnLwRMuqtp3nfxMMsn7592JFvq4vjfpEVETw6IOBwQPUF35Y@spT/p15BPXqLmf4ghfAMhHO1e4Cde4nrylUxXe6SNHBMHJ6VYtOoLkcHjTqMXJ3o33wLA4dGN/b36xQyZ4dxRVxB9HFrm7fvLDw2fKToqdkUar6o4OY@lFIznwy1SATcdY9xWDQp/hHmabtsOL@v5lx8MILSlL7svi9M3RvD7nPWXWZcG91RPHrX@x6jCgQ0dOz4PVuLPQ2TPuOf7PoAAX7Oez77B53Zz5uIsHJbe1fWAm33W@0s9o0UJcEm2QdsgH0MatOI05Vjmfs60/BxuLiSoE4jTKJsF8aIcD@9@N@afWCAVHZjrf83xvBrBQK5WsxQQsg9jxwLQPi5QoAYnDENuvm0NTD6UxAat1uGH2CJUUrY4Epl37VGhwAhXZdV7/61U40I5KP@V1m4e@9UOZAYTtHwjH5gn6WZdJ13NBidOPWzb4kI3k8rHh0y5@LjgZMYi78TOW7J5RZekmFsKA2rkvYnNaXPsBRh5QBb0th7bBnnDgjr4PfD2nq9V6GAy3OXZbtg3TBrZlf/Q4JXV/6Cp20WjggJCpw2IcsnWQNAlCT2J4QTrgE0McHXV2CNrYWXIje6ExCKgf5VvVFrzDRSPlZBy69cAb1BqbVvlNLy8LDTQCBQdzgMU1hLUGHUUPB4wsYpBFjPMOM@WeMbUY@lg4d3i4vwPc9C2BzLYcKCshDNgKICiVgGdvIwQDLgEbS9NmmprZKgbqeRonG0bwVrUFpMAkmJ0UdCS2h2hUIR8Q5baRKPfM0HVul22JK0mQKBbnHImMRSx3OLUDWmMVCEbsxmZ6@jei@FZRyalX4agVUBLN3PPeHAPjTY79C24cvLP@/qLBq9slRVYBbAtnmSQoura/dFzUGyYiEuu4OlP3JBZvf2fZMlhE6sE97advvydHAS1GOvaCMP1VDhfFO95GOd4sqrAsmET9tOE9dFtQ3VqxNMJfy@0eFRNdgVqDdQZ6uVUceRI82@ehsroDmXiDArCuZLtciUh0vJYzxqktA61DN3q1Gluro9ArtUTlaAZsuRpBluNENjX1KZSSFngCK4XZBZBUI0x@2DNeckilQMlgzUoFUlt2xmBRzuFazaDNxtgs@4tQBcWyEXo6c8RY3sZOBahADSsxPYBYZYGnTMrc4ABH6GnYPNLg/fUNPxcvgIMdZqsGodny9gRf4f2woP0j1thskeP4pHC1B@YpavbeCbwT1aA5vTvvOu0hALALnyOSCXRZbxxlhT9yLwmRSTwmIYDIxMHtKOXFBaymDW3n6obIkqUkBTNO3jOIlnzhoPOS4uqUbretocXtxBZiUfiZwjBu0UiCPGPer/Jsb6PnBADNBvuUxnbmMpMwiUSjjBIhJv2z0EVmfDZYELSXVKJJVMpLtyEUyo6DPzJtahQAULpPC/SRiaX62vK@HvSADoWQH/qPGEBWdozkLk7zOLCZK/NQckZePC5nka7nXqoCWxhRZ5QPT@MErWC@52rxOVdyitm14OXeg6YcJSHrAXBYVUlUYr8INSuLEheb7gemc9R0RXk3ZTxrIkYc7DltC6qRQw7zSMz@WIjiWZDShea@1Jbgwth3m8o5cioth6wFjHBmWBIHSkAW@ITn@UStptA99@xYSQLWOffX5Zx0JEuRWBgWAIhxP3Dqh14VQTrMEw4zLEfss@8TWJJD/A8gdigqvJqRhTQrB8nJigWXvQvdJpgRiwa@XMBGy8liBpdvFpOPZfiBzCymazucbIhthgMSQpOmrm6UYHUOQztIqFmSwcyKSmrIq8P@WLBwJIMNclw4oNWy5qHvmYoJdOAc1p9ORNmslC0kSlxfMCkp89FRlhqRleTNo/oFQUtdau20I0u8qrkpXrkShPP7IVRCFXZgFoEODtEf4KZCLdPTtWWzSEXA6dgHGnJOyLPoJhFIO4FBsJQMtqKyWRHf4DLSFrogCT3Woxg9ekPo1SC3w51lh8Tk5lmaguEcZSYIR@@Bdc6iNRIuuBqBnUrMtcDSsUYAHYJcVUbv6xwSTW9oxZTO3GJkr6QQgkTFhXm9zpNMQcwGe1U2UVMpJFQRrr7rDJxTkwC0JpRNOH0BPHWPXL6O7qyDOB1phkCJLPs4JTqkeC7aNA9mfrem6aEPlwYOeQQZYzl2otF/OZi@Eaib6hAUvmLKnkbMlmaYptpjzgxVI72N8TdU8NAj1AghQKGhIWw5hOro4UASGYnwzfMMs10QxsLGqzjJiehtGJDbp6k03gzQxFVqPyJgTFImtGkQLJCJMi6zqgshF7SYhj6ZlqeZgaKRZD7Gk/8VJDqoMok4szISWIlVI7BAAun1mBnVpnjkbCDzM/y/UQibg2RjVRvA5KCqCwQaRGpnij3aGhJw0FYJ0dEqIrxSrNaYOu81Xn41gc9Anvul8lG0hACBjngXVYxPz7qkh@9oViLT5ch/yXM7bnPKqFAHUXI7LLetQZAfVoByM0g3E/gBZHyzl@IrAoRCadY/k3EopMjF4bD@QJUEibiA0G1nprJcwvAmRIlyCyrYsrfjUMAmjeRIUeZ59mo@ZNgO6qKcz5Q0BjJfVAkpHrtyIfaILiuhZw2mLFUzIGKA8Adt2TbmLkqoocZFVoxw3oXegB/qMIS0OarjYBUKQdKMdau9Co8U0BEY@d8B9kvCALEEgdYfjdC3Y9Uk4uUnUkLw6PLgtA2UY94g9ZyWxNxy@jSn7JHPfedEAyq0e/AIM3ghdaP1BuJGsFXld3j1nRJmnx3ml8vaKGLjBiIwXdUpqCNBvUdM9u9CYZEpZ0admYQ00M2iUZhDbpFNzh1QyGSQW/3SSsqoNhh2T5d7PUV36mGXepCvTLwOPgyoPhQ@3JvTHQZGjkQivSb0yzpBmG4nYLFIfJ3NDXFqPpdlFmNPa2lfikNUYGUdQLwfmSseIMVli1a5qBMH16aj9mJ8RmGCGNBkEBEPiZRqWbB8kO8iq4@baMJZJCqIhw1IXcqpIggj3GoUAeuDwTQhn@LCqzFrn4ZTZaVbmi1HgS6Y6eOfv61hoTYbA4oTGaiGFVgiX@AybhacBFsfpxj@8pVI@JtvEW04fP8423qMWswwUOrOFosWMmUpdguHpK7EAkbYEjQUo6wDiGxWJotGN02kEEIU16q0wlOcfod1bm0xQg6b6aHP4VotnUeO/GZc16GKGCGrcYl7uj6ysVVUftlCI@GMokOjWqkV@BhFXeWQBSywCwVihxLDjJOTOJiQOhjLzb70YAauoEyhwyAZZPKsqNtgk7Bpg3MNEhyBpL0nemJSBqUHx@WE@bf@UqTwVtPF6zLQ4Ak7DoOS0mWP0XrW2B@OFnf3NNB4NR3kipt4BZm4cIpTS2OslW5uTAP04yVKO791vKjD3Fpe2TSrXDrdVju4UXrcOr9udKqTnSKwt8uX53Bboky@b1eTBtYV5sEyNzFYEym3KyNSrPDxPkFkDenNbAsSnvzTqpx4LJ69mZMNqIQ4@NIyJ@vLMapwlbXE6g8Q62lk0RQGBMLjLBkTlcvpxjZG2BkpehOgG0G2MSUpLxM4IrGg/txotvkMSTGys8wpsVCfHaG7hogfag5FZePlIhPYUNMWf3roup2yatJ3cAHhs5XYFPgMUO3ziiSMZ5iurlc77ThJBQpMF5iUDrnNquL3x3keKqruyFnokC9kJbn/GgQG5wYs7gMumjkilvxnIM4zGJladf2IQdUfk4pal/EonzuDqibshGgMPluM2Y@J/d5ehmQq6OyN7DAUFDUKlLDJfpdFSMLF6e7ScacBaOYbq/FUeRwN8Z@94HR20ydWKt2Ol35UedyUhxvb20GE23CJiQsiOFjIFRK8nDFI9jQddgkEGRmdxmTsmVzsmSXXcTUpsLyIsRZdlCaa3ic2rmTDV@RvDsZmCMgypiZsEtTJJuHcMlF2Vg14kQOBNiFzEBDGD1Q9vZFt08qYK@9gVBCuT7Aq75MjtJHam7tEEAzmf1/qTG93Bp91YeW/mi5Qcc5dq30BzLFCJFdjBDOdicjYcttJFnpkDj8o0nVB5C7mK8LqTzxxnGBJutAuqwKrZ@BhJM2OlxIdKR8UkXCJTjoNH@hSLrKsA2ZQ9RbEjKpEZk7hCZzzRP3o@IYoyGFhtZhAIdcHJm4SMBVpVsd4I9ioNCNdLMgQ/A6DKpRMjzOr@p0iLpNI74j@yWKMyI62mErtITbeQBf22AZMp6xdeHH4LbJFzzZWHOPw5fyuw4yyH4zeHZcmiEfIIrYayNLVkq6xKewhXjh/I7fmDjazIJlTeM1A48JcqdSL7lfDt57mFSGxyRs1ePeRiFYRQ9w2syNLkF95ThFfXXiNFzLQJiBOqVDq85RTTCytJoHjGSNiTTzVlOF0i5Lnuk@IbOjF8xpF4CC6xUQaT1QTeuFuEwtTLc5TGZxrTCq@4NLnLAkcO1SRevfYd1qN26bdy414XdEFdQWTq4S5W93yZPv@iN2Esa8mtgCkgVi0/bvY1ADvMic487Jfp0Ng3vJacokunWUxaF9J69c1AwSeIqLVlu6yzCU0ydYCtQnGUDUL4vtGF7/wkVDZQtYCXCa7CGq4SumUMrq1EJ2KYNcImCaH@HZUjzGoEG0GQX/sawizfGULd5aY2tiiS5VYXginlphf5UfLZu0zVI2ixnZuXfc51a12l4SIgcUlp5WpFNsFdpjiAhIifDq61w6uJxUT7A4fBOvsUxqz@y5tD9zbL0Hs2eRs6HIhSMi2jtbbQlX1GaQSyX@LGQNFEqjaLbh808DMdsHikAXM2r4dNa/WmO11ntr0iKI8enMZsel5Qj/Sbd9z6pVp/me4kazgsLssu8f9Y6SitJdhqhAF2Rc8krRJKzJEXUOUnSBAj/FsHQzUxXa@K6EDX8b3PN2kK@yWLKk9q6T9HdpAKnz8p7T9cdZR6mcXZV80adeMstJGEw15KwKgBTMphr5EdwRlmxNb7LlNrlqS1Su1lgEFs1mWYeByIn51O/Jqs4wlSSBfIjfezU716Y069ClMZCqzpC601dxoAXGYbEoX6SVU0dqy2lmbyEZGG1W57Tg/KW7InYKp2bHEiPwdfubr5yttkTSardtTobS@l3kQo8WeYmmc0QD3WN0pFBFEG8/1ng3nAaMYmo1HnlCg1dhYnYMIGBTdnec@bwYSr13xSlg5TjRgG7SZwQbvfOqW2dXYbyk7xOwRj@A8TS7u17iEsMXGsja2o@0Yh6Ufc1jiD8xfKHa7TUYTimDYvFQdGykHzdLR2IxJ2ElhrobK9v1xhSmqRLQVw4poJvD7xqJp9mGULDS6xYGPjCnwimeeOX8R5uwA5GM1vp065vyL1RTJSom4YnrPErYvEArpMFsBU9azuEWqsAv55mB36/JIep8rq5BEG2OGJkTQl/T9OrED6@jj/aamyqIYhGWQoTxcZav69TU4qOd5bMWOPbdwjQycNTEG6R/wTq5sHOHONty8JnAXRbO7Gq5k1y/iOA1huBlQ1OdkREQo6dENJrGGXZK1x6pyy5rcTrzpZMcussx6mlwVhJbCE3ChIINhZkGV2cNt15xdEstUN6xGOZ0rwd0WxUpK6PNlct767FxUYxip4cvyG9lSRlrfh3eySeGhC067j2mpkYcvl23lShoKRvKlGM98g9n0TDExhTXb9JyxX0da5cxP00V8ulpapBve/FIc3z5Wx9O7/7b/fvu2eDk82bcP9dPppX5897079/7Nh7/@8ZcP378@/Fq9ND96ftkf/vmyf34sHvbf3nz9j5925S8/n7/709ftfW@su8e7d@//2D@U9c3PTzfv3@Rd@dX3wwt8@PPb3XffvX/zv/ZWprnX293N@z/@Dw "PHP – TIO Nexus")
# PHP, 59.4%
49 Bytes
```
<?=ucfirst(preg_replace("#^h\w+,? #i","",$argn));
```
[Try it online!](https://tio.run/nexus/php#xV3bjuPGEX3fr2iPF7AX7i/I2lkINiAF@xJgBlgIthMwI1lkdjycjDQWiCDf7ohNsrsup8luDqh92R02xVtf6nLqVPX3H57Kpze/1c/74r789uc3P99sqqYw9/X5aPbFyZRFc2NvfqSHv9rLrz4Vx@PLk23ql68u5@mRO11Uh/Jknvb108P@cn5FD90Pyqqy4fzfyZlN0Vhzrp8fdu2N3f@u/VDXO1P8dto/P9b1o3zD9cjZ/oFNYf92Of5jb/7zsj9V9ePRlPXZ7Or90fz7pbrfm@LRFH/U98Wuvtwx/bfda9cPhVnyAWVR2bK6XLepwhOtYU3lvln0Hdzc4G9RVqafBFs/@pdXRSO42xfP5vDSHNvxav9zrbfFw8up6B6vTophtcMPUHM38R6e3Vyzw/NXvKHvpoeH2t4Xp/ZeP7b/uebz@Jx2r6@@lb@KNfAN@@ZuHn@zM7uiMb8Xp33XlWvR0r1jfd41VvfIXfHw2Zxq8/veWL9@QGN/k3aKqHf@XJ@Lf708HoqhDz7yhm5cnvaFv2l/C93Wz0T3rmDIy6qs8Gp@3l@m3OPhaKEQoJ3kn77WjUHYWCEQVrrR/fhIPmF4r1vVNgyBKZ73bf/5TtyotqEHhmaTs/7mXScnQj@KssV/xO6b9v67OvT1BrS6n/uZ4DtHtnTfu28i4ps9z@AHMk3gBOekvvHLOKd3Z1xEH2bla@F2IlIiGo0MspdLoBHMfCUfjBcQmwpIh05qLKgB6PLxH3urG4O6UNKnW5l@frFDJFL72Y1a3c9PYdq77rpjx0QOKoFPVI9QpJf5XcDudfeZmqxHcl@t0qi0l1ZM9JwQmpG159Sz1rBheGyWdJp5IbEAB9G9IkehJ9Wbtg3GTvZvp2/U1USL8TtETnTDcbk80p1NHdq3NZ/Z@2ZZa697gFo7Tu5OG8deyqxhezcrzpfJlPUJuVf4/jVLCiT3UkQWsWMuzoM/Ilp6abXsiFLLoZ@7uq3rs2GdG22kls7PUBPDdcMg4W7DQZDD11EK3lC6VW1B26uVy5Sh7htq4G@qClxf2aiecXI9/C1VxvC4O9nkXyyYLVR3y9ZheWJRchEfnS7v/@jliyXyRRnu03rm4iqDqRCsexOVg8CCubxN/4b@BcPv/XuqJiB@@j5f60Y/G5Fubf1@7lq6qQ6kXaed1dJwaiFBfZTt5cBpbay50voHzkQj5y0HT7ioat918jPJJO@fdyda6OP63qRHRE0MizocEDxAdeVPrac86deRT1yj5n6KI3wBIB/tXOEm3MX15C2dqvBOHzkiCE5Ot2rRESSHw5tGLU72brwHhsWhG/t784sdMsG7o6gi/jiyyN31kx8ePlN2UuyMNFpVd3QYSy8ayYFfpgJsOsa6rxgU@gz3MNu0HV7U9y87HkZoSVnyqSxO3xzNy1PeU2ZdFtxbPXHc@herDgM6dOT0PFiNOwudPeOe4/8MCnDBfj77DpvXzZmPazwoua3tPTP5rvOVfkaLFuKSaIO0Qz6ANm7Facyxyvmcbf0abCwmqhCIc1E2CeZDOxzY/76Yf2qNUHBkpvM9z/dmAAu1UslaTMAyiB0PTPuwSIkSkDgMsf26OTT1UBoTsFqHG2aPUEnR6khg2rVPhQYnUJFd5/W/XoUD7aj0U163eehbP5QZQNj@gXBsnqCfdZl0PReUOP24ZYMP2UguHxs@7eLngpMRg7gvfsaS3TOqLN3EQhhQO/dFbE6Laz/AyAOqoLfl0DbYEw7c0feBr@d0tVoPg@E2x27LtmHawLbsjx6npO4PXcUuGg0cEDJ1WIxDtg6SJkHoSQwvSAd8Yoijo84OQRs7S25kLzQGAfWjfKvagne4aKScjEO3HniDWmPTKv/Sy8tCAxeBgoM5wOIawlqDjqKHA0YWMcgixnmHmXLPmFoMfSycOzzc3wFu@pZAZlsOlJUQBmwFEJRKwLO3EYIBl4AXS9NmmprZKgbqeRonG0bwVrUFpMAkmJ0UdCS2h2hUIR8Q5baRKPfM0HVul22JK0mQKBbnHImMRSx3OLUDWmMVCEbsxsv09G9E8a2iklOvwlEroCQuc897cwyMNzn2L7hx8M76@4sGr26XFFkFsC2cZZKg6Nr@0nFRb5iISKzj6kzdk1i8/Z1ly2ARqQf3tJ@@/RM5Cmgx0rENwvRXOVwU73gb5XizqMKyYBL104b30G1BdWvFchH@Wm73qJjoCtQarDPQy63iyJPg2T4PldUdyMQbFIB1JdvlSkSi47WcMU5tGWgdutGr1dhaHYVeqSUqRzNgy9UIshwnsqmpT6GUtMATWCnMLoCkGmHyw57xkkMqBUoGu6xUILVlZwwW5Ryu1QzabIzNsm@EKiiWjdDTmSPG8jZ2KkAFaliJ6QHEKgs8ZVLmBgc4Qk/D5pEG769v@Ll4ARzsMFs1CM2Wtyf4Cu@HBe0fsMZmixzHJ4WrPTBPUbP3TuCdqAbN6d1512kPAYBd@ByRTKDLeuMoK/yRe0mITOIxCQFEJg5uRykvLmA1bWg7VzdEliwlKZhx8p5BtOSGg85LiqtTut22hha3E1uIReFnCsO4RSMJ8ox5v8qzvY2eEwA0G@xTGtuZy0zCJBKNMkqEmPRPQheZ8dlgQdBeUokmUSkv3YZQKDsO/si0qVEAQOlTWqCPTCzV15b39aAHdCiE/NB/xACysmMkd3Gax4HNXJmHkjPy4nE5i3Q991IV2MKIOqN8eBonaAXzPVeLz7mSU8yuBS/3HjTlKAlZD4DDqkqiEvtFqFlZlLh46X5gOkdNV5R3U8azJmLEwZ7TtqAaOeQwj8Tsj4UongQpXWjuprYEF8a@21TOkVNpOWQtYIQzw5I4UAKywCc8zydqNYXu@cSOlSRgnfPpupyTjmQpEgvDAgAx7ntO/dCrIkiHecJhhuWIffZ9AktyiP8BxA5FhVczspBm5SA5WbHgsneh2wQzYtHAlwvYaDlZzODyzWLysQw/kJnFdG2Hkw2xzXBAQmjS1NWNEqzOYWgHCTVLMphZUUkNeXXYHwsWjmSwQY4LB7Ra1jz0PVMxgQ6cw/rTiSiblbKFRInrCyYlZT46ylIjspK8eVS/IGipS62ddmSJVzU3xStXgnB@P4RKqMIOzCLQwSH6A9xUqGV6urZsFqkIOB37QEPOCXkW3SQCaScwCJaSwVZUNiviG1xG2kIXJKHHehSjR28IvRrkdriz7JCY3DxLUzCco8wE4ejds85ZtEZCg6sR2KnEXAssHWsE0CHIVWX0vs4h0fSGVkzpzC1G9koKIUhUXJjX6zzJFMRssFdlEzWVQkIV4eq7zsA5NQlAa0LZhNMXwFP3yOXr6M46iNORZgiUyLKPU6JDiueiTfNg5ndrmh76cGngkEeQMZZjJxr9l4PpG4G6qQ5B4Sum7GnEbGmGaao95sxQNdLbGH9DBQ89Qo0QAhQaGsKWQ6iOHg4kkZEI3zzPMNsFYSxsvIqTnIjehgG5fZpK480ATVyl9iMCxiRlQpsGwQKZKOMyq7oQckGLaeiTaXmaGSgaSeZjPPlfQaKDKpOIMysjgZVYNQILJJBej5lRbYpHzgYyX@H/jULYHCQbq9oAJgdVXSDQIFI7U@zR1pCAg7ZKiI5WEeGVYrXG1Hmv8fKrCbwCee6XykfREgIEOuJdVDE@PeuSHr6jWYlMlyP/Jc/tuM0po0IdRMntsNy2BkF@WAHKzSDdTOAHkPHNXoqvCBAKpVn/TMahkCIXh8P6A1USJOICQredmcpyCcObECXKLahgy96OQwGbNJIjRZnn2av5kGE7qItyPlPSGMh8USWkeOzKhdgjuqyEnjWYslTNgIgBwh@0ZXsxd1FCDTUusmKE8y70BvxQhyGkzVEdB6tQCJJmrFvtVXikgI7AyP8OsF8SBoglCLT@aIS@HasmES8/kRKCR5cHp22gHPMGqee0JOaW0@c5ZY987jsnGlCh3YNHmMELqRutNxA3gq0qv8Or75Qw@@wwv1zWRhEbNxCB6apOQR0J6j1isn8XCotMOTPqzCSkgW4WjcIccotscu6AQiaD3OqXVlJGtcGwe7rc6ym6Uw9r6kG@MvE6@DCg@lD4cG9OdxgYORKJ9JrQL@sEYbqdgMUi8XU2N8Sp@VyWWYw9raV9KQ5RgZV1APF@ZK54gBSXLVrlok4cXJuO2ovxGYUJYkCTQUQ8JFKqZcHyQb6LrD5uoglnkaggHjYgdSmniiCMcKtRBKwPBtOEfIoLr8asfRpOlZVuabYcBbpgpo9//raGhdpsDChOZKAaVmCJfIHLuFlwEmx9nGL4y1ci4W@@RbTh8P3jbOsxajHDQKk7WyxayJSl2C0ckroSCxhhS9BQjLIOILJZmSwa3TSRQghRXKvSCk9x@h3WubXFCDlspoc@h2u1dB458ptxXYcqYoSsxiXu6frIxlZR@WULjYQzig6NaqVW4GMUdZVDFrDALhSIHUoMM05O4mBC6mAsN/vSgxm4gjKFDoNkkMmzom6DTcKmDc41SHAEkvae6IlJGZQeHJcT5t/6S5HCW00Xr8tAgyfsOAxKSpc9ROtZY384Wtzd00Dj1XSQK27iFWTiwilOLY2xVrq5MQ3Qj5co7fzW8aIOc2t5ZdOscul0W@3gRulx6/y60alOdorA3i5fnsNtiTL5vl1NGlhXmAfL3MRgTaTcroxIscLH@wSRNaQ3sy1IePJPq3LisXj2Zk42oBLi4EvLnKwvx6jCVdYSqz9ArOcii6YwIBAeZ8mYqFxON7Yxws5I0ZsA3QiyjSlJeZnAEYkF9edGs80rJMXIzjKnxEJ9doTuGiJ@qDkUlY2Xi0xgQ01b/Omh63bKqknfwQWEz1ZiU@AVoNrriiSMZ5iurlc77ThJBQpMF5iUDrnNquL3x3keKqruyFnokC9kJbn/GgQG5wYs7gMumjkilvwrEOcZjEytun7CoOpPSUWty3iUz51BVRN2QjQGny3G7MfEfm8vQzIVdPZGdhgKihoFSthkv8siJOHidHfpuNMANPON1XiqPI6G@M9ecDq76RMrlW7HSz@qPG7Kw43t7SDCbbjERIMIDhZyhQQvZwySPU2HXQJBRkanMRl7Jhd7Zsl1XE0KLC9irEUXpYmm94mNK9nwFfmbg7EZArKMqQmbBHWySTi3TJSdVQNe5ECgTcgcBITxA1VPb2TbtDLmyjsYFYTrE6zKT8kR2kjtzV0iCAbzv5s609udwWddWPmvpgtUnHPXal8Ac6wQydUYwUxnIjK23HaShR6Zww@KdDWI3MV8RVj9iSeOEyxJF9plVWD1DDyMpNnxUqIj5YMiEi7RSafhA13KRZZ1wAyq3oKYUZXIzCk8gXOeqB8d3xAFOSysFhMo5HrPxE0CpiLN6hhvBBuVZqSLBRmC32FQhZLpcWZVv1PEZRLpHdE/WYwR2dEWU6k9xMYb6MIe24DplLULLw6/Rbbo2caKYxy@nN91mFH2g9G749IE8QhZxFYDWbpa0jU2hT3EC@dv5NbcwWYWJHMKrxloXJgrlXrR/Wr41tO8IiQ2eaMG7z4S0SpiiNtmdmQJ8ivPKeKrC6/xQgbaBMQpFUp9nnKKiaXVJHA8Y0SsiaeaMpxuUfJc9wmRDb14XqMIHES3mEjjiWpCL9xtYmGqxXkqg3ONScUNLn3OksCxQxWpd499p9W4bdq93IjXFV1QVzC5Spi71S1Ptu@P2E0Y@2piC0AaiEXbv4tNDfAuc4IzL/t1OgTmLa8ll@jSWRaD9pW0fl0zQOApIlpt6S7LXEKTbC1Qm2AMVbMgvm908QsfCZUtZC3AZbKLoIarlE4po1sL0akIdo2AaXKIb0f1GIMK0WYQ9Me@hjDLV7ZwZ4mpjS26VInlhXBqiflVfrRs1j5D1ShqbOfWdZ9T3WrXJEQMLC45rUyl2C6wwxQXkBDh09G9dnA9qZhgd/ggWGef05jdd2l74N5@CWLPJmdDl4YgIds6Wm8LVdVnkEok/y1mDBRJoGq34PJNAzPbBYtDFjBr@3bUvFpjttd5atMjivLozWXEpucJ/Ui3fc@pV6b5n@FGsoLDrll2j/uHSEVpL8NUIQqyL3gkaZNWZIi6hig7QYAe49k6GKiL7XxXQge@jO95uklX2C1ZUntWSfs7tIFU@PjPafvjrKPUzy7KvmjSrhllpY0mGvJWBEALZlIMfYnuCMo2J7bYc5tctSSrV2otAwpmsyzDwOVE/Op25NVmGUuSQL5EbrybnerTL@rQpzCRqcySutBWc6MFxGGyKV2kTaiitWW1szaRjYw2qnLbcX5S3JA7BVOzY4kR@Tv8zNfPV9oiaTRbt6dCaX0v8yBGiz3F0jijAe6xulMoIog2nus9G84DRjE0G488oUCrsbE6BxEwKLo7z6e8GUi8dsUrYeU40YBt0GYGG7zzqVtmV2O/pewQs0c8gvM0ubhf4xLCFhvL2tiOtmMcln7MYYk/MH@h2O02GU0ogmHzUnVspBw0S0djMyZhJ4W5Girb98cVpqgS0VYMK6KZwO8bi6bZ@1Gy0OgWBz4ypsArnnnm/EWYswOQj9X4duqY8y9WUyQrJeKK6T1L2L5AKKTDbAVMWc/iFqnCLuSbg92tyyPpfa6sQhJtjBmaEEFf0vfrxA6so4/3m5oqi2IQlkGG8nCVrerX1@CgnuexFTv23MI1MnDWxBikf8A7ubJxhDvbcPOawF0Uze5quJJdv4jjNIThZkBRr8mIiFDSoxtMYg27JGuPVeWWNbmdeNPJjl1kmfU0uSoILYUn4EJBBsPMgiqzh9uuObsklqluWI1yOleCuy2KlZTQ58vkvPXZuajGMFLDzfIb2VJGWt@Hd7JJ4aELTruPaamRhy@XbeVKGgpGclOMZ77BbHqmmJjCmm16ztivI61y5ufpIj5dLS3SDb8Wx7cP1fH07r/tv9@@LZ4Pj/btff14eq4f3v3gzr1/8@Gvf37/4YeX@9@q58uPnp73h38@758eivv9tzdf/6P85fyd/WC@bu96Y90t3r17/@f@vqxvfnm8ef8m68Kvfhge/@Evb3fffff@zf/aO5nLrd7ubt7/@X8 "PHP – TIO Nexus")
# PHP, 58.4%
50 Bytes
```
<?=ucfirst(preg_replace("#^[gh]\w+.#i","",$argn));
```
[Try it online!](https://tio.run/nexus/php#xV3bjuPGEX3fr2iPF7AXbuQDsnEWgg1Iwb4EmAEGgu0EzEgWmR0PJyONBSHItztkk@yuy2mymwtqX3aHTfHWl7qcOlX9lw/P5fObX@uXffFQfvvTm59uNtWlMA/1@Wj2xcmUxeXG3vxAD3@xza/ui@Px9dle6tevmvP0yJ0uqkN5Ms/7@vlx35xf0UP3g7KqbDj/d3JmU1ysOdcvj7v2xu5/136o650pfj3tX57q@km@4XrkbP/AS2H/1hz/vjf/ed2fqvrpaMr6bHb1/mj@/Vo97E3xZIrf64diVzd3TP9t99r1Y2GWfEBZVLasmus2VXiiNayp3F8WfQc3N/hblJXpJ8HWj37zqmgEd/vixRxeL8d2vNr/XOtt8fh6KrrHq5NiWO3wA9TcTbzHFzfX7PD8FW/ou@nxsbYPxam91w/tf675PD6n3eurb@WvYg18w765m8ff7MyuuJjfitO@68q1aOnesT7vLlb3yF3x@MmcavPb3li/fkBjf5N2iqh3/lSfi3@9Ph2KoQ8@8oZuXJ73hb9pfwvd1s9E965gyMuqrPBqftk3U@7pcLRQCNBO8k9f68YgbKwQCCvd6H58JJ8wvNetahuGwBQv@7b/fCduVNvQA0OzyVl/866TE6EfRdniP2L3TXv/XR36egNa3c/9TPCdI1u6791fIuKbPc/gBzJN4ATnpL7xyzind2dcRB9m5WvhdiJSIhqNDLKXS6ARzHwlH4wXEJsKSIdOaiyoAejy8R97qxuDulDSp1uZfn6xQyRS@9mNWt3PT2Hau@66Y8dEDiqBT1SPUKTN/C5g97r7TE3WI7mvVmlU2ksrJnpOCM3I2nPqWWvYMDw2SzrNvJBYgIPoXpGj0JPqTdsGYyf7t9M36mqixfgdIie64Wguj3TnpQ7t25rP7P1lWWuve4BaO07uThvHXsqsYXs3K87NZMr6hNwrfP@aJQWSeykii9gxF@fBHxEtvbRadkSp5dDPXd3W9dmwzo02UkvnZ6iJ4bphkHC34SDI4esoBW8o3aq2oO3VymXKUPcNNfA3VQWur2xUzzi5Hv6WKmN43J1s8i8WzBaqu2XrsDyxKGnER6fL@z96@WKJfFGG@7SeaVxlMBWCdW@ichBYMM3b9G/oXzD83r@nagLip@/ztW70sxHp1tbv566lm@pA2nXaWS0NpxYS1EfZXg6c1os1V1r/wJm4yHnLwRMuqtp3nfxMMsn7592JFvq4vjfpEVETw6IOBwQPUF35Y@spT/p15BPXqLmf4ghfAMhHO1e4Cde4nrylUxXe6SNHBMHJ6VYtOoLkcHjTqMXJ3o33wLA4dGN/b36xQyZ4dxRVxB9HFrm7fvLDw2fKToqdkUar6o4OY@lFIznwy1SATcdY9xWDQp/hHmabtsOL@v5lx8MILSlL7svi9M3RvD7nPWXWZcG91RPHrX@x6jCgQ0dOz4PVuLPQ2TPuOf7PoAAX7Oez77B53Zz5uIsHJbe1fWAm33W@0s9o0UJcEm2QdsgH0MatOI05Vjmfs60/BxuLiSoE4jTKJsF8aIcD@9@N@afWCAVHZjrf83xvBrBQK5WsxQQsg9jxwLQPi5QoAYnDENuvm0NTD6UxAat1uGH2CJUUrY4Epl37VGhwAhXZdV7/61U40I5KP@V1m4e@9UOZAYTtHwjH5gn6WZdJ13NBidOPWzb4kI3k8rHh0y5@LjgZMYi78TOW7J5RZekmFsKA2rkvYnNaXPsBRh5QBb0th7bBnnDgjr4PfD2nq9V6GAy3OXZbtg3TBrZlf/Q4JXV/6Cp20WjggJCpw2IcsnWQNAlCT2J4QTrgE0McHXV2CNrYWXIje6ExCKgf5VvVFrzDRSPlZBy69cAb1BqbVvlNLy8LDTQCBQdzgMU1hLUGHUUPB4wsYpBFjPMOM@WeMbUY@lg4d3i4vwPc9C2BzLYcKCshDNgKICiVgGdvIwQDLgEbS9NmmprZKgbqeRonG0bwVrUFpMAkmJ0UdCS2h2hUIR8Q5baRKPfM0HVul22JK0mQKBbnHImMRSx3OLUDWmMVCEbsxmZ6@jei@FZRyalX4agVUBLN3PPeHAPjTY79C24cvLP@/qLBq9slRVYBbAtnmSQoura/dFzUGyYiEuu4OlP3JBZvf2fZMlhE6sE97advvydHAS1GOvaCMP1VDhfFO95GOd4sqrAsmET9tOE9dFtQ3VqxNMJfy@0eFRNdgVqDdQZ6uVUceRI82@ehsroDmXiDArCuZLtciUh0vJYzxqktA61DN3q1Gluro9ArtUTlaAZsuRpBluNENjX1KZSSFngCK4XZBZBUI0x@2DNeckilQMlgzUoFUlt2xmBRzuFazaDNxtgs@4tQBcWyEXo6c8RY3sZOBahADSsxPYBYZYGnTMrc4ABH6GnYPNLg/fUNPxcvgIMdZqsGodny9gRf4f2woP0j1thskeP4pHC1B@YpavbeCbwT1aA5vTvvOu0hALALnyOSCXRZbxxlhT9yLwmRSTwmIYDIxMHtKOXFBaymDW3n6obIkqUkBTNO3jOIlnzhoPOS4uqUbretocXtxBZiUfiZwjBu0UiCPGPer/Jsb6PnBADNBvuUxnbmMpMwiUSjjBIhJv2z0EVmfDZYELSXVKJJVMpLtyEUyo6DPzJtahQAULpPC/SRiaX62vK@HvSADoWQH/qPGEBWdozkLk7zOLCZK/NQckZePC5nka7nXqoCWxhRZ5QPT@MErWC@52rxOVdyitm14OXeg6YcJSHrAXBYVUlUYr8INSuLEheb7gemc9R0RXk3ZTxrIkYc7DltC6qRQw7zSMz@WIjiWZDShea@1Jbgwth3m8o5cioth6wFjHBmWBIHSkAW@ITn@UStptA99@xYSQLWOffX5Zx0JEuRWBgWAIhxP3Dqh14VQTrMEw4zLEfss@8TWJJD/A8gdigqvJqRhTQrB8nJigWXvQvdJpgRiwa@XMBGy8liBpdvFpOPZfiBzCymazucbIhthgMSQpOmrm6UYHUOQztIqFmSwcyKSmrIq8P@WLBwJIMNclw4oNWy5qHvmYoJdOAc1p9ORNmslC0kSlxfMCkp89FRlhqRleTNo/oFQUtdau20I0u8qrkpXrkShPP7IVRCFXZgFoEODtEf4KZCLdPTtWWzSEXA6dgHGnJOyLPoJhFIO4FBsJQMtqKyWRHf4DLSFrogCT3Woxg9ekPo1SC3w51lh8Tk5lmaguEcZSYIR@@Bdc6iNRIuuBqBnUrMtcDSsUYAHYJcVUbv6xwSTW9oxZTO3GJkr6QQgkTFhXm9zpNMQcwGe1U2UVMpJFQRrr7rDJxTkwC0JpRNOH0BPHWPXL6O7qyDOB1phkCJLPs4JTqkeC7aNA9mfrem6aEPlwYOeQQZYzl2otF/OZi@Eaib6hAUvmLKnkbMlmaYptpjzgxVI72N8TdU8NAj1AghQKGhIWw5hOro4UASGYnwzfMMs10QxsLGqzjJiehtGJDbp6k03gzQxFVqPyJgTFImtGkQLJCJMi6zqgshF7SYhj6ZlqeZgaKRZD7Gk/8VJDqoMok4szISWIlVI7BAAun1mBnVpnjkbCDzM/y/UQibg2RjVRvA5KCqCwQaRGpnij3aGhJw0FYJ0dEqIrxSrNaYOu81Xn41gc9Anvul8lG0hACBjngXVYxPz7qkh@9oViLT5ch/yXM7bnPKqFAHUXI7LLetQZAfVoByM0g3E/gBZHyzl@IrAoRCadY/k3EopMjF4bD@QJUEibiA0G1nprJcwvAmRIlyCyrYsrfjUMAmjeRIUeZ59mo@ZNgO6qKcz5Q0BjJfVAkpHrtyIfaILiuhZw2mLFUzIGKA8Adt2TbmLkqoocZFVoxw3oXegB/qMIS0OarjYBUKQdKMdau9Co8U0BEY@d8B9kvCALEEgdYfjdC3Y9Uk4uUnUkLw6PLgtA2UY94g9ZyWxNxy@jSn7JHPfedEAyq0e/AIM3ghdaP1BuJGsFXld3j1nRJmnx3ml8vaKGLjBiIwXdUpqCNBvUdM9u9CYZEpZ0admYQ00M2iUZhDbpFNzh1QyGSQW/3SSsqoNhh2T5d7PUV36mGXepCvTLwOPgyoPhQ@3JvTHQZGjkQivSb0yzpBmG4nYLFIfJ3NDXFqPpdlFmNPa2lfikNUYGUdQLwfmSseIMVli1a5qBMH16aj9mJ8RmGCGNBkEBEPiZRqWbB8kO8iq4@baMJZJCqIhw1IXcqpIggj3GoUAeuDwTQhn@LCqzFrn4ZTZaVbmi1HgS6Y6eOfv61hoTYbA4oTGaiGFVgiX@AybhacBFsfpxj@8pVI@JtvEW04fP8423qMWswwUOrOFosWMmUpdguHpK7EAkbYEjQUo6wDiGxWJotGN02kEEIU16q0wlOcfod1bm0xQg6b6aHP4VotnUeO/GZc16GKGCGrcYl7uj6ysVVUftlCI@GMokOjWqkV@BhFXeWQBSywCwVihxLDjJOTOJiQOhjLzb70YAauoEyhwyAZZPKsqNtgk7Bpg3MNEhyBpL0nemJSBqUHx@WE@bf@UqTwVtPF6zLQ4Ak7DoOS0mWP0XrW2B@OFnf3NNB4NR3kipt4BZm4cIpTS2OslW5uTAP04yVKO791vKjD3Fpe2TSrXDrdVju4UXrcOr9udKqTnSKwt8uX53Bboky@b1eTBtYV5sEyNzFYEym3KyNSrPDxPkFkDenNbAsSnvzTqpx4LJ69mZMNqIQ4@NIyJ@vLMapwlbXE6g8Q62lk0RQGBMLjLBkTlcvpxjZG2BkpehOgG0G2MSUpLxM4IrGg/txotvkMSTGys8wpsVCfHaG7hogfag5FZePlIhPYUNMWf3roup2yatJ3cAHhs5XYFPgMUO3ziiSMZ5iurlc77ThJBQpMF5iUDrnNquL3x3keKqruyFnokC9kJbn/GgQG5wYs7gMumjkilvxnIM4zGJladf2IQdUfk4pal/EonzuDqibshGgMPluM2Y@J/d5ehmQq6OyN7DAUFDUKlLDJfpdFSMLF6e7ScacBaOYbq/FUeRwN8Z@94HR20ydWKt2Ol35UedyUhxvb20GE23CJiQsiOFjIFRK8nDFI9jQddgkEGRmdxmTsmVzsmSXXcTUpsLyIsRZdlCaa3ic2rmTDV@RvDsZmCMgypiZsEtTJJuHcMlF2Vg14kQOBNiFzEBDGD1Q9vZFt08qYK@9gVBCuT7Aq75MjtJHam7tEEAzmf1/qTG93Bp91YeW/mi5Qcc5dq30BzLFCJFdjBDOdicjYcttJFnpkDj8o0nVB5C7mK8LqTzxxnGBJutAuqwKrZ@BhJM2OlxIdKR8UkXCJTjoNH@hSLrKsA2ZQ9RbEjKpEZk7hCZzzRP3o@IYoyGFhtZhAIdcHJm4SMBVpVsd4I9ioNCNdLMgQ/A6DKpRMjzOr@p0iLpNI74j@yWKMyI62mErtITbeQBf22AZMp6xdeHH4LbJFzzZWHOPw5fyuw4yyH4zeHZcmiEfIIrYayNLVkq6xKewhXjh/I7fmDjazIJlTeM1A48JcqdSL7lfDt57mFSGxyRs1ePeRiFYRQ9w2syNLkF95ThFfXXiNFzLQJiBOqVDq85RTTCytJoHjGSNiTTzVlOF0i5Lnuk@IbOjF8xpF4CC6xUQaT1QTeuFuEwtTLc5TGZxrTCq@4NLnLAkcO1SRevfYd1qN26bdy414XdEFdQWTq4S5W93yZPv@iN2Esa8mtgCkgVi0/bvY1ADvMic487Jfp0Ng3vJacokunWUxaF9J69c1AwSeIqLVlu6yzCU0ydYCtQnGUDUL4vtGF7/wkVDZQtYCXCa7CGq4SumUMrq1EJ2KYNcImCaH@HZUjzGoEG0GQX/sawizfGULd5aY2tiiS5VYXginlphf5UfLZu0zVI2ixnZuXfc51a12l4SIgcUlp5WpFNsFdpjiAhIifDq61w6uJxUT7A4fBOvsUxqz@y5tD9zbL0Hs2eRs6HIhSMi2jtbbQlX1GaQSyX@LGQNFEqjaLbh808DMdsHikAXM2r4dNa/WmO11ntr0iKI8enMZsel5Qj/Sbd9z6pVp/me4kazgsLssu8f9Y6SitJdhqhAF2Rc8krRJKzJEXUOUnSBAj/FsHQzUxXa@K6EDX8b3PN2kK@yWLKk9q6T9HdpAKnz8p7T9cdZR6mcXZV80adeMstJGEw15KwKgBTMphr5EdwRlmxNb7LlNrlqS1Su1lgEFs1mWYeByIn51O/Jqs4wlSSBfIjfezU716Y069ClMZCqzpC601dxoAXGYbEoX6SVU0dqy2lmbyEZGG1W57Tg/KW7InYKp2bHEiPwdfubr5yttkTSardtTobS@l3kQo8WeYmmc0QD3WN0pFBFEG8/1ng3nAaMYmo1HnlCg1dhYnYMIGBTdnec@bwYSr13xSlg5TjRgG7SZwQbvfOqW2dXYbyk7xOwRj@A8TS7u17iEsMXGsja2o@0Yh6Ufc1jiD8xfKHa7TUYTimDYvFQdGykHzdLR2IxJ2ElhrobK9v1xhSmqRLQVw4poJvD7xqJp9mGULDS6xYGPjCnwimeeOX8R5uwA5GM1vp065vyL1RTJSom4YnrPErYvEArpMFsBU9azuEWqsAv55mB36/JIep8rq5BEG2OGJkTQl/T9OrED6@jj/aamyqIYhGWQoTxcZav69TU4qOd5bMWOPbdwjQycNTEG6R/wTq5sHOHONty8JnAXRbO7Gq5k1y/iOA1huBlQ1OdkREQo6dENJrGGXZK1x6pyy5rcTrzpZMcussx6mlwVhJbCE3ChIINhZkGV2cNt15xdEstUN6xGOZ0rwd0WxUpK6PNlct767FxUYxip4cvyG9lSRlrfh3eySeGhC067j2mpkYcvl23lShoKRvKlGM98g9n0TDExhTXb9JyxX0da5cxP00V8ulpapBve/FIc3z5Wx9O7/7b/fvu2eDk82bcP9dPppX5897079/7Nh7/@8ZcP378@/Fq9ND96ftkf/vmyf34sHvbf3nz9j58O5S8/n7/709ftfW@su8e7d@//2D@U9c3PTzfv3@Rd@dX3wwt8@PPb3XffvX/zv/ZWprnX293N@z/@Dw "PHP – TIO Nexus")
[Answer]
# Vim, ~~55.4%~~ 44.4%
```
df,<<vgU
```
Explanation:
```
df, Delete until and including the first comma
<< Remove leading spaces
vgU Uppercase first letter
```
] |
[Question]
[
Following on from [Monte Carlo estimator of Pi](https://codegolf.stackexchange.com/questions/47759/monte-carlo-estimator-of-pi) this challenge is to produce the shortest code for the constant Pi. Except here your code must output consecutive digits of pi forever.
This is code golf, so the shortest submission (in bytes) wins except that it must output the first 10,000 digits in less than 10 seconds on a reasonable PC and it must never terminate.
You can't use any built-in for Pi or trig functions.
---
Removed the hard limit on code size.
[Answer]
# Python, 138 bytes
```
q,r,t,i=1,180,60,2
while 1:u,y=27*i*(i+1)+6,(q*(27*i-12)+5*r)//(5*t);print(y,end="");q,r,t,i=10*q*i*(2*i-1),10*u*(q*(5*i-2)+r-y*t),t*u,i+1
```
Implementation of <http://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf>.
[Answer]
# CJam - 48
```
3.1o{1YAZ2*:Z#*{_2$*2$2*)/@)\}h*]:+sX2*:X>X<o1}g
```
This calculates π as 2\*sum(k!/(2k+1)!!) with greater and greater precision and at every step prints a bunch of digits from where it left off.
You can [try online](http://cjam.aditsu.net/#code=3.1o%7B1YAZ2*%3AZ%23*%7B_2%24*2%242*)%2F%40)%5C%7Dh*%5D%3A%2BsX2*%3AX%3EX%3Co%7D8*) a modified version that does only 8 (outer loop) iterations and prints 512 digits, or use the [java interpreter](https://sourceforge.net/projects/cjam/) for the real thing. On my laptop it gets to 16384 digits in about 6 seconds.
Note: this program is very memory-hungry; a better behaved but slightly longer version is:
```
3.1o{T2AZ2*:Z#*1{@2$+@2$*2$2*)/@)1$}g;;sX2*:X>X<o1}g
```
**Explanation:**
```
3.1o print 3.1
{…1}g repeat indefinitely
1YA push 1, 2 and 10 (Y=2, A=10)
Z2*:Z push Z*2 (Z=3 initially) and store back in Z
#* calculate 2*10^Z (2 from the formula and 10^Z for precision)
this is the term for k=0, and the earlier 1 represents k
{…}h do-while
at each iteration, the stack contains: terms, k, last-term
_2$* copy the previous term and k and multiply them
2$2*)/ divide the previous number by 2*k+1
this is the current term of the series
@)\ increment k and move it before the current term
the current term now serves as the loop condition
so the loop terminates when the term becomes 0
* multiply k and the last term (0), to get rid of k
]:+s put all the terms in an array, add them and convert to string
we obtain an approximation of π*10^Z
X2*:X push X*2 (X=1 initially) and store back in X
>X<o print X digits starting from the X position
```
[Answer]
## GolfScript (81 chars)
```
1:i:^3{3i):i*(.(*3*.@*.5*3$27i*12-*+@^*:^5*/.print^*2$5i*2-*--\10*i*2i*(*\10*.}do
```
[Online demo](http://golfscript.apphb.com/?c=MTppOl4zezNpKTppKiguKCozKi5AKi41KjMkMjdpKjEyLSorQF4qOl41Ki8ucHJpbnReKjIkNWkqMi0qLS1cMTAqaSoyaSooKlwxMCp9MzAqOzs%3D) (that's much slower than a reasonable desktop, and has trivial code changes to loop a finite number of times).
I have, of course, used the spigot algorithm which I mentioned in an earlier comment, but it took me a while to golf it to my satisfaction. The algorithm as presented in Gibbons' paper is (pseudocode)
```
q = 1; r = 180; t = 60; i = 2
while (true) {
u = 3*(3*i+1)*(3*i+2)
y = (q*(27*i-12)+5*r) / (5*t)
print y
r += q*(5*i-2)-y*t
r *= 10*u
q *= 10*i*(2*i-1)
t *= u
i += 1
}
```
The GolfScript above is equivalent to (pseudocode)
```
t = i = q = 1; r = 3
while (true) {
u = 3*(3*i+1)*(3*i+2)
i += 1
r *= u
t *= u
y = (q*(27*i-12)+5*r) / (5*t)
print y
r -= y*t - q*(5*i-2)
q *= 10*i*(2*i-1)
r *= 10
}
```
which saves some characters in the initialisation and in the stack management.
[Answer]
# Pyth - 87 85 bytes
Another translation of <http://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf>. I was gonna do Python but @orlp beat me to it, so I did Pyth. Small enough to fit in a tweet.
```
=H3=d1=bd=Gd#K+**hb27b6~b1=H*HK=d*dKJ/+*-*27b12G*5H*5d=H*T-H-*Jd*-*5b2G=G***GTbtybpkJ
```
It gives output to stdout, albeit in intermittent steps because of the print buffer that comes from setting `end=""` in print. I currently don't print the decimal point since the spec says "consecutive digits". Its the assignments that are killing my score.
```
=H3 Set H to 3
=d1 Set d to 1
=bd Set b to d which is 1
=Gd Set G to d which is 1
# Infinte Loop
K Set K to
+**hb27b6 27*b*(b+1)+6
~b1 b+=1
=H*HK H*=K
=d*dK d*=K
J Set J to
/ Integer division
+*-*27b12G*5H G*(27*b-12)+5*H
*5d 5*d
=H Set H to
*T-H-*Jd*-*5b2G 10*(H-(J*d -G*(5*b-2)))
=G Set G to
***GTbtyb G*10*b*(2*b-1)
pkJ Print J with the end as "", not a newline
```
[Try it here](http://pyth.herokuapp.com/?code=%3DH3%3Dd1%3Dbd%3DGdV100K%2B**hb27b6%7Eb1%3DH*HK%3Dd*dKJ%2F%2B*-*27b12G*5H*5d%3DH*T-H-*Jd*-*5b2G%3DG***GTbtybpkJ). (Note: Since the online interpreter only give completed results, the infinite loop is out, so it only prints first 100 which increases code size. To try out infinite, download the local interpreter.)
## Timing
On my google cloud compute micro instance, according to gnu time it took: `real: 0m2.062s` so it is obviously fast enough.
[Answer]
# Scala, 599 bytes
The code below is a straight port of the Pascal code from Appendix 2 of [A Spigot Algorithm for the Digits of Pi](http://www.mathpropress.com/stan/bibliography/spigot.pdf). Clearly very little golfing has yet been done. The code does generate 10,000 digits in under 10 seconds with `piSpigot(10000)` and if one has infinite memory can be parameterized to generate many digits, but not infinite. I am not sure if this is meeting the problem constraints so please provide feedback.
```
def piSpigot(n: Int): Unit = {
val len=10*n/3
var nines=0
var predigit=0
val a=Array.fill(len)(2)
(1 to n).foreach {_=>
var q=0
(1 to n).reverse.foreach{i=>
var x=10*a(i)+q*i
a(i)=x%(2*i-1)
q=x/(2*i-1)
}
a(1)=q%10
q/=10
if (q==9) {
nines+=1
} else if (q==10) {
print(predigit+1)
1.to(nines).foreach(_=>print(0))
predigit=0
nines=0
} else {
print(predigit)
predigit=q
if (nines!=0) {
1.to(nines).foreach(_=>print(9))
nines=0
}
}
}
println(predigit)
}
piSpigot(10000)
```
[Answer]
# Befunge-98 (PyFunge), 120 bytes
```
cf*10p'<20p11>00p1+:30p:::*+39**6+:30g39**c-00g*10gv
>:2*1-*00g*a*^
^:p02*g02p01*a*-*g02\+g01*g00-2*5g03,+*86:/*5g02+*5<
```
[Try it online!](https://tio.run/##HcrBCsJADIThe19EmDU4m9LShtInkYKWNjfJRcGnX3e9hO8f8jzO98sPmSeJ75@l7Ccy47IoI@eV9SbrGWaG1M/A2NKbdiG9PvunW02RBa0f2LrNggqnBnMdpPGevIaTohic/TVhGu3WrAnDUsoP)
This is borderline in terms of the timelimit. 10,000 digits take around 11 seconds on my laptop, but I'm sure there must be a "reasonable" PC that could do it faster than that.
However, if you're trying it out on TIO, note that it won't return anything until it hits the 60 second time limit, since the algorithm is designed to keep going forever. By that time you'll have a lot more than 10,000 digits though.
I'm using the Jeremy Gibbons spigot algorithm, which I think is the same as most other answers here. However, note that this relies on the interpreter having arbitrary precision memory cells, and the only implementation I'm aware of that supports that is [PyFunge](https://pythonhosted.org/PyFunge/).
**Explanation**
```
cf*10p Initialise r to 180.
'<20p Initialise t to 60.
11 Initialise i and q on the stack to 1.
> Start of the main loop.
00p Save the current value of q in memory.
1+:30p Increment i and save a copy in memory.
:::*+39**6+ Calculate u = 27*(i*i+i)+6.
: Make a duplicate, since we'll need two copies later.
30g39**c-00g*10gv Calculate y = (q*(27*i-12)+5*r)/(5*t).
/*5g02+*5<
,+*86: Convert y to a character so we can output it.
*a*-*g02\+g01*g00-2*5g03 Calculate r = 10*u*(q*(i*5-2)+r-y*t)
p01 Save the updated r.
*g02 Calculate t = t*u
p02 Save the updated t.
>:2*1-*00g*a* Calculate q = 10*q*i*(i*2-1).
^:
^ Return to the start of the main loop.
```
] |
[Question]
[
Given two positive reals \$a\$ and \$b\$, output some positive reals \$r\_i\$, such that \$\sum r\_i=a\$ and \$\prod\left(r\_i+1\right)=b\$. You can assume that it's possible. You can also assume that your float type have infinite precision.
Test cases:
```
2,3 => 2
2,4 => 1,1 or 1/2,(sqrt(57)+9)/12,(9-sqrt(57))/12 or etc.
2,5 => 1/3,1/2,2/3,1/2 or etc.
2,8 => (undefined behavior)
2,2 => (undefined behavior)
e,2e => 1,e-1 or etc. (e is natural base, though any number>1 work)
3,e^3 => (undefined behavior) (It's possible to get as close as you want to e^3, but not reaching)
```
Shortest code wins.
# Notes
* Given the assumption with infinite precision, you can't solve arbitrary equation if your language doesn't have such functions(you can still use functions like `Solve` in Mathematica to solve such). In this case, some forms may have solution mathematically but you can't work it out, e.g. \$p,p,p,...,p,q\$ where \$p\$ and \$q\$ are reals. (At least software don't provide exact solution for `x*x*x*y=5,3*x+y=7`)
[Answer]
# [Haskell](https://www.haskell.org/), 67 bytes
```
a#b|h<-a/2,c<-sqrt$(1+h)^2-b,c>0=h+c:[h-c|h>c]|l<-(a/2)#sqrt b=l++l
```
[Try it online!](https://tio.run/##LY7LboQwDEX3@QprhgURCYUAU6iAL5hdl3SmCgE1qOHRENQN/06N1MW1fKXjI2u5fvfGHIe8trsuuXwRTJV8/bHO8@NA06fgLVN1VOlAvTWaq13X6rGbkvvI0utJQluZIDDHKIepWjb37ux9uviN/RweDNZt9HGjDBY7d5tyZwtiSj@mS12beV7IOapuJtBI1j5KPsoFbC@78He23Vp69Vfv7sPUEzC9A1vhswRtw4Quhn6w7N/t@WjGA0uRReshICECUkxGRPga5yI/k2ZFlGaQhWlyy25nijiPCpJAXPwB "Haskell – Try It Online")
Based on [this solution of Delfad0r](https://codegolf.stackexchange.com/a/225850/20260), who also saved 1 byte off this
We first try to find a two-element solution with \$r\_1+r\_2=a\$ and \$(r\_1+1)(r\_2+1)=b\$, which we do by solving a quadratic equation. If we get real solutions, we're done. (If one solution is zero, we remove it and output a singleton.)
If this quadratic isn't solvable in the reals, we replace \$a \to a/2\$ and \$b \to \sqrt{b}\$ and solve from there. If we find a solution to this, then duplicating the list (that is, repeating each element a second time) gives a solution to the original problem, since this doubles the sum and squares the product of numbers-plus-one. We recursively make these substitutions until we simplify \$(a,b)\$ to ones that give a two-element solution.
We show that this process always reaches a solution. For the problem to be solvable, we must have \$b < e^a\$, which follows directly from \$\sum r\_i=a\$ and \$\prod\left(r\_i+1\right)=b\$ along with \$e^{r\_i}>r\_i+1\$. Since \$e^a\$ is the increasing limit of \$(1+a/N)^N\$ as \$N \to \infty\$, the bound \$b < e^a\$ implies that \$b < (1+a/N)^N\$, or equivalently that \$b^{1/N} < 1+a/N\$, for sufficiently large \$N\$. By choosing \$N=2^n\$ as a large power of \$2\$, doing \$n-1\$ steps of the substitution \$a \to a/2\$ and \$b \to \sqrt{b}\$ gives us \$a' = 2a/N\$ and \$b' = b^{2/N}\$, which we've shown satisfy \$\sqrt{b'} < 1 + a'/2\$.
This is exactly what we need to have real solutions for \$r\_1+r\_2=a\$ and \$(r\_1+1)(r\_2+1)=b\$, which gives a quadratic with discriminant \$(1+a/2)^2-b\$. It solutions are $$r = a/2 \pm \sqrt{(1+a/2)^2-b}$$
[Answer]
# [Haskell](https://www.haskell.org/), ~~102~~… 95 bytes
* -6 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) (also, go upvote [his amazing answer](https://codegolf.stackexchange.com/a/225866/82619)!).
```
a#b|m<-until(\m->(1+a/m)**m>=b)(+2)2=filter(>0)[a/m+sqrt((1+a/m)^2-b**(2/m))*(-1)**i|i<-[1..m]]
```
[Try it online!](https://tio.run/##LY/BboMwEETv/gorzcEGTLGBFCTgC3LrkdDKFLe1ahtqjHrJv9NFymFWs9qZJ@23XH@UMfsun8a7bdjmgjbkZllHeCyfLY0i27UjJbGgov3UJihPuoz2cIvXXx/II/cm2BhFRIClEWEcivquG9bzNLXDsFupXbts4TX4qzuR3r/rIcHrZgk4muDFz9P2EY4t5pTe3KnrzDwv6BjtNCPcy2QcGmblgr2SU/o3@2ltzt2XClftFMJGBexbeAQBTTtgJcDHPnmwzwTIUPAUskDdBc6RwAWoRCJ94ZWoDhVlnRUlLtMiv5SXQzWvshrlmNf/ "Haskell – Try It Online")
The relevant function is `(#)` which takes as input `a` and `b` as described in the statement.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
NθNη≔¹ζW›ηX⊕∕θ⊗ζ⊗ζ≦⊕ζFζIΦE²⁺∕θ⊗ζ×∨λ±¹₂⁻X⊕∕θ⊗ζ²Xη∕¹ζκ
```
[Try it online!](https://tio.run/##jVA9j8IwDN37Kzw6Um6gAwvTCXSnDkDF3R8IxdCINGnzARJ/PucCJ4HEgAfLz/bzs920yjdOmZwr26e4St2WPA5iVjziVhSfIeiDxYmECxfPrTYE@O1JxbEuoXZnDirbeOrIRtrhQp/0jnCQsHBpazhzEUI8IwFL1d9HP3BvInvngbug9tpGnKsQ8UubUY9JWLKmSeG1jIRf3VHAtUcjYUUHXhMnY/5nSMrTxrmIS22Z//7ipfg/k@@9N13/cTMJR/aznMtimj9O5g8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Basically another port of @xnor's answer.
```
NθNη≔¹ζ
```
Input \$ a \$ and \$ b \$ and start counting the number of repetitions of the output that we need.
```
W›ηX⊕∕θ⊗ζ⊗ζ≦⊕ζ
```
Keep incrementing (doubling also works of course, but it's not strictly necessary) the number of repetitions while \$ b > (1 + \frac a {2n}) ^ {2n} \$. (This explains why \$ b < e^a \$.)
```
Fζ
```
Repeat the output the appropriate number of times...
```
IΦE²⁺∕θ⊗ζ×∨λ±¹₂⁻X⊕∕θ⊗ζ²Xη∕¹ζκ
```
... output up to two non-zero solutions to the quadratic.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ 31 bytes
```
ḷ‘ɼ_’;N};1Ær½ßH}¥/}x®$ÆiṪṪƊ?,ḟ0
```
[Try it online!](https://tio.run/##y0rNyan8///hju2PGmac3BP/qGGmtV@tteHhtqJDew/P96g9tFS/tuLQOpXDbZkPd64ComNd9joPd8w3AOkxOLTy/Y6@o5Me7pxh/ahhjoKuncKjhrnWh5frg8VUNCO5DI0f7uhKNtJxUDy26VHTmkeNO6wPt///H22sYxSrE20CJk3BpJGeuaGFkYWOqZ6JsZmpWSwA "Jelly – Try It Online")
A full program taking two arguments, `b` and `a` in that order. Implements [@xnor’s algorithm](https://codegolf.stackexchange.com/a/225866/42248), so be sure to upvote that one too! Uses recursion to find real roots to a quadratic equation of the form \$x^2 - w x + (y - w - 1) = 0\$ where \$w = \frac{a}{2 ^ n}\$ and \$y = b ^ \frac{1}{2n} \$ for some non-negative integer \$n\$.
## Explanation
```
ḷ‘ɼ | Increment the register, then revert to the original left argument (i.e. b)
_ | b - a
’ | Subtract 1
;N} | Concatenate to -a
;1 | Concatenate to 1
Ær | Roots of polynomial with terms (b - a - 1, -a, 1)
ÆiṪṪƊ? | Does the last root havecan imaginary component?
¥/} , | - If yes, do the following using the original arguments to this link:
½ßH} | - Call the current link recursively with the square root of the left argument and half the right argument
x®$ | - If not, repeat each term the number of times indicated by the register
ḟ0 | Filter out zeros
```
[Answer]
# JavaScript (ES10), 93 bytes
This is really just a port of [@xnor's answer](https://codegolf.stackexchange.com/a/225866/58563).
Expects `(a)(b)`.
```
a=>g=(b,r=1,x=(q=a/=2)+(d=(++q*q-b)**.5))=>x?Array(r).fill(a-d?[x,a-d]:x).flat():g(b**.5,r*2)
```
[Try it online!](https://tio.run/##fU5JboNAELz7FX2I5G4YJqyOFw1WDnkFQvKwObYIAwOOiCzeToY4yjGHUpdqadVVfso@15d2cBpVlHMlZinis8CMaeGxUWAn5LPwycZCoG13VudkZFk8IhLxeHzVWn6hJl5d6hqlUxyTkZmT7kej1XJA2p8xWwpMWz7NhwQS8BkEkLIHC/9Y9Mv4i7f1twvCaOeGkXF4GGyizYKdt3V3j2DAwDMU0hWvlH6T@TtiApJBBimBiOG@AtBlDwIqlIQZHYyQq6ZXdclrdcZT8nQ3AX5VlwbXsKYpBceJob99mNLD02Vxy0vElkH@87UFG3IGLk0MWq2MO/wXtgC9pUFmLU0ns2Gi@Rs "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
## Background
The game [Grand Theft Auto: San Andreas](https://en.wikipedia.org/wiki/Grand_Theft_Auto:_San_Andreas) went down in history also thanks to its wide selection of cheats. They're almost 90 and anyone who has ever touched this game, no doubt has tried them all!
One cheat is activated (on PC) typing in-game a secret keyword, and then boom, a jet pops out of thin air or perhaps all pedestrians look like Elvis Presley or some other rowdy effect...
*They always come with this confirmation message:*
[](https://i.stack.imgur.com/F0Ro3m.png)
Rockstar [chose to store them hashed](https://gtagmodding.com/sanandreas/cheats/), so due to collisions, in addition to the intended ones there are many other strings that trigger each cheat.
Therefore I propose to solve this [downside](https://www.youtube.com/watch?v=yrXhYgVmKLQ)!
## Task
Write a full program that prints `CHEAT ACTIVATED` *if and only if* the last part of a string is a `cheat code`.
## Cheat codes
```
THUGSARMOURY
PROFESSIONALSKIT
NUTTERSTOYS
INEEDSOMEHELP
TURNUPTHEHEAT
TURNDOWNTHEHEAT
PLEASANTLYWARM
TOODAMNHOT
DULLDULLDAY
STAYINANDWATCHTV
CANTSEEWHEREIMGOING
TIMEJUSTFLIESBY
SPEEDITUP
SLOWITDOWN
ROUGHNEIGHBOURHOOD
STOPPICKINGONME
SURROUNDEDBYNUTTERS
TIMETOKICKASS
OLDSPEEDDEMON
DOUGHNUTHANDICAP
NOTFORPUBLICROADS
JUSTTRYANDSTOPME
WHERESTHEFUNERAL
CELEBRITYSTATUS
TRUEGRIME
ALLCARSGOBOOM
WHEELSONLYPLEASE
STICKLIKEGLUE
GOODBYECRUELWORLD
DONTTRYANDSTOPME
ALLDRIVERSARECRIMINALS
PINKISTHENEWCOOL
SOLONGASITSBLACK
FLYINGFISH
WHOATEALLTHEPIES
BUFFMEUP
LEANANDMEAN
BLUESUEDESHOES
ATTACKOFTHEVILLAGEPEOPLE
LIFESABEACH
ONLYHOMIESALLOWED
BETTERSTAYINDOORS
NINJATOWN
LOVECONQUERSALL
EVERYONEISPOOR
EVERYONEISRICH
CHITTYCHITTYBANGBANG
CJPHONEHOME
JUMPJET
IWANTTOHOVER
TOUCHMYCARYOUDIE
SPEEDFREAK
BUBBLECARS
NIGHTPROWLER
DONTBRINGONTHENIGHT
SCOTTISHSUMMER
SANDINMYEARS
KANGAROO
NOONECANHURTME
MANFROMATLANTIS
LETSGOBASEJUMPING
ROCKETMAN
IDOASIPLEASE
BRINGITON
STINGLIKEABEE
IAMNEVERHUNGRY
STATEOFEMERGENCY
CRAZYTOWN
TAKEACHILLPILL
FULLCLIP
IWANNADRIVEBY
GHOSTTOWN
HICKSVILLE
WANNABEINMYGANG
NOONECANSTOPUS
ROCKETMAYHEM
WORSHIPME
HELLOLADIES
ICANGOALLNIGHT
PROFESSIONALKILLER
NATURALTALENT
OHDUDE
FOURWHEELFUN
HITTHEROADJACK
ITSALLBULL
FLYINGTOSTUNT
MONSTERMASH
```
## Input
* A string \$s\$ over the alphabet:
`[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]`
## Output
* Print `CHEAT ACTIVATED` if there exists a `cheat code` \$c\$ such that \$c\$ is a [suffix](https://en.wikipedia.org/wiki/Substring#Suffix) of \$s\$
* Nothing otherwise
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~976~~ 965 bytes
*Saved 11 bytes thanks to @user202729*
Nothing fancy here. This is a hand-crafted regular expression which was randomly shuffled to please zlib and save a few more bytes.
```
import zlib,base64,re
if re.search(zlib.decompress(base64.a85decode('''GaqK,9,=TU&D^"aoJ0#fKbc'=7=3*ZC@Sjrb9-nO,G4ij>guO6,*oNLi[tq[ZsOTo,XZG;oZsh/gQt)R:U?gtgs2QpS5&Cl,CM,c4B%`<W5ZEuN=Sb$f!,mP`%@TQ:&Dg(:q8*+N)Y?Q#F9kM'KZ&%\I2W`#7oOUp1-0Ge3]q_o8g@lWflG`*QMr*9[[`i?a`=U:auDF%8=66MDaNUUiPI8J#lO0\l@*E:%PS)VCHdD>/N`=l1`t*hVA<^ON+dhUtN/]3U\\tupZtkD$:DPFh-HW3PZ$AAiEFm(g;<YJ6I4"uMdQX16JBN/W.`>QFrON6O,^B%Jl3Mn<d^IObA<=$[b;g`-:O$Ga?$ch!SrhQNm;`Led6I;8/VCeIra;1&X%b)&*]\XB4+g3`FkTT#fc%HR8*)g95de$99CT;oVaps<Yn\im/BJu&A6-O8L3#Ha0p6]PKP2a7,,T6[K>'rQiC1R,U1_Ko/:-EAfrcS7ik6HfK>2:cMot]rkBY#!9d"ujd=<dn@]JT9h=mClIt.YL?*b"(ImA*!E/(\Gob*ghDs1dJ.;O"]CPGTo!=5g=9e2+caXT43.mu:*o8`ai!KoaLJ5',M&K[V8d'?J=ISEG?GUZMbWXJ[iCde,Mu[(,9nY8%-73jGpPZFWBXSOTGg5:U<P2"/=V(g[PZJodG+cZuag^64TE.>i4i"BRD8=mu,Jga5Ip(0Z34oicZ"d'bi@2Bqe/D6Y*)Cc-#tb7!E4Q']mZ0F2M]&qrpj]qLqg0MLln_4Q7QA[9<@I^3OJAJ)p1?+NpZH)nYYp(.J''*9mJUg?9h.]o72ZKgN)90W>0sIe(IqbdBCsfj<Ma5N''')).decode(),input()):print('CHEAT ACTIVATED')
```
[Try it online!](https://tio.run/##LVPJkqIKALu/rxhXFhEXFAFFRVAEBaQFFxCbVcQWQZbDvJ/vN13zUpUcktxSSX8X9@SFfX9HcZpkxa9/n5GLuE4e4AMkC/6Jbr@yAM0DJ/Pu4E@G@oGXxGkW5Dn4t4Y6xPDH9AMQAADeeW8QEqE1vcldq04idmu3jesB9IjGYIOd7x@ZS7ZfCsIPosc0LBUcgRN5G5nF2zRyRUuQk8GPEyO/d0K1gD4ofRYWYd5X0/2wyT4RVkK8waJhT45DY1nK9N6t3ypIvLMbc02lmlwIUm8CbsnQeabWVuSXBGyMZuMi9I92bZQoetprd/kAs96fCRHOn8fbk7dhVcpg0jTtaObYtE45JbdqEDSOS5wj63q0Ewix9lS6l@ccXlKN3R46sGufm3Zkm3727AK@H5jJVZFb/l0v5I6F6ZdLUaZG8cXVKW63urfXR2xn1BkmWq5iMBxPziIuDKql5KunHi4u5M4RtafqKlNkXEGui4b4xKTXxL8KistM6LrpjkO7TSl13pnVvXtln91VOR7b28DHhTHRObCBkDnjXvPUcKEmbF1Oi0ErxOzVl6bVbl5j/UHAUEj@malOkqw2Tg5Omk/Or0sUdxZi2WTwtkJssdra6aa4tdvs@s4IQTTc3EyBTI3Y3gei9z43SYdqL5lb5u1H0Re@vm2mfcqTksLKvhbnWoX0q@XDpyf@a26JGnmnY/YpFOh5O4PdKijEDFxZdsALn7hweOfyni@iY6VqsTteSyr0MKTJoN/ynJM2wNC4pOCEsJ2oskmcrTgEEKm5MQ@ED8xEWtgv@RmvG5J7PIlmxPoBIpUmiJCvM9Foj7AHn@6M1XFx2isaHw4pfbLrVzv0AQzNnSEmPt/yjNIJr/hAW6LTaBBVFx8cQcclIobOUEjBroENksgzqj7gRvP@4h10OPwMQ6zXrhXuqLIcqIAVG91VX7Ka7yx9WO/tO@xK2@frc6COVMYkJ3PhiikiI0Jpb9aSU2MNvc7nFERFAIDJWNTDGXlHrWTUNzahDJHd47SbCwEovF1/wea3x0RyhvKfQ0EQ@v@7ICR6pWUBQhCVZtGrAAF2vWS0XwyrCQdGW3IA9P19@gG7FjTt/FcXjMz/8D8 "Python 3 – Try It Online")
Or [See the uncompressed regex](https://tio.run/##LZPHlqIIAADv@xVrJIgRREAxgSIoqQUDiE0UURBEOMz@fO/M271WHetV9qu4py/05ydKsjQv/v4njlzEdT4Bjv2V5dGrAP@Qjh94aZLlwecD/ic7DjH8A/0ABACAc95bhERoTW@y16qTCr3abet6AD2iUdhg5vtH7pLtl4xwWPSYhqWMI3Aq7SKzeJvGR9ZS5GRw49T43LuhWkBflD4Li/AzULP9sMnECCMiHrZs2JPj0FiVEr1367cKkih2Y66pVJMNQepNwC0JOs/U2pp8isDWaDYu/OBo10aprGf9do8LUOv9nRLhPD7eYs6GVTGHSdO0o5lj0zrllOy6QdA4LrKOpOuRwhNCLZZ7l3gOr6iGsocOzMZnp13JpuO@XcD3w2JylaWWf9cLqWuh@uVSlJlRPNk6xSrre3tzRBWjvlhEq3UChuPJWcB5rFqKvnrq48JS6h479lRd57KEy8h12RBiVHxN/Csvu4sJXTfdcWi3KbnOObO6d6/s87sqJWN7F/g4Pya6Bybgc2fcb54aLtSErctpibVC1F4/Na128xqbLwKGQvJ3pjpJMto4PTjZZ3J@XaKkuxTK5gJvy8QOrW2cXoZbylYZOCME0XBzOwVyNWL6X4je/96mXaq9Wtxybz@Knvjmtp0OKE9MCyt/Ls@1CulXy4dPT/zX3BI08k4nTMwXnfNuBrtVkE8WcGXVBS9c6sLhnf30faEzlqsWo3BaWqGHIU0Gg5bnnDQM7SQlBaeE7USVbershCGAiM2teSB8YCbQ/H7FzTjdEN3jSTAjxg8QsTRBhHydiUZ7hD64TDHWx@VpL2tcOKT0iTKodukDGJqKIaQ@1/KM0gmvOKatOtMIi6rLL5agkxIRQmfIZ2DPQLE08oyqD7jRfLB8B10WP8MQ47VrhTuqrDAVsBKjtx6IVvOdZw/rvXuHPXEXv74xdaQuTHIy56@oLCwEKOvPWlJmbKDX@ZyBHQEAYDIR9HBG3jtWOhoY21CCyN5x2vvwAci/XX/JfG6PiegMpd9DQVDn/7sg6OfnXw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 753 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•ćÉÞû9‚2¬ú@iH°<]ĆA~Qò†ø‚”Kƒćž»”‚ŸǝD6øZ\§HÔØΔÚÿþjv¤¼§….[Ωîužć“₅nÕbn`ιwU0›•#`’ÿ¨¥€´y ‡ªsíÃ ÝæÿŠ… i‚Û€ä€Ô ‹‡€¾€€š¢ ‹‡„‹€€š¢ À®ly©Ã …«Â£…ß ÿ‚Ž ‹€€†€ƒ‰Ï…Û ÏÏ€È‚Ã›Î…ì €º‚‰f´‹€‹ ŠÍ€•€¾ ¥€€•„‹ À¸ÿ€´Â° ‹®â¢€‰€á က‹Ýæÿ €º€„»áí„ „ÏŠÍ«™n ÿÝæ‡´i¦§ €–€‡‚ƶ¨ ‚‰‡Ü€ƒ‹®€á ‚Ãs€€¼§ ¨À‡‚ ‰¦ÿ €Ÿˆ™‚œÒÞ ¯š€É‚µ ©ß€èÿ ‚¿Þ¡ÿ‚ï ¬Í‡Ü€ƒ‹®€á €Ÿ¢ž€™žÜs ™Å€ˆ€€€¢îÁ ¸•ÿ®ísƒÏ °ä•Ç €Ðâ쀟€€Èšs Ó´f€á€¾ ÞŸ€ƒ‹ˆ ‡—ÿŠë œÆ€‚€€™¨‚… ‚ìsaˆÁ €É€¨€ˆï¶ …ç‹€¹¶s ÿ‰à „Ρ¤ÿ€Ÿ ŽÇ€ˆ—‹ ŽÇ€ˆ›Í c•»tyc•»ty±»±» cjƒ¿€¨ ïų• iƒ¾€„h‚Š ›ä€¯ƒ´€î—Ç ŠÍÿ ͈ˆ™ †æˆ×ÿ ¬Í‰€€†æ µ±Ž€ ³Ö€†€¯ÖÇ ÿ €¸€µ€©»å€á …Ž€šÿ ´Û‚œŠàëÌ ÕÕ…Ž i€·€œi‚µ •€‰ st±µ€èaÍÝ i€Ü‚ÒàŠ ‚‹€‚™‰ ©„‰à ƒ¶acŽÏ¼Ã ‚衹 iÅˈ¬€‹ ·ä‰à ÿ´™e Åˀ€¯³£ €¸€µ€©‹®€ª ÕÕ€¿ÿ º°€á Ÿ™£Í i€©‚œ€Ÿ†æ ‡ªÃ½ ˆÃ¼Î ŠçÞ® †ì¦³ˆ¦ •»€€†â—É €ç€ŸÅÍ °ä€„ÿ ±¹mÌ¢’u#Å¿à‘Ç¥Ù‡‘×
```
[Try it online](https://tio.run/##bVRbTxtnEP0rn5T3qOpDpUp9aNVGDYKXqo0q9SKFoER11NIHJ614qbZc7KDGuDImAQcc7wK2CcY2xRBfgi3N8dIHS/yI/SP0zKwNVVUJ1t/ON5dzZs7sz8nZB4mHV1e3Iy8YprGKInofRl7hfamh@3HirjQ/@n6Y@uS3L/BX5JXQ5lXk7Uxf5IbpsC89nmkJ23/vfPYB2t98J5W7yGPzMo8CBug//mXoyZ68k0rklW9/e3mA@tOwP0xH3na0uDKPjQfz9y87v957L/K6BHDrfuRtYSBV2Y8Wa9JacJHny5skjrDksIMyBmGJmVyCRfGKPtjTR55@HbpqUJ8P/oW@BBOrV9TDjRme1H9ckAMmZTI5xKLs8oDXDgNlc@6u/cmZz4tc5DWRVZ9XDlmeWPSZYlgicKzpRc1p9a71p/lIWuMUXseFJWTsGBg@Z@TGBoOmgNosrZSJpanlpY5AAvNqajXfwZ@EdeJWjAuqpSg9@DjigbFFZLWkHEbLwTwpqbf2sZWQslScBazb01cKKTmTqotx04TtMWFCiAsbz2RcXEfppAovDuZdU8ZQwvYoxYrawHXkUHTSCBUyVmmSU8d@v9bXqrrTMkBRfGs4Go5qy/x/cU0sQWhjXeYvtpOOB6zQwIJxSwgsQB2/O6FAAyqojqPkRQ5ZJ01KhKa0ZsKfCGAyaMdReBb6SYd1aT2ycvGAULR7wzFKOaOaV@nh0JGbFWW74tLLgVSteWVrVC05O0oRSEyc6aqGEw05U7GhEutCOnKWNLk1UbKZrYkveyaCsO3Cc6Rjfl7eJHTz3kXGzZGR9J4sTH7lWHr67@YeX@TEhFR1aGBFTujhEjT2Y538oOPRgl3bHGnwqqVY60oxbVrlfJAZpWyaTpe@TPwvadUhoR73zlQZLwjKTk7lODznq5MTvLjeG2ngBZOOpapxcqqPA8p1fyKusgWGvhZocalVP4TBZuO5wwY2zIUrz8C36rmeiAV1DWW8Ji75hE04NY3NEumOxVBSHEsOJaNdmKxlwaTapCptB3UKbMXZ7BxbnZV39mkooMqhdFwCK/hjlJLx9jl5q5rSECqtxUQPnXposca/uMuJ7P6X@ETZ8iamxtNAiXdlvOWkREXtcsiJcQDbESvWOm0fRCzJueNQlgh0TWdW4S7VbVY17vgJsaontXEzpEAHvGq6rFg@Qs7E62HKUBTH0vkJz/nZ8bae3qJ6BuDXdhNp2ceWbcEmXl5dTX09NTPz5VdTn07PTE3f@Xzm3p1/AA) or [verify all the cheat-codes](https://tio.run/##bVRNbxtVFP0rT@q@QiyQkFiAxKISKxZsoEhNo1a4gnThliobNOTDbkQdI8cp1E1czyS1ncaxHeKk/mhs6R5PWFjKj5g/Es69b5wghJSM39x3P86599x5nF24n3lwdXU7CaJpHhuoYvRpElQ@lhaGn2fuSPez76e5L375Gn8lQQ19XiXB7lcXpWk@HsuIZ1ri/t@7X36C/rd3pXEHZfx5WUYFE4wf/TwNZF8@SCMJ6re/uzxA@2k8nuaTYCdZWV/C9v2le5eDZ998lARDArh1LwleYSJNeZustKS37JIglHdZHGHVYRd1TOIaM7kMi@I1fbCvjzL9BnTVoDEf/ItDiebWoKqHGzMCaf@4LAdMymRyiBXZ4wFvHCbK5txd@5MznxelJOiiqD6vHYo8sehzxbBK4NjUi5bT6kPrT/eh9NIUwcDFNRTsGBk@Z@RSg0FTQH2WVsrE0tXy0kYkkXl1tVroEM7DBr4VaUG1VGWEEEc8MLaKopaUw2QtWiIl9dY@9jJSl4azgC17hkohJ2fSdB43TdhJCROCL2w8s764jtJJE4EP5l1XUihxf5ZjRW3gFkqoOunEChkbNMmpY7/f6GtT3WmZoCqhNRwdR7UV/r@4JpYotrGu8Rc7WccD1mlgQd8SAovQxq9OKNCICmrjKHtRQtFJlxKhKa@Z8DsimAz6PgrP4zDrsCW9h1bODwhVuzccs5wzqmWVHg4duVlRtsuXXoukac2rW6Na2YVZjkA8caZrGk505EzFhobXhQzkLGty66JmM9uUUPZNBHHfxefIe35B2SR08z5EwS2SkYyeLM9/5VhG@u8WH12UxITUdOhgXU7o4TI0jr1OftDxaMGhbY50eNVTrG2lmDetcj4ozHI2TadLXyf@P2jVIaHte2eq9AuCupNTOY7P@erkBC@v90Y6eMmkqVQ1Tk71cUC5vp2Lq26BcagFelxq1Q9hsNl44bCNbXPhyjPwvXpuZbygrqGka@KyT9iEU9PYApHuWgwlxbGUUDPalflaVkyqXarSdlCnwFacLSyy1UX5YJ@GCpocysBlsI7fZjlJt8/Je9WUhlBpPSZ64NRDi3X@xV1OZO@/xOfKlneeGk8TJT6UdMtJiYra45AzaQDb4RVrnbYPIlbl3HEoqwS6qTNrcJfaNqsWd/yEWNWT2rgZUqQD3jBdNiwfIRf8epgyFMWxDH7CC352gldPb11d/QM).
**Explanation:**
```
.•ćÉÞ...U0›• # Push compressed string "stunt hem hicksv atlantis kangaroo wler freak quer ninja suede nga cruel glue grime dough ters neighb dulldull ters thugs"
# # Split it on spaces to a list
` # Pop and push all strings separated to the stack
’ÿ¨¥...mÌ¢’ # Push dictionary string "ÿarmoury professionalskit nutÿtoys ineedsomehelp turnuptheheat turndowntheheat pleasantlywarm toodamnhot ÿday stayinandwatchtv cantseewhereimgoing timejustfliesby speeditup slowitdown roughÿourhood stoppickingonme surroundedbynutÿ timetokickass oldspeeddemon ÿnuthandicap notforpublicroads justtryandstopme wheresthefuneral celebritystatus trueÿ allcarsgoboom wheelsonlyplease sticklikeÿ goodbyeÿworld donttryandstopme alldriversarecriminals pinkisthenewcool soloÿsitsblack flyingfish whoateallthepies buffmeup leanandmean blueÿshoes attackofthevillagepeople lifesabeach onlyhomeisallowed betterstayindoors ÿtown loveconÿall everyoneispoor everyoneisrich chittychittybangbang cjphonehome jumpjet iwanttohover touchmycaryoudie speedÿ bubblecars nightproÿ dontbringonthenight scottishsummer sandinmyears ÿ noonecanhurtme manfromÿ letsgobasejumping rocketman idoasiplease bringiton stinglikeabee iamveryhungry stateofemergency crazytown takeachillpill fullclip iwannadriveby ghosttown ÿille wannabeinmygang noonecanstopus rocketmayÿ worshipme helloladies icangoallnight professionalkiller naturaltalent ohdude fourwheelfun hittheroadjack itsallbull flyingtoÿ monstermash",
# where the `ÿ` are automatically filled with the strings on the stack
u # Convert it to uppercase
# # Split it on spaces
Å¿ # Check for each word whether the (implicit) input-string ends with it
# (1 if truthy; 0 if falsey)
à # Check if any are truthy by taking the maximum
‘Ç¥Ù‡‘ # Push dictionary string "CHEAT ACTIVATED"
× # Repeat the string the integer amount of times
# (so once for truthy; and it becomes an empty string for falsey)
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how compressed string `.•ćÉÞ...U0›•` and dictionary strings `’ÿ¨¥...mÌ¢’` and `‘Ç¥Ù‡‘` work.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~1094~~ 1082 bytes
```
HE
g
Tg
y
ST
a
GO
b
TT
c
DO
d
IT
e
AS
f
LE
h
IN
i
AN
j
AR
k
LL
l
OU
m
RO
n
ES
o
ON
p
ER
q
ED
r
AT
s
HO
t
IC
u
jD
w
Al
x
ME
z
NIGHT
=
M`(THUGSkMmRY|PnFoSIpAL(SKe|KILhR)|(SURRmNDrBYNUcq|NUcqaOY|TIzTOKuKf|NOTFORPUBLunAD|CEhBReYasU|xDRIVqSkECRIMiAL|BEcqaAYidOR|BUBBhCk|SwiMYEk|MjFnMsLjTI)S|(DUlDUlDA|TIzJUaFLIoB|IAMNEVqHUNGR|asEOFEMqGENC|IWjNADRIVEB)Y|(aOPPuKibN|TRUEGRI|CJPHpEt|WORSHIP)z|(JUaT|dNc)RYwaOPz|NOpECj(aOPUS|HURTz)|iErSOzgLP|T(URN(UP|dWN)ygs|OODAMNtT|mCHMYCkYmDIE|AKEACHIlPIl)|PhfjTLYWkM|aAYiwWsCHTV|CjTSEEWgREIMbiG|S(PEr(FREAK|eUP)|LOWedWN|OLpGfeSBLACK|COcISHSUMMq)|RmGHNEIGHBmRtOD|OLDSPErDEMp|dUGHNUTHwuAP|WgRoyFUNqAL|xCkSbBOOM|(WgELSpLYPhf|auKLIKEGLU|IdfIPhf|aiGLIKEABE|OHDUD)E|bODBYECRUELWORLD|PiKISyNEWCOOL|FLYiG(TOaUNT|FISH)|WtsExyPIo|BUFFzUP|hjwzj|BLUoUroto|AcACKOFyVIlAGEPEOPh|LIFoABEACH|pLYtMIoxOWr|LOVECpQUqSx|EVqYpEIS(POOR|RuH)|(CHIcY){2}BjGBjG|JUMPJET|IWjcOtVq|=PnWhR|dNTBRibNy=|KjGkOO|hTSbBfEJUMPiG|nCKETM(j|AYgM)|BRiGep|(Gta|CRAZY)TOWN|NiJsOWN|FUlCLIP|HuKSVILh|WjNABEiMYGjG|glOLADIo|ujbx=|NsURALTAhNT|FmRWgELFUN|HeynADJACK|eSxBUl|MpaqMfH)$
0
1
CHEAT ACTIVATED
```
[Try it online!](https://tio.run/##VVTLkqs2EN33V2SRVMEuyX4WAhqQERLRw4zuKh6P3@@xXWM7nW@/aTx1K0kVgpJEP8/p8zG7rPaT778k1Z/fa4QF@AXcwXmYQGXgDbyHKRQG3kF6mIFwMAeFsASpYQVCwxqEhQ0oBVswAXZgDewBHRzAaDgCWjgBFvABwsMZagMXkDlcYV3AJ4gt3KBFeICWVe3hBdo/E1@Hym3anY3U7cuDk0ehEtfMqJFqaVNKXLB2p4uPLOowPdHwmphIXj68aa7NnLTxpbFdyNR1LwrKcZnZWZycA90KK8cnt8HcynYlFGXIxiKu3o2lLGTZMt@Q@1y1ETfUrst9e1ZrL1NHSRG2wyOGOKMwKZU8ZCRFq3F8qoOuLE3OaEpsTxXqnGS/1mKIhlkaKZmYrrs2qzdN3gasrKR81NVHvFBvrKtllz4oYbee3vU0tfGTDR5cyBHz9WAcHNXB@kdKK/xw5rFQHfkkWJ2Ejt57nd4XZzKm4HwunnZ53cZ8E3eFRBINiryW205uU@qW87VXsd@0NJT92Z/z2o8pX3uH2C8syvZtVZFLOvxISouioVnoUlKmn3EYMupYzWcuUyJvKDdT6WoX2vaUkt1VtUaGMdvZiyn4z8KxkwLbI70Hvgu@/ryKjjjK4V4GfeL23/KNe8uMaSnpF6jcUUXOkCbXRskGKxVIvs/l82hVDUciQzJ1EYoU6c0UWWQkAypuoiqoWzXS3TX2uTGKShVXVeLNJGhPJSeaUn854@3eyQNjXZYPbt1y/flYU6bCIXwcLgcSUy7MlPex3IoKOzTdkpQsDxyXm0ic36WVh5vpP7glY8yPf4STuxFzIB5RctsME8leOVbCPZ/G9K/f/87WFT80Cm03Qj8wY2ou4xO9dPt@aRlwn1lmxv2FmnW1MYaWnpsyx8GAsdjnDfo2WZOIizYl/reaHSmpLhPKrfgWU28YGL0anYdvGba5kh3V18aNeWBo4GGGzOiKc1hsjRIF139dv91eSJ@DFcqL5dChnR0gYGCont15bkYDxDN3y8KW2uPk1M7r9Gf4FeA3yGsU/ieRezkWHovvrB1KmefgCtuaYCMMM6ii1JU3zjMCoIUTJdQYcYw2GqaKG5oF/26tzGuWif94@QaeKR46X@MQ8bkruMof@yIo9Vwick7S@/j1zoSuhgWvudBPZtc4ULsynBD0teGshVLsppOsVQMZWgzdkF1htPc2Cl04bzrWJj6LJkR0/B4F9/9L6R37yTgFaI12Hm0rXA2Dk8xyLDOk@qVtjq2kZmER1rEEcnaGTb/uOsvC4Zw0WijXsNR@DQ8WPD0sozkqZHc@Oi98YOueq/KmZgLaL@VkB73iTS3zJ@ys0U9uDNSAweqpTGgHaYrw@voKPMH1jzWAJZ6Y/gM "Retina 0.8.2 – Try It Online")
[Verify all matches](https://tio.run/##XVbJcus4ErzXV8yhJ0K69cz9HUCyRMIEATYWK9inlm3Z2mxJlhRepvrbXycoO6ZnIrQEZaCWrMwsvy7P65fFz39O6j9@NkxPFJ/og0KkBdWO7ihGuqfK0QPpSEtSgR7JMK1IW1qTsrQh5WlLxtCOXKJn8o5eiAPtyVk6EHs6Elf0SirSiRpHZ9IlXWhT0RupHb1Tx/RJVtdNpB/U/TGJTarDtnv2g/Qvs33QB2UmoV1Kq83KT2USkvfPtnotBpvuj5I/Fm6QqD@jay/to1gXZ873qTCXF1VJyavCL4fFKcl75fXtMWy59LpbKyMF47Ia1g/OS5GKYlVuJbytu4G30m1mL93JbKKeBplUaZdfKue5SYuZ0ftCtOos3x6bZGsvixO7GXfHmm0per6xKmfjYjrIZOH6/tKu76xEn7j2WsqbvjnwWebOh0b300@ZIGyUB3s/9cMbLnyikQOXm3w5BWmSj59TWfNrcJ9Pppc4Sd5OUi8Pczv9eDqJcxXqOUd5LptuKLfDc6VZVMuqbPSu17up9KvHTTTDfNtJbvttfiqbeCvlJgbm@ZNn3d2tawmTnl8nM8@qlWXqp2LcfIk04syhflyGwqiyldLd69CE1HXHqfjnurGMMRbP/uwqnKwCglTcHeQh4W8pNm8X1Quy7D9myR4B/3u5DXeFc51M5k9swsEMqFAWl9bolmuTRD886vGndZ1/UgWLa6pUTVnuXFUMmGRiAxBNJf261eHD8rx0zsjMDOt6Et0i2SgzFDqV@fnE7x@93mPWs9knoFtt3j43Upi0T6/7817UPRpzs49bvVM19@z6lRg92yMvQBTUd@70/t3NXwHJLZeH39IxvAs4MBxYAzYHIvkLck2A@f0w/c@//yw2NV5yk7r@hmNmxr073x7lR/8yX3kMPBYezPj4Ie2m3jonqwhQHjlfwCxeypZjN9mIGp66qeBsvTzIpD4vpPTq92EaHQZj1zen/D1Lu9LoXppLG24hGMk8LBiMrlHD084ZVaH/y@bu/YfYU/LKRLXKCD37PAIMRprlB3Rzk0e8DO9F2kl3WBy7x2b6C/1K9C8qG1bxH6qM@lZFrn7@HDWrfOeSH6j3kEEI2lllQgvjwOgj@xDdEGAczFVwHTdseopgcOpjwzng@FShie/n3rAKyma@IjbFK78bF6lKxoxvNcCt1KCtstVcxUxmKnEls7nhTOfaaVtT1B3wDBGy5VDgUo8ydEw9BVBbx5wW3pW@OYxGGqRDcAhXly1iOAunyt7jkq24yu4ztjXGhvPglAqBrrznCsSHA1bui/qoT5eqp/96ky69U1WgXFb0Aw7kZMgxFh4AAmbBmA@VbLjwOg5oNSYkvFoIjipjSuVD7bKG8kVoyFmIKCOHaiOK@lISw9H/TzCozv5vasQbPctjmKNH6jxD6rWFslDRl7YoOONsrYKOVysgiA0QZZWhCgdSIBLO90CbstY6BtQoKs@pwxdBchwSVxwahzMqxlF4uAPWmi/tYdVAfByu6qPcWeM6xER0N8daKfjKrMyACtILWCT2RmVF0KhPZ39LuRssKEZbg8N4Qxbp3x69RmyoNcbh@lkoW@c3ZY/GEeRk@pIv6TnoFV2D6B6UTKPVKoRKMNsrr0bfpLxODOfxXLcbZDE3uJNBxzQzoTKi4@ILpYvxy0txJGS2WCyhfLlFJco7B@qgFpA7LwIU1Ck7865T0aAgHYBuzETA3HOpmfTejdYBtHXlMKwvVozJdQQ7wQ/7batM12XGftxmo67iuNDY54020Og2I7Txa6cY0@NNMygxm86IzffWG6huHJidzzegYXYjzHM8UXDurs4QfzeVCQhqf5c8NAw@X1cjeoVZmNG5QBXICNhholfo/u42bU7hyUIlo68ZtpHGdcE0g6RHgUBVlMcMlbmry@Gfm8yQIuVeRiJHVI61QZBwAME6FZq/AA "Retina 0.8.2 – Try It Online")
This solution is based on the observation that many letter pairs repeat several times in different cheat codes. We can replace those common pairs with lowercase letters (since the input will be in all uppercase) before executing the main regex.
Common letter pairs were generated using [this program](https://tio.run/##dVS7juU2DP2WdDMpAuQDgkCWaEnXlOhI1BgKpkiKLbZJEQSYhv8@OfLsAJsihX0hXIo8PA///eWfr3/9@f7@w9sfT69vr2/PT7/@8tOPT68/P//f@/n9XdOI3bUio007m@zUe5bquB9ZrQ5Val1ldsuVKHQplIhP09HqODXh5PQ@Bbnq5/lkct1V5Xmht6lIcKUmUQuD@X7ctK5u5upquJz6pC/mcaUTXYka5RIl12iaCz1G150z9Q2XTsDIOk7rLFfWNdaajJgq5Zg2LJIwDs3lPLM/0ENqIeujoaoGCtv8ttbdW@VAlevdhMPdPFCRauFuOTQBX/butCq6SzvHxtk3caHbgqVtomANw4wbeAcJ@6jUHJsnpq1lnVhVBwa2QbFhqjlm71qPsomUdZG4S@V5Mwe0ClCcD4o8yCIW2iZ53OZLGgegq/8djX6h5Rds5RoKc8lLQztzPfJCVOnyImxdWGp0PWvf2PnDdoYGcc89AYU4JXRC/Qm2bRv7XghUA9TSqeDHNiDqgwL1JKhxqmgjO@68ZGYX6STBFsYZXnIbOZ9sbZakoCe6y0XBNvpw1nJAEIEYNdeH06Umywt5qb@NtQ2zEdaaAnn7icrvji2jt09ZdX68N1fjesw/zoQSzCTIVM4HqeUL9lJJ6N5gyeFTmdBgygiZPny1N3IH1t42piUPQMWkiMXFuLNIh5rLUIvR9Zd1L6ogr49SUNKXW2qZtC4fQOKaCKwDLDB3Gk0BqLi6NylOGYByB7u6jADdF9Rl@ib@IEWd5SAQ65sr7uFZ4U74o8blDxBMlhGuxUoaNbY7V0pIMgBFqn6ab@73eVOr7liCQKgTj@1Ioud83txUdzsIGYtJ4OxVn2DDvnSFuVfFRmu7uCj@XGoZENb@hDwTwc8QNOXlS3wsWNiFZSfECNxB0Q/qvv/aHGtEs4qUIDfqmKqapDAC2Y5I3wFBqmzJjJQhf4/lXtgY/baxdrmNrEA@cBcR7jBYcT39Cw "Retina 0.8.2 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 744 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ú↓╒E╢≤3░ü(⌡▬α▲Kw~Eæ║aù≡╕↓╠ækîª♥J╠⌂ÿb╞╝ø└╫£φ├╡▌ê╔ê;y9¿¿¢Ö⌡D◘MB╡ú:¢▌BÇ!ÜÅ?╫-◙¥·╘hM┌ûoƒP墿δ╓x╓7╤½{α█hè▄ΔZ∙╙d≥♀'ô▼╘[πCò"┬╦•ù,╫▀╚╟TεÿRD°ß£{♠╕~>G╧ÜG⌠é~F~⌐?Iê→LA╟αa°♦V╔xhU∟δ¶╧▀Dïîc╫►τ8üîÄ╠⌂○╣*i☻▌ƒç╥¿ÇàM H─▬½÷`bû>miWπ∞*ü\σ¶REuü╚∙╠K┌ΦîΣ╫←▒╜A+░Ñ@)nφ₧∞'i╤Su@↑⌂¥ynΓv█e-0y╧ŧ∟8φ·k½▌↑ëK╡7╛ƒ └¥τ─~↕τ╫^sh<▀Ö¥4╟╔«▼»0┌▌ûÆ↨1ñFf┘ê▒}[d↔ätf,▀⌂qt‼≈Xⁿ←ìhà⌂ÇΦXDÿs═JéΔ♠ö╙═[═4○tºyBoz?e╔§▐Ñ│δ`♣m♠°⌐ñ▐b╙|I₧◙Çq╧WNÿ:hYⁿ╝Ö┤ Ö╟╗φW@‼¡Δ¥♥£<Mÿt·╛~Ö◘U3∞P♂πΩ○U÷₧ï↨75-]├╢▒║3#│‼8^7.♦▼2↨8├Fⁿ♥>º√√─Ö¥┌Æ☼;∙Δ;+ï♪≥àΔñö╢íhåhò╤7e╣D┼┌τ·▐\½N⌂se0░╖1NmQQChs╕ë╒┌≈Å■╓{]&§╦π◄▲┘#?◙èáK?A▲≤û}╥5V#(¢⌠ü,∟δ$:åΓ↑╟ΘΘ±○«╠j┐≈o,v♦ì9╜æ-K│↑♀fwß☻δA┐┼à◄?║H√╖¿Æ↨á░Ö╗╣ΩÄú╢Mé=Ä▌↔→a°◘^j►╡┐t'◄wΔh←▬╜δt♫¡ïù«○├α7♣G▼K]H┬>♥á»φ9öù|╜Δ╥Éﬡ.╚øKôªRø─Ç╞╗}₧4◙|`▓íâM ╥╨uⁿYéΔß☻¶∟ëæ┤,á╔∞₧Hæ}♪↑ßvâúy[>lu7▌z╒sóÄO:L▬╦íDq§φiIΔ═ûδ▓^ff▒
```
[Run and debug it](https://staxlang.xyz/#p=a319d545b6f333b08128f516e01e4b777e4591ba6197f0b819cc916b8ca6034acc7f9862c6bc00c0d79cedc3b5dd88c9883b7939a8a89b99f544084d42b5a33a9bdd4280219a8f3fd72d0a9dfad4684dda966f9f50869ba8ebd678d637d1ab7be0db688adcff5af9d364f20c27931fd45be3439522c2cb07972cd7dfc8c754ee985244f8e19c7b06b87e3e47cf9a47f4827e467ea93f49881a4c41c7e061f80456c97868551ceb14cfdf448b8c63d710e738818c8ecc7f09b92a6902dd9f87d2a880854d2048c416abf66062963e6d6957e3ec2a815ce51452457581c8f9cc4bdae88ce4d71bb1bd412bb0a540296eed9eec2769d1537540187f9d796ee276db652d3079cf8f151c38edfa6babdd18894bb537be9f20c09de7c47e12e7d75e73683cdf999d34c7c9ae1faf30dadd96921731a44666d988b17d5b641d8474662cdf7f717413f758fc1b8d68857f80e858449873cd4a82ff0694d3cd5bcd340974a779426f7a3f65c915dea5b3eb60056d06f8a9a4de62d37c499e0a8071cf574e983a6859fcbc99b42099c7bbed574013adff9d039c3c4d9874fabe7e99085533ec500be3ea0955f69e8b1737352d5dc3b6b1ba3323b313385e372e041f321738c346fc033ea7fbfbc4999dda920f3bf9ff3b2b8b0df285ffa494b6a168866895d13765b944c5dae7fade5cab4e7f736530b0b7314e6d5151436873b889d5daf78ffed67b5d2615cbe3111ed9233f0a8aa04b3f411ef3967dd2355623289bf4812c1ceb243a86e218c7e9e9f109aecc6abff76f2c76048d39bd912d4bb3180c6677e102eb41bfc585113fba48fbb7a89217a0b099bbb9ea8ea3b64d823d8edd1d1a61f8085e6a10b5bf74271177ff681b16bdeb740ead8b97ae09c3e03705471f4b5d48c23e03a0afed3994977cbdffd2908baaad2ec8004b93a65200c480c6bb7d9e340a7c60b2a1834d20d2d075fc5982ffe102141c8991b42ca0c9ec9e48917d0d18e17683a3795b3e6c7537dd7ad573a28e4f3a4c16cba1447115ed6949ffcd96ebb25e6666b1&i=ZZZZZTRUEGRIME%0ANOTREALLYANYTHING%0AATTACKOFTHEVILLAGEPEOPLE%0AIAMWHOATEALLTHEPIES&a=1&m=2)
It relies heavily on compressed string literals, and there's not too much interesting about it.
[Answer]
# JavaScript, 1200 bytes
`s=>/(ALL(CARSGOBOOM|DRIVERSARECRIMINALS)|ATTACKOFTHEVILLAGEPEOPLE|BETTERSTAYINDOORS|BLUESUEDESHOES|BRINGITON|BUFFMEUP|CELEBRITYSTATUS|DOUGHNUTHANDICAP|DULLDULLDAY|EVERYONEIS(POOR|RICH)|FLYING(FISH|TOSTUNT)|FOURWHEELFUN|FULLCLIP|GOODBYECRUELWORLD|HELLOLADIES|HICKSVILLE|IAMNEVERHUNGRY|INEEDSOMEHELP|ITSALLBULL|IWAN(NADRIVEBY|TTOHOVER)|JUMPJET|KANGAROO|LEANANDMEAN|LIFESABEACH|LOVECONQUERSALL|MANFROMATLANTIS|MONSTERMASH|NATURALTALENT|NIGHTPROWLER|NOONECAN(HURTME|STOPUS)|NOTFORPUBLICROADS|NUTTERSTOYS|OHDUDE|OLDSPEEDDEMON|ONLYHOMIESALLOWED|PINKISTHENEWCOOL|PLEASANTLYWARM|PROFESSIONAL(KILLER|SKIT)|ROCKETMA(N|YHEM)|ROUGHNEIGHBOURHOOD|SCOTTISHSUMMER|SLOWITDOWN|SPEED(FREAK|ITUP)|STA(TEOFEMERGENCY|YINANDWATCHTV)|STI(CKLIKEGLUE|NGLIKEABEE)|SURROUNDEDBYNUTTERS|TAKEACHILLPILL|THUGSARMOURY|TIME(JUSTFLIESBY|TOKICKASS)|TOODAMNHOT|TOUCHMYCARYOUDIE|TURN(DOWN|UP)THEHEAT|WHERESTHEFUNERAL|WHOATEALLTHEPIES|(HITTHEROADJ|SOLONGASITSBL)ACK|((CHITTY){2}BANGB|WANNABEINMYG)ANG|(BUBBLEC|SANDINMYE)ARS|(CANTSEEWHEREIMGO|LETSGOBASEJUMP)ING|(CJPHONEHO|(DON|JUS)TTRYANDSTOP|STOPPICKINGON|TRUEGRI|WORSHIP)ME|(DONTBRINGONTHE|ICANGOALL)NIGHT|(IDOASI|WHEELSONLY)PLEASE|(CRAZY|GHOST|NINJA)TOWN)$/.test(s)?'CHEAT ACTIVATED':''`
[Try it online!](https://tio.run/##dVZNb9w2EL3Pr8ihgKVDHaCnooBbUNKsSC9FqiLphYoeEqTOR2HEQdbIpdPf7j5qPySt04N2JYofM2/evKe/3357u3/39dOXpx@//fz8/uZ5f/Pr60JZW9RqCK2vvO@kGcwdD0ENXA@mM07ZUIqKUdVbv4ma74y1quWefW9ZKo4Rs6MajWu8H4JUNnFI3HDQnvE4GNea6J1UabPpOPVSs2UMxxHLYgrS@NRql6JWrjG16qVJ1k6XGoURzOgdm1D02F8GU@tSNhbntcXGBC3Rh5hcxKBPw04z201yssH62ppeWu@bakQyie3OD7YRzdZ6qxqD8LSptyGnxGJU5/JpOrl2GMU45ib4jjG9FxMDcKqwqZidcoVTE07VKDF67bGslNvU9bccZatcqwbvxbJyyKnDn1iz4aAqVrUWi/m1d7@njDN27JTbDL5T0SoXTZDOuwBUO4XsHCAalI3KsoviTKtjP/id5UGcBy41gtFpiB1LiL5PKJbzceOHPlXW1INXTRCAO1XJj0G8blLD4m0TemTYME4T7@yofQdEEI/fcSO9cVsTUG/Hu9p7K6i2CojPjjs1dIIgkFAwHgQpthnAQcLWoAyDr7ccO1U4GTV3eSDXlxF6hQpp1ENC7SMy1SF1XV6IM01s/M7JFFSxGVhtAXrqS6Slisg4DTNbdvUoqD1g3alY63iXJ5ii3lqz5RbcE9fmW0DNeJUGnO4aBgWOIEhU21wFhNzjkqhTC7Z3CA3FNB0XtynEjQUWubp@C4aoAFgjAgdFtI@4TbXuRnTN6BN4JKiRK6b4ETFA06yigIsDZwjBR0YNMeBVZCCMsT6zr9Am4j4X6VaCtx7ECaBaZUu0mxRFnSeM5T8//VuBVJWAeg6ZGdeNbYkRKapUVZZrCbl5MMwlWlnQ0C4G5ikE07WZizF3uAqcaVqavLa@7TUopL0gdgf@hjLGYcROmUoTn3pkj7l4G9FA7WAEPRS06UsQLq@KU4PjX6ODcGrrkV858VQK03jkI1NThsyxcmIRVtaD@mOUVqN3QWp3q8oI9MofXl8/3e@fin3521WdQXyl6mjugFpz9cvV1fO7j/dvn@rHv@73N2@WhaMlHTMNaUF5WrUy5Vql/lik6SkX7vS8pjnNRaeFKtFB8GYS0iXewIQymRZcoonamdM0851eNgetcO@YvkPiae8zN2nVzHSpp/RCECiHNVcaZ1xylS5Emo7lx1TUd7YLmmt7KC2iN3Mz0gv1pcyZ1dHY7zueQ5cCRKv@QHvQwQSyB9BlZ9HJbGihwbS2Jvo/U6OFVtMLZaQXlkcTgTN/6ULZaXavbF6Lx2xjdOjuw@/U37jo3JSA5ugolC3n5DN0KT4HXk2KSUc1UFNQs1XQulGnV7TWYDoLSF58sjA6eczBYujCqWitKpn0J/V3dGj@IyvOnwGZH7NC09p0c1@tpJ4mnZigXcs2nfx9wubsxjQpyjR/dnZaqmaG@JTUwTDPIWe3oqO8IdfFZwKdle0A3VJtDt5HK5@mg8nS8ouEFlqf2Tt/URyJfPyOoYX7v7nef3n49FRc/fn5qiR69/h5//hwf/3w@KGYlfD6/aeHp/uv88irm19fvZ8fy/L64f7zh6eP5fN/ "JavaScript (V8) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 996 bytes
```
a=0n;process.argv[2].match(require(`zlib`).unzipSync(Buffer("\"T93)OC8m{J84WLB/+>ui0kf`VU#jJp;3(nOUQ))1b/-^*.t&O'V58#/0;D$- /te\"l_)RiO<j]tu=ck_:{b,bL^?Gm'^`%I5M;I{g\\GA-\\kud?RvYIH8=nvGq|{S l-zt5?.(zt9thR%m.v=[|hJZW7^/1RYRTJ8+)_>V-k!)[c2y1Ra5];'BM+#+!n-2\\nl;libQ7NmmYjG*0$n=S;=<W)dm/(vF=Q'zuYjfx2p,OBrqGc%upq28Y65rxj`@+]P6@s^O#A9G==H*bCz3G'rNADJOFs{8k~8#8.&Y|1=soo(JS>iVRy?Gj})\"?t NCjVmoUUDo*B98e-`xYyA#X#El;vqDjJwNb8cE|~@N).v3TT{?Kk*M1zw`y:}{$\\DPj\\GVv0lgP;5satf1\"K}4G:Jc1xt]OXCu^$#u&4?NA:Od)v+!+'1=TrUBx2vfh'~HFyXZ1BzK4(Dh_-_';/A}:SxM` !3\"4qXIjrCu$]]r+$P,6_+PqH#IU9,><UJ4U#[wEb`<,f%X*dr<#2V_U\"BjiPA]En0Ls\\yt61u #m@3rm6e]NMBR_\\La.7|9^)uh/$Ef.w^7{mn;~ug\\w`3MDQPb$IR}_2A3qkc:V>rC9|xC/0g:_A'nuV<Q ugVj|`1<(]*a~.jFlp$'Mw[gDF<E]5I$tbg\\10'xvwUBeWBk8g2( XjBhu*Y(KK}Yzu}(,YY6.5TcF)u9'=M[Lb4^ /g#<P$$3*>i}.Y4]m$2e1@c\\>dAW?O`DdexO=jB$7!bJ'/|O:X,}]|qQ%zs;xVStjz[4~8?>\"m \"yR5 L+5)\\&(jZD6$<-<mb>^;j2<").map(n=>[a=a*95n+BigInt(n-32)]).map(n=>[(a>>=8n)%256n])))&&console.log('CHEAT ACTIVATED')
```
[Try it online!](https://tio.run/##RZNrl6lgAIX/ilFULlFkomJKGAa5NhpvdJFLFFK5@@tz5tv5vNfaaz37WdvWQ/1kepuDn3b3C@v3V@eyLnPw9qZ1OuG6twqnpIo7um@uUc86BhvPQrXbbmNoGB64t81heHVNVAiWS8tDoyA6KuYwqUo79xad/24LmWS8MQo22e1Sk8eQ3TowOdSVxn0MI4xMepbA/biEyBQNZbKMCKcjGd8C0d0cG2wk1lb9gDO389LdSBntWaXhIDMt1qQ6TPO@AqDBpwHYBovKIFSanzTnho3j4z6M7NI3n6rg6M0v@utBzMFDbvpYt36@32cZYqAMRi06ic3Lcnr7hk1N8koMdEplEKGThJJvbpoEwN0xf4D9967jKHYjkYVdbshw7De2cDJoWOf6yC1Q7OWFPKQkwTs2zFhwOJK0UqC8i619JNVe4eM0kyC@2OC4z4RRveUaiNflxZZUP93p7YuGaDyuPAjutN@jrWF5Iw@ulYb9xEC04ke6VVt29uOxuE8IRdpKaxflykMTqLZjwqNot85dgzZrj9dHF8PD3Gh0r3xtEx3idtaupecdBkDs2X/zyGF2t@ox1En3lwSIfj3zjVLLJC6@Kk2qwQyGgni@0uVL0gILk29JhOBG3li4kOFyjbw@69fJDyHcvvKouJ6n5wiT4Z@l4aWjRd5yIJo/Tpq2Vw1gVfWScC9VmCd7x0@oOS6myuy4lR9D03PN0NjUMjZJLDwWIuX5GEQFe9Pj1ZqbbZ8AuPoFIohAzkfOcwqW2u0IgzkAbR1/fxRnWLDOwLUlfp693x2XeQV/ws9ariP2ewbcHDznJJ87bs2SXPaqxcelmsmuSnMecQOZ7UeClWw/NIJF1YT@wu367gAjnfN0JdbZmko1Yd/4ayOyyCU8jwXrW9jSKxKNTGxhHSQU9OvrqdyCJ5pSlAJOjcw6FhQRrjNtG/lZJLOC2B4M5xLlzRNX8qoDkxbxYQJQXvDfFUkTF9ZF4mwBfn8zWkjmIZUmqaf6OPZjtxNzkYe@fZvmX3SlDKJOBESvAyrSTlIYAHHU/hELMJtmHaM8Y2ySjWJ/tzugLlee6pyeKFJuUtismq6Puukcian/Y1QvlznaxWIkVXBVDMPicXPvnvY7C9/tVyhS/azxowhfHTVlflQTEez397cpSvyw2WvX@GHtHw "JavaScript (Node.js) – Try It Online")
```
a=0n; // Init
process.argv[2] // Take Input
.match( // Check
require(`zlib`).unzipSync( // Uncompress
Buffer("...") // For each char
.map(n=>[a=a*95n+BigInt(n-32)]) // Add info to a
.map(n=>[(a>>=8n)%256n]) // and take bytes out
) // [] convert BigInt to Number
)&&console.log('CHEAT ACTIVATED') //Output
```
First time using Node for full program
[Answer]
# C (Linux GCC)
## Count: 1584
```
void f(char*s){char c[][30]={"THUGSARMOURY","PROFESSIONALSKIT","NUTTERSTOYS","INEEDSOMEHELP","TURNUPTHEHEAT","TURNDOWNTHEHEAT","PLEASANTLYWARM","TOODAMNHOT","DULLDULLDAY","STAYINANDWATCHTV","CANTSEEWHEREIMGOING","TIMEJUSTFLIESBY","SPEEDITUP","SLOWITDOWN","ROUGHNEIGHBOURHOOD","STOPPICKINGONME","SURROUNDEDBYNUTTERS","TIMETOKICKASS","OLDSPEEDDEMON","DOUGHNUTHANDICAP","NOTFORPUBLICROADS","JUSTTRYANDSTOPME","WHERESTHEFUNERAL","CELEBRITYSTATUS","TRUEGRIME","ALLCARSGOBOOM","WHEELSONLYPLEASE","STICKLIKEGLUE","GOODBYECRUELWORLD","DONTTRYANDSTOPME","ALLDRIVERSARECRIMINALS","PINKISTHENEWCOOL","SOLONGASITSBLACK","FLYINGFISH","WHOATEALLTHEPIES","BUFFMEUP","LEANANDMEAN","BLUESUEDESHOES","ATTACKOFTHEVILLAGEPEOPLE","LIFESABEACH","ONLYHOMIESALLOWED","BETTERSTAYINDOORS","NINJATOWN","LOVECONQUERSALL","EVERYONEISPOOR","EVERYONEISRICH","CHITTYCHITTYBANGBANG","CJPHONEHOME","JUMPJET","IWANTTOHOVER","TOUCHMYCARYOUDIE","SPEEDFREAK","BUBBLECARS","NIGHTPROWLER","DONTBRINGONTHENIGHT","SCOTTISHSUMMER","SANDINMYEARS","KANGAROO","NOONECANHURTME","MANFROMATLANTIS","LETSGOBASEJUMPING","ROCKETMAN","IDOASIPLEASE","BRINGITON","STINGLIKEABEE","IAMNEVERHUNGRY","STATEOFEMERGENCY","CRAZYTOWN","TAKEACHILLPILL","FULLCLIP","IWANNADRIVEBY","GHOSTTOWN","HICKSVILLE","WANNABEINMYGANG","NOONECANSTOPUS","ROCKETMAYHEM","WORSHIPME","HELLOLADIES","ICANGOALLNIGHT","PROFESSIONALKILLER","NATURALTALENT","OHDUDE","FOURWHEELFUN","HITTHEROADJACK","ITSALLBULL","FLYINGTOSTUNT","MONSTERMASH"};for(int i=0,j=0,k=0;i<87;i++){j=strlen(c[i]);k=strlen(s);if(k<j||strncmp(s+(k-j),c[i],j))continue;printf("CHEAT ACTIVATED\n");}}
```
## Count w/out cheats themselves: 143
```
void f(char*s){for(int i=0,j=0,k=0;i<87;i++){j=strlen(c[i]);k=strlen(s);if(k<j||strncmp(s+(k-j),c[i],j))continue;printf("CHEAT ACTIVATED\n");}}
```
So if I wanted to improve mine, I'd need to find a better way to represent that data
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 823 bytes
```
`Ö„t aå¡ê*`pUè`(kÂ
žo|â‘(adjack|(g—¡|cŸzy|nˆja)Èu|fÒàg(‘Ð|t|f‰h)|Ü…hnÔAÌap|Ü‹(ç°GÊght|â2Øop´)|ÂlckÆøevÅNgepeop¤|¦fƒa¼a®|i(°n(nÃqveby|t‘—v€)|amšv€Ë¡ry|ÖÁoa¥night|tÑ¡ÞÑ|ã””lp)|æˆrQtÓƒ‰|n(å
…ys|otfŽèFŠÞads|Çʯn(ˆ´|¡op«)|Âxत|ightpžw¤r)|ʵsvÅH|àP‰(Îr|poŽ)|è wal(kÅHr|skŠ)|s(Ö-‰hsum´r|å€dbynÔjrs|áʉkts½ack|pe‚(fœak|Ä¿)|t(…ee´rgcy|Ãà„d°t®tv|Åikeglue|Äikea¼e|áⶨg´)|Óqtܵ|ÂnÛŒrs)|Î…hšighÞ€—od|goodbyecruelwŽld|b(ub½eÖÜ|Áªã §€ÇÔ|ãˆ
E|luàÂoƒ|uff´up)|jÔÍ々p´|fŒr؇Óô|c(jpÊÊÊà|Ê•yÖ’tyßAßA|e¤ßŠyÐa«|„t eØ€e‹goˆg)|è0b$ew¬ol|t(ruegÎX|‹e(j«tf¦ƒby|‘kick†s)|oo»mn—t|aê‚ZUpi¥|˯‡Ú€y|Æ2myÖÝŒ¹e|¨n(ܵ|up)eÊ!)|ž×Fµ(n|y”m)|Ò „dÚ |§Êãà!»d|fªlc¦p|è "ç°rm|ÚŽ’rÚR|jumpjet|oldspe‚¸¶n|w(Æ¢ip´|„na¼ˆmyg„g|—ÂT¥epiƒ|†fÕal)|love¬nquÀ&¥|ohdu¸|Ê)oÓ©ƒ|(iº†i|؇ls§)pÒ"e|a¥(ÖÜgoÞ¼|d㎀›e×ˈals)|ç9
é»y|¤tsgoßPjuÛpg)$`u¹u
```
[Try it online!](https://tio.run/##HZPLTxtXFMbVt5JWNFVXUTcOiqpxpUpVdl26ooRN2xSClGbFYF8Ptsczwzygrs7Cb4wBFxsHR0CNDTY4kAcLiEhJVOk7fxg9E9mLmTvn3vN9v@/ctO7419dzvI2yH9F5iD6ffDfnzPJoTstw8XN0beIDNLUP9URaj2dIM9BBn@LY/ytHFmppPcq1gJLc4p6hocmb5FMSqwtR4j1UFixux3h9THfC1zWNj3GGwn2uf2ks@HLyPX76le3gXKqLZjzDVb5US1z51VCOkvUB4SiJko63Ol5SSsOZpVlcWlxS8zny0URnCfko6VnsyAOvoe/miLe5YOsYWqmwh89NMdXlJvHh12hjE23TkXZHqLm/@7yFElbJ0nh4Uz5Vch7ZfhINHk2izl094RGvcB2vpGINVZwT@qLrNNT7J/cwwOAzCvs46C5j4Mp6HReeWJgi7j345FOsatxwybHRkG@jG7eXsaGbwrYy5ZKXQT1Knsbb3wsxL8ji3CUefnwL@cR8TtClXenflyNXM76Hd2EAjkJRS2JPzxCX8V@UfA0Vhb@V7DVQiIv/kggrJ3Dm46W/RFzBi1RGGWagZMeYPApOFR57gNcYGdh4j39r0ZeELsTXBxbvYt31ZLEhCWJH/HEXeXTsBBm2LdJU3A2UuYyGmaB5LZjHOyXU94gLOOHDCI4ljBVuC3LUbv5MZsC9b7g4ZqNEQTKJ80ASSHObN6TghZxckRGQqVl3@SlWeIvPKa6lHa6///VCpk9yMqMtP8f7MfmTwoD3Uc/xpo5TCodXyda8wppho2aEqH@Yv4uCWsZz2xRGotfgxiPCmtLSOJWMj1CSIUIzk4pnUBW3to2rrIWOTzqfoPh41klhSBL7K9G0g7yQrd7Lig7@B@t4owgjmYqQmdjBpuL6nSihy51JXGgW5dDOio5WRLLgnQgJ52Nxcygo7uAqIXZPzDiO5GKMIuNcEmZnbpakUQMtl3emKR1knbTyyTYTXpg6LvHaomWNqzhIhcBQtiRK1LI5A2WD0OHiQwxFiQgvhdc2/1EkyU9u6WaUTHtJ4bm1GHD@W3FlLyQCXArYqC1X4JmUayn8i2qKwgRMLxQbdbg1rkhukhaGa9gyBG8pIZE1JLJdxR1hU9PNcFCOf/yCn@FKeA58Tyr3H6QD3nWM6N25AG@C6@vx2E@xxxOxR7GZicmZ2MTDqdn7M7HpX36bnf5j/H8 "Japt – Try It Online")
## Explanation
```
`...`pUè`...`u¹u
`...` u // Compressed version of "CHEAT ACTIVATED"
p // Repeat the string
Uè // Number of matches of the regex on the input
`...`u // Compressed version of regex from the python solution
```
The [regex](https://tio.run/##LZPHlqIIAADv@xVrJIgRREAxgSIoqQUDiE0UURBEOMz@fO/M271WHetV9qu4py/05ydKsjQv/v4njlzEdT4Bjv2V5dGrAP@Qjh94aZLlwecD/ic7DjH8A/0ABACAc95bhERoTW@y16qTCr3abet6AD2iUdhg5vtH7pLtl4xwWPSYhqWMI3Aq7SKzeJvGR9ZS5GRw49T43LuhWkBflD4Li/AzULP9sMnECCMiHrZs2JPj0FiVEr1367cKkih2Y66pVJMNQepNwC0JOs/U2pp8isDWaDYu/OBo10aprGf9do8LUOv9nRLhPD7eYs6GVTGHSdO0o5lj0zrllOy6QdA4LrKOpOuRwhNCLZZ7l3gOr6iGsocOzMZnp13JpuO@XcD3w2JylaWWf9cLqWuh@uVSlJlRPNk6xSrre3tzRBWjvlhEq3UChuPJWcB5rFqKvnrq48JS6h479lRd57KEy8h12RBiVHxN/Csvu4sJXTfdcWi3KbnOObO6d6/s87sqJWN7F/g4Pya6Bybgc2fcb54aLtSErctpibVC1F4/Na128xqbLwKGQvJ3pjpJMto4PTjZZ3J@XaKkuxTK5gJvy8QOrW2cXoZbylYZOCME0XBzOwVyNWL6X4je/96mXaq9Wtxybz@Knvjmtp0OKE9MCyt/Ls@1CulXy4dPT/zX3BI08k4nTMwXnfNuBrtVkE8WcGXVBS9c6sLhnf30faEzlqsWo3BaWqGHIU0Gg5bnnDQM7SQlBaeE7USVbershCGAiM2teSB8YCbQ/H7FzTjdEN3jSTAjxg8QsTRBhHydiUZ7hD64TDHWx@VpL2tcOKT0iTKodukDGJqKIaQ@1/KM0gmvOKatOtMIi6rLL5agkxIRQmfIZ2DPQLE08oyqD7jRfLB8B10WP8MQ47VrhTuqrDAVsBKjtx6IVvOdZw/rvXuHPXEXv74xdaQuTHIy56@oLCwEKOvPWlJmbKDX@ZyBHQEAYDIR9HBG3jtWOhoY21CCyN5x2vvwAci/XX/JfG6PiegMpd9DQVDn/7sg6OfnXw) is from this [python solution](https://codegolf.stackexchange.com/a/205275/91267)
[Answer]
# JavaScript, no compression, ~~1356~~ 1351 bytes
`a=T=>~"THUGSARMOURY,PROFESSIONALSKIT,NUTTERSTOYS,INEEDSOMEHELP,TURNUPTHEHEAT,TURNDOWNTHEHEAT,PLEASANTLYWARM,TOODAMNHOT,DULLDULLDAY,STAYINANDWATCHTV,CANTSEEWHEREIMGOING,TIMEJUSTFLIESBY,SPEEDITUP,SLOWITDOWN,ROUGHNEIGHBOURHOOD,STOPPICKINGONME,SURROUNDEDBYNUTTERS,TIMETOKICKASS,OLDSPEEDDEMON,DOUGHNUTHANDICAP,NOTFORPUBLICROADS,JUSTTRYANDSTOPME,WHERESTHEFUNERAL,CELEBRITYSTATUS,TRUEGRIME,ALLCARSGOBOOM,WHEELSONLYPLEASE,STICKLIKEGLUE,GOODBYECRUELWORLD,DONTTRYANDSTOPME,ALLDRIVERSARECRIMINALS,PINKISTHENEWCOOL,SOLONGASITSBLACK,FLYINGFISH,WHOATEALLTHEPIES,BUFFMEUP,LEANANDMEAN,BLUESUEDESHOES,ATTACKOFTHEVILLAGEPEOPLE,LIFESABEACH,ONLYHOMIESALLOWED,BETTERSTAYINDOORS,NINJATOWN,LOVECONQUERSALL,EVERYONEISPOOR,EVERYONEISRICH,CHITTYCHITTYBANGBANG,CJPHONEHOME,JUMPJET,IWANTTOHOVER,TOUCHMYCARYOUDIE,SPEEDFREAK,BUBBLECARS,NIGHTPROWLER,DONTBRINGONTHENIGHT,SCOTTISHSUMMER,SANDINMYEARS,KANGAROO,NOONECANHURTME,MANFROMATLANTIS,LETSGOBASEJUMPING,ROCKETMAN,IDOASIPLEASE,BRINGITON,STINGLIKEABEE,IAMNEVERHUNGRY,STATEOFEMERGENCY,CRAZYTOWN,TAKEACHILLPILL,FULLCLIP,IWANNADRIVEBY,GHOSTTOWN,HICKSVILLE,WANNABEINMYGANG,NOONECANSTOPUS,ROCKETMAYHEM,WORSHIPME,HELLOLADIES,ICANGOALLNIGHT,PROFESSIONALKILLER,NATURALTALENT,OHDUDE,FOURWHEELFUN,HITTHEROADJACK,ITSALLBULL,FLYINGTOSTUNT,MONSTERMASH".split`,`.findIndex(E=>0<=T.indexOf(E)&T.indexOf(E)>=T.length-E.length)?"CHEAT ACTIVATED":""`
Attempted using `min<var<max` in the array callback, but that resulted fale positives.
Pretty straightforward otherwise; I preferred not to use compression; can't be shorter that way.
---
5 bytes spared by @KevinCruijssen and my reading to JS golfing.
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 1322 bytes
```
a(X)->lists:any(fun(I)->lists:suffix(I,X)end,string:split("THUGSARMOURY
PROFESSIONALSKIT
NUTTERSTOYS
INEEDSOMEHELP
TURNUPTHEHEAT
TURNDOWNTHEHEAT
PLEASANTLYWARM
TOODAMNHOT
DULLDULLDAY
STAYINANDWATCHTV
CANTSEEWHEREIMGOING
TIMEJUSTFLIESBY
SPEEDITUP
SLOWITDOWN
ROUGHNEIGHBOURHOOD
STOPPICKINGONME
SURROUNDEDBYNUTTERS
TIMETOKICKASS
OLDSPEEDDEMON
DOUGHNUTHANDICAP
NOTFORPUBLICROADS
JUSTTRYANDSTOPME
WHERESTHEFUNERAL
CELEBRITYSTATUS
TRUEGRIME
ALLCARSGOBOOM
WHEELSONLYPLEASE
STICKLIKEGLUE
GOODBYECRUELWORLD
DONTTRYANDSTOPME
ALLDRIVERSARECRIMINALS
PINKISTHENEWCOOL
SOLONGASITSBLACK
FLYINGFISH
WHOATEALLTHEPIES
BUFFMEUP
LEANANDMEAN
BLUESUEDESHOES
ATTACKOFTHEVILLAGEPEOPLE
LIFESABEACH
ONLYHOMIESALLOWED
BETTERSTAYINDOORS
NINJATOWN
LOVECONQUERSALL
EVERYONEISPOOR
EVERYONEISRICH
CHITTYCHITTYBANGBANG
CJPHONEHOME
JUMPJET
IWANTTOHOVER
TOUCHMYCARYOUDIE
SPEEDFREAK
BUBBLECARS
NIGHTPROWLER
DONTBRINGONTHENIGHT
SCOTTISHSUMMER
SANDINMYEARS
KANGAROO
NOONECANHURTME
MANFROMATLANTIS
LETSGOBASEJUMPING
ROCKETMAN
IDOASIPLEASE
BRINGITON
STINGLIKEABEE
IAMNEVERHUNGRY
STATEOFEMERGENCY
CRAZYTOWN
TAKEACHILLPILL
FULLCLIP
IWANNADRIVEBY
GHOSTTOWN
HICKSVILLE
WANNABEINMYGANG
NOONECANSTOPUS
ROCKETMAYHEM
WORSHIPME
HELLOLADIES
ICANGOALLNIGHT
PROFESSIONALKILLER
NATURALTALENT
OHDUDE
FOURWHEELFUN
HITTHEROADJACK
ITSALLBULL
FLYINGTOSTUNT
MONSTERMASH","
",all)).
```
[Try it online!](https://tio.run/##VVTbbhs3EH2frwj0JAF2P8APAbjL2SW1JGdLDq1siz4IrR0IUNXAUtD2693DdRykAlYCpeHMmXPR08v5ePl8/3T9/eX05fZKr8ftp939x/Ppers@HC//bp@/Xrb@@zfXr8/Pp3@2/u7T7unyx9319nK6fH64fjmfbtuNujoWk6PUvNCcZeBSvCQTyuSVUlXlXFSWQj4x2yKRHYeZtOZUZ3U4GV1PVg7p/TwHNsUkDcsBvUlFrInJiZKtIayPWaioWXwyyR6M9k4fqceVwnxwnNnHUXwaSX3kfS06BM@lw6UZMLzWmUqQg9c2lrLU0SX2o@uwiMM4NJd59v2EHpIiU6kZVcmy7ZZva629VSZUmVJIgl2bW46SyK4tqzrg872ZKYkOkufaBd9nMbZQg6V5QUEbhhkr8AIShpo4m0A9B@6y1wWrasXAXHnMmEomhN7kMkonEttFDkVSWFbmgFYBKviJx1CZRizULdzjdjhIDhbo0v9Ho5/N/hFbmYxCH33TkGafJt8QJT70IoGKBEmjKV5LF0w/0RCgwTj44oBCjDI6oX4G29TVYYgMqgGq6RTxQR0QlcqWixPUGFW0kQF3Hn0IZuSZBVtQ8PCS6dj0jtpmTiJ6orsc2FLHb85qDrAiECP5tDfa1AzyyL2kn2vbJgRirLUI5C0zKn84Zo/evfOqy9t7Z9LYHur3s0MJZjJkivOelfwB9lJx6J5hydq7uECDRar1/OarIbOZsHbXBW7yANToFLE4BNxppEPNZqjGaPuJSi@qIK/UGFFSmltSXLhdnoDEZBFYB1hgblezAlA0acgSjQYA8gXsajMCdG9Qm@mz9BMr6shbgVjfXLEO9wp3wh9pbP4AwUwe4WqsuJrGvOZKGUkGoJFTv1CfzS/LSq2aqQkCoWY8NCCJffDzyk0yq4OQsdEJnN3qHWxYmq4wd6vouG03Norfl2oGhLXfIS@O4WcI6nzzJf4sggRjm50QI3AHRd@o@/HfZmojMiWkBLlREzgpibPVMg2I9BoQpIqazEgZ8rdv7oWN0a@rbZfVyArkFXcR4QKDRVPc5m5Dm7vj@bzb/fT65/F02f762@7D/Uf6gNfpr4e/X063p@1xuzHf99600v8A "Erlang (escript) – Try It Online")
] |
[Question]
[
Write a program or a function that accepts the list of outputs from a logic function and outputs the LaTeX code for its truth table.
The inputs should be labeled as lowercase letters `a-z`, and the output should be labelled as `F`. The length of list of inputs will always be shorter than `2^25`, which means that number of inputs will always be less than 25, so you can use letters from lowercase alphabet for input names.
## Input
A number `n` of inputs and list of length `2^n` of binary numbers which represents the outputs of a logical function.
## Output
LaTeX code that produces the truth table for that function. Input and output values should be centered in rows.
There must be a line between table header and its values and between inputs and output, so the code should be similar to that below.
```
\begin{tabular}{c * <NUMBER OF INPUTS>|c}
<INPUTS>&F\\
\hline
<INPUT VECTOR i>&<OUTPUT>\\
\end{tabular}
```
## Example
Input:
```
2
[0, 0, 0, 1]
```
Output:
```
\begin{tabular}{cc|c}
a & b & F \\
\hline
0 & 0 & 0 \\
0 & 1 & 0 \\
1 & 0 & 0 \\
1 & 1 & 1 \\
\end{tabular}
```
Which when displayed in LaTeX shows the following truth table
[](https://i.stack.imgur.com/8UwyT.png)
## General rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes
```
≔tabularζ\ζ{*θc|c}⸿⪫✂β⁰Iθ¹&⁰&F\\⸿\hline⸿Eη⁺⪫⁺⮌EIθI﹪÷κX²λ²⟦ι⟧&¦\\⁰\endζ
```
[Try it online!](https://tio.run/##bVBNC8IwDL37K0oPo5MK3a6eRBEUBkOP1kPtiiuWVtttgh@/vXZTNgUDCclL8vIIL5nlhinvZ87Jo0awYodaMQsxuMXTUW6lrhCkFPbFF3wfD/BlgPmDP6kdWmsjNdoqyQU6YEAwmDPXLmCQBIcRjPtRMrBES9qapaWSWnzzZeyMSgxyVbs3d5dtRCOsE123P9AlmSlqZdBKVwvZyEKgU1g2V2FRioGKw1gat3En9x89Iba3g7B/yigVuvh5iPfpiBCS@EmjXg "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔tabularζ
```
Save this string in a variable to avoid duplication.
```
\ζ{*θc|c}⸿
```
Print the initial `\tabular{*2c|c}` line (2 or whatever value the first input `q` has).
```
⪫✂β⁰Iθ¹&⁰&F\\⸿\hline⸿
```
Get the first `q` letters from the predefined variable `b` and insert `&`s between them, then append the `&F\\` and also print `\hline` on the next line.
```
Eη⁺⪫⁺⮌EIθI﹪÷κX²λ²⟦ι⟧&¦\\
```
Loop over the characters in the second input. For each one, its index is converted to binary with length `q`, the character is concatenated, the result is joined with `&`s and `\\` is appended. The resulting strings are implicitly printed on separate lines.
```
⁰\endζ
```
Print the `\endtabular`. (The `⁰` is just a separator as the deverbosifier forgots to insert a `¦`.)
[Answer]
# [Python 2](https://docs.python.org/2/), 153 bytes
```
lambda n,l:r'\tabular{*%dc|c}%s&F\\\hline%s\endtabular'%(n,q(map(chr,range(97,97+n))),r'\\'.join(q(bin(2**n+i)[3:]+x)for i,x in enumerate(l)))
q='&'.join
```
[Try it online!](https://tio.run/##TYw7DoMwGIN3TpEFkkBU8RgQSKy9BGEIEEqq8AMBJKq2Z6dIhaqD7eGzPTzmtodwazK@adGVtUDAdGown0W5aGGerl1Xr@ptT86Vc95qBdKeuIT6KGCbABtJJwZStYYZATdJkpglsQeUUrZfcXy59wrISMrdQ9cFT9E8SgtvpU1vkGIrUoAkLJ00YpZE70NrzLDzHW6DUTCjhoQM5djH7KcAF9Q6aXTS4JD/l2d7@wA "Python 2 – Try It Online")
Outputs like
```
\tabular{*2c|c}a&b&F\\\hline0&0&0\\0&1&0\\1&0&0\\1&1&1\endtabular
```
`\tabular` and `\endtabular` are used as shorter `\begin{tabular}` and `\end{tabular}`, as per [this LaTeX golf tip](https://codegolf.stackexchange.com/a/124042/20260). The `*2c` is a shorthand to define 2 columns.
[Answer]
## Haskell, ~~164~~ 155 bytes
```
s%f=((:"&")=<<s)++f:"\\\\"
n#r=unlines$("\\tabular{"++('c'<$[1..n])++"|c}"):take n['a'..]%'F':"\\hline":zipWith(%)(mapM id$"01"<$[1..n])r++["\\endtabular"]
```
[Try it online!](https://tio.run/##PY07D4MgGEX3/gryiQVDQiTdiKzdOnXoYB2oj0hEYhCXPn47xaTpHW/uOXfU69RbG@OaD4pSCUcoVFWtBWODhHsKHFzm1eascf2KaeqCfmxW@xcwRklLKlwLzl2TEHi3Hyhk0FOPXE004bzJyZnspnEXgHya5WbCSPOCznq5INNhKAX8JZ6xOq171/1uoImzNg4ptGzhGjzC6IQyBGVZCiESGr8 "Haskell – Try It Online")
```
unlines -- take a list of strings and join it with NL.
-- the strings are:
"\\tabular{"++('c'<$[1..n])++"|c}" -- tabular definition with n times 'c'
take n['a'..]%'F' -- table header
"\\hline" -- hline
zipWith(%)(mapM id$"01"<$[1..n])r -- table content
["\\endtabular"] -- end of tabular definition
Table header and content are built via function '%'
s%f= -- take a string 's' and a char 'f'
((:"&")=<<s) -- append a "&" to each char in 's'
++f:"\\\\" -- and append 'f' and two backslashes
Table header:
take n['a'..] % 'F' -- s: the first n letters from the alphabet
-- f: char 'F'
Table content:
zipWith(%) -- apply '%' pairwise to
mapM id$"01"<$[1..n] -- all combinations of '0' and '1' of length n
r -- and the string 'r'
```
Edit: using `\tabular` instead of `\begin{tabular}` (stolen from [@xnor's answer](https://codegolf.stackexchange.com/a/146906/34531)).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~192~~ ~~168~~ 166 bytes
```
lambda n,l:r'\begin{tabular}{*%dc|c}%s\end{tabular}'%(n,r'\\'.join(map('&'.join,[map(chr,range(97,97+n))+[r'F\\\hline']]+[bin(2**n+i)[3:]+l[n]for i in range(2**n)])))
```
[Try it online!](https://tio.run/##PYuxDoMgGIRfhcUCQhqrg9Gka18CGEBRafDXUDs01menGpMON3x3982fZZggj91dRq9H02oE3NcBS2N7B@uizdvrsK1p0jbfZkte0kL7r3FCgO9nia/PyQEZ9Uzw5QQuDmqGwIOG3pKq5FXJgFImAn5IKQfvwGKlmDC7mqcpMEdFUSvmBahuCsghB@i0j5kqSmmcg4MFdaTgOMuy2xFM4w8 "Python 2 – Try It Online")
Pretty printed version:
# [Python 2](https://docs.python.org/2/), ~~234~~ ~~229~~ ~~218~~ ~~209~~ ~~205~~ 203 bytes
```
n,l=input()
print'\\begin{tabular}{'+'c'*n+'|c}\n'+' & '.join(chr(i+97)for i in range(n)+[-27]),'\\\\\n\hline'
i=0
for r in l:print' & '.join(bin(i)[2:].rjust(n,'0')+`r`),r'\\';i+=1
print'\\end{tabular}'
```
[Try it online!](https://tio.run/##RY7dCoJAEIXvfYq9anbbTdQupMInUcGfLCdklGm9CPPZbaWwOQzDwOE7Z3jZtqdoWch0CdIwWqm8gZEsZFnV3JEmW1ZjV/I8gYYa9qThXc8ZuU/sBPiPHknWLUvUp1jdehYokASXdG8kKZ0eojhXxuHcUNZ2SA14mATe6uXV252/iX9e5RZVGp1znx/j00oyEIDSBRfKsGPBBXUSbk0bum49YVmOJg3MqtD8bv4B "Python 2 – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 142 bytes
```
n=>x=>"\\tabular*#{n}c|c#{j(map(chr,97..97+n))}&F\\\\\hline"+'\\\\'.join(j(bin(i)[2to].zfill(n)+x[i])for i:0..len(x))+"\\endtabular"j="&".join
```
[Try it online!](https://tio.run/##LY1BCoMwFESvUiLo/40E2y7EQlz2EupCrWIk/ZGQgtR6dhvbzsCbWc1M1jhDWy83kvksc1aWrm6eurbHYKG1fbfBMsKjnqAdbJylQmQpJ8Q1vJW7Bq2oYzzaeyRGowhGaDwVFmdnKvHqldZAyOdCVdgbe1DXRAjdEcyI3P91dP9fslGykH1XtskqctDDBaFI4pP3jz4rxO0D "Proton – Try It Online")
Output is in golfed LaTeX form; thanks to xnor for that trick!
~~This should be able to be golfed to shorter than xnor's Python answer because Proton should in theory never lose to Python lol (in practice I'm bad xD). I may steal some tricks from xnor ;P~~
Managed to now be shorter by making some things into variables, which I just noticed xnor also did :P
And there we go, -6 bytes by using some Proton golfing tricks.
[Answer]
# [R](https://www.r-project.org/), ~~196 187~~ 171 bytes
```
function(m,n){cat("\\tabular{*",n,"c|c}")
write(c(letters[1:n],"F\\\\\\hline",rbind(t(rev(expand.grid(rep(list(0:1),n)))),paste0(m,"\\\\")),"\\endtabular"),1,n+1,sep="&")}
```
[Try it online!](https://tio.run/##NY2xDsIwDER3PsMDcsBCjdgqdeUnKEOauhCpmCh1Aan020tAcMPp7oZ7aemqpRvFa7gJXknM5J0i1LW6ZuxdmjZAQuBffgazeqSgjB57VuU0HG0pJ4JD/dWlD8JAqQnSomLiO/IzOml35xTa3CP2YVAsSmsyKIuiG5SLzIXPAeQlB5b2BwdDlmRraeBYwRrMvHSZXlCRd/t3Q3uzvAE "R – Try It Online")
Output similar to [the Charcoal answer](https://codegolf.stackexchange.com/a/146900/80010). `expand.grid` from [this answer](https://codegolf.stackexchange.com/a/164409/80010).
For the record, using `xtable` from the eponym package is not ~~much~~ shorter since one has to specify a lot of options to match the spec, in addition to including the package:
### [R](https://www.r-project.org/), 187 bytes
```
function(m,n){u=rbind(apply(expand.grid(rep(list(0:1),n)),1,rev),m)
rownames(u)=c(letters[1:n],"F")
print(xtable(t(u),dig=0,align=c(rep("c",n+1),"|c}")),hl=0,include.r=F)}
library(xtable)
```
[Try it online!](https://tio.run/##Nc49DsIwDIbhvcfIZAsLtWJDysolEEOapMVSaiI35UfA2UuQYPH0@tGn62DXYRFf@CIwkeBzsdqzBHA5pwfEe3YStqNyAI0ZEs8F2n2HNUXqSOMVacJGLzdxU5xhQeshxVKizsduLycyB4NNVpYC9@L6FKHUigKPtiWXeJT68bWNNySbSpuXf5vKn1MtWHxaQtyqPeC7Sdyr08dPwnUADy21dUn3v0g7XD8 "R – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Roman numeral converter function](/questions/797/roman-numeral-converter-function)
(4 answers)
Closed 10 years ago.
The usual rules: no external resources, or the like. Input will be a positive integer in valid Roman numeral format less than 10 thousand, say.
Use all the Roman numeral characters:
* I = 1
* V = 5
* X = 10
* L = 50
* C = 100
* D = 500
* M = 1,000
Respect subtractive notation (copied from [the Wikipedia page](http://en.wikipedia.org/wiki/Roman_numerals)):
* the numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
* X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
* C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern[5]
[Answer]
# Mathematica, 33 chars
```
FromDigits[InputString[],"Roman"]
```
[Answer]
**JavaScript, ~~98~~ 91 characters**:
```
for(k=d=l=0,a=prompt();i={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}[a[k++]];l=i)d+=i>l?i-2*l:i;d
```
Expanded form:
```
a = prompt(), // a is input string
d = 0, // d is result sum
l = 0, // l is last value processed (for comparison with current val)
k = 0, // k is current position in string
v = {I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}; // map of values
// for each char in string a[k] (left to right), put its base-10 value in i
while(i = v[a[k++]]) {
// if previous left-side value is lower than this value,
// it should have been substracted, so subject twice its value
// (once to negate the past addition, and again to apply negative value)
// regardless, add this value
if(i>l) {
d += i - 2*l;
} else {
d += i;
}
// store this value as previous value
l=i;
}
// yield result
d;
```
[Answer]
**Scala 195**
```
val t=Map('I'->1,'V'->5,'X'->10,'L'->50,'C'->100,'D'->500,'M'->1000)
def f(n:String)={val r=n.substring(1).foldLeft((0,t(n.head)))((a,x)=>(if(a._2>=t(x))a._1+a._2 else a._1-a._2,t(x)));r._1+r._2}
```
[Answer]
## GolfScript: 83
```
0\{[77 68 67 76 88 86 73]?[1000 500 100 50 10 5 1]=}%{)@.@.@<{~)}{}if@.}do;{+\.}do;
```
[Answer]
# MS Excel,12
Enter a value in A1, then enter this in A2
```
=ARABIC(A1)
```
[Answer]
**Python 201 characters**
```
m={'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900,'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
f=lambda s:m[s] if s in m else(m[s[:2]]+f(s[2:])if s[:2]in m else m[s[0]]+f(s[1:]))
f(raw_input())
```
Example:
```
>>> m={'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900,'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000};f=lambda s:m[s] if s in m else(m[s[:2]]+f(s[2:])if s[:2]in m else m[s[0]]+f(s[1:]));f(raw_input())
MMMCMLXXXVII
3987
```
**~~119~~ 117 characters**
```
>>> X=[dict(zip('MDCLXVI',(1e3,500,100,50,10,5,1)))[x]for x in raw_input()];sum((x,-x)[x<y]for x,y in zip(X,X[1:]))+X[-1]
MMMCMLXXXVII
3987.0
```
Expanded form:
```
>>> # Maps roman numbers to their decimal counterpart
>>> roman_map = dict(zip('MDCLXVI',(1e3,500,100,50,10,5,1)))
>>> # Maps the list of input number to the corresponding decimals
>>> X=[roman_map[x]for x in raw_input()]
>>> # A number will be added (x) or subtracted (-x) depending on its value vs the next number
>>> # For instance CM -> [100, 1000], 100 < 1000, therefore -100, +1000
>>> result = sum((x,-x)[x<y] for x,y in zip(X,X[1:])) # True = 1, False = 0
>>> # Adding the last element (which is always added)
>>> result += X[-1]
```
[Answer]
## JavaScript, 198 characters
```
n={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3,IV:4,IX:9,XL:40,XC:90,CD:400,CM:900},s=prompt(),a=i=0;for(;i<s.length;i++){b=(j)=>s.substr(j,1);c=b(i);d=b(i+1);e=n[c+d];if(e){a+=e;i++}else{a+=n[c]}}alert(a);
```
The ungolfed code:
```
n = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1e3,
IV: 4,
IX: 9,
XL: 40,
XC: 90,
CD: 400,
CM: 900
}, s = prompt(), a = i = 0;
for (; i < s.length; i++) {
b = (j) => s.substr(j, 1);
c = b(i);
d = b(i + 1);
e = n[c + d];
if (e) {
a += e;
i++
} else {
a += n[c]
}
}
alert(a);
```
How this works: first, you store all values inside an object. Then, you prompt for input and you loop over all characters in the string. If the current character + the next character are a number (`CM` for example), then look up `current char + next char` in the object. If `current char + next char` isn't available in the object, just look up the current char.
Demo: <http://jsfiddle.net/vSLfM/>
[Answer]
## Ruby, 134
```
i=gets
%w[IV,4 IX,9 XL,40 XC,90 CD,400 CM,900 I,1 V,5 X,10 L,50
C,100 D,500 M,1000].map{|s|k,v=s.split ?,;i.gsub!(k,?++v)}
puts eval i
```
] |
[Question]
[
Inspired by [Random with your hands tied](https://codegolf.stackexchange.com/questions/6832/random-with-your-hands-tied):
---
## The Goal
The goal of this challenge is to write a program that generates a pseudorandom bit stream, which is a string of 1s and 0s that appears to be purely random, but is actually generated in a deterministic way. Your program should output a string of 1 and 0s (with optional whitespace) and should pass the following requirements:
1. Given unlimited time and memory, your program must continue to output a string of 1s and 0s forever
2. Your program must output more than 1000 random bits in about one minute, on a reasonable machine. If this requirement is impossible, then I will lessen it.
3. The string of bits can repeat, but the length of the repeating section must be more than 1000 bits.
4. The string of bits must pass as many of the randomness tests (described below) as possible.
5. The program must not take any input from any external sources or use any built-in rand()-like function.
6. Because of the above requirement, the program must output the same exact string of bits each time that it is run.
---
## Randomness Test #1
The string of pseudorandom bits must not include any obvious pattern upon visual inspection.
## Randomness Test #2 (subject to change based on comments)
The string of bits must contain an equal distribution of 1s and 0s. To test this (and other things too), the stream of bits is broken into segments that are 3 bits long, such as `101|111|001`.
Out of all of these segments, 1/8 of them should have three 1s and no 0s, 3/8 of them should have two 1s and one 0, 3/8 of them should have one 1 and two 0s, and 1/8 of them should have no 1s and three 0s.
## Randomness Test #3
A "run" is defined as a consecutive series of bits that all have the same value. The string `1001001110` has three runs of size 1 (`1..1.....0`), two runs of size 2 (`.00.00....`) and one run of size 3 (`......111.`). Notice that runs do not overlap.
Out of a string of 1000 random bits, there should be about 250 runs of size 1, 125 runs of size 2, 62 runs of size 3, etc. In general, for run size R, there should be about `1000/(2**(R+1))` runs of that size.
## Randomness Test #4
The first 840 bits are split into two halves of 420 bits each. Each bit on the first half is compared to the corresponding bit on the second half. The two bits should match about fifty percent of the time.
---
[Here](http://pastebin.com/8E97YRqf) is the source code of a Perl program that performs tests 2 through 4. As of now, it requires that the string of bits not contain any whitespace.
---
## Objective Winning Criterion Time!
The winner is the program that passes all of the 6 requirements and all of the randomness tests to the degree that it is indistinguishable from randomness. If multiple programs accomplish this, then the one that takes the longest amount of time to repeat will win. If multiple programs accomplish this, then I might have to find more randomness tests to act as tie-breakers.
[Answer]
# Mathematica 78 53 chars
The digits of the binary representation of Pi seem to behave as if they are chaotically produced although this is unproven.
The following simple routine deterministically returns as a string the binary digits of pi, corresponding to `d` decimal digits:
```
f[d_]:=ToString@FromDigits@RealDigits[N[Pi,d],2][[1]]
```
**Usage**
If we request the counterpart of 301 decimal digits of Pi, we receive 1000 binary digits.
```
f[301]
StringLength[%]
(* out *)
1100100100001111110110101010001000100001011010001100001000110100110001001100011001100010100010111000000011011100000111001101000100101001000000100100111000001000100010100110011111001100011101000000001000001011101111101010011000111011000100111001101100100010010100010100101000001000011110011000111000110100000001001101110111101111100101010001100110110011110011010011101001000011000110110011000000101011000010100110110111110010010111110001010000110111010011111110000100110101011011010110110101010001110000100100010111100100100001011011010101110110011000100101111001111110110001101111010001001100010000101110100110100110001101111110110101101011000010111111111101011100101101101111010000000110101101111110110111101110001110000110101111111011010110101000100110011111101001011010111010011111001001000001000101111100010010110001111111100110010010010010100001100110010100011110110011100100010110110011110111000010000000000111110010111000101000010110001110111111000001011001100011011010010010000011011000011100011
1000 (* characters *)
```
Because Pi is an irrational number, there is no period. However, there will be practical constraints due to the hardware one is running.
**Test 1**
Looks good to me.
**Test 2**
```
d=301;
Partition[RealDigits[N[Pi,d],2][[1]],{3}];
Tally[%]
(* out *)
{{{1,1,0},35},{{0,1,0},45},{{0,0,0},41},{{1,1,1},40},
{{0,1,1},50},{{1,0,1},32},{{1,0,0},43},{{0,0,1},47}}
```
More thorough check:
```
d=10^6;
Partition[RealDigits[N[Pi,d],2][[1]],{3}];
Tally[%]
{{{1,1,0},138565},{{0,1,0},138146},{{0,0,0},138260},{{1,1,1},138427},
{{0,1,1},139119}, {{1,0,1},138404},{{1,0,0},137926},{{0,0,1},138462}}
```
**Test 3: Runs**
```
d=10^6;
res3=SortBy[Tally@Split@RealDigits[N[Pi,d],2][[1]],Last]/.{a_,b_}:> {Length[a],b}
ListPlot[res3 ,AxesLabel-> {"Run Length","Runs"},AxesOrigin->{0,0}]
```
I ran a large number of cases to systematically check out the distribution of runs.
In approximately 3 million binary digits, there were 830k runs of 1, 416k runs of 2, 208k runs of 3, 104k runs of 4, etc.

**Test 4: Matching of first and second half of data**
The matches are the 212 cases of 0 and 2; the mismatches are the 208 cases where the sum of the respective digits is 1.
```
d=301;
Tally[Plus@@Partition[Take[RealDigits[N[Pi,d],2][[1]],840],420]]
(* out *)
{{1,208},{0,108},{2,104}}
```
**Timing**
It takes under two seconds to calculate 3321928 binary digits (corresponding to 10^6 decimal digits).
```
(r=f[10^6]);//AbsoluteTiming
StringLength[r]
(*out*)
{1.785928,Null}
3321928
```
[Answer]
## C, 61
```
main(s,n){for(n=1u<<31;putchar((s%=n)/(n/2)&1|48);s*=65539);}
```
Yeah, I know it's not code golf. This is [obviously rather an anti-solution](http://en.wikipedia.org/wiki/RANDU)... but it sure enough fulfills your criteria.
>
> $ ./a.out | head -c840
> 000000001000111101100110110011100100011101110001101001101110011101100111010111010010001001110001111110010001010101101000110101000011110010100101001101110100011111000101000110000111100100010101010100110101101010001110101000011011001010111011110110101000001110011000010100001111110110001000000101100011000110000010110011000010101101011100010011011111111100001010111110111010110001000010110111000010101001000011001001110110001001101011011110111011010100000000001001010100111000000100010011110001010111001110101111100110110111010001101001100000101000111000101000110100001111010110100001100110011011110001011011100010111011100001110100110001010011001110001010110100111111111010110101100110000101111111111000111101100011000111010111010100110001001110101110100011101110001100110110000001100101110100101000101011100000110111101101100110000000101110
>
> $ ./a.out | head -c840 | perl tester.pl
>
> Test 2: 1 (1) 2.93333333333333 (3) 3.1 (3) 0.966666666666667 (1)
>
> Test 3: 214 99 71 24 7 5 1 1 2 2
>
> Test 4: 0.495238095238095
>
>
>
>
Period length is 2²⁹.
[Answer]
## Python, 90
```
g=[19]
print(''.join("01"[(g.append((11*g[-1]+13)%1024)or g[-1])>512]for i in range(1000)))
```
`g` is the seed value. Random sampling exhibits a remarkably normal distribution repeated random sampling of sample means yielded a mean of `0.506` and a a standard deviation of `.0473` (sample size of 1000). Unfortunately, randomness is highly sensitive to initial seed. The seed in the above code gave me the best randomness :p
**UPDATE**
Let's see how this code holds up to the OP's tests:
## Test #1
This one's a bit subjective... but it looks pretty irregular to me.
## Test #2
>
> Three 1's: 0.141
>
> Two 1's: 0.371
>
> One 1: 0.353
>
> Zero 1's: 0.135
>
>
>
## Test #3
Runs by size:
```
8: 11
7: 3
6: 7
5: 13
4: 32
3: 67
2: 119
1: 216
```
## Test #4
>
> ~~Ratio of equalities: 0.94~~ This is a typo. Will update with the correct number soon.
>
>
>
[Answer]
## Haskell ~~74~~ 58
```
main=print$iterate(read.take 9.show.(^3))7>>=show.(`mod`2)
```
Thanks to **shiona** for the simplification.
Results:
>
> $ ~/golf$ ./pseudorandom | head -c 1000
> 111110110101011110001011110101011110001111011001110101100100111000100100000011000100011101010111000000001110100111100010110000100000001001111011100001101101001111110100111011111110011011101111010110001110011100010000001011011100010111011110011110100110100000110110010011101010001111101011111110000110110110011111011101000011110010000011011010011110110100010011100011011111011010110001100111100100100001110100001110111011111000001101001010100001100111010111011011011001110000100000100000010111011010111011111011011101001100100011111101110101101010111101001111110101110101001011111011111100111110001001001010001011100100101000010101011001101011011001100111101010001110001011110001011111110110100110011000010101100010011011010100000110100001000010110110111101101010000001110001100011010100000011111010111100101110101001000111001000000101111110010110001011011000011111011001100001101000101001111000101011101010001010110010111111110111111101000111010001001010010011101011100101011101000101101000010101100
>
>
> ./pseudorandom | head -c 1000 | perl test.pl
>
>
> Test 2: 0.966666666666667 (1) 2.4 (3) 3.3 (3) 1.33333333333333 (1)
>
>
> Test 3: 260 108 66 33 15 11 5 2
>
>
> Test 4: 0.495238095238095
>
>
>
This is also a terrible pseudo-random generator (similar to one used by von-Neuman). For those that were not aware `concatMap == (=<<) == flip . (>>=)` (for lists)
[Answer]
## C, 52 chars
```
main(a){for(a=1;putchar(48+a%2);a=a/2^-(a%2)&576);}
```
This is a 10 bit LFSR, test results:
```
$ ./a.out |head -c 1000 | perl randtest.pl
Test 2: 1.13333333333333 (1) 2.86666666666667 (3) 3.16666666666667 (3) 0.833333333333333 (1)
Test 3: 251 122 64 32 16 8 4 2 1
Test 4: 0.466666666666667
```
[Answer]
The question is essentially equivalent to "implement a stream cipher". So I implement RC4, since it's relatively simple.
I use no key, and drop the first 100000 bits, because the beginning of RC4 is a bit biased, especially since I skipped the key schedule. But I'd expect it to pass your test even without that (saving 20 chars of code).
Normally one would output a full byte per cycle, but converting to binary is rather ugly in C#, so I simply discard everything except the least significant bit.
```
var s=Enumerable.Range(0,256).ToArray();
byte i=0,j=0;
for(int k=0;;k++)
{
i++;
j+=(byte)s[i];
var t=s[i];s[i]=s[j];s[j]=t;
if(k>99999)
Console.Write(s[i]+s[j]&1);
}
```
Or without spaces:
```
var s=Enumerable.Range(0,256).ToArray();byte i=0,j=0;for(int k=0;;k++){i++;j+=(byte)s[i];var t=s[i];s[i]=s[j];s[j]=t;if(k>99999)Console.Write(s[i]+s[j]&1);}
```
C#, 156 chars, works in LinqPad's statement mode. For a full C# program add the usual boilerplate.
---
We could also use built in crypto primitives(Cheater solution):
```
var h=SHA256.Create();for(BigInteger i=0;;i++){Console.Write(h.ComputeHash(i.ToByteArray())[0]%2);}
```
(C#, 99 chars, works in LinqPad's statement mode. For the normal C# compiler you'll need to add a bit of boilerplate)
The output of cryptographic hash functions is designed to be indistinguishable from random data, so I expect it to pass all randomness tests(die harder,...) you throw at it, but I'm too lazy to test.
[Answer]
## Sage/Python
This program prints the rightmost binary digits that are common to every sufficiently tall exponentiation tower of form 3333... For all that could ever be feasibly generated, these are the rightmost binary digits of [Graham's number](http://en.wikipedia.org/wiki/Graham%27s_number). The digit sequence is infinite, and is not periodic.
```
m = 1; x = 3; last = 0
while True:
m *= 2; x = pow(3,x,m); l = len(bin(x))
print '1' if l > last else '0',
last = l
```
For 1000 digits, this took less than 2 seconds; however, the time will increase much faster than linearly in the number of digits.
The [test results using the OP's program](http://ideone.com/8uZKn) are
```
Test 2: 1.26666666666667 (1) 3.16666666666667 (3) 2.8 (3) 0.766666666666667 (1)
Test 3: 268 126 61 30 20 7 2 1 1
Test 4: 0.466666666666667
```
(See [Are the rightmost digits of G random?](https://sites.google.com/site/res0001/digits-of-graham-s-number/random-rightmost-digits-of-g) for more than 32000 digits and additional statistical tests.)
[Answer]
**Java, 371 317**
Based on a 128 bit [LFSR](http://en.wikipedia.org/wiki/Linear_feedback_shift_register) (bit taps are from [xilinx app note 52](http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf))
**EDIT:** I was not satisfied with using BigInteger so this version does not. Saved some characters. Output might be a little less random as I could not think of a good 'seeding' method.
**New Code:** Arguments: BITS\_TO\_PRINT
```
class R{public static void main(String[]a){int L=65536;int[]v={0,128,126,101,99};int[]b=new int[L];for(int x=0;x<L;x++)b[x]=(x*x)&1;for(int i=0;i<Integer.parseInt(a[0])+L;i++){if(1!=(b[v[1]]^b[v[2]]^b[v[3]]^b[v[4]]))b[v[0]]=1;else b[v[0]]=0;if(i>L)System.out.print(b[v[0]]);for(int j=0;j<5;j++)v[j]=(v[j]-1)&(L-1);}}}
```
**Old Version:**
Arguments: SEED, BITS\_TO\_PRINT
```
import java.math.BigInteger;class R{public static void main(String[]a){BigInteger v=new BigInteger(a[0]);BigInteger m=new BigInteger("ffffffffffffffffffffffffffffffff",16);for(int i=Integer.parseInt(a[1]);i>0;i--){v=v.shiftLeft(1);if(!(v.testBit(128)^v.testBit(126)^v.testBit(101)^v.testBit(99))){v=v.setBit(0);}v=v.and(m);java.lang.System.out.print(v.testBit(0)?1:0);}}}
```
**New Version:** Example output, bits=100:
```
011001100111000110010100100111011100100111000111001111110110001001100000100111111010111001100100011
```
[Answer]
**JavaScript - 1ms to 2ms for 1000 pseudo-random bits (139ms to 153ms for 100000 bits)**
This solution uses the fact that square roots are irrational, and thus pretty much random. Basically, it takes the square root of 2 to start, converts it to binary, throws out the leading part that matched the previous root, appends that to the random string, repeats with the next higher number (or back to 2 if the number repeated and was at least 30 bits long), and returns the random string once it is long enough.
```
var getDeterministicPseudoRandString = function(length){
var randString = '';
var i = 2;
var prevRand = '';
outerLoop:
while(randString.length < length){
var nextRand, nextFullRand = Math.sqrt(i++).toString(2).substring(1).replace('.', '');
nextRand = nextFullRand;
for(var j = prevRand.length; j > 0; j--){
var replaceString = prevRand.substring(0, j);
nextRand = nextFullRand;
if(nextFullRand.indexOf(replaceString) == 0){
if(j == prevRand.length && j > 30){
//start i over at 2
console.log('max i reached: ' + i);
i = 2;
continue outerLoop;
} else {
nextRand = nextFullRand.replace(replaceString, '');
}
break;
}
}
prevRand = nextFullRand;
randString += nextRand;
}
return randString.substring(0, length);//Return the substring with the appropriate length
};
```
I haven't ran it through the tests yet, but I imagine it will do well on them. [Here's a fiddle](http://jsfiddle.net/briguy37/wbRat/) so you can see it in action. For my times, I just ran the program several times and took the fastest and slowest values as the ranges.
[Answer]
## Python
```
import hashlib
x=''
while 1:
h=hashlib.sha512()
h.update(x)
x=h.digest()
print ord(x[0])%2
```
Should have a period of about 2^512.
[Answer]
# perl, 44 bytes
I know this isn't code golf, but I've always been a fan of taking the low order bits of a simple quadratic function, eg:
```
$x=1/7;print substr($x*=4-4*$x,9,1)%2while 1
```
Period is longer than 3 billion, but I've run out of disk space to calculate more.
] |
[Question]
[
Given a sequence of integers find the largest sum of a subsequence (integers on consecutive positions) of the sequence. The subsequence can be empty (in which case the sum is 0).
Input is read from standard input, one integer per line. The largest sum must be written to standard output.
I wrote a small generator for you:
```
#include <stdio.h>
#include <assert.h>
/* From http://en.wikipedia.org/wiki/Random_number_generation */
unsigned m_w;
unsigned m_z;
unsigned get_random()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
int main(int argc, char **argv)
{
int i;
assert(argc == 3);
m_w = atoi(argv[1]);
m_z = atoi(argv[2]);
i = 10;
while (i--);
get_random();
i = atoi(argv[2]);
while (i--)
printf("%d\n", (int) get_random() << 8 >> 22);
return 0;
}
```
Examples:
```
$ printf "1\n2\n-1\n4\n" | ./sum
6
$ printf "0\n-2\n-3\n" | ./sum
0
$ ./a.out 1 1 | ./sum
387
$ ./a.out 1 10 | ./sum
571
$ ./a.out 1 100 | ./sum
5867
$ ./a.out 1 1000 | ./sum
7531
$ ./a.out 1 10000 | ./sum
27268
$ ./a.out 1 100000 | ./sum
101332
$ ./a.out 1 1000000 | ./sum
187480
$ ./a.out 1 10000000 | ./sum
666307
```
* `./sum` is my solution
* `./a.out` is the generator
Your solution must run in reasonable time for all tests above (mine runs in 1.2s on the last test case).
Shortest code wins.
**Edit**: Please provide an example run on one of the tests above.
[Answer]
**Python, 91 84 64 chars**
```
s=m=0
try:
while 1:s=max(s+input(),0);m=max(m,s)
except:print m
```
Takes about 14 12 72 seconds on the last test case. Edit: using algorithm Paul R found. Edit: nixed the import, using `input()`.
[Answer]
## C, 100 characters
```
main(){char s[80];int i,m=0,n=0;while(gets(s)){i=atoi(s);n=n+i>0?n+i:0;m=m>n?m:n;}printf("%d\n",m);}
```
Run time = **1.14 s** for final test case (10000000) on 2.67 GHz Core i7 with ICC 11.1 (previously: **1.44 s** with gcc 4.2.1).
Note: The algorithm used for the above solution comes from *Programming Pearls* by Jon Bentley. Apparently this algorithm is known as [Kadane's Algorithm](http://algorithmist.com/index.php/Kadane%27s_Algorithm).
[Answer]
## Ruby, 53 characters
```
p$<.inject(-1.0/s=0){|a,b|[s=[0,s+b.to_i].max,a].max}
```
Takes about 28 seconds for the last testcase here.
[Answer]
## Haskell (~~88~~ 64)
Implementing Kadane's algorithm.
```
main=interact$show.maximum.scanr(\x->max x.(x+))0.map read.lines
```
[Answer]
**Python - 114 chars**
```
import sys
s=map(int,sys.stdin.readlines())
l=range(len(s)+1)
print`max(sum(s[i:j])for i in l[:-1]for j in l[i:])`
```
It surely isn't as fast as required, but it works allright.
[Answer]
**Python, using dynamic programming - 92 chars**
```
import sys
s=map(int,sys.stdin.readlines())
f=h=0
for x in s:h=max(0,h+x);f=max(f,h)
print f
```
[Answer]
## J (~~34~~ 33 characters)
This solution implements a variant of Kadane's algorithm and is reasonable fast.
```
echo>./0,([>.+)/\.0".];._2(1!:1)3
```
Here is an explanation:
* `u/ y` – The verb `u` *inserted* between items of `y`. E.g., `+/ 1 2 3 4` is like `1 + 2 + 3 + 4`. Notice that all verbs in J are right-associated, that is, `-/ 1 2 3 4` is like `1 - (2 - (3 - 4))` and computes the alternating sum of `1 2 3 4`.
* `x >. y` – the maximum of `x` and `y`.
* `x ([ >. +) y` – The maximum of `x` and `x + y`. `[ >. +` is a verb in tacit notation and evaluates to the same as `x >. x + y`.
* `([ >. +)/ y` – the non-empty prefix of `y` with the largest sum.
* `u\. y` – `u` applied to all suffixes of `y`. Notice that special code handles the common case `u/\. y` such that this runs in linear instead of quadratic time.
* `([ >. +)/\. y` – A vector denoting the largest non-empty subarray that starts at each position of `y`.
* `0 , ([ >. +)/\. y` – `0` preprended to the previous result as `0` is the length of an empty subarray of `y`.
* `>./ 0 , ([ >. +)/\. y` – The largest subarray of `y`.
* `0 ". ];._2 (1!:1) 3` – Standard input marshalled into a vector of numbers.
* `>./ 0 , ([ >. +)/\. 0 ". ];._2 (1!:1) 3` – The largest subarray in standard input.
[Answer]
## Ruby, 68 chars
```
m=-2**31;n=0;$<.lines.map{|x|n+=x.to_i;n=0 if n<0;m=n if n>m};puts m
```
Also a bit slow, but completes the 1-10000000 tests in a bit over half minute, most of the time spent in the last test...
Indented version:
```
m=-2**31
n=0
$<.lines.map {|x|
n+=x.to_i
n=0 if n<0
m=n if n>m
}
puts m
```
[Answer]
C++, 192 chars
```
#include <iostream>
#include <string>
#include <stdlib.h>
#define S std::
main(){long a=0,m=0,M=0;char s[9];while(S cin.getline(s,9)){a+=atoi(s);if(m>a)m=a;if(M<a-m)M=a-m;}S cout<<M<<S endl;}
```
Works reasonably fast on my laptop (4 seconds for the last test).
[Answer]
```
{if((r+$1)>0)
r=r+$1
else r=0;
if(m<r)
m=r;
}
END{print m}
```
**awk Code (66)**, very slow, 8+ seconds for last test case
```
dwang@dwang-ws ~/Playground/lss $ time ./random 1 10000000 | awk -f lss.awk
666307
real 0m6.705s
user 0m8.671s
sys 0m0.052s
```
] |
[Question]
[
You task is to write a small program, that counts the points of a Skat hand. A Skat deck has cards 7 to 10, Jack, Queen, King and Ace (called Unter, Ober, König and Daus). We use the German suits, which have Acorns, Leaves, Hearts and Bells instead of Clubs, Spades, Hearts and Diamonds. The points are determined by the number on the card:
* 7, 8 and 9 are 0 points
* Unter is 2 points
* Ober is 3 points
* König is 4 points
* 10 is 10 points
* Daus is 11 points.
### Input / Output
The input format consists of two symbols, the first one represents the value, while the second one stands for the suit:
* 7, 8 and 9 stand for them self
* 0 (zero) stands for 10
* Unter, Ober, König and Daus are named after their first letters (U, O and D)
* The same for Acorns, Leaves, Hearts and Bellys (A, L, H and B)
The input is a single line of cards, separated by a single whitespace. You may take the input from anywhere, command line arguments are okay too. The output is the value of the hand, either printed out or returned as an exit code. The output of your program must show an error, if any card appears twice in the hand. (So `7A 0L 7A` must return an error instead of `10`). It is also okay to quit with an exit code of 255 instead of showing an error, if this is the default way of your program to output the result.
### Examples
* `7A 8A 9A UA OA KA 0A DA 7L 8L 9L UL OL KL 0L DL 7H 8H 9H UH OH KH 0H DH 7B 8B 9B UB OB KB 0B DB` gives *120*
* `7A 8L 0K DB 8L` gives an error
* `UA OB DL KH` gives *20*
### Rules
* Code golf: The shortest code wins
* Usual code golf rules apply
* The program has to work for all hands, not just the examples
* GIGO: If the input is invalid, the output may be arbitrary
[Answer]
## Ruby 1.9, 52 characters
Input via command line arguments. I'm assuming the error message when having duplicate cards doesn't matter, so it just complains about an eval/type conversion error.
```
p eval$*.uniq!||$*.map{|i|"..UOK#$<.0D"=~/#{i}?/}*?+
```
Example usage:
```
$ ruby1.9 skatscore.rb 7A 8A 9A UA OA KA 0A DA 7L 8L 9L UL OL KL 0L DL 7H 8H 9H UH OH KH 0H DH 7B 8B 9B UB OB KB 0B DB
120
$ ruby1.9 skatscore.rb 7A 7A
skatscore.rb:1:in `eval': can't convert Array into String (TypeError)
from skatscore.rb:1:in `<main>'
```
[Answer]
### Scala, 87 82 characters
```
args.distinct(args.size-1);println(args.map(a=>1+" UOK 0D".indexOf(a(0))).sum)
```
Throws an exception on repeated cards.
[Answer]
# Haskell, ~~122~~ ~~108~~ 107 characters
```
import List
main=interact$f.words
f x|nub x==x=show$sum$map(maybe 0 id.(`elemIndex`" UOK 0D").head)x
```
[Answer]
## APL (~~54~~ 48)
There *has* to be a shorter way of selecting the card value, but I don't see it.
```
(+/12-'D0.....KOU.'⍳⊃¨A)÷A≡∪A←↓A⍴⍨2,⍨2÷⍨⍴A←⍞~' '
```
You get a `DOMAIN ERROR` if there's a duplicate card.
Explanation:
* `A←⍞~' '`: store (`←`) into `A` a line of user input (`⍞`) without (`~`) the spaces.
* `2,⍨2÷⍨⍴A`: a two-element list, containing the length of (`⍴`) `A` divided by (`÷⍨`) 2, followed by (`,⍨`) the number 2. (So, if the input is `UA OB DL KH` the list is (4, 2)).
* `↓A⍴⍨`: define a matrix (`⍴`), with the dimensions of that list, containing the values of A. Then join the elements of its rows together (`↓`), giving a list of lists, for example `['UA','OB','DL','KH']`.
* `A←`: Store this list in A.
* `A≡∪A`: `∪A` is the list of unique elements in A. If this is equal to A, there are no duplicates and this returns 1, otherwise 0.
* `÷`: divide what's on the left (which does the actual calculation) by the result of the equality test. So if there are no duplicates, the score is unchanged, and if there are duplicates you get a `DOMAIN ERROR` because of the division by zero.
* `⊃¨A`: A list giving the first element (`⊃`) of each element (`¨`) of A. So this drops the suit letter, leaving the score letter. (`UODK`)
* `'D0.....KOU.'⍳`: gives the index of each of the score letters in this string, returns 12 for values not in the string. (`10 9 1 8`)
* `+/12-`: subtract all of these from 12, and then add them together. (`2 + 3 + 11 + 4 = 20`)
---
[Answer]
### GolfScript ~~54~~ ~~53~~ 52
**Edit 1:**
I just discovered an error in the code. It did not detect duplicate cards if the duplicates were the first two in the input (because I was using the `*` fold operator and not the `/` each operator for the first loop).
Now I fixed the code and also managed to strip off 1 char in the process. Here's the new version:
```
' '/{1$1$?){]?}{\+}if}/2%{"UOK0D"\?).0>+.4>5*+}%{+}*
```
The input has to be on the stack as a string, in the specified format (example: `'7A UA DA'`).
In case the input is valid, the program prints the total value of the cards.
In case there's at least one duplicate card, the program throws the following exception:
```
(eval):1:in `block in initialize': undefined method `class_id' for nil:NilClass (NoMethodError)
```
**Edit 2:**
After seeing [this post on the meta site](https://codegolf.meta.stackexchange.com/questions/88/on-golfscript-and-language-bigotry), I decided to post a description of the code. This also helped me find and fix an error. So, here goes:
```
# Initially, we epect the input string to be on the stack
# Example: "7A UA DA"
' '/ # split the input string by spaces
# now we have on the stack an array of strings
# (in our example: ["7A" "UA" "DA"])
# {1$1$?)!{\+}{]?}if}/ -> this piece of code checks for duplicate cards
#
# The trailing symbol (/) is the 'each' operator, meaning that the
# preceding code block (enclosed in curly brackets) will be executed
# for every cards in the previous array.
#
# Before each execution of the code block, the current card value
# is pushed on the stack.
#
# Basically what this code does is concatenate cards into a string
# and checks whether the current card is contained in the accumulated
# value.
#
# So, for each card, this is what we execute:
1$ # copies the concatenated string on top of the stack
# (initially this is an empty string)
1$ # copies the current card on top of the stack
? # returns (places on the stack) the 0-based index where
# the current card is found in the concatenated string
# or -1 if not found
) # increments the topmost stack value
# Now we have 0 if the card is not a duplicate
# or a value greater than 0 otherwise
{]?}{\+}if # if the current stack value is non-0 (duplicate)
# then execute the first code {]?} (generates an error)
# Otherwise, if the card is valid, execute the {\+} block.
# What this code does is essentially concatenate the current
# card value:
# \ -> swaps the two topmost stack values; now we have
# the concatenated string and the current card value
# + -> this is the concatenation operator
# After the previous code block finishes execution (in case the input is)
# valid, we end up having the concatenated card values on the stack
# In our example, this value is "DAUAUB7A".
# The next code fragment is the one that computes the card values
# This is the code: 2%{"UOK0D"\?).0>+.4>5*+}%{+}*
# And this is how it can be broken down:
2% # takes only the even indexed chars from the existing string
# in our case, "DAUA7A" -> "DU7"
# Only these characters are important for determining the
# card values.
# The following piece of code is:
# {"UOK0D"\?).0>+.4>5*+}%
# This code performs a map; it takes the individual chars,
# computes the corresponding numeric value for each of them and outputs an
# array containing those values
# This is achieved using the map operator (%) which evaluates the preceding
# code block, delimited by curly braces, so, essentially this is the code that
# computes the value for a card:
# "UOK0D"\?).0>+.4>5*+
# It can be broken down like this:
"UOK0D" # pushes the "UOK0D" string on the stack
\ # swaps the two topmost stack values
# Now, these values are: "UOK0D" and "l"
# (where "l" represents the current letter
# that gives the card its value: U,O,K,0,D,7,8...)
? # Find the index of the card's letter in the
# "UOK0D" string.
# Remember, this is 0-based index, or -1 if not found.
) # increment the index value
# Now we have the following value:
# 1 if the card is U
# 2 if the card is O
# 3 if the card is K
# 4 if the card is 0
# 5 if the card is D
# 0 if it is anything else
.0>+ # if the current value is greater than 0,
# add 1 to it.
.4>5*+ # if the current value is greater than 4,
# add 5 to it.
# Passing through these steps, we now have the following value:
# 2 if the card is U
# 3 if the card is O
# 4 if the card is K
# 10 if the card is 0
# 11 if the card is D
# 0 if it is anything else
# This is the exact value we were looking for.
# Now we have an array containing the value of each card.
# in our example, [0, 2, 11]
# The next piece of code is easy:
{+}* # uses the * (fold) operator to add up all the
# values in the array.
# This leaves the total value of the cards on the stack,
# which is exactly what we were looking for (0+2+11=13).
# Golfscript is awesome! :-)
```
[Answer]
## Python, 114 characters
```
i=input().split();print(sum(int(dict(zip('7890UOKD','000A234B'))[x[0]],16)for x in i)if len(i)<=len(set(i))else'')
```
Unfortunately, the `index` method of lists in Python raises an error if an element isn't found rather than returning a negative value, and importing `defaultdict` would require more characters than it would save.
[Answer]
eTeX, 201 characters (not counting the two irrelevant linebreaks)
```
\def~#1#2{\catcode`#113\lccode`~`#1\lowercase{\def~}##1 {\ifcsname
#1##1 ~\D\fi\if\csname#1##1 ~\fi+"#2}}~70~80~90~0A~U2~O3~K4~DB\def
\a[#1]{\let~\endcsname\write6{^^J \the\numexpr#1 }\end}\expandafter\a
```
Used as `etex filename.tex [UA OB DL KH]`. Putting the argument in brackets is necessary: otherwise, eTeX has no way of determining that we reached the end of the argument list.
EDIT: as allowed in the statement of the question, incorrect input can cause (an) error. For instance, `etex filename.tex [OK]` crashes horribly (because `K` is not a valid color).
[Answer]
## PowerShell, 79 ~~80~~
```
($a=$args|sort)|%{$s+=(10,11+4..0)['0DKOU'.IndexOf($_[0])]}
$s/("$a"-eq($a|gu))
```
Throws »Attempted to divide by zero.« if cards appear twice.
] |
[Question]
[
The `period` of a string is the shortest non-zero shift so that the string matches itself, ignoring any parts that overhang. So for example, `abcabcab` has period `3`. By convention we say that if there is no such shift then a string has period equal to its length. So the period of `abcde` is `5` and the period of `a` is `1`.
In more formal terms, the period of a string `S` is the minimum `i > 0` so that `S[1,n-i] == S[i+1,n]` (indexing from `1`).
For a given string S of power of two length, we will compute the period of all its prefixes of power of two length. For example, consider `S = abcabcab`. The periods we will compute are:
```
'a', 1
'ab', 2
'abca', 3
'abcabcab', 3
```
We will in fact just output the array of periods, that is `[1, 2, 3, 3]`.
For a given positive power of two `n`, consider all possible binary strings `S`. Recall that a binary string is simply a string of `1`s and `0`s so there are exactly `2^n` such strings (that is `2` to the power `n`). For each one we can compute this array of periods.
>
> The challenge is to write code that takes `n` (a power of two) as input and computes how many distinct such arrays there are.
>
>
>
The answers for `n = 1, 2, 4, 8, 16, 32, 64, 128` are:
```
1, 2, 6, 32, 320, 6025, 216854, 15128807
```
The full set of distinct period arrays for `n = 4` is:
```
1, 1, 1
1, 1, 3
1, 1, 4
1, 2, 2
1, 2, 3
1, 2, 4
```
**Score**
I will run your code on my computer running Ubuntu for 10 minutes. Your score is the largest `n` for which your code terminates in that time. In the case of a tie, the answer that completes the joint largest `n` fastest wins. In the case that there is a tie within 1 second on timings, the first answer posted wins.
**Languages and libraries**
You can use any available language and libraries you like. Please include a full explanation for how to run/compile your code in Linux if at all possible.`
Your code should actually compute the answers and not, for example, just output precomputed values.
**Leading entries**
* **2 minutes and 21 seconds** for **n = 128** in **C#** by Peter Taylor
* **9 seconds** for **n = 32** in **Rust** by isaacg
[Answer]
## C#, n=128 in about 2:40
```
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sandbox
{
class PPCG137436
{
public static void Main(string[] args)
{
if (args.Length == 0) args = new string[] { "1", "2", "4", "8", "16", "32", "64", "128" };
foreach (string arg in args)
{
Console.WriteLine(Count(new int[(int)(0.5 + Math.Log(int.Parse(arg)) / Math.Log(2))], 0));
}
}
static int Count(int[] periods, int idx)
{
if (idx == periods.Length)
{
//Console.WriteLine(string.Join(", ", periods));
return 1;
}
int count = 0;
int p = idx == 0 ? 1 : periods[idx - 1];
for (int q = p; q <= 1 << (idx + 1); q++)
{
periods[idx] = q;
if (q == p || q > 1 << idx || p + q - Gcd(p, q) > 1 << idx && UnificationPasses(periods, idx, q)) count += Count(periods, idx + 1);
}
return count;
}
private static int Gcd(int a, int b)
{
while (a > 0) { int tmp = a; a = b % a; b = tmp; }
return b;
}
private static bool UnificationPasses(int[] periods, int idx, int q)
{
UnionSet union = new UnionSet(1 << idx);
for (int i = 0; i <= idx; i++)
{
for (int j = 0; j + periods[i] < Math.Min(2 << i, 1 << idx); j++) union.Unify(j, j + periods[i]);
}
IDictionary<int, long> rev = new Dictionary<int, long>();
for (int k = 0; k < 1 << idx; k++) rev[union.Find(k)] = 0L;
for (int k = 0; k < 1 << idx; k++) rev[union.Find(k)] |= 1L << k;
long zeroes = rev[union.Find(0)]; // wlog the value at position 0 is 0
ISet<int> onesIndex = new HashSet<int>();
// This can be seen as the special case of the next loop where j == -1.
for (int i = 0; i < idx; i++)
{
if (periods[i] == 2 << i) onesIndex.Add((2 << i) - 1);
}
for (int j = 0; j < idx - 1 && periods[j] == 2 << j; j++)
{
for (int i = j + 1; i < idx; i++)
{
if (periods[i] == 2 << i)
{
for (int k = (1 << j) + 1; k <= 2 << j; k++) onesIndex.Add((2 << i) - k);
}
}
}
for (int i = 1; i < idx; i++)
{
if (periods[i] == 1) continue;
int d = (2 << i) - periods[i];
long dmask = (1L << d) - 1;
if (((zeroes >> 1) & (zeroes >> periods[i]) & dmask) == dmask) onesIndex.Add(periods[i] - 1);
}
long ones = 0L;
foreach (var key in onesIndex) ones |= rev[union.Find(key)];
if ((zeroes & ones) != 0) return false; // Definite contradiction!
rev.Remove(union.Find(0));
foreach (var key in onesIndex) rev.Remove(key);
long[] masks = System.Linq.Enumerable.ToArray(rev.Values);
int numFilteredMasks = 0;
long set = 0;
long M = 0;
for (int i = 1; i <= idx; i++)
{
if (periods[i - 1] == 1) continue;
// Sort the relevant masks to the start
if (i == idx) numFilteredMasks = masks.Length; // Minor optimisation: skip the filter because we know we need all the masks
long filter = (1L << (1 << i)) - 1;
for (int j = numFilteredMasks; j < masks.Length; j++)
{
if ((masks[j] & filter) != 0)
{
var tmp = masks[j];
masks[j] = masks[numFilteredMasks];
masks[numFilteredMasks++] = tmp;
}
}
// Search for a successful assignment, using the information from the previous search to skip a few initial values in this one.
set |= (1L << numFilteredMasks) - 1 - M;
M = (1L << numFilteredMasks) - 1;
while (true)
{
if (TestAssignment(periods, i, ones, masks, set)) break;
if (set == 0) return false; // No suitable assignment found
// Gosper's hack with variant to reduce the number of bits on overflow
long c = set & -set;
long r = set + c;
set = (((r ^ set) >> 2) / c) | (r & M);
}
}
return true;
}
private static bool TestAssignment(int[] periods, int idx, long ones, long[] masks, long assignment)
{
for (int j = 0; j < masks.Length; j++, assignment >>= 1) ones |= masks[j] & -(assignment & 1);
for (int i = idx - 1; i > 0; i--) // i == 0 is already handled in the unification process.
{
if (Period(ones, 2 << i, periods[i - 1]) < periods[i]) return false;
}
return true;
}
private static int Period(long arr, int n, int min)
{
for (int p = min; p <= n; p++)
{
// If the bottom n bits have period p then the bottom (n-p) bits equal the bottom (n-p) bits of the integer shifted right p
long mask = (1L << (n - p)) - 1L;
if ((arr & mask) == ((arr >> p) & mask)) return p;
}
throw new Exception("Unreachable");
}
class UnionSet
{
private int[] _Lookup;
public UnionSet(int size)
{
_Lookup = new int[size];
for (int k = 0; k < size; k++) _Lookup[k] = k;
}
public int Find(int key)
{
var l = _Lookup[key];
if (l != key) _Lookup[key] = l = Find(l);
return l;
}
public void Unify(int key1, int key2)
{
int root1 = Find(key1);
int root2 = Find(key2);
if (root1 < root2) _Lookup[root2] = root1;
else _Lookup[root1] = root2;
}
}
}
}
```
Extending to n=256 would require switching to `BigInteger` for the masks, which probably kills the performance too much for n=128 to pass without new ideas, let alone n=256.
Under Linux, compile with `mono-csc` and execute with `mono`.
### Basic explanation
I'm not going to do a line-by-line dissection, just an overview of the concepts.
As a rule of thumb, I'm happy to iterate through on the order of 250 elements in a brute-force combinatoric program. To get to n=128 it is therefore necessary to use an approach which doesn't analyse every bitstring. So rather than working forwards from bit strings to period sequences, I work backwards: given a period sequence, is there a bitstring which realises it? For n=2x there's an easy upper bound of 2x(x+1)/2 period sequences (vs 22x bitstrings).
Some of the arguments use the **string periodicity lemma**:
>
> Let `p` and `q` be two periods of a string of length `n`. If `p + q ≤ n + gcd(p, q)` then `gcd(p, q)` is also a period of the string.
>
>
>
Wlog I will assume that all of the bitstrings under consideration start with `0`.
Given a period sequence `[p1 p2 ... pk]` where `pi` is the period of the prefix of length 2i (`p0 = 1` always), there are some easy observations about possible values of `pk+1`:
* `pk+1 ≥ pk` since a period of a string `S` is also a period of any prefix of `S`.
* `pk+1 = pk` is always a possible extension: just repeat the same primitive string for twice as many characters.
* `2k < pk+1 ≤ 2k+1` is always a possible extension. It suffices to show this for `pk+1 = 2k+1` because an aperiodic string of length `L` can be extended to an aperiodic string of length `L+1` by appending any letter which isn't its first letter.
Take a string `Sx` of length 2k whose period is `pk` and consider the string `SxyS` of length 2k+1. Clearly `SxyS` has *a* period 2k+1. Suppose its period `q` is smaller.
Then `2k+1 + q ≤ 2k+1+1 ≤ 2k+1 + gcd(2k+1, q)` so by the periodicity lemma `gcd(2k+1, q)` is also a period of `SxyS`, and since the greatest divisor is less than or equal to its arguments and `q` is the smallest period, we require `q` to be a proper factor of 2k+1. Since its quotient cannot be 2, we have `q ≤ (2k+1)/3`.
Now, since `q ≤ 2k` is a period of `SxyS` it must be a period of `Sx`. But *the* period of `Sx` is `pk`. We have two cases:
1. `gcd(pk, q) = pk`, or equivalently `pk` divides exactly into `q`.
2. `pk + q > 2k + gcd(pk, q)` so that the periodicity lemma doesn't force a smaller period.Consider first the second case. `pk > 2k + gcd(pk, q) - q ≥ 2k+1 - q ≥ 2k+1 - (2k+1)/3 ≥ 2q`, contradicting the definition of `pk` as the period of `Sx`. Therefore we are forced into the conclusion that `pk` is a factor of `q`.
But since `q` is a period of `Sx` and `pk` is the period of `Sx`, the prefix of length `q` is just `q/pk` copies of the prefix of length `pk`, so we see that `pk` is also a period of `SxyS`.
Therefore the period of `SxyS` is either `pk` or 2k+1. But we have two options for `y`! At most one choice of `y` will give period `pk`, so at least one will give period 2k+1. QED.
* The periodicity lemma allows us to reject some of the remaining possible extensions.
* Any extension which hasn't passed a quick-accept or a quick-reject test needs to be tested constructively.
The construction of a bitstring given a period sequence is essentially a satisifiability problem, but it has a lot of structure. There are `2k - pk` simple equality constraints implied by each prefix period, so I use a [union set](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) data structure to combine bits into independent clusters. This was enough to tackle n=64, but for n=128 it was necessary to go further. I employ two useful lines of argument:
1. If the prefix of length `M` is `01M-1` and the prefix of length `L > M` has period `L` then the prefix of length `L` must end in `1M`. This is most powerful precisely in the cases which would otherwise have most independent clusters, which is convenient.
2. If the prefix of length `M` is `0M` and the prefix of length `L > M` has period `L - d` with `d < M` and ends in `0d` then it must in fact end in `10d`. This is most powerful at the opposite extreme, when the period sequence starts with a lot of ones.
If we don't get an immediate contradiction by forcing the cluster with the first bit (assumed to be zero) to be one then we brute force (with some micro-optimisations) over the possible values for the unforced clusters. Note that the order is in descending number of ones because if the `i`th bit is a one then the period cannot be `i` and we want to avoid periods which are shorter than the ones which are already enforced by the clustering. Going down increases the chances of finding a valid assignment early.
[Answer]
# Rust, 32, 10s ~~11s~~ ~~29s~~ on my laptop
Call it with the bitsize as the command line argument.
Clever techniques: represent bitstrings directly as numbers, use bittwiddling to check for cycles. Only search the first half of the bitstrings, those starting with 0, because the array of periods of a bitstring and its inverse (0s swapped for 1s) are identical. If every possibility for the final position has already occured, I don't search it.
More clever stuff:
To deduplicate each block (strings where the first half of the bits are the same) I use a bitvector, which is much faster than a hashset, since the final cycle lengths don't need hashing.
Also, I skip the first steps of the cycle checking, because I know that the final cycle can't be shorter than the second-to-last cycle.
After lots of profiling, I can now tell that almost all of the time is being used productively, so algorithmic improvements will be required to improve from here, I think. I also switched to 32 bit integers to save a little more time.
```
//extern crate cpuprofiler;
//use cpuprofiler::PROFILER;
extern crate bit_vec;
use bit_vec::BitVec;
use std::collections::HashSet;
fn cycle_len(num: u32, mask: u32, skip_steps: usize) -> usize {
let mut left = num >> skip_steps;
let mut mask = mask >> skip_steps;
let mut steps = skip_steps;
loop {
left >>= 1;
if left == (num & mask) {
return steps;
}
mask >>= 1;
steps += 1;
}
}
fn all_cycles(size_log: usize) -> HashSet<Vec<usize>> {
let mut set = HashSet::new();
if size_log == 0 {
set.insert(vec![]);
return set;
} else if size_log == 1 {
set.insert(vec![0]);
set.insert(vec![1]);
return set;
}
let size: usize = 1 << size_log;
let half_size: usize = 1 << size_log - 1;
let shift_and_mask: Vec<(usize, u32)> = (1..size_log)
.map(|subsize_log| {
let subsize = 1 << subsize_log;
(size - subsize, (1 << (subsize - 1)) - 1)
})
.collect();
let size_mask = (1 << (size - 1)) - 1;
for block in 0..(1 << (half_size - 1)) as u32 {
let start: u32 = block << half_size;
if block % 1024 == 0 {
eprintln!(
"{} ({:.2}%): {}",
start,
start as f64 / (1u64 << size - 1) as f64 * 100f64,
set.len()
);
}
let leader = {
let mut cycles = Vec::new();
for &(shift, mask) in &shift_and_mask {
let subnum = start >> shift;
cycles.push(cycle_len(subnum, mask, 0));
}
cycles
};
let &end = leader.last().unwrap();
if (end..size).all(|count| {
let mut new = leader.clone();
new.push(count);
set.contains(&new)
})
{
continue;
}
let mut subset = BitVec::from_elem(size, false);
for num in start..start + (1 << half_size) {
subset.set(cycle_len(num, size_mask, end), true);
}
for (unique_cycle_len, _) in subset.into_iter().enumerate().filter(|x| x.1) {
let mut new_l = leader.clone();
new_l.push(unique_cycle_len);
set.insert(new_l);
}
}
set
}
fn main() {
let size: f32 = std::env::args().nth(1).unwrap().parse().unwrap();
let size_log = size.log2() as usize;
//PROFILER.lock().unwrap().start("./my-prof.profile").unwrap();
let cycles = all_cycles(size_log);
//PROFILER.lock().unwrap().stop().unwrap();
println!(
"Number of distinct arrays of periods of bitstrings of length {} is {}",
1 << size_log,
cycles.len()
);
}
```
Put `bit-vec = "0.4.4"` in your Cargo.toml
If you'd like to run this, clone this: github.com/isaacg1/cycle then `Cargo build --release` to build, then `Cargo run --release 32` to run.
[Answer]
# [Rust](https://www.rust-lang.org/), 16
```
use std::collections::HashSet;
use std::io;
fn main() {
print!("Enter a pow of two:");
let mut input_text = String::new();
io::stdin()
.read_line(&mut input_text)
.expect("failed to read from stdin");
let n_as_string = input_text.trim();
match n_as_string.parse::<usize>() {
Ok(n) => {
let log2 = (n as f64).log(2_f64) as usize;
if n != 1 << log2 {
panic!("{} is not a power of two", n);
}
let count = compute_count_array(log2, n);
println!("n = {} -> count = {}", n, count);
}
Err(_) => { panic!("{} is not a number", n_as_string); }
}
}
fn compute_count_array(log2:usize, n: usize) -> usize {
let mut z = HashSet::new();
let mut s:Vec<bool> = vec!(false; n);
loop {
let mut y:Vec<usize> = vec!();
for j in 0..log2+1 {
let p = find_period(&s[0..1<<j]);
y.push(p);
}
z.insert(y);
if !next(&mut s) {
break;
}
}
z.len()
}
#[inline]
fn find_period(s: &[bool]) -> usize {
let n=s.len();
let mut j=1;
while j<n {
if s[0..n-j] == s[j..n] {
return j;
}
j+=1;
}
n
}
#[inline]
fn next(s:&mut Vec<bool>) -> bool {
if s[0] {
s[0] = false;
for i in 1..s.len() {
if s[i] {
s[i] = false;
} else {
s[i] = true;
return true;
}
}
return false
} else {
s[0] = true;
}
true
}
```
[Try it online!](https://tio.run/##dVNNb9swDD3bv4LNgMJGW2Mphh6UOLcCu@1QYJciMFxHbuQ6lCHJS5PCvz2jKOej@zCCgJTIx8dHyvTWHQ69lWDdSohKt62snNJohfhe2vWTdLP4dK30LI5rhE2pMEnhI446o9BdJZNHdNJACZ3egq7BbbWYpLM4aqWDTe9AYde7wsl3Bzk8Ocp6FQLlNqEgoE9pIaiEh2Xff5mR5apoFcrk@jPGRYx874hwMqlL1coVOA0@C2qjN8CAngaHeypYlLawXJ54nAEzOtp4LtGmdNX6Mi7rSmOlEPPeqr1chLajH28JppAv2OEuW/16T5gJQmmhfviWZnSS3Bfe9EecPvPRqgaEqxymMJ@HNAaJuhJVRVp@DKAsoHZBT9I1KDq5BUwZYTgWrXSPXtFKb6gVWbBflMaUu8QjnzJ4Ti0SOlI4VbhbnJI/Bo98G3wO9/iPxiRFaBH@xQz7zYs0PvOsVToDSh3igbfkf6QES0GJIoiSejJseSGOG7MnZuMGnjblfGvFT1nNX7RuFxT3SxK7umytnIWGW607VvUYv@P4MMJjArdaawMNbQJ8zfzA7m@m55F2FFkrXBWdNEqvkmv7TFHT@bxZBlV3WdfbddIF0aKI/veZQiuNS3Z8SLO@QlqwsME2LE/0Qjv6NgpNv33WSr/4JNuXZ4V@45dewMvaVsD1s@93@bdcmNuAcPHgmnxK3nZNrwKaOXJdIsMd4F2zhDwnpyFnGTgZ6XqD0Bzn39x4BP9wyMN4iP4gx11ZwX2dZsHcvOUxQ7kAzwapyTMaZVde9mmWjeQDDU5SI6eIzYu0aABJ5udbZ/pweezhdDCMvYznDBNfYoy0xgQK9VY8HA7Th98 "Rust – Try It Online")
Compilation: `rustc -O <name>.rs`
The string is implemented as a Bool vector.
* The `next` function iterate through the combinations ;
* The `find_period` takes a Bool slice and returns the period ;
* The `compute_count_array` does the job for each "power of two" subsequence of each combinations of Bools.
Theoretically, no overflow is expected until `2^n` exceeds the u64 maximum value, ie `n > 64`. This limit could be outreached with an expensive test on s=[true, true, ..., true].
Bad news is: it returns 317 for n=16, but I don't know why. I don't know either if it will make it in ten minutes for n=32, since the `Vec<bool>` is not optimized for this kind of computation.
**EDIT**
1. I've managed to remove the limit of 64 for `n`. Now, it won't crash until `n` is greater than the max usize integer.
2. I found why the previous code returned 317 for `n=32`. I was counting *sets* of periods and not *arrays* of periods. There were three arrays with the same elements:
````
[1, 2, 3, 3, 8] -> {1, 2, 3, 8}
[1, 2, 3, 8, 8] -> {1, 2, 3, 8}
[1, 1, 3, 3, 7] -> {1, 3, 7}
[1, 1, 3, 7, 7] -> {1, 3, 7}
[1, 1, 3, 3, 8] -> {1, 3, 8}
[1, 1, 3, 8, 8] -> {1, 3, 8}
````
Now it works. It is still slow but it works.
[Answer]
# C - 16
It fails on values greater than 16 cuz of overflow.
I have no idea how fast this runs cuz im on a chromebook running it on repl.it.
Just implements the question as it reads, goes through all bit strings, calculates the period arrays, and checks if they have already been counted.
```
#include "stdio.h"
#include <stdbool.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int per(int s[], int l) {
int period = 0;
while (1) {
period++;
bool check = 1;
int i;
for (i=0; i<l-period; i++) {
if (s[i]!=s[i+period]) {
check = 0;
break;
}
}
if (check) {
return period;
}
}
}
bool perar(int* s, int l, int* b, int i) {
int n = 1;
int j=0;
while (n<=l) {
b[i*l+j] = per(s, n);
n=n<<1;
j++;
}
for (j=0;j<i;j++) {
int k;
bool check = 1;
for(k=0; k<l; k++) {
if (b[j*l+k] != b[i*l+k]) {
check = 0;
break;
}
}
if (check) {
return 0;
}
}
return 1;
}
int main(int argc, char* argv[]) {
int n;
scanf("%d", &n);
puts("Running...");
int i;
int c = 0;
int* a = malloc(n*sizeof(int));
int m=pow(2, n);
int* b = malloc(m*n*sizeof(int));
for (i=0; i<m; i++) {
int j;
for (j=0; j<n; j++) {
a[j] = (i>>j)&1;
}
c+=perar(a, n, b, i);
}
printf("Answer: %d\n", c);
return 0;
}
```
Just compile it with gcc, etc.
[Answer]
## Haskell
```
import qualified Data.Set as S
import Data.Bits
period :: Int -> Int -> Int
period num bits = go (bits-2) (div prefix 2) (clearBit prefix $ bits-1)
where
prefix = (2^bits-1) .&. num
go p x y
| x == y = p
| otherwise = go (p-1) (div x 2) (clearBit y p)
allPeriods :: Int -> [[Int]]
allPeriods n = map periods [0..div(2^n)2-1]
where
periods num = map (period num) powers
powers = takeWhile (<=n) $ iterate (*2) 2
main = readLn >>= print . S.size . S.fromList . allPeriods
```
Compile with `ghc -O2`. [Try it online!](https://tio.run/##XVCxTsMwEN39FW9AKEGKRTMwVKQDYkGqBFIHhqpIprm0Vp3E2C5tEd9OOIdUjZj87r2753e3VX5HxnSdrm3rAj72yuhKU4lHFZRcUIDyWIhB7skHHbwQlpxuS0yneGoCstnoOWvNvsY7N6PApkUSYZanSEr9Ceuo0kfEcm1IOTY9c1f9UDZJBXDYkiN@B6lAkr8NKuS1jF@wyu4WR5wYAt@MigKniAvYgWsDOx20pyGMjQ59kn8hTrCpEMqYl34JP9oQyyWj1WqsNuxXKws71MtbKdmVYzZpnk1W4x3OI3yWv6HkcqgUtj2Q87GvB9wS1I5et9oQkvuiSfkwOpBTgesbzpwLUSsdAzhS5bzBbMb7Os1hJRbS6y/qQeXaeq59ZC/Bu25y97OujNr4LnvOfwE "Haskell – Try It Online")
Runs in less than 0.1sec on my 6 year old laptop hardware for `n=16`. `n=32` takes ~~99~~ 92min, so I'm factor 9 or 10 off. I've tried caching the periods in a lookup table so I don't have to recalculate them over and over again, but this quickly runs out of memory on my 4GB machine.
[Answer]
# Python 2 (PyPy), 16
```
import sys
import math
def do(n):
masks=[]
for i in range(n):
masks+=[(1<<((2<<i)-1))-1]
s=set()
bits=1<<n
for i in xrange(1<<bits):
r=[0,]*n
for j in range(len(masks)):
mask=masks[j]
k,c=i>>bits-(2<<j),1
d=k>>1
while k&mask^d:
d>>=1
mask>>=1
c+=1
r[j]=c
s|={tuple(r)}
return len(s)
print do(int(math.log(int(sys.argv[1]),2)))
```
[Answer]
# [C++], 32, 4 minutes
```
#include <iostream>
#include <vector>
typedef unsigned int u;
template<typename T, typename U>
u Min(T a, U b) {
return a < b ? a : b;
}
template<typename T, typename U>
u Max(T a, U b) {
return a > b ? a : b;
}
u Mask(int n) {
if (n < 0) n = 0;
return ~((u)(-1) << n);
}
u MASKS[32];
inline u Rshift(u v, int n) {
return n < 0 ? v >> (-1*n)
: n > 0 ? v << n
: n;
}
int GetNextPeriodId(u pattern, int pattern_width, int prior_id) {
int period = (prior_id % (pattern_width>>1)) + 1;
int retval = prior_id * pattern_width;
for (; period < pattern_width; period+=1) {
u shift = pattern >> period;
int remainder = pattern_width-period;
u mask = MASKS[period];
for (;remainder >= period && !((pattern ^ shift) & mask);
shift >>= period, remainder -= period);
if (remainder > period) continue;
if (remainder == 0 || !((pattern ^ shift) & MASKS[remainder])) {
retval += (period-1);
break;
}
}
if (period == pattern_width) {
retval += pattern_width-1;
}
return retval;
}
int ParseInput(int argc, char** argv) {
if (argc > 1) {
switch(atoi(argv[1])) {
case 1:
return 1;
case 2:
return 2;
case 4:
return 4;
case 8:
return 8;
case 16:
return 16;
case 32:
return 32;
default:
return 0;
}
}
return 0;
}
void PrintId(u id, int patternWidth) {
for(;patternWidth > 0; id /= patternWidth, patternWidth >>= 1) {
std::cout << (id % patternWidth)+1 << ",";
}
std::cout << std::endl;
}
int TestAndSet(std::vector<bool>& v, int i) {
int retval = v[i] ? 0 : 1;
v[i] = true;
return retval;
}
std::vector<bool> uniques(1<<15);
int uniqueCount = 0;
void FillUniques(u i, int id, int target_width, int final_width) {
int half_size = target_width / 2;
u end = 1u<<(half_size-1);
u mask = MASKS[half_size];
u lowers[] = { i, (~i)&mask };
for (u j = 0ul; j < end; j++) {
u upper = j << half_size;
u patterns[] = { (upper|lowers[0]), (upper|lowers[1]) };
for (int k=0; k < sizeof(patterns)/sizeof(patterns[0]); k+=1) {
int fid = GetNextPeriodId(patterns[k], target_width, id);
if (target_width != final_width) {
FillUniques(patterns[k], fid, target_width*2, final_width);
} else {
if (TestAndSet(uniques, fid)) {
uniqueCount += 1;
}
}
}
}
}
int main(int argc, char** argv) {
for (int i = 0; i < 32; i++) {
MASKS[i] = Mask(i);
}
int target_width = 32; // ParseInput(argc, argv);
if (!target_width) {
std::cout << "Usage: " << argv[0] << " [1|2|4|8|16|32]" << std::endl;
return 0;
}
if (target_width == 1) {
std::cout << 1 << std::endl;
return 0;
}
FillUniques(0, 0, 2, target_width);
std::cout << uniqueCount << std::endl;
return 0;
}
```
] |
[Question]
[
You are to golf a program that will take a filename as input and you must output what color the file is.
The file will have any one of these extensions but your program only needs to support one. Please say which one in your answer.
* `.jpg`
* `.png`
* `.svg`
* `.gif`
* `.bmp`
And now to the classic layout.
# Input
A filename with one of the above extensions.
You may also take an image object or already encoded image instead.
# Output
The only color in that file as a 6 digit hex code with an *optional* leading `#` e.g. `#000000` is black.
You may also output a list/tuple/string containing the decimal or hex values of the RGB color, with a clear, non-numeric delimiter e.g. `,` `|` etc
You may not output the transparency.
If the file isn't all one color, you must output a falsy value that isn't `#000000` and terminate **without** printing anything to `STDERR`. This is so that you can't simply open the file and get the RGB value of the first pixel.
# Rules
* The hex code only needs to be outputted if the file is all one color.
* The file will be `500x500` pixels
* The pixels will all have 0% transparency.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins!
# Examples
* [#16C293](https://pasteboard.co/8bawQk5kM.png)
* [#8B16C2](https://pasteboard.co/8b9foR0H6.png)
* [#959090](https://pasteboard.co/8baglmIE8.png)
* [#84F00C](https://pasteboard.co/8b9Uhhovn.png)
* [Falsy Value](https://pasteboard.co/8bb4DeKx3.png)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~15~~ 12 bytes
```
Yi6Bed~?2MYm
```
Tested with the ".png" images given in the challenge. It probably works with other extensions too. Input can be a filename or a URL of the image.
Output is R, G, B decimal values separated by spaces, or the empty string (which is falsy) if there are more than one color.
Example with first and last test cases:
[](https://i.stack.imgur.com/vuuTp.png)
### Explanation
```
Yi % Implicitly input filename. Read image as an M×N×3 array
6B % Push [true true false] (6 in binary)
e % Reshape. This collapses firsts two dimensions. Gives an (M*N)×3 array
d % Consecutive diferences down each column. Gives an an (M*N-1)×3 array
~? % If all those differences are zero (this means there is a single color)
2M % Push the (M*N)×3 array again
Ym % Mean of each column
% Implicit end
% Implicitly display
```
[Answer]
# Bash + core-utils + Imagemagick, 60
```
a=(`convert $1 txt:|sort -uk3`)
((${#a[@]}-9))||echo ${a[2]}
```
Outputs the colour if there is one colour and nothing if there is more than one colour.
* `convert $1 txt:` reads the input file and outputs as a text file, specifically in this format:
```
# ImageMagick pixel enumeration: 500,500,255,srgba
0,0: (245,236,236,1) #F5ECEC srgba(245,236,236,1)
1,0: (245,236,236,1) #F5ECEC srgba(245,236,236,1)
2,0: (245,236,236,1) #F5ECEC srgba(245,236,236,1)
3,0: (245,235,235,1) #F5EBEB srgba(245,235,235,1)
4,0: (245,235,235,1) #F5EBEB srgba(245,235,235,1)
```
* `sort -uk3` uniquely sorts this by the third column. This output is assigned to an array `a`
* `((${#a[@]}-9))` tests if the array does NOT have length 9
* if the array does NOT NOT have length 9 (i.e. it does have length 9), then output element 2 (0-based) which will be the unique colour.
[Answer]
# JavaScript (ES6) + HTML, ~~315~~ ~~289~~ ~~243~~ ~~218~~ ~~217~~ ~~215~~ ~~211~~ ~~210~~ 208 bytes
~~Checking that all pixels were identical added a *lot* of bytes.~~ Down to it not being much bigger than when I was just checking the colour of the first pixel - happy with that :)
Takes the URL (absolute, relative, data or anything that can be used as the `src` of an `img`) of the image file as input. Outputs the RGB colour as a comma separated string or `0` for falsey. Tested with PNG files but should work with JPG & GIF too.
```
u=>(a=[...Array(c.width=c.height=500)]).map((_,x)=>a.map((_,y)=>(v=""+[(d=g.getImageData(x,y,1,1).data)[0],d[1],d[2]],h=x&y?v!=h?0:h:v)),i.src=u,(g=c.getContext`2d`).drawImage(i,0,0))&&h
```
```
<img id=i><canvas id=c
```
---
## Try it
Requires the addition of a closing `>` on the `canvas` element in order to work in a Snippet. As pulling images in from external sources would cause an error to be thrown, the following will instead take Base-64 data URLs as input. Uncomment the last line to test for different colours using an image consisting of the 4 test colours.
```
f=
u=>(a=[...Array(c.width=c.height=500)]).map((_,x)=>a.map((_,y)=>(v=""+[(d=g.getImageData(x,y,1,1).data)[0],d[1],d[2]],h=x&y?v!=h?0:h:v)),i.src=u,(g=c.getContext`2d`).drawImage(i,0,0))&&h
console.log(f("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AQMAAADxGE3JAAAAA1BMVEUWwpMvG5UqAAAANUlEQVR42u3BMQEAAADCIPun9lkMYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5fQAAASJ0bysAAAAASUVORK5CYII"))
//console.log(f("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AgMAAAC2uDcZAAAADFBMVEWLFsIWwpOVkJCE8Az9F2TyAAABB0lEQVR42uzNIQEAMAwDsEk8ucmTS9xElAwkBlI3cipit9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91uX72/yO+I3W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdPhu1fdT2UdtHbR+1fdT2UdsHs+0AqVGfBnNZ7+UAAAAASUVORK5CYII"))
```
```
<img id=i><canvas id=c>
```
[Answer]
# Python 2, 80 bytes
```
from PIL import Image
i=Image.open(input()).getcolors(1)
print i and i[0][1][:3]
```
PIL.Image has a getcolors function which returns `None` if the number of colors is bigger than the parameter and returns a histogram of the colors in a `[(pixels, (r,g,b,a)), ...]` structure.
[Answer]
## Mathematica, ~~55~~ 51 Bytes
-4 thanks to CalculatorFeline
+0 for refactoring into full function.
Using Mathematica image object as input - `Import["filename.png"]`.
```
If[Length@#==1,#,0]&@Union[Join@@ImageData@#]&
```
Returns 0 if not all one color. Outputs the decimal value of the color if just one.
Explanation:
```
ImageData@# & - Convert input into 2D array of RGB values
Join@@ - Join the array into 1D array f RGB values
Union[ ] - Union all the RGB values
Length@# &@ - Find length of the union of arrays
If[ ==1,#,0] - Check if its 1, return it if true, return 0 if not
```
[Answer]
# Java 8+, ~~331~~ ~~165~~ 119 bytes
```
i->{Integer j=i.getRGB(0,0),k=500,l;for(;k-->0;)for(l=500;l-->0;)if(i.getRGB(k,l)!=j)return"";return j.toHexString(j);}
```
-a lot of bytes thanks to @LethalCoder for updating me on a rule change that allowed for a lot of golfing
-46 bytes thanks to @KevinCruijssen and fixed typo
[Answer]
# [Python 2](https://docs.python.org/2/), ~~123~~ 85 bytes
```
from PIL import Image
c=Image.open(input()).getdata()
print len(set(c))<2and c[0][:3]
```
[Answer]
# C, ~~224~~ 205 bytes
```
m[3],i;
main(c,v)char**v;{
void*s=fopen(v[1],"r");
for(;i<54;i++)getc(s);
m[2]=getc(s);m[1]=getc(s);*m=getc(s);
for(i=0;i<500*500;i++)if((c=getc(s))!=m[i%3]&&~c)exit(puts("0"));
printf("%d,%d,%d",*m,m[1],m[2]);}
```
Takes a 500x500 bitmap as a command-line argument. Prints the RGB of the file, e.g. `255,255,255`, or `0` if the file is not constant. Probably crashes badly if no file is provided.
Interesting points to note:
* Uses `void*` in the place of `FILE*` to avoid including `<stdio.h>`
* Uses a simple `for` loop with `i%3` to determine if all bytes are the same
* Can be *very* golfed, I golfed 50 bytes while writing this answer
* BMP stores colors as BGR so it more/less reads backwards
[Answer]
# C#, ~~163~~ ~~128~~ 125 bytes
```
b=>{var c=b.GetPixel(0,0);for(int w=500,h;w-->0;)for(h=500;h-->0;)if(b.GetPixel(w,h)!=c)return"";return c.R+" "+c.G+" "+c.B;}
```
*Saved 3 bytes thanks to @Kevin Cruijssen.*
If we didn't have to have the additional check for the image being the same colours this is only 55 bytes:
```
b=>{var c=b.GetPixel(0,0);return c.R+" "+c.G+" "+c.B;};
```
[Answer]
## Mathematica, 112 bytes
image
>
> i=Import@"c:\a.png";
>
>
>
```
If[Length@DominantColors@i==1,"#"<>StringPadLeft[IntegerString[Most@PixelValue[i,{1,1},"Byte"],16],2,"0"],False]
```
[Answer]
# Bash + ImageMagick, 100 bytes
```
i=$(expr `identify -format "%k" $1` = 1)&&convert $1 -format "%c" histogram:info:-|grep -o "#......"
```
Tested with .png, should work with the other formats as well. The output for a polychromatic image is simply an empty string.
[Answer]
# JavaScript + HTML, 143 + 23 = 166 bytes
```
u=>(i.src=u,s=C.width=C.height=500,c=C.getContext`2d`,c.drawImage(i,0,0),d=c.getImageData(0,0,s,s).data,!d.some((n,i)=>n-d[i%4])&&d.slice(0,3))
```
```
<img id=i><canvas id=C>
```
### Try it:
```
f=
u=>(i.src=u,s=C.width=C.height=500,c=C.getContext`2d`,c.drawImage(i,0,0),d=c.getImageData(0,0,s,s).data,!d.some((n,i)=>n-d[i%4])&&d.slice(0,3))
console.log(
f('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AQMAAADxGE3JAAAAA1BMVEUWwpMvG5UqAAAANUlEQVR42u3BMQEAAADCIPun9lkMYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5fQAAASJ0bysAAAAASUVORK5CYII'),
f('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0AgMAAAC2uDcZAAAADFBMVEWLFsIWwpOVkJCE8Az9F2TyAAABB0lEQVR42uzNIQEAMAwDsEk8ucmTS9xElAwkBlI3cipit9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91uX72/yO+I3W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdbrfb7Xa73W632+12u91ut9vtdrvdPhu1fdT2UdtHbR+1fdT2UdsHs+0AqVGfBnNZ7+UAAAAASUVORK5CYII')
)
```
```
<img id=i><canvas id=C>
```
Less golfed:
```
u => {
i.src = u
s = C.width = C.height = 500
c = C.getContext('2d')
c.drawImage(i, 0, 0)
d = c.getImageData(0, 0, s, s).data
return d.every((n,i) => n == d[i % 4]) && d.slice(0,3)
}
```
[Answer]
# PowerShell, 79 bytes
```
param($b)if(!($c=499..0*500|%{$b|% G*l $_ $y;$y+=!$_}|gu).Rank){$c.R;$c.G;$c.B}
```
Less golfed test script:
```
$f = {
param($b)
$c=499..0*500|%{$b.GetPixel($_,$y);$y+=!$_}|gu
if(!$c.Rank){
$c.R;$c.G;$c.B
}
}
@(
,("22 194 147", "https://cdn.pbrd.co/images/8bawQk5kM.png")
,("139 22 194", "https://cdn.pbrd.co/images/8b9foR0H6.png")
,("149 144 144","https://cdn.pbrd.co/images/8baglmIE8.png")
,("132 240 12", "https://cdn.pbrd.co/images/8b9Uhhovn.png")
,("", "https://cdn.pbrd.co/images/8bb4DeKx3.png")
) | % {
$expected,$s = $_
$binData = [System.Net.WebClient]::new().DownloadData($s)
$memoryStream = [System.IO.MemoryStream]::new($binData)
$bitmap = [System.Drawing.Bitmap]::FromStream($memoryStream)
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$result = &$f $bitmap
"$("$result"-eq$expected): $($sw.Elapsed): $result"
}
```
* *Note 1*: expression `499..0*500` means: repeat 500 times an range from 499 downto 0
* *Note 2*: expression `$b|% G*l $_ $y` [is shortcut](https://codegolf.stackexchange.com/a/111526/80745) for `$b.GetPixel($_,$y)`. This trick is usefull with gofing, but it slows down the code.
Output with `$b|% G*l $_ $y`:
```
True: 00:01:45.4904622: 22 194 147
True: 00:01:56.4208157: 139 22 194
True: 00:01:46.7629439: 149 144 144
True: 00:01:48.1999005: 132 240 12
True: 00:01:55.8579935:
```
Output with `$b.GetPixel($_,$y)`:
```
True: 00:00:05.7637937: 22 194 147
True: 00:00:06.8743244: 139 22 194
True: 00:00:08.7456055: 149 144 144
True: 00:00:08.5942450: 132 240 12
True: 00:00:06.6495706:
```
Explanation:
* the script creates an array of each pixel color.
* the script applies `gu` (alias for [Get-Unique](https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Get-Unique)) to the array of color.
* if the result of `hu` is a single element (property `rank` has value for an array only) then output decimal value of R,G,B of this element
[Answer]
**Python 2 + OpenCV + NumPy: 66 characters**
colors.py
```
import numpy as N
def c(i):p=i[0,0];print(p[::-1],"")[N.any(i-p)]
```
test.py
```
import cv2
from colors import c
c(cv2.imread('16C293.png'))
c(cv2.imread('84F00C.png'))
c(cv2.imread('8B16C2.png'))
c(cv2.imread('959090.png'))
c(cv2.imread('falsy.png'))
```
Result:
```
18:14 ~/colors $ python test.py
[ 22 194 147]
[132 240 12]
[139 22 194]
[149 144 144]
18:15 ~/colors $
```
OpenCV is able to read an image and return it as an N-dimensional array. NumPy is used to test the first pixel against the others and either print out the RGB values or blank.
[Answer]
# PHP, 88 bytes
```
function($i){return~-imagecolorstotal($i)?0:sprintf("#%06x",imagecolorsforindex($i,0));}
```
anonymous function takes an indexed PHP image resource as parameter, assumes color in first palette slot, returns color code or 0.
**program, 96 bytes**
```
imagecolorstotal($i=imagecreatefromgif($argv[1]))-1||sprintf("#%06x",imagecolorsforindex($i,0));
```
takes GIF file name from argument, prints color code or nothing. Run with `php -r '<code>' <filename.gif>`.
## for true color images, ~~113~~ 112 bytes
```
function($i){for(;$p<25e4;$p++)$r[$c=imagecolorat($i,$p%500,$p/500)]=1;return~-count($r)?0:sprintf("#%06x",$c);}
```
as above, but requires true color image.
**program, ~~122~~ 116 bytes**
```
for(;$p<25e4;$p++)$r[$c=imagecolorat(imagecreatefrompng($argv[1]),$p%500,$p/500)]=1;count($r)-1||printf("#%06x",$c);
```
as above, but requires PNG file.
] |
[Question]
[
Your task is to write a program that outputs its own source code in reverse. However, when the reversed code is run, it should output the source code, facing the correct direction.
## Example
Say your program is `abc`. When run, it should output `cba`. `cba`, when run, should output `abc`.
## Rules
Your program should follow all the rules of a [proper quine](https://codegolf.meta.stackexchange.com/a/4878) (except for outputting the source code).
Palindromes are disallowed.
Random note:
I am aware of [this](https://codegolf.meta.stackexchange.com/questions/8047/things-to-avoid-when-writing-challenges/8595#8595) but I believe that this challenge is different because the transformed code must have the same properties.
[Answer]
# [Befunge-98](https://github.com/catseye/FBBI), 33 bytes
```
b3*>1#;-:0g,:#;_@_;#:,g0:-;#1>*b3
```
[Try it online!](https://tio.run/nexus/befunge-98#@59krGVnqGyta2WQrmOlbB3vEG@tbKWTbmCla61saKeVZPz/v6GRMQA "Befunge-98 – TIO Nexus")
[Answer]
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 3 bytes
```
1
2
```
*Thanks to @MartinEnder for reminding me about [this answer](https://codegolf.stackexchange.com/a/103262/12012).*
[Try it online!](https://tio.run/nexus/rprogn#@2/IZfT/PwA "RProgN – TIO Nexus")
### How it works
This exploits a potential flaw in our [definition of proper quine](http://meta.codegolf.stackexchange.com/a/4878/12012):
>
> It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)
>
>
> Furthermore, a quine must not access its own source, directly or indirectly.
>
>
>
That's obviously the case here, as the output is the reverse of the code and the code is not a palindrome.
RProgN – *reverse* programmer notation – uses a LIFO stack and prints the items on it in the order they are popped. The two tokens **1** and **2**, separated by spaces and/or newlines, get popped in reverse order and are printed separated by a newline.
This prints the reversed program
```
2
1
```
which, in turn, prints the original one.
[!enilno ti yrT](https://tio.run/nexus/rprogn#@2/EZfj/PwA "RProgN – TIO Nexus")
[Answer]
## [Fission 2](https://github.com/C0deH4cker/Fission), 10 bytes
```
"L;L'!+!'_
```
[Try it online!](https://tio.run/nexus/fission2#@6/kY@2jrqitqB7//z8A "Fission 2 – TIO Nexus")
This prints:
```
_'!+!'L;L"
```
[Try it online!](https://tio.run/nexus/fission2#@x@vrqitqO5j7aP0/z8A "Fission 2 – TIO Nexus")
And vice versa.
### Explanation
This is a modification of the [reverse quine](https://codegolf.stackexchange.com/a/50970/8478). It's working to our advantage here that `!` is used for printing and is also only one code point away from the the quote `"`. That makes it easier to make the quote printing section palindromic (the `'!+!'`). Let's start with the first code:
```
"L;L'!+!'_
```
This program has two entry points at the `L`s, which each creates a left-going atom. However, the right one immediately hits the `;` which destroys it. The left one enters string mode and wraps around to the end, so that it prints the entire code (except the `"`) from back to front. That already gives us `_'!+!'L;L`. All that's left is to print the `"`. `_` can be ignored, `'!` sets the atom's mass to 33 (the code point of `!`), `+` increments it to `"`, and `!` prints it. That's all the output done. The `'L` sets the atoms mass to the code point of `L` but that's irrelevant. `;` destroys this atom as well and since no atoms are left, the program terminates.
Now the other way round:
```
_'!+!'L;L"
```
Again, we have two entry points but one atom is immediately destroyed. This time we move through the `!+!'` section first, so we start by printing a quote. The `'_` is again irrelevant, but we need the `_` (or some other useless character) here to avoid `'` escaping the `"`. The atom wraps to the end, traverses the source code once in string mode to print the rest of the program in reverse, the `L` is then ignored and `;` destroys the atom and terminates the program.
[Answer]
# <><, 19 bytes
```
"rf2+2*rol?!;70.05;!?lor*d3r'
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiXCJyZjIrMipyb2w/ITs3MC4wNTshP2xvcipkM3InIiwiaW5wdXQiOiJiYmJhY2RlZmFhYSIsInN0YWNrIjoiIiwibW9kZSI6Im51bWJlcnMifQ==)
**Reversed**
```
'r3d*rol?!;50.07;!?lor*2+2fr"
```
[it yrT](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiJ3IzZCpyb2w/ITs1MC4wNzshP2xvcioyKzJmclwiIiwiaW5wdXQiOiJiYmJhY2RlZmFhYSIsInN0YWNrIjoiIiwibW9kZSI6Im51bWJlcnMifQ==)
So I'm not super sure if this is a proper quine. Let me know what your opinion is, I'll delete the post if people think it's invalid.
I use the `'` to switch into quoting mode that will push the code raw into the stack. Then when the pointer wraps around it will exit the quote again. However, I do need to manually add the `'` quote character at the end as `d3*`, and `"` as `rf2+2`. These would count as "code that encodes a different part of the program".
] |
[Question]
[
In this challenge, you will remove duplicate words from each **sentence**.
## Examples
```
Hello Hello, World!
Hello, World!
Code Code! Golf Code
Code! Golf Code
Hello hello World
Hello World
Programming Golf Programming!
Programming Golf!
```
## Specification
* Input will be a string of ASCII characters.
* A sentence is defined as anything until the end of the string, a linefeed (`\n`), or punctuation (`.!?`).
* A word is defined as a sequence of `A-Za-z`.
* Words are case insensitive (`Hello` == `heLlO`).
* Only the first occurrence of a word in a sentence is kept.
* If a word is removed, the spaces *before* the removed word should be removed. (e.g. `A A B` -> `A B`).
* As always [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins!
[Answer]
# JavaScript (ES6), 98
*Note* while I found it myself, it's annoyingly similar to @Neil's, just with the additional logic to split the whole input string in sentences.
```
s=>s.replace(/[^\n.!?]+/g,s=>s.replace(/ *([a-z]+)/ig,(r,w)=>k[w=w.toUpperCase()]?'':k[w]=r,k=[]))
```
**Test**
```
f=s=>s.replace(/[^\n.!?]+/g,s=>s.replace(/ *([a-z]+)/ig,(r,w)=>k[w=w.toUpperCase()]?'':k[w]=r,k=[]))
console.log=x=>O.textContent+=x+'\n'
;[['Hello Hello, World!','Hello, World!']
,['Code Code! Golf Code','Code! Golf Code']
,['Hello hello World','Hello World']
,['Programming Golf Programming!','Programming Golf!']]
.forEach(t=>{
var i=t[0],k=t[1],r=f(i)
console.log((r==k?'OK ':'KO ')+i+' -> '+r)
})
```
```
<pre id=O></pre>
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~66~~ 46 bytes
Byte count assumes ISO 8859-1 encoding.
```
i`[a-z]+
·$0·
i` *(·[a-z]+·)(?<=\1[^.!?¶]+)|·
```
[Try it online!](http://retina.tryitonline.net/#code=aWAgKig_PCFbYS16XSkoW2Etel0rKSg_IVthLXpdKSg_PD0oPzwhW2Etel0pXDEoPyFbYS16XSlbXi4hP8K2XSspCg&input=SGVsbG8gSGVsbG8sIFdvcmxkIQpDb2RlIENvZGUhIEdvbGYgQ29kZQpIZWxsbyAgaGVsbG8gICBXb3JsZApQcm9ncmFtbWluZyBHb2xmIFByb2dyYW1taW5nIQ)
### Explanation
Since only letters should be considered word characters (but regex treats digits and underscores as word characters, too), we need to make our own word boundaries. Since the input is guaranteed to contain only ASCII characters, I'm inserting `·` (outside of ASCII, but inside ISO 8859-1) around all words and remove them again with the duplicates. That saves 20 bytes over using lookarounds to implement generic word boundaries.
```
i`[a-z]+
·$0·
```
This matches every word and surrounds it in `·`.
```
i` *(·[a-z]+·)(?<=\1[^.!?¶]+)|·
```
This is two steps compressed into one. `<sp>*(·[a-z]+·)(?<=\1[^.!?¶]+)` matches a full word (ensured by including the `·` in the match), along with any spaces preceding it, *provided that* (as ensured by the lookbehind) we can find the same word somewhere earlier in the sentence. (The `¶` matches a linefeed.)
The other part is simply the `·`, which matches all artificial word boundaries that weren't matched as part of the first half. In either case, the match is simply removed from the string.
[Answer]
# C, 326 bytes
Who needs regular expressions?
```
#include <ctype.h>
#define a isalpha
#define c(x)*x&&!strchr(".?!\n",*x)
#define f(x)for(n=e;*x&&!a(*x);++x);
main(p,v,n,e,o,t)char**v,*p,*n,*e,*o,*t;{for(p=v[1];*p;p=e){f(p)for(e=p;c(e);){for(;a(*++e););f(n)if(c(n)){for(o=p,t=n;a(*o)&&(*o-65)%32==(*t-65)%32;o++,t++);if(a(*t))e=n;else memmove(e,t,strlen(t)+1);}}}puts(v[1]);}
```
[Answer]
# Vim, 27 bytes
```
:s/\v\c(<\a+>).{-}\zs\s+\1
```
Note that the 27 bytes is including a trailing carriage return at the end.
[Try it online!](http://v.tryitonline.net/#code=OiVzL1x2XGMoPFxhKz4pLnstfVx6c1xzK1wxCg&input=SGVsbG8gSGVsbG8sIFdvcmxkIQpDb2RlIENvZGUhIEdvbGYgQ29kZQpIZWxsbyAgaGVsbG8gICBXb3JsZApQcm9ncmFtbWluZyBHb2xmIFByb2dyYW1taW5nIQ) Side note: This is a link to a different language I'm writing called "V". V is *mostly* backwards compatible with vim, so for all intents and purposes, it can count as a vim interpreter. I also added one byte `%` so that you can verify all test cases at once.
Explanation:
```
:s/\v "Substitute with the 'Magic flag' on. This magic flag allows us
"to shorten the regex by removing a lot of \ characters.
\c(<\a+>) "A case-insensitive word
.{-} "Any character (non-greedy)
\zs "Start the selection. This means everything after this atom
"will be removed
\s+ "One or more whitespace characters,
\1 "Followed by the first word
```
[Answer]
# [Perl 6](http://perl6.org), 104 bytes
```
{[~] .split(/<[.!?\n]>+/,:v).map(->$_,$s?{.comb(/.*?<:L>+/).unique(as=>{/<:L>+/;lc $/}).join~($s//'')})} # 104
```
### Usage:
```
# give it a lexical name
my &code = {...}
say code "Hello Hello, World!
Code Code! Golf Code
Hello hello World
Programming Golf Programming!";
```
```
Hello, World!
Code! Golf Code
Hello World
Programming Golf!
```
### Explanation
```
{
[~] # join everything that follows:
.split(/<[.!?\n]>+/,:v) # split on boundaries, keeping them
.map( # loop over sentence and boundary together
-> $_, $s? { # boundary is optional (at the end of the string)
.comb(/.*?<:L>+/) # grab the words along with leading non letters
.unique( # keep the unique ones by looking at …
as => {/<:L>+/;lc $/} # only the word chars in lowercase
)
.join # join the sentence parts
~ # join that with …
($s//'') # the boundary characters or empty string
}
)
}
```
[Answer]
## Perl 5, 57 bytes
**56 bytes code + 1 for `-p`**
```
s/[^.!?
]+/my%h;$&=~s~\s*([A-z]+)~!$h{lc$1}++&&$&~egr/eg
```
### Usage:
```
perl -pe 's/[^.!?
]+/my%h;$&=~s~\s*([A-z]+)~!$h{lc$1}++&&$&~egr/eg' <<< 'Hello Hello, World!
Code Code! Golf Code
Hello hello World
Programming Golf Programming!
'
Hello, World!
Code! Golf Code
Hello World
Programming Golf!
```
Might need to be +1, currently I'm assuming that there will only be spaces in the input, no tabs.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
x=>x.replace(/(?<=\b(\w+)\b[^.!?\n]*) +\1\b/ig,'')
```
[Try it online!](https://tio.run/##bY2xDoIwFEV3v6JMbQUhzooMDjq6OVhNCrQV8@gjxSh/X4UuxrDc93Jzcu5DvmRfuaZ7rizWyuvcD/luSJ3qQFaKZazY5qJk4h1zUV5uaVQIe11yEou1KLPGJJRyv1lUaHsElQIaphk9KgAkUybkjA7qiHL@T@2/i2SMiBwQ9PTOYEFG7uEE3Qx2cmicbNvGmqD7KcZ1/wE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) with -p option, 27 + 1 = 28 bytes
```
s/\A(\w+)[^.!?]*\K\s+\1//gi
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP8ZRI6ZcWzM6Tk/RPlYrxjumWDvGUF8/PfP/f4/UnJx8BTCpoxCeX5STosjlnJ@SqgAiFBXc83PSwEwuiEKFDAgFUcoVUJSfXpSYm5uZlw5RiiSg@C@/oCQzP6/4v24BAA "Perl 5 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 39 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ô┘ⁿ=3⌠↕ê║▌ßa⌡ô½â╖¬╥▓lå3Öîz╝╥'n┐←ûl₧'○0T
```
[Run and debug it](https://staxlang.xyz/#p=93d9fc3d33f41288badde161f593ab83b7aad2b26c8633998c7abcd2276ebf1b966c9e27093054&i=Hello++hello+++World%0AHello+Hello,+World%21%0ACode+Code%21+Golf+Code%0AProgramming+Golf+Programming%21&m=2)
I'm not sure if Stax's JS regex has the features to match up with Vim regex, but nested regex works!
## Explanation
```
'!+".+?[\n!?]"{cV^{c:~\{:}m$"\s*"s+{i!*}Rc}Rd}RNd
'!+ append an ! to the string
".+?[\n!?]" match anything(non-greedy),
followed by a sentence terminator
{ }R replace each sentence with:
c copy it
V^ /[a-zA-Z]+/
{ }R for each regex word match:
c copy the word
:~ toggle case
\ zip the two
{:}m embed each pair in square brackets
$ flatten
"\s*"s+ prepend \s*
Example for "wOrd":
"\s*[wW][Oo][rR][dD]"
{ }R replace each occurrence of word with:
i! index negated (1 if first)
* multiply with word
c copy
d delete the faulty replaced string
Nd remove last !
```
] |
[Question]
[
Your friend is trying to break into a vault that has a peculiar locking system: it requires a certain number of gentle knocks in a particular spot. Your friend discovered the number (which is in the range 1...99999) and possesses a gadget that produces the required knocks. However, the gadget is a Brainfuck interpreter! So your friend needs to feed it a Brainfuck program, which, obviously, should be as short as possible (the gadget's I/O is slow).
Your task is to help him! Write a program or a subroutine, in any language, that accepts as input a number `N`, and outputs a Brainfuck program, which takes no input and outputs a string of printable ASCII characters (excluding the space character - codes in the range 33...126) of length `N`.
Example: for input `10`, the output might be
```
+++++++++++++++++++++++++++++++++..........
```
(but I am sure it can be shortened!)
Your score will be the sum of lengths of your outputs for the following values of `N` (they are random numbers):
```
55
68
15
28
841
838
522
846
4898
9004
9363
3810
13230
67175
37231
44701
```
Oh, and you will be transmitting your code (the generator program) to your friend by Twitter. So make sure it's [140 characters](https://dev.twitter.com/overview/api/counting-characters) or less!
---
P.S. The Brainfuck language has many variants. Let's assume the tape is infinite in both directions (or "circular and large enough"), and the cells have 32-bit int capacity (finite and able to hold numbers up to 99999). Also, no wrapping: when a cell overflows, the machine self-destructs!
[Answer]
## BrainF\*\*\*, score: 193,313
It's not under 140 characters (it's 147, so close!!), so this can't win, but I thought it was cool.
Prints 43 plus signs, then `N` periods. Not very optimal.
```
>++++++[>+++++++<-]>+[->+>+<<]>[->.<]<<+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]>>>+++<<<<[>>>>.<<<<-]
```
If anyone can help shorten this I would love it.
[Answer]
# J, Total score = 1481
*(For my previous entry and explanation check revision history.)*
```
f10=.('>++++++++++<';'')rplc~;@([:(<@('+++++[>+++++++<-]>>+',;@((<'[>++++++++++')#~#)),[<@(']',~'<-','<.>'#~],[,])"0 #-i.@# )10#.inv])
```
This function generates nested BF loops based on the base10 digits of the input number. Checking all reasonable bases and choosing the smallest BF code would improve the score with a small amount.
BF programs for the test set:
```
f10 every 55 68 15 28 841 838 522 846 4898 9004 9363 3810 13230 67175 37231 44701
+++++[>+++++++<-]>>+[>++++++++++[-<<.....>>]<-<.....>]
+++++[>+++++++<-]>>+[>++++++++++[-<<......>>]<-<........>]
+++++[>+++++++<-]>>+[>++++++++++[-<<.>>]<-<.....>]
+++++[>+++++++<-]>>+[>++++++++++[-<<..>>]<-<........>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[-<<<........>>>]<-<<....>>]<-<.>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[-<<<........>>>]<-<<...>>]<-<........>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[-<<<.....>>>]<-<<..>>]<-<..>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[-<<<........>>>]<-<<....>>]<-<......>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[-<<<<....>>>>]<-<<<........>>>]<-<<.........>>]<-<........>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[-<<<<.........>>>>]<-<<<>>>]<-<<>>]<-<....>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[-<<<<.........>>>>]<-<<<...>>>]<-<<......>>]<-<...>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[-<<<<...>>>>]<-<<<........>>>]<-<<.>>]<-<>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[>++++++++++[-<<<<<.>>>>>]<-<<<<...>>>>]<-<<<..>>>]<-<<...>>]<-<>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[>++++++++++[-<<<<<......>>>>>]<-<<<<.......>>>>]<-<<<.>>>]<-<<.......>>]<-<.....>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[>++++++++++[-<<<<<...>>>>>]<-<<<<.......>>>>]<-<<<..>>>]<-<<...>>]<-<.>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[>++++++++++[-<<<<<....>>>>>]<-<<<<....>>>>]<-<<<.......>>>]<-<<>>]<-<.>]
```
Computing score on the test set:
```
+/#@> f10 each 55 68 15 28 841 838 522 846 4898 9004 9363 3810 13230 67175 37231 44701
1481
```
[Answer]
## Python 2, score: 1021
I've just realized that this contest is pretty old but still, since I came up with a better solution than those posted, I posted it as well.
Here's a 102 byte python script that does the job:
```
n=input()
s='>'
while n:
s+='>'+'+'*(n%5+1);n/=5
print s+'[->[-<+++++>]<<]<+++++++[>+++++<-]>>[-<.>]'
```
The idea is to use base 5 encoding for N (best base at least for the current inputs, which do not seem very "random" by the way, looks like they were arbitrarily chosen by OP), and to write a generic Brainfuck algorithm to decode a number of arbitrary length (the number is encoded with each digit increased by one in order to detect the end of conversion). I chose to print character 35 `#`, character 36 `$` is equivalent.
You may run the following bash script to get the score:
```
i=0
while read p; do
i=$((i+`echo $p | python convert.py | wc -m`))
done
echo $i
```
With a more advanced program that replaces encoding with multiplication for small numbers and chooses the best base for encoding each number, I can reach 958 Brainfuck characters, but Python is far too verbose (and I'm a pretty bad/lazy golfer) in order to get the converter into 144 bytes!
[Answer]
# Pyth, 1702
Reconstruct numbers using factors of N + x.
```
+holN+]++">>"*"+"Q"<<"mjk(">>"j">"m*"+"kP+Qd"<[[->[->+>+<<]>>[-<<+>>]<<<]>[-]>[-<<+>>]<<<]>"*"-"d"<<")50"++++++[>++++++<-]>>[<.>-]"
```
[Answer]
# CJam, 52 74 108 bytes, total = 1304 1244 1210
```
ri5b_,1>{(_3<{\(@5*+}*\+}*W%)\{T+_2>:T5*-_0>"-+"=\z*}%\T+'+*a+W%{"[->+++++<]>"\}*">x[>x<-]<[->>.<<]"'x/'+6**
```
A test script (slow in the online interpreter):
```
q~]
{
_[0:T;
5b_,1>{(_3<{\(@5*+}*\+}*W%)\{T+_2>:T5*-_0>"-+"=\z*}%\T+'+*a+W%{"[->+++++<]>"\}*">x[>x<-]<[->>.<<]"'x/'+6**
]s
_[L:RL@0\
"-+><.]"['('){+\_{)}0?@\}{@\+\_{)}0?}{R1$c+:R;}]:`"]a"{{_aa+1$4G#%{:~~1}{;0}?}g}`+a+er:~:~
];R,@=!"Error."N+*o
}%s,
```
[Answer]
# Befunge-98, N + 41, total = 193281
```
&>'+\:v
v^-1,\_
' >1-:v
>v^,+'_
,' :
>ff3++^
>2f*+v
^>/9+:,
>'>,61v
, v*6+<
^/2,:<@
v >+2+,
>'<,']^
```
I know it's bad, but I felt like writing some Befunge today. The best part of Befunge is that the programs are even less understandible than the actual golf languages, especially when they reuse code :D
Uses a similar algorithm to Martin Büttner's [CJam answer](https://codegolf.stackexchange.com/a/47904/30164):
```
(N +'s)>+++++++++++++++++++++++++++++++++<[->.<]
```
[Answer]
# CJam, 40 + N, Total: 193265
```
'+33*'>'+l~*"[<.>-]"
```
Just to get this started, here is the baseline solution. It generates the following code:
```
+++++++++++++++++++++++++++++++++>_[<.>-]
```
where `_` is `N` copies of `+`.
[Run the generator here.](http://cjam.aditsu.net/#code='%2B33*'%3E'%2Bl~*%22%5B%3C.%3E-%5D%22&input=55)
[Answer]
## Befunge-93 - 24 + N, total = 193009
```
&>">>]-<]-<++++>[++++>[+++"v
v ,,,,,,,,,,,,,,,,,,,,,,, <
>:v
,v_@
"1
.-
"
^<
```
This uses a prefix of `+++[>++++[>++++<-]<-]>>` to set the first tape index to '0' with 24 characters.
The Befunge program is very basic and outputs that along with N '.' characters.
] |
[Question]
[
>
> **Related:** [Hello world!!! Fibonacci distribution](https://codegolf.stackexchange.com/questions/18812/hello-world-fibonacci-distribution)
>
>
>
Create a program that returns True if a given input meets the following specifications, and False otherwise:
* The count of numeric characters (0-9) in the input matches a Fibonacci number.
* The count of non-numeric characters !(0-9) in the input matches the Fibonacci number immediately preceding the count of numeric characters.
Additional Rules:
* Your program must use the proper Fibonacci sequence, per OEIS - that is, the Fibonacci sequence must start with `0, 1, 1, 2, ...`
* If the numerics or non-numerics count is 1, the following must occur:
+ Numerics 1: Non-numeric count of 0 *or* 1 should be handled as True - all others False.
+ Non-Numerics 1: Numerics count of 1 *or* 2 should be handled as True - all others False.
* Input may be taken however you like, but the program must be capable of handling any arbitrary text.
* True/False are not case-sensitive, and can be substituted with 1/0 or T/F.
* You may only hard-code up to two Fibonacci numbers.
* Output may *only* be True/False or 1/0 or T/F. Any additional text or visible errors generated is unacceptable.
[Answer]
# Golfscript, 36
```
:?1 2{.@+.?,<}do?,=@{.48<\58<^},,@=*
```
Explanation:
* `:?` stores the input into `?`.
* `1 2{.@+.?,<}do` computes the last two fibonacci numbers until it hits the input length. The block reads: "duplicate the top, rotate the third value to the top, add them, duplicate the top, get the input, get its length, compare".
* `?,=` compares the last computed fibonacci number to the input length.
* `@` brings the input to the top
* `{.48<\58<^},` filters out only digits. The block reads "is the ASCII value below 48 XOR below 58?"
* `,@=` compares the filtered string length to the lower fibonacci number (count of digits)
* `*` merges the two comparisons to provide a single boolean value.
Live demo: <http://golfscript.apphb.com/?c=OyIvMDU5OiIKOj8xIDJ7LkArLj8sPH1kbz8sPUB7LjQ4PFw1ODxefSwsQD0q>
[Answer]
# Javascript, ~~92 88~~ 86 characters
```
t=prompt()
for(b=c=1;c<t[l='length'];c=a+b)a=b,b=c
alert(c==t[l]&b==t.match(/\d/g)[l])
```
I hope you don't mind I've hard-coded the the first three Fibonacci numbers.
[Answer]
# Python - ~~128~~ 125
```
import re
def v(s):
l=len(re.sub("\d","",s));L=len(s)-l;a,b=1,2
while a<L:
if a==l and b==L:
print 1;return
b,a=a+b,b
print 0
```
Really hope there is no problem with hardcoding the first few fibonacci numbers
[Answer]
# Python 3, 105 characters
Script file name is passed to the program through the command line
```
import sys
a=[0]*2
for b in open(sys.argv[1]).read():a['/'<b<':']+=1
a,b=a
while a>0:a,b=b-a,a
print(b==1)
```
## 87 characters
Script must be written in file with name `s`
```
a=[0]*2
for b in open('s').read():a['/'<b<':']+=1
a,b=a
while a>0:a,b=b-a,a
print(b==1)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes
```
ḟ,fɗØDẈẇ⁸LŻÆḞ¤
```
[Try it online!](https://tio.run/##y0rNyan8///hjvk6aSenH57h8nBXx8Nd7Y8ad/gc3X247eGOeYeW/D/c/qhpzdFJD3fO@P8/motTyVBJB0RWgKkKCzMIrW5iYWZq5gyEbkYG5uZmbuZGQLaJkaGRoXpNjbqiOlhZYpKhkTGQBTLACGoO1CAICZEGKUyGMGMB "Jelly – Try It Online")
## How it works
```
ḟ,fɗØDẈẇ⁸LŻÆḞ¤ - Main link. Takes a string S on the left
ØD - Yield "0123456789"; D
ɗ - Group the previous three atoms together as a dyad, f(S, D):
ḟ - Remove digits from S
f - Remove non-digits from S
, - Pair these two
Ẉ - Lengths of each in the pair; [a, b]
¤ - Create a nilad:
⁸ - Yield S
L - Take its length, L
Ż - [0, 1, 2, ..., L]
ÆḞ - nth Fibonacci number for each
ẇ - Sublist exists?
This returns 1 if the left argument ([a, b]) is a contiguous sublist
of the right argument (the list of Fib numbers), i.e.
a and b are both Fibonacci numbers, and a immediately precedes b
```
[Answer]
## Perl, 92
```
$_=join"",<>;@_=1;$d=s/\d//g;push@_,$t=$_[-1]+$_[-2]while$t<$d;print$t==$d&$_[-2]==y///c?1:0
```
Usage:
```
cat fib-test
print "Hello world%s"%("!"*int(3.141592653589793238462643383279502884197169399375105820))
perl -e '$_=join"",<>;@_=1;$d=s/\d//g;push@_,$t=$_[-1]+$_[-2]while$t<$d;print$t==$d&$_[-2]==y///c?1:0' fib-test
1
```
[Answer]
# Java - ~~147~~ 145
```
boolean v(String s){int l=s.replaceAll("\\d","").length(),L=s.length()-l,a=1,b=2,c;while(a<L){if(a==l&&b==L)return 0<1;c=b;b+=a;a=c;}return 0>1;}
```
I'd say this is not bad for Java.
**Edit**: Thanks to Chris Hayes for [suggesting](https://codegolf.stackexchange.com/questions/18887/fibonacci-distribution-validator/18892?noredirect=1#comment37072_18892) `0>1` for false and `0<1` for true.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
d1Ý¢¤ÅFs.kd
```
-3 bytes by taking inspiration from [*@cairdCoinheringaahing*'s initial Jelly program](https://codegolf.stackexchange.com/revisions/214232/1)
-1 byte thanks to *@ovs*
Input as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f8/xfDw3EOLDi053OpWrJed8v9/tFKFko6SOhCbALEFEJsBsSmUdkaj3YDYCIgNgNgcimHi5lA5ZPUmUDFDJBpkVw0Ug9iKYDoWAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXw/xTDw3MPLTq05HCrW7Fedsp/nf/RSkZKOkqGFUCiwsIMRKqbWJiZmjkDoZuRgbm5mZu5EZBtYmRoZKheU6OuqA5UlJhkaGSspKOgBNILMQBsAgiDZYAqkiEMpVgA).
**Explanation:**
```
d # Check for each character in the (implicit) input-list if it's a
# non-negative (>=0) integer (1 if truthy; 0 if falsey)
1Ý # Push the list [0,1]
¢ # Count them in the list of truthy/falsey results
¤ # Push the last count, without popping the pair itself
ÅF # Pop and push a list of Fibonacci numbers <= this count
s # Swap so the pair is at the top of the stack
.k # Get the index of the pair (as sublist) in the Fibonacci list
# (or -1 if this pair isn't a sublist)
d # Check that this index is non-negative (>=0), thus that it was found
# (after which the result is output implicitly)
```
Unfortunately the Fibonacci sequence contains two `1`s, otherwise we could have saved two bytes by changing `s.kd` to `sſ` (check whether it ends with the pair), [which fails for single-digit inputs](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXw/xTDw3MPLTq05HCrW/Hh1kP7/@v8j1YyUtJRMqwAEhUWZiBS3cTCzNTMGQjdjAzMzc3czI2AbBMjQyND9ZoadUV1oKLEJEMjYyUdBSWQXogBYBNAGCwDVJEMYsQCAA).
[Answer]
# APL, 34 chars/bytes\*
```
{n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
```
Expects the input string on standard input and prints either 0 or 1 as required. `⎕IO` must be set to 0 (the default is implementation-dependent.)
**Ungolfed**
```
s←⍞ ⍝ read input string
d←s∊⎕D ⍝ vector with 1 for each digit, 0 for each non-digit in s
n←+/0 1∘.=d ⍝ 2-vector with number of non-digits and number of digits in s
f←+\∘⌽ ⍝ a function that computes a fibonacci step (f 2 3 → 3 5)
t←f⍣{≥/+/⊃⍺n}0 1 ⍝ apply f repeatedly, starting with 0 1, until we get two fibonacci
⍝ terms whose sum is ≥ the length of the input string (sum of n)
n≡t ⍝ return 1 if the fibonacci terms match the no. of digits and non-digits
```
**Examples**
```
{n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
%~n01234
1
{n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
x'48656C6C6F20776F726C642121'||'!'
1
{n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
[72 101 108 108 111 32 119 111 114 108 100 33 {.}2*]''+
1
{n←+/⍵∘.=⍞∊⎕D⋄n≡+\∘⌽⍣{≥/+/⊃⍺n}⍵}⍳2
What?12345
0
```
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~23~~ ~~21~~ ~~19~~ ~~18~~ 16 bytes
*Edit: -1 byte, then -2 more bytes, thanks to Razetime*
```
€↑→L¹İfe#€ṁsŀ9¹L
```
[Try it online!](https://tio.run/##yygtzv7//1HTmkdtEx@1TfI5tPPIhrRUZaDAw52NxUcbLA/t9Pn//7@SoZGxiWliUnJKqpm5hRIA "Husk – Try It Online")
```
€↑→L¹İfe#€ṁsŀ9¹L
€ # index of argument in list, if found, otherwise 0,
↑ # list: the first n elements
→L¹ # n = length of input +1
İf # of the list of fibonacci numbers
e # argument: 2-element list
# # 1. number of elements in input that are
€ ¹ # present in list of
ṁsŀ9 # string from 0 to 9
L # 2. length of input
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~46~~ ~~40~~ ~~38~~ 32 bytes
* -12 bytes from golfing, -2 from @ngn's improvements
```
{~^(|+\)\[#x;|!2]?+/'~:\~"0:"'x}
```
[Try it online!](https://ngn.codeberg.page/k#eJw9zN9ugjAUBvB7ngLrkmr8U9o5aNqLXSzxJYDFUkAbkW60LjUizz7mrDk3vy/nfKdm1+Fz1i+yeZZOHe8nJH9fIDiwbAARA9DdgsCy60t6GTpWh2Ho+E4f+WxXC9Vwxy+8m+e3wKZLQADH+SiAnZej8ZNwQ+O3+GOcLYmSJN4mZPSGYIJh38MJ9JeiwOTVB8Cj/5/kKeceXAIv4O6V6NGXPgUoOFj7ZRhCUpfVXjf12lghj5WTB9Huq7XUJ/R9roxVujUIU0oTVKtCt0JKtSqVsZ0qzn/b1Y9oVCms7tAv+ntacQ==)
* `~"0:"'x` determine which characters in the input are digits
* `+/'~:\` count the number of digits and non-digits
* `~^(...)[...]?` determine if the above is in...
+ `(|+\)\[#x;|!2]` the pairs of fibonacci numbers
[Answer]
## Ruby, 85
```
d=-(n=(i=$<.read).gsub(/\d/,'').size)+i.size
a=b=1;while b<d;b=a+a=b end;p b==d&&a==n
```
Takes input either on `STDIN` or as a filename argument.
Output is either `"true"` or `"false"`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Êô@MgXÃã de[\D\d]£èX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=yvRATWdYw%2bMgZGVbXERcZF2j6Fg&input=WwoiMSIKIjF4IgoieDg2IgoieCc0ODY1NkM2QzZGMjA3NzZGNzI2QzY0MjEyMSd8fCchJyIKImFiMTIzIgoiMTIiCiIxeHgiCiJ4IgoieDEyMyIKImFiYzEyMyIKXS1tUg) (Test cases appropriated from [caird](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing))
] |
[Question]
[
Pick a programming language.
In that language, write a function or program that takes as input a string of working code (in the same language).
It should return/output a [minified](http://en.wikipedia.org/wiki/Minification_%28programming%29) version of the input code. The output should be functionally equivalent to the input.
Answers should contain both
1. The code that does the minifying (should be readable/non-golfed)
2. The resulting output after passing your code (that is, the code that does the minifying) in to itself
The shortest **output** wins.
*Edit:* notes explaining the minification methods you used are appreciated.
*Edit:* obviously, minification methods could vary from language to language, but a good-faith attempt at writing a minifier for this challenge would most likely perform actions such as
* Removing unnecessary whitespace
* Removing unnecessary newlines
* Removing comments
* Shortening variable names
[Answer]
# Brainfuck
I always had in mind to do this, so here we go:
```
>>>,
[
[->+>+<<] copy input
<<<+++++++++++++ fill cell with 13 for subtraction
[->+>+>+<<<] and duplicate some times
>>>[->---<] sub 39
>---- 43
[ plus
-
[ comma
-
[ minus
-
[ dot
<<[->>-<<]>>- 60
[ less than
--
[ greater than
<<<[->>>--<<<]>>> 86
--- 91
[ open square bracket
--
[ closing square bracket
>[-] remove copy
]]]]]]]]
>[.[-]>] the copy has not been removed; print
<<[-]<<<[-]>[-]> clean up
,]
```
Compresses itself to (144 characters):
```
>>>,[[->+>+<<]<<<+++++++++++++[->+>+>+<<<]>>>[->---<]>----[-[-[-[<<[->>-
<<]>>-[--[<<<[->>>--<<<]>>>---[--[>[-]]]]]]]]]>[.[-]>]<<[-]<<<[-]>[-]>,]
```
The size of the compressing could probably still reduced a bit. The compression alogorithm itself is near perfect, it's hard to do any more than removing non-`+-[]<>,.`.
[Answer]
## Python 2.6
I tried to implement a basic Python minifier which does the following things:
1. Removing unnecessary whitespace
2. Removing unnecessary newlines
3. Removing comments
4. Shortening variable names
As others stated, the winning criteria (shortest output when run through itself) does not make a whole lot of sense for a minifier if you want to start with a non-golfed solution.
## Original (2591 characters)
```
# imports
import keyword, tokenize, sys, token, itertools
# vars
line = ""
out = [] ; block = []
idx = 0 ; previdx = 0 ; prevdirection = 0
varnames = set() ; imports = set()
t = tokenize.generate_tokens(sys.stdin.readline)
newline = '\n'
# settings
replace_varnames = True
while 1:
try:
toknum, tokval, _, _, _ = t.next()
iskwd = tokval in keyword.kwlist
if toknum == 1:
if ''.join(line).lstrip().startswith("import "):
imports.add(tokval)
else:
if not (iskwd or line[-1]=="." or tokval in __builtins__.__dict__.keys() or tokval.startswith("_") or len(tokval) <=2 or tokval in imports):
varnames.add(tokval)
if toknum == 53:
continue
if toknum == 4:
block.append(' '.join(x for x in ("".join(l for l in line if l)).strip().split()))
line = []
if toknum == 5 or toknum == 6:
if out and out[-1] != newline:
out.append(newline)
previdx = idx
idx += (-1,1)[toknum==5]
indenting = previdx < idx
dedenting = previdx > idx
prefix = " " * previdx
base = ";".join(l for l in block)
if dedenting and prevdirection == 1:
out.pop()
out.append(base)
else:
if len(block) > 1:
if indenting:
out.append(prefix + ";".join(l for l in block[:-1]))
out.append(newline)
out.append("".join(prefix + l for l in block[-1:]))
else:
out.append(prefix + base)
elif len(block) == 1:
out.append(prefix + base)
block = []
prevdirection = [-1,1][indenting]
space_if_needed = [""," "][iskwd and tokval not in ("else","try")]
line += space_if_needed + tokval + space_if_needed
except StopIteration:
out.append(" " * idx + ";".join(l for l in block))
break
total_out=''.join(out)+newline
if replace_varnames:
wrappers = [";"," ", ":", "=", "(", "[", ")", "]", ".",",","*","+","-","/","<",">","!","\n"]
wrl = list(itertools.permutations(wrappers,2)) + zip(wrappers, wrappers)
for i, e in enumerate(varnames):
# print i, e, "v"+str(i)
for p, a in wrl:
total_out = total_out.replace(p+e+a,p+"v"+str(i)+a)
print total_out[0:-1]
```
## Minified (by itself), 1388 characters (a 46 % reduction)
```
import keyword,tokenize,sys,token,itertools;v16="";v20=[];v19=[];v4=0;v15=0;v17=0;v10=set();v6=set();t=tokenize.generate_tokens(sys.stdin.readline);v8='\n';v13=True
while 1:
try:
v18,v9,_,_,_=t.next();v2=v9 in keyword.kwlist
if v18==1:
if ''.join(v16).lstrip().startswith("import "):v6.add(v9)
else:
if not (v2 or v16[-1]=="." or v9 in __builtins__.__dict__.keys() or v9.startswith("_") or len(v9)<=2 or v9 in v6):v10.add(v9)
if v18==53:continue
if v18==4:v19.append(' '.join(x for x in ("".join(l for l in v16 if l)).strip().split()));v16=[]
if v18==5 or v18==6:
if v20 and v20[-1]!=v8:v20.append(v8)
v15=v4;v4+=(-1,1)[v18==5];v5=v15<v4;v12=v15>v4;v11=" "*v15;v14=";".join(l for l in v19)
if v12 and v17==1:v20.pop();v20.append(v14)
else:
if len(v19)>1:
if v5:v20.append(v11+";".join(l for l in v19[:-1]));v20.append(v8);v20.append("".join(v11+l for l in v19[-1:]))
else:v20.append(v11+v14)
elif len(v19)==1:v20.append(v11+v14)
v19=[];v17=[-1,1][v5]
v3=[""," "][v2 and v9 not in ("else","try")];v16+=v3+v9+v3
except StopIteration:v20.append(" "*v4+";".join(l for l in v19));break
v1=''.join(v20)+v8
if v13:
v0=[";"," ",":","=","(","[",")","]",".",",","*","+","-","/","<",">","!","\n"];v7=list(itertools.permutations(v0,2))+zip(v0,v0)
for i,e in enumerate(v10):
for p,a in v7:v1=v1.replace(p+e+a,p+"v"+str(i)+a)
print v1[0:-1]
```
## Known limitations:
1. Keyword arguments are problematic when variable name shortening is on.
2. The code is ugly and can probably break some of the more dynamic Python constructs. It does work fine for itself (and other simple scripts) though.
[Answer]
## JavaScript, 562 → 334 bytes
40% reduction, but it's pretty compact to begin with.
Uses the [Google Closure Compiler API](http://code.google.com/closure/compiler/docs/api-ref.html) in advanced optimization mode, which might rename certain variables but it is still functionally equivalent.
```
function minify(input) {
// Closure Compiler API url:
var url = 'http://closure-compiler.appspot.com/compile';
// Create and initialize the Ajax request:
var rq = new XMLHttpRequest();
rq.open('POST', url, false);
rq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Send the request:
rq.send('js_code=' + encodeURIComponent(input) +
'&compilation_level=ADVANCED_OPTIMIZATIONS&output_format=text&output_info=compiled_code');
// Return the result and just assume the code succeeded (hey, it's Google):
return rq.responseText;
}
```
[Here's a sample jsFiddle](http://jsfiddle.net/minitech/guMc5/), and here's the code run on itself when compiled without a run:
```
window.a=function(c){var b=new XMLHttpRequest;b.open("POST","http://closure-compiler.appspot.com/compile",!1);b.setRequestHeader("Content-Type","application/x-www-form-urlencoded");b.send("js_code="+encodeURIComponent(c)+"&compilation_level=ADVANCED_OPTIMIZATIONS&output_format=text&output_info=compiled_code");return b.responseText};
```
[Answer]
## APL, 76 character output
```
{(~(n ↓ b) ∧ ' ' ⍷ d) / d←(n←- +/ ∨\ ('⍝'⍷⍵) ∧ b←~a∨ ≠\ a←(('''' ⍷ ⍵) ∧ {⍵ ∧ ¯1⌽⍵}~'''''' ⍷ ⍵)) ↓ ⍵}⍞ ⍝ This takes a line of APL as input and removes comments and unnecessary spaces!
```
This isn't really a serious attempt at golfing, but it was interesting to implement.. I think? It removes comments (⍝) and spaces. This works on Dyalog APL. (Note that it preserves spaces and ⍝ characters found in quoted strings.)
Example (first line is the code, second is the input, third is the output):
```
{(~(n ↓ b) ∧ ' ' ⍷ d) / d←(n←- +/ ∨\ ('⍝'⍷⍵) ∧ b←~a∨ ≠\ a←(('''' ⍷ ⍵) ∧ {⍵ ∧ ¯1⌽⍵}~'''''' ⍷ ⍵)) ↓ ⍵}⍞ ⍝ This takes a line of APL as input and removes comments and unnecessary whitespace!
{(~(n ↓ b) ∧ ' ' ⍷ d) / d←(n←- +/ ∨\ ('⍝'⍷⍵) ∧ b←~a∨ ≠\ a←(('''' ⍷ ⍵) ∧ {⍵ ∧ ¯1⌽⍵}~'''''' ⍷ ⍵)) ↓ ⍵}⍞ ⍝ This takes a line of APL as input and removes comments and unnecessary whitespace!
{(~(n↓b)∧' '⍷d)/d←(n←-+/∨\('⍝'⍷⍵)∧b←~a∨≠\a←((''''⍷⍵)∧{⍵∧¯1⌽⍵}~''''''⍷⍵))↓⍵}⍞
```
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/products.htm), 2145 → 763 bytes (−64%)
```
Minify←{
⍝ Minifies source code ⍵ — see examples at end
ns←⎕NS ⍬ ⍝ namespace to keep names created by side-effects
src←ns.(61 ⎕ATX ⎕FX) '_',⊆⍵ ⍝ get normalised source
⍝ make large magnitude numbers use exponential format:
src←'\d+\.\d+' '\d00+'⎕R{⍵.PatternNum: (⊃,'E',∘⍕¯1+≢)⍵.Match ⋄ ⍵.Match} src
(from to)←⍬ ⍬
(from to),∘⊂←'''[^'']+''|\d+ [eEjJ]' '&' ⍝ preserve strings and space before e/j
(from to),∘⊂←' ?⍬ ?' '⍬' ⍝ remove spaces around ⍬
(from to),∘⊂←'([^#]) # ([^#])' '\1#\2' ⍝ remove spaces around #
(from to),∘⊂←'# ([^#])' '#\1' ⍝ remove space after #
(from to),∘⊂←'([^#]) #' '\1#' ⍝ remove space before #
(from to),∘⊂←' ([⎕:])' '\1' ⍝ remove space before ⎕ and :
(from to),∘⊂←' *⍝.*|^ +' '' ⍝ remove comments and leading spaces
(from to),∘⊂←'(\pL) 0\.' '\1.' ⍝ make X 0.5 into X.5
(from to),∘⊂←'(\d) (\pL)' '\1\2' ⍝ make 1 X into 1X
(from to),∘⊂←' ?(⋄ ?)+' '⋄' ⍝ make 1 X into 1X
(from to),∘⊂←'(:End)([DFHPRTW]|If|Sel)\w+' '\1' ⍝ make :EndXYZ into :End where permitted
(from to),∘⊂←':Return|:GoTo ' '→' ⍝ Replace keywords with "→"
src←from ⎕R to ⊢ src ⍝ do it!
⍝ make small magnitude numbers use exponential format:
src←'\b0\.00+(\d+)'⎕R{lead←-/⍵.Lengths ⋄ mantissa,'E',⍕10⍟⍵.Match÷⍥⍎mantissa←lead↓⍵.Match} src
src←'\b0\.'⎕R'.' ⊢ src ⍝ make 0.5 into .5
_←'adic' ns.⎕CY 'dfns' ⍝ import adic from dfns.dws
from←' '(2⌽'\b\b',~)¨⍨' '~¨⍨↓ns.(⎕REFS ⎕FX)'\.[∆⍙\w]+'⎕R' '⍠'UCP' 1 ⊢ src ⍝ get non-dotted names
from{⍵,⍺,⍵}¨←⊂'\b' ⍝ names have to be in isolation
to←('_',⎕A,⎕C ⎕A)∘ns.adic¨⍳≢from ⍝ generate short names
(from to),⍨∘⊂←'''[^'']+''' '&' ⍝ preserve strings
from ⎕R to ⊢ 1↓src~⊂'' ⍝ minify names and remove blank lines
More examples:
Refs: ⎕SE # ## ⎕DMX #
Numbers: 100000 0.000001 16 E3 16 F3
}
```
[Run it on its own source](https://dyalog.run/run?1=nVZRaxtHEH6ufsU0ol1dZF90MQlFL6Y4ctpiGyO7VKlONifdSrr4bk_cnqIay6akwaRKFUpTQ0spNYGAKYU8lFAo9MX9Fe3j_ZLO7J5sWT2L0gXdrfZ2v_lm9tuZ_eFnd9_xw86u0_NPT1_14_bie3-_9QLWPeG195Pjrw9yQC0Z_6jHPC5Bhv2oxaEVuhw_vIHk829Bcg78Myfo-TjBiYELV68UElGS5ycbWzj3F40knIDLnoMYcQh7nPf0CLQi7sTcheY-SM_li7zd5q1YaiD9lFEL8YQ0C3ctQNj3t2v0Wq0ZwHbZQjI6JkbKSofHIMIocHxPIqhmfelO4Oxx8J2ow7HbEV7cR3dEP2jySEJfkju9UHARe44PbcKJy9McmO0WbRMfDLBbKhUZ8qgeoHlz04ljHomNflCGQjL6YoFVkNrT75Lxyflrq5h8-dKgaetO3OpC8uwJXPw7JPCcNlNoR2GAETIogBg6_M18UJijx0SGsfoOY40iY0OkBHVeefhRg4Fu7N20R373Ii559IiDjCNPdHC3BAZH7UaTo5_o-K2H1xuCZeKyPIGebQy_ThmLeBCSKYJHS1HYR2NzHSnUd_INA_KgO1ftMNvK27fZHOz89cjZkBPkvG2xLNbgtHEv5-FOGGfjIuNs3DTYc4CRL0qqfA1jgmaZgZ5A42K1ueU5Jm7iYvPmcAeKWUbYZHDKRCsMAjwVWjc-d1wUUboJc2Jk99YMKNlmphXbMi9ipI5lDUrmHfAEpoeaeWcerGuAws7ARVillUtYC4EVqFWbJ_ACHcllIzMiKPBnT6YE_t9xC-WKcI1C_d7qB5vV7U8aww_bwy3uG_ZAZZCpvVSYNLv24FONS39g0OW4qT0eBR6mF_d6S-Uqj_uRGJbvh9shsFn-x99M8a_ynk-S2eP7gzByJQy8uAs3cNKN3HS2U2YowVHKTkYvaVgjuCF48du5mcQqMe36_zexNlEomFBxd4uGzqqkM_y0eIsy5RoXnbgrVeYMHMSR0tEpdnxilZLxTxfp9M_fkvGrZPx8MgshNNKLzIw7bV_ZZajLK84q3y60idLUC3dpGZ6EFsN6Z-LKlQfA3LaQaarygl4YxUAzQEWSvpnuID0xNKSkxwq3k6_-QAJ2ky0cGednyfgMR49UB1lT3SNeldWttOox26wnT7HofW8PGroEMUrCp-zjlU2GyrxCX5dEseiGpCBddS8pUO3CGP6OvzeHaBLLzugxkvnXObio4dB1Hqki3uQYEfBk6DuxFwqNGYcIUVBlGQs1PVZUyTZQqugJRYMc-xXroQpKSlHwCG8BILsUsimKU1LHYGRUPjYpdFll7tLNKzK2MKoYniPylM36GKhbUOoqpbs0BTZ9R-yB7wmkpnHXVd1M7z-pmqlVeVuWyeBWBUtaPk_de-u1SdantqFPRhmsEjVUl3pbYN2FyhI9V5dycKjvZn-9gwDo9fnZQQF1jRtl0N2qSjuGFw3qr52_XtKTJxe6fwA) to get:
```
B←{
K←⎕NS⍬L←K.(61⎕ATX⎕FX)'_',⊆⍵
L←'\d+\.\d+' '\d00+'⎕R{⍵.PatternNum:(⊃,'E',∘⍕¯1+≢)⍵.Match⋄⍵.Match}L
(H M)←⍬⍬
(H M),∘⊂←'''[^'']+''|\d+ [eEjJ]' '&'
(H M),∘⊂←' ?⍬ ?' '⍬'
(H M),∘⊂←'([^#]) # ([^#])' '\1#\2'
(H M),∘⊂←'# ([^#])' '#\1'
(H M),∘⊂←'([^#]) #' '\1#'
(H M),∘⊂←' ([⎕:])' '\1'
(H M),∘⊂←' *⍝.*|^ +' ''
(H M),∘⊂←'(\pL) 0\.' '\1.'
(H M),∘⊂←'(\d) (\pL)' '\1\2'
(H M),∘⊂←' ?(⋄ ?)+' '⋄'
(H M),∘⊂←'(:End)([DFHPRTW]|If|Sel)\w+' '\1'
(H M),∘⊂←':Return|:GoTo ' '→'
L←H⎕R M⊢L
L←'\b0\.00+(\d+)'⎕R{I←-/⍵.Lengths⋄J,'E',⍕10⍟⍵.Match÷⍥⍎J←I↓⍵.Match}L
L←'\b0\.'⎕R'.'⊢L
F←'adic'K.⎕CY'dfns'
H←' '(2⌽'\b\b',~)¨⍨' '~¨⍨↓K.(⎕REFS⎕FX)'\.[∆⍙\w]+'⎕R' '⍠'UCP' 1⊢L
H{⍵,⍺,⍵}¨←⊂'\b'
M←('_',⎕A,⎕C⎕A)∘K.adic¨⍳≢H
(H M),⍨∘⊂←'''[^'']+''' '&'
H⎕R M⊢1↓L~⊂''
C G:
E:⎕SE# ##⎕DMX#
D:1E5 1E¯6 16 _ 16F3
}
```
[Run *this* on itself](https://dyalog.run/run?1=dVRNaxNRFF24m1_xYNA7r2nHTItBZhM0mTRNJqUkFSOZtKRN2io1KW1CkSRdVCk1OkWUgCJiKBSKFLqQIghu4q_Q5fsJ_gLPe5N-QKeL3Lnz7sc57-bc-fyt-qKy3lhdrGysDwZHrebKxP2_t_49FHvv2loWVhz0ZwvCP9FcvGRNI2bh5MF8ETZV5LRI46K3J_wzFSevGvFMGGJwo9EIIS3fRticqzSbtc36bOu5bYjey3FyULn_Ufj94akVEa8PuczKVZrLa-LNqwu_62pGmuW4ZOKfSB7qVZX2diUkUWmBqBwh6gCYlWrOs0wZ-HfoWiqLowGLI4jn9bBRWtDLnOkscOQdLN2bvJ54JUP3rJsbBR1CeBglzMUeQYTEx4T_xRzrLDA5yJD-3obLWdQzVb0ZllDlTGWpjLA7sLiBObM4lxDwQprYTr3KjVIylZ7Lzz8ud2ZWOoXaOve2IzfwtvO1Zmuz3rGnG_MNJvvuvScljLTUAcuJ3qE7EsoS6EMgYBrhgUpmcD5xV_7zbq2-2lzbAqtMoBO_b0WF__VCFb9_CP9I-AcZlKDsw1W5XLZXbQkPiZqSx5Xq02XKmjhPPKHqSn2LtLQaBhmT4u0vlHlLNL7Dh8fCP8bpjnIAAOHLZk6qMNK9Z5bEPnT_ydsuBypXqhrQo8QcMUtBpqXwQf4nfmddtIKGe7sAIS0H31DLg2WSJiEdjlFmTUlS4n7HUqTPZwwWIYoPZH45XAtU3R0JQlqCTduaYyNWcHSm63CSuaKuJW3LuccsZ3gaY1aMLcKkprRusPp_biMNGMPjtoH5gjeXH4C8vAC2Vvru8HQqSD7_XvwH) to get something very similar (only names differ).
**Removes:**
* All redundant spaces
* Comments
* Empty lines
* Leading and trailing zeros in numbers
**Abbreviates:**
* Numbers into exponential form (only when it actually saves characters)
* Control structure keywords to their shorter alternate forms
* All used names into `_`, `A`, `B`, `C`,… `Z`, `a`,… `z`, `__`, `_A`, `_B`,…
**Fails on:**
* Evaluated strings
* Global and to-be-imported names (abbreviates them)
[Answer]
## Bash, 17 characters output
They say my Python solution below isn't a minimizer. So here's one that does minimize, and it's even shorter:
```
sed -e '1 s/^ //'
```
It reduces its own size from 18 to 17 characters.
## Python, 38 character output
I misunderstood the question a bit, so my 0 character attempt was incorrect.
So I have a new and improved solution. I'd start a new answer, but since it's in the same spirit, I prefer to edit.
I'm sure it can be much improved, especially if you switch the language. But as it is, I'm still way ahead of the competition:
```
import sys
for l in sys.stdin:print l,
```
When given itself as input, you get a 100% equivalent program, 38 characters long.
---
## Python, 0 character output (but not when run on itself, so it doesn't count).
```
import sys
program = [ l for l in sys.stdin ]
if len(program)>1 or program[0]!="x=12345\n":
print "".join(program),
```
Sample input (also Python):
```
x=12345
```
I admit, it isn't very effective on most programs.
However, it reduces my example to 0 chars, still keeping it equivalent.
"The shortest **output** wins" - I don't think anyone can top this.
] |
[Question]
[
You are given a matrix of size m x n where each cell can contain either 1 or 0. You need to find the largest square submatrix that contains only 1's. The output should be the area of the largest square submatrix.
For example, given the following matrix:
```
1 0 1 1 1
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
```
The largest square submatrix that contains only 1's is:
```
1 1 1
1 1 1
1 1 1
```
So the output should be 9 since the area of the square is 3x3 = 9.
The time complexity of your algorithm should be O(mn).
[Answer]
# [Python](https://www.python.org) NumPy, 148 bytes
```
lambda X,o=1:[B:=c(c(pad(X,1),0),1),[o:=o+(B[i,j]+B[i-o,j-o]-B[i,j-o]-B[i-o,j]==o*o)for i,j in argwhere(X)+1]]and~-o*~-o
from numpy import*
c=cumsum
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LU9BboMwELzzCh_XsKBQtVWE5AN5AickalUuYEIUey0HlOTSV_TWC1LV_qm_qWly2N3RjEYz-_njrtOe7PKlxcv3POl0-_txVOatU6xGEnnR7ArRQgtOdVBjznHD191QISiBXTPiQSbhpISHlGT6z9zBykkhKCauybMgsNEy5Yfzvvc91DzJpVS2e08pDhNpT4bZ2bgrG40jP8VRK9rZnGZz76a9HZhgPpjIZF2v1XycXgMJPKpWwQ7ZaKd-6P0JNviA8ISP-Mx5tBYo1_i4wioz6gLhkQBGG0ARMeeDD0rUUHJ-S1uW2_0D)
Should be linear in the size N (total number of elements) of the input.
### How?
Computes first the 2d partial sums B of the input. After this one off O(N) (space and time) investment we can count the number of ones in any grid rectangle in constant time using the four corners of the rectangle: B(top left)+B(bottom right)-B(top right)-B(bottom left).
We can now find the maximum in linear time by traversing the input a single time top left to bottom right. We only check for squares that have their bottom right corner at the current position. If the current point is bottom right of a new maximum square we know that the current maximum must be one less because we have already visited the top left neighbour of the current point. Therefore we need at each point only check a single square, the loop body is constant time and the loop is linear.
[Answer]
# MATL, ~~21~~ 19 bytes
```
lYa`9I&ZItz}x@UGaa*
```
*2 bytes saved thanks to @lmendo*
The complexity of the erosion operation is O(mn), but unfortunately with this approach, we perform erosion as many as max(m, n) times.
Try it at [MATL Online](https://matl.io/?code=lYa%609I%26ZItz%7Dx%40UGaa%2a&inputs=%5B1+0+1+1+1%3B1+0+1+1+1%3B1+1+1+1+1%3B1+0+0+1+0%5D&version=22.7.4)
**Explanation**
```
% Implicitly grab input as a multi-dimensional array
lYa % Pad with a row of zeros on the top and bottom to ensure erosion works
` % do...while loop
9I&ZI % Perform image erosion with a 3 x 3 neighborhood
t % Duplicate the output
z % Check if there are any 1's left in the eroded result, if so, repeat
} % End loop
x % Delete the last element on the stack (the eroded matrix of all 0's)
@ % Get the index of the last loop iteration and
U % Square it to get the size of the largest contiguous square of 1's
Gaa % Check if there are any 1's in the input
* % Multiply with the result (to account for a matrix of all 0's)
% Implicitly display the result
```
[Answer]
# [J](http://jsoftware.com/), 78 76 75 bytes
```
[:>./@,@;($<@,:&2@#:i.@#@,)({:*1+<./@}:)@,;.0`(0<@{1+[)`]}&.>/@,&|.0<@,0&,.
```
[Try it online!](https://tio.run/##dY3BCoJAEIbv@xSjxq6b27TrIXA0GQg6deoqkhBJdekBzGff1k5FyTDMz/fzMXdfROTaTUSFUiJG1cOWQIEBCxR2hbA7Hva@oRrXbLhMFxUbkjkndENO2Oh0oKXLqlCPpNmUaLvUVjy4rNFdO0qsgyifGJix0qDX4nK@PqCHGEs85dBOv6xw4bhpvpL7YBO1YlZ3f6TfNK8L@66FfwE "J – Try It Online")
\$\mathcal{O}(mn)\$ using a standard dynamic programming table.
The only challenge was how to translate this essentially procedural algorithm into an array paradigm:
* First add a top-left border of zeros:
```
0 0 0 0 0 0
0 1 0 1 1 1
0 1 0 1 1 1
0 1 1 1 1 1
0 1 0 0 1 0
```
* Next generate the coordinates for what would be the nested loop in a procedural language -- that is, we traverse from left to right, top to bottom. We also add `2 2` to each, since we'll be cutting out 2x2 squares later. For example, the first element represents the 2x2 square whose top-left coordinate is `0 0`:
```
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│0 0│0 1│0 2│0 3│0 4│1 0│1 1│1 2│1 3│1 4│2 0│2 1│2 2│2 3│2 4│3 0│3 1│3 2│3 3│3 4│
│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│2 2│
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
```
* Now we reverse the above list and use it in a single reduction of the input from the previous step. In each step of the reduction, we slice out a two by two square. For example in the first step of the reduction we take the top-left square:
```
0 0
0 1
```
* The reduction logic is simple. Call the value of the lower-right cell `lr`. We update `lr` as follows: `lr * (1 + min(all values except lr))`.
* Return the max value of the completed dynamic programming table.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~88~~ ~~80~~ 46 bytes
```
≔Eθ⁰θWS«≔⮌θη≔⟦⁰⟧θFι⊞θ×Iκ⊕⌊⟦↨υ⁰⊟η↨η⁰⟧⊞υ⌈θ»IX⌈υ²
```
[Try it online!](https://tio.run/##NY4/D8IgEMVn@RSMR6IJuDqpk0OTRt2MA6mnEFva8kdNjJ8dr60ywOXx3u9eZbSvWl3nvA7B3hwUuoN@zqWY816s2NPYGjnsXJfiIXrrbiAEf7PZz77HB/qA0JPfkP@vn@R5AsyuredgBS9TMAP5aBsMsNUhwp1CO1d5bNBFvEBhnW1SA6eNJmSaWpRtB4beUTODdhZ0iDwSyVXo1xjrB/XDSmoZpwVl@0QP//9ElOUQzVlJpRT73WqapZIsLx71Fw "Charcoal – Try It Online") Link to verbose version of code. Takes input as a list of newline-terminated bit strings. Explanation: Now a port of @Jonah's J solution.
```
≔Eθ⁰θ
```
Start with a row of zeros.
```
WS«
```
Loop over each input row.
```
≔⮌θη
```
Reverse the previous row totals to make them easier to process.
```
≔⟦⁰⟧θ
```
Start collecting a new row with a zero column.
```
Fι
```
For each cell...
```
⊞θ×Iκ⊕⌊⟦↨υ⁰⊟η↨η⁰⟧
```
... multiply its value with the incremented minimum of the cells above and to the left. The cell above is obtained by popping the reversed previous row, the cell to the above left is obtained as the base `0` of the popped reversed previous row and the cell to the left is obtained as the base `0` of the new row.
```
⊞υ⌈θ
```
Collect the maximum square found in this row.
```
»IX⌈υ²
```
Output the largest found square from all rows.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes
```
ɖλZɖλ÷nfṪg›*";vt;fG²
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJls67WsmWzrvDt25m4bmqZ+KAuipcIjt2dDtmR8KyIiwiIiwiW1sxLDAsMSwxLDFdLFsxLDAsMSwxLDFdLFsxLDEsMSwxLDFdLFsxLDAsMCwxLDBdXSJd)
Based on [*@Jonah's* J answer](https://codegolf.stackexchange.com/a/257862/116074).
For each 2x2 square
```
a b
c d
```
it replaces `d` with `d*(min(a,b,c)+1)` in sequence going from left to right, top to bottom. Then it takes maximum and squares it.
```
ɖλ # scan by:
Z # zip
ɖλ # scan by: receives [a,c], [b,d]
÷ # push each to stack
n # push the function argument [[a,c],[b,d]]
f # flatten
Ṫ # remove tail [a,c,b]
g # minimum
› # increment
* # multiply
" # pair [b, new d]
; # end scan
vt # get the tail of each
; # end scan
f # flatten
G # maximum
² # square
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 109 bytes
```
Catch[Do[If[AnyTrue[Erosion[ArrayPad[#,1],BoxMatrix[All,n]],#==1&,2],Throw[n]],{n,Min@Dimensions@#,1,-1}]]^2&
```
[Try it online!](https://tio.run/##FcyxCoMwEIDhhyk4XcEIjkJs7eAgSHE7Uggaa8Bc4EypIj57Wtcfvt/pMBmng@11HIt416GfsPJYj1jS1vHH4IP9Yj1hyay3Vg94AaHg5tdGB7YrlvMMpBRcikIkkCnoJvZfPNNO0FiSlXWGzsci/xau4lDqlSWxZUtBjvKpafCupmDehlHAnqeQp4eKPw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# C, C++ : ~~231~~ ~~227~~ 196 bytes
-4 bytes thanks to EzioMercer
-31 bytes thanks to ceilingcat
```
int f(int t[],int x,int y){int z=1,j=y,i,v,w,m,k,b;for(;j--;)for(i=x;i--;)if(t[i*y+j]){v=k=1;w=0;for(m=x-i<y-j?x-i:y-j;k++<m;w=v?k:w)for(b=k*k;b--;)v=t[y*(i+b%k)+j+b/k]?v:0;z=w>z?w:z;}return z*z;}
```
[TIO Link](https://tio.run/##jZHdaoQwEIXvfQrZspCYsVXYvTFmfRDrRdW1jamu2PiPz24TrdBuoTSBnDk5kw/CJFVlvybJsvBSmhnSpwwj0Nqv54AnLSNzIWcDcGihgwIExDS71Yjmtk2xrjjrKdeGZ0iG3BpIHuGpZYK5tGPO2l2w3ub@YOeBUk8pFYT4hcrbQHjdyomZsASNNallMhwsxEl8FJjkJH4SUdB6Dh1ZdxmDzhvpXF9lU5fmaKl6eeBl8t6kV/9Dpvz2@HYxtg@do/AUmcycDFOtyYV1z7BZBxxlnd1u6Z1171Njpiu8@Q3/QVvN9@f/SXd48cJLhL/IVa2uMnSo2TF9Lg@gxqXnZWEJZzhhTP/uavauefkE) thanks The Thonnu for pointing it out
Test code :
```
int t[5][4] = {
{1,1,1,1},
{0,0,1,0},
{1,1,1,0},
{1,1,1,1},
{1,1,1,0}
};
int main() {
printf("r=%d\n", f((int*)t,5,4));
return 0;
}
```
[Answer]
# Excel, 142 bytes
```
=LET(b,SEQUENCE(ROWS(a)),c,TRANSPOSE(b),MAX(MMULT(N(COUNTIF(OFFSET(INDIRECT(TOCOL(CELL("address",OFFSET(a,b-1,c-1)))),,,c,c),"<>1")=0),b^0))^2)
```
Input ***a*** is a *worksheet range* comprising the matrix. The above should preferably be placed in a worksheet different to that containing the matrix so as to avoid potential circular references.
Complexity is unfortunately \$\mathcal{O}(m^3)\$.
[Answer]
# JavaScript, 186 bytes
I know that the complexity should be `O(mn)` but here the complexity is `O((mn)^2)` :)
```
m=>eval('for(x=b=0;x<(r=m.length);++x)for(y=0;y<(c=m[0].length);++y)if(m[x][y]){for(o=s=1;o&&s<(c>r?r:c);++s)for(t=s+1;t--;)if(!m[x+s]?.[y+t]||!m[x+t][y+s]){o=0;--s;break}b=s>b?s:b}b*b')
```
Try it:
```
f=m=>eval('for(x=b=0;x<(r=m.length);++x)for(y=0;y<(c=m[0].length);++y)if(m[x][y]){for(o=s=1;o&&s<(c>r?r:c);++s)for(t=s+1;t--;)if(!m[x+s]?.[y+t]||!m[x+t][y+s]){o=0;--s;break}b=s>b?s:b}b*b')
;[
[
[1, 0, 1, 1, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0],
],
[
[1, 0, 1, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0],
],
[
[1, 0, 1, 1, 1],
[1, 0, 1, 0, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0],
],
[
[1]
],
[
[0]
]
].map(m => console.log(f(m)))
```
# JavaScript, 200 bytes
Here the complexity is much less than `O((mn)^2)` because if the algorithm find the biggest possible square it will stop
```
m=>eval('a=(c=m[0].length)>(r=m.length)?r:c;for(x=b=0;b!=a&&x<r;++x)for(y=0;b!=a&&y<c;++y)if(m[x][y]){for(o=s=1;o&&s<a;++s)for(t=s+1;t--;)if(!m[x+s]?.[y+t]||!m[x+t][y+s]){o=0;--s;break}b=s>b?s:b}b*b')
```
Try it:
```
f=m=>eval('a=(c=m[0].length)>(r=m.length)?r:c;for(x=b=0;b!=a&&x<r;++x)for(y=0;b!=a&&y<c;++y)if(m[x][y]){for(o=s=1;o&&s<a;++s)for(t=s+1;t--;)if(!m[x+s]?.[y+t]||!m[x+t][y+s]){o=0;--s;break}b=s>b?s:b}b*b')
;[
[
[1, 0, 1, 1, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0],
],
[
[1, 0, 1, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0],
],
[
[1, 0, 1, 1, 1],
[1, 0, 1, 0, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0],
],
[
[1]
],
[
[0]
]
].map(m => console.log(f(m)))
```
## Explanation
I will not explain each line of code because it is a lot and boring
Here is illustration of algorithm:
[](https://i.stack.imgur.com/dxOFQ.png)
When I meet the 1 in matrix (blue) I start checking the right and bottom edges of this cell (red cells) if all red cells are 1 then I start check the right and bottom edges of red cells (green cells) and so on until where I won't meet 0 or meet the matrix edge
] |
[Question]
[
[Robbers thread](https://codegolf.stackexchange.com/q/223160/45613)
Your task is to create a method for hiding information in an image. You will post three encoded messages of your choice (keep them classy), each with its associated image. Reveal the messages for the first two images and do not reveal the third. Robbers have the task of determining what your third hidden message is, along with an explanation of how your system works.
## Rules and Scoring
* Any data aside from the image required to make your algorithm work must be revealed openly and be constant across all possible message encodings.
+ For example, you may have a book cipher referencing The Great Gatsby (which is in the public domain as of January 1, 2021) as long as you link to the exact text required to make your system work.
+ RNG and Cryptographic algorithms are allowed under this caveat. Robbers should not be required to guess cryptographic secrets such as keys, hashes, salts, or initial seeds, as that easily makes cracking any given challenge infeasible. That would ruin the fun.
+ Do not share irrelevant information, e.g. "It's one of these 100 books" when you only use 1, or revealing a key which you don't use at all in your system, etc...
* Data may not be hidden entirely in image metadata; you must incorporate at least one bit of one pixel in your system of encoding.
* The encoded messages must be in English.
* The encoded message does not need to be easily machine-readable (though it's perfectly acceptable if it is), but must be reasonably legible as rendered.
+ For example, you could have the message manifest itself as a rendering in Arial. Or perhaps it renders as a figlet font in ascii art.
+ The hidden message being rendered in something like Wingdings would be unacceptable, however. Using a frilly gothic font is probably pushing it.
* You may encode the message as audio as long as it is intelligible to a fluent English speaker.
* The encoded message should always be in the same format. So for example, using a rendered hidden text image for one message, an audio recording for the second, and plain text for the third, would not be allowed.
* Data required to render the message as an image or audio is not considered part of the data required to make your algorithm work (which you would otherwise need to reveal)
* A rendered encoding must be intelligible as-is and not require additional processing, e.g. a ROT13 cipher.
* You may post more than 3 hidden messages if you wish, but keep in mind this is probably a disadvantage.
* You may only encode one message in the image. No (intentional) decoy messages.
* It's not required per-se that the images hiding your messages look like anything (e.g. cats, dinosaurs, scenic vistas, etc...), but you're no fun if they look like random noise and I will be downvoting any post that uses examples that do.
You will score 1 point if your system remains uncracked after 7 days.
[Answer]
# RRRGGGBBB!!! [`Cracked by Unrelated String`](https://codegolf.stackexchange.com/a/239965/98630)
##### Difficulty: Easy
---
## First image: `HELLO,WORLD!`
[](https://i.stack.imgur.com/mVA5k.png)
## Second image: `COPS AND ROBBERS`
[](https://i.stack.imgur.com/mMKDa.png)
## Third image
[](https://i.stack.imgur.com/oNgLT.png)
Title inspired by [rrrgggbbb.com](https://rrrgggbbb.com)
[Answer]
# Low difficulty
**Image 1:**
>
> `ABCDabcd01::::`
>
>
>
[](https://i.stack.imgur.com/Nz7gt.png)
**Image 2:**
>
> `Fun fact: The practice of designing a cryptographic algorithm which itself uses cryptography to allow the designer of the algorithm to read any message is known as "kleptography"` (not relevant to this, just an interesting field that's a friend-of-a-friend of steganography)
>
>
>
[](https://i.stack.imgur.com/uXQLP.png)
**Image 3:**
Crack this one!
[](https://i.stack.imgur.com/Mq03v.png)
## Hints
**Hint 1:**
>
> Only one color channel is relevant. Look for odd patterns.
>
>
>
**Hint 2:**
>
> Try looking at the parity of things. (You'll know what these "things" are when you see them)
>
>
>
**Hint 3:**
>
> Symmetry matters, but not necessarily the visual symmetry.
>
>
>
[Answer]
# [Cracked by Redwolf Programs](https://codegolf.stackexchange.com/a/239646/100664)
[](https://i.stack.imgur.com/3jUHD.png)
Message: HI
[](https://i.stack.imgur.com/HfXm1.png)
Message: BYE
[](https://i.stack.imgur.com/gMnct.png)
So what is this one?
I'll see what happens....
[Answer]
# Feline Steganography
### Image 1: `feline steganography`
[](https://i.stack.imgur.com/IDBDD.png)
### Image 2: `what could it be?`
[](https://i.stack.imgur.com/KSmSV.png)
### Image 3: ???
[](https://i.stack.imgur.com/KbMdc.png)
[Answer]
# Medium difficulty
**Image 1:**
`hello world`
[](https://i.stack.imgur.com/mRoK5.png)
**Image 2:**
`llama with wheels`
[](https://i.stack.imgur.com/k47i3.png)
**Image 3:**
[](https://i.stack.imgur.com/LUiWG.png)
[Answer]
# Should be easy
##### Image 1:
[](https://i.stack.imgur.com/hVf4q.png)
>
> `This was a really astoundingly terrible idea, come to think of it`
>
>
>
##### Image 2:
[](https://i.stack.imgur.com/H7iMP.png)
>
> `posed look`
>
>
>
##### Image 3:

[Answer]
# The sort you'd expect
**Image 1:**
>
> `These are colorful for a reason!`
>
>
>
[](https://i.stack.imgur.com/szWO1.png)
**Image 2:**
>
> `Stock photos FTW`
>
>
>
[](https://i.stack.imgur.com/vuXj1.png)
**Image 3:**
Crack this one!
[](https://i.stack.imgur.com/N5huG.png)
**Hint 1:**
>
> The title is a hint
>
>
>
**Hint 2:**
>
> This was inspired by emanresu A's cop
>
>
>
[Answer]
# Medium
*Note: I had to update the images due to a problem with the encoder, be sure to redownload them if needed*
**Image 1:**
`explore the universe`
[](https://i.stack.imgur.com/GOpvQ.jpg)
**Image 2:**
`no transparency?`
[](https://i.stack.imgur.com/gqIua.jpg)
**Image 3:**
[](https://i.stack.imgur.com/YJ2J2.png)
**Hint 1:**
>
> The first pixel of the image is the only one where the green channel is important.
>
>
>
[Answer]
# Should be easy for real this time
##### Image 1
>
> `This is a simplified version of my previous cop, and very directly so. I hope you can already guess at the basic principle of it, but I would strongly caution against trying to do this by eye alone.`
>
>
>
[](https://i.stack.imgur.com/O7UGJ.png)
##### Image 2
>
> `In combination with salt, this liquid will give the sea a flavour of the kind of lemonade known as aigresel. It will thus be easy to remove the saline and citric particles from the water and render it drinkable, which will make it unnecessary for ships to be provisioned with barrels of water. This breaking down of sea water by the boreal liquid is a necessary preliminary to the development of new sea creatures, which will provide a host of amphibious servants to pull ships and help in fisheries, replacing the ghastly legions of sea-monsters which will be annihilated by the admixture of boreal fluid and the consequent changes in the the sea’s structure. The sudden death of all of them will rid the Ocean of these vile creatures, images of the intensity of our passions which are represented by the bloodthirsty battles of so many monsters.`
>
>
> `--Charles Fourier, apparently` (there's only supposed to be one newline)
>
>
>
[](https://i.stack.imgur.com/AEE7H.png)
##### Image 3
[](https://i.stack.imgur.com/NA9gz.png)
Hints even though it's already been a week:
>
> An image composed entirely of red and white of the same intensity (by some measure) could not encode a message. Replace either with yellow, and it could.
>
>
>
>
> The message is encoded in UTF-8.
>
>
>
] |
[Question]
[
[](https://i.stack.imgur.com/sjl00.png)
**Challenge:**
Find the number of ways to climb some stairs with n steps and with some limitations. You should be able to run the tests below on TIO <https://tio.run/> **without timing out.** – 60 seconds. (Typically a fraction of a second is well within reach for most languages if a good optimizing strategy is applied).
**The input is a list of positive numbers:**
* the first number in the input is the total number of steps in the stairway
* the rest of the input is the different number of steps you are allowed to climb at once, but you're only allowed to use n steps a maximum n times if n>1. So if 2 is allowed you're only allowed to take 2 steps a maximum of 2 times. And 3 steps maximum 3 times and so on for all n>1. So if 1 is allowed, you can take 1 step as many times as you like.
* you should not "overstep", with a stairway of 5 steps and only 2 steps at once are allowed, there is no way to climb it (output 0)
Allowed assumptions: all input numbers are positive integers, at least 1 (0, negative and fractional numbers need no special handling). The list of allowed steps are unique numbers and ordered if it helps. Also the size of the stairs can be the last number or a separate part of the input if that's helpful to your implementation ("reorganizing" input don't need to be a part of the problem)
**Output:**
* a number which is the number of ways to climb the stairs
**Examples:**
* Input: 3,1 Output: 1 (as there is only one way when you're only allowed one step at a time)
* Input: 3,1,2 Output: 3 (since you can climb in three ways: 1+1+1 or 1+2 or 2+1)
* Input: 3,4 Output: 0 (you should always end at the top, you cannot take 4 steps since the stairs only has 3)
* Input: 4,1,2,3 Output: 7 (1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2, 3+1, 1+3)
* Input: 6,2 Output: 0 (since you're not allowed to take 2 steps 3 times)
* Input: 6,2,1 Output: 12 (2+2+1+1, 2+1+2+1, 2+1+1+2, 2+1+1+1+1, 1+2+2+1, 1+2+1+2, 1+2+1+1+1, 1+1+2+2, 1+1+2+1+1, 1+1+1+2+1, 1+1+1+1+2, 1+1+1+1+1+1. But 2+2+2 isn't allowed)
* Input: 99,99,1 Output: 2 (99 or 1+1+1+1+...99 times)
**More tests:**
```
2,1 → 1
10,1 → 1
3,1,2 → 3
3,4 → 0
3,2 → 0
4,1,2 → 5
4,1,2,3 → 7
6,2 → 0
6,2,1 → 12
7,1,2 → 17
5,1,2,3 → 13
15,1,2,7 → 266
39,3,2,7 → 301
99,11,3,2 → 1981
```
[Answer]
# JavaScript (ES6), 71 bytes
Expects `(list)(n)`.
```
(a,t=0)=>g=n=>n>0?a.map(x=>--g[(g[x]=-~g[x])+~x|x<2&&g(n-x),x])|t:t+=!n
```
[Try it online!](https://tio.run/##ddHdbsIgFAfw@z0FuzEQQfmo7VhG9yCNF8Qp2eKo0cZwYXz1jq4wJxVuSMgvh3P@50uf9Wlz/Dx0xLYf236neqhxpyhStVFW1bam73rxrQ/QqZoQ00DTuLUi1@FC86u7uDc@mxloiUPYP126126unm2/ae2p3W8X@9bAHWwYGM4aQYEQAMslYE@pwPxeiFQUaQ36oAYWgyiCqFLBY40yV4Njdi8YT4mUg/FESm88mYi/cQEfBcsKRnMiBgLEKPKBREGz42bF7ZdiFKtsqFHkQwVlro8YahTTUG@NVIFU@U5WgYhHpPqNNRBelqkR0YiwPkGn4TPs2b8VM/nC@h8 "JavaScript (Node.js) – Try It Online")
### Commented
```
(a, t = 0) => // a[] = input list, t = output
g = n => // g is a recursive function taking the number of steps n
n > 0 ? // if n is positive:
a.map(x => // for each value x in a[]:
--g[ // decrement g[x] afterwards
(g[x] = -~g[x]) // increment g[x]
+ ~x | // if g[x] is not equal to x + 1
x < 2 && // or x = 1:
g(n - x), // do a recursive call with n - x
x // actual index to update g[x]
] // end of entry update: this is guaranteed to be 0 on
// the first iteration; therefore, .map() is coerced to
// 0 by the the bitwise OR even if a[] is a singleton
) | t // end of map(); yield t
: // else:
t += !n // increment t if n = 0
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes
```
⊞υ⟦Eη⟦ι⎇⊖ιιθ⟧⁰⟧FυF‹§ι¹θF§ι⁰⊞υ⟦ΦE§ι⁰Eμ⁻ξ∧π⁼μλ§μ¹⁺§ι¹§λ⁰⟧I№Eυ⊟ιθ
```
[Try it online!](https://tio.run/##ZU/LCsIwELz7FXvcQAQfeOqp@ABBoQdvpYfQRhpI05o0Ur8@bmoVxRwyuzMTZlLWwpat0CFk3tXoOeRn0WFNqDhcpDXCPnAnSysbaXpZoWIcSLqxgoZFwZLZtbWAnsGIJ@kcpv3RVHJA8i1Z9E7iF78g7hN5ULqXFmPyj4VDpBoCZbzDgUNqKuw47G9eaBcVzegQPz1rYiLtmfZ/Nd6rHtNj88wq0@NWOLpaT2OMo0JZ29E/X81ZEkK@oZJLDisO66II87t@Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⟦Eη⟦ι⎇⊖ιιθ⟧⁰⟧
```
Start a breadth-first search with a tuple of a list of steps and remaining counts (except that the count for a single step is the total number of steps) and the number of steps taken so far.
```
Fυ
```
Loop over every possible permutation of steps.
```
F‹§ι¹θ
```
If the total has not been reached, then...
```
F§ι⁰
```
... loop over the remaining steps, and...
```
⊞υ⟦ΦE§ι⁰Eμ⁻ξ∧π⁼μλ§μ¹⁺§ι¹§λ⁰⟧
```
... push a tuple of the list with one step removed (entirely if the count falls to zero) and the new position reached.
```
I№Eυ⊟ιθ
```
Count the number of times the desired total was reached exactly.
[Answer]
# [R](https://www.r-project.org/), 171 bytes
```
function(N,S){s=S;s[s==1]=N
for(i in 1:N){m=expand.grid(rep(list(S),i))
m=t(m[rowSums(m)==N,])
if(z<-ncol(m))for(j in 1:z){R=m[,j]
t=table(factor(R,S))
F=F+all(t<=s)}}
+F}
```
[Try it online!](https://tio.run/##TY49b4MwEIZ3/wrGO8WpavJRqeVWRoYwIgZCcOTINpHtqFUQv51CHCmZ3o979OrcJJNsnUzyZtugegsFL3HwVP74yhOJmgomewcqUTYR3wUOhrq/a2NPH2enTuC6K2jlA5TIFSIzFMBUrv8tb8aDQaKC18iUhHu2tm2v5w6XwUscvONwIFPxS80CheaoO5BNG2bgMD@CLKd81WgNISOP48hW@ThJ@OQCmYQ0injGDW9B8BSj30ZJF9m@XZ6ebx5pH4H9XC5ri/96g3cvePoH "R – Try It Online")
Times out for large `N`.
This is rough for R. Looking at [this recursive solution](https://tio.run/##DcOxCsJADADQb7lOCaRgHVxK/IQsGcUhVCIH13qY61DEbz998N69O/u@LS2/NhBSCv4Y62w3Y57uLLN9ccg@gFxPFPsKq9VaDnCSUankaKBIUUtu0CDGR7YnpKSI9I@UBLvDhRaY6IzYfw) which is still wrong, but a decent start, should anyone want to pick up where I left off -- note that it requires `S` to be sorted ascending due to `split`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 119 bytes
```
If[#<1,0,Length@Flatten[Permutations/@(S=Select)[IntegerPartitions[#,All,#2],And@@(#>=#2&@@@S[Tally@#,#&@@#>1&])&],1]]&
```
[Try it online!](https://tio.run/##HcqxCsIwEIDhVxEOQgsHmjoVbLkuQsGhULeQIdQzLaQR4jmI@OyxOP58/@pk5tXJMrnsm9zfDZw0HvDC0ctM5@BEOJqB0/qSbXvE556KsRk58CSl6aOw5zS4JMtfDWAXAkJlsYs3ogLaBipFRKO5uhDeBAhbQquVLZVFba3KQ1qi7MibusaP1njE6mtz/gE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 120 bytes
```
def f(z,w,a=0,s=0,i=0):
for x in w:b=(a or w)[:];b[i]-=1;s+=b[i]*(x-1)>=0and(f(z-x,w,b)if z>x else z==x);i+=1
return s
```
[Try it online!](https://tio.run/##rZBNb4MwDIbv/Aorp2QYiZCWrqD0tvOkXlEOoJIObaJVYILx51n46JSut2mRItlPHL@vff1q3y61GMdTqUHTATvMZYiNvZUMWeKBvhjooaqhSwpJc7Bpx7JEpUVWqUDytPHlFD7RPuDsIMO8PlHbKehtr4JVGoZDD@VHU8IgZc/SypfcA1O2n6aGZhY@W2HoEMwkCNqAXLyw1KZrJSHgQ9MaOjAbEMhueTfnChK4EW2WEpgJJZd3AtaHNlKaxQkJpgMvx@PrEeaYMM@7mqpu6ZkKzLhCztgdwUihuGcbhaFDNnMVCoU7h8aYRfd1E8FJIXLgfo@ZvRa7NHqwwsM/uhMPPjbrv@1/zbBbG3L37/anI3cN8pXv7MBx7Pq0ixDLgwj5rw1xjmJW2D9PT@M3 "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
```
f=lambda n,s,p=[]:0**n+sum(f(n-d,s,p+1%d*[d])for d in s if p.count(d)<d<=n)
```
[Try it online!](https://tio.run/##rZDfa4MwEMff@1ccgUHSXocxrU5XH/c86KvkoVtMJ2ujRKWs/7yLth1xfRsLBO4@9@t7V3@1H5URfa@zw@74pnZgsME6y2UazOdm0XRHqqlZqoEu@IOa50oyXVlQUBpooNRQP75XnWmpYhu1yQzrVaFhT88IJwTL0hmAtpCBdujEnp1ri7azBgiBBTStpWfmDAL5zT@NvoQUbkTbSwqMhJLqkwyjtc0yC8WhKYAshwcv2@3rFkabsNmstqVTtqcCcy6RMzYhGEoUU7aSGHhkNWahkBh7NMI8nOYNBIcJoQeTBHP3HfZpeCeFB39UJ@50rK516//aIb425H7t@qcj9wXyK4/dwlHk63SHEJeACPivC3GOYpyQPA2h/hs "Python 3 – Try It Online")
Based on [Donat's solution](https://codegolf.stackexchange.com/a/216653/20260).
[Answer]
# [Scala](http://www.scala-lang.org/), 123 118 115 bytes
Thanks to user x2
```
% =>b=>1 to%map{b.flatMap($=>Seq.fill(if($<2)%else $)($))combinations _ flatMap(_.permutations)count(_.sum== %)}sum
```
Input: (#steps)=>(list). The algorithm creates the list of all allowed steps, analyzes all the permutations of the combinations of n elements (n from 1 to the number of stairs) and counts the ones that sum up to the number of steps
[Try it online!](https://tio.run/##fdJPa4MwFADwez7FO1RIIEijbZ1lKew42E7dTmWUaGObodFpLIziZ3epdpt2f7y8p7/k5T1JFYtUtHn0KmMDT3BCaCcTyITSWJT7agl3ZSneN2tTKr1/IUt41soAtwsBjiKFpNaxWcK9NnwFD6oyG5u@gH2xEThqHZtHfMXA5E4milPkJqkwj6LAE75ayzc3UWmKVYIntx5xZFpJmBA8ISTOs0hpYVSuK9jC566tW8gyq00PdlWtjf1Y1Rnn4JDGJi06d3a0XZ4bwgh3waMMuocAUOhyQi/Gphf8xXzKqPdl/pXNBjWnV@b9abNRzflPo/7FgpEt/qlprR@in8EbWjA6jwVDm4/OY/7ov/QY9OYtFsP5Qup/mz9lAwtDytiZ@5rhDQNCEDq6SV5KER9OsagkFjQi9qIU9mqZVOOI8@42YeEepNgRG41QKSENQk3TfgA "Scala – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 129 bytes
```
int f(int z,int[]...v){int s=1/~z,i=0,a[];for(int y:v[0])s-=--(a=v[v.length-1].clone())[i++]<0&y>1|y>z?0:f(z-y,v[0],a);return-s;}
```
[Try it online!](https://tio.run/##tZNPc6IwGMbvfop3MmMnGd9kCVitWNrTHjs7Y4@UQ6rQpbXQIRGLLv3qNlCZVetx95KQ55e8/@bhWZWKPy9edvOl0hrutgC7NDOQ0GbdoF3DSAhRsm0j6ED@@LBq4KAKo2mSF@29yi9DJ2KaB5xTFZRhKZZx9mR@cxmJ@TLPYspYmA4G0bVzUd3IP9XN5tbxE7rhFTZPUbFpEZtVkXE9rXfwtnpcpnPQRhm7lXm6gFeVZvTeFGn2FEaKbXsAhnqYxWtoi9zKGiWbfpfRrdE7A4Y1Ont5eHwfvRrHezQ6QO7fF0cyNqndPZlMDpA9WNYh93y10vk3XXjnSx2ehrn8D12PT5PILtTl9yyya0SewrEd1mjU9XM4Se@Leo48N2cp0WuzTq4sB@hB3Ttyjzn087rZoGg91Jo9aCLdUSasI3HdJihVYd1OSPPd2fzdXzM9CN4HBFv9vtImfhX5yog360uTUNJ3FxD2@ZWOwIf@cAHQ1w8ZwQ1qoVePuvUvdezp6wehjEuGCSZBUNyS/IX45Ods9mtGmiLqXr37BA "Java (JDK) – Try It Online")
Reduced from 167 to 161 with hint by ceilingcat.
Further reduced to 153, 136, 132 now.
From 132 to 129, thanks to ceilingcat.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~74~~ ~~65~~ 63 bytes
```
Sum[UnitStep@@(--+#(#-a))Multinomial@@a,{a,FrobeniusSolve@##}]&
```
[Try it online!](https://tio.run/##TYtBC4IwHMXvfo2BKE1oaYWH4n/qFhSjk3hYMmmgM2x2GfOrr3RNuv3e773XMvXgLVOiYrY@WDq0xU0KRRV/AkRJskIRSlgcn4dGCdm1gjUADGuGT31351IML9o1bw4ImTK010FwBZdeSFWg5FgDoDIcacXkqAOticFrgx1sPJCfmkw6Y@ZhMXOZeZxk5gc7B5h4nLf7/@12CV9NXEpdSnPXEZxOtzw3gbEf "Wolfram Language (Mathematica) – Try It Online")
```
Sum[ ,{a,FrobeniusSolve@##}]& (* for each way to climb with the given step increments, sum *)
Multinomial@@a (* the number of rearrangements *)
UnitStep@@(--+#(#-a)) (* if no quotas are surpassed *)
```
---
### 66 bytes
```
If[#>0,If[##3'~Count~i>=i>1,0,#0[#-i,##2,i]]~Sum~{i,#2},1+Sign@#]&
```
[Try it online!](https://tio.run/##TYw9C8IwEIb3/o2ADp6Qj2rp0FBwchM6lg6hWM3QFCSdQvLXY2KMdbrnuXvvnYV@3meh5Sj81Pjr1COOIQ7E9u6yrEo7yRvJCWBAuEdHCQhRkMPgunV2Jii1QA6dfKgWDTt/e0mlQ45PbXTXjUI5UxgMhlgLhaEZyG/FAgDNWGZIm3I7JgT2kXMORIBUVG3Z03@WfK1K1TWE@mx1MEKAxb/C@jc "Wolfram Language (Mathematica) – Try It Online")
A recursive function. Move the outer condition into the sum to conform to the initial spec: [68 bytes](https://tio.run/##TYxPC4IwGMbvfosY2OUN3GaJkEPq1C3wKDsMURqkQszT2L76mq1lp/f3/HmfUahHPwolO@GGyt2GFiG6t9d5mZSVrJIMQwarzSSgrEUHfxAByeEyz8@@3qGz5Nw2y2i1j4hJ3f0lJ@WbbKhrxFPbdGKyOtEZaGwMJJpEwD@LegASMY8QnHwLAwL9iFMsrABhqNi6x/8u/qoiTJfg56MqvcIY6PqXGPcG).
```
If[#>0, (* if there are still stairs to climb, *)
If[##3'~Count~i>=i>1,0, (* and we haven't used up our quota of i-steps, *)
#0[#-i,##2,i]] (* check how many ways there are after an i-step, *)
~Sum~{i,#2}, (* and add those up for all possible step sizes. *)
1+Sign@#]& (* otherwise, check if we overshot. *)
```
[Answer]
# [Perl 5](https://www.perl.org/), 75 bytes
```
sub f($z,$w,%a){$z&&map{%b=%a;++$b{$_}>$_&$_>1|$_>$z?():f($z-$_,$w,%b)}@$w}
```
[Try it online!](https://tio.run/##pY9Pa4NAEMXv@RSDjKmSCWTd/GkSTHLpsRRytSJKtdg2Kq4hVOtXr921KsmxdGGXnd/ue/MmC/OPRdOIcwCRgSXhhXTfrLAcj09@VumBrfvbyQSDCr16h94YvR37kgeWe8PcKM0UvVYWmPUBL3XrVYSigGoEcPqEzhZz0z54W8kwysHu25mKZHmcFBFoWIKjCxc2oL8AgC6eE43gLY0T447uSNqbpOQkTaPctjGHPWjpuyYV2lQteDgen47Q3jXpXY9GKovByWEuMUmGkiyX@BWYuzTry3n7TtylVY@W5FhXP1RJytLqyXpNjtySDci67cpmf0vBb1vOu@@L/6RcdSZskCwGFzYEYR1cyWGWyyGPnJD/Uj5j13MzRrx1Xd9L3nynWRGniWimj1HoF@c8nIj4NWlv4gc "Perl 5 – Try It Online")
The function returns a list of zeros. Perl will convert it to the number of its elements, when evaluated in scalar context. This will be the result.
Evaluation in scalar context can be forced by a helper function like this:
```
sub g{+&f}
```
In my test cases this not necessary because the result is treated as a scalar value.
] |
[Question]
[
The task is a rather simple quine challenge with a twist, you must output your source code in the shape of a pyramid. The shape of a pyramid is defined below:
```
1
234
56789
ABCDEFG
HIJKLMNOP
QRSTUVWXYZa
bcdefghijklmn
......etc......
```
The main limitation of this challenge is that your quine must contain exactly enough bytes as to not obstruct the pattern of the pyramid. For instance, the following program lengths would work:
```
1-byter: 1st layer of the pyramid (not allowed by definition of a quine).
4-byter: 1st and 2nd layers of the pyramid.
9-byter: 1st, 2nd and 3rd layers of the pyramid.
etc...
```
So, if your program was:
```
QWERTY
```
It would not be valid, because it would arrange like:
```
Q
WER
TY
```
However, if your program was QWERTYUIO, it would be fine:
```
Q
WER
TYUIO
```
---
# Rules
* Standard loopholes are obviously disallowed, no reading your own source.
* The pyramid must be centered, trailing characters are allowed, but not required.
+ Also, any character may be used to center the pyramid, doesn't have to be `(char)32`.
* Your quine must be able to be shaped into a pyramid.
+ It must retain the original ordering of your sourcecode.
+ **Your source-code may *NOT* contain the character being used to format the pyramid.**
+ E.G. if your sourcecode contains a space, you'll need another char for the format.
* You may use comments in your quine to "pad" to the correct size.
+ Obviously, these must be output as part of the quine.
* If the program contains newlines/tabs, they aren't part of the quine and should be omitted in the output.
* The shape is counted in characters, not bytes; if the shape is malformed you're not doing it right.
**The lowest possible score here should be 4.**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 36 bytes
```
"34çs«DJā·<£õK.cJ?"34çs«DJā·<£õK.cJ?
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fydjk8PLiQ6tdvI40Htpuc2jx4a3eesle9rjE//8HAA "05AB1E – Try It Online")
If `trailing characters are allowed` also means at the end of the output, `0"D34çýā·<£.c"D34çýā·<£.c` is a layer shorter at 25 bytes.
[Answer]
# Java 11, ~~324~~ ~~256~~ 227 bytes
```
v->{var s="v->{vars=%c%s%1$c;for(inti=0;;)System.out.printf(%1$c%%%1$c+(15+i)+%1$cs%%n%1$c,s.format(s,34,s).substring(i*i,++i*i));}///";for(int i=0;;)System.out.printf("%"+(15+i)+"s%n",s.format(s,34,s).substring(i*i,++i*i));}//
```
-29 bytes thanks to *@JoKing*.
Outputs with leading spaces to make the triangle. (Note that the whitespace between `var s` and `int i` are tabs, not spaces.)
[Try it online.](https://tio.run/##lVDLTsMwEDy3X7GysGTj1KECTlb4A3qpxAVx2LoJckmcKutYQlW@PdglPXLgMvvQzo5mThhxczp@zbZFInhF5y9rAOdDPTRoa9jlESD27ghWvOUSpUm7aZ2AAgZnYQceKpjj5uUScVhRxZaWKm458e2dNU0/iPTWVQ/GyP03hbrT/Rj0eUjbRuQbzjMqsX1WTqrcE@c@14J04ncYBBWPTwVJTeOBQqJ@CnfvCqUSSmmmsizZTWr1lxbj7CbCiHv2j@@zybbP46FNthf312y6lJzYXznvH4DyNzavrfBj2y6JTfMP)
**Explanation:**
**[quine](/questions/tagged/quine "show questions tagged 'quine'")-part:**
* `var s` contains the unformatted source code String
* `%s` is used to put this String into itself with `s.format(...)`
* `%c`, `%1$c` and `34` are used to format the double-quotes (`"`)
* `%%` is used to format the `%`
* `s.format(s,34,s)` puts it all together
**Challenge part:**
```
for(int i=0;;) // Loop `i` indefinitely upwards from 0
System.out.printf( // Print with format:
"%"+(15+i)+"s // Add leading spaces to make the line length size 15+`i`
%n", // And include a trailing newline
s.format(s,34,s).substring(
// And append a substring of the source code-String
i*i, // From index `i` squared
++i*i));} // To index `i+1` squared
```
Which stops with an `java.lang.StringIndexOutOfBoundsException: begin 225, end 256, length 226` error for the `String#substring(int,int)` method, the iteration after it has printed the result ([which is fine according to the meta](https://codegolf.meta.stackexchange.com/a/4781/52210)).
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
s='n=0;\nprint(8-n)*chr(32)+("s=%r;exec(s*9)"%s)[n*n:][:n-~n];n+=1;#JK';exec(s*9)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWPc/WwDomr6AoM69Ew0I3T1MrOaNIw9hIU1tDqdhWtcg6tSI1WaNYy1JTSbVYMzpPK88qNtoqT7cuL9Y6T9vW0FrZy1sdoej/fwA "Python 2 – Try It Online")
An eval quine that uses spaces as the filler character.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 67 bytes
```
<say("<$_>~~.EVAL".substr($!++²,$!*2-1).indent(8-$!))xx⁸>~~.EVAL
```
[Try it online!](https://tio.run/##K0gtyjH7/9@mOLFSQ8lGJd6urk7PNczRR0mvuDSpuKRIQ0VRW/vQJh0VRS0jXUNNvcy8lNS8Eg0LXRVFTc2KikeNO2A6/v8HAA "Perl 6 – Try It Online")
I used a couple of unicode characters in order to squeeze out that extra layer. Outputs using spaces:
```
<
say
("<$_
>~~.EVA
L".substr
($!++²,$!*2
-1).indent(8-
$!))xx⁸>~~.EVAL
```
### Explanation:
```
<say("<$_>~~.EVAL" ) >~~.EVAL # Normal quine
.substr($!++²,$!*2-1) xx⁸ # Split into layered substrings
.indent(8-$!) # And indent each one
```
[Answer]
# [Python 2](https://docs.python.org/2/), 169 bytes
Uses `0` for formatting the pyramid.
```
s='s=%r;k=s%%s;print"\\n".join(`1-1`*(12-n)+k[n*n:][:n-~n]for n in range(13))#######################';k=s%s;print"\n".join(`1-1`*(12-n)+k[n*n:][:n-~n]for n in range(13))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWvdhWtcg627ZYVbXYuqAoM69EKSYmT0kvKz8zTyPBUNcwQUvD0Eg3T1M7OzpPK88qNtoqT7cuLzYtv0ghTyEzT6EoMS89VcPQWFNTGTtQB5sON5w8s///BwA "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 147 bytes
This uses the rule *If the program contains newlines/tabs, they aren't part of the quine and should be omitted in the output.*
```
s='s=%r;k=s%%s;print"\\n".join(`1-1`*(12-n)+k[n*n:][:n-~n]forninrange(13))##';k=s%s;print"\n".join(`1-1`*(12-n)+k[n*n:][:n-~n]for n in range(13))##
```
[Try it online!](https://tio.run/##jcw9CoAgAAbQ2WsYkhYG1lZ4kgxq6MeCz9CWlq5u0BCNvQO8/TwWhzLGoNOgmW82HRgLze4tDmoMaLE6C94rqfqMq1JC5FuLDHXX1pAXusl5WPgB88hVJUSSpM/yJv8OAmJBvk2MNw "Python 2 – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 36 bytes
```
":P}r6&56F:M}F0ss|&:P&Roao{|;Nooooo!
```
[Try it online!](https://tio.run/##S8/PScsszvj/X8kqoLbITM3UzM3Kt9bNoLi4Rs0qQC0oPzG/usbaLx8EFP//BwA "Gol><> – Try It Online")
**an even younger version, 36 bytes**
```
":P}r6&56F:M}R` &:P&Fo|ao{|;Noooooo!
```
I feel so close to getting it one line shorter, grrrr....
[Try it online!](https://tio.run/##S8/PScsszvj/X8kqoLbITM3UzM3KtzYoQUHNKkDNLb8mMb@6xtovHwwU//8HAA "Gol><> – Try It Online")
**even younger version, 36 bytes**
```
"r2ss6&56F:M}R` &:P&Fo|ao{|;what????
```
This one's code is smaller, but it still comes out to the same amount sadly, the comment takes up the remainder of the space.
[Try it online!](https://tio.run/##S8/PScsszvj/X6nIqLjYTM3UzM3KtzYoQUHNKkDNLb8mMb@6xro8I7HEHgj@/wcA "Gol><> – Try It Online")
**slightly younger version, 36 bytes**
```
"r2ss156F:M}F` o|:PP}Fo|ao{{|;Wowza!
```
Wowza! Heh, I just used that to fill some space, but the program works, to golf down, I used a few prepushed values rather than using variables!
[Try it online!](https://tio.run/##S8/PScsszvj/X6nIqLjY0NTMzcq31i1BIb/GKiCg1i2/JjG/urrGOjy/vCpR8f9/AA "Gol><> – Try It Online")
**Older version, 42 bytes**
```
"r2ss0V_~6:&F&:M&F` o|_PPV_Fo|ao|;empty...
```
This has a trailing newline, and has more chars than i would like...
I'm going to be golfing this severely...
[Try it online!](https://tio.run/##S8/PScsszvj/X6nIqLjYICy@zsxKzU3NylfNLUEhvyY@ICAs3i2/JjG/xjo1t6CkUk9P7/9/AA "Gol><> – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 256 bytes
```
module QQ;import StdEnv,Text;q=dec'#';$n#k=(s<+q<+s<+q)%(n^2,n^2+n*2)=lpad k(16+n)(dec q);Start=join{toChar 10}(map$[0..15]);s="module QQ;import StdEnv,Text;q=dec'#';$n#k=(s<+q<+s<+q)%(n^2,n^2+n*2)=lpad k(16+n)(dec q);Start=join{toChar 10}(map$[0..15]);s="
```
[Try it online!](https://tio.run/##xU3NSsNAGLznKT5spRvTbJqCXrYrSA0otGqoN1HZZFcauz9J9qtUxGePqxd9Aw8zzAwzTCX8dhhqgXBelrSpdaQOresRlqvi4ub56nZd8My1mNVaCRv9yqxqbFAGUvluhWlqD@n1Ci7/mjst8MX1oVNBahFS46EsI5oJ6vY4DMbJvVYhYo35Od2gLOzb9F4dkHVcqnoymrCxHe048YukWyTfHB8T@zSfBiT2ZB5z3QoJO5KfJTYmYQNdzDYoeuSvrrEf6JZb0UM@@yRGtOOHGaX56WPMPD/67/8v "Bash – Try It Online")
Pretty much the standard quine, conveniently also a template quine, with the formatting function added.
[Answer]
# [R](https://www.r-project.org/), ~~169~~ 144 bytes
```
s='`!`=intToUtf8;cat(sprintf("%*s",11+(i=1:12),substring(paste0("s=",q<-!39,s,q,";eval(parse(t=s))"),(i-1)^2+1,i^2)),sep=!010)';eval(parse(t=s))
```
[Try it online!](https://tio.run/##ZYxBDsIgEADfAonprt0mLF7Uyi/02hQNNSSNUhb9PnL3OjOZXKu4blazi69yfd/KchwfvoCk3MACercXTcw9RMdntkjyuUtp8gnJSwkGtDhN22VQhxMJbaTH8PVrs1kCFCeIGgniwDjZnilOFtslJKcMG@z@6lp/ "R – Try It Online")
```
s
='`
!`=in
tToUtf8
;cat(spri
ntf("%*s",1
1+(i=1:12),su
bstring(paste0(
"s=",q<-!39,s,q,"
;eval(parse(t=s))")
,(i-1)^2+1,i^2)),sep=
!010)';eval(parse(t=s))
```
Managed to shorten it by moving to a string that’s parsed rather than an expression that’s departed. Had to use a redefinition of a unary operator to get it under the 144 though.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 225 bytes
```
var s="var s={0}{1}{0};for(int i=0;;)WriteLine(string.Format(s,(char)34,s).Substring(i*i++,2*i-1).PadLeft(i+14,(char)2));//";for(int i=0;;)WriteLine(string.Format(s,(char)34,s).Substring(i*i++,2*i-1).PadLeft(i+14,(char)2));//
```
Uses a `STX` char as padding. Did not realize Kevin Cruijssen already submitted an exact copy in java before posting until I was done, but I decided to post this anyways.
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSeu0/CKNzLwShUxbA2trzfCizJJUn8y8VI3ikqLMvHQ9t/yi3MQSjWIdjeSMxCJNYxOdYk294NIkiLRGplamtraOkVamrqGmXkBiik9qWolGprahCVS9kaamtb6@El1s@f8fAA "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
I'm attempting to create a function over multiple lines.
# Parameters of the challenge:
1. Function returns 'barbarian'
2. Only 2 characters per line
3. 40 lines maximum.
I keep trying to use a fat arrow to declare my function, but fat arrows don't seem to work if you don't have them connected.
Source of Challenge: <https://www.codewars.com/kata/multi-line-task-plus-plus-hello-world>
My current work:
```
f=
(
)=>
'\
b\
a\
r\
b\
a\
r\
i\
a\
n\
s\
'
```
This works, but the ')=>' is 3 characters long. I really just want to know how it is possible to even stretch out the creation of a function. I can't find any info on it anywhere as it's obviously not very practical.
[Answer]
# 35 Lines
```
f=
0[
c=
'\
c\
o\
n\
s\
t\
r\
u\
c\
t\
o\
r'
][
c]
`
r\
e\
t\
u\
r\
n\
'\
b\
a\
r\
b\
a\
r\
i\
a\
n'
`
```
[Try it online!](https://tio.run/##VYtBDkAwFET3c5HqgriAk/gSVSVE@qUt16/6C4ndvDczu7lNtGE7U@15djkvHdoetoMiWAITPCESEiEQLpFJfFAYynLA@DZO9CWr8ijviWAEv7BJ8ApjtuwjH645eK0WjR9WWucH "JavaScript (Node.js) – Try It Online")
Uses the fact that `0` is a number, the constructor of `0` is `Number`, and the constructor of `Number` is `Function`.
# 32 Lines
```
0[
c=
'\
c\
o\
n\
s\
t\
r\
u\
c\
t\
o\
r'
][
c]
`
f=
_\
=>
'\
b\
a\
r\
b\
a\
r\
i\
a\
n'
`(
)
```
[Try it online!](https://tio.run/##VYtBDsIgFAX3cxFgofECeBF/Y5G2pqbhG0Cvj8qiibt5k3mP8A4l5vVZD0mnubXThegxQhRUSEIRqpCFV5e1@2wYvuXAyOK5Cv78O92E0Nsd1g7JMFpci5qKbvNx07tdHH/TOtc@ "JavaScript (Node.js) – Try It Online")
This essentially runs
```
Function(`
f=
_=>
'barbarian'`)()
```
which uses the [IIFE structure](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression). Added bonus is that we can line-break some parts in the function body to reduce the line count.
# 24 Lines
```
f=
''
[
'\
t\
r\
i\
m'
][
'\
b\
i\
n\
d'
]`
b\
a\
r\
b\
a\
r\
i\
a\
n`
```
[Try it online!](https://tio.run/##VYpNCoAgFAb330XURd2gk/QCzZ8wTEOl61u5CNrNDLOrSxWd/VmHmIxtzU1gDDMYoRIywRMOhqWXtWskmKfIV1V/PvAdomw6xZKCHUPauBP4KRei3Q "JavaScript (Node.js) – Try It Online")
Inline version:
```
f=''['trim']['bind']`
barbarian`
```
Since all we want is to return a string, we can get away with a string method bound to a string. By using `trim`, we can also safely leave a beginning newline.
[Answer]
Here is a 38 line solution:
```
f=
[]
[
'\
m\
a\
p'
][
'\
c\
o\
n\
s\
t\
r\
u\
c\
t\
o\
r'
]`
r\
e\
t\
u\
r\
n\
'\
b\
a\
r\
b\
a\
r\
i\
a\
n\
'`
```
It creates a function using the `Function` constructor, which it accesses from `[].map.constructor` using subscript notation (`[]['map']['constructor']`). This is the method JSFuck uses to create functions.
] |
[Question]
[
*This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge the Cops' Thread can be found [here](https://codegolf.stackexchange.com/questions/111190/anagram-quines-cops-thread)*
Your challenge, as robbers is to take outputs from the cops' thread and find anagrams of the output that when run as a program output the original output provided.
The winner will be the person with the most valid cracks on this question.
## Rules
* You may not crack answers marked as safe with a provided program.
* If a cop provides a language that the intended solution is in you must crack it in that particular language, if they choose not to you may crack it in any competing language.
* Standard rules for Quines apply.
* Cracks must not be perfect Quines. i.e. they must not output their exact source but a reordering of it (the order is provided by the cop).
[Answer]
# [Unspecified language (CJam), 254 bytes, DJMcMayhem](https://codegolf.stackexchange.com/a/111205/12012)
```
0000000: 3235 362c 583e 3130 2d5b 445d 2f41 612a 256,X>10-[D]/Aa*
0000010: 3a63 6523 0102 0304 0506 0708 090b 0c0e :ce#............
0000020: 0f10 1112 1314 1516 1718 191a 1b1c 1d1e ................
0000030: 1f20 2122 2425 2627 2829 2b2e 3334 3738 . !"$%&'()+.3478
0000040: 393b 3c3d 3f40 4243 4546 4748 494a 4b4c 9;<=?@BCEFGHIJKL
0000050: 4d4e 4f50 5152 5354 5556 5759 5a5c 5e5f MNOPQRSTUVWYZ\^_
0000060: 6062 6466 6768 696a 6b6c 6d6e 6f70 7172 `bdfghijklmnopqr
0000070: 7374 7576 7778 797a 7b7c 7d7e 7f80 8182 stuvwxyz{|}~....
0000080: 8384 8586 8788 898a 8b8c 8d8e 8f90 9192 ................
0000090: 9394 9596 9798 999a 9b9c 9d9e 9fa0 a1a2 ................
00000a0: a3a4 a5a6 a7a8 a9aa abac adae afb0 b1b2 ................
00000b0: b3b4 b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2 ................
00000c0: c3c4 c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2 ................
00000d0: d3d4 d5d6 d7d8 d9da dbdc ddde dfe0 e1e2 ................
00000e0: e3e4 e5e6 e7e8 e9ea ebec edee eff0 f1f2 ................
00000f0: f3f4 f5f6 f7f8 f9fa fbfc fdfe ff0a ..............
```
[Try it online!](https://tio.run/nexus/bash#ddNZdxU0EAfw936KPwpu2NvsCwJaXHBBQBEFZXG2FCpdvBasin71mvY@CJ5z522Sk9/JTCYndnx4sDzCje2b16/Y/uO7dzaOjxWbS1wF7dPOkvYWskt7G7v0grC5S0tsHRwebZ2ubcqB2hY/f/pMz/LF6e6rh/ASEzs5cau4hBhiRixBkFs0RB8dgmZGSlkRRvIoPhAQcnn/3lXvNn/65OHWNr23cQb4U4JKRMkhYqYBLroEl12Bq67Bdcdw4gy4JPbm4pVYEWESbngH732Ajz7BZ1/gq2/w3RM8e4FXP4nF/2JFxEn4EebNfQgIKWSEEipCCx2Bw6wrxoRYY5sEzr1x/sJbb7/z7sVFTLWtiHRaSI@MKFERR3JIIUWknApSTQ2pJ0LiJED/4PKVDz@69vGnn13//Isvv7qxIvIkkiZDGtkh@xyQY07IORfkmjsy5dlnywP4@uat2998e@e7u9//cP/HB48er4gyieJKQEmloNTSUHohFC6CosVQRnWovgbgZ9ax8@Tp7i/P9vYPDn9drog6iRprQs21oNbaUHslVK6CqtVQR3Novk3it6PnL34//uPPv17@/c9/7WyTaLEltNwKWm0NrTdC4yZo2gxtdIfue1j3In0SPfaEnntBr72h907o3AVdu6EPciBPawmaBEVKoEwFVKmBOhGISUBKBhrswJ7XEjwJjpzAmQu4cgN3JjCzgJUNPMRBvKwlZBISJUGyFEiVBulCEBaBqBhkqIN6XUvoJDRqgmYt0KoN2pWgrAJVNegwB/O2lrBJWLQEy1Zg1RqsG8HYBKZmsDEcxvwE64gxiTHnGiOPgjGHAGO@AcZsAca8AaYw//lZvA78Cw "Bash – TIO Nexus")
### How it works
```
256, Push the range [0 ... 255].
X> Remove the first item (0).
10- Remove 10 (0x0a).
[D]/ Split at occurrences of 13 (0x0d).
Aa* Join, separating by 10 (0x0a).
:c Cast all integers to character.
e# Begins a comment, terminated by the linefeed at the very end.
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), [Riley](https://codegolf.stackexchange.com/a/111204/56656)
```
()((((((()()()){}){}){})()){}{}){({}[()][((((((()()()()()){}){}){})()))]{})}{}((()()()){}()){({}[()][((((((()()()){}){}()){({}[()])}{})()()))]{})}{}((((()()()()){}){}()){}){({}[()][((((((((()()()()()){}){}){}())){}{})()()))]{})}{}
```
[Try it online!](https://tio.run/nexus/brain-flak#@6@hqQEBmiCoWV0LRWA2iKlRXRutoRkbjawMQ6lmLJAGKkcyB0Rg0wvRhCQL0geRQTJFA9UaKI1mHjbXgIypxjDx////uo4A "Brain-Flak – TIO Nexus")
# Explanation
This was a bit easier than I had expected.
I wrote 3 separate loops to print each type of brace:
```
(((((()()()){}){}){})()){}{}){({}[()][((((((()()()()()){}){}){})()))]{})}{}
((()()()){}()){({}[()][((((((()()()){}){}()){({}[()])}{})()()))]{})}{}
((((()()()()){}){}()){}){({}[()][((((((((()()()()()){}){}){}())){}{})()()))]{})}{}
```
I used standard Mini-Flak technique to avoid using `<...>` monad and to be honest I never really felt the need to use the `<>` nilad.
This must have been extremely similar to what Riley did in the first place because when I was done I had an extra `()` left over. This is not a problem because `()` is essentially a no-op at the top level so I stuck it at the front of my program.
[Answer]
## [Haskell, 107 bytes, Laikoni](https://codegolf.stackexchange.com/a/111229/34531)
```
main=print$id=<<['|':[d]>>[d|i<-"$$'''',--..:<<<<====>>[[[[]]]]addddddiiiiiimnnprt|||",i==d]|d<-id['$'..]]
```
Plus a trailing newline.
[Try it online!](https://tio.run/nexus/haskell#HcmxCQAhDADAXURIow7wJC4iKYQ0KRQRy@zuB6@9O7pOWlvniSqE2MDga8K1NjHFHGIEl3Iu5UNHztOx6/LoM@Zc@5hZSEokbIJZpUGEUpjv/QE "Haskell – TIO Nexus") (needs a few seconds to run, because it loops through all unicode characters).
The program has an `id` (right before `['$'..]`) which is not needed for the program logic, but somehow I have to spend the `i` and `d`.
[Answer]
# [Python, 96 bytes, Agargara](https://codegolf.stackexchange.com/questions/111190/anagram-quines-cops-thread/111607#111607)
```
f= 'B7ofx)wdr0o{1{6{{r){1x0sD00qF1{{24}wr2wlo)y))xm2'; print''.join([r+chr(ord(r)-9)for r in f])
```
[Try it online!](https://tio.run/nexus/python2#BcFBCsIwEAXQq8wuGaSSBGkp4kbES4grQzDFZvQrJDJ49vheTwcyx0lS4xrhRL2OqmD1zb1Pzr3OXjXsfhWhPoS/zG0NZk9P5PIxZrtILvaCze0OK4gWPMycBATKhdKVe/8D)
Once I noticed that some characters repeated in pairs, it was just a matter of finding a suitable ascii map between characters.
[Answer]
# [Pyth, 32 bytes, Rod](https://codegolf.stackexchange.com/questions/111190/anagram-quines-cops-thread/111216#111216)
```
J+"J+J=JJ 1-2#pTN%"N #%2J=T-1pJJ
```
[Try it online!](https://tio.run/nexus/pyth#@@@lreSl7WXr5aVgqGukXBDip6rkp6CsauRlG6JrWODl9f8/AA)
I don't really know Pyth that well, but I started with printing the required output and went from there.
```
+"J+J=JJ 1-2#pTN%"N # Add a '"' to the string in quotes
J # Assign result of above step to J
# # Start an infinite loop
%2J=T-1 # Loops one iteration, then breaks
# (I have no idea why this works)
pJ # Explicitly print J
J # Implicitly print J
```
[Answer]
# [CJam, 46 bytes, Business Cat](https://codegolf.stackexchange.com/questions/111190/anagram-quines-cops-thread/111219#111219)
```
93]_:c58]99]95]93]e__:c36]95]95]101]101]e_$_:c
```
[Try it online!](https://tio.run/nexus/cjam#@29pHBtvlWxqEWtpGWtpGgvkpsYDBYzNwDzTWEMDQzBOjVcBCv//DwA)
```
93] # Push [93] onto the stack
_ # Copy
:c # Push ascii char 93 ']'
58 99 95 93 # Push these numbers...
] ] ] ] # Push entire stack as array
e__ # Flatten and copy
:c # Map ascii values to all elements
36]95]95]101]101] # Same as above
e_ # Flatten
$ # Sort
_ # Copy, implicitly print
:c # Map ascii values to all elements
# Implicitly print
```
[Answer]
# [Octave, 91 bytes, drolex](https://codegolf.stackexchange.com/questions/111190/anagram-quines-cops-thread/111611#111611)
```
a=['111111111123666667eeegggkkknnszEEGn};:;:'];
disp(['a=[''',a,'''];',10,[a-10,']);']]);dd
```
[Try it online!](https://tio.run/nexus/octave#@59oG61uCAdGxmYgYJ6ampqenp6dnZ2XV1zl6uqeV2ttZW2lHmvNlZJZXKARrQ7Spq6uk6gDJGOt1XUMDXSiE3WBpHqsprV6LJBISfn/HwA)
Very similar to the [python solution](https://codegolf.stackexchange.com/questions/111191/anagram-quines-robbers-thread/112046#112046) in that it abuses ascii values to print the characters it needs.
] |
[Question]
[
[SmileBASIC](http://smilebasic.com/en) deserves more attention. I've only seen 3 users here (including myself!) providing SB answers, and while that doesn't surprise me, it disappoints me. It being a paid lang as well as being a BASIC dialect certainly turns people off, but [for those who own it](https://smilebasicsource.com) it's actually pretty flexible and, surprisingly, golfable. I figured I'd open this tips thread for it and see what comes up.
I expect 12Me21 to visit frequently :)
[Answer]
# Replace `string!=""` with `string>""`
SB allows you to do greater/less comparisons on strings, based on their codepoints. However, the empty string is considered the *smallest string there is.*
So for situations where you do `string!=""` you can use either `string>""` or `""<string`, since every string is greater than `""` and `""` is less than every string. Depending on whether you use `<` or `>` depends on if the statement needs whitespace before or after to be valid syntax, which can also save you bytes.
For example:
```
WHILE S$!=""
```
can be turned into
```
WHILE S$>""
```
and further golfed to
```
WHILE""<S$
```
[Answer]
# Using `?`, `.`, `@`, and unclosed strings
Many dialects of BASIC support `?` for printing, and SB is no exception. Having an extremely short text output function is a big advantage.
In SmileBASIC, `.` is evaluated to `0.0`, so it can be used in place of 0 to save space. For example:
`SPSET 0,21` can be `SPSET.,21`, saving 1 byte. (`SPSET0,21` is invalid because `SPSET0` could be a user defined function)
`EXEC.` is an extremely short way to make a program loop forever (but it resets all your variables, so it's not always usable)
Labels (used for `GOTO`, `GOSUB`, and reading `DATA`) are represented as `@LABEL` in SmileBASIC. When used in an expression, they are actually treated as strings. For example, `BGMPLAY"@305C"` can be written as `BGMPLAY@305C`
Strings are automatically closed at the end of a line (or the end of the program). `?"Hello, World!"` can be written as `?"Hello, World!`. This can also be used to make programs more readable by splitting them into multiple lines without changing the length: `?"Meow"BEEP 69` can be
```
?"Meow
BEEP 69
```
[Answer]
# Use string indexing instead of `MID$`
The `MID$` function is a common function in many BASICs to get a substring from somewhere in the middle of a string. However, if you just need to get the character at some index, using string indexing is far shorter. For example:
```
PRINT MID$("ABC",2,1)
PRINT "ABC"[2]
```
Both of these print C. Strings support array-like indexing on a character basis, so if you only need to check one character at a time, this is the best way to do it.
[Answer]
# When to use `:` (or not)
The `:` character is used as a statement-breaker in SB. Basically, you use it to stack statements on one line like so:
```
PRINT "HELLO!":PRINT "GOODBYE!"
```
Otherwise, your average statement is broken by a newline:
```
PRINT "HELLO!"
PRINT "GOODBYE!"
```
In reality, you often don't need to use the colon at all. So long as statements can be broken into syntactically valid tokens, the parser tends to figure out when one ends and the other starts. The same often goes for whitespace.
```
PRINT"HELLO!"PRINT"GOODBYE!"
```
Of course, this doesn't always work. There are always ambiguous cases and invalid syntaxes where you have to explicitly break statements. Take for example:
```
PRINT "HELLO";END
```
The semicolon means that `PRINT` is expecting another expression to print out, unless the statement breaks there (we use dangling semicolons to suppress the newline.) Here it assumes `END` is supposed to be a value, despite being a keyword, and tries to print it, resulting in an error. Thus, we have to explicitly break this statement, be it the colon or the newline.
In general, if something seems ambiguous, try it to see if it works. If it doesn't, break the statement. In addition, anything that would produce invalid syntax isn't highlighted correctly as 12Me21 mentioned.
[Answer]
# Use the syntax highlighter!
SmileBASIC's code editor has a built in syntax highlighter, that can be used to determine whether code will work or not.
For example, if you try to do `BEEP0`, it will not highlight it, because there needs to be a space between a function and a digit. However `BEEP.` works, because . is not a digit.
Normally code like `X=7BEEP` is valid, since functions can't start with a number, so SB assumes that `7` and `BEEP` are separate. However. `X=7END` is NOT allowed (and not highlighted), because it tries to interpret `7E...` as a number, but since there's no digit after the E, it fails, causing an error. Normally this would be pretty hard to figure out, but with a very reliable syntax highlighter, it's much easier to tell what you can and can't do.
[My SmileBASIC syntax highlighter](https://12Me21.github.io/sbhighlight3) is designed to (hopefully) perfectly match the behavior of SB, so you can use it to check if code is valid.
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://12Me21.github.io/sbhighlight3/sbhighlight.js"></script>
<link rel="stylesheet" type="text/css" href="https://12Me21.github.io/sbhighlight3/style.css">
<link rel="stylesheet" type="text/css" href="https://12Me21.github.io/external/smilebasicfont.css">
<script>
function update(event){
$code.textContent=$input.innerText;
//must be innerText since contentedible and textContent are too dumb to understand linebreaks
//contenteditable adds <br>s which textContent ignores
//whyyyyy
applySyntaxHighlighting($code,true);
}
function setCaretPosition(elem,caretPos){
if(elem){
if(elem.createTextRange) {
var range=elem.createTextRange();
range.move('character',caretPos);
range.select();
}else{
if(elem.selectionStart){
elem.focus();
elem.setSelectionRange(caretPos,caretPos);
}else
elem.focus();
}
}
}
</script>
<style>
#editcontainer{
position: absolute;
}
#editcontainer>pre{
position: absolute;
left: 0;
top: 0;
}
pre.csssucks *{
color:transparent !important;
background-color:transparent !important;
caret-color: white;
}
pre.csssucks {
color:transparent !important;
background-color:transparent !important;
caret-color: white;
border-color:transparent;
padding-right: 50ch;
}
</style>
</head>
<body>
Use SB font:<input type="checkbox" autocomplete="off" onchange="$code.dataset.sbfont=$input.dataset.sbfont=this.checked;update()"></input>
<button onclick="update()">force update</button>
<hr>
<div id="editcontainer">
<pre id="$code">test</pre>
<pre id="$input" class="csssucks" contenteditable="true" spellcheck="false" onkeydown="setTimeout(function(){update(event)},2);">test</pre>
</div>
</body>
</html>
```
[Answer]
# Avoid the MOD operator
The modulus operator is really long, and should be avoided if possible.
If you're getting characters from a string, you can just repeat the string instead:
```
"ABC"[X MOD 3]
("ABC"*9)[X] (assuming X will always be less than 27)
```
Sometimes you can save 1 character with `AND` instead:
```
X MOD 4
3AND X
```
[Answer]
# Omitting `OUT` return values
An `OUT` form function is one with multiple returns; you specify the variables to accept the return values after the `OUT` keyword. An example using `DTREAD`:
```
DTREAD OUT yearVar,monthVar,dayVar
```
But what if you only want one of the values, like the current month? You can "ignore" the rest of the values by simply not writing any variable name to accept them! You do, however, have to leave in the commas (aside from the occasional optional return.)
```
DTREAD OUT ,monthVar,
```
Which can be further golfed to
```
DTREAD OUT,M,
```
[Answer]
# Use `LAST()`
Now that SmileBASIC 4 is out in Japan, we can check out some of the potential golf savings. One that immediately jumps out to me is the new `LAST()` function, which returns the last index of an array or string. You can save one byte.
```
LEN(v)-1 'old way
LAST(v) 'new way
```
] |
[Question]
[
# Definition
The infinite spiral used in this question has `0` on the position `(0,0)`, and continues like this:
```
16-15-14-13-12
| |
17 4--3--2 11
| | | |
18 5 0--1 10
| | |
19 6--7--8--9
|
20--21...
```
It is to be interpreted as a Cartesian plane.
For example, `1` is on the position `(1,0)`, and `2` is on the position `(1,1)`.
# Task
Given a non-negative integer, output its position in the spiral.
# Specs
* Your spiral can start with `1` instead of `0`. If it starts with `1`, please indicate so in your answer.
* Output the two numbers in any sensible format.
# Testcases
The testcases are 0-indexed but you can use 1-indexed as well.
```
input output
0 (0,0)
1 (1,0)
2 (1,1)
3 (0,1)
4 (-1,1)
5 (-1,0)
6 (-1,-1)
7 (0,-1)
8 (1,-1)
9 (2,-1)
100 (-5,5)
```
[Answer]
## Python, 46 bytes
```
f=lambda n:n and 1j**int((4*n-3)**.5-1)+f(n-1)
```
[Dennis's answer](https://codegolf.stackexchange.com/a/87185/20260) suggested the idea of summing a list of complex numbers representing the unit steps. The question is how to find the number of quarter turns taken by step `i`.
```
[0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7]
```
These are generated by `int((4*k-n)**.5-1)`, and then converted to a direction unit vector via the complex exponent `1j**_`.
[Answer]
# Python, 53 bytes
```
lambda n:sum(1j**int((4*i+1)**.5-1)for i in range(n))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ ~~16~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḷ×4‘ƽ’ı*S
```
This uses the quarter-turn approach from [@xnor's](https://codegolf.stackexchange.com/a/87188)/[@orlp's](https://codegolf.stackexchange.com/a/87187) answer.
Indexing is 0-based, output is a complex number. [Try it online!](http://jelly.tryitonline.net/#code=4bi2w5c04oCYw4bCveKAmcSxKlM&input=&args=MTAw) or [verify all test cases](http://jelly.tryitonline.net/#code=4bi2w5c04oCYw4bCveKAmcSxKlMKMTDhuLY7MTAwwrU7IsOH4oKsRw&input=).
### How it works
```
Ḷ×4‘ƽ’ı*S Main link. Argument: n (integer)
Ḷ Unlength; create the range [0, ..., n - 1].
×4 Multiply all integers in the range by 4.
‘ Increment the results.
ƽ Take the integer square root of each resulting integer.
’ Decrement the roots.
ı* Elevate the imaginary unit to the resulting powers.
S Add the results.
```
[Answer]
# Python 2, ~~72~~ 62 bytes
```
n=2;x=[]
exec'x+=n/2*[1j**n];n+=1;'*input()
print-sum(x[:n-2])
```
*Thanks to @xnor for suggesting and implementing the quarter-turn idea, which saved 10 bytes.*
Indexing is 0-based, output is a complex number. Test it on [Ideone](http://ideone.com/EHfyPJ).
[Answer]
# Ruby, ~~57~~ 55 bytes
This is a simple implementation based on [Dennis's Python answer](https://codegolf.stackexchange.com/a/87185/47581). Thanks to Doorknob for his help in debugging this answer. Golfing suggestions welcome.
```
->t{(1...t).flat_map{|n|[1i**n]*(n/2)}[0,t].reduce(:+)}
```
**Ungolfed:**
```
def spiral(t)
x = []
(1...t).each do |n|
x+=[1i**n]*(n/2)
end
return x[0,t].reduce(:t)
end
```
[Answer]
## JavaScript (ES7), 75 bytes
```
n=>[0,0].map(_=>((a+2>>2)-a%2*n)*(a--&2?1:-1),a=(n*4+1)**.5|0,n-=a*a>>2)
```
Who needs complex arithmetic? Note: returns `-0` instead of `0` in some cases.
[Answer]
## Batch, 135 bytes
```
@set/an=%1,x=y=f=l=d=0,e=-1
:l
@set/ac=-e,e=d,d=c,n-=l+=f^^=1,x+=d*l,y+=e*l
@if %n% gtr 0 goto l
@set/ax+=d*n,y+=e*n
@echo %x%,%y%
```
Explanation: Follows the spiral out from the centre. Each pass through the loop rotates the current direction `d,e` by 90° anticlockwise, then the length of the arm `l` is incremented on alternate passes via the flag `f` and the next corner is calculated in `x,y`, until we overshoot the total length `n`, at which point we backtrack and print the resulting co-ordinates.
] |
[Question]
[
Given an input of a positive integer, output the number of steps it takes to
find the input via a binary search starting at 1.
We are simulating a binary search for the integer that was given as input, in
which the simulated searcher can repeatedly guess an integer and be told
whether it is too high, too low, or correct. The strategy for finding the
integer is as follows:
* Let n be the integer given as input that we are trying to find.
* Start with a guess of 1. (For every guess, increment the number of steps
(regardless of whether it was correct or not), and immediately stop and
output the total number of steps if the guess was correct.)
* Double the guess repeatedly until the guess is greater than n (the target
number). (Or if it is correct, but that's already covered by our
correct-guess rule mentioned above.)
* Now, set an upper bound of the first power of 2 that's greater than n (i.e.
the number that was just guessed), and set a lower bound of the power of 2
directly below it.
* Repeatedly guess the average (rounded down) of the upper bound and the lower
bound. If it is too high, set it as the upper bound. If it is too low, set it
as the lower bound. This procedure is guaranteed to eventually result in a
correct guess.
Here's an example, for the input of n=21:
```
1 -> 2 -> 4 -> 8 -> 16 -> 32 -> 24 -> 20 -> 22 -> 21
\__________________________/
repeated doubling \________________________/
repeated averaging
```
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Here are all outputs from n=1 to n=100:
```
1
2
4
3
6
5
6
4
8
7
8
6
8
7
8
5
10
9
10
8
10
9
10
7
10
9
10
8
10
9
10
6
12
11
12
10
12
11
12
9
12
11
12
10
12
11
12
8
12
11
12
10
12
11
12
9
12
11
12
10
12
11
12
7
14
13
14
12
14
13
14
11
14
13
14
12
14
13
14
10
14
13
14
12
14
13
14
11
14
13
14
12
14
13
14
9
14
13
14
12
```
And here are some larger test cases:
```
1234 -> 21
1337 -> 22
3808 -> 19
12345 -> 28
32768 -> 16
32769 -> 32
50000 -> 28
```
[Answer]
# Japt, ~~13~~ 12 bytes
Oh my gosh I was beating both Jelly and Pyth for a time :D
```
¢a1 ªJ +1+¢l
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=MSuibCArKKJhMSCqSg==&input=MzI3Njk=)
Here's the strategy I use: let **x** be the input integer, and let **b** be **x**'s binary representation. The correct output is 1 + the length of **b** + the last index of a **1** in **b**, minus 1 if this index is 0.
[Answer]
# Jelly, ~~18~~ ~~15~~ ~~10~~ 9 bytes
```
B>WU;BḄBL
```
[Try it online!](http://jelly.tryitonline.net/#code=Qj5XVTtC4biEQkw&input=&args=MTIzNA) or verify the [small test cases](http://jelly.tryitonline.net/#code=Qj5XVTtC4biEQkwKyLcyUsOH4oKsauKBtw&input=) and [large test cases](http://jelly.tryitonline.net/#code=Qj5XVTtC4biEQkwKMTIzNCwxMzM3LDM4MDgsMTIzNDUsMzI3NjgsMzI3NjksNTAwMDDDh-KCrGrigbc&input=).
### Background
Let **n** be a positive integer and **m** the smallest power of **2** that is greater or equal than or equal to **n**.
* The *doubling* phase takes one step for each digit in the binary representation of **m**.
* Take the binary representation of **n**, remove the first, most significant digit (always **1**) and all trailing zeroes. The *averaging phase* takes one step for each remaining digit.
To avoid calculating **m**, we observe that, if **n < m**, the number of binary digits of **n** is exactly one less than the number of binary digits of **m**.
If we replace the first binary digit of **n** with a **0**, reverse the result, append the original binary digits and remove all leading zeroes, then following happens:
* If **n** is a power of **2**, *all* digits of the first (modified) half get removed, leaving only the digits of the original binary representation of **n = m**.
* If **n** is *not* a power of **2**, the digit in the first half that corresponds to the most significant digit does *not* get removed, compensating for the fact that **n** has a binary digit less than **m**.
### How it works
```
B>WU;BḄBL Main link. Input: n
B Compute the binary representation of n.
>W Compare it with [n].
n is positive, so it is not less than the first binary digit and the
comparison yields zero. When comparing lists of different length, the
elements in the longer list that do not have a pair remain untouched.
Therefore, this will just zero out the first binary digit.
U Reverse the modified binary representation.
;B Concatenate it with the unmodified binary representation of n.
ḄB Convert from binary to integer, and back to binary.
This removes leading zeroes.
L Get the length of the resulting array.
```
[Answer]
## ES6, 38 bytes
```
x=>33-(g=Math.clz32)(x-1)+g(x&-x)-g(x)
```
As alluded to by other answers, you can calculate the number of steps from the positions of the first and last bits.
The number of steps in the doubling phase is `n=33-Math.clz32(x-1)`. We want 2ⁿ ≥ x but `n=33-Math.clz32(x)` gives us 2ⁿ > x so we subtract 1 from x to compensate.
The number of steps in the averaging phase is easier, it's simply `n=Math.clz32(x&-x)-Math.clz32(x)`. `x&-x` is a handy expression that evaluates to the lowest bit of `x` (as a power of 2).
[Answer]
# Pyth, ~~15~~ 13 bytes
```
h-y.ElQ/PPyQ2
```
I have found that the number to be calculated is `1 + 2*ceil(log_2(x)) - [number of 2s in x's prime factorization, minus 1 if x is a power of 2 greater than 1].`
Try it [here](https://pyth.herokuapp.com/?code=h-y.ElQ%2FPPyQ2&input=50000&debug=0).
[Answer]
# Julia, ~~37~~ 35 bytes
```
n->endof(strip(bin(n-1)bin(n),'0'))
```
*Thanks to @AlexA. for saving 2 bytes!*
This follows the observations from [my Jelly answer](https://codegolf.stackexchange.com/a/71643), but deals differently with the edge cases.
If **n > 1**, the binary representation of **n - 1** has one digit less than the one of the next power of **2**, which is compensated by not removing the first digit of the binary representation of **n**.
By removing all zeroes *from both sides*, we deal with the edge case **1** as well.
[Answer]
# Haskell, 82 bytes
This is a pretty straightforward implementation in Haskell:
```
f x=[j|j<-[1..],let g i|i<2=1|x>g(i-1)=2*g(i-1)|1<2=div(g(i-1)+g(i-2))2,g j==x]!!0
```
Less golfed:
```
f x = head [ stepNum | stepNum <- [1..], step stepNum == x]
where
prevStep i = step (i-1)
step i | i == 1 = 1
| x > prevStep i = 2 * prevStep i
| otherwise = div (prevStep i + step (i-2)) 2
```
] |
[Question]
[
2015 was the year of the goat! In this challenge, you will figure out which animal represents the year. To avoid making this challenge to complex you won't need to calculate Chinese new year.
Because they are only 12 animals in the Zodiac, your code will need to be as short as possible.
## Examples
**Your program must get the system year**, the first line is just for reference
```
2015
Goat
1924
Rat
1923
Pig
2008
Rat
```
## Specification
The order of the Zodiac is:
```
Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig
```
`Rat` starts at 2008, `Pig` is 2007, `Ox` at 2009, etc. at the end this loops back around.
Output must be correctly capitalized.
[Answer]
# Pyth - 65 bytes
```
@c." y=CÅQ¯@îR
°©ÀáëªfÞ#[õNqÀN8Ô'¼ô,n7˶~fB").d3
```
[Try it online here](http://pyth.herokuapp.com/?code=%40c.%22+y%0B%3DC%17%C3%85Q%C2%95%0F%C2%87%C2%AF%40%1D%C3%AER%0A%C2%B0%C2%A9%C3%80%C3%A1%C3%AB%C2%AAf%1A%C3%9E%C2%AD%23%5B%C3%B5%C2%96%C2%8BN%13%C2%9C%C2%98q%C3%80%C2%99N8%C2%84%C3%94%27%C2%BC%C3%B4%2C%C2%9E%04n7%C3%8B%C2%B6%7EfB%22%29.d3&debug=0).
```
@ Modular indexing
c ) Split string, use default of spaces
."ajs&^asd" Packed string to compress space separated zodicas
.d3 Current year
```
[Answer]
# Pyth, 54 bytes
```
@rR3c."ayÖÚ©*ÐPk<`eüµÜxþ!¬Ì ¾½hÑðÙBwp"\c.d3
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%40rR3c.%22ay%02%C3%96%06%C3%9A%C2%A9*%C2%9B%1B%C3%90Pk%3C%1B%60e%C3%BC%C2%B5%0B%C3%9Cx%C2%80%C3%BE!%C2%AC%16%C3%8C%C2%8C%20%C2%BE%C2%BDh%C3%91%C2%89%C3%B0%C3%99B%C2%9Bwp%22%5Cc.d3&debug=0)
You can replace the last 3 chars `.d3` with any year number to test the other Zodiac animals.
### Explanation:
```
."ayö..." packed string, decrypts to "monkeycroostercdogcpig..."
c \c split this string at "c"s
rR3 make the first letter of each animal uppercase
.d3 current year
@ take the correct animal of the list and print
```
[Answer]
# JavaScript ES6, ~~106~~ ~~105~~ ~~104~~ 103 bytes
Saved 1 byte thanks to Maltysen, 1 byte to insertusernamehere, *and* 1 byte to edc65!
```
x=>"RatOxTigerRabbitDragonSnakeHorseGoatMonkeyRoosterDogPig".match(/.[a-z]+/g)[new Date().getYear()%12]
```
Pretty self explanatory.
[Answer]
# CJam, ~~82~~ ~~80~~ 75 bytes
~~This is was a direct port of [my Milky Way answer](https://codegolf.stackexchange.com/a/68324/39462).~~
```
"Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat"S/et0==
```
*Saved 7 bytes thanks to [NinjaBearMonkey](https://codegolf.stackexchange.com/users/29750/ninjabearmonkey).*
[Answer]
## [Japt](http://ethproductions.github.io/japt/), ~~72~~ 65 bytes
```
`Mkey RooÐP Dog Pig R Ox Tig Rabb Dg Snake HÆ Go`¸gÐ i %C
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=YE2Na2V5IFJvb9BQIERvZyBQaWcgUoUgT3ggVGlngCBSYWJiiiBEn2eNIFNuYWtlIEjGoCBHb4VguGfQIGkgJUM=&input=)
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 85 bytes
```
'Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey'YbZ'10H$XOU12X\)
```
Uses [release 6.0.0](https://github.com/lmendo/MATL/releases/tag/6.0.0) of the language/compiler. Works in Octave.
### Example
```
>> matl
> 'Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey'YbZ'10H$XOU12X\)
>
Monkey
```
### Explanation
Note that the initial string is cyclically displaced by 3 to avoid a subtraction.
```
'Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey'
Yb % split at spaces
Z' % number representing current date and time
10H$XO % get year as a string
U % convert to number
12X\ % modulo 12, with 0 converted to 12
) % index (and implicitly print)
```
[Answer]
# [Milky Way 1.6.1](https://github.com/zachgates7/Milky-Way), ~~101~~ 96 bytes
```
M" "\=A12n"Goat Horse Snake Dragon Rabbit Tiger Ox Rat Pig Dog Rooster Monkey"" "\;>=<&{~1-;^};!
```
*Saved 5 bytes thanks to a reminder by [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo).*
---
### Explanation
The code modulos the system year by 12 and outputs the proper animal.
---
### Usage
```
./mw <path-to-code>
```
[Answer]
# CJam, 69 bytes
```
"SKiN<lEz=2)aFBY8H[$h-0|4=K`T2Cp%-a)o6"132b26b'`f+'`/et0==(eu\
```
Contains a bunch of unprintables. [Try it here.](http://cjam.aditsu.net/#code=%22SKi%0E%08N%3C%0C%1ClEz%3D2)aFBY8H%5B%24h-0%7C4%05%3DK%60T2%7FCp%25%02-a)o6%22132b26b'%60f%2B'%60%2Fqi%3D(eu%5C&input=2016)
[Answer]
# Python 3, ~~126~~ ~~116~~ 112 bytes
**Edit:** I'm keeping the other answer because it's cool, but this is shorter.
```
from time import*
"Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Goat".split()[localtime().tm_year%12]
```
If trailing whitespace is ok, then it's 126 bytes. If not, it's 134 bytes after adding `.strip()` to the end of the code.
```
from datetime import*
"MRDPROTRDSHGoooiaxiarnoonoggt gbaaraks ebgkstet rioee ye tn r"[datetime.now().year%12::12]
```
[Answer]
# R, 119 bytes
```
scan(t="Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat",w="")[(format(Sys.Date(),"%Y"):1)[1]%%12+1]
```
`format(Sys.Date(),"%Y")` returns the year as a character string, `(format(Sys.Date(),"%Y"):1)[1]` is the shortest way i could think of to coerce it into an integer so that we can apply `%%` to it (the sequence generator `:` indeed coerces automatically to integer). `+1` because R indices are 1-based and not 0-based.
[Answer]
# PHP >= 5.6, 84 bytes
Very straight forward:
```
<?=[Monkey,Rooster,Dog,Pig,Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat][date(Y)%12];
```
[Answer]
# Python ~~129~~ 126 bytes
**EDIT**: I just learnt s.split(' ')=s.split()
Although this isn't the shortest method, here is an alternative answer to @Sherlock9's one:
```
from datetime import*
print 'Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat'.split()[date.today().year%12]
```
[Try it here](http://ideone.com/XgSbHI)
[Answer]
## PowerShell, 92 bytes
```
(-split"Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat")[(date).Year%12]
```
Similar in spirit to other answers, added here only for sake of cataloging. This takes the string `"Monkey ... Goat"` and `-split`s it on spaces to create an array, which is cheaper than specifying the elements individually with `("Monkey","Rooster",...)`. We index into that array with the current `year` mod `12`, which outputs the result. Nothing too fancy.
[Answer]
## C# 159
```
using System;class P{static void Main(){Console.Write("Monkey;Rooster;Dog;Pig;Rat;Ox;Tiger;Rabbit;Dragon;Snake;Horse;Goat".Split(';')[DateTime.Now.Year%12]);}}
```
Readable / ungolfed version
```
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Monkey;Rooster;Dog;Pig;Rat;Ox;Tiger;Rabbit;Dragon;Snake;Horse;Goat".Split(';')[DateTime.Now.Year % 12]);
}
}
```
[Answer]
# [J](http://www.jsoftware.com/help/learning/contents.htm), 78 bytes
```
(>;:'Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat'){~12|
```
Usage:
```
(>;:'Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat'){~12| 2015
Goat
```
Explanation:
```
;: separates the string into boxed array according to the spaces
> opens the boxed array so that it becomes a normal array
x {~ y is choose the y-th element from x.
the ~ reverses the argument, so x { y is choose the x-th element from y.
12| is the residue when the year is divided by 12
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 49 bytes
```
`⌊ẇ ₃¼ Roos≠∴ •∞ Ḣ⟩ ₀⌊ Ox ṗȦ ₈Ė ėɾ Ċṅ ½√`⌈kD⌊12%i
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%E2%8C%8A%E1%BA%87%20%E2%82%83%C2%BC%20Roos%E2%89%A0%E2%88%B4%20%E2%80%A2%E2%88%9E%20%E1%B8%A2%E2%9F%A9%20%E2%82%80%E2%8C%8A%20Ox%20%E1%B9%97%C8%A6%20%E2%82%88%C4%96%20%C4%97%C9%BE%20%C4%8A%E1%B9%85%20%C2%BD%E2%88%9A%60%E2%8C%88kD%E2%8C%8A12%25i&inputs=&header=&footer=)
```
`...` # Compressed string of names
⌈ # Split on spaces
kD⌊ # Current year
12% # Modulo 12
i # Index into list of names
```
] |
[Question]
[
A magic sequence is a sequence of non-negative integers `x[0..n-1]` such that there are exactly `x[i]` instances of `i`
For instance, 6,2,1,0,0,0,1,0,0,0 is a magic sequence since there are 6 0's, 2 1’s, and so on.
Write a function which when given n, outputs all magic sequences of length n
---
The program that can produce the correct output for the highest value of n within 10 seconds win. (All programs are welcome, though)
For example, Alice's program can deal with upto n=15 within 10 seconds while Bob's can deal with upto n=20 within the same time. Bob wins.
Platform: Linux 2.7GHz @ 4 CPUs
[Answer]
# Python, n≈108
```
def magic_sequences(n):
if n==4:
return (1, 2, 1, 0),(2, 0, 2, 0)
elif n==5:
return (2, 1, 2, 0, 0),
elif n>=7:
return (n-4,2,1)+(0,)*(n-7)+(1,0,0,0),
else:
return ()
```
This uses the fact, which I'll prove, that the only Magic sequences of length `n` are:
* `[1, 2, 1, 0]` and `[2, 0, 2, 0]` for `n=4`
* `[2, 1, 2, 0, 0]` for `n=5`
* `[n-4, 2, 1, 0, 0, ..., 0, 0, 1, 0, 0, 0]` for `n>=7`
So, for `n>=7`, one only needs to return a huge tuple. I can do this for up to roughly `n=10^8` on my laptop, which is likely limited by memory; any more and it freezes up. (Thanks to trichoplax for the idea of using tuples rather than lists.) Or, if one can instead print a dictionary of nonzero entries, `{0:n-4, 1:2, 2:1, (n-4):1}`, one can do this for ginormous `n`.
I prove the uniqueness for `n>=7`; the other ones can be checked by brute force or casework.
The sum of the entries of `l` is the total count of all numbers of the list, which is its length `n`. The list has `l[0]` zeroes, and so `n-l[0]` nonzero entries. But by definition `l[0]` must be nonzero or we get a contradiction, and each of the other nonzero entries is at least 1. This already accounts for a sum of `l[0] + (n-l[0]-1)*1 = n-1` out of the overall sum of `n`. So not counting `l[0]`, there can be at most one 2 and no entry bigger than 2.
But that means the only nonzero entries are `l[0], l[1], l[2], and l[l[0]]`, whose values are at most `l[0]` and a permutation of `1,1,2`, which gives a maximum sum of `l[0]+4`. Since this sum is `n`, which is at least 7, we have `l[0]>=3`, and so `l[l[0]]=1`. Now, there's at least one `1`, which means `l[1]>=1`, but if `l[1]==1` that's another `1`, so `l[1]>=2`, which implies `l[1]` is the lone `2`. This gives `l[2]=1`, and all the remaining entries are `0`, so `l[0]=n-4`, which completes the solution.
[Answer]
# Python 3, n≈40
```
def plausible_suffix(l,N):
if sum(l)>N:
return False
pairs = [(N-1-i,l[i]) for i in range(len(l))]
if sum(i*x for i,x in pairs)>N:
return False
num_remaining = N - len(l)
for index, desired_count in pairs:
count = l.count(index)
more_needed = desired_count - count
if more_needed<0:
return False
num_remaining -= more_needed
if num_remaining<0:
return False
return True
plausible_func = plausible_suffix
def generate_magic(N):
l=[0]
while l:
extend = False
if plausible_func(l,N):
if len(l)==N:
yield l[::-1]
else:
extend = True
if extend:
l.append(0)
else:
while l[-1]>=N-2:
l.pop(-1)
if not l:raise StopIteration
l[-1]+=1
n=40 #test parameter
if n>0:
for x in generate_magic(n):
print(n,x)
```
Does a breadth-first search of possible lists, filling in entries from right to left, stopping the search at a suffix if it isn't plausible, which can happen if:
* The sum of the entries in the suffix exceeds `n` (the sum for the whole list must be `n`)
* The weighted sum of `i*l[i]` in the suffix exceeds `n` (the sum for the whole list must be `n`)
* Any number appears in the suffix more times that the suffix says it should
* The number of remaining unfilled spots is too small to account for all numbers that need to appear more times.
I had original tested prefixes left to right, but that went more slowly.
The outputs up to `n=30` are:
```
4 [1, 2, 1, 0]
4 [2, 0, 2, 0]
5 [2, 1, 2, 0, 0]
7 [3, 2, 1, 1, 0, 0, 0]
8 [4, 2, 1, 0, 1, 0, 0, 0]
9 [5, 2, 1, 0, 0, 1, 0, 0, 0]
10 [6, 2, 1, 0, 0, 0, 1, 0, 0, 0]
11 [7, 2, 1, 0, 0, 0, 0, 1, 0, 0, 0]
12 [8, 2, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0]
13 [9, 2, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
14 [10, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
15 [11, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
16 [12, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
17 [13, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
18 [14, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
19 [15, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
20 [16, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
21 [17, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
22 [18, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
23 [19, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
24 [20, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
25 [21, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
26 [22, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
27 [23, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
28 [24, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
29 [25, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
30 [26, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
```
Except for the first three lists `[1, 2, 1, 0], [2, 0, 2, 0], [2, 1, 2, 0, 0]`, there is exactly one list of each length `n>6`, and it has the form `[n-4, 2, 1, ..., 0, 0, 1, 0, 0, 0]`. This pattern persists up to at least `n=50`. I suspect it holds forever, in which case it's trivial to output a huge number of these. Even if not, a mathematical understanding on the possible solutions would greatly speed up a search.
[Answer]
# Pyth - 15 bytes
Uses brute force by all possible sequences of len `n` and then filters.
```
f.A.eq/TkYT^UQQ
```
Full explanation coming soon.
[Try it here online](https://pyth.herokuapp.com/?code=f.A.eq%2FTkYT%5EUQQ&input=4).
[Answer]
# K, 26 bytes
```
{f@&{x~(+/x=)'!#x}'f:!x#x}
```
Like Maltysen's approach, brute force. The heart of the program is a predicate which tests whether a given vector is "magic":
```
{x~(+/x=)'!#x}
```
Build an iota vector as long as the input vector (`!#x`), count the occurrences of each digit (`(+/x=)'`) and compare the result with the input vector (`x~`). If there's a match, you have a magic sequence.
Unfortunately, this first stab seems to be pretty slow. Testing using Kona on my laptop it takes about 12 seconds to handle n=7. I need to give this a bit more thought.
] |
[Question]
[
Write a program that defines a function that can check if a string variable called "anything you want or inputted by the user" is or not a piem.
(piem = a story or poem in which the word lengths represent the digits of π ([from Wikipedia](http://en.wikipedia.org/wiki/Piphilology#Examples_in_English)))
Some examples:
```
myfunction("I am clearly wrong") # False
myfunction("How I want a drink, alcoholic of course, after the heavy lectures involving quantum mechanics") #True (Taken from Wikipedia)
myfunction("Law ' s fine") # True
```
You should delete any kind of punctuation or newline before processing.
Pure code golf, the shortest wins
# End date: evening of 1/10/2014
# Various answers
* How many digits do we need to handle? **More than 10**
* As a matter of interest, how should 0's in PI be interpreted? Skipped or 10 letter words? **As 10 letters words**
* "a variable called piem" – so the name of the parameter must be piem? **No, it hasn't, question text corrected**
* A fun bonus might be a solution that is itself a piem **If your solution is a piem you get \*0.5 bonus**
* For the sake of argument, is **\_** always punctuation? **You can decide if it is punctuation or if it isn't**
* It's unclear what is meant by "any kind of punctuation" **I mean ,.'"?!;;()**
* So digits should be counted? And Law's fine would be false? **Digits should be treated as letters, Law's fine = False; Law ' s fine = True**
# Comments
* The APL solution should be counted in Bytes
* **If your solution works for 100+ digits of pi you get \*0.8 bonus**
* Because of the great interest the end date is one day more in the future.
[Answer]
# JavaScript (169)(140)(137)(135) (63)for 17 digits of pi
In my version `Law's fine` and `Law ' s fine` return both true.
Newest Version (63) by Ingo Bürk and hsl
```
f=s=>!s.split(/\W+/).some((x,i)=>x.length-(Math.PI*1e16+'')[i])
```
New Version (135) for 17 digits of pi (Thanks to Ingo Bürk):
```
f=(s)=>{
s=s.split(/[!"#$%&'()*+, \-.\/:;<=>?@[\\\]^_`{|}~]+/);
p=Math.PI*1e16+'';
r=0;
for(a=s.length;a--;)r+=s[a].length!=p[a];
return !r
}
```
Old version (169) for 32 digits of pi:
```
f=(s)=>{
s=s.split(/[!"#$%&'()*+, \-.\/:;<=>?@[\\\]^_`{|}~]+/);
p="31415926535897932384626433832795".split('');
r=1;
for(a=s.length;a--;)if(s[a].length!=p[a]){r=0};
return r;
}
```
[Answer]
# Ruby, 113 101 79 (98 \* 0.8)
```
require"bigdecimal/math"
x=->p{!(BigMath.PI(999).to_s[2..-1]!~/^#{p.scan(/\w+/).map(&:size)*''}/)}
```
## Explanation
* Input is taken as the argument to a lambda. It expects a `String`.
* Pi is calculated up to `999` decimals and turned into a String with the `.` removed.
* Punctuation marks are removed from the poem and it is split into individual words. `"Let's"` is counted as two words: `"Let"` and `"s"`.
* Use `Array#map` to convert each word to the size of the word, concatenate them into a `String`.
* Using a Regexp, check if the two created `String`s begin with the same characters.
I have applied the bonus for handling 100+ digits. `_` is not handled as punctuation in this solution.
[Answer]
## Mathematica, 123 bytes \* 0.8 = 98.4
```
f=#&@@RealDigits[Pi,10,Length[d=StringLength/@StringSplit@StringReplace[#,RegularExpression@"[!-.:-?]
"->""]/. 10->0]]==d&;
```
Almost the longest submission so far, but:
* It works for any number of digits of Pi.
* It removes all the required ASCII characters and the line break, without splitting the words in those places.
* It handles 0-digits in Pi correctly (as 10-letter words)
[Answer]
# APL (39)
```
{N≡(≢N←≢¨('\w+'⎕S'\0')⍵)↑⍎¨'_. '~⍨99⍕○1}
```
It uses all the digits the APL interpreter's pi constant provides, to a limit of 99. In my case (Dyalog APL 14 32-bit) that was 16 digits. The 64-bit version likely has more digits. 16 digits is enough for the given examples to work, though.
Strings that have more than that amount of words will *fail*, even if all the digits it could check were true. (The same is true of other posts, as of this writing.) For example, if there were only 10 digits, the 'How I want a drink' one would fail. This can be fixed, but at the cost of 14 characters:
```
{(≢¨('\w+'⎕S'\0')⍵){∧/(⌊/≢¨⍺⍵)↑∨⌿⍺∘.=⍵}⍎¨'_. '~⍨99⍕○1}
```
That version will *accept* any string where the first *N* digits are correct.
[Answer]
# Python - ~~130 127~~ *116* - 17 digits of pi
As in [@flawr 's answer](https://codegolf.stackexchange.com/a/38267/31300), `Law ' s fine` and `Law's fine` both return True.
Thanks to [@Emil](https://codegolf.stackexchange.com/users/29703/emil) for removing 12 characters from the program.
```
import re
f=lambda x:all(j==int("31415926535897932"[i])for i,j in enumerate([len(s)for s in re.findall("[\w]+",x)]))
```
[Answer]
## Java, 185
```
boolean f(String...s){s=s[0].replaceAll("\\W","~").replaceAll("~+","~").split("~");for(int i=0;i<s.length;){if(s[i].length()!=(int)(Math.PI*Math.pow(10,i++)%10))return 0>1;}return 1>0;}
```
[Answer]
# python 3, 17 digits of pi, 104
```
import re;f=lambda s:all(map(int.__eq__, map(int, '31415926535897932'), map(len,re.findall('[\w]+',s))))
```
[Answer]
# Python 3 - 129
Doesn't account for punctuation:
```
import math
f=lambda p:all(1if len(p.split(' ')[i])!=int(str(math.pi).replace('.','')[i])else 1for i in range(len(p.split(' '))))
```
[Answer]
## T-SQL ~~488~~ 383
And now for a large T-SQL solution :)
```
CREATE FUNCTION F(@s VARCHAR(MAX))RETURNS CHAR(6) AS BEGIN DECLARE @ CHAR='T',@p VARCHAR(50)='31415926535897932384626433832795028841971693993751',@i INT=0WHILE @='T'AND @s<>''BEGIN SET @i=PATINDEX('%[^a-z0-9]%',@s)IF @i=0RETURN'#True'IF @i-1<>LEFT(@p,1)RETURN'#False'SET @p=STUFF(@p,1,1,'')SET @s=STUFF(@s,1,@i,'')SET @s=STUFF(@s,1,PATINDEX('%[a-z0-9]%',@s)-1,'')END RETURN'#True'END
```
~~This creates an inline table valued function that uses a recursive CTE to detect word boundaries.~~
Creates a scalar function that chews it's way through the words and PI to 31 decimals (first 0).
It is called in the following way
```
SELECT dbo.f('SQL I golf, a large procedure is normal. Hefty not terse') --#True
```
[Answer]
## CJam, 40
```
"
,.'\"?!;:"{-}/S%{,PAV#*iA%=V):V}/]0#)!
```
It's unclear what is meant by "any kind of punctuation"; this solution removes the `,.'"?!;;` characters.
[Answer]
# Bash and unix tools, 111
```
f() { grep ^"$(echo "$@"|grep -Po '[\w]+'|xargs -n1 sh -c 'echo ${#0}'|xargs|tr -d ' ')"<<<31415926535897932;
```
[Answer]
**NodeJS 32 digits 230 Bytes**
I can't get it shorter with JS :D
```
var p = "31415926535897932384626433832795", i = 0;
console.log(process.argv[2].split(/[\s,.]+/).every(function(w) {
if (parseInt(p.charAt(i)) !== w.length) {
return false;
}
i++;
return true;
}) ? 'True' : 'False');
```
] |
[Question]
[
[**Latest update: benchmark program and preliminary resuls available, see below]**
So I want to test the speed/complexity tradeoff with a classic application: sorting.
Write an ANSI C function that sorts an array of floating point numbers in *increasing* order.
You can't use *any* libraries, system calls, multithreading or inline ASM.
Entries judged on two components: code length *and* performance. Scoring as follows: entries will be sorted by length (log of #characters without whitespace, so you can keep some formatting) and by performance (log of #seconds over a benchmark), and each interval [best,worst] linearly normalised to [0,1]. The total score of a program will be the average of the two normalised scores. Lowest score wins. One entry per user.
Sorting will have to (eventually) be in place (i.e. the input array will have to contain sorted values at return time), and you must use the following signature, including names:
```
void sort(float* v, int n) {
}
```
Characters to be counted: those in the `sort` function, signature included, plus additional functions called by it (but not including testing code).
The program must handle any numeric value of `float` and arrays of length >=0, up to 2^20.
I'll plug `sort` and its dependencies into a testing program and compile on GCC (no fancy options). I'll feed a bunch of arrays into it, verify correctness of results and total run time. Tests will be run on an Intel Core i7 740QM (Clarksfield) under Ubuntu 13.
Array lengths will span the whole allowed range, with a higher density of short arrays. Values will be random, with a fat-tail distribution (both in the positive and negative ranges). Duplicated elements will be included in some tests.
The test program is available here: <https://gist.github.com/anonymous/82386fa028f6534af263>
It imports the submission as `user.c`. The number of test cases (`TEST_COUNT`) in the actual benchmark will be 3000. Please provide any feedback in the question comments.
Deadline: 3 weeks (7 April 2014, 16:00 GMT). I will post the benchmark in 2 weeks.
It may be advisable to post close to the deadline to avoid giving away your code to competitors.
**Preliminary results, as of benchmark publication:**
Here are some results. The last column shows the score as a percentage, the higher the better, putting Johnny Cage in first place. Algorithms that were orders of magnitude slower than the rest were run on a subset of tests, and time extrapolated. C's own `qsort` is included for comparison (Johnny's is faster!). I'll perform a final comparison at closing time.

[Answer]
## 150 character
Quicksort.
```
/* 146 character.
* sizeup 1.000; speedup 1.000; */
#define REC_SIZE \
sort(l, v+n-l); \
n = l-v;
/* 150 character.
* sizeup 1.027; speedup 1.038; */
#define REC_FAST \
sort(v, l-v); \
n = v+n-l; \
v = l;
void sort(float* v, int n)
{
while ( n > 1 )
{
float* l = v-1, * r = v+n, x = v[n/2], t;
L:
while ( *++l < x );
while ( x < (t = *--r) );
if (l < r)
{
*r = *l; *l = t;
goto L;
}
REC_FAST
}
}
```
Compressed.
```
void sort(float* v, int n) {
while(n>1){float*l=v-1,*r=v+n,x=v[n/2],t;L:while(*++l<x);while(x<(t=*--r));if(l<r){*r=*l;*l=t;goto L;}sort(v,l-v);n=v+n-l;v=l;}
}
```
[Answer]
## 150 chars (without whitespaces)
```
void sort(float *v, int n) {
int l=0;
float t, *w=v, *z=v+(n-1)/2;
if (n>0) {
t=*v; *v=*z; *z=t;
for(;++w<v+n;)
if(*w<*v)
{
t=v[++l]; v[l]=*w; *w=t;
}
t=*v; *v=v[l]; v[l]=t;
sort(v, l++);
sort(v+l, n-l);
}
}
```
[Answer]
# 67 70 69 chars
Not fast at all, but incredibly small. It's a hybrid between a selection sort and bubble sort algorithm I guess. If you are actually trying to read this, then you should know that `++i-v-n` is the same as `++i != v+n` .
```
void sort(float*v,int n){
while(n--){
float*i=v-1,t;
while(++i-v-n)
*i>v[n]?t=*i,*i=v[n],v[n]=t:0;
}
}
```
[Answer]
## 123 chars (+3 newlines)
A standard Shell sort, compressed.
```
d,i,j;float t;
void sort(float*v,int n){
for(d=1<<20;i=d/=2;)for(;i<n;v[j]=t)for(t=v[j=i++];j>=d&&v[j-d]>t;j-=d)v[j]=v[j-d];
}
```
PS: discovered it is still 10x slower than quicksort. You might as well ignore this entry.
[Answer]
## 395 character
Mergesort.
```
void sort(float* v,int n){static float t[16384];float*l,*r,*p,*q,*a=v,*b=v+n/2,
*c=v+n,x;if(n>1){sort(v,n/2);sort(v+n/2,n-n/2);while(a!=b&&b!=c)if(b-a<=c-b&&b-
a<=16384){for(p=t,q=a;q!=b;)*p++=*q++;for(p=t,q=t+(b-a);p!=q&&b!=c;)*a++=(*p<=
*b)?*p++:*b++;while(p!=q)*a++=*p++;}else{for(l=a,r=b,p=t,q=t+16384;l!=b&&r!=c&&
p!=q;)*p++=(*l<=*r)?*l++:*r++;for(q=b,b=r;l!=q;)*--r=*--q;for(q=t;p!=q;)*a++=
*q++;}}}
```
Formatted.
```
static float* copy(const float* a, const float* b, float* out)
{ while ( a != b ) *out++ = *a++; return out;
}
static float* copy_backward(const float* a, const float* b, float* out)
{ while ( a != b ) *--out = *--b; return out;
}
static void ip_merge(float* a, float* b, float* c)
{
/* 64K (the more memory, the better this performs). */
#define BSIZE (1024*64/sizeof(float))
static float t[BSIZE];
while ( a != b && b != c )
{
int n1 = b - a;
int n2 = c - b;
if (n1 <= n2 && n1 <= BSIZE)
{
float* p = t, * q = t + n1;
/* copy [a,b] sequence. */
copy(a, b, t);
/* merge. */
while ( p != q && b != c )
*a++ = (*p <= *b) ? *p++ : *b++;
/* copy remaining. */
a = copy(p, q, a);
}
/* backward merge omitted. */
else
{
/* there are slicker ways to do this; all require more support
* code. */
float* l = a, * r = b, * p = t, * q = t + BSIZE;
/* merge until sequence end or buffer end is reached. */
while ( l != b && r != c && p != q )
*p++ = (*l <= *r) ? *l++ : *r++;
/* compact remaining. */
copy_backward(l, b, r);
/* copy buffer. */
a = copy(t, p, a);
b = r;
}
}
}
void sort(float* v, int n)
{
if (n > 1)
{
int h = n/2;
sort(v, h); sort(v+h, n-h); ip_merge(v, v+h, v+n);
}
}
```
[Answer]
## 331 326 327 312 chars
Does radix sort 8 bits at a time. Uses a fancy bithack to get negative floats to sort correctly (stolen from <http://stereopsis.com/radix.html>). It's not that compact, but it is really fast (~8x faster than the fastest prelim entry). I'm hoping for speed trumping code size...
```
#define I for(i=n-1;i>=0;i--)
#define J for(i=0;i<256;i++)
#define R for(r=0;r<4;r++)
#define F(p,q,k) I p[--c[k][q[i]>>8*k&255]]=q[i]
void sort(float *a, int n) {
int *A = a,i,r,x,c[4][257],B[1<<20];
R J c[r][i]=0;
I {
x=A[i]^=A[i]>>31|1<<31;
R c[r][x>>8*r&255]++;
}
J R c[r][i+1]+=c[r][i];
F(B,A,0);
F(A,B,1);
F(B,A,2);
F(A,B,3)^(~B[i]>>31|1<<31);
}
```
[Answer]
## ~~511~~ 424 character
Inplace radixsort
**Update:** Switches to insertion sort for smaller array sizes (increases benchmark performance by a factor of 4.0).
```
#define H p[(x^(x>>31|1<<31))>>s&255]
#define L(m) for(i=0;i<m;i++)
void R(int*a,int n,int s){if(n<64){float*i,*j,x;for(i=a+1;i<a+n;i++){x=*i;for(
j=i;a<j&&x<j[-1];j--)*j=j[-1];*j=x;}}else{int p[513]={},*q=p+257,z=255,i,j,x,t
;L(n)x=a[i],H++;L(256)p[i+1]+=q[i]=p[i];for(z=255;(i=p[z]-1)>=0;){x=a[i];while
((j=--H)!=i)t=x,x=a[j],a[j]=t;a[i]=x;while(q[z-1]==p[z])z--;}if(s)L(256)R(a+p[
i],q[i]-p[i],s-8);}}void sort(float* v,int n){R(v,n,24);}
```
Formatted.
```
/* XXX, BITS is a power of two. */
#define BITS 8
#define BINS (1U << BITS)
#define TINY 64
#define SWAP(type, a, b) \
do { type t=(a);(a)=(b);(b)=t; } while (0)
static inline unsigned int floatbit_to_sortable_(const unsigned int x)
{ return x ^ ((0 - (x >> 31)) | 0x80000000);
}
static inline unsigned int sortable_to_floatbit_(const unsigned int x)
{ return x ^ (((x >> 31) - 1) | 0x80000000);
}
static void insertsort_(unsigned int* a, unsigned int* last)
{
unsigned int* i;
for ( i = a+1; i < last; i++ )
{
unsigned int* j, x = *i;
for ( j = i; a < j && x < *(j-1); j-- )
*j = *(j-1);
*j = x;
}
}
static void radixsort_lower_(unsigned int* a, const unsigned int size,
const unsigned int shift)
{
/* @note setup cost can be prohibitive for smaller arrays, switch to
* something that performs better in these cases. */
if (size < TINY)
{
insertsort_(a, a+size);
return;
}
unsigned int h0[BINS*2+1] = {}, * h1 = h0+BINS+1;
unsigned int i, next;
/* generate histogram. */
for ( i = 0; i < size; i++ )
h0[(a[i] >> shift) % BINS]++;
/* unsigned distribution.
* @note h0[BINS] == h1[-1] == @p size; sentinal for bin advance. */
for ( i = 0; i < BINS; i++ )
h0[i+1] += (h1[i] = h0[i]);
next = BINS-1;
while ( (i = h0[next]-1) != (unsigned int) -1 )
{
unsigned int x = a[i];
unsigned int j;
while ( (j = --h0[(x >> shift) % BINS]) != i )
SWAP(unsigned int, x, a[j]);
a[i] = x;
/* advance bins.
* @note skip full bins (zero sized bins are full by default). */
while ( h1[(int) next-1] == h0[next] )
next--;
}
/* @note bins are sorted relative to one another at this point but
* are not sorted internally. recurse on each bin using successive
* radii as ordering criteria. */
if (shift != 0)
for ( i = 0; i < BINS; i++ )
radixsort_lower_(a + h0[i], h1[i] - h0[i], shift-BITS);
}
void sort(float* v, int n)
{
unsigned int* a = (unsigned int*) v;
int i;
for ( i = 0; i < n; i++ )
a[i] = floatbit_to_sortable_(a[i]);
radixsort_lower_(a, n, sizeof(int)*8-BITS);
for ( i = 0; i < n; i++ )
a[i] = sortable_to_floatbit_(a[i]);
}
```
[Answer]
# ~~121~~ ~~114~~ 111 characters
Just a quick-and-dirty bubblesort, with recursion. Probably not very efficient.
```
void sort(float*v,int n){int i=1;float t;for(;i<n;i++)v[i-1]>(t=v[i])&&(v[i]=v[i-1],v[i-1]=t);n--?sort(v,n):0;}
```
Or, the long version
```
void sort(float* values, int n) {
int i=1; // Start at 1, because we check v[i] vs v[i-1]
float temp;
for(; i < n; i++) {
// If v[i-1] > v[i] is true (!= 0), then swap.
// Note I am assigning values[i] to temp here. Below I want to use commas
// so the whole thing fits into one statement, but if you assign temp there you will get sequencing issues (i.e unpredictable swap results)
values[i - 1] > (temp = values[i]) && (
// I tried the x=x+y,y=x-y,x=x-y trick, but using a temp
// turns out to be shorter even if we have to declare the t variable.
values[i] = values[i - 1],
values[i - 1] = temp);
}
// If n == 1, we are done. Otherwise, sort the first n - 1 elements recursively.
// The 0 is just because the third statement cannot be empty.
n-- ? sort(values, n) : 0;
}
```
[Answer]
## ~~221~~ ~~193~~ 172 characters
Heapsort - Not the smallest, but in-place and guarantees O(n\*log(n)) behavior.
```
static void sink(float* a, int i, int n, float t)
{
float* b = a+i;
for ( ; (i = i*2+2) <= n; b = a+i )
{
i -= (i == n || a[i] < a[i-1]) ? 1 : 0;
if (t < a[i])
*b = a[i];
else
break;
}
*b = t;
}
void sort(float* a, int n)
{
int i;
/* make. */
for ( i = n/2-1; i >= 0; i-- )
sink(a, i, n, a[i]);
/* sort. */
for ( i = n-1; i > 0; i-- )
{
float t = a[i]; a[i] = a[0];
sink(a, 0, i, t);
}
}
```
Compressed.
```
void sort(float* a,int n){
#define F(p,q,r,x,y) for(i=n/p;q>0;){t=a[i];r;for(j=x;(b=a+j,j=j*2+2)<=y&&(j-=(j==y||a[j]<a[j-1]),t<a[j]);*b=a[j]);*b=t;}
float*b,t;int i,j;F(2,i--,,i,n)F(1,--i,a[i]=*a,0,i)
}
```
[Answer]
## ~~154~~ 166 characters
OK, here is a longer but faster quicksort.
```
void sort(float*v,int n){while(n>1){float*j=v,*k=v+n-1,t=*j;while(j<k){while(j<k&&*k>=t)k--;*j=*k;while(j<k&&*j<t)j++;*k=*j;}*k++=t;sort(k,v+n-k);n=j-v;}}
```
Here is a correction to survive sorted inputs. And formatted since white space doesn't count.
```
void sort(float*v, int n){
while(n>1){
float*j=v, *k=j+n/2, t=*k;
*k = *j;
k = v+n-1;
while(j<k){
while(j<k && *k>=t) k--;
*j=*k;
while(j<k && *j<t) j++;
*k=*j;
}
*k++ = t;
sort(k,v+n-k);
n = j-v;
}
}
```
[Answer]
## 150 character
Shellsort (w/Knuth gap).
```
void sort(float* v, int n) {
float*p,x;int i,h=0;while(2*(i=h*3+1)<=n)h=i;for(;h>0;h/=3)for(i=h;i<n;i++){x=v[i];for(p=v+i-h;p>=v&&x<*p;p-=h)p[h]=*p;p[h]=x;}
}
```
Formatted.
```
static void hsort(float* v, const int h, const int n)
{
int i;
for (i = h; i < n; i++) {
float* p, x = v[i];
for (p = v + i-h; p >= v && x < *p; p -= h)
p[h] = *p;
p[h] = x;
}
}
void sort(float* v, int n)
{
int i, h = 0;
while (2*(i = h*3+1) <= n)
h = i;
for (; h > 0; h /= 3)
hsort(v, h, n);
}
```
[Answer]
# C 270 (golfed)
```
#define N 1048576
void sort(float*v,int n)
{
float f[N],g;
int m[N],i,j,k,x;
g=v[0];k=0;
for(i=0;i<n;i++){for(j=0;j<n;j++){if(m[j]==1)continue;if(v[j]<g){g=v[j];k=j;}}f[i]=g;m[k]=1;for(x=0;x<n;x++){if(m[x]==0){g=v[x];k=x;break;}}}
for(i=0;i<n;i++){v[i]=f[i];}
}
```
Explanation:
A blank array is used to store each successive minimum number. An int array is a mask with 0 indicating the number has not yet been copied. After getting the minimum value a mask=1 skips already used numbers. Then the array is copied back to original.
I changed the code to eliminate use of library functions.
[Answer]
## 144
I shamelessly took Johnny's code, added a tiny optimization and compressed the code in a very dirty way. It should be shorter and faster.
Note that depending on your compiler, sort(q,v+n- ++q) must be replaced by sort(++q,v+n-q).
```
#define w ;while(
void sort(float*v, int n){
w n>1){
float *p=v-1, *q=v+n, x=v[n/2], t
w p<q){
w *++p<x )
w *--q>x );
if( p<q ) t=*p, *p=*q, *q=t;
}
sort(q,v+n- ++q);
n = p-v;
}
}
```
Well, actually, I started form my code and optimized it, but it seems Johnny already made all the right choices. So I ended up with quasi his code. I didn't think of the goto trick, but I could do without.
[Answer]
## 228 character
Radixsort.
```
void sort(float* v, int n) {
#define A(x,y,z) for(x=y;x<z;x++)
#define B h[(a[i]^(a[i]>>31|1<<31))>>j*8&255]
int m[1<<20],*a=v,*b=m,*t,i,j;
A(j,0,4) {
int h[256] = {};
A(i,0,n) B++;
A(i,1,256) h[i] += h[i-1];
for (i = n-1; i >= 0; i--)
b[--B] = a[i];
t = a, a = b, b = t;
}
}
```
] |
[Question]
[
Given two natural numbers (less than 100) as input print the sequence of intermediate results obtained when computing the sum of the two numbers using only the following operations1:
* `n <-> (m+1)` for integers `n`and `m` satisfying that equation
* `(a+b)+c <-> a+(b+c)` for integers `a`,`b` and `c` (associative law)
*You are **not** allowed to use the commutative law (swapping the arguments of `+`)*
## Example
```
5+3 # Input
5+(2+1) # 3 = 2+1
(5+2)+1 # Associative law
(5+(1+1))+1 # 2 = 1+1
((5+1)+1)+1 # Associative law
(6+1)+1 # 5+1 = 6
7+1 # 6+1 = 7
8 # 7+1 = 8
```
## Rules
* Input: two natural numbers (positive integers)
* Output list of all intermediate steps in the calculation of the sum (using the rules defined above), you may omit the final result
* The expressions can be output in any reasonable format (the left and right operands of each `+` should be clearly determinable)
* You can choose the order in which the operations are applied as long as you reach the final result
* Each expression in the output has to be obtained from the previous expression by applying **exactly one** allowed operation to the previous operation
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest code wins
## Test cases
infix notation:
```
2+2 -> 2+(1+1) -> (2+1)+1 -> 3+1 -> 4
3+1 -> 4
1+3 -> 1+(2+1) -> 1+((1+1)+1) -> (1+(1+1))+1 -> ((1+1)+1)+1 -> (2+1)+1 -> 3+1 -> 4
1+3 -> 1+(2+1) -> (1+2)+1 -> (1+(1+1))+1 -> ((1+1)+1)+1 -> (2+1)+1 -> 3+1 -> 4
5+3 -> 5+(2+1) -> (5+2)+1 -> (5+(1+1))+1 -> ((5+1)+1)+1 -> (6+1)+1 -> 7+1 -> 8
```
postfix notation:
```
2 2+ -> 2 1 1++ -> 2 1+ 1+ -> 3 1+ -> 4
3 1+ -> 4
1 3+ -> 1 2 1++ -> 1 1 1+ 1++ -> 1 1 1++ 1+ -> 1 1+ 1+ 1+ -> 2 1+ 1+ -> 3 1+ -> 4
1 3+ -> 1 2 1++ -> 1 2+ 1+ -> 1 1 1++ 1+ -> 1 1+ 1+ 1+ -> 2 1+ 1+ -> 3 1+ -> 4
5 3+ -> 5 2 1++ -> 5 2+ 1+ -> 5 1 1++ 1+ -> 5 1+ 1+ 1+ -> 6 1+ 1+ -> 7 1+ -> 8
```
[Example implementation](https://ato.pxeger.com/run?1=VZBBCsMgEEXJNqdwaaiBSCmUggHPIe6qiRDSkBhaz9JNNs2heprOGEvajc48589857kOwbe3flles7fl-Z1lV2NJQ2VxyQlxlvgwGCoV14UQrvdII0dU8y0lMRMKz5IzriM13S6v_uRQL5AdeCqczN6o0qLZFPnvkxRKIWU4BO4UcI3DRuPnsScyR_OWPliI9kEDIRbcW9eZZAacdG5KVoYRXAFLM_Dj2yZWS0_smJLvej4)
---
1
The operations are based on the [formal definition of additon](https://en.wikipedia.org/wiki/Peano_axioms#Addition) but modified to work without the concept of a successor function.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
FṖ.ịoƲ€2¦ṁ¥,/ƭ$ƬṪ§Ƭ;@Ɗ
```
A monadic Link that accepts a pair of positive integers and yields a list of nested lists representing (much like the [reference implementation](https://ato.pxeger.com/run?1=VZBBCsMgEEXJNqdwaaiBSCmUggHPIe6qiRDSkBhaz9JNNs2heprOGEvajc48589857kOwbe3flles7fl-Z1lV2NJQ2VxyQlxlvgwGCoV14UQrvdII0dU8y0lMRMKz5IzriM13S6v_uRQL5AdeCqczN6o0qLZFPnvkxRKIWU4BO4UcI3DRuPnsScyR_OWPliI9kEDIRbcW9eZZAacdG5KVoYRXAFLM_Dj2yZWS0_smJLvej4)) one way to perform their sum.
**[Try it online!](https://tio.run/##y0rNyan8/9/t4c5peg93d@cf2/SoaY3RoWUPdzYeWqqjf2ytyrE1D3euOrT82Bprh2Nd/w@3H530cOcMoKLI/9GmOgrmsVwgKtpMR8EwFsgGccxiQRwIG4SBElABEM8UzEESiDaBK4GJgoRN4CLIotHGKIrhUiA5YxRhFKloIwxtCHmQAiMMOVT5aEOsBiApgvgUF4YqMsMvb45TygKbqCWagKEBgmMIdvB/Y1MdcwA "Jelly – Try It Online")**
### How?
```
FṖ.ịoƲ€2¦ṁ¥,/ƭ$ƬṪ§Ƭ;@Ɗ - Link: pair of positive integers, A = [n, m]
Ƭ - starting with X=A collect up while distinct under:
$ - last two links as a monad - f(X):
F - flatten X
ƭ - alternate between:
¥ - (1) last two links as a dyad - F(Flat_X, X):
€2¦ - apply to second element, V, of X:
Ʋ - last four links as a monad - f(V):
Ṗ - pop -> [1 .. V-1] or [] if V == 1
. - 0.5
ị - index into -> [V-1, 1] or [] if V == 1
o - logical OR V -> [V-1, 1] or V if V == 1
/ - (2) reduce Flat_X by:
, - pair -> ...[[[[a,b],c],d],...]
Ɗ - last three links as a monad - f(StepsSoFar):
Ṫ - tail -> removes and yields PreviousStep
Ƭ - starting with PreviousStep collect up while distinct under:
§ - sums
;@ - append to the tailed StepsSoFar
```
---
Seems like the sums (`§`) could be performed within the first collect-loop (`Ƭ`), but I've not figured out a good way to do so...
[Answer]
# [Python](https://www.python.org), 98 bytes
```
f=lambda m,n:[f"{m}+{n}"]+([n:=n-1]*n and[f"{m}+({n}+1)",*(f"({x})+1"for x in f(m,n)),f"{m+n}+1"])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3k9JscxJzk1ISFXJ18qyi05Sqc2u1q_NqlWK1NaLzrGzzdA1jtfIUEvNSoHIaQEltQ00lHS2NNCWN6opaTW1DpbT8IoUKhcw8hTQNoDGamjogtdoghUqxmlCbzAuKMvNKNNI0jHSMNDW5YDxDHWMknrGOIRLPFCQH0Q5zMAA)
-1 thanks to @STerliakov
### Original [Python](https://www.python.org), 100 bytes
```
f=lambda m,n:[f"{m}+{n}"]+(n-1and[f"{m}+({n-1}+1)",*(f"({x})+1"for x in f(m,n-1)),f"{m+n-1}+1"]or[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3U9JscxJzk1ISFXJ18qyi05Sqc2u1q_NqlWK1NfJ0DRPzUqBiGtVAbq22oaaSjpZGmpJGdUWtprahUlp-kUKFQmaeQpoG0ABdQ01NHZB6bYhipdj8ouhYTahd5gVFmXklGmkaRjpGmppcMJ6hjjESz1jHEIlnCpKDaIc5GQA)
Outputs a list of strings in infix notation.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 64 bytes
```
NθNηF⊖ηE²⪫⟦×(ιθ+×(κI⁻η⁺ικ×+1)κ×)+1ι⟧ω⮌Eη⪫⟦×(ι⁻⁺θη⊕ι+1×)+1ι⟧ωI⁺θη
```
[Try it online!](https://tio.run/##dY8/D4IwEMV3P8WFqQ11QOPEqAsmGmLcjAPimTZCgfLHj1@PQoBBp/bevb7fayoTkxZJZm2ky7Y5t/kDDat4uFrOkuZXYYAdMDWYo27wSSKH2CjdsFNSso2AY6E0u11VjjXzmCdAcQGVAM@n@0J@k7xPanqndFszKSDO6FT9hvPJ6gd8NI8C9wMXehfwIWO4GugX7NDU6FrIPy0GksNQIUlKpOefqJ7qufTfqInlas8xtLB2B1u77rIv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input the two numbers.
```
F⊖ηE²⪫⟦×(ιθ+×(κI⁻η⁺ικ×+1)κ×)+1ι⟧ω
```
Output the steps that split the second number into units and associate them with the first number.
```
⮌Eη⪫⟦×(ι⁻⁺θη⊕ι+1×)+1ι⟧ω
```
Output the steps that add the units to the first number.
```
I⁺θη
```
Finish with the final sum.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 90 bytes
```
\d+
$*
+`\+1(1+)(.*$)
$&¶$%`+($1+1)$2¶($%`+$1)+1$2
+`\(?(1+)\+1\)?(.*$)
$&¶$%`1$1$2
1+
$.&
```
[Try it online!](https://tio.run/##VYyxDYQwEATzq2NBd6yEdLY@JvwmHBgJAhICRG0uwI357fDDHc3sc77XvbdJv7mlg4JFmBNdnabrAhPMtWDKVDjdEGrRMeFGRxi2bsPuUbLtr3EMw/vrOjdILS0wSKR3FuXD@AM "Retina 0.8.2 – Try It Online") Link is to test suite that outputs all the test cases. Explanation:
```
\d+
$*
```
Convert to unary.
```
+`\+1(1+)(.*$)
$&¶$%`+($1+1)$2¶($%`+$1)+1$2
```
Repeatedly convert `x+<1y>` into `x+(y+1)` and then `(x+y)+1` until `y` is `1`.
```
+`\(?(1+)\+1\)?(.*$)
$&¶$%`1$1$2
```
Repeatedly convert `(x+1)` into `<1x>`.
```
1+
$.&
```
Convert to decimal.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 99 bytes
```
x=>g=(y,a='',b=`
`)=>(--y?a+x+`+${y+1+b+a+x}+(${y}+1)`+b+g(y,'('+a,')+1'+b)+a:a)+x+++`+1${a?b:b+x}`
```
[Try it online!](https://tio.run/##VcvLCoMwEEbhvc8hZIZfC6GXhRB9lUysSouYUksxiM@ezrbLc@B7ylfW/v14feol3oc8ury5dnKUKnHGVMH5wrNrqa5TJ9jgUe4JFgFaB0jrgGWvY1JkyEAqw7AGgSGNsCIos@UuXWiCKp/7uKxxHk5znGikK9OZufifN6aLzvwD "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), ~~140~~ 137 bytes
```
lambda x,y,a='',b='':(a+f"{x}+{y}{b}\n{a}{x}+({y-1}+1){b}\n{f(x,y-1,'('+a,b+')+1')}\n"if~-y else'')+a+f"{x+y-1}+1{b or chr(10)+str(x+y)}"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JY5BCsIwEEWvErqZCZOAQQQRvEk3iTa0UNuSRmgIce8Z3BREdx7I2xjJZj7zPv_zH-8p-HYc1qc91q-rt3L_vff6Ys6aLSIIfQQQJp8DarJVXBLFkKJJ9RB1-r8Yg1SJFC_QYo5JJQCBtDAEnBTw7FSdvcnAmn5uIMPSRiUbDRsdO7UO1YbT7B1mh6eqDPpMrhs8WtyJLeeFrWvRHw)
A port of [l4m2's JavaScript answer](https://codegolf.stackexchange.com/a/266689)
[Answer]
# [Perl 5](https://www.perl.org/) (`-lp`), 135 bytes
```
1while print,s/\+(?!1\b)\d+/"+(".($&-1)."+1)"/e||s/(\d+)\+\((\d+)\+(\d+)\)/($1+$2)+$3/||(s/^[^+\d]*\K(\d+)\+1\b/$1+1/e,s/\((\d+)\)/$1/)
```
[Try it online!](https://tio.run/##NY3BCsIwEETvfoWGILuu7bKt9eoH@AmuPUgDFkIbmoKXfLuxYj3NwLyZCW7yTc7yevbebcPUD/MxshJcdqIP1I7YEJgS7L4QLA0JGnYpRYYlQyWF1fwEGayQrZBszSlB5PbWknb3g15XcNnlhRF23yf496ww5txQvTnT6T2GuR@HmAsfPg "Perl 5 – Try It Online")
[Answer]
# [Scala 3](https://www.scala-lang.org/), 153 bytes
```
def f(m:Int,n:Int):Seq[String]=n match{case 1=>Seq(s"$m+1");case _=>Seq(s"$m+$n")++Seq(s"$m+(${n-1}+1)")++f(m,n-1).map(x=>s"($x)+1")++Seq(s"${m+n-1}+1")}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY5NCsIwEIX3nmIIXWRIFGIRRKng0oUrlyISa-oPZqwmQqF4EHHTjZ7Ci3gbWxWRbmZ438x7M9e7i_VOh8Vjv9ia2MNYbwhM5g0tHQzTFPIGwO3kk2b3eVmaBBJueyPykqqKvYk5TCf-uKHVLCKw2sfrPNbOgIoG5Yw7FlihGPbfcP4HA2IoxE_yIKemOguFFS6vyFJiy-qUZ9HAMR5kWAX9LLkVHwPD8_fBEUBavuJ3xBPelm3Exj9RMqyRUKoa6bx3voFF8ekv)
] |
[Question]
[
It's [Nowruz](https://en.wikipedia.org/wiki/Nowruz) and you want to set up a [Haft-Sin](https://en.wikipedia.org/wiki/Haft-sin) table by words. This means finding seven words that start with letter *s*.
# The Challenge
Write a program which its input is a list of words separated by space, and output at most first 7 words which starts by letter *s*. If the *s* is before letter *h* it doesn't count because it would not pronounce /s/.
### Input
An arbitrary length string containing words separated by space.
Words must not contain anything other than letters (uppercase or lowercase) and numbers and `_`.
These inputs are valid:
```
hello Puzzle code_golf 12
Start say_hello separating_by_space_is_right
I am a valid word list
```
And these inputs are invalid:
```
code-golf, #invalid_word, separating_by_comma_is_wrong
I'm an invalid word list
```
### Output
The first 7 words which starts by letter *S-s* and not followed by letter *H-h*, in every acceptable way (comma separated, space separated, new-line etc) and in any order.
* If two words are duplicate don't count them twice. Every single word
is count once.
* If the input contains less that 7 word starting with *s* output nothing. Don't output the words.
* The output must contain the exact word which is in the input. So if the input contains `SuPER`, output should be `SuPER` and not `SUPER` or `super` or any other form of lower and upper case.
* Words pronunciation matter. The word `Speed` and `SPEED` both count the same. You may want to lowercase all the input and unique the words and then check for words.
### test-cases
input:
```
speed speed new car book seven sad sum power fun super sister silver silly start
```
output:
```
speed seven sad sum super sister silver
```
input:
```
speed SpEEd new book seven sad sum power fun super sister silver silly start
```
output:
```
speed seven sad sum super sister silver
```
input:
```
sheep speed new car book seven sad sum power fun super sister silver silly start
```
output:
```
speed seven sad sum super sister silver
```
input:
```
first second third
```
output:
## Edited
This was my first question and I missed many special cases. I try to clarify them.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 28 bytes
```
⌈'⇩ḣh\h≠$h\s=∧;:ɽ:vḟUİ₅6>7*Ẏ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIgn4oep4bijaFxcaOKJoCRoXFxzPeKIpzs6yb06duG4n1XEsOKChTY+Nyrhuo4iLCIiLCJTUEVFRCBzUGVFZCBzaG9wcGVyIFNQRUVEIG5ldyBjYXIgYm9vayBzZXZlbiBzYWQgc3VtIHBvd2VyIGZ1biBzdXBlciBzaXN0ZXIgc2lsdmVyIHNpbGx5IHN0YXJ0Il0=) or [Try some testcases!](https://vyxal.pythonanywhere.com/#WyJqIiwi4pahxpsiLCLijIgn4oep4bijaFxcaOKJoCRoXFxzPeKIpzs6yb06duG4n1XEsOKChTY+Nyrhuo4iLCIiLCJzcGVlZCBzcGVlZCBuZXcgY2FyIGJvb2sgc2V2ZW4gc2FkIHN1bSBwb3dlciBmdW4gc3VwZXIgc2lzdGVyIHNpbHZlciBzaWxseSBzdGFydFxuc3BlZWQgU3BFRWQgbmV3IGJvb2sgc2V2ZW4gc2FkIHN1bSBwb3dlciBmdW4gc3VwZXIgc2lzdGVyIHNpbHZlciBzaWxseSBzdGFydFxuc2hlZXAgc3BlZWQgbmV3IGNhciBib29rIHNldmVuIHNhZCBzdW0gcG93ZXIgZnVuIHN1cGVyIHNpc3RlciBzaWx2ZXIgc2lsbHkgc3RhcnRcbmZpcnN0IHNlY29uZCB0aGlyZFxuU1BFRUQgc1BlRWQgc2hvcHBlciBTUEVFRCBuZXcgY2FyIGJvb2sgc2V2ZW4gc2FkIHN1bSBwb3dlciBmdW4gc3VwZXIgc2lzdGVyIHNpbHZlciBzaWxseSBzdGFydCJd) Mis-deduplication should be fixed now.
```
⌈'⇩ḣh\h≠$h\s=∧;:ɽ:vḟUİ₅6>7*Ẏ
⌈' ; Filter input, split on spaces, by:
⇩ḣ Push (input lowercased)([0], [1:])
h\h≠ Second character (input[1:][0]) isn't `h`
$h\s=∧ and first character isn `s`
:ɽ Duplicate, lowercase each
:vḟ Find first occurrences of each of ^ in ^
U Uniquify ^
İ Index ^ into filtered list, resulting
in the properly deduplicated list
₅6> 1 if len(^) is 7 or more, otherwise 0
7*Ẏ Multiply by 7 and slice [0:that]
```
[Answer]
# [R](https://www.r-project.org/), ~~57~~ ~~61~~ ~~58~~ 79 bytes
*Edit: -2 bytes thanks to "regex stealing" by pajonk*
*Edit2: +21 bytes to remove case-sensitive duplicates, while returning the originally cased input*
```
q=(o=grep("^s(?!h)",scan(,""),T,T,T))[!duplicated(tolower(o))];if(q[7]>F)q[1:7]
```
[Try it online!](https://tio.run/##JYzBDoIwEER/Zempm3DxRKJBL@KZRG8EkwqLECst3Rbi11fQzOElLzPjYpxyafKnIyvFneUp6VGk3KhRpkJgetuCWCVtsHpolKdWeqPNQk4axPowdHKqsvp4wana7bM6XsuiOAOXVLTAwL2xlhz87UgLNMrBw5gXMM00Aqu1Ft5gt0vowmrCNuCB/Q96/kN/gL1yPn4B "R – Try It Online")
Outputs the first 7 unique words starting with 's' or 'S' but not 'sh' or 'Sh', if there are at least 7.
Otherwise errors without outputting anything.
---
# [R](https://www.r-project.org/), ~~59~~ ~~63~~ ~~61~~ 82 bytes
```
(q=(o=grep("^s(?!h)",scan(,""),T,T,T))[!duplicated(tolower(o))])[1:7][length(q)>6]
```
[Try it online!](https://tio.run/##JYzBCsIwEER/ZZvTBnrxoiBUL/Ze0FupENu1FWOSZpMWvz62ljk8eMyMTwnHAm3Re3Io7oznbJAi51YZzIWQ@W2NlHXWRadfrQrUYbDazuTRStnIenc8NLUm04cBR3naN@laleUFuKKyAwYerHPkYbOGZmiVh4e1b2CayACrpRY/4NZTeMbFxHXALw5/6GmD/gIH5UP6AQ "R – Try It Online")
As above, but exits quietly without erroring if there are less than 7 valid words.
[Answer]
# JavaScript (ES6), ~~62~~ 61 bytes
*Saved 1 byte thanks to @l4m2*
```
s=>(a=[...new Set(s.match(/\bs(?!h)\w*/g))]).slice(a[6]||7,7)
```
[Try it online!](https://tio.run/##XU2xEoIwFNv9iidT62nZZEI/whEYSnlAtVCur8B5x7/XKptLkktyyVMukpTTk7@MtsHQ5oHyG5N5IYQYcYUHekZikF71LC1rYvdjz8v1lHacV1yQ0QqZLK7VtmXnjAdlR7IGhbEda1lCE2IDO37nlHRQW/sCwgVHIBnDeYDJruignaMzT1GRJv8js@xk3kBeOp9wfvi7aLUjH/ei3YDvtWtiKXwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 47 bytes
```
+msi`(^(.+)$.+)^\2$
$1
Gi`^s(?!h)
1!`.+(¶.+){6}
```
[Try it online!](https://tio.run/##K0otycxL/P9fO7c4M0EjTkNPW1MFiONijFS4VAy53DMT4oo17BUzNLkMFRP0tDUObQPKVpvV/v9fXJCamsIFIfNSy7mSE4u4kvLzs7mKU8tS87iKE4GSpblcBfnlqUVcaaVAkdICIKs4s7gETOWUQaicSq7iksSiEgA "Retina 0.8.2 – Try It Online") Explanation:
```
+msi`(^(.+)$.+)^\2$
$1
```
Delete case-insensitive duplicates.
```
Gi`^s(?!h)
```
Keep only words beginning with `s` but not `sh`.
```
1!`.+(¶.+){6}
```
Select the first seven words.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Assuming that we must handle uppercase `S` and `H` too and that we must/may return the leftmost distinct "s-words"
```
ḣ2ŒliⱮ⁼Ø.
ḲQçƇ⁾hsḣJf7ḢƊ$
```
A monadic Link that accepts a list of characters and yields a list of the words.
**[Try it online!](https://tio.run/##LUw9CsIwFN49xRucHVy8g07SE0R95UVjE/Kalo6dCo5Ozjq4CTp1EJdi79FeJKZY@H754NujUoX3XX2bf89K9s9HX76by2zS1a91c2@rvvwQh3kZL7r62p6mvqlW3rNB3MGoQEAMIoCAhSFpEZi0U2EjYYYiAoF57AnmsBUWNlofIMIME2B3BKNztBC7BCJnQmIRDiSnQ5Qq@5sqgFNh0x8 "Jelly – Try It Online")**
### How?
```
ḣ2ŒliⱮ⁼Ø. - Helper Link, valid word?: list of characters, Word; identifiers ("hs")
ḣ2 - head Word to index two - e.g. "Child" -> "Ch"
Œl - lower-case -> X -> X = "ch"
Ɱ - map across C in identifiers with:
i - first (1-indexed) index of C in X -> [2,0]
('h' at index 2, no 's' exists)
Ø. - [0,1]
⁼ - equal?
ḲQçƇ⁾hsḣJf7ḢƊ$ - Link get s-words: list of characters, T
Ḳ - split T at space characters -> Words
Q - deduplicate
⁾hs - set the right argument to "hs"
Ƈ - filter keep those Words for which:
ç - call the helper Link as a dyad - f(Word, "hs")
$ - last two links as a monad - f(ValidWords):
Ɗ - last three links as a monad - g(ValidWords):
J - range of length -> [1,2,...,number of valid words]
7 - seven
f - filter-keep -> [7] or [] if less than seven valid words
Ḣ - head -> 7 or 0
ḣ - head of ValidWords to that index
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 (or 22?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#ʒlć'sQsн'hÊ*}DlDÙkèDg7@7*£
```
Assumes differently cased words (e.g. `speed`/`SPEED`/`sPeEd`) are all the same for the uniquify. Otherwise this could have been 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) by replacing the `DlDÙkè` with `Ù`.
[Try it online](https://tio.run/##yy9OTMpM/f9f@dSknCPt6sWBxRf2qmcc7tKqVXDJcTk8M/vwCpd0cwdzrUOL//8PDnB1dVEoDkh1TVEILnBNBbILUlNTFPJSyxWSE4sUkvLzsxWKU8tS8xSKE1MUiktzFQryy1OLFNJKgSKlBUBWcWZxCZjKKYNQOZUKxSWJRSUA) or [verify some more test cases](https://tio.run/##rYwxDoJAEEV7T/GjBYmxt9QCeownWNhRNiBLdhYMibaaWNJZ23gJG7Gy8gxeBDdS25lM/v@ZP/M0i0hRt6vq2RDvQ4PhrO5GzyZ7HD1e8OvmJe1pvPczvz2n7dVfT@fT8f3STbplGAQ@OKRAYlkE5HJBJJHTFrEwiLROwVRRDhYSXG5Q6C0ZrEq3KQuXWLH9Wlb1ltVgK4wd9Kg/AlfKsHXfsc4lbKKMHDDYTdIfOIByIsDRzwIcfwA).
**Explanation:**
```
# # Split the (implicit) input-string by spaces
ʒ # Filter this list of words by:
l # Convert it to lowercase
ć # Extract head; pop remainder-string and first char separated
'sQ '# Check if this head is an "s"
s # Swap so the remainder-string is at the top
н # Pop and push its first character
'hÊ '# Check that it's NOT equal to a "h"
* # Check that both were truthy
}D # After the filter: duplicate the resulting list of words
l # Convert each to lowercase
D # Duplicate it again
Ù # Uniquify the top copy
k # Get all its indices in the lowercase list
è # Use it to index in the regular case-insensitive list
D # Duplicate the list
g # Pop and push its length
7@ # Check if it's >=7
7* # Multiply that 0/1 by 7 (either 0 or 7)
£ # Leave that many leading words from the list
# (after which the resulting list is output implicitly)
```
[Answer]
# [Perl 5](https://www.perl.org/), 60 bytes
```
my%s;$_=(@r=grep!$s{lc$_}++,/\bs(?!h)\w*/gi)<7?"":"@r[0..6]"
```
[Try it online!](https://tio.run/##rY7LCsJADEX3fkUsFdT62qigFt30C1xakT6iHRw7IZlaRPx1x2I/QTf3hIQcLiHruXO3R0/W/ins7zi8MFLXl6fO/NMrCEbTOJX@tlsM4no4vajBZrn1vJW348NsMlkcPeeEEHNos8QasoQhNeYKgncsQZLmWN2ATI0M56rZVNRMosR@oe8t9APEJmw7rWpPUdQKf5MViPTPdmfFYpvvzJQ52EJx/jZklSnFjRPSHw "Perl 5 – Try It Online")
[Answer]
# Python 3, ~~111~~ ~~102~~ 103 bytes
I am pretty sure this isn't a perfect solution, as my regex skills are far from perfect and this seems an unnecessarily long way to check for "any word character that is not h or H", but it works. Takes a list of the words, and returns a set of the seven words, or nothing if it cannot find seven words.
```
import re
def f(x):
r=set()
for i in x:
if re.match("[Ss](?![Hh])",i):r|={i}
if len(r)>6:return r
```
Edit -9 bytes: realized that it didn't have to check if the words only contained alphanumerics
Edit +1 bytes: @a stone arachnid pointed out my regex failed for input of `s`
[Try it online!](https://tio.run/##VY1RS8NAEITf8yuWe7oTU4SCaKD1h9giZ7JnliZ3x@6mabX@9ngYEHyZGWY/dvJV@xS3T5mXhcacWIGx6jBAsBfXVMA7QbWugpAYCCjCpbRAoXCb0WvbW2NfyMmrrz@o/nyon9@Oh/nO3JNr@Lb7ou8VHzBadvvHhlEnjsBLZopqgzWSETtYNeIMrWd4T@kEgmeMIL4cpxFympEhTKWZcklCor82nFcbriDqWc1G8kBqDRjnXPW3E4hFy9M2xQ60J@7@k8sP)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell) for Windows, 68 bytes
*Thanks @[Julian](https://codegolf.stackexchange.com/a/245651/80745) for the inspiration*
```
($r=$args|sls '\bs(?!h)\S*'-a|% m*|% v*e|sort -u -t 7)*!($r.count-7)
```
[Try it online!](https://tio.run/##1ZNNT8MwDIbPza8wpUA7LVx3QBNI07gysQMHQCjrPFromhInG9O63z68ZHzdQYJL/MZ2Hr@t5EYv0VCBVSVzbXBLaKWqSkVA2lh/SD15wtzCIXD2pqynekkw@ngnRDLrr7dpYvqJMo/UUkVwcjeh9PygyO7GnROp2iOYd/hYdLD1XOlAWuhlnQN@d5prV1vZy7YbIS5SEXXTmBrEKYSzxiXkysBE62cgXGANpLjo5tDsbMDMccY1rKgk60O1CKFaAVllbNwVURSocRdiT/FChbubh8AQLzwnqB1qr6qVFx6YiS9Gx81wGIz@TZMFYvMv/ib8klU/6ef9zkpDvCWY63oKtijNlCsZtHCpzVDlhbwKu7MWUWKR7EARdiHB14az/IV9SB7OuGaQXGX5epzM4KOTK7ej8cCR1fMAuocLRkVjl@dIxP1xkn7S2m/7Kq1ueMVikPji@/ZDQlcWMz26fp8b76u77EZstm8 "PowerShell Core – Try It Online")
The alias `sort` is not defined for Linux PowerShell and TIO. Linux requires `sort-object`.
Less golfed:
```
$result = $args|select-string '\bs(?!h)\S*' -allMatches|% matches|% value|sort -unique -top 7
$result*($result.count-eq7)
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~78~~ 75 bytes
```
($r=-split$args-match'^s[^h]*$'|?{!($_-in$u);$u+=,$_})[0..6]*($r.count-ge7)
```
[Try it online!](https://tio.run/##xZBBT8JAEIXP7a8Ym4202BJPeiCNJASvGjkSIMsypdXSXXd2QYP97XWxQjAx8aRednbnzfvmZZXcoqYcyzIRUmPDsnTXhEynCamyMIzrFSVrbkTemdFklk@7rPN2szsL2TwpKmajPrMXaczmdTS57PWupl1n7glpK5Os8Dpqat8fhL4XD8KAFOIS2rPCLQiuYSHlExBusALiTrRrUPtIkFnXscrdqCDzUcpNW8pXIMO1CWI4ML8AvrEF0WmEsRqN2gh/vT5HVP/8A/ArIeCnGIf9WaHJuDkhqyWYvNDLvd@pEbzBrdQjLvLkbvGIwsDO95hBMkNOGAPDF@W6bksKbN53mkaypXHPc5bBcdIpk/vx0JKR6xY0hYFDeWMrBBLt7UdUgs8QfIIC5/QeDszTbu3XzTs "PowerShell Core – Try It Online")
-3 bytes thanks to *mazzy*!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
WS⊞υι≔Φυ∧›⁼↧§ι⁰s⁼↧§ι¹h⁼κ⌕↧υ↧ιυ…υ∧‹⁶Lυ⁷
```
[Try it online!](https://tio.run/##fY/NbsMgDMfvfgqUE0hMWi/doaeoSqdKPVTqE7DgJagMGIZkfXoGm6bc5oM/f5b/HmcVR69sKetsLDJ@diGnW4rGTVwIds008yyZEQfoiczk@MnYhLE1e6f5a0TVyuEzK0v84leMoyLkfTo7jV/cSPYsJOuoq/4/ateouRMbdpfsZOqNDc91uFVGNJMsV3HXqjjx42O0eJx9@JN3QSK@r0voplQ/afhLXTqUQgFRwy0MgwaHK7x5fwfCBR2Q0kD5A0I7Be@5dnKoGRlKP8Euv8E@gJKKCcrTYr8B "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:
```
WS⊞υι
```
Input the list of words.
```
≔Φυ∧›⁼↧§ι⁰s⁼↧§ι¹h⁼κ⌕↧υ↧ιυ
```
Case-insensitively filter out all words that don't start with an `s` or start with `sh` or are duplicate.
```
…υ∧‹⁶Lυ⁷
```
Output the first seven remaining words if there are more than six of them.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I think this is right; it's been a *long* day so I'm not at all sure!
```
¸fÈÎos «XÅÎohÃòk mί7
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=uGbIzm9zIKtYxc5vaMPyayBtzq83&input=IlNIZWVwIGZpcnN0IHNwZWVkIFNwRUVkIG5ldyBib29rIHNldmVuIHNhZCBzdW0gcG93ZXIgZnVuIHN1cGVyIHNpc3RlciBzaWx2ZXIgc2lsbHkgc3RhcnQiCi1R)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
s=>(a=s.match(/(\bs(?!h)\w*\b)(?<!\b\1 .*)/gi)).slice(a[6]||7,7)
```
[Try it online!](https://tio.run/##XYyxDoIwFEV3v@LJ1BKFuOgiMvEFjtah0AdUC236CsTEf8dGN6dzc3JzHnKW1Hjtwn60Cte2WKm4MFlQNsjQ9CxnoiZWbnsullTUnJXnrajFAbKU553mPCOjG2Tydry/36fdia@NHckazIztWMsScogKrq6qFIy4QG3tEwhnHIGkApoGcHZBD@0UzeTiIk3hCzP/YF5AQfqQcL75y7faU4i9qBWEXnsVT@sH "JavaScript (Node.js) – Try It Online")
Fixed Arnauld's uppercase problem with 3 bytes
[Answer]
# [PHP](https://www.php.net/), ~~134~~ 131 bytes
```
$a=explode(" ",$argn);foreach($a as$v){$l=strtolower($v);if($l[0]=="s"&&$l[1]<>"h"){$b[$l]="$v ";if(count($b)==7){echo join($b);}}}
```
[Try it online!](https://tio.run/##JY7BTsMwEER/ZWWtKkcCCU4cUsOF9ozEscrBSTY4xfVaXicFVfl1ggOXeaOnOUx0cd2/xJJoDX1Fzz1pBeoObfoIVT1wIts5jRas4Fzd0BvJKbPnKyVdTD0OGv3poTFGidrtSn9s9s/KqTJuT@gbo3AGte06nkLW2FbGPFU36hzDmcewmXpZlnUVRxRBIlEP72@HwysEukJnE7TMnyA0UwCxPch0gbhdgGEqZoqlySj5D37@h/8GyTblH4555CDr/fEX "PHP – Try It Online")
Explanation: Used associative array key to prevent dups instead of in\_array function.
----- Previous answer -----
```
$a=explode(" ",$argn);foreach($a as$v){if($v[0]=="s"&&$v[1]<>"h"&&!in_array($v,$b)&&$i<7){$b[]=$v;$i++;}}if($i==7){echo join($b," ");}
```
[Try it online!](https://tio.run/##JY1BS8QwEIX/yhiGpWUr6MlDG724ngWPS5FpOzXRmoRMm3VZ@tetUS/zPt57zAsmbM1DyBdJ81eY/MCFAlUhxTdX1qOPTL0pkIAEU3mxY4HpeNNqrUTtdplv2@ZemcxX1r1SjHTOjQq7Mqe2uSsv2B1bjalGu9/X6/r7wWqdA@6Nh3dvXYFdlUfLet02McwBJDAP8PJ8ODyC4xP0FKHz/gOEEzsQGkCWTwj@xBHGJTtLyCRW5j@Z0r9MZ5CZ4vztw2y9k@366Qc "PHP – Try It Online")
Explanation: Straightforward conversion of input to array, step through array testing each word against the rules, if a word passes the test add it to second array, and only print second array if 7 words pass the test.
] |
[Question]
[
Create a function that accepts a list of dates (unsorted with possible duplicates) and returns the days of the week in one of the following formats:
* A format similar to `MTWTFSS` or `SMTWTFS` (i.e. beginning with Monday or Sunday), with non-days replaced by an underscore `_`, illustrated below.
* `WEEKDAY` if all the dates are between Monday to Friday (i.e. Monday, Tuesday, Wednesday, Thursday and Friday must all be present, no other days)
* `WEEKEND` if all the dates are on Saturday or Sunday (i.e. Saturday and Sunday must both be present, no other days)
* `ALLWEEK` if all the dates are on all days of the week!
Assume the list of dates to be in your language's date data type (e.g. `List<LocalDate>` for Java), else the ISO date string `"YYYY-MM-DD"`. **Addition: After looking at [05AB1E's entry](https://codegolf.stackexchange.com/a/230848/21697), I'm now also inclined to accept 'the most convenient representation', but please explain clearly why this would be used in lieu of the original rules. I just don't want to open the flood gates here...**
If it helps, you can further assume that all dates are within an arbitrary calendar non-leap-year.
Examples:
| Input | Output (starting Monday) | Output (starting Sunday) |
| --- | --- | --- |
| `["2021-06-21"]` | `M______` | `_M_____` |
| `["2021-06-21", "2021-06-28"]` | `M______` | `_M_____` |
| `["2021-06-22", "2021-06-22"]` | `_T_____` | `__T____` |
| `["2021-06-23", "2021-07-16"]` | `__W_F__` | `___W_F_` |
| `["2021-06-27", "2021-07-02", "2021-05-01"]` | `____FSS` | `S____FS` |
| `["2021-06-21", "2021-06-22", "2021-06-23", "2021-06-24", "2021-06-25"]` | `WEEKDAY` | `WEEKDAY` |
| `["2021-06-27", "2021-06-26", "2021-06-27"]` | `WEEKEND` | `WEEKEND` |
| `["2021-06-21", "2021-06-23", "2021-06-22", "2021-06-26", "2021-06-25", "2021-06-24", "2021-06-27"]` | `ALLWEEK` | `ALLWEEK` |
Winning Criteria: Shortest code wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~93~~ 92 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'_7×sε`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·(O7%}D.•1Î㦕©sèsǝÀÐáÐÙ'sQi'œÙ뮦¦Qi’…Â‚Ž’ëQi’€Ÿ…Â’]u
```
Inputs in the format `[dd,mm,yyyy]`; output format starts at Sunday (`SMTWTFS`).
[Try it online](https://tio.run/##yy9OTMpM/f9fPd788PTic1sTQl2MHzXsPLTS0EhL2@5RU5NWyOHth9ZFnNt4aOXFJlUXExDvYhOQXAlmHtqu4W@uWuui96hhkeHhvsMTDm0@tAzIPrSy@PCK4uNzDzccnnB44eEJjxrmFRcHZqofnXx45uHVQH3LDi0LzHzUMPNRw7LDTY8aZh3dC@QcXg0Ra1pzdAdUYmZs6f//0dFGxjpmOkYGRoaxOtGGZjrmEHbsf13dvHzdnMSqSgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXSf/V488PTi89tTQh1MX7UsPPQSkMjLW27R01NWiGHtx9aF3Fu46GVF5tUXUxAvItNQHIlmHlou4a/uWqti96jhkWGh/sOTzi0@dAyIPvQyuLDK4qPzz3ccHjC4YWHJzxqmFdcHJipfnTy4ZmHVwP1LTu0LDDzUcPMRw3LDjc9aph1dC@Qc3g1RKxpzdEdUImZsaX/lfTCdP5HR0cbGeqY6RgZGBnGxuooIHN1oo0sUKWMkKSMUKWMEVKGZjrmyFLmSLpgMkBVOqa4bEW2BslcIxMktimq9ch2mCGxzXH7zRiHjWbYbEGzHWFs7H9d3bx83ZzEqkoA).
**Explanation:**
Since 05AB1E has no Date builtins, we'll have to calculate the *Day of the Week* manually.
The general formula to do this is:
$${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$
Where for the months March through December:
* \$q\$ is the \$day\$ of the month (`[1, 31]`)
* \$m\$ is the 1-indexed \$month\$ (`[3, 12]`)
* \$K\$ is the year of the century (\$year \bmod 100\$)
* \$J\$ is the 0-indexed century (\$\left\lfloor {\frac {year}{100}}\right\rfloor\$)
And for the months January and February:
* \$q\$ is the \$day\$ of the month (`[1, 31]`)
* \$m\$ is the 1-indexed \$month + 12\$ (`[13, 14]`)
* \$K\$ is the year of the century for the previous year (\$(year - 1) \bmod 100\$)
* \$J\$ is the 0-indexed century for the previous year (\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\$)
Resulting in the day of the week \$h\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday.
[Source: Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence)
The implementation of this formula in the code below is:
```
`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·(O7%
```
```
'_7× '# Push string "_______"
s # Swap to get the (implicit) input-list
ε # Map over each date:
# Determine its day of the week:
` # Push the day, month, and year to the stack
U # Pop and save the year in variable `X`
D # Duplicate the month
3‹ # Check if the month is below 3 (Jan. / Feb.),
# resulting in 1 or 0 for truthy/falsey respectively
© # Store this in variable `®` (without popping)
12* # Multiply it by 12 (either 0 or 12)
+ # And add it to the month
# (This first part was to make Jan. / Feb. 13 and 14)
> # Month + 1
₂* # Multiplied by 26
T÷ # Integer-divided by 10
® # Push month<3 from variable `®` again
Xα # Take the absolute difference with the year
© # Store this potentially modified year as new `®` (without popping)
т% # mYear modulo-100
D4÷ # mYear modulo-100, integer-divided by 4
®т÷©4÷ # mYear integer-divided by 100, and then integer-divided by 4
®·( # mYear integer-divided by 100, doubled, and then made negative
O # Take the sum of all values on the stack
7% # And then take modulo-7 to complete the formula, resulting in 0 for
# Saturday, 1 for Sunday, and [2, 6] for [Monday, Friday]
}D # After the map: duplicate the list of integers
.•1Î㦕 # Push compressed string "ssmtwtf"
© # Store it in variable `®` (without popping)
s # Swap so the duplicated list of integers is at the top
è # Index each into this string
s # Swap so the list of integers is at the top again
ǝ # Insert the characters at these indices inside the "_______" string
À # Rotate it once towards the left
Ð # Triplicate this result
á # Only leave the letters of the top copy
Ð # Triplicate that as well
„ssQi '# Pop one copy, and if it's equal to "ss":
'œÙ '# Push dictionary string "weekend"
뮦¦Qi # Else-if it's equal to `®` minus its first two characters ("mtwtf"):
’…Â‚Ž’ # Push dictionary string "weekday"
ëQi # Else-if the string remained the same after only leaving letters:
’€Ÿ…Â’ # Push dictionary string "allweek"
] # Close all if-else statements
u # Uppercase the result
# (after which this is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•1Î㦕` is `"ssmtwtf"`; `'œÙ` is `"weekend"`; `’…Â‚Ž’` is `"weekday"`; and `’€Ÿ…Â’` is `"allweek"`.
[Answer]
# JavaScript (ES6), 119 bytes
Expects a list of `Date` objects. Uses the `SMTWTFS` format.
```
a=>a.map(d=>a|=1<<d.getDay())|a-127?a-62?a-65?'SMTWTFS'.replace(/./g,(c,i)=>a>>i&1?c:'_'):'WEEKEND':'WEEKDAY':'ALLWEEK'
```
[Try it online!](https://tio.run/##hZJBa4MwGIbv/orQwxLBpCZOHV1VCrrLul1aKKOU8RGjczgVlY1B/7tTemhtWZtD@J48JO97yCd8QyPrrGppUcaqS7wOPB/YF1Qk7oe9x@fzmKWqDeGX6PoeKBduANQRw2YHePWy3qyfVpjVqspBKjJl09Qg0sj0/r7vZ3c8kDP8jvUZ3kTRc/Qa4sMULt76abFcDoC7x62G0HYiTMGp6VDBJzvj/MRAR3q48GLkxYW3jt6l3Lnw7qk3T16zqXmrzTjbGtH9iOxruT05I3Jv5FpXWjhnuf936lO0ncaSso5AfhBAno9kWTRlrlhepiQhhy/RDKJQPyiEVpFGH1b3Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 71 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Not happy with this first pass; need to try a few different approaches to see if I can get it down any smaller. ~~Outputs in lowercase, pending confirmation.~~ +3 bytes for the unnecessary requirement of uppercase output.
```
£ÐX eÃÍâ
`³ekÜü³ekÀAa¥³ekmtwtfs`qi o£øY ?X:'_ÃfÏg[Ue5õ)60¥U¬Ô7¥UÊ1]ÃÎu
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o9BYIGXDzeIKYLNla9z8s2VrwEFhpbNla4ltdHd0ZnNgcWkgb6P4WSA/WDonX8Nmz2dbVWU19Sk2MKVVrNQ3pVXKMV3DznU&input=WwpbIjIwMjEtMDYtMjEiXSBfTV9fX19fClsiMjAyMS0wNi0yMSIsICIyMDIxLTA2LTI4Il0gX01fX19fXwpbIjIwMjEtMDYtMjIiLCAiMjAyMS0wNi0yMiJdIF9fVF9fX18KWyIyMDIxLTA2LTIzIiwgIjIwMjEtMDctMTYiXSBfX19XX0ZfClsiMjAyMS0wNi0yNyIsICIyMDIxLTA3LTAyIiwgIjIwMjEtMDUtMDEiXSBTX19fX0ZTClsiMjAyMS0wNi0yMSIsICIyMDIxLTA2LTIyIiwgIjIwMjEtMDYtMjMiLCAiMjAyMS0wNi0yNCIsICIyMDIxLTA2LTI1Il0gV0VFS0RBWQpbIjIwMjEtMDYtMjciLCAiMjAyMS0wNi0yNiIsICIyMDIxLTA2LTI3Il0gV0VFS0VORApbIjIwMjEtMDYtMjEiLCAiMjAyMS0wNi0yMyIsICIyMDIxLTA2LTIyIiwgIjIwMjEtMDYtMjYiLCAiMjAyMS0wNi0yNSIsICIyMDIxLTA2LTI0IiwgIjIwMjEtMDYtMjciXSBBTExXRUVLCl0tbVI) - includes all test cases
[Answer]
# [Python 3](https://docs.python.org/3/), ~~223~~ ~~216~~ ~~204~~ ~~200~~ ~~190~~ 186 bytes
Straight forward implementation with `datetime` functions, no fancy string compression.
Saved some bytes exploiting a `dict` for the special cases.
*-4 bytes thanx to Kateba*
```
from datetime import*
m='MTWTFSS'
def f(x,y='_'*7):
for z in x:i=date.fromisoformat(z).weekday();y=y[:i]+m[i]+y[i+1:]
return{y:y,m:'ALLWEEK','MTWTF__':'WEEKDAY','_____SS':'WEEKEND'}[y]
```
[Try it online!](https://tio.run/##hZFfa4MwFMWfzacIfYm2Wvyz6sjwoVD3sm4vLZQRRGRGFkZU0ow1HfvsLqEPrcLcfQic8@PecyCdku9tE/V9LVoOq1JSyTiFjHetkHPAU/S8P@wfdzsEKlrD2j65KkUFmicOBrBuBTxD1sATZqlZXpoz7NhqwEtpn53lF6UfVals50GlimCWLzjRjyJsEeAcQEHlp2i@FVYux2i93R6y7Am5l9iiQBgZY7N@1V5hRle5eNnLBv0QlfemxVt5pKYIARaZhX4YeH7shcEsd0eGC6/qfozDAQ7HOLrixAviMU5usX9za@X5/zQZBkcDdTdQq4lUreKBSqZTo4kO8Sj170Y6BFg5BlYnWCPt2jZ/4Tj9Lw "Python 3 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 155 bytes
```
$o="_"x7;join("",map{strftime"%F%w%A",0,0,0,$_,0,0}0..6e4)=~/$_(.)(.)/,substr$o,$1,1,$2for@F;$_={_MTWTF_,WEEKDAY,S_____S,WEEKEND,SMTWTFS,ALLWEEK}->{$o}||$o
```
[Try it online!](https://tio.run/##bY1tS8MwFIW/@yskpLDBTZekSyuMioW1IG4qZDD9FCZ0UNmW0tYX6OpPN7ZFl4FNAvfkuZxz8rTYCWOwDpFCn8HsVWeHEUKw3@R1WRXbKtunyEmcDydCQPuLVTca6rp@Oh2HXxOsRu64fRMo315aE9aAGTDAfKuLm2SGVVir5Wq9ShSs4/huHj2DVN2R/T@@n4Ps9xKixaJDDbmusW6OR6yN4ZQzQn3C2YWVlyd5ZSm3lFvq/dKAMN/S4ETpn00QOlxxlutZObVS/M9tpW9lMJjrDVac2cRgW/Ct8yrTh9KQTb4zZPkuXEbb@fggb59@AA "Perl 5 – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~133~~ 132 bytes
```
for($w=SMTWTFS,$r=_______;$d=$argv[++$i];)$r[$j=$d->format(w)]=$w[$j];echo$r==$w?ALLWEEK:$r==_MTWTF_?WEEKDAY:$r==S_____S?WEEKEND:$r;
```
[Try it online!](https://tio.run/##rVPBboJAFLzzFS9kD5BCVGy1kaIhSi@l7QGMaSghFLZFE4EsqE2afjt9rLRaExtjymHZmd15bx5h8iSvbkZ5kguvGZN0ErK3tXdxQYK5r8tbVO/BgDgsaRAxii9pdyDrVS0kG8O5d2furaMQZgTbRyex8VOQ12MeWRgkVoeoWYaltJF9g2yQ9HUaJRlKEY5M255Z1t2ghgGvGoxqYmI@cc7h1R3OWQ8T5PSqloMoCKgF13JcGJuO5QwEURfqyWgYJZInAHjiKl0VNAapiNg8LyENl1QWFRC1ttZR2z1V64i@curNfXR9sk47QKfqujvUVzu9k3X9fV17r/uV2j53Wu2YM0SXv9DVOT4R9Q7OzvPZ/cN178Dn8Rl4dx/CAvgPLX@glVaL0YKWME9j@g7rkBVIYiYwK6ReHqa2rSPFryY0jCkbQJSla8pKKDMeKMheFjQqa@W5@fvuYI7dqWnD@HFiNdX@J5QeaoeEKVht2CRTaVJpDJtYKk0ktwRm0keV31jbRvM5xSh@VtXu4@@2/S8 "PHP – Try It Online")
Uses the script arguments array converted to `DateTime` objects (1-indexed), uses the `SMTWTFS` format.
First version with the dict exploit like in [movatica's answer](https://codegolf.stackexchange.com/a/230878/90841), but still looking how to shorten it.
**EDIT:** saved 1 byte with ternary operators
[Answer]
# [Ruby](https://www.ruby-lang.org/), 125 bytes
```
f=->l{i=0;l.map{|d|i|=2**d.wday};{i=>(0..6).map{|a|i[a]>0?'SMTWTFS'[a]:?_}*'',62=>'WEEKDAY',65=>"WEEKEND",127=>"ALLWEEK"}[i]}
```
[Try it online!](https://tio.run/##hZJda4MwFIbv/RUhN2lFQ4wzlhUtBd3Nut20UIZIyZqUCd3m/GCUxt/uImO0VtbeBJ73gbwHzinq10Pb7gI73B@zgEz3@J3nRyVUpgJqmgJ/C35optqFI4IxG/96rrKEpyGZoeXTar16WCKN97NNYyJkMRqEaB3Hj9H8RZMXhLCj@DmClkN9jfPFoktgk2Rp0xbyq84KCZDglURGYgCQQEqoYxNmUwem1mVigRNNBp72PB149@R922ED7597cvabZ5Nb0/S73R7d9ci71quJ9ci/0etemYJd9P4/k24xUiz59g2IT6AqWVZbXkqlm/O6KsEu@Yu6MwD6TvTGFIj0i3NelHLUBeMmNeSHaH8A "Ruby – Try It Online")
Takes a list of `Date`s and outputs in the `SMTWTFS` format.
Abuses Ruby's integer subscriptions to get a (sort of) boolean array.
I copied the dict exploit of the python answer, it works well :)
] |
[Question]
[
The flag of Tennessee is specified by chapter 498 of the Public Acts of 1905.
>
> An oblong flag or banner in length one and two thirds times its width, the large or principal field of same to be of color red, but said flag or banner ending at its free or outer end in a perpendicular bar of blue, of uniform width, running from side to side; that is to say, from top to bottom of said flag or banner, and separated from the red field by a narrow margin or stripe of white of uniform width; the width of the white stripe to be one-fifth that of the blue bar; and the total width of the bar and stripe together to be equal to one-eighth of the width of the flag.
>
>
> In the center of the red field shall be a smaller circular field of blue, separated from the surrounding red field by a circular margin or stripe of white of uniform width and of the same width as the straight margin or stripe first mentioned. The breadth or diameter of the circular blue field, exclusive of the white margin, shall be equal to one-half of the width of the flag. Inside the circular blue field shall be three five-pointed stars of white distributed at equal intervals around a point in the center of the blue field and shall be of such size and arrangement that one point of each star shall approach as closely as practicable without actually touching one point of each of the other two around the center point of the field; and the two outer points of each star shall approach as nearly as practicable without actually touching the periphery of the blue field. The arrangement of the three stars shall be such that the centers of no two stars shall be in a line parallel to either the side or end of the flag, but intermediate between same; and the highest star shall be the one nearest the upper confined corner of the flag.
>
>
>
Here is the flag, with annotations for its ratios:
[](https://i.stack.imgur.com/fd6bC.png)
Your task is to draw this flag in a way that complies with the statute. However, because the statute is ambiguous, you have some wiggle room with what you output. Specifically:
* You may use any colors reasonably recognizable as "red", "white", and "blue". (The sample image uses `#cc0000`, `#002d65`, and `#ffffff`.)
* The "stars" may have any exterior or interior angles. But all the interior angles must be equal, all the exterior angles must be equal, all edges must be the same length, it must have ten edges and ten vertices, and it must be reasonably recognizable as a five-pointed star.
* The stars must be as large as "practicable" so that their points do not touch each other in the center or the white band around the edge of the circle. Between the two points of each star closest to the edge and the edge, and between the points approaching the center of any two stars, there must be at least 1 pixel of space but not more than 1/48 of the length of the flag.
* The centers of the three stars may form any equilateral triangle, so long as no side of the triangle is parallel to an edge of the flag, and the vertex closest to the top of the flag is closer to the top left corner than the top right corner.
Shortest code wins.
[Answer]
# [PostScript](https://en.wikipedia.org/wiki/PostScript), ~~346~~ 315 bytes
Code (compressed version):
```
5 5 scale<</C {setrgbcolor}/R{1 0 0 C}/B{0 0 1 C}/W{1 setgray}/o{closepath fill}/c{0 360 arc o}/f{rectfill}/t{translate}/p{currentpoint}/s{gsave p t 4{0 -11 lineto p t -144 rotate}repeat o grestore}>>begin R 0 0 74 48 f B 75 0 5 48 f W 37 24 13 c B 37 24 12 c W 37 24 t 3{-.1 -.5 moveto s 120 rotate}repeat showpage
```
Code (uncompressed version):
```
5 5 scale % over-all scale
% define some short-named procedures for later use
<<
/C {setrgbcolor}
/R {1 0 0 C} % set red color
/B {0 0 1 C} % set blue color
/W {1 setgray} % set white color
/o {closepath fill}
/c {0 360 arc o} % draw circle
/f {rectfill}
/t {translate}
/p {currentpoint}
/s { % draw 5-pointed star
gsave
p t
4 {
0 -11 lineto % one line of star
p t
-144 rotate % rotate by 144°
} repeat
o % fill the star
grestore
}
>> begin
R 0 0 74 48 f % draw big red rectangle
B 75 0 5 48 f % draw blue rectangle
W 37 24 13 c % draw white circle
B 37 24 12 c % draw blue circle
W
37 24 t % translate to center of circle
3 {
-.1 -.5 moveto % move a little off the center
s % draw white star
120 rotate % rotate by 120°
} repeat
showpage
```
Result:
[](https://i.stack.imgur.com/PSBwM.png)
[Answer]
# HTML+CSS 28+291 = 319 bytes
Tested on FireFox 69 and Chrome 77 on Windows 10 1903.
```
*{position:absolute}c,d{height:480px}d,e{background:blue}c{width:700px;background:red}d{width:84px;left:716px}e{width:240px;height:240px;left:214px;top:104px;border-radius:100%;color:#FFF;border:16px solid}f{left:21px;top:-44px}g{font-size:150px;transform:rotate(120deg);top:65px;left:110px}
```
```
<c><d></d><e><f><g>★<g>★<g>★
```
---
# HTML+CSS 28+278 = 306 bytes
This version uses % instead of pixels, so some places can be off by a tiny amount of pixels, but CSS is shorter.
```
*{position:absolute}c,d{height:480px}d,e{background:blue}c{width:700px;background:red}d{width:84px;left:102%}e{width:34%;height:50%;left:31%;top:22%;border-radius:100%;color:#FFF;border:16px solid}f{left:9%;top:-19%;font-size:938%}g{transform:rotate(120deg);top:65px;left:110px}
```
```
<c><d></d><e><f><g>★<g>★<g>★
```
[Answer]
# [Scratch](https://scratch.mit.edu/), 530 bytes
[Try it online!](https://scratch.mit.edu/projects/520681894/)
I will be explaining the code here as well as in Scratch so that parameters can be more easily confirmed. Note that 1/48 = 2 pixels. Alternatively, 43 blocks
```
define W
set pen color to(#fff
define B
set pen color to(#036
when gf clicked
set y to(-48
erase all
set pen size to(1
pen down
repeat(96
change y by(1
set x to(86
B
set x to(76
W
set x to(74
set pen color to(#c00
set x to(-74
end
go to x:()y:(
set pen size to(52
W
pen down
set pen size to(48
B
pen down
set pen size to(1
W
repeat(3
pen up
go to x:()y:(
turn cw(120)degrees
move(2)steps
pen down
set[S v]to(20
repeat(9
change[S v]by(-2
turn cw(18)degrees
move(1)steps
turn ccw(18)degrees
repeat(5
move(S)steps
turn cw(144)degrees
```
## Definitions
```
define W Combined, these definitions save ~ 40 bytes
set pen color to(#fff Sets the pen color to white
define B Note that these hex values are approximations - they may not be perfectly replicated in vanilla Scratch
set pen color to(#036 Sets pen color to blue
```
## Base
```
when gf clicked Initiates code
set y to(-48 Sets y position to the bottom of the flag
erase all Clears the stage
set pen size to(1 Resets the pen to be 1 pixel in diameter
pen down Applies the pen
repeat(96 Loops code for each row of pixels in the flag
change y by(1 Moves y position to the next row
set x to(86 Sets the x position to the right side of the flag
B Sets pen color to blue
set x to(76 Draws a horizontal line 10 pixels long
W Sets pen color to blue
set x to(74 Draws a horizontal line 2 pixels long
set pen color to(#c00 Sets pen color to red
set x to(-74 Draws a horizontal line 148 pixels long
end Signifies the end of the code that should be looped
```
## Circles
```
go to x:()y:( Sets position to the center of the red field (which, for optimization, is the origin)
set pen size to(52 Sets the diameter of the pen to 52 pixels (diameter of the white ring)
W Sets the pen color to white
pen down Applies the pen
set pen size to(48 Sets the diameter of the pen to 48 pixels (diameter of the blue circle)
B Sets the pen color to blue
pen down Applies the smaller blue circle onto the white, making the ring
```
## Stars
```
set pen size to(1 Sets the diameter of the pen to 1 pixel
W Sets the pen color to white
repeat(3 Loops code for each star
pen up Removes the pen
go to x:()y:( Moves to the center of the circle
turn cw(120)degrees Rotates around the center
move(2)steps Moves 2 pixels out in a certain direction
pen down Applies the pen
set[S v]to(20 Sets the size of the stars to 20 pixels
repeat(9 Loops code so that 9 nesting pentagrams are drawn, essentially filling in the stars
change[S v]by(-2 Decrements the size of the next pentagram
turn cw(18)degrees Moves the starting position
move(1)steps of the pentagram to adjust
turn ccw(18)degrees for the smaller size
repeat(5 Loops code for each edge of a pentagram
move(S)steps Draws an edge of the appropriate length
turn cw(144)degrees Rotates the edge to be drawn an appropriate amount
Note that an "end" line is not needed if a "c-block" is at the end of a script
```
[Answer]
## PHP, 288 bytes
```
<?php
echo gzuncompress(base64_decode("eJyNjssKgzAQRX9loIupi9DM+GgF47+IJiagtcT08fnVYMFCF90Mc+Hcw63mR19XXrcBnq4LViEzo9Wut0EhZRkaNwwKD62UeNrI10rluBUo/8VLLla+h+Cb62wmPyqM79AEfSQiOHPygY0xWFet8+2gwStMy7W7ywXCt/fWBAuuW5wIyx0FExCU4gKLuRC5oJgEMVBMIgXiGCOxOu6zBuu1WawBdzP9FOJGlskfGGcRewOZ3F4l"))?>
```
Unpacks and echos the following inline svg image that abuses the browser's handling of both the HTML and SVG standards (newlines added for readability):
```
<svg>
<rect width='222'height='144'fill='#c00'/>
<rect x='225'width='15'height='144'fill='#026'/>
<g transform='translate(111 72)'fill='#fff'>
<circle r='39'/>
<circle r='36' fill='#026'/>
<path id='t' d='m-21 1 9-8 11 6-5-11 9-8-12 1-5-11-3 12-12 1 11 6'/>
<use href='#t'transform='rotate(120)'/>
<use href='#t'transform='rotate(240)'/>
```
Tested under Chrome and Firefox.
[Try it on phpfiddle.org](http://phpfiddle.org/lite?code=%3C%3Fphp%20echo%20gzuncompress%28base64_decode%28%22eJyNjssKgzAQRX9loIupi9DM%2BGgF47%2BIJiagtcT08fnVYMFCF90Mc%2BHcw63mR19XXrcBnq4LViEzo9Wut0EhZRkaNwwKD62UeNrI10rluBUo%2F8VLLla%2Bh%2BCb62wmPyqM79AEfSQiOHPygY0xWFet8%2B2gwStMy7W7ywXCt%2FfWBAuuW5wIyx0FExCU4gKLuRC5oJgEMVBMIgXiGCOxOu6zBuu1WawBdzP9FOJGlskfGGcRewOZ3F4l%22%29%29%3F%3E)
[Answer]
# Java + Processing, 441 bytes
```
void star(float x,float y,float r1,float r2){float t=TWO_PI/5;beginShape();for(float a=0;a<TWO_PI;a+=t){vertex(x+cos(a)*r2,y+sin(a)*r2);vertex(x+cos(a+t/2.0)*r1,y+sin(a+t/2.0)*r1);}endShape();}void setup(){size(166,100);background(#cc0000);stroke(255);fill(#002d65);strokeWeight(2.1);circle(77,50,50);rect(154,-3,13,103);noStroke();fill(255);for(int i=0;i<3;i++){pushMatrix();translate(77,50);rotate(i*2*PI/3);star(-5,12,4,11);popMatrix();}}
```
5 pointed star function modified from Processing examples.
[](https://i.stack.imgur.com/FO1kg.png)
[Answer]
## Python+PIL, 485 bytes
```
from math import*;from PIL import Image,ImageDraw
_=255
w,B,W,l,a=(_,_,_),(0,45,101),425,393,1.85
I=Image.new('RGB',(W,_))
d=ImageDraw.Draw(I)
t=d.rectangle
t([0,0,W,_],(_,0,0));t([l,0,W,_],B);t([l,0,398,_],w)
x,y,e,f=193,127,64,'d.ellipse([(x-e,y-e),(x+e,y+e)],%s)'
exec(f%'w'+';e-=4;'+f%'B')
def S(x,y,R):p,a,v,r=[],pi/5,2.65,29;exec('R+=2*a;p+=[(x+cos(R)*r,y+sin(R)*r),x+cos(R+a)*r/v,y+sin(R+a)*r/v];'*5);d.polygon(p,w)
exec('S(193+cos(a)*32,127+sin(a)*32,a-1.85);a+=2;'*3)
I.save('img.png')
```
[](https://i.stack.imgur.com/RQC0F.png)
[Answer]
# SVG, 260 bytes
Not very cross browser friendly, renders correctly in Firefox.
```
<svg viewBox=-35,-24,80,48 style=background:red><g fill=blue stroke=#fff><circle r=12.5 /><path d=M39.5,-44v99h99 /><g fill=#fff stroke=blue stroke-width=.2><text x=-10>★</text><text x=-10 transform=rotate(120)>★</text><text x=-10 transform=rotate(240)>★
```
] |
[Question]
[
Tomorrow is the Mid-Autumn festival, and in the spirit of that holiday, I will introduce a gambling game that we (people from [Xiamen](https://en.wikipedia.org/wiki/Xiamen)) play during the holiday!
# Rules
The game is played with six 6-sided dice. Different combinations of numbers have different ranks, with a special emphasis on fours and ones. Your job is to write a program/function that will rank the hand, given a roll of 6 dice. Here are the ranks (I've modified/simplified the rules a bit):
[](https://i.stack.imgur.com/hy8hP.jpg)
~~I guess only Chinese people can do this challenge!~~ Okay, fine, here are some English explanations.
* 0: 4 fours and 2 ones.
* 1: 6 fours.
* 2: 6 ones.
* 3: 6 of any kind except fours and ones.
* 4: 5 fours.
* 5: 5 of any kind except for fours.
* 6: 4 fours.
* 7: Straight. (1-6)
* 8: 3 fours.
* 9: 4 of any kind except 4.
* 10: 2 fours.
* 11: 1 four.
* 12: Nothing.
# Input
6 numbers, an array of 6 numbers, or a string of 6 numbers that represent the values of the 6 dice rolls from 1-6
# Output
Your program/function may return/output anything to indicate the rank, as long as each rank is indicated by one output and vice versa. Ex. Using the numbers 0-12, 1-13, etc.
# Examples(Using 0-12 as the outputs)
```
[1,1,1,1,1,1]->2
[1,4,4,4,1,4]->0
[3,6,5,1,4,2]->7
[1,2,3,5,6,6]->12
[3,6,3,3,3,3]->5
[4,5,5,5,5,5]->5
```
This is code-golf, so shortest byte count wins!
[Answer]
# JavaScript (ES6), 88 bytes
```
a=>a.map(o=n=>[x=o[n]=-~o[n],6,,,21,9,8^o[1]][a=x<a?a:x])[5]|[,1,4,5,o[1]&2|8,2,4][o[4]]
```
[Try it online!](https://tio.run/##bdDPCsIwDAbwu0/Rk3QQ59p1m4rVBwkRgjrxXytOZAfx1WenIoPJd8ghPz5CDnznan3dX24j5zfbprQN2wXHZ75Ib51dYG09OrKjZzsgBwCtYAqTlUdFhGzrOS95VlOEGT0QFBjIoF0O9WMCGgyhR0PUrL2r/Gkbn/xOlhIV/EJRJMZjcWV3FFoIqUw06GnzTphdnQSdqp5Ow6HZ@xTd1UXQxZ9qDWngOeRdrLSQyd/m9JMuzkLztIfbT3zTx80L "JavaScript (Node.js) – Try It Online")
or [Test all possible rolls!](https://tio.run/##ZVBNb8IwDL3vV/i0JGCitisdXy2nnZHGMcukrBQodAlqu4mJj7/O3DJNaDsktvP8np@zMZ@mSst8V/esW2SXZXwxcWLku9lxF9s4UfvYKavj3rkJGCFi4OMQB69O@VorE@8nZmpGey1UXx8V@hhiHxvwPjgOMMBQK6dCrS9LV/LSFQXEcDghWIremMIEIuh0IKK82xVwuAMwhCkppZW1m9dlblc8EnJnFvPalDWPEDyhW5OkkkDvbMWYaKWx24YJDz6CH9AJEQYUqBwiBHQeEfqU0QNBdHugZW4X2X625EtuRKvT2lSNmia5m@J4BKXJyEe15kZuXG45Yw3ndDd722RpLbfZV9XShaR9n0y65ldXSbtY6mzlikwWbsXZcwMw6F59d4GNrtXvPFlkdlWvG6h95ZVg4o/KTXdV5GnGPdrQEz/mkAli8/@SCTXBFBjSLzOgwW0je7E04CQu3w)
Outputs an integer according to the following mapping:
```
Rank | Output Rank | Output
------+-------- ------+--------
0 | 31 7 | 7
1 | 12 8 | 5
2 | 14 9 | 21
3 | 8 10 | 4
4 | 11 11 | 1
5 | 9 12 | 0
6 | 29
```
## How?
### Method
The output is computed by performing a bitwise OR between:
* a bitmask based on \$F\$: the number of 4's
* a bitmask based on \$M\$: the maximum number of occurrences of the same dice
Exceptions:
* When \$F=4\$: we use a special bitmask \$4b\$ when the two other dice are 1's, or a default bitmask \$4a\$ otherwise.
* When \$M=6\$: we use a special bitmask \$6b\$ when we have a six-of-a-kind of 1's, or a default bitmask \$6a\$ otherwise.
### Table
Valid combinations of \$F\$ and \$M\$ are highlighted in bold and blue in the following table.
$$\begin{array}{c|c|cccccccc}
&F&0&1&2&3&4a&4b&5&6\\
\hline
M&\text{OR}&0&1&4&5&8&10&2&4\\
\hline
1&6&\color{grey}{6}&\color{blue}{\textbf{7}}&\color{grey}{6}&\color{grey}{7}&\color{grey}{14}&\color{grey}{14}&\color{grey}{6}&\color{grey}{6}\\
2&0&\color{blue}{\textbf{0}}&\color{blue}{\textbf{1}}&\color{blue}{\textbf{4}}&\color{grey}{5}&\color{grey}{8}&\color{grey}{10}&\color{grey}{2}&\color{grey}{4}\\
3&0&\color{blue}{\textbf{0}}&\color{blue}{\textbf{1}}&\color{blue}{\textbf{4}}&\color{blue}{\textbf{5}}&\color{grey}{8}&\color{grey}{10}&\color{grey}{2}&\color{grey}{4}\\
4&21&\color{blue}{\textbf{21}}&\color{blue}{\textbf{21}}&\color{blue}{\textbf{21}}&\color{grey}{21}&\color{blue}{\textbf{29}}&\color{blue}{\textbf{31}}&\color{grey}{23}&\color{grey}{21}\\
5&9&\color{blue}{\textbf{9}}&\color{blue}{\textbf{9}}&\color{grey}{13}&\color{grey}{13}&\color{grey}{9}&\color{grey}{11}&\color{blue}{\textbf{11}}&\color{grey}{13}\\
6a&8&\color{blue}{\textbf{8}}&\color{grey}{9}&\color{grey}{12}&\color{grey}{13}&\color{grey}{8}&\color{grey}{10}&\color{grey}{10}&\color{blue}{\textbf{12}}\\
6b&14&\color{blue}{\textbf{14}}&\color{grey}{15}&\color{grey}{14}&\color{grey}{15}&\color{grey}{14}&\color{grey}{14}&\color{grey}{14}&\color{grey}{14}\\
\end{array}$$
All other combinations (in gray) can't possibly happen. For instance, if we have three 4's, we must have \$M\ge3\$. But because there are only 3 other remaining dice in such a roll, we also have \$M\le3\$. So, there's only one possible value of \$M\$ for \$F=3\$.
### Example
If we have a straight, each dice appears exactly once. So we have \$M=1\$ and \$F=1\$. Using the bitmasks described in the above table, this leads to:
$$6 \text{ OR } 1 = 7$$
There is another \$7\$ in the table, but it's invalid. Therefore, a straight is uniquely identified by \$7\$.
## Commented
```
a => // a[] = input array, reused as an integer to keep track of the
a.map( // maximum number of occurrences of the same dice (M)
o = // o = object used to count the number of occurrences of each dice
n => // for each dice n in a[]:
[ // this is the lookup array for M-bitmasks:
x = // x = o[n] = number of occurrences of the current dice
o[n] = -~o[n], // increment o[n] (we can't have M = 0, so this slot is not used)
6, // M = 1 -> bitmask = 6
, // M = 2 -> bitmask = 0
, // M = 3 -> bitmask = 0
21, // M = 4 -> bitmask = 21
9, // M = 5 -> bitmask = 9
8 ^ o[1] // M = 6 -> bitmask = 14 for six 1's, or 8 otherwise
][a = // take the entry corresponding to M (stored in a)
x < a ? a : x] // update a to max(a, x)
)[5] // end of map(); keep the last value
| // do a bitwise OR with the second bitmask
[ // this is the lookup array for F-bitmasks:
, // F = 0 -> bitmask = 0
1, // F = 1 -> bitmask = 1
4, // F = 2 -> bitmask = 4
5, // F = 3 -> bitmask = 5
o[1] & 2 | 8, // F = 4 -> bitmask = 10 if we also have two 1's, 8 otherwise
2, // F = 5 -> bitmask = 2
4 // F = 6 -> bitmask = 4
][o[4]] // take the entry corresponding to F (the number of 4's)
```
[Answer]
# [R](https://www.r-project.org/), 100 bytes
Encode the score as a bunch of indexed conditionals. Simpler than my first stringy-regex approach.
Edit- fixed bug and now rank all rolls.
```
function(d,s=sum(d<2))min(2[s>5],c(11,10,8,6-6*!s-2,4,1)[sum(d==4)],c(7,12,12,9,5,3)[max(table(d))])
```
[Try it online!](https://tio.run/##VY5Rb4MgFIXf/RWsfeEu10XQ2nXR/oi9Nn1giJ0ZUiI26X69A3SNzSEh9@Pcwxmmtkqn9mbk2F0NbdDV7tbTpuIAfWcoP7nj7oySMoYsw3cs0/L1xaUcC2Rwit66LiBY9sh4OAfcYQ6nXtzpKL60og3AGaaW@hR8CGCbHnnyTHmkuyfKF3pYUf6g7D@iiPJ3xFmkOZa@S3ibzfvFyzH3vMRyHRHM@axVi8IbFz1Rvoitus0FYvgczMiWsIx0hgzC/BB1F73VKkm25DPMQmsyXLV2iZRVqu5WmObtMnQNHZSlunMjZR8lhJqJs1XqrO5GKqzVv1RK/5UVblQZSp8hrFP1ZgN4M3Fx5Woh7M/AWdTKXMZvmP4A "R – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
≡⌈Eθ№θι⁶I⁻²⌕14§θχ⁵I⁻⁵⁼⁵№θ4⁴⎇⁼№θ4⁴§60⁼№θ1²9¹7I⁻¹²⌊⊘X²№θ4
```
[Try it online!](https://tio.run/##bY/BbsIwDIbvewrLp1TKJNK1RRsnhJi2AxKHvYDVBhEpJJAmwDTt2bNkQNkEPsSW83@/7XZNrrWkY@wPyrdrYAs6qk3YpLxlOw4zG4zPhSpSwNdDS72E5gWWTqWPGfWeLZQJPSs5vCrTMRQVcpj6d9PJYybFKKPF5ITWd9Caw3wXSP9Ww0Ss8C9YXcAP6Qy5T3ZG/uk5VMV1ODYjHKyvOpF1ZZEefMbBX1z8cYyp18kVBe3vbCvypdpax95I72XHlvYgXb7/ZvVs/h2jKJ/qpomPe/0D "Charcoal – Try It Online") Link is to verbose version of code. Does not skip 10. Explanation:
```
≡⌈Eθ№θι
```
Calculate the highest frequency of any digit.
```
⁶I⁻²⌕14§θχ
```
If there is a 6 of a kind, then subtract the position of the digit in the string `14` from 2. This results in 1 for 6 4s, 2 for 6 1s, and 3 for 6 of anything else.
```
⁵I⁻⁵⁼⁵№θ4
```
If there is a 5 of a kind, then the result is 5 unless there are 5 4s, in which case 1 is subtracted.
```
⁴⎇⁼№θ4⁴§60⁼№θ1²9
```
If there is a 4 of a kind, then if there are 4 4s then the result is 6 unless there are 2 1s in which case the result is 0, otherwise the result is 9.
```
¹7
```
If all the digits are different then the result is 7.
```
I⁻¹²⌊⊘X²№θ4
```
Otherwise the result is 12 - (4 >> (3 - # of 4s)).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 169 bytes
```
a=>-~"114444|123456".search(w=a.sort().join``,[l,t]=/(.)\1{3,}/.exec(w)||[0],l=l.length)||(l>5?3-"14".search(t):l>3?4+(5.5-l)*(t-4?4:2):[,13,12,11,9][w.split`4`.length])
```
[Try it online!](https://tio.run/##fY3dToQwEEbvfQyuWh26Dp2SLAnwIEgCwe4um4ZuoBET0VdH1v1JVKDnbk7O12P5VnZVW5@c39hXPe7isYwT/8tDpOkNGEhSoSc6XbbVgfVxKTrbOsbF0dZNUUBmwOXxhgn@gh8SPjdCv@uK9XwYsuccTGyE0c3eHaYDM4lKpe8h3Qcdj0wiU3piSijf8EfmfEopCniUAUrAABBhm2e96E6mdgUV172cj5VtOmu0MHbPdixDQKALOecPfywBrdhze2XGhnBndVnNWAk3cKVVsxYhmLqzXf5XLrQBXKDFNoSf/Vkbrlj12/6P1Y1Jj98 "JavaScript (Node.js) – Try It Online")
Returns `1..13`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~148~~ 119 bytes
-27 bytes thanks to ovs's (1. use of `.count` allowing a `map` to be used; 2. removal of redundant `0` in slice; 3. use of an `in` rather than a `max`; 4. shortened `(F==4)*O==2` to `F==4>O==2` [since golfed to `F>3>O>1`])
```
C=map(input().count,range(1,7))
O,F=C[::3]
print[F>3>O>1,F>5,O>5,6in C,F>4,5in C,F>3,all(C),F>2,4in C,F>1,F,1].index(1)
```
**[Try it online!](https://tio.run/##PY7NCsIwEITvPkVuJjKKSdoKlfRSyLUPUHIotNWARqlV9Onrpv5kCPlmFjJ7fY3HS1DT1HY963kr8tLUt/uZP4zxrL8M7MF8YK2I6CMOTTh0XGIn3L6CNWW9zXPt9tfBh7Hm1phErCpjFGyRoqJ7bp68FAS2SJDSFyWRRnM6UUyokHxDCQvpNj603ZNLMcXSsbuNsZfXEn85MLLJLHqj1ciQRgP1mSpoCjJkv6n@KFra4ycn8gWjM@8/t4Et18USc9rzmIjpDQ "Python 2 – Try It Online")**
[Answer]
# Pyth, 60 bytes
```
eS[@[ZhZ2 4*6hq2hJuXtHG1Qm0Q8hT)@J3*5hSJ*Tq6hJ*<3KeSJ@j937TK
```
Maps to reversed rank, 0-12. Try it online [here](https://pyth.herokuapp.com/?code=eS%5B%40%5BZhZ2%204%2A6hq2hJuXtHG1Qm0Q8hT%29%40J3%2A5hSJ%2ATq6hJ%2A%3C3KeSJ%40j937TK&input=%5B2%2C3%2C2%2C3%2C2%2C2%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=eS%5B%40%5BZhZ2%204%2A6hq2hJuXtHG1Qm0Q8hT%29%40J3%2A5hSJ%2ATq6hJ%2A%3C3KeSJ%40j937TK&test_suite=1&test_suite_input=%5B1%2C1%2C1%2C1%2C1%2C1%5D%0A%5B1%2C4%2C4%2C4%2C1%2C4%5D%0A%5B3%2C6%2C5%2C1%2C4%2C2%5D%0A%5B1%2C2%2C3%2C5%2C6%2C6%5D%0A%5B3%2C6%2C3%2C3%2C3%2C3%5D%0A%5B4%2C5%2C5%2C5%2C5%2C5%5D&debug=0).
The full mapping used is as follows:
```
12: 4 fours and 2 ones.
11: 6 fours.
10: 6 ones.
9: 6 of any kind except fours and ones.
8: 5 fours.
7: 5 of any kind except for fours.
6: 4 fours.
5: Straight. (1-6)
4: 3 fours.
3: 4 of any kind except 4.
2: 2 fours.
1: 1 four.
0: Nothing.
```
This works by mapping the dice values to frequencies, then calculating the value of several rules, and taking the maximum of the set.
```
Implicit: Q=eval(input()), Z=0, T=10
JuXtHG1Qm0Q Input mapping
u Q Reduce each element of the input, as H, ...
m0Q ...with initial value, G, as an array of 6 zeroes (map each roll to 0)
tH Decrement the dice roll
X G1 Add 1 to the frequency at that point
J Store the result in J
@[ZhZ2 4*6hq2hJuXtHG1Qm0Q8hT)@J3 Rule 1 - Values for sets including 4
Z *0
hZ *1 (increment 0)
2 *2
4 *4
JuXtHG1Qm0Q Input mapping (as above)
h First value of the above - i.e. number of 1's
q2 1 if the above is equal to 2, 0 otherwise
*6h *Increment and multiply by 6
Maps to 12 if there are 2 1's, 6 otherwise
8 *8
hT *11 (increment 10)
[ ) Wrap the 7 starred results in an array
@J3 Get the 4th value of the input mapping - i.e. number of 4's
@ Get the value at that position in the array
*5hSJ Rule 2 - Straight
hSJ Smallest frequency in input mapping (first, sort, J)
For a straight, smallest value will be 1, 0 otherwise
*5 Multiply by 5
*Tq6hJ Rule 3 - 6 1's
hJ Frequency of 1's (first value from input mapping)
q6 1 if the above == 6, 0 otherwise
*T Multiply by 10
*<3KeSJ@j937TK Rule 4 - 4,5,6 of a kind, other than 4's
KeSJ Get the max frequency from input mapping, store in K
j937T [9,3,7]
@ K Get the element at K'th position in the above (modular indexing)
<3K 1 if 3<K, 0 otherwise
* Multiply the previous 2 results
eS[ Wrapping it all up!
[ Wrap all the above rules in an array
eS Take the max value of the above, implicit print
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~137~~ 126 bytes
```
4
A
O`.
^11A+
0
1+$
2
^A+
1
(.)\1{5}
3
^.A+
4
.?(.)\1{4}.?
5
^..A+
6
12356A
7
.+AAA$
8
.*(.)\1{3}.*
9
.+AA$
10
.+A$
11
.{6}
12
```
-11 bytes thanks to *@Neil*.
Output is 0-indexed (`0..12`).
[Try it online](https://tio.run/##Jc2xDsIwDATQ/b4jAzSS1WucAFPlL@AHUNQOHVgYEFuVb29dOvn0dCd/l9/7M3PbFIbnJKikRfRgDBhQPRMXub645oaEKi4KGU/TJiOy68EFHFIuhhskmlnAHdKdxdSkw@PvAeyP4JeQtTSf@X/NqtwB) or [verify all test cases](https://tio.run/##JY49jsJgDET7OUeQgEgW4z/YCn3VlnuBVQQFBQ0Footy9uAkr7Hn2Zb8fnyerzvn3f73Njsa/m6CgWw9TmDfQTFUT@zl8M8xJhgGKeOQ6@Z8kiui7KITVItsOEP61lqHC@S4LdokR/ysvgNPS1OVkDGnOptnujsdvlKTBeRKyVikFbQtEZZ0jUoWlVRdU@FJU4dWTUM9w5LhUYBhqXUekRlf).
**Explanation:**
Replace every 4 with an 'A':
```
4
A
```
Sort all the input-digits (the A's will be at the back):
```
O`.
```
Every other two lines replaces the input with the expected output:
```
Regex Replacement Explanation
^11A+ 0 starts with "11", followed by any amount of A's
1+$ 2 ends with any amount of 1s
^A+ 1 starts with any amount of A's
(.)\1{5} 3 six of the same characters
^.A+ 4 starts with any character, followed by any amount of A's
.?(.)\1{4}.? 5 five of the same characters,
with optionally a leading or trailing character
^..A+ 6 starts with any two characters, followed by any amount of A's
12356A 7 literal "12356A" match
.+AAA$ 8 any amount of leading characters, ending with three A's
.*(.)\1{3}.* 9 four of the same characters,
with optionally any amount of leading/trailing chars
.+AA$ 10 any amount of leading characters, ending with two A's
.+A$ 11 any amount of leading characters, ending with a A
.{6} 12 any six characters
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~57~~ 55 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4¢[[email protected]](/cdn-cgi/l/email-protection)¢©5-Di14¹нk2αë>Di5X-ë>i9X3*-¹1¢2Ê*ë®i7ë¹4¢o;ï12α
```
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/172756/52210), because my initial approach was already at 60 bytes and I wasn't done yet. My current answer can probably be golfed some more, though.
Input as a list of digits.
[Try it online](https://tio.run/##yy9OTMpM/f/f5NAiE4dQPd9Diw6tNNV1yTQ0ObTzwt5so3MbD6@2c8k0jdAF0pmWEcZauod2Gh5aZHS4S@vw6kPrMs2B5E6g7nzrw@sNgcr//4820TEFQjMgNI0FAA) or [verify all test cases](https://tio.run/##VY49CsJAEIWvElLKRNhfEcFYpLVUEkIKBYvFIoUgpLC1sBKPkE4Cigew2e3FM3iRuLNLIu4rhpnvzb4pd6u12rT7Kg6Dz/EShHFlzsmy5brms8Vwrmt9FVGiCM/ezy19PUwzTZRII1vVOGWDKCO6puY0MI2@qZFpMrtaTsydWHN7sA/aPCfAnWwtIMg59MKWQC9sJfTqzOJnZuBFgP1T4qnEEKAgOsocd5TaOTIJ1FM0Mxx66gfS/4x7vnVm4YKc/M0CMIx2Zwhnl5YWXw).
**Explanation:**
```
4¢ # Count the amount of 4s in the (implicit) input-list
4@ # Check if it's larger than or equal to 4
# (results in 1 for truthy; 0 for falsey)
U # Pop and store that result in variable `X`
.M # Push the most frequent number in the (implicit) input-list
¢ # Pop and push the count of that number in the (implicit) input-list
© # Store it in the register (without popping)
5-Di # If the maximum count - 5 is exactly 1 (so the maximum count is 6):
14 # Push 14
¹н # Push the first digit of the input-list
k # Get its index in 14, resulting in -1, 0, or 1
2α # Take the absolute difference with 2
# (This covers cases 1, 2, and 3)
ë>Di # Else-if the maximum count - 5 + 1 is exactly 1 (so the maximum count is 5):
5 # Push 5
X- # And subtract variable `X`
# (This covers cases 4 and 5)
ë>i # Else-if the maximum count - 5 + 2 is exactly 1 (so the maximum count is 4):
9 # Push 9
X3* # Multiply variable `X` by 3
- # And subtract it from the 9
¹1¢ # Count the amount of 1s in the input-list
2Ê # Check if it's NOT equal to 2 (1 if truthy; 0 if falsey)
* # Multiply it with the 9 or 6
# (This covers cases 0, 6, and 9)
ë®i # Else-if the maximum count is 1:
7 # Push a 7
# (This covers case 7)
ë # Else (maximum count is 2 or 3):
¹4¢ # Count the amount of 4s in the input-list
o # Take 2 to the power this count
;ï # Halve and floor it
12α # And take the absolute difference with 12
# (This covers cases 8, 10, 11, and 12)
# (Output the top of the stack implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 100 bytes
```
->a{%w(^2.*4$ 6$ ^6 6 5$ 5 4$ ^1*$ 3$ 4 2$ 1$ .).index{|b|/#{b}/=~([1,*a,4].map{|c|a.count(c)}*'')}}
```
[Try it online!](https://tio.run/##PY3RCoIwFEDf/YoLLdRxm@jm3uxHxoRpBT1kEknFtn59zbQ4D5dzz4V7m7pXODVhtzd2@8jailFBQBJoJUioCdQQvS0pAU5AQEWgJMBydh4Ox6d1nSs2tvNF885UidSg0OxiRut6Z1h/nYZ71ueepmnufVDx5I9GiCq@xDkrR4n1LFgttUIeFxLlr/KFWUUsK3r9aVwygjIIJ2W0Tnz4AA "Ruby – Try It Online")
### How it works:
Count occurrences of every number in the array, prepend number of 1s and append number of 4s.
After that, try to match with different regex patterns.
] |
[Question]
[
## Challenge
Given an image of the Moon as input, output the phase of the Moon.
## Phases of the Moon
Your program will be supplied one of these images in png format and you must output the phase exactly as given:
```
new moon
```
[hexdump](https://gist.github.com/beta-decay/9b7f749f38dc0c9111915e4ffdd65991)

```
waxing crescent
```
[hexdump](https://gist.github.com/beta-decay/bef0e11df0f341fd898a3374f3359e9a)

```
first quarter
```
[hexdump](https://gist.github.com/beta-decay/6eb33f2bd86edacc48b2691b478d8d57)

```
waxing gibbous
```
[hexdump](https://gist.github.com/beta-decay/04a900f675a7f2f6a1b55c3eb6a4802d)

```
full moon
```
[hexdump](https://gist.github.com/beta-decay/306e2fb0ed1193cd2ec3c89f1f60a46b)

```
waning gibbous
```
[hexdump](https://gist.github.com/beta-decay/132ae63f6af2484bdd6972c63db2b5bc)

```
third quarter
```
[hexdump](https://gist.github.com/beta-decay/ed0f4874c88c0c601a621860a2764dc4)

```
waning crescent
```
[hexdump](https://gist.github.com/beta-decay/8d3b14d4ac2ad86b6ed9bc45196959ed)

## Input
The input will be the path to a 240 px by 240 px png file and will be the one of the images above.
The image bytes are guaranteed to be the same.
## Winning
Shortest code wins
[Answer]
# [Node.js](https://nodejs.org), 145 bytes
```
p=>'third/waning/first/full/waxing/new'.split`/`[(s=require('fs').statSync(p).size)%418%6]+' '+'quarter/crescent/gibbous/moon'.split`/`[s%12%9%4]
```
[Try it online!](https://tio.run/##VY7BTsMwEETvfMVKKLKjmLhp3KQVSm9wRuKCVFWqm24ao2CnXocCPx/SqgeY09Nodmfe9aem2ps@PFh3wLGpxr5as9Aaf5BnbY09ysZ4CrIZum5yvi6OxTNLqe9M2MndhlPl8TQYj5w1xOKUgg6v37bm/cTmB@NIZcuo2CYMWMJOg/YBvaw9Uo02yKPZ791A8sM5@@ctRdk8WkVqOz5ucrXIBBQqnwlYZEoJKGflhefL/MJFKUCtymLK5Hm5vUsb55903XJOAkwM1Rr4/41nbwI@mw6vQ9m1WwB7Y6nHHnXgFMcCamfJdZh27sjZS6sJ4Z5BAkZAczuKJ42/ "JavaScript (Node.js) – Try It Online") (generates dummy files with the same sizes)
### How?
We just look at the size of the file and convert it to indices in two lookup tables.
First part:
```
phase | file size | mod 418 | mod 6 | mapped to
-------+-----------+---------+-------+-----------
0 | 3451 | 107 | 5 | new
1 | 6430 | 160 | 4 | waxing
2 | 5144 | 128 | 2 | first
3 | 7070 | 382 | 4 | waxing
4 | 5283 | 267 | 3 | full
5 | 7067 | 379 | 1 | waning
6 | 4976 | 378 | 0 | third
7 | 6337 | 67 | 1 | waning
```
Second part:
```
phase | file size | mod 12 | mod 9 | mod 4 | mapped to
-------+-----------+--------+--------+--------+-----------
0 | 3451 | 7 | 7 | 3 | moon
1 | 6430 | 10 | 1 | 1 | crescent
2 | 5144 | 8 | 8 | 0 | quarter
3 | 7070 | 2 | 2 | 2 | gibbous
4 | 5283 | 3 | 3 | 3 | moon
5 | 7067 | 11 | 2 | 2 | gibbous
6 | 4976 | 8 | 8 | 0 | quarter
7 | 6337 | 1 | 1 | 1 | crescent
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~223~~ 222 bytes
-1 byte thanks to OMᗺ
```
lambda p:'new moonzzfull moonzzfirst quarterzzwaxing crescentzzwaning gibbouszzwaxing gibbouszthird quarterzwaning crescent'.split('z')[sum(n*Image.open(p).getpixel((n*48,99))[2]for n in[1,2,3,4])%13]
from PIL import Image
```
`getpixel((x,y))` - will return the RGBA pixel at `x,y`
`getpixel((n*48,99))[2]for n in[1,2,3,4]` - will return the blue channel of the middle line, where `n*48 ... for n in 1,2,3,4` will be 4 points where the sunlight may cover
`n*getpixel(...)` - will generate a different value for each column
`sum(...)%13` - these values are added together and `%13` is used to get an unique value to each phase, that will be used as index for the phase list
The pixels are approximately inside the red circles:
[](https://i.stack.imgur.com/dcm80.png)
[Answer]
## Ruby, 131 bytes
```
->f{f=open(f,'rb').read;%w[first third waxing new full waning][f[699].ord%7]+' '+%w[x moon gibbous quarter crescent][f[998].ord%5]}
```
Byte offsets found by brute force -- taking the 699th byte of the file modulo 7, for instance, gives an index into the first lookup table.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~196~~ 165 bytes
```
lambda f:'first quarter|new moon|waning crescent|waxing gibbous|third quarter|full moon|waxing crescent|waning gibbous'.split('|')[sum(map(ord,open(f).read()))%41%9]
```
[Try it online!](https://tio.run/##jXtpdxZF1/V3fkUpKAGlqK65EUVBRFBxQkGcqKkBZQxBRvnr97t3dXUS/PCsl7WMCeQ6XXWGffYZOqcnd/5X0p54LZ4/r@LUrvhE3L2fbjf56MHtI0f4L5@I8rDi5xfi7NmL337xv3vpfq5JLGeOL3d3n@yJx0/T7l7bff2gPRP3Hz588PpZenD3wW1RdtuT0h7s4efn/Pn23ZwfPn3yeu/O3d26/6nl6b1728ee/@djDw597Lh88uje3b2d46@Pn/j1ydP7O/fTo52Hu/XDh4/ag53lhNxtqe6cOHHiPTu9N//@v0e7dx/s7dzeOb5/m@MnThzB@Y8cedJw0bvi@JPTf9w7ffvje6ePbzc8cuTRi707Dx/o7S/@p8afMyLOTgnbbBCqqiSmhC/8F36pws42CmudFkJ@d/WSHH8uf/n5D0dWCRNkjN9f1OHvotLbj3kSJoQGGW/9CW@GDA0Zxant495rYTNOZC1@XJaDL0kNGfmrS58PKUOGgQzYL4jZbIc3ys6QYSfhbIhiLlBQrSFv51CXP//s2nN882rIsJAxKxeEd1MVJSyTWEJcRHMJJ4o5C9eUF5ObLWRcb@MEX8o/Ds7heJdcksBnvAhRG/zos7AaR1CzcSKFrES1buI5br7//Kj8@/xz6SDi@yHDU6fFGaofRzZTFFNNOIxWi/Ahw44@FxGLoT5@vPzNeo7b/VJDRqBtW7IiGdVwIZ9EcmYWc1qCaHby0EyMOOU8r/pof8mZ//9c3tzuEiHDG5w26QBjZgXtetrWT1lErTL@Li9iaUsUoki5e9i6Q8bcbZu9KAnnXsrihSk1iMXMReCnLOa4VBFDmDe7nOWXv/HfiyEj0batLMKFFkQxdRbB4PfnFqAjXFAoM3cr0y7yOj765IV8ckVJeW1vyMjUaa54ksK1LX09W22FdXHCraAoHasSs57seg4o9dhF/H/n4C6FMpxL@C06hLJwCP6@j3C0mODwuuI7N3U/vSnlp1/9IO9clvLU5e83GRUytNOzUCnjmYgtEafZi2R1FFXNWkxWOdoFMffeiUOHOLBLg4ykLeI2O/6@x4XmiLjVmiELz8JZnNAzriveOgQEDhkLZFhjYFGFuxttLBRrPSIH9/O8WqZtW1Lw0wtBSm3lF/Lmra8ObDupHnMItxYRbtkBSVSCEl2tPFaLohRaXk1p2PY7KX9/yz8m4oePBN6WDQKkwjGnxYjFGwaeTkInhBuO4YW40z/5mZTn5MmTBzKIHz4hQFSDe0ULf0qTW3CDeRHwlgLomAJUDDATf62P/1PKj3vwDhnEjzilJmpDqLgI/9DZ40JOI9KCcyKrArnFrxj01w35wS35ofwJ398aMogfE29QTEiIfR/wSSgxJfjY0qieZXHAJRW7jJfPb29aUdtdiB/Rw7ZhgT4yzZo0LGQrwsdkRI5KfoGOACyw7XqZb@RHUj787OiQQfzQJeJDHpFpFPwDls6iQLqYIiDMGmjLTsBY8SHMqu6YVzzFBfnZpSEjdB@b6@rNZkkOkASvaAgAqkeJmP0kfG79Lt/DJPIr@dMNKdPf212IH6EZqNMqA1UU3AqKFlOBQwSrNZQ9N7itg5@@OXMNN3mMmN17F9/8PmQQP9wUcWQ/R2JQpndWuJz3Iif67jIV/AP18T3uAnN8Ixe6iNz0Qfxo8DQEHoBL4UZ4cIQ6Zx4mwGDRtyYKUIF3ea/rdFZv@Wle7wITakRJ0QVBNhlIm9MM14CBkRsWWA1qF29UP8hH/PxBbpiIHy1Aa85Ba7alAosqpt8YRO3GCTmtGUzI9JO8ChFXu3/syyB@qISM0CJMsijGbaF6mCBMDjhWQlTHEvWIOdv947EM@zKIH9k04Loi5FVkJucQJVbBs6IDvCLdWpHLVIeM5z/JTx@@pQ/iR4YGgOHIL9GbiX4N6ACQCSR74KOZEJE6bzImJf86/ww@tsnQqsdLYrw0gxQHuGoNEBYb1BmU8cjZgEYkDbPPHU5J@cgfnEMTP2ZCqUJwiGmacBgDGuBVoJPYJjSsLhQzxz7/uPWvvPru9/syOv9Q0Fom6IRmkWlUSsADD2kOn2wqIGUpTw4T5Lk338IkDyDomXwwZBA/xuOI6wvUqZZkYMwAK6fZwD8QSCX3nH31XXmaB3l9hv4xcrbu@GGoD/jB6l6gZ0W4JYMBULidW4GOgut3eQX3@A1AdhXo/nTIIH54vbojPmngbWGCtxmPFA6ap0SOunMB8KCMp/@YHku/Kx/Jk/KjIaPjx1SQoyxwbDIGd1FQitVI1/2SQUPFJscixDvAMaTsb8//La/u4kBDRucfE9wxKzc@pAvwVxu4nKHzBdIGrXrOfix/lVc//PKoNPKNFCNna@LHBBCnXbpLB1zIAhUZQzo1OOvkgB85rLaFh/94QaaTDLpnQ0bnH7pQnRUsLBagBsBNGAdNQjisXPFd2PfTL@FgrnvJ7naX1PM@7m4arAG7WOEygHzS@BEMh@wuI5NOxDH59ye/SfurlL9JeX4fxzTxA3G@IMdPhDBDMgQ@FiwhaSaSOGSfODFnX6WPajnvDQwZMkrP2ZlY4Z0IM@wCEIUWjALRTcgX3hhDqEO@RZy1F2fPw82uyGL2ZRA/QHlglxSr0A2acRWOOS8ReRxHEnlBBOdAfnqj62Fk7PMbP9XED4UrIyws8xwCtV8DyGHAN0FcY0O6niM8UMgP5JXnfo9Sfjx0l44fZnuSVfCnoiJBB7fSFWSvZJwSIUSd4tk91Z09xa8fHxmUn7EfE5zbgpoaDTTSvjnydVDeqJlawAUsw0cQCLV8Hx8ni/h2nMMQP3o@6op1k7dIbPBOox1jrvsHzBozkEEwQ35fwYVudLWcGzKIH1VR/eAiOAz81Df4afVQpwU1A7ZtgiDjFk7y4AKZ9kGeM8SPFIl7E4A85IqCZYaTGGgFeFoATgkuB6v1HPUYwS/1WQDQgU4N8SN7ZKZQQCYL8beDSGWOgjWMCHVa6HeeMl7vbDnqXyn9kEH8CBaZLGugV2Wk4WwEMzim9ThHo9dPE6Ja7PHDCc7FdPeb/HXI8J3DFKYRgF@jf3gLMjQR15cFNCBa3GoO81oTvpa@3n67bjDED@vXPFeRDBBkS9EjXqoGKLQAM3kD7Qom20dSnujnkWWT0fEjIuydL07U7hAJDh8U860GREM7sNoUeq78uX/6Uf@adocM4kdwCSTOLcD1gLRg1QwtTExPEekmI4uKNFfc5Sk@eZykzL91l44fGaATsrMwawQWkicjTcJZA8rj5DL/QVEfj16BCJ0clt2XQfzIC7RWK5wKSgT8GOB6pBbwdHhstR3ml7fr7I@/9JsM4keMSGd4LmsPeltD1QJCQLkR2SrSWWk6yHhz7RjQ@D92IX4sE9yrk9SyQJM5w9eXoIEfnsnLZyK8pp/udIZ6QfYTmSGC8BFQLolKzJkz/AxELrESKav/lgoR4FmAj@dvtQyO3Rsylp4q4Zz4FpV@q4WIBA9l5pxUBFZTUKyeZXaS8hNQh89edcukI6PaZ9jSBCjaC50ejlVIdgNcTDs4rIayxRLLKE33eo557/apfXXY3v5YoPMA9AcDYvUD/xd@Buag8nCgV/gCTt7N8gJE/8dbd9fLPBwyCB/NRvxWgotVhBvUV9kjAIsqSL@IYtCgptUoTaUyXZ8HZrGEDzXj45PGg3UoRFJ8vBpY2kWw27A4UKklTquM4/xy7Ub3@iGD8FHpCqAsYPYe@XUxqD/AHCpC2dHtXCAd62EbyLIllPEjK@4hg/CB4EVmWWBMFHENzkkuOQEZW2P1UxKd3tI9/j3dDTOK/k@HjE4/lkKXzGyhgFouxvQLWRT@EDnzGh4lgBCkUc8nktwnn5CTDRmEDz0jOhPSJEAAJaSfSE9BV@EaqAvLYumBM6jUiTXk5T16x6f7dyF8zCHx7h6aBAujgQEkGUmiMnAM/hJ5aulwKjPLOIn08PGf@zLmHvpwZO2XAhnIa7aEtvJiMPEmFguUnydL295jevp6jTktPx8yCB@IqX54lDsKeXvm4WENFKl01uiQuybPFtvfuIXiLW52C48WmyV8NMYLiqGNNnlQupygCuvgKUuYiSY1rPECCvWtlBcPhb4lfMxQiFCRfsoYLRXRh1oIaXzpMA1pqOMZLy9Xu364Quo8ZHT6UZCtAxsLsCgNjKuVmQ0cYtnkQAXg9ID137oQIgBbOjIOGZ1@VBwBlAxOspALVcRoMrDQXOGdxQePm66lKRy8/bse5p/9uyxbKZYcEsLCbosN@K5NCtICrVwV061yQx/yUuf7B/pwvXxpyB3OOzLIBlVMIaw1XS34JKpmZKxYGfu7P/@2K9951vPtL883GcQPN4MmlznjcQ4O4TzKbEN7LxalplnAfaeqcY5fHvPDP38FGV@cAxANGcQPFH4IcY8sknW1a9GeAjJFYDU4O3xcMfeLrgSU62DtgZXukEH8MBG2tRlQEzPcK4NFrN3DkkDzvOYTpgX4EV9@JUfr4UoGFRkyiB@oC4C/gT21BjtmAqjTwDawQoYbnuCmCT528tVqkh@kU/Ll1h5zvf0xwYS5pyPaRYO/wb1o4Nodh@S1@K2slMf6V3jK/SGD@AFiz55aw4VY3oLxNLp5JsGGTpO2os3TKJG/eS4f0NPPHNvXR@htXKT9AF2gToArLbxBWXxi42QGAICo5jz1dnLPUqhvP7tMIBsyiB/ZorhQnmUUjeMSoFQzoXh8VICYAseYrcR6hZundnrn89YmY@76AHEpZPZ4OJ5OdzFwcYAqbFWgd8DlwHXkhMuPz5JMfXp6k0H8ANUoLPIN6VsEuMOOU4WjTShFgGPgdQABxO0zdrRuLGzmyI/lHyeGjLziKdyAN04R6sdfoo4s7FBX4COuAbStoEbAU9zhfu9L5VsH8VJ6fgEd63nOoxLEESZW7pCRPSBpqUiTQMbR5s8fdxl/yIcfbDKIH2HJbPZyZEE2Vxr4l1t601TjHMBBVCKxl4TXLq29vpvvptu/bzKIHzO1lvA8oLN1UCL4tk0oSDMb0ZPT9JTgR4vtIosoJO8P5D9DRi9fcmRLmuhlECotM14Kkl1NFawy42zarqX69X0G87c8Nkp1r/pdYFa9EJgbfAyko6c98m24eYgFoFo6/zCngUI/d0d7DsY8ZEydFuLIIKHAdYsTxQp/iuzQTcuMf1igZ1ASxv6Lw7xwo4We@AGowQ0Mu54atrWlGfZLe4sZ/u@nGTWdCb0Uk@/e/5q9bfbrwpDR@UdBLT/RSVQ1ZGEebo5wJVcGECkWQzA9ZOz1wuMu3NQ8goKHDNvLBrb11nMATxNRwDjteTa4nEGSafw7QfLBPqF7/zA99Wv7Y4ZPTkkL1fozgRpLxDVSTBbuAvIK6ye2P/gHBuZNdq5tMjp@WDAo76G/MoPOFdRWQAFYQ7O3PSNqkC/W/LIwXD/tnalblzYZvXxhhqweZMEDa6g/cnzYtqAMg2vAzS0ZjvgGrOFBb9QRzb7ZZPT2adc8McgZ0J3kS0G5j3hRNFOwQFuLhCEEUf3HtRd8f@/VxTpkzD3PZTjmoqlJNeNqgOPqErxTc8w1gzakUldueXRtfUCzb/Z1SvxAvUeTIFrxXDAodvkie651Rsia3ptls0gg1FBknzkvj8qHYFMvhwziB5gw4jZCFbahLpwj3RblMXwXuQ@2AVFbfV3ekFdfw1sv9@JhO0fp@VbXdQazHoaEG0bvA5MC1l0AIiXSLqd4EiGbvCnvHvhHH7@YAOdmvw@1JQc34BrZkL7T@aYMoxsWVOLoE7aUZETVACPPmwziR02AH82ulne4CwhEXT8UEsApzxA5O@ZKeWnnanvNT7/skoYM4gfCfGbRB0yuSFSuu5dG3MLIDYexBT7m45bnfoVVwFC/vnTnyJjwreNbA7rD3s0M5q5r4JgQ/LskDUxhDV9Kzw3dOU49Rq3/zkG8BOJHa4AfxFwmDe19Fw4Nuk4be4bsIKg@Skq9c4JEd7M3DoaMzj/IEyZLdfptDgYEYwsWn8x6@9dxl1OX3y4rg@nlPsABd4efasV@BzCrWjg32M9W8zeEFMr9e6DHklz7g0MyiB8ICJTlE0yoDNs2GtWCm5HdYgI4JVBg1BIcA11aO1uf/MKyzm9joED8mMkjQTUcR9HAD2eQvSdgELRARIOntHle4@WpLBfPsKt0@@Acvf3R@jARv2VQ0ImIh6I@C5xWAL3yhEQ1o@Je9fGxQezvnethN2QQP8yy4OlxJoQ1Dn7BPxwnlRMnoMl4diCJQefklwCg26o3MNq@DOJHKwsyQkF1YRLPjSwNULVqDd4ywYHNbNfx3OdnVjg8Kq/OV4aMXr/0NpZb5zhJBFcSbpBBAxp8pnCAqshOIOPimWvy6WbaUe@HtN4lkJZHsjuOrzy7/si8wQOY/YIayLH7hbuQTH22yIv/XHuob2x36fjhK1tyQC@b@tAWP46hLfQ8cwbTmhpt/ivb1PTALsSPJc8cdkys0NnUWVo/PEoAuguKCtiK3gYZP3XcgJ//Dgz6YMiovYVCSjjjBibWxnE21BmQ9lzocj1Zdyj9HEvs4@zr8m55@XrI6Phhkd5dQo6a6KKV@wo1oZrUkaV@Yds@Tl2nN9ca@U/cJm11Q@j9j8TSjzVkz3MHed8tnWsn8LzU3OF20J8oDf8aMiLxw4Etc77AkgFOUkgDeh8GJRK8Pk7ML3A58dOtP@X3nzP7y06IhoyOH@wCL5w4w4zQAgGgVpB8wC0YIlcgLJ6Dc1xBxXFybbPJoxd/HjL02kMB/GRHUrtAkEeG9AZYXx3yRdHcHTB9dePVSqZK7wRvqxvRdG6JhySkIUQ8eLI28JTg2FjiGDn7XrD3OvtneekXuPlT9tnkx6POjsQPRHcFgYBSgICFwwstSmzcfmDpvuAcLjBeboPaKpYvHRKvj3iJvX5JnrUHqIrVk6d7AY416K2Go8Jq3AYJdnCY8yvNBmW@dGHI6PjBymDiCGde2JcOSPmQyw4dGxIkQ74ctPqufyML/39vs0voqxvsbRUk@koTasQxQrB40JFE@gJT@wX/KvpHpbjH/sml8w83GbGPPTQnDZylFdwgVCBPr719A/sPSDXg2oY6fe/Fv/IP1tlgMsd/t0NGH78kNtUJAJEjz0DW3SqwEPzIsdFWEcuK@qjDTcEP37u/xW3s/Q8qsbK9EB38ydeKqtYCOhSZPvgF@KZje72wZjh6f@V0@@312Me3BfCzmBkFCGf8lsVlK3AXlFAOjsPhzIR0Kl6TZf91hSU/y8Ifh4x1/IIkVugfUwD4xQXPVBaqUGxwmxncUuc49/HLrTE7uT3vbPVL7O3TmcMADq20AaguCfpYAnge8ksAJQSu29muI89nR8@MEX@7vPlH63jK1ngFfqSWmCCo3bWDyRaz54gKhVHHUzmK9WvS/rado/c/2BoHw2Y3Cv4UOUZeGqgHqFgHdy7LVPNWO/nQ@sfc@x9lJoZP5FIAIvilP9TP6As3ik2v0XdQcu1h7Mvo/Q/On@KEPBcc7GgN6i7HUXSYwKVaxAHnooAfv/eEe@Gf7x4@Piyj84@EX0iNnwTvWueTynKaq@aE3IcfgVVrn@6fX/7clfLcI3nmQIZZc7bFXaB5Pzdun8EaKBHh5uTJPnJmOWrTfy7c7eObXXkHgDRkED@KOWiIzY1Pn9eGmGFhmBNPVErvXWydMeSHc1s9NxM/lqoL@7jg1Rxn5wZm2zzoXFVFcVQA73GOeQ4iJirinRUEhgzf@@uklaQZaoEJl6g4OtGLyBEg2RvvOpNLPV/LKLl3mo2yzU9n4sekwUAXcDM8vc0CrFJxl4eVDFtBDjA48WxCfi2fjI6yfHplX6cdP8Dy4fC9jnKZQQZ@OvEI7AWjPJ5JHTcc@1X2dt2xF/sy@vpHATv2lW1StjlSA65PC/6u2MSZG/RRJjir@E3e1/sj/gPbpj6e4@QqcBbfYMzkAI0LewbBwL0ym8SRO2F9HLW2pJ8c9jHiR@HTUS4jXU@UxnWHxlpiUayjFjbIkzo8fnmyFmVDRtkfrXFsBIqAzMSGuimN099K/GBhY@ByfbT28qW8TvYw3zy6yahrn39ZvXlCkHILQ62NehOYg1lgLbMKh@M2vHfoLsQPZ6BOGAMpIBLMbOQkm012R5BUyLwmwuXEj9DonVt9jeS5PBXfGTKIHwW8UuDhEFQ5COcWC2o6zoEr9MxGACqT7Ry/rYR73j9H6uPbZDgNBwB4Tl1RGSPc0sxtTeacCSQkqsy64aNbvTP2sk8r92VM2zrMeo2FHZwZeDNnUMLe6pp4mMmvPfp@E/65cUhG739MDvgLBEW6XiMHiY18bE7RssvLUePC2P@lg@nxm38yfLdRYzIrl4r0RMNWK7t@sCjqFZQMGqA6k2klzTWUn@5sdsndUYeMlX9oHhnGBOYw3LiNCgQFDE7cUILGAfAN/GOnh/31W12v8uqQ0ce3bEk5j2Cfdb8Q0LmwB5s4HJtJAzTXn8Qz@fPp0cd9BeqwnYP4sZg@0@OwZEEZqyyMmSOKh95t67NCUBJyywt91Wo/cQ8ZxI/ATUTcBbWKxokgUbH/B3zMqMAKx491AvkVL77ve0qgUx98iW8@GTLW@QuSEooeTvbBvWYDnU6a2kUWZRE/EdbC2ud/fzvGtHd8yCB@ZM29NXaznWPnsBYu94KZeQ4hFRuJ1mjG7Vdk/b@vKwKXLpweMnr/NBq3PqmCocNdcBfdUGsaC5ZeFxA7S9cXz93e8Z7o2M45sfWDUu46XQrbceB0FqzUVUROC7BLa4lsN6NUDcsaL2e3tYsCujtkdPxwhet3cHilMlcmGsvSubJOhG25oKZn/J14urr4utCitrXPRPxICzcAA3wh2oSc3XNDS9BHaIaNs8iaptfql16xafGmV7dnNxmt50qDp5NNTwu8HiVA5IaBZkvbrdsPwAPV16U@hzpp1770MGQQP3Bh5jR2cLiCg@xUVlhTHN3OFrHcB46CM5P7W@mxn@cy8UN7z4Y6Q3xiT6lyYsLMZJQ2K9qCFgJP37@/w0WDL9wVdXQPVh4yOn4gt3CvcYIgwFXj1rRjTVNRiwBEGmevo1b/njXld1cOc5is1zkhvIjRmrmw0Wcnlr3Pmjkrj4bcSHedfnp9TJN25Cdq9Ndzx4@FG01L907D7VWwmUhQLdxTNJHdVTarBaEHQdcJVdyTF4cM4kdQSAaW/SMXZo7VoOJpyhzfoKoFCWHkoFgUj5C01650/uDswV1cXyHpW4Ea4D6zwiywaO7biaZvJ3Iakf3ayzm2LbDiz90hg/iRFB63NMXcyilU7qrgywSFoMo1g8rrirWDAzf78us/D@mU@OEywNJwUcJy/cOURHINBdjcU77hggnnQL@CyX0K//zg4ldstI05UO79jzhxise5R1n02mQHvXXcKAns1heAmfWHcuXFvgDyxZBB/FiZMHffoABOx6FY6ztn5csBE2fiSq/9oL85F/@ie6k8NmT09XULHGsNvxW44tl32OEQoBIB52jeeNhqzPePPVsBpC8rDBl9/YPtOFfZavW5Ozegkb3uiassqsxccV66jN87Fv/wVv8jEz8M0atYRUHEda5GqcCRn/ONnVEmcyQ7oQ8Wvx4c3ZWPhozOP9xUVqdStQB0NJRoLPwj@r4YM/du26G@g139Y8w9cut9OiSUhntBC6asWz2WgdentjGBnZTCPj/7dOrsHtdgORPf7kL88DO3RNjX0wGcx0Ru@HIpQC@A9Bx7EwRXE3flSYByhIDTl6jYI2Obv9sF6doh0A8toi4KCbZvLCrNYQb3uMW@Nq72o9weMqbO@eEBzXCkPvXV7L73ijznSdoRcxon4swTPvGHfPgZ20LvnJXbfK70/Y8ZxWiGUlnqgM1wh8TFviXMfbiZ0wul919dKbduyKtnT1zb@lLF9P4YQCf39ZG@nUieEGpnd/APN2cwokWvdlHA1Kv/gnv8Irc5cunrpz1JKwRNqkj@WnPeQFirGtR0YjtEmZ5v1ZgTXJc34Wgj35b@@gvSLuILdlk0t77YUtEJrCMpFpwsM/Pc12Dloz2mlpP35KFXV0rf/wjguAu7JNEXvk3EjDdzmU8HMgBoq6tYHO8Tgr6f@OzA10vvf3hcthC9Jk76PQcdtmW@XFT5ilDhuyRcxV/IjtPdN1fX8naTsa6PTWTYqF907C9okK4m3KByV8E5x0Q8Dc6/syM/4usF3IIfMvr81iK0EuvKkImF6wo8yo6oy7L@q2ZVIeQDeeFVX4Fn1L2/yejrY6ubwwagpixGwUqjq10zC/vU3dv6bO34TXlqEMz7y@AwJfe79FElHEJHMP3J8jWLwtVivvQVLHzGsdXLu9zasRuj@3k7B/HDkVIrFKdcYQWxKwCMwLeaHOcYC5fQgbHItz/w/YhZ7r5wvxzWKfHDcxVfcdIDd4Em3bT1cWdcI06QVpHNhEgDP3aY/t2@jNZrZHqWSZyGtd5O4msWOBHScX87AiSVvUwht8XCWZ7@7JQ8P2T0/ilZB5yKLQcU24HL3wtMCpEowBcLQoUaefQ/Lsh/zoE2fHhQI9d1/wPG9AoRMQcOwVkCRB8r6RmoOopxAR5D26pbx2VuwzDb@mklfqSEa1TNw1Q2TWacI3Ji0t9NCp4vtthDeHqO/dd/9vG0Ej@cmsJY6dUFzKVyA3Zh67S99V6R@G6NWvlwtMeHjM4/2BD7/3ivSPznzaaBH7Xvf8z/14tVBy9Pif@82bSdg/jxf79YdfDylPjPm02bjI4fh16sAq2cmGU7rC0L9TyxNEt8zeLYxbdfShwywsFrjXyJkFBqSZYtW3@snQ7/4RuRF69@Ls/fkv8P "Bash – Try It Online")
[Answer]
# [PHP](http://www.php.net/) (>=5.4), ~~199~~ 197 bytes
(-2 bytes by more golfing)
```
<?$s=strlen(file_get_contents($argv[1])).'';echo strtr([waning_crescent,waning_gibbous,new_moon,0,waxing_crescent,waxing_gibbous,full_moon,first_quarter,third_quarter][($s[0]+$s[3])%11-2],'_',' ');
```
To run it:
```
php -d error_reporting=0 -d short_open_tag=1 <filename> <image_path>
```
Example:
```
php -d error_reporting=0 -d short_open_tag=1 lunar_phase.php https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Moon_phase_6.svg/240px-Moon_phase_6.svg.png
```
**Notes:**
* The `-d error_reporting=0` option is used to not output notices/warnings.
* The `-d short_open_tag=1` is required to allow short tags.
* If you are using a `https` URL like the example above, [OpenSSL](http://php.net/manual/en/book.openssl.php) should also be enabled.
---
# How?
Gets file size (bytes) and creates a unique number for it by this formula:
`((<first_bytes_digit> + <fourth_bytes_digit>) % 11) - 2`
This formula generates numbers from 0 to 8 with only a 3 missing.
```
┌─────────────────┬───────┬─────────┬─────┬────────────────────────┐
│ Phase │ Bytes │ 1st+4th │ %11 │ -2 (position in array) │
├─────────────────┼───────┼─────────┼─────┼────────────────────────┤
│ new moon │ 3451 │ 3+1=4 │ 4 │ 2 │
│ waxing crescent │ 6430 │ 6+0=6 │ 6 │ 4 │
│ first quarter │ 5144 │ 5+4=9 │ 9 │ 7 │
│ waxing gibbous │ 7070 │ 7+0=7 │ 7 │ 5 │
│ full moon │ 5283 │ 5+3=8 │ 8 │ 6 │
│ waning gibbous │ 7067 │ 7+7=14 │ 3 │ 1 │
│ third quarter │ 4976 │ 4+6=10 │ 10 │ 8 │
│ waning crescent │ 6337 │ 6+7=13 │ 2 │ 0 │
└─────────────────┴───────┴─────────┴─────┴────────────────────────┘
```
---
# Previous approaches:
### [PHP](http://www.php.net/) (>=5.4), 251 bytes
```
<?foreach([4,8,16,20]as$w){$a+=imagecolorat(imagecreatefrompng($argv[1]),$w*10,120)>1e7;$a&&$w<5?$b=-2:0;}$x=explode('_','full moon_waning gibbous_third quarter_waning crescent_new moon_waxing crescent_first quarter_waxing gibbous');echo$x[$a*++$b+4];
```
To run it:
```
php -d error_reporting=0 -d short_open_tag=1 <filename> <image_path>
```
Example:
```
php -d error_reporting=0 -d short_open_tag=1 lunar_phase.php https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Moon_phase_6.svg/240px-Moon_phase_6.svg.png
```
**Notes:**
* The `-d error_reporting=0` option is used to not output notices/warnings.
* The `-d short_open_tag=1` is required to allow short tags.
* PHP must have [GD](http://php.net/manual/en/book.image.php) and it should be enabled.
* If you are using a `https` URL like the example above, [OpenSSL](http://php.net/manual/en/book.openssl.php) should also be enabled.
---
### How?
Checks for the color of 4 pixels in the image at `40,120`, `80,120`, `160,120` and `200,120` and decides on the moon phase from those colors.
] |
[Question]
[
# Challenge
The task is simple. Given an array and a first and last value: Return the first of the last after the first, and the last of the first before the last.
---
Or simply: Given an array, var1, var2.
Example Array:
[ var2, , var1, , var2, , var2, var1, var2, ]
Return:
* The index of the first var2 on the right side of the first var1 that appears in the array.
[ var2, , *first var1*, , **first var2**, , second var2, var1, third var2, ]
* The index of the first var1 on the left side of the last var2 that appears in the array.
[ var2, , second var1, , var2, , var2, **first var1**,*last var2*, ]
# Input
Two distinct positive integers
Array of positive integers
# Output
Index of answers, in order
# Rules
The array will contain at least one of each variable (minimum size of 2)
Assume inputs work
>
> Example: `0, 1 [1, 0]` or similar would fail
>
>
>
[IO is flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
# Examples
```
Input
First = 2; Last = 4; [0, 2, 4, 2, 3, 1, 4, 0, 1, 2, 4, 9]
Output
2, 9
```
---
```
Input
First = 4; Last = 2; [0, 2, 4, 2, 3, 1, 4, 0, 1, 2, 4, 9]
Output
3, 6
```
---
```
Input
First = 0; Last = 1; [0, 1]
Output
1, 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
def f(x,y,a):i=a.index;j=a[::-1].index;print i(y,i(x)),len(a)+~j(x,j(y))
```
[Try it online!](https://tio.run/##jYsxDoMwEAT7vOLKO3GJMKGJES9BLixhi7MigyIKu8nXHYLzgDSr2dXslvdljV0ps/PgMXFmS1pGe5M4uzSE0U5aX5X59e0lcQfBzIKJiJ8uoqXmHY5rwExUPHYMPcPUMlQ68s6gTm5PqPvD0MVjFf616/K1laHyAQ "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~29~~ 27 bytes
```
⊃{(⊃⍵~⍳⊃⍺),⊃⌽⍺∩⍳⊃⌽⍵}/⍸¨⎕=⊂⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/4/6mqu1gASj3q31j3q3Qxm7dLUAdE9e4HMRx0rocIg7tZa/Ue9Ow6tABpi@6irCUj9B5ryP02By0DBSMEEiI0VDIG0AZAE8S25gCQXVxpOaaAYRNoQhAE "APL (Dyalog Classic) – Try It Online")
prompts for the array and then for var1,var2
[Answer]
# JavaScript (ES6), 63 bytes
```
(x,y,a)=>a.map(P=(v,i)=>v-y?v-x?0:a=i:1/(p=a)?P=+P||i:0)&&[P,p]
```
[Try it online!](https://tio.run/##jYzBDoIwEETvfkVPpI0LFDUmkFR@oXfCYYNgapA2YhpI@Pda6EkPxj1sZnZn3h0tjs1TmVc86GvrOuHoBDMgExdMHmioFNSC8tbGc2njqeQFClVkKTUCWSnFXi6LKjiLokqCqV2jh1H3bdLrG@3oAcgJSMWBBOX3EUi2ab6JcM9rxkiari7ffSJC63@Ef56/ECG2IrI19Hs8woe5ewM "JavaScript (Node.js) – Try It Online")
### Commented
```
(x, y, a) => // given the two integers x, y and the array a[]
a.map(P = // initialize P to a non-numeric value
(v, i) => // for each value v at position i in a[]:
v - y ? // if v is not equal to y:
v - x ? // if v is not equal to x:
0 // do nothing
: // else (v = x):
a = i // save the current position in a
: // else (v = y):
1 / (p = a) ? // update p to a (last position of x); if p is numeric (>= 0):
P = +P || i // unless P is also already numeric, update it to i
// (if P is numeric, it's necessarily greater than 0 because
// we've also seen x before; that's why +P works)
: // else:
0 // do nothing
) // end of map()
&& [P, p] // return [P, p]
```
### Alternate versions
Using JS built-ins, a more straightforward answer is 79 bytes:
```
(x,y,a)=>[a.indexOf(y,a.indexOf(x)),a.slice(0,a.lastIndexOf(y)).lastIndexOf(x)]
```
which can be slightly compressed to 75 bytes:
```
(x,y,a)=>[a.indexOf(y,a.indexOf(x)),a.slice(0,a[L='lastIndexOf'](y))[L](x)]
```
[Try it online!](https://tio.run/##jYzBCsIwEETvfkVuzcLapipCD/UuFPyAkENoU6mEREyR9uvjtgFBD@IelpnZ2XfTTx3ax3Aft853JvZ15BPOqKE@SZ0PrjPTpecUvPUEQC7YoTVcoJZNnVkdxnM6Z4rPALJR1FOx9S54a3Lrr7znO2QHZFIgS4r2Hlm5arGKlFcKgBXF4qrNJyJ9/Y@g4/ELkWoLolxKv4cQVBbxBQ "JavaScript (Node.js) – Try It Online")
**Edit**: [@Neil](https://codegolf.stackexchange.com/users/17602/neil) managed to reduce it to a very nice **67-byte**:
```
(x,y,a,f=s=>a[z=y,y=x,x=z,s+=`ndexOf`](x,a[s](y)))=>[f`i`,f`lastI`]
```
[Try it online!](https://tio.run/##jYzBDsIgDIbvPgVHiNVtakx26O6efABCAtmGmSHDyGJgL49snPRg7KH523797uqlXPscHtNutF0fNUbqIYACjQ4bxWcMENCDxxncFuXY9f6qpUiU4k7QwBjDhms5SNDSKDddpIitHZ01/d7YG9X0AOQEhJdAckr9CKRac7mGvK8FY6QolqnefCry1/@KdDx/KTK2KKoF@l1JkeAyvgE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
ẹⱮṚ>Ƈ<Ƈƭ"1,0ị"$⁺Ʋ
```
[Try it online!](https://tio.run/##y0rNyan8///hrp2PNq57uHOW3bF2m2Ptx9YqGeoYPNzdraTyqHHXsU3///@PNtBRMNJRMAGTxjoKhmC2AZgBEbeM/R8Nko4FAA "Jelly – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~97~~ 93 bytes
-4 bytes thanks to ovs
```
def h(f,l,a,I=list.index):j=I(a,f);i=len(a)+~I(a[::-1],l);print(I(a[j:],l)+j,i-I(a[i::-1],f))
```
[Try it online!](https://tio.run/##nY2xCoMwEIZ3n@I2c3gWTbM0YseC0DcQh4ARIyEVdWiXvrrVCA7tUswQ/nz5777@NbUPd57nWjfQsoYsKSpya8bpZFytnyi7vGCKGsxMbrVjCqP3Akop47Qii1k/GDexFXVyBVFHJl6fZqs0iPPWCW9mGCeQwDO4K59EBmVCwAmEv88Eqc@JDxu/VBBfQ9KuzkMIMWgZJ0H/zGHwZRa7mR8zC@LHzMluTr05/Vm9MPIfOC/nAw "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~27~~ ~~25~~ 24 bytes
*Inspired in [@Arnauld answer](https://codegolf.stackexchange.com/a/167870/78039)*
*Thanks @Shaggy -2 bytes and @ETHproductions -1 byte*
I just started with japt so it must be a better way.\
```
[WsX=WbU)bV +XWsTWaV)aU]
```
[Try it online!](https://tio.run/##y0osKPn/Pzq8OMI2PClUMylMQTsivDgkPDFMMzE09v9/Ex0jHYVoAx0FIGUCJo11FAzBbAMwAyJuGQsA "Japt – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 42 [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 infix function. Takes var1,var2 as left argument and the array as right argument.
```
{⍸<\(⍵=⊃⌽⍺)∧∨\⍵=⊃⍺},{⍸⌽<\(⍵=⊃⍺)∧∨\⍵=⊃⌽⍺}∘⌽
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9e6widF41LvV9lFX86OevY96d2k@6lj@qGNFDEywd1etDkgdUBZJKaY6sObaRx0zgKz/aUDjH/X2QWzqaj603vhR20QgLzjIGUiGeHgG/zdSMFFIUzDQUTDSUTABk8Y6CoZgtgGYARG35DJRMCJOoYGCIUShIQA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 81 bytes
```
function(a,b,v,x=which(v==b),y=which(v==a))c(x[x>y[1]][1],tail(y[y<tail(x,1)],1))
```
[Try it online!](https://tio.run/##nZDBasMwDIbvfQpBLjaoJd7GoGXZYbde9gIhB8dxlsCIiy23ztNnwmbrYbDDBDK/5f//BPbb2GxjXAzNbhEae7xiam7TbCZxbZpe4nq/aSmNSG16XVvVddxIev4Ua7u@ZJFQyY5bbhW8H94OJ6DJwjcdvKXol5CH8zLYBGrf62AH2FVQKjg4Q4g9eW0IFJDLbhfpEolD4PxgPY9/Eh@WssWmizXErOINu1E8IDwhGFEjFMnnI4LKus6izI9Swp63AVR3Dj8dGVJi/4Ww85khxZch/Dvwd/2CcLTevgA "R – Try It Online")
(1-indexed)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 27 bytes
```
y=Y>/ti=PY>P/t3G=f1)w2G=f0)
```
[Try it online!](https://tio.run/##y00syfn/v9I20k6/JNM2INIuQL/E2N02zVCz3AhIGWj@/x9toKNgpKNgAiaNdRQMwWwDMAMibhnLZcRlAgA "MATL – Try It Online")
Alternately for the same bytecount:
### 27 bytes
```
y=Y>yi=*f1)y3G=PY>Pb2G=*f0)
```
[Try it online!](https://tio.run/##y00syfn/v9I20q4y01YrzVCz0tjdNiDSLiDJyB3IN9D8/z/aQEfBSEfBBEwa6ygYgtkGYAZE3DKWy4jLBAA "MATL – Try It Online")
The second one is easier to explain:
```
y % implicitly get the first two inputs (the array and var1),
% and duplicate the first input
% stack: [[0 2 4 2 3 1 4 0 1 2 4 9] 2 [0 2 4 2 3 1 4 0 1 2 4 9]]
= % compare and return logical (boolean) array
% stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 1 0 1 0 0 0 0 0 1 0 0]]
Y> % cumulative maximum - make all values after the first 1 also 1s
% stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 1 1 1 1 1 1 1 1 1 1 1]]
% now we have 1s in positions at and after the first time var1 appears
y % duplicate 2nd element in stack
% stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 1 1 1 1 1 1 1 1 1 1 1] [0 2 4 2 3 1 4 0 1 2 4 9]]
i= % compare with the next input (var2), returning a boolean array
% stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 1 1 1 1 1 1 1 1 1 1 1] [0 0 1 0 0 0 1 0 0 0 1 0]]
* % multiply the two boolean arrays - so we'll have 1s only where var2 was present after the first occurrence of var1
% stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 0 1 0 0 0 1 0 0 0 1 0]]
f1) % find the index of the first 1 in that (this is our first result value)
```
The second part of the code does the same thing, except for these changes:
* use `2G` for second input (var1) and `3G` first 3rd input (var2) instead of implicit input or `i`, since those have been consumed
* use `PY>P` (flip array left-to-right, get cumulative maximum, flip back) instead of `Y>`, to get 1s *before the last occurrence* instead of after the first occurrence
* use `f0)` to get *last* place where both conditions are true, instead of first place (works because MATL uses modular indexing, so 0 is taken to refer to the last index of the array)
[Answer]
## MATLAB (80 bytes)
Input is `x`, `y`, and `a`. Since MATLAB is 1-indexed, you should add 1 to test cases.
```
xi=find(a==x);
yi=find(a==y);
yi(find(yi>xi(1),1))
xi(find(xi<yi(end),1,'last'))
```
Test case:
```
x=4
y=2
a = [0, 2, 4, 2, 3, 1, 4, 0, 1, 2, 4, 9]
%
xi=find(a==x);
yi=find(a==y);
yi(find(yi>xi(1),1))
xi(find(xi<yi(end),1,'last'))
ans =
4
ans =
7
```
[Answer]
# Java 8, 114 bytes
A lambda taking a `java.util.List<Integer>` and two `int`s (var1, var2) and returning a comma-separated pair.
```
(a,f,l)->a.indexOf(f)+a.subList(a.indexOf(f),a.size()).indexOf(l)+","+a.subList(0,a.lastIndexOf(l)).lastIndexOf(f)
```
[Try It Online](https://tio.run/##ZVHLbsIwEDyHr1hxsoWJQttLy6PqpRJSqx7ghqLKJDYyNU5kOxQa5dup7UBK20u8nszOjme3dE@HRcnUNv84ldVaigwySY2BVyoU1L3oDBpLrTuEskxzmjFYFPK5UtlkOfOsC21htVAboGUpj2jrxOPKChm/CGMnj8AOlqncgOuRDiGwBC50W7ihFo97UdP7O5MLRWU3b@4cbJieAYfpCVHCicTDGY2FytnhjSOOBzQ21dqPRNcwcbD4YgjjDpR40Cf9K37iSN7IvCPgX3eOT9H4n8F9IXLYubxQ@/xVClRvDA7B/Amhs@8DgCn8/H7Smh5NTE1wotgnnLlOrk4I3BC4C99bAqNQJ6Fo8fvGhxe5/axS17Cn0jh1r3KB6tozGwK1l2kaT@eFBhQIoeMdHsLZOo8WR2PZLi4qG5fuXVYqxON2te36Qs8qSS/VKMXBRePX2Jy@AQ)
[Answer]
# [Kotlin](https://kotlinlang.org), 132 bytes
```
{f:Int,l:Int,a:Array<Int>->{var p=a.indexOfFirst{it==f}
while(a[p]!=l)p++
var i=a.indexOfLast{it==l}
while(a[i]!=f)i--
Pair(p,i)}()}
```
[Try it online!](https://tio.run/##nVbbbttGEH3nV4yFoCAThbKcIG2UKEDaJoUBAy7SAHkw/LAiV9bCvHV3Gdk19O3pmVleJMdJL4JBk7tznzNn97r2ham@zB7TL1Yrr3Na15b8xjjK6lzTVV2sKduootDVlV5EG@8bt5jNeJP3UudVdq1vIIL9NKvL2Z@tdt7UlZvNX/z404tn0Xtjnacz1T/kO/qlNxpFHzeavHLXBK/OlE2hU/rNfNYVKfxZq27xkpOitVji94INfVZFqxf0QfvWVghadwL1Wj5ERq29tuPeVLSH3U4yqK00ctfDZhpF5zbEc7u4F88Uvu1cnieQCxEsoojw42xMleubQ@velFrkSTWNVtaRKUudGxS9uEXVi6LemurqAY35qBGylBDSf@Vt/qC3e5k@FNuhp9OqaT0ata0pN@hulXlqamc8qgJZr6@0dVH0VnqFQL7eO2@9mDjtY1WV22Jjyq5qm2sbfWgL7QIaQtO3pigAw8oryChPhZaeVZr1tco2HLNRq0JTXJrKlG2Jfv0l2ycJwnGuLTkGeHa0re11qNm7G8UgW9DxlOZ0gT4eXyIG7rUplIVkW2AQlCkQ7zmjcl3oGwM/Uafq@pIEbC/p5FXA9pKev6IL2D2Z0nN5PoMPeT@Wl7D@8jLqK4KFl/etPR@snfxHa9h/cd/a8WBtHqzNR3nOPXo8i6LZjH5VXlEGQLhAAhhjypTTLo3ycesjlmNMXgDagk4rz3NQCJLCJxdZVgyvCCheY/1NIm7e3TSYQWaaFjACUZCvqbF1pmFdjW7TCAL9RrzvbfQUgHLgYyEt/l0Z@1okeJHuuPHw/d500//AyATMIpywGhTClhCNMEdZA9SozlZZkFBdX/PIBsrsNEZmGi0iQSsUkUZcGTvuLLsRk3jO16Fld8Yvl@J5B/ntxjDARe6iV7yko6W4SgZbT558N0mJ68Ec9yIeUlyB1b@d435Vvp1kcH8vQ0GiJMhuv8pPpCQ58ZEEI0@fdql9VNeIrfabwa0LMfO6ogZd71IrEU/QGYMKb4KNuNefBg9JtGPZDm2CUwY65RYsZknfNDoDh3gQIM5L7diL8EoqDCzBstLWILYRU4dHleMaOfArmAv1TMULZJ0GyeWjbmC/QTa44BOXFZSQGkxtwIgsHWLDPDXK46xDRYQ3V4zTtspZJzYpjtQxrKotV8iqbOXUC3J7h0LUgyLIvRrx86CiHLGsc99BmtAn3bG48tmmCzfTDVc@aCAJEaizrLVSr9aFkynXa9UWXggB9RZ55uSWg6xJV3ywZ7W1yJ6YoAJhlDgsAKYr17PCH94CwG@SgQTOVLnK1QH9rHlkrHbwF9BbUENL9jh/dkKrW8Tw5W69YEIp5KkWI@U8fXMnM71UB2McpngXCb5jddFcHi2LpMGYynCM0jwSYSJGYQPhdWIA/IDWqUl2cbL7Igl80CoMuNAy16ynTyPhe3uLZKlj4dALh0HEDS8/A3rj5OgodU1hfDyhSZKWqunk@QcbvkZecCdrZk1xZyOV0xXDidM1CPuNrbd0ipvclSre2itAs/Lv@hbHg1GiySdbg0c6BGF8OPijSTLEGVD/f6Ns0GRfVPHkbI@wHt11gV8cX@7oB5o8GfQn494ce7hgPAo81UXU22vi0cSURpXpYGkEQuAwKdKU7jpC85e7JEk66J1XI/6nAC/uEnK36WB/AHnu5K4bnFhbW9sFiADl5gtP0pViSPtnQEIIaQpLnP@Brf06h3nqaPl8HcuBHi4S/VJ/4xhy/ObNI0mm4UYg15NB/r6h7xoYtMRQ2N0zMOfy8TZ3NJbrAd9OOYsBhQPgvwMF1kjDqXoIhQ4Osi@HkqCh@8YVBkA7wz8grQfHIUBGw1MajPSvUEx6pX/s5kH0pxW6ZXJGycpUiiFzNBlNMXva22jvVV6Y/r78DQ "Kotlin – Try It Online")
[Answer]
# [Julia](https://docs.julialang.org), ~~71~~ 64 bytes
thanks to sundar and his `find(A.==x)[]` instead of `findfirst(A,x))`.
.
```
(A,x,y)->findnext(A,y,find(A.==x)[]),findprev(A,x,findlast(A,y))
```
] |
[Question]
[
Given a square matrix, output the matrix's eigenvalues. Each eigenvalue should be repeated a number of times equal to its algebraic multiplicity.
The eigenvalues of a matrix `A` are scalar values `λ` such that, for some column vector `v`, `A*v = λ*v`. They are also the solutions to the characteristic polynomial of `A`: `det(A - λ*I) = 0` (where `I` is the identity matrix with the same dimensions as `A`).
Outputs must be accurate to 3 significant digits. All inputs and outputs will be within the representable range of numerical values for your chosen language.
Builtins are acceptable, but you are encouraged to include solutions that do not use builtins.
## Test Cases
In these test cases, `I` represents the imaginary unit. Complex numbers are written in the form `a + b*I`. All outputs have 3 significant digits of precision.
```
[[42.0]] -> [42.0]
[[1.0, 0.0], [0.0, 1.0]] -> [1.00, 1.00]
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] -> [16.1, -1.12, -1.24e-15]
[[1.2, 3.4, 5.6, 7.8], [6.3, 0.9, -5.4, -2.3], [-12.0, -9.7, 7.3, 5.9], [-2.5, 7.9, 5.3, 4.4]] -> [7.20 + 5.54*I, 7.20 - 5.54*I, -4.35, 3.75]
[[-3.22 - 9.07*I, 0.193 + 9.11*I, 5.59 + 1.33*I, -3.0 - 6.51*I, -3.73 - 6.42*I], [8.49 - 3.46*I, -1.12 + 6.39*I, -8.25 - 0.455*I, 9.37 - 6.43*I, -6.82 + 8.34*I], [-5.26 + 8.07*I, -6.68 + 3.72*I, -3.21 - 5.63*I, 9.31 + 3.86*I, 4.11 - 8.82*I], [-1.24 + 9.04*I, 8.87 - 0.0352*I, 8.35 + 4.5*I, -9.62 - 2.21*I, 1.76 - 5.72*I], [7.0 - 4.79*I, 9.3 - 2.31*I, -2.41 - 7.3*I, -7.77 - 6.85*I, -9.32 + 2.71*I]] -> [5.18 + 16.7*I, -24.9 - 2.01*I, -5.59 - 13.8*I, 0.0438 - 10.6*I, -1.26 + 1.82*I]
[[-30.6 - 73.3*I, 1.03 - 15.6*I, -83.4 + 72.5*I, 24.1 + 69.6*I, 52.3 + 2.68*I, 23.8 + 98.0*I, 96.8 + 49.7*I, -26.2 - 5.87*I, -52.4 + 98.2*I, 78.1 + 6.69*I], [-59.7 - 66.9*I, -26.3 + 65.0*I, 5.71 + 4.75*I, 91.9 + 82.5*I, -94.6 + 51.8*I, 61.7 + 82.3*I, 54.8 - 27.8*I, 45.7 + 59.2*I, -28.3 + 78.1*I, -59.9 - 54.5*I], [-36.0 + 22.9*I, -51.7 + 10.8*I, -46.6 - 88.0*I, -52.8 - 32.0*I, -75.7 - 23.4*I, 96.2 - 71.2*I, -15.3 - 32.7*I, 26.9 + 6.31*I, -59.2 + 25.8*I, -0.836 - 98.3*I], [-65.2 - 90.6*I, 65.6 - 24.1*I, 72.5 + 33.9*I, 1.47 - 93.8*I, -0.143 + 39.0*I, -3.71 - 30.1*I, 60.1 - 42.4*I, 55.6 + 5.65*I, 48.2 - 53.0*I, -3.9 - 33.0*I], [7.04 + 0.0326*I, -12.8 - 50.4*I, 70.1 - 30.3*I, 42.7 - 76.3*I, -3.24 - 64.1*I, 97.3 + 66.8*I, -11.0 + 16.5*I, -40.6 - 90.7*I, 71.5 - 26.2*I, 83.1 - 49.4*I], [-59.5 + 8.08*I, 74.6 + 29.1*I, -65.8 + 26.3*I, -76.7 - 83.2*I, 26.2 + 99.0*I, -54.8 + 33.3*I, 2.79 - 16.6*I, -85.2 - 3.64*I, 98.4 - 12.4*I, -27.6 - 62.3*I], [82.6 - 95.3*I, 55.8 - 73.6*I, -49.9 + 42.1*I, 53.4 + 16.5*I, 80.2 - 43.6*I, -43.3 - 3.9*I, -2.26 - 58.3*I, -19.9 + 98.1*I, 47.2 + 62.4*I, -63.3 - 54.0*I], [-88.7 + 57.7*I, 55.6 + 70.9*I, 84.1 - 52.8*I, 71.3 - 29.8*I, -3.74 - 19.6*I, 29.7 + 1.18*I, -70.6 - 10.5*I, 37.6 + 99.9*I, 87.0 + 19.0*I, -26.1 - 82.0*I], [69.5 - 47.1*I, 11.3 - 59.0*I, -84.3 - 35.1*I, -3.61 - 35.7*I, 88.0 + 88.1*I, -47.5 + 0.956*I, 14.1 + 89.8*I, 51.3 + 0.14*I, -78.5 - 66.5*I, 2.12 - 53.2*I], [0.599 - 71.2*I, 21.7 + 10.8*I, 19.9 - 97.1*I, 20.5 + 37.4*I, 24.7 + 40.6*I, -82.7 - 29.1*I, 77.9 + 12.5*I, 94.1 - 87.4*I, 78.6 - 89.6*I, 82.6 - 69.6*I]] -> [262. - 180.*I, 179. + 117.*I, 10.3 + 214.*I, 102. - 145.*I, -36.5 + 97.7*I, -82.2 + 89.8*I, -241. - 104.*I, -119. - 26.0*I, -140. - 218.*I, -56.0 - 160.*I]
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~576 554 532~~ 507 bytes
No built-ins!
```
import Data.Complex
s=sum
l=length
m=magnitude
i=fromIntegral
(&)=zip
t=zipWith
(x!a)b=x*a+b
a#b=[[s$t(*)x y|y<-foldr(t(:))([]<$b)b]|x<-a]
f a|let c=[1..l a];g(u,d)k|m<-[t(+)a b|(a,b)<-a#u&[[s[d|x==y]|y<-c]|x<-c]]=(m,-s[s[b|(n,b)<-c&a,n==m]|(a,m)<-a#m&c]/i k)=snd<$>scanl g(0<$c<$c,1)c
p?x|let f=foldl1(x!);c=l p-1;n=i c;q p=init$t(*)p$i<$>[c,c-1..];o=f(q p)/f p;a|d<-sqrt$(n-1)*(n*(o^2-f(q$q p)/f p)-o^2)=n/last(o-d:[o+d|m(o-d)<m(o+d)])=last$p?(x-a):[x|m a<1e-9]
z[a,b]=[-b/a]
z p=p?0:z(init$scanl1(p?0!)p)
```
[Try it online!](https://tio.run/##VVFLj5swGLzzK7xaFNkJdjBvEtw9tJceeu4BuSvzyqLltYGobMR/T22crFQJBTKemW@@8ZsY38umud3qdujPE/ghJkG@9@3QlLMxsvHSGg1ryu40vRkta8Wpq6dLURo1q859@7ObytNZNAbcIHatB2NSv79rSYbzk0AZm7dilxniOWNpOpoT3KIZfC6fCa76pjjDCR4QgilPzAxlfJkTLLhRAbE05QRyllJCGiD48QQvVoHelzbB6QR3SIBsgcLKkBQ8XzbSOy2WmbFPrrzz1SnnnMHWwqM8lOxuZecbYXWMtVzJ21XebnK@r8E7YmNXJOa3MRddA07QTsxcPhZFuTG8zGukiqncDZXboWPOGjBgeuxYDfLjBxhYLdtZlxzMWjqluZVjuQI/9qyCkoD2FRiOYikSPH6cJxN2mKIt7Law/@NgSTEfJIQlgli3b8Q4wR4Xh7TfFUurPlEiX7sCccTUqTm8wBkLdEjnpQUioSWOuXFNZT2cpTjby0qvMtzwYh@ucI24rkihRJ7QgG7lLNSFv9bdcJkAA2kKsUscB4HDDkAcEztEFrAJjV2FxIRSC/jEj9U/SlzXAkpg3/kB8SnSUOh@YZ6DuAXSiHixhlziBSuNEqpHBcSNFRARx7/rbOL5vmTFxA2/nNxVFpBIyyLiesoaYp84wR2yQ80JohWQURwdyaF3a58ErnammhEFFvDkbvo4UvbalhLHQ3pz27OkeRQ@0tmu7yAFub6CPOJba2PBozxHDbRkS2HwGBtq35DYGvFIGOsgD4mr@3OI9wgbEr10SMLwq9LIR3qaq6c5JKScG0Yr6k5eYyuGX69gONfdBExQ1ifw30UbAPx9K8/lesLAFRBQ3f4B "Haskell – Try It Online")
Many thanks @ØrjanJohansen for a total of -47 bytes!
### Explanation
First this computes the characteristic polynomial with the [Faddeev–LeVerrier algorithm](https://en.wikipedia.org/wiki/Faddeev%E2%80%93LeVerrier_algorithm) which is the function `f`. Then the function `z` computes all roots of that polynomial by iterating `g` which implements [Laguerre's Method](https://en.wikipedia.org/wiki/Laguerre%27s_method) for finding a root, once a root is found it is removed and `g` gets called again until the polynomial has degree 1 which is trivially solved by `z[a,b]=[-b/a]`.
### Ungolfed
I re-inlined the functions `sum`,`length`,`magnitude`, `fromIntegral`, `zipWith` and `(&)` as well as the little helper `(!)`. The function `faddeevLeVerrier` corresponds to `f`, `roots` to `z` and `g` to `laguerre` respectively.
```
-- Transpose a matrix/list
transpose a = foldr (zipWith(:)) (replicate (length a) []) a
-- Straight forward implementation for matrix-matrix multiplication
(#) :: [[Complex Double]] -> [[Complex Double]] -> [[Complex Double]]
a # b = [[sum $ zipWith (*) x y | y <- transpose b]|x<-a]
-- Faddeev-LeVerrier algorithm
faddeevLeVerrier :: [[Complex Double]] -> [Complex Double]
faddeevLeVerrier a = snd <$> scanl go (zero,1) [1..n]
where n = length a
zero = replicate n (replicate n 0)
trace m = sum [sum [b|(n,b)<-zip [1..n] a,n==m]|(m,a)<-zip [1..n] m]
diag d = [[sum[d|x==y]|y<-[1..n]]|x<-[1..n]]
add as bs = [[x+y | (x,y) <- zip a b] | (b,a) <- zip as bs]
go (u,d) k = (m, -trace (a#m) / fromIntegral k)
where m = add (diag d) (a#u)
-- Compute roots by succesively removing newly computed roots
roots :: [Complex Double] -> [Complex Double]
roots [a,b] = [-b/a]
roots p = root : roots (removeRoot p)
where root = laguerre p 0
removeRoot = init . scanl1 (\a b -> root*a + b)
-- Compute a root of a polynomial p with an initial guess x
laguerre :: [Complex Double] -> Complex Double -> Complex Double
laguerre p x = if magnitude a < 1e-9 then x else laguerre p new_x
where evaluate = foldl1 (\a b -> x*a+b)
order' = length p - 1
order = fromIntegral $ length p - 1
derivative p = init $ zipWith (*) p $ map fromIntegral [order',order'-1..]
g = evaluate (derivative p) / evaluate p
h = (g ** 2 - evaluate (derivative (derivative p)) / evaluate p)
d = sqrt $ (order-1) * (order*h - g**2)
ga = g - d
gb = g + d
s = if magnitude ga < magnitude gb then gb else ga
a = order /s
new_x = x - a
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 4 bytes
```
@eig
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en998hNTP9f5pGdLShnoGOghGIMNYziLVWiDYBsU1BhBlEwBzEtgARlkCBWM3/AA "Octave – Try It Online")
Only two bytes more than the MATL golfing language equivalent!
Defines an anonymous function handle to the `eig` built-in. Interestingly, the MATLAB design philosophy goes against many high-end languages, which like to use `DescripteFunctionNamesTakingArguments()`, whereas MATLAB and consequently Octave tend to get the shortest unambiguous function name possible. For example, to get a **s**ubset of eigenvalues (e.g., the smallest `n` in absolute magnitude), you use `eigs`.
As a bonus, here's a function (works in MATLAB, and in theory could work in Octave but their `solve` is not really up to the task) that doesn't use built-ins, but instead symbolically solves the eigenvalue problem, `det(A-λI)=0`, and converts it to numerical form using `vpa`
```
@(A)vpa(solve(det(A-sym('l')*eye(size(A)))))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Yv
```
[Try it online!](https://tio.run/##NY9JbkMhEESv4rUxJXqABuUkUeRFlpbineXrfxfws3x0UcPz9/V3HN/v4/jJBtU8UOL6uF0KZFgaEJlUUUcSmE2gsOSGKieEkVyvj69Lhw@@eFsngWhqsLGoQ2su8FonDljMb9uxoWvqMJ8muUIbaRfhrfXEFD3jVChodpoIT33FObsypK8izFZn/eLzxNdgdLGqG60mx@rBwU2z0nWSIBrdY3kEZzpinEkU2Z6scMmBXT0Qc0j/dzNNiqDw/gE "MATL – Try It Online")
### Explanation
I followed the usual advice in numerical linear algebra: instead of writing your own function, use a built-in that is specifically designed to avoid numerical instabilities.
Incidentally, it's shorter. ¯\\_(ツ)\_/¯
[Answer]
# Mathematica, 11 bytes
```
Eigenvalues
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zUzPTWvLDGnNLX4f0BRZl6JQ1p0dbWhnoGOghGIMNYzqNVRqDYBsU1BhBlEwBzEtgARlkCB2tj/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 22 bytes
```
function(m)eigen(m)$va
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jVzM1Mz0VRKuUJf5P00jJTEzXMNbU/A8A "R – Try It Online")
Takes `m` as a matrix. Frustratingly, the `eigen` function in R returns an object of class `eigen`, which has two fields: `values`, the eigenvalues, and `vectors`, the eigenvectors.
However, more annoyingly, the optional argument `only.values` returns a `list` with two fields, `values`, containing the eigenvalues, and `vectors`, set to `NULL`, but since `eigen(m,,T)` is also 22 bytes, it's a wash.
[Answer]
# Python + numpy, 33 bytes
```
from numpy.linalg import*
eigvals
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 19 bytes
```
m->mateigen(m,1)[1]
```
[Try it online!](https://tio.run/##BcE7CsAgFATAq2ypsBbmH0JyEbGwULFQRLz/y0wPo5jcJeGFVPPVMGPJsalKq5310kdpUyXlLLEQ64ON2InjwUlcxO21lh8 "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 24 bytes
It seems that someone downvoted every answer that uses a built-in. OK, if you don't like built-in:
```
m->polroots(matdet(x-m))
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9X164gP6coP7@kWCM3sSQltUSjQjdXU/N/QVFmXolGmka0oY6CkY6CsbWCiY6CqY6CmbWCuY6ChY6CZSxQFQA "Pari/GP – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 12 bytes
```
n->eig(n)[1]
```
[Try it online!](https://tio.run/##XY29DsIwDIR3nsJjMthq/muh8iJVBwaKgqoIIXj@cO2EGGzr7j6dH5@tXnPv69T4cqt30@zslv581fbemlnN7GSgAXM@NtRi7ek3J08BaaREGbfQSPrPCBgBIZmKjKCyBPQpcYLNXvYGdh4fWKUACoB1N70kSIUMFCWiuX8B "Julia 0.6 – Try It Online")
Unfortunately, [`eig`](https://docs.julialang.org/en/stable/stdlib/linalg/#Base.LinAlg.eig) returns both the eigenvalues and eigenvectors, as a tuple, so we waste another 9 bytes to lambdify it and grab the first item.
] |
[Question]
[
>
> Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of `0` or `1` for each term:
>
>
> `25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1`
>
>
> The choice of `0` and `1` is... not very binary. We shall perform the *true* binary expansion by expanding with powers of 2, but with a coefficient of `1` or `-1` instead:
>
>
> `25 = 1*16 + 1*8 + 1*4 - 1*2 - 1*1`
>
>
> Now *this* looks binary.
>
>
> Given any positive number, it should be trivial to see that:
>
>
> * Every odd number has infinitely many true binary expansions
> * Every even number has no true binary expansions
>
>
> Hence, for a true binary expansion to be well-defined, we require the expansion to be the *least*, i.e with the shortest length.
>
>
>
---
Given any positive, odd integer `n`, return its true binary expansion, from the most significant digit to the least significant digit (or in reversed order).
### Rules:
* As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), you should aim to do this in the **shortest byte count possible.** Builtins are allowed.
* Any output that can represent and list the coefficients is acceptable: an array, a string of coefficients with separators, etc...
* Standard golfing loopholes apply.
* Your program should work for values within your language's standard integer size.
---
### Test Cases
```
25 -> [1,1,1,-1,-1]
47 -> [1,1,-1,1,1,1]
1 -> [1]
3 -> [1,1]
1234567 -> [1,1,-1,-1,1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,1,1]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 bytes
```
¤é r0J
```
[Try it online!](https://tio.run/##y0osKPn//9CSwysVigy8/v83MQcA "Japt – Try It Online")
## Explanation:
```
¤é r0J // Test input: 25
¤ // Binary the input: 11001
é // Rotate 1 chars to the right: 11100
r0J // Replace 0s with -1: 111-1-1
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~12~~ 11 bytes
```
|R_1.>jQ2 1
```
**[Try it here!](https://pyth.herokuapp.com/?code=%7CR_1.%3EjQ2+1&input=47&debug=0)**
---
# How?
```
|R_1.>jQ2 1 Full program.
jQ2 Convert input to a binary list.
.> 1 Cyclically rotate the list above by 1 place to the right.
|R_1 Substitute 0 with -1.
Implicitly output.
```
First off, we notice that the task is just "substitute the `0`s in the binary writing with `-1`s and shift to the right by 1 place." — That's exactly what we should do! The binary conversion gives us a list of `0`s and `1`s. All we should do here is to find a golfy way to convert `0` to `-1`. The bitwise operator `|` (bitwise OR) is our friend. The map over the binary representation shifted with `|` and `-1`. If the current number is `0`, it gets converted to `-1`.
[Answer]
# [Perl 6](https://perl6.org)
String version, 31 bytes
```
1~(*+>1).base(2).subst(0,-1,:g)
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPvfsE5DS9vOUFMvKbE4VcNIU6@4NKm4RMNAR9dQxypd8781F1dxIkithpGppjWMbWKOYBsimMZIokbGJqZmQGX/AQ "Perl 6 – Try It Online")
List version, 36 bytes
```
{map * *2-1,1,|($_+>1).base(2).comb}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/OjexQEFLQctI11DHUKdGQyVe285QUy8psThVw0hTLzk/N6n2f3EiSLWGkammNReUbWKOYBsimMZIokbGJqZmQGX/AQ "Perl 6 – Try It Online")
[Answer]
## JavaScript (ES6), ~~35~~ 34 bytes
```
f=n=>n?[...f(n>>=1),!n|n%2||-1]:[]
```
### Test snippet
```
let f=n=>n?[...f(n>>=1),!n|n%2||-1]:[];
[25, 47, 1, 3, 1234567].map(x => console.log(x + ":", JSON.stringify(f(x))))
```
[Answer]
# [Perl 6](https://perl6.org), 72 bytes
There is surely a better way, but this is what I have...
```
->$a {grep {$a==[+] @^a.reverse Z+< ^∞},[X] (1,-1)xx $a.base(2).chars}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPtf104lUaE6vSi1QKFaJdHWNlo7VsEhLlGvKLUstag4VSFK20Yh7lHHvFqd6IhYBQ1DHV1DzYoKBZVEvaTE4lQNI0295IzEouLa/9ZcxYkgMzUMDTX/AwA "Perl 6 – Try It Online")
**Explanation**: It's a function that takes one argument (`->$a`). We first get the number of coefficients needed (`$a.base(2).chars` = number of characters in base 2 representation), then make a Cartesian product (`X`) of that many pairs `(1,-1)`. (The `[X]` means: reduce the following list with `X`.) So we get a list of all possible combinations of 1s and -1s. Then we filter (`grep`) only the lists which encode the given number `$a`. There is only one, so we get a list of one list with the coefficients.
The grep block does this: takes its argument as a list (`@^a`), reverses it and zips it with an infinite list `0,1,2,...` using the "left bit shift" operator `+<`. Zipping stops as soon as the shorter list is depleted (good for us!) We then sum all the results and compare it with the given number. We had to use `.reverse` because the OP demands that the coefficients be in the order from most significant to least significant.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Bṙ-o-
```
[Try it online!](https://tio.run/##y0rNyan8/9/p4c6Zuvm6/w@3H530cOeM//8NjYxNTM3MAQ "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes
```
bÁ0®:
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/6XCjwaF1Vv//G5kCAA "05AB1E – Try It Online")
[Answer]
# J, 11 bytes
```
1-~2*_1|.#:
```
[Try it online!](https://tio.run/##y/r/P03BVk/BULfOSCvesEZP2YqLKzU5I18hTcHIFMYyNDI2MTUz//8fAA)
Thanks to @JosiahWinslow for the algorithm.
Any thoughts on making the conversion shorter? My thoughts are to using `!.`-fit (nvm, it just changes the tolerance of the conversion).
Using `{`-take is longer by 1 character.
```
_1 1{~_1|.#:
```
[Answer]
# Java 8, 101 bytes
```
n->{String s=n.toString(n,2);return(s.charAt(s.length()-1)+s.replaceAll(".$","")).replace("0","-1");}
```
Port of [*@Oliver*'s Japt answer](https://codegolf.stackexchange.com/a/141159/52210), with *a few* more bytes.. ;)
Can definitely be golfed by using an mathematical approach instead of this String approach.
**Explanation:**
[Try it here.](https://tio.run/##hY9Ba8MwDIXv/RXC7GCzxixpux5CBz3u0F52HDt4rpe6dZVgK4VS8tszbcmOIyCBpO/B0zuZq8nqxuHpcO5tMCnBzni8zwA8kotfxjrY/6wAbxQ9VmDlK5PKRUBVMui4uRIZ8hb2gLCBHrOX@6hPG9RUD4vEeaHK6KiNKJO2RxO3xENwWNFRqixXj0lH1wT23YYghX4QcyGU@jtK8cSHLBeq7PpysG7az8DW4wfX2h/gwiHk4Pn@AUaNCW6J3EXXLemGEQWUqK3M1W@Qf/ligherCcFyPSHIi8Vy9TyqulnXfwM)
```
n->{ // Method with Integer parameter and String return-type
String s=n.toString(n,2); // Convert the Integer to a binary String
return(s.charAt(s.length()-1) // Get the last character of the binary String
+s.replaceAll(".$","") // + everything except the last character
).replace("0","-1"); // Then replace all zeroes with -1, and return the result
} // End of method
```
[Answer]
# [R](https://www.r-project.org/), ~~90~~ ~~88~~ 46 bytes
```
function(n)c((n%/%2^(0:log2(n))%%2)[-1],1)*2-1
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPM1lDI09VX9UoTsPAKic/3QgopKmqaqQZrWsYq2OoqWWka/g/TcNQkytNwxhEGJmCSBNzzf8A "R – Try It Online")
Implements [Oliver's algorithm](https://codegolf.stackexchange.com/a/141159/67312), but returns the digits in reverse order. Since we are guaranteed that `n` is never even, the least significant bit (the first) is always `1`, so we remove it and append a `1` to the end to simulate rotation in R. Thanks to Shaggy for [getting me to fix my math](https://codegolf.stackexchange.com/questions/141156/the-binary-binary-expansion/141158?noredirect=1#comment346194_141158).
Simply putting `rev( )` around the function calls in the footer should return the values in the same order.
## original answer, 88 bytes:
```
function(n,b=2^(0:log2(n)))(m=t(t(expand.grid(rep(list(c(-1,1)),sum(b|1))))))[m%*%b==n,]
```
Anonymous function; returns the values in **reverse order** with column names attached.
[Try it online!](https://tio.run/##FcbRCoIwFIfx@95D@J9Y0aYmCOdJoqCpk4E7ypzQRe@@2nfx44vZcXaHDMmvAlGWzQu3fllnAyEiBE5ImD7bW8brHP2IOG1Y/J4w4KKVJlL7EWC//ys9QnWuLLOoZ3bQdHKoC6YtNl1Rm7pp7x3lHw "R – Try It Online")
Explanation:
```
function(n){
b <- 2^(0:log2(n)) # powers of 2 less than n
m <- expand.grid(rep(list(c(-1,1)),sum(b|1))) # all combinations of -1,1 at each position in b, as data frame
m <- t(t(m)) # convert to matrix
idx <- m%*%b==n # rows where the matrix product is `n`
m[idx,] # return those rows
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 30 bytes
29 bytes code, 1 byte for `-p` switch.
```
$_=sprintf'1%b',$_/2;s/0/-1/g
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ra4oCgzryRN3VA1SV1HJV7fyLpY30Bf11A//f9/QyNjE1Mz83/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# CJam, 12 bytes
A port of my Golfscript answer.
```
qi2b{_+(}%)\
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~44 37 33~~ 32 bytes
```
->n{("1%b"%n).chop.gsub ?0,"-1"}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWkPJUDVJSTVPUy85I79AL724NEnB3kBHSddQqfZ/gUJatJFpLBeINjGP/Q8A "Ruby – Try It Online")
[Answer]
# Golfscript, ~~14~~ ~~13~~ 14 bytes
*-1 byte because I forgot `%` existed.*
*+1 byte because I also forgot input is a string.*
```
~2base{.+(}%)\
```
] |
[Question]
[
**This question already has answers here**:
[Generate combinations that add up to a target value](/questions/153221/generate-combinations-that-add-up-to-a-target-value)
(15 answers)
Closed 6 years ago.
Write a function that gets as an input a sorted array of positive numbers `A`, and an additional number `n`. The Task is to print out all **distinct** subsets of `A`, that sum to `n`.
Example:
```
Input:
A = [1,2,2,4,4]
n = 9
Output:
[1,2,2,4]
[1,4,4]
```
Bonus:
-50% if your code doesn't store duplicate subset (the same subset but in different order) intern. The function will not store more than one duplicate subset in memory at a time.
Shortest code in bytes wins.
[Answer]
# Pyth, 6
```
@yE./Q
```
[Try it online](https://pyth.herokuapp.com/?code=%40yE.%2FQ&input=9%0A%5B1%2C2%2C2%2C4%2C4%5D%0A&debug=0)
We get all of the subsets of the given list with `yE`, and then `./Q` gets all of the integer partitions (lists of integers that add up to it) of the other input. `@` Finds the intersection of the two sets.
[Answer]
# Julia, ~~89~~ ~~82~~ 72 bytes
```
f(x,n)=partitions(n)∩foldl(vcat,[collect(combinations(x,i))for i=1:n])
```
This is a function that accepts an array and an integer and returns an array of arrays. It uses the same approach as FryAmTheEggman's clever Pyth [answer](https://codegolf.stackexchange.com/a/75744/20469) and doesn't qualify for the bonus.
We get all combinations of the elements of *x* of size *i* for *i* in 1 to *n*, and take the intersection of this with the integer partitions of *n*. The resulting array is the set of combinations which are also partitions of *n*, i.e. those that sum to *n*.
[Answer]
# Pyth, 9 - 50% = 4.5 bytes
```
f!.-TQ./E
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=f!.-TQ.%2FE&input=%5B1%2C2%2C2%2C4%2C4%5D%0A9&debug=0)
Got a little bit inspired by Fry.
### Explanation:
```
f!.-TQ./E implicit: Q = input list
./E read a number from input and compute a list of partitions
f filter for partitions T, which satisfy:
.-TQ remove the numbers in Q one by one from T
! check if the resulting list is empty
(and therefore the partition is a subset of Q)
```
[Answer]
# JavaScript (ES6) 115
Using an hash table to store results, no duplicate is ever stored. But I doubt that this is what OP means for the bonus, so I will not claim it.
```
(A,n)=>[...Array(1<<A.length)].map((x,m)=>(x=A.filter((v,i)=>1<<i&m&&(t-=v,1),t=n),t||++s[x]),s={})&&Object.keys(s)
```
**Less golfed**
```
(A,n) =>
[...Array(1<<A.length)].map( // enumerate all the subsets (2^A.len)
(x, // used as a local variable
m // current index, used as a bit mask
) => ( // build the current subset in x using bit mask
// meanwhile, check if the elemnt sum is == n
t = n,
x = A.filter( (v,i) => 1<<i&m && (t-=v,1) ),
t || ++s[x] // if the sum is n, add X to hash table (this avoid dups)
),
s={} // hash table init to empty
) && Object.keys(s) // return keys
```
**Test**
```
f=(A,n)=>[...Array(1<<A.length)].map((x,m)=>(x=A.filter((v,i)=>1<<i&m&&(t-=v,1),t=n),t||++s[x]),s={})&&Object.keys(s)
function go() {
var a = A.value.match(/\d+/g)
var n = +N.value
O.textContent = f(a,n).join('\n')
}
go()
```
```
Array A <input id=A value='1 2 2 4 4'><br>
Value n <input id=N value=9><br>
<button onclick='go()'>Go</button>
<pre id=O></pre>
```
[Answer]
# [Perl 6](http://perl6.org), 50 bytes - 50% = 25
`{@^a.combinations.unique(as=>~*).grep: *.sum==$^n}`
Ungolfed
```
sub d (@a,$n) {
@a.combinations.unique(as => ~*).grep: *.sum == $n
}
```
Perl 6 has a built in `combinations` operator (as well as one for `permutations`!). Both of these return a lazy list.
`unique` by itself would not return unique combinations, because technically they are not unique (they are *equivalent*) so we tell `unique` to compare them as strings (`~$var` coerces `$var` to a string, and `*` means `Whatever`)
Then we `grep` for `Whatever.sum` is equal to n; Result of last evaluated expression is returned by default
Lastly, if I don't define a signature, I can use `$^var` to refer to a passed variable. Alphabetical (Positional) order matters with these, as `$^a` is passed in before `$^b`;
[Answer]
## Pyth, 8 bytes
```
{fqsTQyE
```
No bonus.
```
{ f Unique elements of filter lambda T:
q equals
s T sum of T
Q First input
y E over all subsets of second input
```
Try it [here](https://pyth.herokuapp.com/?code=%7BfqsTQyE&input=9%0A%5B1%2C2%2C2%2C4%2C4%5D%0A&debug=0).
[Answer]
# Ruby, 73 bytes
```
->x,n{(1..n).flat_map{|i|x.combination(i).select{|c|eval(c*?+)==n}.uniq}}
```
This is a lambda function that accepts an array and an integer and returns an array of arrays. To call it, assign it to a variable, say `f`, and do `f.call(x, n)`.
For each *i* from 1 to *n*, we get all combinations of size *i* of the elements of *x*, select those combinations *c* such that *c* sums to *n*, and take the unique elements.
[Try it here](https://repl.it/Bx2u/0)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 39 bytes
```
:1fd.,{,.[L:N]hs?{_,0 .|b:2&I,?h+I=.}N}
```
Called with a list containing the list of numbers first and the value of the sum second.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes
Uses **CP-1252** encoding. Code:
```
æÙvyO²Q—
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w6bDmXZ5T8KyUeKAlA&input=WzEsMiwyLDQsMywgNCwgNSwgNSw0XQo5)
[Answer]
## Haskell, ~~54 \* 1.0~~ 76 bytes \* 0.5 = 38
```
import Data.List
f n=foldl(\r e->r++[e|notElem e r,sum e==n])[].subsequences
```
Usage example: `f 9 [1,2,2,4,4]` -> `[[1,2,2,4],[1,4,4]]`.
Brute force: check every subsequences, keep it if it has the right sum and has not been seen before. `subsequences` build the list of subsequences lazily, i.e. one after the other, so at most one new element is kept in memory together with all unique elements so far.
For reference the previous version with the built-in function to remove duplicates, which requires to build the whole list of subsequences in memory. 54 bytes, no bonus.
```
import Data.List
x#n=nub[y|y<-subsequences x,sum y==n]
```
[Answer]
# PHP, 162 - 50% = 81 bytes
```
function c($a,$n){$o=[];for(;++$i<pow(2,count($a));){$s=[];foreach($a as$x=>$e)if($i&pow(2,$x))$s[]=$e;if(array_sum($s)==$n&&!in_array($s,$o))$o[]=$s;}return$o;}
```
Without a powerset built in this was kind of a pain.
```
for(;++$i<pow(2,count($a));) #generate integers
foreach($a as$x=>$e)if($i&pow(2,$x))$s[]=$e; #use integers to generate subsets
if(array_sum($s)==$n&&!in_array($s,$o))$o[]=$s; #conditionally add suset to output
```
the rest is just necessary initialisation and output
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 26 \* 0.5 = 13
```
x{}FTinZ^!"0$G@)s=?2MVJX(u
```
Works with [current version (14.0.0)](https://github.com/lmendo/MATL/releases/tag/14.0.0) of the language/compiler.
*EDIT (June 10, 2016): The link below replaces `J` by `JQ` to adapt to recent changes in the language*
[**Try it online!**](http://matl.tryitonline.net/#code=eHt9RlRpblpeISIwJEdAKXM9PzJNVkpRWCh1&input=OQpbMSAyIDIgNCA0XQ)
### Explanation
All possible subsets are tested to see if the sum is correct. For each subset, if the sum condition is satisfied the subset is stored in a (cell) array. Immediately after that, duplicates are removed (the only possible duplicate at this point is the newly added array, and in that case it is removed). So this gets the bonus.
```
x % take number input implicitly. Delete (gets copied into clipboard G)
{} % push empty cell array. Will be grown with the found subsets
FT % push array [false, true]
in % take array input. Push its length
Z^! % Cartesian power. 2D array in which each column indicates (via
% logical indexing) which elements of the input array form a
% subset. This covers all possible subsets.
" % for each column
0$G % push the two inputs: number, then array
@) % apply logical index to extract the current subset
s % compute its sum
= % are they equal?
? % if so
2M % push the subset again
V % convert numbers to string. Needed to test for uniqueness
JX( % append that to the cell array that stores the subsets
u % remove duplicates (the only possible duplicate is the
% newly appended subset)
% end if implicitly
% end for each implicitly
% display implicitly
```
[Answer]
# Jolf, 9 bytes, noncompeting
I had to do some bugfixes, ergo, invalid :( [Try it here anyhow!](http://conorobrien-foxx.github.io/Jolf/#code=z4htWnhkPXVIag&input=WzEsMiwyLDQsNF0KCjk)
```
ψmψxd=uHj
mψx unique powerset of input array
ψ d filtered according to a function
=uH that tests if the sum of the member
j is the input number.
```
Test like
```
[1,2,2,4,4]
9
```
[Answer]
# Oracle SQL 11.2, 199 bytes
```
SELECT DISTINCT s FROM(SELECT SYS_CONNECT_BY_PATH(TRUNC(i),'+')s FROM(SELECT''||COLUMN_VALUE+ROWNUM/100 i FROM XMLTABLE((:a)))START WITH i>0 CONNECT BY i>PRIOR i),XMLTABLE(s)WHERE''||column_value=:n;
```
Inputs are :
:a the array of positive numbers, formated like "1","2","3","3"
:n the target number
Un-golfed :
```
SELECT DISTINCT s
FROM (
SELECT SYS_CONNECT_BY_PATH(TRUNC(i),'+')s
FROM (
SELECT ''||COLUMN_VALUE+ROWNUM/100 i
FROM XMLTABLE((:a))
)
START WITH i>0 CONNECT BY i>PRIOR i
), XMLTABLE(s)
WHERE ''||column_value=:n;
```
[Answer]
# Mathematica, 33 bytes
```
Cases[{}⋃Subsets@#,s_/;Tr@s==#2]&
```
# Mathematica, 57 bytes (-50%) = 28.5 bytes
```
Cases[Fold[Append@@@Thread@{##}⋃#&,{{}},#],s_/;Tr@s==#2]&
```
[Answer]
# [J](http://jsoftware.com), 28 bytes
```
~.@((=+/@>)#])]<@#~2#:@i.@^#
```
Generates the power set and filters it before removing duplicates.
## Usage
Since J does not support ragged arrays, each subset is output within a box.
```
f =: ~.@((=+/@>)#])]<@#~2#:@i.@^#
9 f 1 2 2 4 4
┌─────┬───────┐
│1 4 4│1 2 2 4│
└─────┴───────┘
```
## Explanation
```
~.@((=+/@>)#])]<@#~2#:@i.@^# Input: n on LHS, A on RHS
# Get the size of A
2 ^ Get 2^len(A)
i.@ Get the range [0, 1, ..., 2^len(A)-1]
#:@ Convert each to binary to get the masks for each subset
#~ Copy using each mask from A
<@ Box each subset
+/@> Unbox each and reduce using addition
= Check which sums are equal to n, 1 if true else 0
] Get the list of boxed subsets
# Copy only those whose sums are equal to n
~.@ Remove duplicates and return
```
] |
[Question]
[
Write a [fixed point combinator](http://en.wikipedia.org/wiki/Fixed_point_combinator) in as few characters as possible, in the language of your choice.
* free form (*i.e.*, whatever's shortest): whole program, actual function, code snippet
* you may not use your standard library's if it has one
* you may however extract it from other high-level functions it you'd rather do that than construct it from the bases
Please include a recursive factorial or Fibonacci that uses it as a demo.
In this question, self-reference is acceptable, the aim is solely to remove it from the recursive function it will apply to.
[Answer]
## Haskell: 10 characters
```
y f=f$y f
```
Example of use to create recursive definitions of factorial or nth-Fibonacci:
```
> map ( y(\f n->if n <= 1 then 1 else n*f(n-1)) ) [1..10]
[1,2,6,24,120,720,5040,40320,362880,3628800]
> map ( y(\f n->if n <= 1 then 1 else f(n-1)+f(n-2)) ) [0..10]
[1,1,2,3,5,8,13,21,34,55,89]
```
Though, a more common way to use `y` would be to generate these sequences directly, rather than as functions:
```
> take 10 $ y(\p->1:zipWith (*) [2..] p)
[1,2,6,24,120,720,5040,40320,362880,3628800]
> take 11 $ y(\f->1:1:zipWith (+) f (tail f))
[1,1,2,3,5,8,13,21,34,55,89]
```
Of course, with Haskell, this is a bit like shooting fish in a barrel! The `Data.Function` library has this function, called `fix`, though implemented somewhat more verbosely.
[Answer]
## Perl, 37
```
sub f{my$s=$_[0];sub{$s->(f($s),@_)}}
```
Factorial demonstration:
```
sub fact {
my ($r, $n) = @_;
return 1 if $n < 2;
return $n * $r->($n-1);
}
print "Factorial $_ is ", f(\&fact)->($_), "\n" for 0..10;
```
Fibonacci demonstration:
```
sub fib {
my ($r, $n) = @_;
return 1 if $n < 2;
return $r->($n-1) + $r->($n-2);
}
print "Fibonacci number $_ is ", f(\&fib)->($_), "\n" for 0..10;
```
[Answer]
## GNU C - 89 chars
```
#define fix(f,z)({typeof(f)__f=(f);typeof(__f(0,z))x(typeof(z)n){return __f(x,n);}x(z);})
```
Example:
```
#define lambda2(arg1, arg2, expr) ({arg1;arg2;typeof(expr)__f(arg1,arg2){return(expr);};__f;})
int main(void)
{
/* 3628800 */
printf("%ld\n", fix(lambda2(
long factorial(int n), int n,
n < 2 ? 1 : n * factorial(n-1)
), 10));
/* 89 */
printf("%ld\n", fix(lambda2(
long fibonacci(int n), int n,
n < 2 ? 1 : fibonacci(n-1) + fibonacci(n-2)
), 10));
return 0;
}
```
[Answer]
# k2, 12 char
The obvious self-referential implementation is the shortest. This is a sign of good language design. Unfortunately, K isn't lazy, so we can only manage call-by-value.
```
Y:{x[Y[x]]y}
```
This definition should also work in k4 and q without trouble, though I assume k2 for the examples below.
```
Y:{x[Y[x]]y}
fac: {[f;arg] :[arg>0; arg*f[arg-1]; 1]}
Y[fac] 5
120
fib: {[f;arg] :[arg>1; f[arg-1] + f[arg-2]; arg]}
Y[fib]' !10
0 1 1 2 3 5 8 13 21 34
```
A more modest 18 characters lets us exactly transcribe `(λx. x x) (λxyz. y (x x y) z)` into K.
```
{x[x]}{y[x[x;y]]z}
```
Maybe someday (k7?), this could look like `Y:{x Y x}`.
[Answer]
# Python 3, 30 Bytes
```
Y=lambda f:lambda a:f(Y(f))(a)
```
Demo :
```
Y=lambda f:lambda a:f(Y(f))(a)
quicksort = Y(
lambda f:
lambda x: (
f([item for item in x if item < x[0]])
+ [y for y in x if x[0] == y]
+ f([item for item in x if item > x[0]])
) if x
else []
)
print(quicksort([1, 3, 5, 4, 1, 3, 2]))
```
Credits : <https://gist.github.com/WoLpH/17552c9508753044e44f>
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 bytes
```
{∇(⍎⍺⍺)⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3y2z4lHbhOpHHe0aj3r7HvXuAiLNR71ba///V682fNS5FMi2MnzU3aIBkVMA8nUNNbWReEa16gpAYxRMAA "APL (Dyalog Unicode) – Try It Online")
An operator whose left operand is a string representing the function to be combinatorified and whose right argument is passed to the function once it is combinatorised. I *think* it's okay to pass the function as a string, but if not, I will delete this answer.
Explanation
```
{∇(⍎⍺⍺)⍵}
∇(⍎⍺⍺) ⍝ Equivalent to f ( Fix f )
⍺⍺ ⍝ Left operand
⍎ ⍝ Evaluate to get monadic operator
∇ ⍝ Self-reference (Fix f). Pass as operand to f (or ⍎⍺⍺)
⍵ ⍝ Apply the derived function to the right argument ⍵
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes
```
v_//Z@g_=Z@g~g~v (* golfed *)
Z[g_][v_] = g[Z[g],v] (* ungolfed *)
```
[Try it online!](https://tio.run/##dc2xCsIwEAbgPU9xo9ZIW1cNOAluDk4NR7iEth60KYTQReyrx9hRcTm447/vHyk@2pEiO0ppNmXZnHuj8lj6ZU6bAjpycQpMAxRbkRcdjARvEBRcO@1BKagk1PlWBO33NeJR3AL7qO9kh1Y3Oj@hZpTwZLlmqxeiENm@sJ08OcerzfbbPqkVlvCRD7j7V8D2tyC9AQ "Wolfram Language (Mathematica) – Try It Online")
This definition of the [*Z* combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator#Strict_fixed-point_combinator) uses the Wolfram Language's pattern-matching to make sure that any expression of the form `Z[g]` remains unevaluated as long as the second argument is missing; only the two-argument form `Z[g][v]` matches the above pattern and is replaced by `g[Z[g],v]`, which in turn contains the single-argument form `Z[g]` that remains unevaluated until later. This distinction between an inert single-argument form `Z[g]` and an automatically-substituted two-argument form `Z[g][v]` allows for a controlled recursion process that remains tied to the application of the second argument.
## examples
### factorial
```
fac[r_, n_] = If[n==0, 1, n*r[n-1]];
Table[Z[fac][i], {i, 0, 10}]
(* {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800} *)
```
Same with an anonymous function:
```
Table[Z[If[#2==0, 1, #2*#1[#2-1]]&][i], {i, 0, 10}]
(* {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800} *)
```
Same but using Mathematica's built-in self-reference operator [`#0`](https://reference.wolfram.com/language/ref/Slot.html): we don't actually need a combinator to define [recursive anonymous functions](https://rosettacode.org/wiki/Anonymous_recursion#Mathematica_.2F_Wolfram_Language),
```
Table[If[#1==0, 1, #1*#0[#1-1]]&[i], {i, 0, 10}]
(* {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800} *)
```
### Fibonacci sequence
```
fib[r_, n_] = If[n<=1, n, r[n-2]+r[n-1]];
Table[Z[fib][i], {i, 0, 10}]
(* {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55} *)
```
[Answer]
# Java 8, 104 bytes
```
interface C{int t(int n);}interface F{C f();}interface P{C c(F f);static F g(P p){return()->p.c(g(p));}}
```
Based on [*@user*'s Java answer](https://codegolf.stackexchange.com/a/229753/52210) for [the related *Implement Fix2 combinator* challenge](https://codegolf.stackexchange.com/questions/229602/implement-fix2-combinator).
**Explanation:**
```
interface C{ // Completed Function interface
int t(int n);} // Using a function that transforms a given integer
interface F{ // Function interface
C f();} // A wrapper to pass the 'Completed Function' as function
interface P{ // Program interface
C c(F f); // Which takes a 'Function' as argument, and returns a 'Completed Function'
static F g(P p){ // Recursive function that accepts a 'Program' as argument, and returns a 'Function'
return()-> // Return a new function, which wraps:
p.c( // A completed call to its own 'Program' interface
g( // Using a recursive call to its own function
p));}} // with the given 'Program' as argument
```
The method to call is `P::g`, which takes `P` as argument and returns `F`. To obtain a completed function `C` from an `F`, we can call `F::f` on it. `P` represents the function to be fixed, and its method `c` takes `F` as argument to prevent immediate evaluation, returning a `C` that represents a complete function to transform a given integer `n` with `C`'s `t(n)`.
**Example Fibonacci implementation:**
```
P fix = fibonacci -> n -> n>1? fibonacci.f().t(n-1)+fibonacci.f().t(n-2) : 1;
C func = P.g(fix).f();
int result = func.t(input);
```
[Try it online.](https://tio.run/##ZZDBasMwEETv@YohJwljURd6qRv3EPCtYMix9KAotqs0kYW8Di3G3@6ulUAovSzDzOix2qO@6PR4@Jpn66gOjTY1tiNrkFimk/l0T8pxi0b8sSq2jCjRyLwnTdagRCsqeDmGmobghEwLr4xohZf8cpr9sD9xzZx03@NNW4dxBdzcG@PS2QPOnIkdBeva9w/o0H7KWAUqNPYbG577zmljLNICLo4ie73bipdVJFyayeS/@SjxjCyPRP7X4AwjK9UKhsuldY2aLsRTWOcH2jzkV/GSPd1UksjYA3Y/PdVn1Q2kPG9NYmGq5ZBck8ka64icVtP8Cw)
] |
[Question]
[
(Similar: [Through the bases](https://codegolf.stackexchange.com/questions/53683/through-the-bases))
Normally, our number system is base ten, with the digits `0123456789`. However, we can increase or decrease the base count (so hexadecimal uses `0123456789abcdef` and octal uses `01234567`.
Your goal is: given a string, interpret it in all bases 2-36 for which it's valid, compute the total, and express that total in the smallest base that was valid for the original string.
The valid base characters are `0123456789abcdefghijklmnopqrstuvwxyz`. It is not case sensitive!
If it is invalid, return zero. There may be a sign for the first character (a `+` or `-`): if it is a `-`, then return the result with a `-` before it.
## Test cases:
```
Xx -> 32s (base 34-36, in base 34, after lowercasing)
zzzzzz -> zzzzzz (36 is the only base that works, the number in base 36 is just "zzzzzz")
12 -> 1000002
MultiBase -> 8qa4f6laud
1v1 -> app
gy -> ye
+Huh -> 41ou
+h -> hh
abc -> 58b5b
-hello -> -k029mh
one -> hmm5
NaN -> k1hl
-Infinity -> -16di5ohk2
hello world -> 0
$0.99 -> 0
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
[Answer]
# [Go](https://go.dev), 146 bytes
```
import."strconv"
func f(n string)string{s,m:=int64(0),36
for b:=m;b>1;b--{if i,e:=ParseInt(n,b,0);e==nil{s+=i;if m>b{m=b}}}
return FormatInt(s,m)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVFNT9wwEFWv8ytM1EPCOigJu6v9kPfQQ1UORUi9VKIInKy9sdYfaeJQIMqf6LWXVaUe-UHwaxrH0GIf_ObNmzfWzK_fO3N4Oq5osac7hhQVGoSqTG1PAq5s8C9obC30rgn-tJbHi6efb_jC6NsAeKsLxEONvDLyT9dgtSJC2_k0TCJ8OgduapSviFrnm3Sdx3EnOBKYrcgFrRt2pm2ocY6TaM0I0UJ2zYSI9aBRm7xTJO_7Hmpm21qjj6ZW1LqKoUnU-589v3sc_tNY1CCCbr7eoXiDTrMGHsbjIo8gzVyQJu5k8LmVVnygDXPk4jud8rmk7RbS29QxtKpgd-_QPYPJp7Z0cJqaFiYjLEugeeHQbJHPcohLJqVxcbxPsqUqwejRulRqBuf03OF9WkqIzzQXWtjRPE7nWzEz5T4Db_DD1HLrMgm8T06WyxHegB-2W1YYoW4c6TWWaEVQTfWwxi-VFG4qwTcdOAFzKU9KHDiTIAKhq9ZidlexwrKtU7DL5AqzS8l0yKI4vQJa2JaOvjwc5UMVRy_s0VDwWtxdDMu2UocvOfI_h5Fv9IbwoqiH4fqtHQ7-_Qs)
### Explanation
```
import."strconv" // boilerplate
func f(n string)string{ // boilerplate
s,m:=int64(0),36 // `s`um, `m`inimum usable base
for b:=m;b>1;b--{ // for all bases from 36 to 2...
if i,e:=ParseInt(n,b,0);e==nil{ // parse `n` as that base. if successful...
s+=i // add to the sum
if m>b{m=b}}} // set to the lower base
return FormatInt(s,m)} // format the number in the `m`inimum base.
```
[Answer]
# JavaScript (ES7), 83 bytes
```
s=>(g=b=>s>'!'&(P=parseInt)(s+0,b)**2>(v=P(s,b))*v&&v+g(b-1,q=b))(q=36).toString(q)
```
[Try it online!](https://tio.run/##bdI9b4MwEAbgvb@CWhWxQyCGfCgZzNCpHRpF6tLVJA5O42DAQJv@eZoPoZJzb7P16D3rfJ@84WZT7vPKz/RWtDvWGhbjlCUsNvHgceDiNct5acRrVhFsPDpKyHAYxbhha2zOBzJsXLfxUpz44ahg5wtcsMmcBJV@r8p9luKCtBudGa1EoHSKdxh9fCOnK0Kc8diZROYBoJ9roR663UAXRjAspJeKIHyrVbV/5kagDi4KPt3NFa@3VmgTovtQnucQpSfY@SSg8V5qie7MNNS1pSRMkhIanmzAk2aLZJZA5kuhlO6PzT/QaHm08nQmQJ48HmdQrfgKqEMoFVTXns6XLtUW3RSF5IkGyyXqB1nEsX6c/rsU1FoKy3l/8@yi2l8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 89 bytes
```
->s{o=p;(2..36).sum{|b|q=s.to_i b;s.tr(?+,'').downcase==q.to_s(b)?(o||=b;q):0}.to_s o||2}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PZBLbtswEIbRLU9BGAFEVhKhhy3YURkDXbUBmnWKIAjEWApZPSiLZF3ZzrK73qApEBTtodplTlJRds3VN__M_DPD7786w_rnnwX9bXThz_989C_UTtI2RREhcYKJMvVuz_ZrqoiWdwKydIAOLV3PcTBZyU1zn6mc0rVNK8TwEsn9nrJ0jc-Dx1GEgxA9Hgf0Z29InbW73tvSu5Ao3YmWqLYSGjnQv4AOThUtbvrbtDVaQeVO4OQ1igNfESW2OXZRSbenBuTgm-AWn4rK_0WK0hIunZenr8658_Ljm4OPCzz_fXV5_cVOiiMFERuWh_HUjxMPigYeQw9mhc47WMlN3g33ieYBg-34bOeRUJxAoaDmOZRN1R-aNc803MiuVN6YaUzNBqeT99jyySgNJwebCQZhZF3DwL4IfDCVFm9t8SDO19m0SKrMrED4ObRK1rbgobfU58B9Z7jFaSgNcEfkHGTs3tJszmYM-DyvKmljvwyiRc2BbEZrXtczcJVdWS5DXgH_fVOIRujR3A-TlZhJXkbgYDDcVK1sJgBnAVksRjz86T8)
[Answer]
# [Factor](https://factorcode.org/), ~~77~~ 75 bytes
```
[ 2 36 [a,b] [ base> ] with map dup sift sum swap [ f = ] count 2 + >base ]
```
[Try it online!](https://tio.run/##XZFfT8IwFMXf@ymuN77hyDYYAY08@KI8yIsxMVl46LaONus/1lVE42fHAmpg96n5nXtOc9qalp1p968vi@XjLSja8WFL9Zq509nS1rEWGtZqJsGxjWe6/BVBGLgjXwTfPhD@5wqiOYxSR/DzOHiGT4RgkvYNSXyYlOCzl514oI7hnzTd0HE9kdRXwfie4KWRWktwvevn7RjBwZPneEHHifGB8/425wRpUfais2mRFQQjzqQ05zWiJk5nKniMZj0PVyojuKTLHm8SLkPUQtdCi273Xy5KJpXIDG9C9eM9sDWtrPCkxgSv4@FshudRMfne55DCaAI5vSlWkEMR3msOK9iK8CuKWqi8BSfqDpxX4LaB5FDDfVgpjdddcA9gfnDBKmTZVgR20JQ1gTFa8v0P "Factor – Try It Online")
```
! "abc"
2 36 [a,b] ! "abc" { 2 3 ... 36 }
[ base> ] with map ! { f f f f f f f f f f f 1845 2126 2427 2748 3089 3450 3831 4232 4653 5094 5555 6036 6537 7058 7599 8160 8741 9342 9963 10604 11265 11946 12647 13368 }
dup ! { f f f f f f f f f f f 1845 2126 2427 2748 3089 3450 3831 4232 4653 5094 5555 6036 6537 7058 7599 8160 8741 9342 9963 10604 11265 11946 12647 13368 } { f f f f f f f f f f f 1845 2126 2427 2748 3089 3450 3831 4232 4653 5094 5555 6036 6537 7058 7599 8160 8741 9342 9963 10604 11265 11946 12647 13368 }
sift ! { f f f f f f f f f f f 1845 2126 2427 2748 3089 3450 3831 4232 4653 5094 5555 6036 6537 7058 7599 8160 8741 9342 9963 10604 11265 11946 12647 13368 } { 1845 2126 2427 2748 3089 3450 3831 4232 4653 5094 5555 6036 6537 7058 7599 8160 8741 9342 9963 10604 11265 11946 12647 13368 }
sum ! { f f f f f f f f f f f 1845 2126 2427 2748 3089 3450 3831 4232 4653 5094 5555 6036 6537 7058 7599 8160 8741 9342 9963 10604 11265 11946 12647 13368 } 162316
swap ! 162316 { f f f f f f f f f f f 1845 2126 2427 2748 3089 3450 3831 4232 4653 5094 5555 6036 6537 7058 7599 8160 8741 9342 9963 10604 11265 11946 12647 13368 }
[ f = ] count ! 162316 11
2 + ! 162316 13
>base ! "58b5b"
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
≔⌕θ-η׬η-≔↧Φθ∨κ∧η⌕θ+θ≔EΦ³⁷⬤θ№Eι⍘νιλ⍘θιη⍘↨η¹⁻³⁷Lη
```
[Try it online!](https://tio.run/##TY@xDsIgEIZ3n4J0ohEG4@DQqZoYh1ZN9AVIJYV4ggWqj49HrbY3kXz3/ffTKOEaKyDG0nvdGrrX5kY7RjKe5YyovFicnTaBXvVDenq0gar8SxGNTmXf0jXCS7QhSJf8k6N3RkoMU4z8Q5eo4TDSTXYtnj9vvUEFIK3ubI9XE9OMbDH7ErBHSw0jOgXAEDMD3QimyjOYnqnIChdqbXo/nKqkaYPCD@EUMfKDBLCRv@AD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⌕θ-η
```
See whether the string begins with `-`.
```
׬η-
```
Output a `-` if it does.
```
≔↧Φθ∨κ∧η⌕θ+θ
```
Remove the first character of the string if it was `-` or `+` and lowercase the result.
```
≔EΦ³⁷⬤θ№Eι⍘νιλ⍘θιη
```
Loop through the bases up to `36`, checking that all the characters in the string can be represented in that base, and if so, convert the string from that base. No number can successfully be represented in base `0`, and while `0` can be successfully represented in base `1`, fortunately this won't affect the result.
```
⍘↨η¹⁻³⁷Lη
```
Take the sum of all of the conversions and convert that into the lowest successful base, calculated as `37` minus the number of successful base conversions (if there were none then the `0` will be converted into base `37` but that's still `0`).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„+-мl©žLRlÙ礮Skà.$¬UδÅβþOXÅвJI'-Ãì
```
[Try it online](https://tio.run/##AUMAvP9vc2FiaWX//@KAnist0LxswqnFvkxSbMOZzrfCpMKuU2vDoC4kwqxVzrTDhc6yw75PWMOF0LJKSSctw4PDrP//LVh4) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw3ztHUv7Mk5tPLoPp@gnMMzz20/tOTQuuDswwv0VA6tCT235XDruU2H9/lHHG69sMmrUl33cPPhNf91/kcrRVQo6ShVgQGQYWgEJHxLc0oynRKLU0ECZYZAMr0SSGh7lGaAKBCRmJQMJHUzUnNy8oGM/DyQWr9EP5CgZ15aZl5mCUgLWF6hPL8oJwXIUzHQs7RUigUA).
**Explanation:**
(Assumes the input will never contain any `-` or `+` in the middle of the input, only optionally at the front.)
```
„+-м # Remove a potential "+" or "-" from the (implicit) input
l # Convert it to lowercase
© # Store this modified input in variable `®` (without popping)
žL # Push builtin "zyx..cbaZYX..CBA987..210"
R # Revert it
l # Convert it to lowercase as well
Ù # Uniquify it to "012...789abc...xyz"
D # Duplicate this string
η # Get all its prefixes
s # Swap so the string is at the top again
® # Push modified input `®`
S # Convert it to a list of characters
k # Get the 0-based index of each character in the string
à # Pop and push the maximum
.$ # Remove that many leading items from the list of prefixes
¬ # Push the first prefix (without popping the list of prefixes)
U # Pop and store this first prefix in variable `X`
δ # Map and use each prefix separately as argument on the modified input:
Åβ # Convert it to this prefix as custom base
þ # Only keep all items consisting solely of digits (for invalid inputs)
O # Sum this list together
X # Push the first prefix from variable `X`
Åв # Convert the sum to this custom base as list
J # Join this list of characters together to a string
I # Push the input-again
'-Ã '# Only keep its "-"
ì # Prepend it in front of the string
# (after which the result is output implicitly)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 22 bytes
```
aFB:,37($+FIaTB:uNa)|0
```
Outputs in uppercase. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhbbEt2crHSMzTVUtN08E0OcrEr9EjVrDCCSUDXLo5X8Ev2UYqFcAA) Or, [verify all test cases](https://ato.pxeger.com/run?1=m724ILNgWbSSbo5S7MLqpaUlaboW2xLdnKx0jM01VLTdPBNDnKxK_RI1awwgkjc7axV8FaK5FJQiKpSAZBUYgFiGRiDStzSnJNMpsTgVLFRmCKLSK0GktkdpBpgGk4lJySBKNyM1JycfxMrPA2vxS_QDi3vmpWXmZZaAdYLVKJTnF-WkgLgqBnqWlkpcsRAHLVgAoQE).
### Explanation
Pip's base-conversion builtins were *made* for this challenge.
* They work for bases 2 through 36, using 0..9A..Z as digits.
* They accept both lower- and uppercase inputs.
* They even handle the leading `+` and `-` correctly.
* If `FB` can't convert from a given base, it returns nil (and issues a warning which is ignored by default).
Thus:
```
aFB:,37($+FIaTB:uNa)|0
a ; First command-line input
FB: ; Convert from the following base(s) and assign back to a:
,37 ; All numbers from 0 through 36
; This results in a 37-element list, which contains nil for
; any base that's too small (including 0 and 1) and a
; decimal integer for the rest
FIa ; Filter the falsey values out of that list
$+ ; Sum it
uNa ; Count the number of times nil occurs in the list
TB: ; Convert the sum to that base
; If the input was invalid, every element of the list was
; nil, which means we just tried to convert 0 to base 37,
; which returns nil rather than 0, so...
( )|0 ; If that result was falsey, use 0 instead
```
[Answer]
# Excel, 136 bytes
```
=LET(
b,"-",
c,TEXTSPLIT(A1,"+",b,1),
d,ROW(A:A),
e,DECIMAL(c,d),
f,1-ISERR(e),
IFERROR(REPT(b,LEFT(A1)=b)&BASE(SUM(IF(f,e)),MIN(IF(f,d))),0)
)
```
Input in cell `A1`.
[Answer]
# [Rust](https://www.rust-lang.org), 362 bytes
```
|s|{let(mut o,mut m)=("".repeat(1),36);let mut n=(2i32..=36).rev().filter_map(|i|i128::from_str_radix(s,i as u32).ok()).zip((2i32..=36).rev()).fold(0,|a,(n,b)|{if m>b{m=b}a+n});let k=n<0;n=n.abs();while{let(d,r)=(n/m as i128, n%m as i128);o=format!("{}{o}",&"0123456789abcdefghijklmnopqrstuvwxyz"[r as usize..=r as usize]);n=d;n>0}{}if k{format!("-{o}")}else{o}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVLBcpswEJ1c9RUK02bEBDDg2HXs4ENP6aG5ZKbTmU7HFiCMYiERJGLHmGt_opcc2p_K11SCOk4me4Dd1e7Te7v6_aeqpXp6PrkeDGCuVCmng0EiUrISLPOkwsmabJMc8xXxElEM7msiFRVcDsLRZDQJBkXNFI2xJC6vi5hUEoBEHyt4O4VnUlUwgtb3LXTncBhKsOvMRL0HgtAEgW8sBF8N2GcNZpKTe3yRjRmuUxA8BCaDyxKsHo33SMD5dZ0b9yIQNTjv3DwHOE6MN5rEoxi4OWFMmNhd--FlkQPBO-i8KEbgBt8Yfx3kDLhfeEY5VR24G4xTOhL5OgQ9wEZULDUnPvjge5eXnWvNAMg4LDDlyIYNYETBTKv9W6vMnTyf3O3lvtFJVNQKCsd8CztCluVVpCRYocB2hmN7ZvrMIY9QSIeh50U6q2sekO1llClSLQpcoj3d0yCcTKdZJYqFHuyiwindIulQiCWsh6HtiTWybW9HS_QOSmMJliLf2WMHcSe29w3NYDGPmyKKW3zO257JOuJX_oxH3MOxRPZsk1NGOhmpU2n6fFCY6wwVB_KPL4E9E1EmqgKrU2Q1bSNayzmz_CAcXozGnyaXei8pyVY5vVuzgovyvpKqfthsH3fWj6oTIOmOaMbH4KeteaQzPvfbptVk183LBa7Bt1vCJNFeexj5L70SqM0ISfQrknodt13GmMcoJ1rTMdHN1WT3en_wlR12wjSAOfdkyahCllm8Zc_e1CLmcbJVels131Qa0Xbgu9Tx0vbV_YlgjCRqOr36RpKrxXyuB94r0EohoryslQPJttRFJLUh5f9lHdkapjhRNTZUM3TW9RxQjOnB3aqK8lX_ctAR7TQ6dL4VX-pqxbge87Lp4NolXDaHvi7o-9rl61m0oP-2oF_H01P__wc)
I'm not very familiar with golfing in Rust, but here is a quick-and-dirty port of [my Golang answer](https://codegolf.stackexchange.com/a/258587/77309).
About half the bytes are dedicated specifically for turning the sum back into base `m`, because apparently, [Rust doesn't have a `to_str_radix`](https://github.com/rust-lang/rust/issues/27728#issuecomment-172538725) or equivalent method for an arbitrary base <=36.
[Answer]
# [Raku](https://raku.org/), 70 bytes
```
{{.sum.base(.first(?*):k//2)}([map {!/\./&&.parse-base($^b)//0},^37])}
```
[Try it online!](https://tio.run/##JYxLD8FAAAb/ykeaatFdJSHEI3HiwFnilS272tg@7Laqmv72EuY6k0m4ksM6LGAKzOqyJDoLicc0t4gIlE6tRdue3Cnt25W1D1mCskEPhJomSZjS3PmlxsmzKe1V3dNgdLSrWrMCTeOM2RylgHGumhCxwiPPp7sX3j/g9rHJZBosvwe4Txe3Ap1V5qPjg3kXOD6XMkYccWzZFs46EkEUpAVaf5HHSl5bMHpkPJ7XHw "Perl 6 – Try It Online")
This is an anonymous function taking its argument in `$_`. Its form is `{ ... }(expr)`, where the inner braces are another anonymous function, which is immediately evaluated with the argument `expr`, available in the inner function as `$_`. This is a golfing idiom I use to avoid assigning to a temporary variable.
* `map { !/\./ && .parse-base($^b) // 0 }, ^37` parses the input string into all bases from zero to thirty-six. `parse-base` returns an error for the invalid bases 0 and 1, as well as any bases for which the input string has invalid characters, so the `// 0` converts those errors into the number zero. `parse-base` is case-insensitive and also handles leading "+" and "-" characters. Unfortunately for this problem, it also accepts a single period character, parsing such a string into a floating-point number, so I have to explicitly guard against that with `!/\./`.
* `[ ... ]` wraps the result of that mapping into an array, so that we can traverse it twice later. (`map` returns a lazy sequence object that can only be traversed once.)
* `.sum.base(...)` is the sum of those parsed numbers (plus zeroes for the invalid bases) expressed in the base given by the `...`, to wit:
* `.first(?*):k` returns the index (thanks to the `:k`ey adverb) of the first element of those parsed numbers that is nonzero, per the `?*` anonymous function that converts its argument to a boolean value.
* `// 2` defaults the base to 2 if `first` did not find any nonzero numbers, as when the input string is not valid in any base. The sum in this case will always be zero, so any valid base could be used here, though of course 2-9 are the best for golfing.
[Answer]
# [Zsh](https://www.zsh.org/), 84 bytes
```
for b ({36..1})((r+=$b#${(M)1:#(+|-|)[[:alnum:]]##}))||break
<<<$[[##$[b+1]]r]||<<<0
```
[Try it online!](https://tio.run/##HYxPi8MgFMTv@RSCgSrSEHdhoSG99NQe0vOCeNCNacK6sRjTv/azZ599h98MM495TP0ymeDOAZlbMGNr2pN1OusIJUvnPNKIPD@/ioK/KCGebXON8ydpKK8wYXEdqRCVsuP8V0mJ8YvSGLU36jer6zoXAuNcaMal9DJGiMqFZh36vgEe7wPDPwDNbMOwU5NJwYUDT3cA2889yDpB6R9gb6x1oEd1TMVh7IZxCOl39a7Q1XnbrtIMSzNlsdks/w "Zsh – Try It Online")
```
for base ({36..1})
# ${(M)1:#$pattern} substitutes $1 if $pattern matches
# Zsh supports [base]#[string] numbers.
(( sum += $base#${(M)1:#(+|-|)[[:alnum:]]##} )) ||
# The previous statement fails in three ways:
# - base is invalid (1#...)
# - the string is empty
# - the string contains invalid characters for the base (13#abc)
break
# increment $b back to the last valid base. This fails when $1 was invalid,
# since then $b is still 36. In that case, we output 0.
<<< $[ [##$[base+1]] sum ] || <<<0
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 35 bytes
```
K37#=+Ziz=tK;s+*>0Z\-@Ljk+UTGj.aZhK
```
[Try it online!](https://tio.run/##K6gsyfj/39vYXNlWOyqzyrbE27pYW8vOICpG18EnK1s7NMQ9Sy8xKsP7/39dz7y0zLzMkkoA "Pyth – Try It Online")
### Explanation
```
# implicitly Z=0 and z=input()
K37 # K = 37
# ; # repeat infinitely until an error occurs, then break
=tK # K = K-1
iz # convert the input from base K to int
=+Z # Z = Z + input as int (base K)
.aZ # absolute value of Z
j hK # converted to base K+1 as a list of ints
@L # convert each int to the value at its index in
+UTG # [0-9] + the alphabet
jk # joined as a string
*>0Z\- # "-" if Z is less than 0, "" otherwise
+ # prepend
s # join all elements together
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 114 bytes
```
s->{Integer t=0,b=1,r=40;for(;++b<37;)try{t+=t.parseInt(s,b);r=b<r?b:r;}finally{continue;}return t.toString(t,r);}
```
[Try it online!](https://tio.run/##hY@xTsMwEIZn8hRWp4QkVgtISDguKwyIoUJCQh2c1EkdXNs6nyuiKM8eTNuZ3nb3f9L/XS@Ooux337M6OAtI@rjTgErTNpgGlTX0liUu1Fo1pNHCe/ImlCFjQuJ4FBjvH0bA8O4kCLRQbRCU6dak5bMv1@OrQdlJIMiXRc1XBfCHJWstpCzP6@r@kWUIw4g5R@oEeBn51Bd1xoDXFTzXT8CmVhmh9TA21qAyQbIJJAYwBCnac1@KBWRsmtlJ7CJ88TtatSOHqJ2e2a8tEdD5bExuNoNHeaA2xPYYoTZpS4VzekgXnz@LLGP/M6u760z@EvbXqXIvtbYn7u@DKZnmXw "Java (JDK) – Try It Online")
Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904).
[Answer]
# [C (gcc)](https://gcc.gnu.org/) with `-lgmp`, ~~231~~ 225 bytes
* -6 thanks to ceilingcat
Uses GMP in case of large values.
```
#import<gmp.h>
f(s,t,b,r,g)char*s,*t;{mpz_t x,y;mpz_inits(x,y,r=0);t=s;g=*s;for(g-43&&g-45?g=0:(t=++s);*t;)r+=!isalnum(*t++);for(b=36;b>1&!r&&!mpz_set_str(y,s,b);b--)mpz_add(x,x,y);printf("-%s"+(g!=45),mpz_get_str(0,b+1,x));}
```
[Try it online!](https://tio.run/##PZLLbsMgEEX3/grsNhbYuLKbpFJKSaWu2kWzrlRVkR8xRvJLgNM8lF@vC05sFuhcmLkjZkgDlqZ9f8erthHqhVXtQ7G2ciixwgkWmKG0iIUnsafIuWpPWwUO@EgM8ZorCbXCgoaIKCoJo54keSMgCxZz19X78pXR8Bkq6vsSEW2ChE9tLuOy7iroKd9HQ0JC508kWUeuLVzXNvZyp7ZSCXjEEieIJEGAzHGcZbqmropIK3itcugEM@n4kNl0sUTYxLBbaogTP8IHhMil16GginkN9w3PEDhbAJiXAU9@/1CjAHC@Dg6@0mlYo4oeR/rsSsXfYrmbrvbRiOw4kv/eFRNPFCfpiEGxK8tmVE092W3izRTzUeemxZPrkAN@G1Fm49F9@LBa3USo9wsGnu6xpdE01YwEaA3aTk/KcdD13QCMnZtJQNfA0VkKkeEmv83EmFmX/i/Ny5jJPij1z/gH "C (gcc) – Try It Online")
Ungolfed:
```
#import<gmp.h>
f(s,t,b,r,g)char*s,*t;{
mpz_t x,y;
mpz_inits(x,y,r=0);
t=s;
g=*s; // get sign (if any)
for(g-43&&g-45?g=0:(t=++s); // advance past sign (GMP only parses unsigned)
*t;)r+=!isalnum(*t++); // check for non-digit characters
for(b=36; // start at base 36
b>1&& // end at base 2 if it gets this far
!r&& // only parse valid strings
!mpz_set_str(y,s,b); // stop when the parse fails
b--) // base worked: go to next-lowest base
mpz_add(x,x,y); // add the parsed value to the sum
printf("-%s"+(g!=45),mpz_get_str(0,b+1,x)); // print the sum in lowest base, adding sign if needed
}
```
[Answer]
# [Julia 1.0](http://julialang.org/), 84 bytes
```
!a=string((l=2:36 .|>b->try parse(Int,a;base=b)catch;0end)|>sum;base=1+argmax(l.>0))
```
[Try it online!](https://tio.run/##VY/NboMwEITvfgoH5QAKIJuGKD@CQ6VKzaE597oGE7sxhoJpSZV3pzb00pUsfbM7Hq8/BiWBjtO0gqw3ndRX31dZcnza4fiRsyg33R230PXcP2sTwolBzzMWFGAKcSJcl8Ej74d66dMNdNcaRl/FOQmCqWo6LLHUuONQKql57wcI24KQjy3OcN8qaXwZYg9HOfaWIbODFczY2o2M0r63BpzleM3@LLKyrlWGbcqs/3lfxpYXhpdH7IXOsVyxqyJ7pvfRPfWU9OhnLqcWQjRxghJXCXoblJHP9luuuf@EbbVTMJSIflHXgbZF17ujO0eb10E43NJmQJsZhUDACkfpnqUMRYIr1Tgd3UhyqAVq9Bwt6jpFF7g4vlGhUHTWldTSzOER3ZUybcQtQUvAd9Op0k0IWpP4cFiQxGSGXw "Julia 1.0 – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 325 bytes
I was rewriting [@naffetS's Ruby answer](https://codegolf.stackexchange.com/a/258592/110802) in Scala.
\$ \color{red}{\text{But the scala code fails on 4 cases. Any help would be appreciated.}} \$
---
Golfed version. [Try it online!](https://tio.run/##XZPfbpswFMbv@xRH1i7slaCQf2saudIyTdqktb3ozaRlFwZMcDE2waZtEuVyd3uE7eX6IplNooJmJGR@h@87x5yDSZhkRx0/8sTCLRMK@IvlKjXwsapgf0x5Bhk21w@2FmpN6P6JSZDUhFZ/08@8/sQMX3i2pGgYjcaT6ezD1ZzFiROuc/FYyFLpalMb2zw9v2x3yAuFsU5Tg76@r6zQ6sdXZX/SO61OVjXFI7AaxjMSZpLZW1btY3ojMizDTNdMSpzQm2VoWcFxTMJEK@sqNzghhLQFbuhSrJ0pNkFMFk5owppXkiUco0sUIET69VO6cY@nEzo/stdUh7r@LA3HD7r0Ocii3WzIgTsKvtTeLjRNuag7Dx2uub0/GYwIORx9TSmzDCj4w@MLcAuj7y8oADQeGcCxqwPGk8F4FoBrwvkxAJZZXoP0pSbM@BYgEpzlu3Z5i9MO8HgGwoDNOWgltycXmzMLz7ouTNBGVFPGzvItSSt5bIyF1dlnhXpJopFPEA39GnX4tpFWLJ2Bj15t2CSbSdakPd1T5EOsqjq23nq05R25/NLknk0i3fRoy/K8I26gPJpexdO4o4OcS6l9YFAMR/OyJ3BtaT3KctrBO3bnYRHlsmfyVWVCCdvWNohmqZjqvOgdtU3iv6BM/SvDLvJuGM7nZ@YQuXA33@awZO7fgcR/X7wNYEeA3rQaPwjGTUGGt@QNFA7sQlNJYTGC1Qq78cw5S9sXDFwCctd7190hDMCEkqu1zYnjxX@xohfDIgPsUlEoCKDXP78QtAOLXv/@bqs9@H@JsyTHlRtaKxW5OBz/AQ)
```
def f(s:String)={val l=s.toLowerCase;val B="0123456789abcdefghijklmnopqrstuvwxyz".toList;var o:Option[Int]=None;val r=(2 to 36).flatMap{b=>if(l.forall(c=>B.take(b).contains(c))){val q=BigInt(s,b);if(s.replace("+","").toLowerCase==q.toString(b)){o=o.orElse(Some(b));Some(q)}else None}else None}.sum;r.toString(o.getOrElse(2))}
```
Ungolfed version. [Try it online!](https://tio.run/##dVPLbtswELz7KxZED2RjC5b8aBzABZqgQAM0ySGXAnUPlERZiihRFqkkduFjb/2E9ufyI@6Sciy1QOULPbM7s1zu6ohLfjio8EFEBm54VoJ4NqKMNXyoKvg@AIhFAgnVF3Bv6qxcs9cDLB0N8MhrUBdwV5lMlV@vS/MNqVtViiMrIeRaXKW81kiQsR9MprP5u/MFDyMUX6fZQy6LUlWbWpvm8el5uyOeUZ8zbU4KuikwlwZgFEzmzEskNzccC4QQlu9dGECWANU2Uz2J@go9vUTVXEoaoTeGdXV4hueChsyLVGnw0tqFMMaOV3q13aDpZbbGO1E9hJCdyNaqFpXkkaDkjAyBENb3huUSNgi0zUKvvjaAQmXlqfqj1ILeq8JWw3q8gzYdsgeBkX9JnFrs@MF/4npRbczew2YO3BEPXYXKWwtz1xYUuFr2Nsq2IeaGY732RahLpOTLs73yJNBAbVdhMh1N5kPA@Tn@HQJPjKhB2oZEXNvRIWx4TN@5z0q0J6CTOWQaTCpAlXLbqpiUG3hSdY7Nt0zZFCFKnkxcykOjDayOOivSM/EDa@CP7Rd08E0jTXaJApY93/BpMpe8iXt5j76leFV12Hproa3okLNPTWqxqa@aHuqwNO0QnHILzc7DWdiho1RIqSwxysfBougl4IM5jaKYdeAtv7Vg7qeyJ3JdJlmZGVfbyJ/H2Uylee@qzsR2UMY2ZNwxb8beYnHEEGL2qe0ze4Xbqsj2l26HsGOv@@XWEKcgoVt2AnIEdp6uZGYogdWK4hKkgsfteMEZEPy9xdcdwwi0J0W5NilDPP@Hy3scddtlFyhnQF5@/SDtUJOX3z9dtXu72IJHKa1wdI0s2WB/OPwB)
```
object Main extends App {
def f(s: String): String = {
var o: Option[Int] = None
val baseChars = "0123456789abcdefghijklmnopqrstuvwxyz".toList
val sum = (2 to 36).flatMap { b =>
if (s.toLowerCase.forall(char => baseChars.take(b).contains(char))) {
val q = BigInt(s, b)
if (s.replace("+", "").toLowerCase == q.toString(b)) {
o = o.orElse(Some(b))
Some(q)
} else {
None
}
} else {
None
}
}.sum
sum.toString(o.getOrElse(2))
}
val data = List(
("Xx", "32s (base 34-36, in base 34, after lowercasing)"),
("zzzzzz", "zzzzzz (36 is the only base that works, the number in base 36 is just \"zzzzzz\")"),
("12", "1000002"),
("MultiBase", "8qa4f6laud"),
("1v1", "app"),
("gy", "ye"),
("+Huh", "41ou"),
("+h", "hh"),
("abc", "58b5b"),
("-hello", "-k029mh"),
("one", "hmm5"),
("NaN", "k1hl"),
("-Infinity", "-16di5ohk2"),
("hello world", "0"),
("$0.99", "0")
)
data.map { case (y, z) =>
val s = f(y)
val k = z.split(" \\(").head
s + " " * (30 - s.length) + k + " " * (30 - k.length) + (if (s == k) "✅" else "❌")
}.foreach(println)
}
```
] |
[Question]
[
This question is tricky (and in particular harder than [Which big number is bigger?](https://codegolf.stackexchange.com/questions/184734/which-big-number-is-bigger)), for those who like more challenging puzzles.
**Input**
Integers a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 each in the range 1 to 10.
**Output**
```
True if a1^(a2^(a3^(a4^a5))) > b1^(b2^(b3^(b4^b5))) and False otherwise.
```
^ is exponentiation in this question.
**Rules**
This is code-golf. Your code must terminate correctly within 10 seconds for any valid input on [TIO](https://tio.run/#). If your language is not on TIO, the code should finish under 10 seconds on your machine.
You can output anything Truthy for True and anything Falsey for False.
**Test cases**
Recall that by the rules of exponentiaon, a1^(a2^(a3^(a4^a5))) == a1^a2^a3^a4^a5.
```
10^10^10^10^10 > 10^10^10^10^9
1^2^3^4^5 < 5^4^3^2^1
2^2^2^2^3 > 10^4^3^2^2
6^7^8^9^10 is not bigger than 6^7^8^9^10
10^6^4^2^2 < 10^6^2^4^2
2^2^2^2^10 > 2^2^2^10^2
10^9^8^7^6 < 6^7^8^9^10
3^1^10^10^10 > 2^1^10^10^10
9^10^10^10^10 < 10^9^10^10^10
```
**New test cases from Kevin Cruijssen**
```
[10,10,10,10,10, 10,10,10,10,9] #true
[2,2,2,2,3, 10,4,3,2,2] #true
[2,2,2,2,10, 2,2,2,10,2] #true
[10,10,10,10,10, 9,10,10,10,10] #true
[3,2,2,1,1, 2,5,1,1,1] #true
[2,2,3,10,1, 2,7,3,9,1] #true
[7,9,10,10,10, 6,9,10,10,10] #true
[3,2,2,2,2, 2,2,2,2,2] #true
[8,3,1,2,1, 2,2,3,1,1] #true
[2,4,2,1,1, 3,3,2,1,1] #true
[5,4,3,2,1, 1,2,3,4,5] #true
[1,2,3,4,5, 5,4,3,2,1] #false
[6,7,8,9,10, 6,7,8,9,10] #false
[10,6,4,2,2, 10,6,2,4,2] #false
[10,9,8,7,6, 6,7,8,9,10] #false
[1,10,10,10,10, 1,10,10,10,9] #false
[2,4,1,1,1, 2,2,2,1,1] #false
[2,2,2,1,1, 2,4,1,1,1] #false
[2,5,1,1,1, 3,2,2,1,1] #false
[4,2,1,1,1, 2,4,1,1,1] #false
[2,4,1,1,1, 4,2,1,1,1] #false
[2,3,10,1,1, 8,3,9,1,1] #false
[8,3,9,1,1, 2,3,10,1,1] #false
[2,4,1,1,1, 3,3,1,1,1] #false
[2,2,1,9,9, 2,2,1,10,10] #false
[2,2,1,10,10, 2,2,1,9,9] #false
[1,1,1,1,1, 1,2,1,1,1] #false
```
[Answer]
# Ruby, 150 bytes
See [revisions](https://codegolf.stackexchange.com/posts/185623/revisions) for previous byte counts.
```
->a,b,c,d,e,f,g,h,i,j{l=->s,t=c{Math.log(s,t)};y,z=l[l[g,b]]-d**e+l[h]*i**=j,l[l[a,f]*b**c,g];a>1?f<2?1:b<2||g<2?z>h:c<2||d<2?l[z,h]>i:y==0?a>f:y<0:p}
```
-10 bytes thanks to *@ValueInk*
+16 bytes thanks to *@RosLuP* for bugs.
[Try it online](https://tio.run/##dVLbcoIwEH3vV3T6pOnaGogoaPAL@gVMHgC5qJmpo/iAl2@nCwkQ1E4YkpOzOZs92eM5Kqs9ryZ@CBHEsIEEUsgghy3srpJP/BMUPL7@hEX@JX@zEcLxfVnChctABhlEQkw2hCSfMsgF2RLCd1AzIaSCRITEkIll6NN1urLW1ItW1u2W4fLi515cgw0CGVwgF/7WKzmfrkM/9crV1Dvcq8O5OI0@iuM5@abex/itwTi97wM6hf8@VzQRFqhh13sMJwRDBvf7hXgl65pIRdjqBA4LZs1Me9UmV83Mcem2zNzUcQxgKg6GIha1XpNMa7eCM12PuoWNaGZeX5fUAvzZbSY6IB4uosvpNXRG7XrzGGkoT8nDW3SxYCi8yMieMra57D6oLlq/YFccdAUrwkF/F8rHftkpOhisLXBwYsbbuhg7x92nU8MeetFLTFdotc6YraQINuwG7QXYwxOsM@vpRJuDGd43hG4rqszpmQ72rUdF9Qc).
[Compare different base powers-towers (of 'height' five)?](https://math.stackexchange.com/a/3227712)
### Ungolfed code:
```
-> a, b, c, d, e, f, g, h, i, j {
l =-> s, t = c {Math.log(s, t)}
i **= j
y = l[l[g, b]] - d ** e + l[h] * i
z = l[l[a, f] * b ** c, g]
if a == 1
return p
elsif f == 1
return 1
elsif b == 1 || g == 1
return z > h
elsif d == 1 || c == 1
return l[z, h] > i
elsif y == 0
return a > f
else
return y < 0
end
}
```
### Code breakdown:
```
l =-> s, t = c {Math.log(s, t)}
```
This is the base `t` logarithm, which will be used to reduce the size of the numbers we are comparing. It defaults to base `c` when only one argument is given.
```
i **= j
y = l[l[g, b]] - d ** e + l[h] * i
z = l[l[a, f] * b ** c, g]
```
This updates `i = i ** j` since `i` never gets used on it's own, and `y` is the result of logging `b^c^d^e == g^h^i(^j)` twice and moving everything to one side. We then let `z = l[a, f] * b ** c` as the log base `g` of the log base `f` of `a ** b ** c`.
```
if a == 1
return p
elsif f == 1
return 1
```
`1^b^c^d^e = 1` is never greater than `f^g^h^i^j`, and likewise, `a^b^c^d^e` is always greater than `1^g^h^i^j = 1` if `a != 1`. Note that `return p` returns `nil`, which is falsey, and `return 1` returns `1`, which is truthy.
```
elsif b == 1
return z > h
```
If `b == 1` or `g == 1`, then this reduces to comparing `a ** b ** c` to `f ** g ** h`, which is done with two logs to both sides.
```
elsif d == 1 || c == 1
return l[z, h] > i
```
This compares `a ** b ** c` with `f ** g ** h ** i` by rearranging it as `log[log[b ** c * log[a, f], g], h]` compared to `i`. (Recall that `i **= j` in the beginning and `z = log[b ** c * log[a, f], g]`.)
```
elsif y == 0
return a > f
else
return y < 0
end
```
This compares the 4 highest powers after logging both sides twice. If they are equal, it compares the base.
[Answer]
# Python 2, ~~671~~ ~~612~~ ~~495~~ ~~490~~ ~~611~~ 597 bytes
```
lambda a,b:P(S(a,b))>P(S(b,a))if P(a)==P(b)else P(a)>P(b)
def S(a,b):
if a and a[-1]==b[-1]:
a.pop()
b.pop()
return S(a,b)
from math import*
L=log
E=exp
N=lambda m,n,x:N(m,n+1,L(x))if x>=1else N(m,n-1,E(x))if x<0else(m+n,x)
A=lambda a,n,x:(0,1)if a==1else(1,R(x,n)*L(a))if a<1else N(2,*C(L(L(a)),x,n-1))if n else(1,x*L(a))
def C(c,x,n):
if c*n==0:return(0if c else n,x+c)
z=R(x,n-1)
if z<=L(abs(c)):return(0,E(z)+c)
return N(1,*C(L(1-E(L(-c)-z)if c<0else 1+E(L(c)-z)),x,n-1))
def R(x,n):
try:exec'x=E(x)'*n
except:x=float('inf')
return x
P=lambda b:b and N(0,*A(b[0],*P(b[1:])))or(0,1)
```
-59 bytes thanks to *@EmbodimentOfIgnorance*
-117 bytes thanks to *@Neil*
+121 bytes for about five bug-fixes, all found by *@ngn*
Takes the inputs as two lists. ~~NOTE: Also works with larger lists or those of unequal length.~~ EDIT: No longer true; it still works if `P(a)` and `P(b)` result in different tuples, but if they are the same this updated code above only works with lists with a fixed size of 5 now.
[Try it online.](https://tio.run/##lVRbb5swFH4ev8LaHmKnzuQLAYzqSlXVPVVVte0tiyIgZmNKICJkov3z3bGBlLapugmEL@f7znduye6@@VWV4jHXPx43yTZdJyihaXyHv2FYCbmwu5QmhBQ5usMJ0foOp8Rs9sYdL@zJW5scdYTYQwiQ4KVco2Qx40utU7vE3ofk867aYeJ9SIdNbZpDXfZUL6@rLdomzS9UbHdV3Uy9G72pfnrX2rQ771b38W1pSdv4FsN6xukNbl1s7YXmLipnmHF6PRjOmb3H2zOgEe9SH9O0bjCj3KIS3dExp19xS0syvcFd0sn54FfQ6RW@wc5AWyviACXqiW3HcdW4wpmF2HoAJJuWWrO4Sxcze@NICEI4y4iHHrRTBY8O/3CuwVW6xxkhRxZk9EAcui/bLWi6iPjsGr6zjMwebEBZlzHiZ/ba3R7jdcF1GUJoTX0fm9Zkk1bbck2mpYdMm5ldE7c631RJgydFmU@eNFvvbihgGqeuy7cQ2vQSpwu2pFMYhwWPl4SQqna1fbSCjdk32NBhQHZ1UTZo8tXsD5smntDc9Z9OfjTfDllmzNqs4dZo/WSYWLIL/o@pi/we44L@JjCXI3/X7c5kjeN2VuBdZs0h2cCNHVZ7cVXVNaAGjB3nZFDwoHirVZlszWqFtEYfV6ttUpSr1Uer4pL4Xh8MRWjBIbend0mfXagleRevnp2P@C8JdI4CngoqqU/nAJ3DKuHMX7sVtHtkF0GHE6/dBTSkEVWd9OjwWpfRANxYJ7Q7CHt8W9l5HLanpG09QC6kwXvSLyt6sqAD2gmCJ9XL87cqOTbSEe2Ufvc4bdHvT/jzj7A@79Od8XsTXciufe95s7BBFHCf0OW@m/YiS5qiKlFe1ehntclNvT@OPazDL8Kn7HMUSCW5jBTzOWc8IPTYqa43Y7Dy2ZzzgCkR@CwI5uTlrA3gEMBcyjCSAj6CCcFVSOjLqf4XinqTIYAhRRBIX8yVAk7ElE9ed/ff8EOLB7QENONqHkVSMjn3mYpUVx1/1On30eOGj9FRGEIQXAjJQxEo2bsW/@H6rUAioTgLhYoCBq/k5OVEjcE8DHgUCGh/FIk5CwPyfLCe0NwGQujor@a09Vm/Hv8C)
**Explanation:**
Golfed version of [this answer on math.stackexchange.com](https://math.stackexchange.com/a/398184/368863), so all credit goes to *@ThomasAhle*.
To quote his answer:
>
> The idea is to represent power towers as a single floating point
> number with \$n\$ exponentiations: \$(x\mid n) := exp^n(x)\$. Normalizing
> \$x\in[0,1)\$, this format allows easy comparison between numbers.
>
>
> What remains is a way to calculate \$a^{(x\mid n)}\$ for any real,
> positive \$a\$. My Python code below is an attempt to do so, while being
> as numerically stable as possibly, e.g. by using the log-sum trick. My
> code runs in time proportional to the height of the tower (number of
> `apow` calls) and the iterated-log of it's value (number of recursive
> calls).
>
>
> I haven't been able to find two towers with values close enough to
> case my method to fail. At least for integer exponents. With
> fractional exponents it is possible to create very towers too close
> for my representation to handle. E.g. \$2^{2^{2^{2^0}}}<2^{2^{2^{2^{(1/2)^{2^{2^{2^2}}}}}}}\$
>
>
> I would be interested in suggestions to other types of counter
> examples, especially integer ones.
>
>
> It seems to me that for the problem to be in P, we need to
> non-numerical methods. It doesn't seem unlikely at all, that certain
> analytical cases are harder than P.
>
>
> **Examples:**
>
>
>
> ```
> powtow([2,2,2,2,2,2,2,2,2,2,2,2,2,2,4,2,2,2]) = (0.1184590219613409, 18)
> powtow([9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]) = (0.10111176550354063, 18)
>
> powtow([2,2,5,2,7,4,9,3,7,6,9,9,9,9,3,2]) = (0.10111176550354042, 17)
> powtow([3,3,6,3,9,4,2,3,2,2,2,2,2,3,3,3]) = (0.19648862015624008, 17)
>
> ```
>
> **Counter examples:**
>
>
>
> ```
> powtow([2,2,2,2,2,2,2]) = (0.8639310719129168, 6)
> powtow([3,2,2,2,2,2,2]) = (0.8639310719129168, 6)
>
> ```
>
>
Regarding the counter examples, he mentions the following in the comment-section:
>
> I believe if we bound the exponents so \$1<a<100\$ (or maybe a much larger upper bound) we can use my method for comparing the height 3 or 4 head of the tower. It should be strong enough to tell us if they are equal or one is larger. Plan B is to choose the highest tower. Plan C is the interesting one: At this point the values of the rest of the tower only matter if the heads are equal, so we can walk down the towers in parallel, stopping as soon as we see a differing value.
>
>
> Hence the main thing to be proven is that once the head of a tower exceeds a certain point, and the rest of the exponents are bounded (and equally numerous), we can simply look at the top differing value. It's a bit counter intuitive, but it seems very likely from the simple inequalities you get.
>
>
>
Since plan A and B are irrelevant in this challenge, since the height is 5 for both power-towers we input, plan C it is. So I've changed `P(a)>P(b)` to `P(S(a,b))>P(S(b,a))if P(a)==P(b)else P(a)>P(b)` with the recursive function `S(a,b)`. If `P(a)` and `P(b)` result in the same tuple, the `P(S(a,b))>P(S(b,a))` will first remove trailing values which are equal at the same indices, before doing to same `P(A)>P(B)` check on these now shorter lists.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~96~~ 104 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
3èI4èmU8.$`m©I7èI2è.n*I6èI1è.nI2è.n+Vнi0ë5èi1ë2ô1èßi¦2£`mIнI5è.n*I6è.nDI7èDi\1›·<žm*ë.n}®›ëXYQiнI5è›ëXY›
```
Port of [*@SimplyBeautifulArt*'s Ruby answer](https://codegolf.stackexchange.com/a/185623/52210), so make sure to upvote him!
+8 bytes as work-around, because \$\log\_1(x)\$ should result in `POSITIVE_INFINITY` for \$x\gt1\$ and `NEGATIVE_INFINITY` for \$x\lt1\$, but results in `0.0` for both cases instead in 05AB1E (i.e. test cases `[3,2,2,1,1,2,5,1,1,1]` (`POSITIVE_INFINITE` case) and `[2,4,1,1,1,3,3,1,1,1]` (`NEGATIVE_INFINITY` case).
Input as a list of ten integers: `[a,b,c,d,e,f,g,h,i,j]`.
[Try it online](https://tio.run/##yy9OTMpM/f/f@PAKT5PDK3JDLfRUEnIPrfQ0BwoYHV6hl6flaQZkGoKYEAHtsAt7Mw0OrzY9vCLT8PBqo8NbgJKH52ceWmZ0aHFCrueFvZ6mcI16eS4go1wyYwwfNew6tN3m6L5crcOr9fJqD60DChxeHREZmAnRAeUCqf//o410THQMwdAYCMGsWAA) or [verify all test cases](https://tio.run/##dVG9SsRAEH6V47A6l3D7kz8QrrkXsFCUGDiFK1LkLAQhxYGVtfgCFoJEAlaCIJxFFvt7hnuROLuzu9kEzAR25tuZb2b2u727vinW3X0ln9AW08nh8XkyXXRc1pWQdXmWBEersn2vYgCYrIPNrIrApcpF4Ph8vyvmsgllXVDZMPkJl/KlaN9Y@7oqq/2uCl1hsFkqqmVxRQ8P3@3Xye9POZNNsNm2HwDI5uLytMAKE8LRbeEjXZbROfnvT3OSMYLGFSDggMCDAewdwMcMfgTXHHPBGAn1SQ2Z5ldwDG6q4dgvj7zAEQ0M0ETR6AaG0tAL05Tr@RENzTY4DIco1Ly078m8QFdQB9g1qNvZPIKrnBOu7iw3cf0AjWDLBBfqXWSK9LAMr/TkiKeQFQM0zB8qNlZO4IhWIffWdmnhKWCWI9zLtc82zrW8wnsEpyAlCSqoYef3Eg85OMrkZqOQntoZzMN7EXE5uL4zNmJR5gk2llYMpbXcvM/Qk2s6r4wPy5hrz62X538).
**Explanation:**
```
3èI4èm # Calculate d**e
U # And pop and store it in variable `X`
8.$`m # Calculate i**j
© # Store it in variable `®` (without popping)
I7èI2è.n # Calculate c_log(h)
* # Multiply it with i**j that was still on the stack: i**j * c_log(h)
I6èI1è.nI2è.n # Calculate c_log(b_log(g))
+ # And sum them together: i**j * c_log(h) + c_log(b_log(g))
V # Pop and store the result in variable `Y`
нi # If `a` is 1:
0 # Push 0 (falsey)
ë5èi # Else-if `f` is 1:
1 # Push 1 (truthy)
ë2ô1èßi # Else-if the lowest value of [c,d] is 1:
¦2£`m # Calculate b**c
IнI5è.n # Calculate f_log(a)
* # Multiply them together: b**c * f_log(a)
I6è.n # Calculate g_log(^): g_log(b**c * f_log(a))
D # Duplicate it
I7è # Push h
Di # Duplicate it as well, and if h is exactly 1:
\ # Discard the duplicated h
1› # Check if the calculated g_log(b**c * f_log(a)) is larger than 1
# (which results in 0 for falsey and 1 for truthy)
·< # Double it, and decrease it by 1 (it becomes -1 for falsey; 1 for truthy)
žm* # Multiply that by 9876543210 (to mimic POSITIVE/NEGATIVE INFINITY)
ë # Else:
.n # Calculate h_log(g_log(b**c * f_log(a))) instead
} # After the if-else:
®› # Check whether the top of the stack is larger than variable `®`
ëXYQi # Else-if variables `X` and `Y` are equal:
нI5è› # Check whether `a` is larger than `f`
ë # Else:
XY› # Check whether `X` is larger than `Y`
# (after which the top of the stack is output implicitly as result)
```
If anyone wants to try and golf it further, here is [a helper program](https://tio.run/##RY5NTsMwFITXySmeLJYWEuV3g1DZtVdASDwnL7VLIFHsInXHOdiCUA7Agk03zQV6Bi4Spk4KlkYafZp548qzcdL3aqpv6Un42ZOpgqUXLlfiiRuheuWt5OSl5oaDlGsKFQUr5ANnj@n00ANaxwKjRzW7Bq3S@ZAqnapcy7W6Oe3a2VnXJj@vb2BOL8Gujo8eRmB1BnCJ0KRrD3ChDeAF4Mk/3OeQSRJ4ht9toi1gz0ec5THzhVYy38d0EYMzBGg8Y@Lg9nOyff@bG8biCTv8Zlgp4rmP7nu3ofjmuu/vFCutDJRBOSRQAS0gCzloqe5/AQ) I've used to get the correct variables from the input-list.
[Answer]
## C, ~~168~~ 180 bytes
C port from Kevin Cruijssen's answer.
```
#define l(a,b)log(a)/log(b)
z(a,b,c,d,e,f,g,h,i,j){float t=pow(i,j),y=l(l(g,b),c)-pow(d,e)+l(h,c)*t,z=l(l(a,f)*pow(b,c),g);return~-a&&f<2|(b<2|g<2?z>h:c<2|d<2?l(z,h)>t:y?y<0:a>f);}
```
[Try it online](https://tio.run/##dVHbbsIwDH3nKxDTUMJcjbbcyvVtX7DHvYTSFqZQUAmagLFPX@fm1haYUjX2OfaxY4dOEoZ5/rSK4k0aNTlhsKR8lxBGX4trSRvnAoMQVhBBDAmsYQOf9BLzHRNNMdvvvkgBwGnGCScJ5kNInQLGDPrCyRr9joCz5BnEtFOQKEkhoZMsEscs/XFYux1PvW@yxF8y9Rbn@Xocor1Cm5MzrOlcjE@L07Q7ZvOYTq65eNzYPtukIiat59VH2oLH3WN6Y8s2KaGXxv4oDqT1nh2jFp00BHG78N8XyAAP1PELqIcXOjUC4dJ4pBlUPRngq3g8HvTl7VpJWacghmgGmhhWRQYVpyJXOxIfFWKykBa2ZXq6vC/fY/C@fp9qzEevr/XdsrpXcZBV83xj/GAGalLBykl8gA8aqc5L04xrIDvyFCnbM0yAkUMEb3Pqy7pfWk@N1aymMmDzvl5t8HoN4NfizZzu442@jdC4Xp8LI7U@TViv3PCtkq82VOnUxZTA9GO3XfHBRpmh2GO7uua/YcxZcsgdvv0D)
[Answer]
# APL(NARS), chars 118, bytes 236
```
{p←{(a b c d)←⍵⋄a=1:¯1⋄b=1:⍟⍟a⋄(⍟⍟a)+(c*d)×⍟b}⋄(=/(a b)←{p 1↓⍵}¨⍺⍵)∧k←(∞ ∞)≡(m n)←{p(3↑⍵),*/3↓⍵}¨⍺⍵:(↑⍺)>↑⍵⋄k:a>b⋄m>n}
```
The function above call z, in "a z w" would return 1 if the number in a is greater than the number in w,
otherwise it would return 0.
If I have
```
f(a,b,c,d,e)=a^b^c^d^e
```
It will be f(aa)>f(bb) with both aa and bb array of 5 positive numbers if and only if
(if the a>1 of aa and bb) log(log(f(aa)))>log(log(f(bb))) one has to use the log() laws:
```
log(A*B)=log(A)+log(B)
log(A^B)=B*log(A)
```
for build v(aa)=log(log(aa))=v(a,b,c,d,e)=log(log(a))+log(b)*(c^(d^e))={p(3↑⍵),*/3↓⍵}
function and so the exercise is find when v(aa)>v(bb).
But there is a case where v(aa) and v(bb) are both infinite (APL has end the float space)
in that case i would use the unsecure function
```
s(a,b,c,d,e)=log(log(b))+log(c)*(d^e)={p 1↓⍵}
```
that i not fully understand if it is ok and it not take in count a parameter too...
test:
```
z←{p←{(a b c d)←⍵⋄a=1:¯1⋄b=1:⍟⍟a⋄(⍟⍟a)+(c*d)×⍟b}⋄(=/(a b)←{p 1↓⍵}¨⍺⍵)∧k←(∞ ∞)≡(m n)←{p(3↑⍵),*/3↓⍵}¨⍺⍵:(↑⍺)>↑⍵⋄k:a>b⋄m>n}
10 10 10 10 10 z 10 10 10 10 9
1
1 2 3 4 5 z 5 4 3 2 1
0
2 2 2 2 3 z 10 4 3 2 2
1
10 6 4 2 2 z 10 6 2 4 2
0
2 2 2 2 10 z 2 2 2 10 2
1
10 9 8 7 6 z 6 7 8 9 10
0
10 10 10 10 10 z 10 10 10 10 9
1
2 2 2 2 3 z 10 4 3 2 2
1
2 2 2 2 10 z 2 2 2 10 2
1
10 10 10 10 10 z 9 10 10 10 10
1
3 2 2 1 1 z 2 5 1 1 1
1
2 2 3 10 1 z 2 7 3 9 1
1
7 9 10 10 10 z 6 9 10 10 10
1
3 2 2 2 2 z 2 2 2 2 2
1
3 10 10 10 10 z 2 10 10 10 10
1
8 3 1 2 1 z 2 2 3 1 1
1
2 4 2 1 1 z 3 3 2 1 1
1
5 4 3 2 1 z 1 2 3 4 5
1
1 2 3 4 5 z 5 4 3 2 1
0
6 7 8 9 10 z 6 7 8 9 10
0
10 6 4 2 2 z 10 6 2 4 2
0
10 9 8 7 6 z 6 7 8 9 10
0
1 10 10 10 10 z 1 10 10 10 9
0
2 4 1 1 1 z 2 2 2 1 1
0
2 2 2 1 1 z 2 4 1 1 1
0
2 5 1 1 1 z 3 2 2 1 1
0
4 2 1 1 1 z 2 4 1 1 1
0
2 4 1 1 1 z 4 2 1 1 1
0
2 3 10 1 1 z 8 3 9 1 1
0
8 3 9 1 1 z 2 3 10 1 1
0
2 4 1 1 1 z 3 3 1 1 1
0
2 2 1 9 9 z 2 2 1 10 10
0
2 2 1 10 10 z 2 2 1 9 9
0
1 1 1 1 1 z 1 2 1 1 1
0
1 1 1 1 2 z 1 1 1 1 1
0
1 1 1 1 1 z 1 1 1 1 1
0
9 10 10 10 10 z 10 9 10 10 10
1
9 10 10 10 10 z 10 10 10 10 10
0
10 10 10 10 10 z 10 10 10 10 10
0
11 10 10 10 10 z 10 10 10 10 10
1
```
[Answer]
# Java 8, ~~299~~ ~~288~~ ~~286~~ ~~252~~ ~~210~~ ~~208~~ 224 bytes
```
Math M;(a,b,c,d,e,f,g,h,i,j)->{double t=M.pow(i,j),y=l(l(g,b),c)-M.pow(d,e)+l(h,c)*t,z=l(l(a,f)*M.pow(b,c),g);return a>1&&f<2|(b<2|g<2?z>h:c<2|d<2?l(z,h)>t:y==0?a>f:y<0);}double l(double...A){return M.log(A[0])/M.log(A[1]);}
```
Port of [*@SimplyBeautifulArt*'s Ruby answer](https://codegolf.stackexchange.com/a/185623/52210), so make sure to upvote him!
-14 bytes thanks to *@SimplyBeautifulArt*.
+17 bytes for the same bug-fixes as the Ruby answer.
[Try it online.](https://tio.run/##pVVNb6MwEL33V1g5VHZxaICkaZImVS97S3el7q3qwYD5yFKIwGmVdvPbs8PwESDhtHL08HjGb8aPCd6IDzHcuH@OTiSyjKxFGH9fERLGSqaecCR5zk1Cftob6SjiUPAQwXO0ER1EF1Eieog@YoAYIm7YAqgOVwBroQKyXgDv7S3RpsTeK5kRlRAVSDSGTrKLFUQ@k5gsyZEKbnOHu1xyj/scaPmGDVffbrKzI0nUcq1vk0@ar/L9MqIR9bnNuMOGhQM2Mi2iAazcKP6FEYJ77KZwAzfjPlukUu3SmIiVcX3tPZh/qQ3gP5iPX6tg7sDchXlEv3jAVmq@Xy5Hj2LlzfcPI7Y4LMpiIlpMdF1/Yt8l5VqPEp8@vY7e2G01N95g1xEOuYXw0CGZEgoeH0noknd4EfRFpWHsv74RkfoZK14ECPY73algP0cTdFPUGPG@3wxFL@NMXgwr94zhAcYlP3hPk2ZAl7xpNeOsYjcMk0/waXTzYA25fwrTWds/bTLfNYzzHK3RdN/nGbCIMlu3hHFZoYU6dNyTUp7iCBZYk3Zu41Sg2TDaHEbtqeQwztUsda65Rtwqg172mZLverJT@hYaQUUxLT1VJ/wQUSZbnVBVy@sTNDPegdr3hZ6naaekO1TGLGJQpk7ADPZNwdfD0O7A3k4cF3pUjXbeIJX440v9U2rLrUu7qzfbu7vKPb70VurWNPh90Zptf714auIeeqtou/OjGUAwqyrvtk1jmdfBHYXrYfYlyEejAXubd9zTvFV@6xSKB29nahBZXSL80Dc/abjnf66P4gNYfBThsviV/yfgchDagA80G9FBdBGlNiAidslA89D2EQPEEHHT@z8r2YFhoKdyKwXINhmWq3okY18FlDEtlp94Z1Kmx7pz8ZYqxTgc/wE)
**Explanation:**
```
Math M; // Math M=null on class-level to save bytes
(a,b,c,d,e,f,g,h,i,j)->{ // Method with ten integer parameters and boolean return-type
double t=M.pow(i,j), // Temp `t` = `i` to the power `j`
y=l(l(g,b),c) // Temp `y` = `c`_log(`b`_log(`g`))
-M.pow(d,e) // - `d` to the power `e`
+l(h,c)*t, // + `c`_log(`h`) * `t`
z=l(l(a,f)*M.pow(b,c),g);// Temp `z` = `g`_log(`f`_log(`a`) * `b` to the power `c`)
return a>1&& // If `a` is 1:
// Return false
f<2|( // Else-if `f` is 1:
// Return true
b<2|g<2? // Else-if either `b` or `g` is 1:
z>h // Return whether `z` is larger than `h`
:c<2|d<2? // Else-if either `c` or `d` is 1:
l(z,h)>t // Return whether `h`_log(`z`) is larger than `t`
:y==0? // Else-if `y` is 0:
a>f // Return whether `a` is larger than `f`
: // Else:
y<0);} // Return whether `y` is negative
// Separated method to calculate `B`_log(`A`) for inputs `A,B`
double l(double...A){return M.log(A[0])/M.log(A[1]);}
```
] |
[Question]
[
# Goal
Write a program or function that takes a positive integer `n` and randomly generate a legal series of pitches (henceforth called a Pitch string) of length `n`.
# Input
A non-zero, positive integer `n` <= 100
# Output
Return a random string, or list of characters, that represent a possible, valid pitch string of length `n`. The characters used will be:
* **B** - Ball. If you accumulate 4 of these, the batter is walked and finished batting.
* **S** - Strike. If you accumulate 3 of these, the batter is out and finished batting.
* **F** - Foul. Will also increase the Strike count but cannot get the batter out. I.e., you cannot have a Foul be the last pitch in a valid string. Any fouls past two strikes/fouls will not increase the Strike count (the batter already has 2 strikes at that point and a 3rd would get him out).
* **H** - Hit. The batter has hit a ball into play and is finished batting.
(This is simplified slightly but don't you worry about that)
Valid pitch strings are those that end in a strike-out, a walk, or a hit.
I.e., an **invalid** pitch string has either
* additional pitches after the 4th Ball, 3rd Strike, or Hit
* terminated before generating a 4th ball, 3rd strike, or Hit.
# Rules
* Your program must be able to produce all possible results for a given input.
* Your program does not have to be uniformly random but still must follow the previous rule.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
# Examples
```
Input => Possible Outputs
1 => [H] #Can only end with a hit
2 => [S,H], [B,H], [F,H] #Can only end with a hit
3 => [S,S,S], [F,F,S], [B,B,H], ... #Can now strike-out, otherwise must end with a hit
4 => [B,B,B,B], [S,B,S,S], [B,F,S,S], [B,B,B,H], ... #Can now be walked, struck-out, or get a hit
6 => [S,B,S,B,B,H], [F,F,F,F,F,S], ... #Can now have a full-count (3 balls, 2 strikes) before finishing
Input => Invalid Outputs
1 => [S], [B] #Not enough for a strike-out/walk
2 => [S,S] #Not enough for a strike-out/walk
2 => [H,H] #Batter has already scored a hit
3 => [S,S,F] #Fouls will not cause a strike-out
4 => [S,S,S,H] #Batter has already struck out
5 => [B,B,B,B,B] #Batter has already walked
```
[Answer]
# [Python 2](https://docs.python.org/2/), 128 bytes
```
from random import*
def g(n):
x=i=S=0;r=''
while(S>2)+x<3>=i-S:x=randint(0,3);r+='BFSH'[x];S+=x>0;i+=1
return(i==n)*r or g(n)
```
[Try it online!](https://tio.run/##TY47D4IwFIV3fsXdaCkmPOIg9TI4GPeOhBgTCjSRC7nBWH89Uienc4bvPJbPOs5UbFvP8wT8oG4XNy0zr0nU2R4GQbKKwKNDg5lmjOMI3qN7WmHqQip/Lmt0B1N5DGlHq8jSUmpWGF@u5hY3vtVGoa8z7RTmEbBdX0zCIZJMGGb@bWz9bggchRODFXl6CrsL741AaRMYCMz9jznKdvsC "Python 2 – Try It Online")
Randomly generate the pitch string until the batter is done, output it if it turns out the right length, and otherwise try again from scratch.
---
**[Python 2](https://docs.python.org/2/), 136 bytes**
```
from random import*
def g(n):
B=H=F=S=0;r=''
while(F+S<3or'S'>x)>B/4+H:x=choice('BHFS');r+=x;exec x+"+=1"
return(len(r)==n)*r or g(n)
```
[Try it online!](https://tio.run/##TY69DoIwFEZ3nuLGpa0lUfwZBC8DA2FnNMYYKNAEbskNxvr0CE5O3xlOcr7xM3WODvPcsBuAn1QvY4fR8bQNatNAK0nFAWRYYI4l7hNGIQJ4d7Y3Mtfl9ehYlCL1Ks12J13EHqvO2cpIkRV5KVTCGn1ivKnA643GaBMAm@nFJHtDkhUiqS2D419rbhYgsLSeaY2MwsvaH9nSBBTeVgdW5/HnnNV9/gI "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~44~~ ~~50~~ 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
[*Crossed out ` 44 ` is no longer 44 :)*](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44)
```
[õ0U.µ["BFSH"3ÝΩ©è«®ĀX+U¼X2›®+3@¾X-3›~#}I¾Q#
```
Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/180491/52210), so make sure to upvote him as well if you like this answer!
+6 bytes due to a bug-fix, and after that -6 bytes again thanks to *@xnor* by porting his way more efficient fix in comparison to my temporary work-around, as I was expecting. ;)
[Try it online](https://tio.run/##AUgAt/9vc2FiaWX//1vDtTBVLsK1WyJCRlNIIjPDnc6pwqnDqMKrwq7EgFgrVcK8WDLigLrCriszQMK@WC0z4oC6fiN9ScK@USP//zk) or [verify some more random outputs](https://tio.run/##AV4Aof9vc2FiaWX/OUx2IlNpemU6ICI/eSwxMEb/W8O1MFUuwrVbIkJGU0giM8OdzqnCqcOowqvCrsSAWCtVwrxYMuKAusKuKzNAwr5YLTPigLp@I315wr5RI/99LH3Ctj//).
**Explanation:**
```
[ # Start an infinite loop:
õ # (Re)set the result-string to an empty string ""
0U # (Re)set variable `X` to 0
.µ # Reset the counter_variable to 0
[ # Start an inner infinite loop:
"BFSH" # Push string "BFSH"
3ÝΩ # Push a random integer in the range [0,3]
© # Store this random integer in variable `r` (without popping)
è # Index it into the string "BFSH"
« # Append it to the result-string
®Ā # If `r` is NOT 0:
X+U # Increase `X` by 1
¼ # Increase the counter_variable by 1
X2›®+ # Calculate `X`>2 (1 if truthy; 0 if falsey) + `r`
3@ # Check if this is larger than or equal to 3
¾X- # Calculate counter_variable - `X`
3› # Check if this is larger than 3
~ # If either of the two checks above is truhy:
# # Stop the inner infinite loop
} # After the inner infinite loop:
I¾Q # If the input and counter_variable are equal:
# # Stop the outer infinite loop
# (and output the result-string at the top of the stack implicitly)
```
[Answer]
# [R](https://www.r-project.org/), 148 bytes
```
function(n){`~`=paste0
`*`=sample
o=""
while(nchar(o)<n-1){a=c("B"[T<4],"F","S"[F<2])*1
F=F+(a>"E")
T=T+(a<"F")
o=o~a}
o~c("B"[T>3],"H","S"[F>1])*1}
```
[Try it online!](https://tio.run/##LcyxCoMwGATgPU9R/im/VWisY5Kh0NC9biIkiEHBJqKWDqKvnkZwOW6476ZgLzwL9uuapfeOOlz1rsVo5qW9EZ1oMZvPOLTECwDy6/qhpa7pzEQ9cpcxXI1oKDygKnlRp6AghTdUiuc1Jowooa7USHgCklKUsfM4wfjmd7MRv59W3qN9nVayw27BUobE0vyIAsMf "R – Try It Online")
Generates the string, using conditional inclusion in the sampling datasets to ensure that the result is a possible pitch sequence.
Possibly doing rejection sampling (as [xnor's python answer does](https://codegolf.stackexchange.com/a/180491/67312)) is shorter.
```
function(n){`~`=paste0 # alias
`*`=sample # alias
o="" # empty string for output
while(nchar(o)<n-1){ # do n-1 times:
a=c("B"[T<4],"F","S"[F<2])*1 # sample 1 from the string "BFS", conditionally including B or S if the ball/strike count is 3/2
F=F+(a>"E") # increment F (strike count) if sampled character is F or S
T=T+(a<"F") # increment T (ball count) if sampled character is B
o=o~a} # append a to output
o~c("B"[T>3],"H","S"[F>1])*1} # append the sampled "BHS", conditionally including B or S if the ball/strike count is 3/2.
```
Random ["F and S" reference](https://www.youtube.com/watch?v=DDB97j8_HSk) that kept playing in my head every time I typed one of those letters...
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 137 bytes
```
f=(n,o='',i=Math.random()*4|0,r=/^(?!.*((B.*){4}|([SF].*){2}S|H).)/)=>r.test(o)?n?f(n-1,o+'BSFH'[i%4])||i<8&&f(n,o,i+1):!r.test(o+1)&&o:0
```
[Try it online!](https://tio.run/##rY2xTsMwEIZ3noIOTe5S95q0GVDBjehQdWHKGAXJoo4wEDuyTaHCffaQCLEiIfWfvjvdff@LOAr3ZFXn565TB2lbo1/lqe8bDpoZHsdM8Qfhn8kKfTAtYJKHlFm@eIRiQgnAlhL8ys8BqnJXj7w8l2GPhAvkG0teOg8GC100oOcZM7N4W@72caWmeY0hqLubKGrGLqZmGa4nvy/DEEVmnfadVdpDRURaflyX8ofvrRUnyNIhWFMrOvjkmwYyRKSjeHuXDoa9M9YD4tW/HMsLOFYXcOR/OZrxHvG2/wY "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# Pyth, 53 bytes
```
u+GO?H+W<K/G\B3+W<Jl@"SF"G2\F\S\B+WqK3+WgJ2\H\S\B_UQ[
```
Try it online [here](https://pyth.herokuapp.com/?code=u%2BGO%3FH%2BW%3CK%2FG%5CB3%2BW%3CJl%40%22SF%22G2%5CF%5CS%5CB%2BWqK3%2BWgJ2%5CH%5CS%5CB_UQ%5B&input=10&debug=0).
This feels way too long, I think another approach may be required.
```
u+GO?H+W<K/G\B3+W<Jl@"SF"G2\F\S\B+WqK3+WgJ2\H\S\B_UQ[ Implicit: Q=eval(input())
_UQ Reversed range from Q-1 to 0
u [ Reduce the above, with initial value G=[], next value as H:
@"SF"G Keep elements of G which are in "SF"
l Length of the above
J Store in J - this is the number of strikes and fouls so far
/G\B Count number of "B"s in G
K Store in K - this is the number of balls so far
?H If H is not 0 (i.e. not final pitch):
\F Start with "F" (foul is always available in non-final pitch)
W<J 2 If J<2...
+ \S ... append "S"
W<K 3 If K<3...
+ \B ... append "B"
Else:
\H Start with "H" (hit is always available in final pitch)
WgJ2 If J >= 2...
+ \S ... append "S"
WqK3 If K == 3...
+ \B ... append "B"
O Choose one element at random from the available options
+G Append the above to G
Implicit print the result of the reduce operation
```
[Answer]
# JavaScript (ES6), ~~107 106~~ 99 bytes
```
f=(n,k=p=s=0,o='')=>p&&p>2|k-s>3|s>2&p<2?k-n?f(n):o:f(n,k+1,o+'FSBH'[p=Math.random()*4|0,s+=p<2,p])
```
[Try it online!](https://tio.run/##NY6xDoJAEER7v2IruPMOAqiN3EJiYWysLI0FQVFEdy@csRG/HY/Caibz8pK5V@/K1X1rXxHx@TKODQrSHVp0mGjGMJRY2CCwRTZ0kSsWgyuywJqs7CIqG0FyzetmUlSqWYXbw2YXHi3uq9ct7is681PI@XJItFPoNW1Pcmy4FwQIaQ4EBmHlUykJnxnAxFrPkhxaMJCCMUC@/zlAzeT4cYkffBXTAZn7@Tv7jj8 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f = recursive function taking:
n, // n = requested length
k = // k = pitch counter, initialized to 0
p = // p = last pitch
s = 0, // s = sum of strikes and fouls
o = '' // o = output string
) => //
p && // if the last pitch was not a foul
p > 2 | // AND the last pitch was a hit
k - s > 3 | // OR we have 4 balls (or 3 balls + 1 hit)
s > 2 & p < 2 ? // OR more than 2 strikes or fouls, ending with a strike:
k - n ? // if k is not equal to n:
f(n) // valid series but bad timing: try again from scratch
: // else:
o // success: return o
: // else:
f( // do a recursive call:
n, // n is unchanged
k + 1, // increment k
o + 'FSBH' // append the pitch letter to o
[ p = Math.random() // pick a new random pitch
* 4 | 0, // in [0..3]
s += p < 2, // increment s if the pitch is a foul or a strike
p ] // actual index in 'FSBH'
) // end of recursive call
```
[Answer]
# [Ink](https://github.com/inkle/ink), ~~120~~ ~~119~~ ~~116~~ 117 bytes
```
=f(n)
->g(n,3,2)
=g(n,b,s)
~n--
{n:{~{b:b->g(n,b-1,s)}|{s:s->g(n,b,s-1)}|}f->g(n,b,s-(s>0))|{~{b:h|b}|{s:h|s}|h}}->->
```
[Try it online!](https://tio.run/##RYsxDsMgDEV3n6IjlrAEzYaEp3bNIRgoqBJDPAK5OoW0Ujf7/fdyeQ/iQ1ljjL5tCOAPVXRGqMURR5WRuBE/90eHJRaycx0@qoITvKa86TuCX1fQgnAWolXXswYXvkqYlWBvVZz8iBayk/T4/5WwQWxXmFq49NSkt9Q7MfEYHw "ink – Try It Online")
Probably still golfable.
# Ungolfed (mildly reformatted)
```
=f(length) // Define a stitch f, with one parameter which specifies the length of the created string. This is the intended entry point.
->g(length,3,2) // Instantly divert to g, defined below, with some extra parameters
=g(length,balls_left,strikes_left) // Define a stitch g, with three parameters.
~ length-- // Decrement remaining length
{
- length: // If this is not to be the last character in the string
// randomly do one of the following:
// 1. If balls_left is nonzero, print a b and recurse
// 2. If strikes_left is nonzero, print an s and recurse
// 3. Do nothing
// If we did not divert earlier, print an f and recurse.
{~{balls_left:b->g(length,balls_left-1,strikes_left)}|{strikes_left:s->g(length,balls_left,strikes_left-1)}|}f->g(length,balls_left,strikes_left-(strikes_left>0))
- else: // Randomly do one of the following
// 1. If a ball would result in a walk, print a b, otherwise an h.
// 2. If a strike would result in a strikeout, print an s, otherwise an h.
// 3. Just print an h.
// And finally, halt.
{~{balls_left:h|b}|{strikes_left:h|s}|h}}->->
```
**Edits**
1. Saved a byte by finishing with `->->` instead of `->END`.
2. Saved three bytes by decrementing `n` earlier.
3. Fixed a bug that caused strikeouts in incorrect places, thanks to @veskah for spotting it (+1 byte)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 77 [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")
```
{'HBSF'[{⍺←⍬⋄∨/((⊃⌽⍺)=⍳3)∧1,4 3≤(⊃s),+/1↓s←⍺∘(+/=)¨1+⍳3:⍺⋄∇⍨⍺,?4}⍣{i=≢⍺}i←⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rdwynYTT26@lHvrkdtEx71rnnU3fKoY4W@hsajruZHPXuB4pq2j3o3G2s@6lhuqGOiYPyocwlIrlhTR1vf8FHb5GKwvl2POmZoaOvbah5aYagNUm8FEgOZ1f6odwWQrWNvUvuod3F1pu2jzkVAfm0mWN/W2Nr/aWBW36O@qZ7@QJMPrTd@1DYRyAsOcgaSIR6ewf@BAmmHVhjrA002NAAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes
```
≔⁰η≔⁰ζF⊖N«≔‽⁺²‹ζ³ι¿›ι¹≦⊕ζ≦⊕η§SFB∨ι›η²»⊞υHF›η¹⊞υSF›ζ²⊞υB‽υ
```
[Try it online!](https://tio.run/##dY/LaoNAFIbX@hQHV0eYgpplVgmlrdCmkjzBRE/qgI4yl1IMffbJaDQJlC5/@P5bWXNVdrxxbqO1@JKYMKjjdXhXg1enTgE@U6moJWmowlz21uxseySFcRzDOQxmx57LqmuxaKzGjME7aY0Dg5WnGAifFYgT4KsibrxXMEi9/YP3sz2Xt5JrdUCNpv@AcWlQKCENbkwuK/rB6PCyjRh8TtlLTc0g8wM8/RsWVtdoGURv0fLsARvX3IjDH2KYgu7EdiSuA@bj1rc4lybu6bu5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰η≔⁰ζ
```
Start with 0 balls and 0 strikes.
```
F⊖N«
```
Loop over all of the deliveries except the last.
```
≔‽⁺²‹ζ³ι
```
If the have been fewer than three balls, then generate a random number from 0 to 2, otherwise just coinflip between 0 and 1.
```
¿›ι¹≦⊕ζ≦⊕η
```
A random value of 2 is a ball otherwise it increases the strike count.
```
§SFB∨ι›η²»
```
The values 0 to 2 map to strike, foul and ball, except that if there would be three strikes then foul is printed instead. (Four balls are excluded above.)
```
⊞υHF›η¹⊞υSF›ζ²⊞υB‽υ
```
Determine whether a strike or ball would get the batter out and choose from those or a hit as appropriate.
[Answer]
# [Perl 5](https://www.perl.org/), 122 bytes
```
map{$B=$S=$H=0;while($B<4&&$S<3&&!$H&&/./g){${$&}++;$S+=$&eq F&&$S<2}y///c>pos||push@a,$_}glob"{B,F,H,S}"x<>;say$a[rand@a]
```
[Try it online!](https://tio.run/##HcrBCoIwGADgVyn5@SlczkpPOhEP4qXTjhGxSlQwt1xRMvfqLeg7f6oe@9i5u1AGCgacQcXC5N12fb2CIo0Qgad7xCVUiDSgzdqAAbS@nwD3GWD9WJT/tLMTpfSaKannWb10mwsCZ9v08uKZgpSkItx6nzRLtJhAHEcx3HJxci76SvXs5KDd5hAH4Tb8AQ "Perl 5 – Try It Online")
[Answer]
# C (GCC) ~~164~~ ~~145~~ 142 bytes
-3 bytes ceilingcat
```
#define A(a)!i&&!r--?puts(#a),++a,--n:0;
b,s,f,h,i,r;p(n){srand(time(0));for(i=n;i--;){for(n=1;n;){r=rand()&3;b>2^!A(b)s+f>1^!A(s)!A(f)A(h)}}}
```
[Try it online](https://tio.run/##HYrLCoMwEADvfkVEkF1MQO2tixZ/pBAfqXtwK4k9if31VHsZZmAG8xqGGLNxciyT6sBiynmeemMesH62AJlFXRRWGyN4LynpddBOz5q1pxUE9@CtjLDxMkGJSO7tgRuhrzFMuF8pTUVyum/@K@Y36tv6mXbQYyhcW10a8ITDDmY8jiOybGqxLIBqT5RaoaqRkiP@AA)
] |
[Question]
[
Given is any integer x > 0 and any base y > 3.
1. Sum all digits of x (if written in the set base).
2. Multiply this by the highest possible digit (is always `base -1`).
3. Repeat until this value is `(y - 1) ^ 2`
Searched is the count of iterations and the steps.
Example 1:
```
x= 739
y= 7
searched: (7 - 1) ^ 2 = 36
based: (b7)2104
sum: (dec)7
mul: (dec)42
based: (b7)60
sum: (dec)6
mul: (dec)36
2 steps needed -> answer is [2, 739, 42, 36] or [739, 42, 36, 2]
```
Example 2:
```
x = 1712
y = 19
s: 324
step1: 1712 -> 360
step2: 360 -> 648
step3: 648 -> 324
3 steps needed -> answer is [3, 1712, 360, 648, 324] or [1712, 360, 648, 324, 3]
```
Special:
In some cases (some combinations with a base of 3) you will not be able to get to `(y - 1) ^ 2` like for `x = 53` and `y = 3`. For this reason `y` needs to be bigger than 3 and you can ignore this.
The count of iterations need to be the first or the last value
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") lowest byte-count wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte by printing as it loops (`Ṅ` replacing a chain separation, `µ` and concatenation `;`)
```
Ṅb⁹S×⁹’¤µÐĿL’
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=4bmEYuKBuVPDl-KBueKAmcKkwrXDkMS_TOKAmQ&input=&args=MTcxMg+MTk)**
### How?
```
Ṅb⁹S×⁹’¤µÐĿL’ - Main link: x, y
µÐĿ - loop monadically until results are no longer unique and collect
Ṅ - print z (initially x), then result of previous loop and return z
⁹ - right argument (y, even though monadic)
b - left to base right
S - sum (the result was a list of base y digits)
¤ - nilad followed by link(s) as a nilad
⁹’ - y decremented
× - multiply
L - length(z)
’ - decrement
- implicit print
```
The alternative 13 byter prints each input to the loop plus a line feed (`Ṅ`), and finally implicitly prints the decremented count of the collected results, removing the need for a monadic chain separation (`µ`) and concatenation (`;`).
[Answer]
# [Perl 6](https://perl6.org), 60 bytes
```
{$/=[$^x,*.polymod($^y xx*).sum*($y-1)...($y-1)²];$/-1,|$/}
```
## Expanded:
```
{ # bare block lambda with placeholder parameters 「$x」 「$y」
$/ = [ # store in 「$/」 ( so that we don't have to declare it )
# generate a sequence
$^x, # declare first parameter, and seed sequence generator
# Whatever lambda
*\ # the parameter to this lambda
.polymod( # broken down with a list of moduli
$^y # declare second parameter of the outer block lambda
xx * # an infinite list of copies of it
)
.sum
*
( $y - 1 )
# end of Whatever lambda
... # repeat until it reaches
( $y - 1 )²
];
# returns
$/ - 1, # count of values minus one
|$/ # Slip 「|」 the list into the result
}
```
## Usage:
```
# store it in the lexical namespace so that it is easier to understand
my &code = {$/=[$^x,*.polymod($^y xx*).sum*($y-1)...($y-1)²];$/-1,|$/}
say code 739, 7; # (2 739 42 36)
say code 1712, 19; # (3 1712 360 648 324)
```
[Answer]
# C, ~~116~~ 113 bytes
-3 bytes for recalculating square each time
```
s,t,i;f(x,y){s=y-(i=1);while(x-s*s){t=0;++i;printf("%d ",x);while(x)t+=x%y,x/=y;x=t*y-t;}printf("%d %d ",x,i-1);}
```
Ungolfed and usage:
```
s,t,i;
f(x,y){
s=y-(i=1);
while(x-s*s){
t=0;
++i;
printf("%d ",x);
while(x)
t+=x%y, //add the base y digit
x/=y; //shift x to the right by base y
x=t*y-t;
}
printf("%d %d ",x,i-1);
}
main(){
f(739,7);puts("");
f(1712,19);puts("");
}
```
[Answer]
## JavaScript (ES6), ~~97~~ ~~91~~ ~~84~~ 82 bytes
```
f=(n,b,k=1,c=b-1)=>[n,(s=(B=n=>n%b*c+(n>b&&B(n/b|0)))(n))-c*c?f(s,b,k+1):[s,k]]+''
```
### Test cases
```
f=(n,b,k=1,c=b-1)=>[n,(s=(B=n=>n%b*c+(n>b&&B(n/b|0)))(n))-c*c?f(s,b,k+1):[s,k]]+''
console.log(f(1712, 19))
console.log(f(739, 7))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
I guess I'll post this anyway, even though it was beaten while I was writing it, because it's a notably different algorithm and it was interesting to write. (I couldn't figure out how `ÐĿ` parsed from the docs and had to give up on it, despite knowing it would probably lead to a shorter solution than this one.)
```
ṄbS×⁹’¤ß<’¥n⁸$?‘
```
[Try it online!](https://tio.run/nexus/jelly#@/9wZ0tS8OHpjxp3PmqYeWjJ4fk2IHpp3qPGHSr2jxpm/P//39Dc0Oi/oSUA "Jelly – TIO Nexus")
Explanation:
```
ṄbS×⁹’¤ß<’¥n⁸$?‘
Ṅ Output {the first argument} and a newline
b Convert to base {the second argument}
S Sum digits
⁹’¤ {the second argument} minus 1, parsed as a group
× Multiply
n⁸$ {the current value} ≠ {the first argument}, parsed as a group
? If that's true:
ß then run the whole program recursively
<’¥ else run (lambda a,b: (a<b)-1)
‘ Increment the result
```
The use of `<’¥` is basically a short way to write a dyad (link with two arguments) that always returns -1 (because we know the answer will never be smaller than the base). Choosing between running that recursively, and the whole program recursively, lets us determine when to stop looping. Then when the stack unwinds at the end of the recursion, we keep incrementing the -1 to determine how many steps there were.
[Answer]
# MATL, ~~25~~ 21 bytes
*4 bytes saved thanks to @Luis*
```
XJx`tJYA!UsJq*tJqU-}@
```
[**Try it Online!**](http://matl.tryitonline.net/#code=WEp4YHRKWUEhVXNKcSp0SnFVLX1A&input=Nwo3Mzk)
**Explanation**
```
XJ % Implicitly grab the first input and store in clipboard J
x % Delete this from the stack
` % Do...while loop
t % Duplicate last element on stack (implicitly grabs second input)
JYA % Convert this number to the specified base
!Us % Sum the digits
Jq* % Multiply by the largest number in this base
t % Duplicate this value
JqU % Compute (base - 1) ^ 2
- % Subtract the two. Evaluates to TRUE if they are not equal
} % When they are finally equal
@ % Push the number of iterations
% Implicitly display the stack contents
```
[Answer]
## Mathematica, 80 bytes
```
(s=FixedPointList[x(#2-1)(Plus@@x~IntegerDigits~#2),#];s[[-1]]=Length@s-2;s)&
```
`` is the private use character [`U+F4A1`](https://unicode-table.com/en/F4A1/) used to represent [`\[Function]`](http://reference.wolfram.com/language/ref/character/Function.html). If the number of steps weren't required in the answer, this could be done in 60 bytes:
```
Most@FixedPointList[x(#2-1)(Plus@@x~IntegerDigits~#2),#]&
```
] |
[Question]
[
Given an input string containing only letters and numbers, write a program or function that prints the possible printable ASCII characters (Hex 20-7E) that correspond with the string's value in bases 8, 10, and 16 (where possible). The characters must be written in increasing order in terms of the bases with which they correspond (base 8 first, etc). The output can be in array format (like `[& . F]`) or separated by spaces or newlines (a trailing newline is optional) like the samples.
If there is not a possible printable ASCII character that can be formed, the program must not have any output.
**Samples**
```
31
==> 1
47
==> ' / G
69
==> E i
7A
==> z
100
==> @ d
156
==> n
189
==> <empty>
potaTO
==> <empty>
5G
==> <empty>
19
==> <empty>
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the fewest bytes wins. Standard rules apply.
[Answer]
## JavaScript (SpiderMonkey 30+), 74 bytes
```
s=>[for(b of'o0x')if((c=+(0+b+s))>31&c<127)String.fromCharCode(c)].join` `
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 23 ~~24~~ ~~28~~ bytes
*1 byte off thanks to @David*
```
8H6hhYs"G@ZA32:126m?6Mc
```
[**Try it online!**](http://matl.tryitonline.net/#code=OEg2aGhZcyJHQFpBMzI6MTI2bT82TWM&input=JzQ3Jw)
```
8H6hhYs % array [8,10,16]
" % for each base
G % push input. Do nothing the first time
@ % push base (8, 10 or 16)
ZA % convert from base to decimal. Takes implicit input the first time
32:126m % is result in acceptable range?
? % if so
6M % push result of base conversion again
c % convert to char
% implicitly end if
% implicitly end for each
% implicitly display stack contents
```
[Answer]
# Python 3, ~~84~~ 82 bytes
```
def a(s):
for n in 8,10,16:
try:b=int(s,n);31<b<127and print(chr(b))
except:0
```
[Answer]
## Pyth, ~~23~~ ~~21~~ ~~20~~ 18 bytes
```
@rd\m.xCizd0[8T16
```
Output as an array. There's a literal `\x80` between the backslash and the C, which I've replaced with a `•`.
```
@rd\•m.xCizd0[8T16 Implicit: z=input
m d [8T16 Map the following lambda d over [8, 10, 16]:
.x try:
izd convert z from that base
C and convert to char
0 except: return the number 0
@ Filter that on presence in
rd\• strings from space to \x80 (the printable ASCII characters).
```
Try it [here](https://pyth.herokuapp.com/?code=%40rd%5C%C2%80m.xCizd0%5B8T16&input=100&test_suite=1&test_suite_input=31%0A47%0A69%0A7A%0ApotaTO&debug=1).
[Answer]
# Jolf, 26 bytes
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=IGbOnOKAmENpOGnOl2nigJlkcEFIZGggc0giWyAtfl0) [Test suite](http://conorobrien-foxx.github.io/Jolf/#code=IGbOnOKAmENpOGnOl2nigJlkcEFIZGggc0giWyAtfl0&input=MzEKCjQ3Cgo2OQoKN0EKCjEwMAoKMTU2CgoxODkKCnBvdGFUTwoKNUcKCjE5)
```
fΜ‘Ci8iΗi’dpAHdh sH"[ -~]
```
# Explanation
```
fΜ‘Ci8iΗi’dpAHdh sH"[ -~]
‘ ’ array containing
Ci8 input as base 8
i input as base 10
Ηi input as base 16
Μ d mapped
pAH with from char code
_f d filtered
_sH"[ -~] with strings matching that.
```
[Answer]
# Bash + GNU utilities + [ascii](http://www.catb.org/%7Eesr/ascii/ascii.html), 36
Not sure if the use of the `ascii` utility is allowed. Input is taken as a commandline parameter.
```
ascii $1|tac|grep -Po '(?<=s as `).'
```
`ascii` may be installed on Ubuntu with `sudo apt-get install ascii`.
[Answer]
# Javascript ES6, 89 chars
```
s=>'0o,,0x'.split`,`.map(x=>(x+=s)>31&x<128&&String.fromCharCode(x)).filter(x=>x).join` `
```
Test:
```
f=s=>'0o,,0x'.split`,`.map(x=>(x+=s)>31&x<128&&String.fromCharCode(x)).filter(x=>x).join` `
"31,47,69,7A,100,156,189,potaTo,5G,19".split`,`.map(f) == "1,' / G,E i,z,@ d,n,,,,"
```
[Answer]
## Lua, 147 Bytes
I don't think I can golf it down a lot more, I've tested a lot of ways to do it, and here come the shortest. Even using an old compiler which contains the deprecated function `table.foreach(table,function)` doesn't shave off some bytes.
This program takes a string as argument, and print the concatenation of a table values separated by spaces.
```
t={}for _,i in pairs({8,10,16})do x=tonumber(arg[1],i)x=x and x or 0 t[#t+1]=127>x and 19<x and string.char(x)or nil end print(table.concat(t," "))
```
### Ungolfed and explanations
```
t={} -- Initalise the array containing the chars to print
for _,i in pairs({8,10,16}) -- Iterate over the array {8,10,16}
do
x=tonumber(arg[1],i) -- convert the input in base i to a number in base 10
x=x and x or 0 -- if the input wasn't a number, x is nil
-- use a ternary operator to set x in this case
t[#t+1]=127>x and 19<x -- if x is the bytecode of a printable character
and string.char(x)or nil-- insert this character into t
end
print(table.concat(t," ")) -- concatenate the values in t with " " as separator
-- and print it
```
If you're wandering why there's a variable set but not used in a golfed code (the variable `_` in the for loop), here's why:
You have 2 ways to iterate over an array in Lua, either in a for style:
```
for i=1,#table do --[[code here, use table[i] ]] end
```
or in a foreach style:
```
for key,value do pairs(table) do --[[code here]] end
```
I was needing the values contained in the table `{8,10,16}` as they are the different bases I have to iterate over. But functions with multiple return won't allow you to chose which one you actually want to be returned, they follow an order. To have the variable `value` set, I need to catch the value of `key` too: that's what we call a dummy `_`.
[Answer]
# C (function), 76
* 2 bytes saved thanks to @anatolyg.
* 5 bytes saved thanks to @luserdroog.
```
j,c;f(char*s){for(j=8;c=strtol(s,0,j);j=j*j/6)isprint(c)?printf("%c ",c):0;}
```
[Ideone.](https://ideone.com/bqkcOW)
[Answer]
# JavaScript ES6, ~~89~~ 88 bytes
Saved 1 byte thanks to Neil!
```
n=>[..."0x+"].map(t=>String.fromCharCode(eval(`0${t+n}`))).filter(k=>~k.search(/[ -~]/))
```
Returns an array. If that's not okay, this works for an extra 8 bytes, displaying the possible matches.
```
n=>[..."0x+"].map(t=>String.fromCharCode(eval(`0${t+n}`))).filter(k=>~k.search(/[ -~]/)).join` `
```
```
F=n=>[..."0x+"].map(t=>String.fromCharCode(eval(`0${t+n}`))).filter(k=>~k.search(/[ -~]/)).join` `
//`
U=x=>o.innerHTML=F(+i.value);
i.onchange=i.onkeydown=i.onkeyup=i.onkeypress=U;U();
```
```
*{font-family:Consolas,monospace;}
```
```
<input id=i type="number" value=31><div id=o></div>
```
[Answer]
# R, 84 bytes
```
function(x){s=sapply;y=s(c(8,10,16),strtoi,x=x);cat(s(y[y%in%c(32:126)],intToUtf8))}
```
uses `strtoi` to convert to each of the bases and then convert to character if in the appropriate range. Could save 4 more bytes by removing `cat` if we allowed the default printing of characters (wrapped in `""`)
] |
[Question]
[
Let `z` be a complex number. `z` is an nth **primitive root of unity** if for a certain positive integer `n` [](https://i.stack.imgur.com/KglnS.gif) and for any positive integer `k < n` [](https://i.stack.imgur.com/d7Gic.gif).
## Challenge
Write a full program or function that, given a positive integer `n` as input, outputs all of the nth primitive roots of unity. You may output them in polar form (`e^θi` or `e^iθ`, argument should be a decimal with at least 2 decimal places) or rectangular form (`a + bi` or a similar form, real and imaginary parts should also be decimals), and they may be outputted in your language's list/array format or as a string with the numbers separated by spaces or newlines. Built-ins that calculate the nth roots of unity or the nth primitive roots of unity are not allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
## Sample Inputs and Outputs
```
6 -> e^1.05i, e^-1.05i # polar form
3 -> e^2.094395i, e^-2.094395i # any number of decimal places is OK as long as there are more than 2
8 -> 0.707 + 0.707i, 0.707 - 0.707i, -0.707 + 0.707i, -0.707 - 0.707i # rectangular form
1 -> 1 + 0i # this is OK
1 -> 1 # this is also OK
4 -> 0 + i, 0 - i # this is OK
4 -> i, -i # this is also OK
```
[Answer]
## Jelly, ~~11~~ 9 bytes
*Thanks to @Dennis for -2 bytes!*
```
Rg=1O÷H-*
```
I wanted to generate the numbers coprime to N by folding set difference over all of the roots of unity from 1 to N, but I couldn't figure out how so I used @Dennis's method.
```
Rg=1O÷H-* Monadic chain: 6
R Range [1,2,3,4,5,6]
g Hook gcds with range [1,2,3,2,1,6]
=1 [gcds equal to one] [1,0,0,0,1,0]
O Replicate indices [1,5]
÷H Divide by half of N [1/3,5/3]
- Numeric literal: - by itself is -1.
* Take -1 to those powers [cis π/3,cis 5π/3]
```
~~Try it [here](http://jelly.tryitonline.net/#code=Umc9MU_Dt0gtKg&input=&args=Ng)~~. Valid in [this version](https://github.com/DennisMitchell/jelly/blob/cff64821686eb6536294e1e67bbc6debf228e25b/jelly.py) of Jelly, but may not be in versions after February 1, 2016.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
Rg=1O°÷×ı360Æe
```
[Try it online!](http://jelly.tryitonline.net/#code=Umc9MU_CsMO3w5fEsTM2MMOGZQ&input=&args=OA)
### How it works
**z = e2tπi** is an **n**th root of **1** if and only if **t = k / n** for some integer **k**.
**z** is *primitive* if and only if **k** and **n** are coprime.
```
Rg=1O°÷×ı360Æe Main link. Input: n
R Yield [1, ..., n].
g Compute the GCDs of reach integer and n.
=1 Compare the GCDs with 1.
O Get all indices of 1's.
This computes all the list of all k in [1, ..., n]
such that k and n are coprime.
° Convert the integers to radians.
÷ Divide the results by n.
×ı360 Multiply the quotient by the imaginary number 360i.
Æe Map exp over the results.
```
[Answer]
# Julia, 48 bytes
```
n->cis(360deg2rad(filter(k->gcd(k,n)<2,1:n))/n)
```
This is a lambda function that accepts an integer and returns an array of complex floats. To call it, assign it to a variable. It uses the same approach as Dennis' Jelly answer.
Ungolfed:
```
function f(n::Int)
# Get the set of all k < n : gcd(k,n) = 1
K = filter(k -> gcd(k,n) < 2, 1:n)
# Convert these to radian measures
θ = deg2rad(K)
# Multiply by 360, divide by n
θ = 360 * θ / n
# Compute e^iz for all elements z of θ
return cis(θ)
end
```
[Answer]
# Ruby, 46 bytes
This is a non-"golfing language" implementation of [Thomas Kwa](https://codegolf.stackexchange.com/users/39328/thomas-kwa)'s Jelly answer.
```
->n{(1..n).map{|j|1i**(4.0*j/n)if j.gcd(n)<2}}
```
Ungolfed:
```
def r(n)
(1..n).each do |j|
if j.gcd(n) == 1 # if j is coprime with n, then this will be a primitive root of unity
p 1i**(4.0*j/n) # print the fourth power of i**(j/n), i.e. the root of unity
end
end
end
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 27 bytes
```
:1-tGYf1X-!\Xpg)2j*YP*G/Ze!
```
Uses [release (9.3.1)](https://github.com/lmendo/MATL/releases/tag/9.3.1), which is earlier than this challenge.
[**Try it online!**](http://matl.tryitonline.net/#code=OjEtdEdZZjFYLSFcWHBnKTJqKllQKkcvWmUh&input=OA)
(The online compiler uses a newer release, but the code runs in release 9.3.1 and gives the same result)
### Explanation
There are three main steps:
1. Generate integers `0`,`1`,...,`N-1`, corresponding to all roots.
2. Keep only integers corresponding to primitive roots. These are identified using the prime factor decomposition of `N`.
3. Generate the actual roots with an imaginary exponential.
Code:
```
:1- % 1. Implicit input "N". Produce vector [0,1,...,N-1]
t % duplicate
GYf % 2. Prime factors of N
1X- % remove factor "1" if present (only if N==1)
!\ % all combinations of [0,1,...,N-1] modulo prime factors of N
Xpg % logical "and" along the prime-factor dimension
) % index into original vector [0,1,...,N-1] to keep only primitive roots
2j*YP*G/Ze % 3. Imaginary exponential to produce those roots
! % transpose for better output format
```
[Answer]
# Matlab 49 bytes
```
n=input('');q=0:n-1;exp(i*2*pi/n.*q(gcd(n,q)==1))
```
Didn't get the task at the first time, but now here it is. Outputs as follows:
```
6
ans =
0.5000 + 0.8660i 0.5000 - 0.8660i
```
[Answer]
## ES6, 96 bytes
```
n=>[...Array(n).keys()].filter(i=>g(i,n)<2,g=(a,b)=>a?g(b%a,a):b).map(i=>'e^'+Math.PI*2*i/n+'i')
```
Polar form was the shortest output.
[Answer]
# PARI/GP, 41 bytes
Pretty straightforward: find the numbers from 1 to n which are coprime to n, then
```
n->[exp(2*Pi*I*m/n)|m<-[1..n],gcd(n,m)<2]
```
There has to be some shorter way, but this was the best I could find.
] |
[Question]
[
Here's an interesting challenge...
I want you to golf code that when executed will allow your input to be converted to mimic output as though you were typing on a DVORAK keyboard layout.
The aim is to mimic the US Simplified Dvorak Keyboard (US:SDK)

In comparison, here is the standard US QWERTY layout:

The keyboard emulation must work for both uppercase and lower case letters as well as shifted keys, for example, if I tapped the `q` (unshifted) key on my keyboard, the Dvorak code should pop out a `'` character on the screen. If I were to tap the `c` (unshifted) button I should get a `j` (also unshifted) in response, `C` (shifted) would get `J` (shifted) and so on...
I am only concentrating of course on the white keys in the diagram above. Tabs, Caps and the other grey keys should work as per normal...
Any questions? Not for now? Good...
I will not allow external resources that already have the layout encoded already, I will not have any files brought in that can encode the layout. The code MUST be `QWERTY INPUT -> (DVORAK RE-CODING) -> DVORAK OUTPUT` in nature. No silly Esolangs that are theoretical or just say something like "This program will take QWERTY input and recode it in DVORAK. This is the program." or crap like that... Take this challenge seriously... So Brainfuck coders, I welcome you.
Please note, this is NOT a string conversion program. For every QWERTY key you press, the corresponding DVORAK character must be outputted...
Shortest code wins...
[Answer]
# C - 144 characters
```
main(c){putch((c=getch())>33?c:"_#$%&-()*}w[vz0123456789SsW]VZ@AXJE>UIDCHTNMBRL\"POYGK<QF:/\\
=^{`axje.uidchtnmbrl'poygk,qf?|+~"[c-34]);main(0);}
```
[Answer]
### Shell: Unix [tr(1)](https://www.mirbsd.org/man1/tr), 94
```
tr \''"+-/:-[]_b-{}' "-_}w[vzSsW]VZ@AXJE>UIDCHTNMBRL\"POYGK<QF:/={xje.uidchtnmbrl'poygk,qf;?+"
```
This command takes QWERTY on stdin and outputs DVORAK on stdout.
[Answer]
## C#, 360 characters
Probably not the shortest, but it does exactly what you ask:
```
using System;class A{static void Main(){string[] q={"-=qwertyuiop[]sdfghjkl;'zxcvbnm,./","_+QWERTYUIOP{}SDFGHJKL:\"ZXCVBNM<>?","[]',.pyfgcrl/=oeuidhtns-;qjkxbmwvz","{}\"<>PYFGCRL?+OEUIDHTNS_:QJKXBMWVZ"};while(true){var c=Console.ReadKey(true);var a=c.KeyChar;int i,w=c.Modifiers==ConsoleModifiers.Shift?1:0;Console.Write((i=q[w].IndexOf(a))>-1?q[w+2][i]:a);}}}
```
If you press a key on your QWERTY keyboard, then the correct DVORAK character appears in the console.
[Answer]
# AutoHotKey, 200 bytes
```
-::[
=::]
q::'
w::,
e::.
r::p
t::y
y::f
u::g
i::c
o::r
p::l
[::/
]::=
s::o
d::e
f::u
g::i
h::d
j::h
k::t
l::n
`;::s
'::-
z::`;
x::q
c::j
v::k
b::x
n::b
,::w
.::v
/::z
```
There should be an answer in AHK for this question but not. So just post one.
[Answer]
# [R](https://www.r-project.org/), 157 bytes
Simple translate script.
```
chartr('\'qQwWeErRtTyYuUiIoOpP[{]}sSdDfFgGhHjJkKlL;:"zZxXcCvVbBnN,<.>/?=_+-','-\'",<.>pPyYfFgGcCrRlL/?=+oOeEuUiIdDhHtTnNsS_;:qQjJkKxXbBwWvVzZ{]}[',scan(,''))
```
[Try it online!](https://tio.run/##FY3HDoJAFEX3fAabpxF0jy0RsIcmKs0QhFEsoQyjIxq/fZTtPTnnYsbiNMIEtyCA0qR7pGKL2LX72F4WuV4Y/ufwrTaJcpqeZ@n8uryt7uu@xL@9lxPLz91xkmnCoDvqjYdhRwQBxAD4ZiiM2m2cWMbWff3HnVxHalNNlHRO7EyrNmFfKs0m@XKOE7p/7t7e/80HoYqjrCUAtNvMpAiTmiOoIhzNrYT9AA "R – Try It Online")
[Answer]
# [Python](https://www.python.org), 181 bytes
```
print(input().translate(str.maketrans("'qQwWeErRtTyYuUiIoOpP[{]}sSdDfFgGhHjJkKlL;:\"zZxXcCvVbBnN,<.>/?=_+-","-'\",<.>pPyYfFgGcCrRlL/?=+oOeEuUiIdDhHtTnNsS_;:qQjJkKxXbBwWvVzZ{]}[")))
```
This code takes QWERTY on stdin and outputs DVORAK on stdout.
It does this by creating a translation table from qwerty to dvorak then translates stdin with `input()` using that translation table
A cleaner representation
```
print(
input().translate(
str.maketrans(
"'qQwWeErRtTyYuUiIoOpP[{]}sSdDfFgGhHjJkKlL;:\"zZxXcCvVbBnN,<.>/?=_+-",
"-'\",<.>pPyYfFgGcCrRlL/?=+oOeEuUiIdDhHtTnNsS_;:qQjJkKxXbBwWvVzZ{]}[",
)
)
)
```
[Try it online!](https://tio.run/##HY7JDoIwAET/pRchIh684ZawuBJFQFYNQUFBsdRSZDF@O4rXN5k3gyoSpXDQNAjHkFAxRDmhaJZgH2aJT0IqI5h9@PfwTyjQee4KM5SwSvTKzvfxMt0ixX0fP5kWiJfZdR4tbqv7OpGH3AHUTmmdhZdx4uGGGbGT/nTsdXuAAb3OAbQAKZXdls4CVhP5F3fTbSi12kCMFkSHm0zzhtxz1zpL68QX5suond@cCxiappvmf/gL "Python 3 – Try It Online")
] |
[Question]
[
## Fast and Golfiest Robbers Thread
Welcome to the first season of **Fast and Golfiest**, a cops-and-robbers challenge! I designed this challenge to encourage competitive coding for efficiency (fastest algorithm) to become more popular on the site.
The rules are simple. The cops choose problems from LeetCode, a competitive coding platform, and solve them with code as efficient and short as possible. Now you, as the robber, will try to golf up their code, **without** sacrificing code efficiency. That is, the time complexity of your code must be smaller or equal to the cop code's complexity. You must also use the same language as the cop. Here's the link to the [Cops Thread](https://codegolf.stackexchange.com/q/263049/118810). Note that for the robbers, **golfiness matters most**! However, if your time complexity is lower than the cop code **and** shorter than theirs, your score will be 2.718 times the original!
Your answer post should include the following:
1. A link to the cop post you cracked.
2. Your code, its length in bytes.
3. The UTC time of your post.
4. The time complexity of your code (must be smaller or equal to the cop code's complexity).
You should also edit the cop post to say "Cracked" and add a link to your post.
Your score is the percentage reduction of the code length in bytes compared to the cop code (with the 2.718 times efficiency bonus if you got it), rounded to the nearest integer! **Edit**: Sorry, it seems unbalanced now so I have to nerf the robbers. The robbers' score will be divided by 4.
If you have any advices please let me know in the comments so that this challenge series could be improved. Thanks in advance!
Leaderboard (Periodically updated. Please note that I rank individual answers instead of answerers to encourage quality over quantity.):
1. 9 points: ATOI String to Integer by The Thonnu
2. 5 points: Concatenated Words by CursorCoercer
3. 4 Points: Longest Substring Without Repeating Characters by CursorCoercer
[Answer]
# [Python](https://www.python.org), 84 bytes (35.4% reduction), cracks [ATOI string to integer](https://codegolf.stackexchange.com/a/263060/114446)
```
lambda s:min(max(L:=-2**31,int([*re.findall("^ *([+-]?\d+)",s),0][0])),~L)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3Q3ISc5NSEhWKrXIz8zRyEys0fKxsdY20tIwNdTLzSjSitYpS9dIy81ISc3I0lOIUtDSitXVj7WNStDWVdIo1dQxiow1iNTV16nw0uTJzC_KLShSKUqFm2xYUgYxI01AyMVLS1OSCcxUUFHTRhEwMLY0VyjNLMhTK84tSioFyEEMWLIDQAA)
* UTC: 09:28 (updated 09:38)
* Same time complexity as the cops' answer I think.
[Answer]
# [C (GCC)](https://gcc.gnu.org), 44 bytes (6.4% reduction), cracks [Removing Stars From a String](https://codegolf.stackexchange.com/a/263081/25180)
```
i;f(char*s){for(i=0;s[i-=*s++-42?0:2]=*s;);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBBCsIwEEX3OcUQEdJotVYXYqwexIqUNNGAttKJgogncePGQ7n0JqaNSmeTmbz5n5_cn3KzlfLxeJ6sDqevvhGayV1WcQyuuqyYSSKBKxMmHHu9cBIvo1m8doMIxO2reXdMIfenXMEcbW7KwW5ByLk0ObEKbeMGzo5cCYBmGAh3HitTWM1oSruY0rSgfajBjRB3Tw6ZKVjt4EWNA45Wa0iA7pWynMsy54qKP4w9VFWGitfVYmPP0ohnVMBwqA5HewG0LsLWLTUhcdTE8n3c6sd1Kv_Q3yd9AA)
-2 bytes thanks to c-- (original cop).
I think this involves undefined behavior. I'm not exactly sure. But it works in the exact compiler version.
It doesn't work for empty strings, but the specification says 1 <= s.length <= 105.
* UTC: 2023-07-20 18:38:43Z; 2023-07-21 03:55:34Z
* Time complexity \$O(n)\$ (same as cops' answer)
[Answer]
# [Python](https://www.python.org), 44 bytes (6.4% reduction), cracks [Reverse words in a string](https://codegolf.stackexchange.com/a/263072/114446)
```
lambda g:print(*filter(str,g.split()[::-1]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3dXISc5NSEhXSrQqKMvNKNLTSMnNKUos0ikuKdNL1igtyMks0NKOtrHQNYzU1oXrs0jSUSjJSFYqzKxUyixWSckpTlTS5gIIKChmpOTn5CuX5RTkpCgoQQaDZ-flAXmpFYm5BDlAlxJQFCyA0AA)
* UTC: 14:04 (updated 14:18)
* Time complexity \$O(n)\$ (same as cops' answer)
[Answer]
# [Python](https://www.python.org), 145 bytes (18% reduction), cracks [Concatenated Words](https://codegolf.stackexchange.com/a/263073/73054)
```
lambda z:[i for i in z if any(q&z==q for q in g(i,0))]
def g(a,b=1):
if b:yield{a}
for i in range(1,len(a)):
for j in g(a[i:]):yield{a[:i]}|j
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY5NCsIwEEb3PUXIQhKIYHcSyElqF1OT1Ck1_SEu2tpDuHZTEL2Tt9G0FVcfM-_Nx9xfdedPlZseVh2eF2-3-_ethHOmgfQyQWKrliBBR3qCloDrWLPplWpm0ASQMxQ7ztNIG_sdQGQq5jIKeiY7NKUeYIz-RS243LBYlMYx4MGcWbF0QYIy5b-7RGI6Xov1MVq36DyzbKC6yqkg9Ah-jbAYOV_MaVryAw)
* UTC: 14:39
* Time complexity \$O(n)\$ (same as the cops')
[Answer]
# [Python 3](https://docs.python.org/3/), 125 bytes (13% reduction), cracks [Longest Substring Without Repeating Characters](https://codegolf.stackexchange.com/a/263083/73054)
```
def f(s):
m=x=0;c=set()
for y in s:
if y in c:
while s[x]!=y:c-={s[x]};x+=1
x+=1
c|={y};m=max(m,len(c))
return m
```
[Try it online!](https://tio.run/##TY7BCoMwEETvfsXWiwltoeJN2S8pPZg0wVATJRtRsX67jVhoYWF33gzD9nNoOlds21Np0Ix4mYDFCW@VRFKB8QR052EG44CiB0YfQu4Cxsa0Cug@PU44l/KKy36v1XTGfPe/W75xmdfKoq0nZi@tckzyWO1VGLwDu9VEyof4QFoLGUeIlCMWyY8LcbD8j/Xj@FLjkey9cYFlNEipiDK@fQA "Python 3 – Try It Online")
* UTC: 18:40
* Time complexity \$O(n)\$ (same as cops')
[Answer]
# [Go](https://go.dev), 168 bytes (2.9% reduction), cracks [Count and Say](https://codegolf.stackexchange.com/a/263093/112488)
```
import."fmt"
func g(n int)string{s:="1"
for;n>1;n--{c,o,f,k:=1,"",rune(s[0]),s[1:]+"_"
for _,r:=range k{if r==f{c++}else{o+=Sprintf("%d%c",c,f);f,c=r,1}}
s=o}
return s}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY9BasMwEEX3PoUQBCw0LhHdFLvTMxS6DCEY1TLC8chI8kroJN2YQqGLXqi3qeJm9Qf-8N__H5-j236WXk_9OLC5t_S1RtM8_X7beXE-PnAzR16ZlTQba2KWogjRWxpTaJGrYjnf0YvqqGmSBgcGphYVcA5-paEOp-NZQDip9iz5ZX9nF_At-p4KcUrWMI9okpYyD9cwJCfxbSmEaGp-eD9oDhqM6Axo9KByrgK6XPkhrp5YyPe-uFe8DagFSzvGshaZ6oo-I3s8lkPKYr3esq9UWyiLrBBVru4h2_avfw)
* Time: 2023-07-20 21:46:57Z
* Time complexity (same as cops' answer)
[Answer]
# [Python 3](https://docs.python.org/3/), 112 bytes (5% reduction), cracks [Simplify Path](https://codegolf.stackexchange.com/a/263078/52194), 2023-07-20 18:02 UTC
Just some minor golfs like realizing `elif` isn't needed and tweaking the string used to construct the final output. -1 by [The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu)
```
def f(p):
s=[]
for x in p.split('/'):
if x=='..'and s:s.pop()
if x not in'..':s+=x,
return'/'+'/'.join(s)
```
[Try it online!](https://tio.run/##TYwxCsMwDEX3nEKbbdLaQ7eAe4pupUMhNlFJLWE7NCXk7K4TMnSQ@NLjff7mgcKllN558JJV10Cy90cDniLMgAFYJx4xS2HERgE9zNYKrcUz9JC6pJlYqoNAoFytDXeptfOpgejyFEPV2zr6RRhkUuUz4OjgFidXSxFslXjKWw9HDFl6seAK5yssXqJahSpmoLczjdG6rj0bT3TE@vw79vwD "Python 3 – Try It Online")
[Answer]
# Python, 122 bytes (1.6% reduction), cracks [Edit Distance](https://codegolf.stackexchange.com/a/263077)
```
lambda a,b:(d:=range(len(b)+1),[d:=[x:=d[(j:=0)]+1]+[x:=1+min(x,d[(j:=j+1)],d[j-1]-(i==k))for k in b]for i in a])and d[-1]
```
A bit of a cheap crack.
Time: 2023-07-25 02:11:18Z
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 171 bytes (3.9% reduction), cracks [Generate Parentheses](https://codegolf.stackexchange.com/a/263127/112488)
```
")")")
")")")")")
")")")
")")![]](https://$ "Go back to the previous stack, adding all elements of the top stack back to it.")
")")")
")")")

")")")![]](https://$ "Go back to the previous stack, adding all elements of the top stack back to it.")")
")")")")![]](https://$ "Go back to the previous stack, adding all elements of the top stack back to it.")
")")")")")")")")")")
```
Hover over any symbol to see what it does
In plaintext:
```
i>:?v~l2,b2.
10-1<.02}}
:?v~{{l2,06.
v-\&'('o:2*[{1+}]$:
\:?v~$}}&1-b2.
')'/.321o
>:?v;
1+&\&:2*[{1-:}]?v:@&:&l2,-+?!v$
{{&>:?v~}}50ao./~0}]
.61-1&>1-&:2*[{/>1{{69!.|.!7f<
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaT46P3Z+bDIsYjIuXG4xMC0xPC4wMn19XG46P3Z+e3tsMiwwNi5cbnYtXFwmJygnbzoyKlt7MSt9XSQ6XG5cXDo/dn4kfX0mMS1iMi5cbicpJy8uMzIxb1xuPjo/djtcbjErJlxcJjoyKlt7MS06fV0/djpAJjombDIsLSs/IXYkXG57eyY+Oj92fn19NTBhby4vfjB9XVxuLjYxLTEmPjEtJjoyKlt7Lz4xe3s2OSEufC4hN2Y8IiwiaW5wdXQiOiIzIiwic3RhY2siOiIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoibnVtYmVycyJ9)
* Time: 2023-07-26 14:58:41Z (updated 15:42:38)
* Time complexity \$O(n!)\$ (same as cops' answer)

[Answer]
# [C (GCC)](https://gcc.gnu.org), 66 bytes (7.04% reduction), cracks [Sum of Scores for buit strings](https://codegolf.stackexchange.com/a/263094/91213)
```
f(s,l,i)char*s;{for(i=0;s[i]&&s[l+i]==s[i];++i);s=l?i+f(s,l-1):i;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCgIxDN3nFGVEaZ1RdCfWUfAaKlI7HwO1I5PqYsSTuHHjyhN5G1s_oEk2ebxPyOWm16XW1-vt4Ire6DEvOCUmQaG3qu6SPBVVzTEdSFrgqtOhhYlxlaZhk3GMQlJqZhi_VL2hGKM8f5zuLbTaHLKcTchlWPW3U_iFarRlwOBYYQYuJ8dDJuuSgBMwtvcEV_ConS1tlLCQwLzK5JaTEELCGcAzYKfQ8uDxlr2Moo3yHXnSF1DNxk-jmj_QV9g_J3-f8AQ)
Based on [This C tip from G B](https://codegolf.stackexchange.com/a/106067/91213)
[Answer]
# [Rust](https://www.rust-lang.org), 184 bytes (4.6% reduction), cracks [Generate Parentheses](https://codegolf.stackexchange.com/a/263091/112488)
```
fn f(z:i32)->Vec<String>{if z<1{vec!["".into()]}else{(0..z).flat_map(|i|->Vec<_>{let b=f(z-i-1);f(i).iter().flat_map(|c|b.iter().map(move|d|format!("({c})")+d)).collect()}).collect()}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZDBbsIwDIbvfYqQU6w1EW0vE4XyEJN2qSpU0gRZSlNUAoemfRIuHNgjTNqr7G0Wtk7CJ_u3_euzr_f-fHKfJeVcNeiwszQmNF2mCa1uH2en-ev3l7ZEs2GFWQq8eFdy_eZ6tIfCoybDOvEXJRclpQKt6xhUkzIn5dlSiAGENrXbtfWRjTj-Le8Kb5Qj-03w5MgTyDVDEOhUz57n5bj_Fx91213U2Iy669vaLRhlXk5A4aUBELIzRknHYHrOp5l_G_jbGi0D4iMS4hjonbHBxK-2UzhYswwgj36bD7aabEiZxGmcVXk029zmd_wA)
* Time: 2023-07-21 05:06:39Z
* Time complexity \$O(n!)\$ (same as cops' answer)
] |
[Question]
[
Your task is to write a program that receives a base 10 number from 0 to 99 and outputs the German name of that number with non-ASCII characters replaced with ASCII equivalents.
## German number names
```
0 -> null
1 -> eins
2 -> zwei
3 -> drei
4 -> vier
5 -> fuenf
6 -> sechs
7 -> sieben
8 -> acht
9 -> neun
10 -> zehn
11 -> elf
12 -> zwoelf
13 -> dreizehn
14 -> vierzehn
15 -> fuenfzehn
16 -> sechzehn
17 -> siebzehn
18 -> achtzehn
19 -> neunzehn
20 -> zwanzig
21 -> einundzwanzig
22 -> zweiundzwanzig
23 -> dreiundzwanzig
24 -> vierundwanzig
30 -> dreissig
31 -> einunddreissig
40 -> vierzig
41 -> einundvierzig
50 -> fuenfzig
60 -> sechzig
70 -> siebzig
80 -> achtzig
90 -> neunzig
```
TL;DR - 0-12 are irregular, 13-19 are mostly just the number plus zehn, multiples of ten are mostly the number plus zig, and other numbers are the number, und, and then the multiple of ten. There are some irregularities, though.
## Rules
* This is code golf, so the lowest byte count wins.
* Standard loopholes apply.
* Any standard input/output methods are allowed.
* You may use any case you want, as long as it's consistent across different runs.
## Test Cases
```
3 -> drei
12 -> zwoelf
14 -> vierzehn
16 -> sechzehn
30 -> dreissig
52 -> zweiundfuenfzig
90 -> neunzig
```
[Answer]
# JavaScript (ES6), 213 bytes
```
f=(n,m=8,u=n%10)=>n<20?`null ein5 zw26 drei vier fuenf sech7 sieb89 acht neun zehn elf zwoelf`.replace(/\d/g,n=>['enasisn'[(m^n)%10]]).split` `[~~n]||f(u,0)+'zehn':(u?f(u,2)+'und':'')+f(n/=10,0)+(n^3?'zig':'ssig')
```
[Try it online!](https://tio.run/##PZDLboMwEEX3@YrZVLYFAUKaNI9CVv0KSgSFgbhyhgjHqYSi/Dq16WPj0T0zvvP4LG@lrnp5uc6pq3Ecm4STf042vknoaRGJJKXXODoUZJQClLSC4SteQ92jhJvEHhqD1IDG6vQCWuLHZgtldboCoSEY8ESAqrGfOhuKoMeLKivk4Xsdtj4lacaQSi01sYyfjyRszzwXgb4oeS2gyB4Pyu/3hhs/Eh5zfmzHzcGB2AJDNdsxJryGU5gsIlfF6bg8sEG2NqO1DWLcZzMAWPoQhtPoVi3iSf0M5vTzpN1Orosj64m41X7JMvp3cMaWrP5cUNpRplsMU2IbgUu4KziQz4Km69/sZThBkkLVke4UBqprLfCAwTy1jwd2DyHEfvwG "JavaScript (Node.js) – Try It Online") (test cases)
[Try it online!](https://tio.run/##FY3BboMwEETv@Yq9VLYFJUDVNk3i5NQv6JESQWENrpw1wjiV0jS/Ts3pjWZmd77rS@2aUQ/TI9kW51lJTvFZbmIv6SFLhTzQPk@PFXljADU9w/Unf4F2RA0XjSMoj6TAYdO/gtP4tXmDuuknIPQEV@wJ0KhwZAOqZMTB1A3y9We77mKSh4Ih1U47YgU/n0iEzbIUiRuMniqoivudyttNcR@nImLLP7bl/rgYeTA8tWzLmIgUp7XM0qXF6fR0ZFfdhcS5ADErO3ICCekOCPaQpYuIIgG/K4DGkrMGE2M7TslkP6ZRU8dFMtTtO7U8FxAB2wILCDNC7FZ/8z8 "JavaScript (Node.js) – Try It Online") (all values from 0 to 99)
### How?
`eins`, `zwei`, `sechs` and `sieben` have different forms when they're used as prefixes. To support these alternate forms, some letters are encoded as decimal digits:
```
ein5 zw26 sech7 sieb89
```
Given a digit \$n\$ and a parameter \$m\$, the correct letter is obtained with:
```
[ 'enasisn'[(m ^ n) % 10] ]
// 0123456
```
The outer brackets are used to coerce the result to an empty string if it's undefined.
We use:
* \$m=0\$ for a prefix of `zehn` or `zig`
* \$m=2\$ for a prefix of `und`
* \$m=8\$ for the regular form
This gives the following table:
```
m | n | m^n | %10 | letter
---+---+-----+-----+-----------------
0 | 5 | 5 | 5 | 's' -> eins (1)
0 | 2 | 2 | 2 | 'a' \_ zwan (2)
0 | 6 | 6 | 6 | 'n' /
0 | 7 | 7 | 7 | - -> sech
0 | 8 | 8 | 8 | - \_ sieb
0 | 9 | 9 | 9 | - /
---+---+-----+-----+-----------------
2 | 5 | 7 | 7 | - -> ein
2 | 2 | 0 | 0 | 'e' \_ zwei
2 | 6 | 4 | 4 | 'i' /
2 | 7 | 5 | 5 | 's' -> sechs
2 | 8 | 10 | 0 | 'e' \_ sieben
2 | 9 | 11 | 1 | 'n' /
---+---+-----+-----+-----------------
8 | 5 | 13 | 3 | 's' -> eins
8 | 2 | 10 | 0 | 'e' \_ zwei
8 | 6 | 14 | 4 | 'i' /
8 | 7 | 15 | 5 | 's' -> sechs
8 | 8 | 0 | 0 | 'e' \_ sieben
8 | 9 | 1 | 1 | 'n' /
```
*(1) Not used*
*(2) Used for -zig only*
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~162~~ 157 bytes
```
12
zwo11
11
elf
(\d)(.)
$2und$1zig
3z
3ss
0?und1.+
zehn
0und
0
null
1
eins
su
u
2
zwei
eiz
anz
3
drei
4
vier
5
fuenf
6
sechs
7
sieben
8
acht
9
neun
sz|enz
z
```
[Try it online!](https://tio.run/##FYxNDoIwFAb3cw4WoAmh4B8rL@JChIc0Ic@EUk0az@UBvFitybeZSeZbZLXaRdo223w/kJXXaGrC62EMaTKP5JehyMuCrPY6ZCbYO02gcY7qnIwptwSZlCoBVKifZ1Jq1eE8nv@f2CQCnaaSYUm442llYc/oRUcOOOknxxFn5SbKia6fVlpUvOLCW1IbYvwB "Retina 0.8.2 – Try It Online") Link is to test suite that automatically generates the results for `0-99`. Explanation:
```
12
zwo11
11
elf
```
Process `12` and `11` first.
```
(\d)(.)
$2und$1zig
```
For two digit inputs, switch the digits, insert `und`, and suffix `zig`.
```
3z
3ss
```
Except `dreizig` becomes `dreissig`.
```
0?und1.+
zehn
```
`nullundeinzig` becomes `zehn`, as does `undeinzig` when a suffix of any other digit.
```
0und
0
null
```
Delete a `nullund` prefix but a lone `0` becomes `null`.
```
1
eins
su
u
```
`1` becomes `eins` unless it's a prefix in which case it's only `ein`.
```
2
zwei
eiz
anz
```
`2` becomes `zwei` except before `zig` in which case it becomes `zwan`.
```
3
drei
4
vier
5
fuenf
6
sechs
7
sieben
8
acht
9
neun
```
Translate the remaining digits.
```
sz|enz
z
```
Fix up `sechszehn`, `siebenzehn`, `sechszig` and `siebenzig` to `sechzehn`, `siebzehn`, `sechzig` and `siebzig`.
Edit: Saved 4 bytes thanks to @Arnauld.
[Answer]
# [Python](https://www.python.org) + [num2words](https://github.com/savoirfairelinux/num2words), ~~54 107 104~~ 91 bytes
```
lambda n:num2words(n,0,'de').translate({252:'ue',246:'oe',223:'ss'})
from num2words import*
```
+53 bytes because we have to replace non-ASCII with ASCII equivalents.
-3 thanks to *@CreativeName*
-13 thanks to *@Neil*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 127 bytes
```
≔E⪪”&⌈⪪γ,‴\Π↶QBσPc�⁸QDι,ÀH⁸²V≧τ⁼θCUH↶⊙↨H⊖O³j⪫JWX<⸿Dη″β↓”p⪪ιqζNθ≔﹪θχη¿‹θ¹³⁺⌈§ζθ×s⁼θ¹¿‹θ²⁰⁺⌊§ζη⌈§ζχ«∧η⁺⌈§ζηund⌊§ζ÷θχ⎇⁼³÷θχss¦z¦ig
```
[Try it online!](https://tio.run/##dVDNbsIwDD6Pp4hySqVOgnHkhLQdkLYJabxAaV1iKXWdpAHWac/eucA0hFgOsb7E349d2iKUbeGGYRkj7si8FWw@2GFnNCXnGJC4PwD6/lAQVwGQ9wiB6wRUc4TSRj/eHBG2QH4sXJS2Y4IkVLDE4GrRaKXoXGnWWa7OFijQ60xwny0mK@LUvadmC8F4wb@J2iq51vhczabSaeUHa2VeIcbT4zzL1DogdWbtUpQBjtikxiy7FVVwNH2u/OiwwQai0VEivPhUuDM5k7OYgIugrkWfpjeiSLeidhS9YyYh/zS/Jg9nlSVVxubqv4QnMZ2o0ifuhXTHdUXdM@6xgss@rts3EKgIn@Yy3vxOt5jEcQO611dEjTst6HsY5rPhce9@AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔E⪪”...”p⪪ιqζ
```
Split a compressed string on `p` and then split each substring on `q` (for the numbers `2`, `6` and `7`).
```
Nθ≔﹪θχη
```
Input the number in base `10` and take the remainder modulo `10`.
```
¿‹θ¹³
```
If the number is less than `13`, then...
```
⁺⌈§ζθ×s⁼θ¹
```
... output the maximum of the two substrings for that number, plus an extra `s` if the number is `1`.
```
¿‹θ²⁰
```
Otherwise, if the number is less than `20`, then...
```
⁺⌊§ζη⌈§ζχ
```
... output the minimum of the two substrings for that number modulo `10`, plus the substring for `10` (although I could have just used the string literal at this point).
```
«
```
Otherwise:
```
∧η⁺⌈§ζηund
```
If the remainder modulo `10` is not zero, then output the maximum of the two substrings for that number, plus the literal string `und`.
```
⌊§ζ÷θχ
```
Output the minimum of the two substrings for the number integer divided by `10`. This outputs `zwan` for `20-29`, `sech` for `60-69`, and `sieb` for `70-79`.
```
⎇⁼³÷θχss¦z¦ig
```
Output `ssig` if the number is in the range `30-39` otherwise output `zig`.
It looks as if the alternate forms are just the first four letters of the regular form, but this only works if you use the original accented characters, which Charcoal can't compress anyway, and working around the cases of `15` and `50-59` just takes too many bytes.
[Answer]
# Mathematica, 427 bytes
Golfed version, [try it online!](https://tio.run/##dZFNS8QwEIbv/oo1VyO06wes3XpfQVE8eAhBuu10G2gn0CYKu/S315mkKAv2NE9m0nce0q5wDXSFM2UxHaDvCnzx3R56hZ87dEAtvXrIV9OzrXwL6mSlG6XNTwJ92wopwOBA5fgNhkrVh/JloKdSe8Ca6gBlw5cGA3tAgqJsHBUEj2LMHKXRKaQUeDSHOWgYAnJYbIa8iBw5E4VG4tRIHMw0Zh@NKRuVbHPcpom0SuFVqrVMQ2edyHfXGzw8WYPqJI7QsB20dXCxEVhlngSViNElcpCZkW0iBp2IwYdxJIHrjSaD9ex0rrCrFT20QhLUl3kQ/j2z@PZReKz4sbR0Sr156wyg@7swUvb0SoFOnf3NROvs4p/@zUI/XS8NbpcG90srlnbfLe3Y8BfTDw)
```
Module[{o,t},o={"null","eins","zwei","drei","vier","fuenf","sechs","sieben","acht","neun"};t={"","","zwanzig","dreissig","vierzig","fuenfzig","sechzig","siebzig","achtzig","neunzig"};Which[0<=n<10,o[[n+1]],10<=n<20,StringJoin[{"zehn","elf","zwoelf","dreizehn","vierzehn","fuenfzehn","sechzehn","siebzehn","achtzehn","neunzehn"}[[n-9]]],20<=n<100,StringJoin[{If[Mod[n,10]!=0,o[[Mod[n,10]+1]]<>"und",""],t[[Quotient[n,10]+1]]}]]]
```
Ungolfed version
```
germanNumber[n_Integer] := Module[{ones, tens},
ones = {"null", "eins", "zwei", "drei", "vier", "fuenf", "sechs", "sieben", "acht", "neun"};
tens = {"", "", "zwanzig", "dreissig", "vierzig", "fuenfzig", "sechzig", "siebzig", "achtzig", "neunzig"};
Which[
0 <= n < 10, ones[[n + 1]],
10 <= n < 20, StringJoin[{"zehn", "elf", "zwoelf", "dreizehn", "vierzehn", "fuenfzehn", "sechzehn", "siebzehn", "achtzehn", "neunzehn"}[[n - 9]]],
20 <= n < 100, StringJoin[{If[Mod[n, 10] != 0, ones[[Mod[n, 10] + 1]] <> "und", ""], tens[[Quotient[n, 10] + 1]]}]
]
]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 108 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'¡Ö.•вß³á∍>jO5:+VÍÏnтågÏÇ&õL1δç´#₄’WH‹fÈ7Pm•#D9ÝÁè©ć«¦¦®¦¦¦.•8WÏ•š…zig«„iz…iss:.•j(}•3ô'z:®¦ć¨š…und«õšδì)˜Iè
```
[Try it online](https://tio.run/##yy9OTMpM/f9f/dDCw9P0HjUsurDp8PxDmw8vfNTRa5flb2qlHXa493B/3sWmw0vTD/cfblc7vNXH8NyWw8sPbVF@1NTyqGFmuMejhp1phzvMA3KB@pVdLA/PPdx4eMWhlUfaD60@tAwI14HJZSDjLcIP9wOpowsfNSyrykw/tPpRw7zMKiAns7jYCqQgS6MWSBof3qJeZQXSCDRkBVh1aV7KodWHtx5dCLR8jebpOZ6HV/z/b2QIAA) or [verify the entire list](https://tio.run/##yy9OTMpM/f9f/dDCw9P0HjUsurDp8PxDmw8vfNTRa5flb2qlHXa493B/3sWmw0vTD/cfblc7vNXH8NyWw8sPbVF@1NTyqGFmuMejhp1phzvMA3KB@pVdLA/PPdx4eMWhlUfaD60@tAwI14HJZSDjLcIP9wOpowsfNSyrykw/tPpRw7zMKiAns7jYCqQgS6MWSBof3qJeZQXSCDRkBVh1aV7KodWHtx5dCLR8jebpOf/L/OyVFB61TVJQsq/U@Q8A).
**Explanation:**
```
'¡Ö '# Push dictionary string "null"
.•вß³á∍>jO5:+VÍÏnтågÏÇ&õL1δç´#₄’WH‹fÈ7Pm•
# Push compressed string
# "eins zwei drei vier fuenf sechs sieben acht neun zehn elf zwoelf"
# # Split it on spaces to a list
D # Duplicate this list
9Ý # Push a list in the range [0,9]
Á # Rotate it to [9,0,1,2,3,4,5,6,7,8]
è # 0-based index each in the copy: ["zehn","eins","zwei","drei","vier",
# "fuenf","sechs","sieben","acht","neun"]
© # Store this list in variable `®` (without popping)
ć # Extract head; push first item and remainder-list separately
« # Append this "zehn" to each item in the remainder-list
¦¦ # Remove the first two items ("einszehn" and "zeizehn")
® # Push list `®` again
¦¦¦ # Remove the first three items ("zehn", "eins", and "zei")
.•8WÏ•š # Prepend "zwan" to the list
…zig« # Append "zig" to each item in the list
„iz…iss: # Replace all "iz" with "iss"
.•j(}• # Push compressed string "enzsz"
3ô # Split it into parts of size 3: ["enz","sz"]
'z: '# Replace both with "z"
# (with `®¦¦¦.•8WÏ•š…zig«„iz…iss:.•j(}•3ô'z:` we've pushed list
# ["zwanzig","dreissig","vierzig","fuenfzig","sechzig","siebzig",
# "achtzig","neunzig"])
®¦ # Push list `®`, and remove the first item "zehn"
ć # Extract head "eins"
¨ # Remove its last letter "s"
š # Prepend "ein" back to the list
…und« # Append "und" to each item in the list
õš # Prepend an empty string "" to the list
δ # Apply double-vectorized on the two lists:
ì # Prepend
) # Wrap everything on the stack into a list
˜ # Flatten it
Iè # Use the input to 0-based index into it
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'¡Ö` is `"null"`; `.•вß³á∍>jO5:+VÍÏnтågÏÇ&õL1δç´#₄’WH‹fÈ7Pm•` is `"eins zwei drei vier fuenf sechs sieben acht neun zehn elf zwoelf"`; `.•8WÏ•` is `"zwan"`; and `.•j(}•` is `"enzsz"`.
[Answer]
# [Haskell](https://www.haskell.org/), 341 bytes
```
n 0="null"
n 1="eins"
n 10="zehn"
n 11="elf"
n 2="zwei"
n 12="zwoelf"
n 20="zwanzig"
n 3="drei"
n 30="dreissig"
n 4="vier"
n 5="fuenf"
n 6="sechs"
n 16="sechzehn"
n 60="sechzig"
n 7="sieben"
n 17="siebzehn"
n 70="siebzig"
n 8="acht"
n 9="neun"
n t|t<20=n(t-10)++"zehn"
n t|mod t 10==0=n(div t 10)++"zig"
n t=n(mod t 10)++"und"++n(t-mod t 10)
```
[Try it online!](https://tio.run/##PY/BjsIwDETvfEVlcdhVg5S0ULYS4UdWHLrU0IhgVk0KEuLfS5y03OaNR2O7a9wFrR1HyqQGGqyFBWVKAxpyUQb7iR1Fzb49sSyC@0AT3ahv84Dzj4ae5sxYamj7lCtl0s6l0VrD3WDPcqPhNCDFgkqDw2OXlk8wH1DJiVPDNpDBP0zHTTRnt3LilP3R0Bw7z7IOj@IQQ/7ld@Fi@vIrJb/z/POqf11vbeb5fc3z1twjxUxq9MGeQ2wP1EKec9XHHa@NIf3fG/JL2i33v6VQhVBroSpRSrEpRF0fxjc "Haskell – Try It Online")
] |
Subsets and Splits