text
stringlengths 180
608k
|
---|
[Question]
[
# Credits
This challenge originated from [@miles](https://codegolf.stackexchange.com/users/6710/miles).
---
Create a function that computes the CRC32 hash of an input string. The input will be an ASCII string of any length. The output will be the CRC32 hash of that input string.
# Explanation
The algorithm of CRC32 and other CRC are essentially the same, so only CRC3 will be demonstrated here.
Firstly, you have the generator polynomial, which is actually a 4-bit [n+1] integer (would be 33-bit in CRC32).
In this example, the generator polynomial is `1101`.
Then, you will have the string to be hashed, which in this example would be `00010010111100101011001101`.
```
00010010111100101011001101|000 (1) append three [n] "0"s
1101 (2) align with highest bit
00001000111100101011001101|000 (3) XOR (1) and (2)
1101 (4) align with highest bit
00000101111100101011001101|000 (5) XOR (3) and (4)
1101 (6) align with highest bit
00000011011100101011001101|000 (7) XOR (5) and (6)
1101 (8) align with highest bit
00000000001100101011001101|000 (9) XOR (7) and (8)
1101 (10) align with highest bit
00000000000001101011001101|000 (11) XOR (9) and (10)
1101 (12) align with highest bit
00000000000000000011001101|000 (13) XOR (11) and (12)
1101 (14) align with highest bit
00000000000000000000011101|000 (15) XOR (13) and (14)
1101 (16) align with highest bit
00000000000000000000000111|000 (17) XOR (15) and (16)
110 1 (18) align with highest bit
00000000000000000000000001|100 (19) XOR (17) and (18)
1 101 (20) align with highest bit
00000000000000000000000000|001 (21) XOR (19) and (20)
^--------REGION 1--------^ ^2^
```
The remainder obtained at `(21)`, when region 1 is zero, which is `001`, would be the result of the CRC3 hash.
# Specs
* The generator polynomial is `0x104C11DB7`, or `0b100000100110000010001110110110111`, or `4374732215`.
* Input can be a string or a list of integers, or any other reasonable format.
* Output be a hex string or just an integer, or any other reasonable format.
* Built-ins that compute the CRC32 hash are not allowed.
# Goal
Standard rules for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply.
The shortest code wins.
## Test cases
```
input output (hex)
"code-golf" 147743960 08CE64D8
"jelly" 1699969158 65537886
"" 0 00000000
```
[Answer]
# Intel x86, ~~34~~ ~~30~~ ~~29~~ 27 bytes
Takes the address of the zero-terminated string in ESI, and returns the CRC in EBX:
```
31 db ac c1 e0 18 74 01 31 c3 6a 08 59 01 db 73
06 81 f3 b7 1d c1 04 e2 f4 eb e7
```
**Disassembly (AT&T syntax):**
```
00000000 xorl %ebx, %ebx
00000002 lodsb (%esi), %al
00000003 shll $24, %eax
00000006 je 0x9
00000008 xorl %eax, %ebx
0000000a pushl $8
0000000c popl %ecx
0000000d addl %ebx, %ebx
0000000f jae 0x17
00000011 xorl $0x4c11db7, %ebx
00000017 loop 0xd
00000019 jmp 0x2
0000001b
```
Incorporating suggestions from Peter Cordes to save four more bytes. This assumes a calling convention where the direction flag for string instructions is cleared on entry.
Incorporating suggestion of Peter Ferrie to use push literal and pop to load a constant, saving one byte.
Incorporating suggestion of Peter Ferrie to jump to the second byte of an `xorl %eax, %ebx` instruction which is a `retl` instruction, combined with changing the interface of the routine to take a zero-terminated string instead of length, saving two bytes in total.
[Answer]
# Jelly, 34 bytes
```
l2_32Ḟ4374732215æ«^
Oḅ⁹æ«32Çæ»32$¿
```
[Try it online!](http://jelly.tryitonline.net/#code=bDJfMzLhuJ40Mzc0NzMyMjE1w6bCq14KT-G4heKBucOmwqszMsOHw6bCuzMyJMK_&input=&args=Y29kZS1nb2xm)
[Answer]
# Ruby, 142 bytes
Anonymous function; takes a string as input, returns an integer.
```
->s{z=8*i=s.size;r=0;h=4374732215<<z
l=->n{j=0;j+=1 while 0<n/=2;j}
s.bytes.map{|e|r+=e*256**(i-=1)};r<<=32
z.times{h/=2;r^=l[h]==l[r]?h:0}
r}
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḅ⁹Bµ4374732215B×ḢḊ^µL¡Ḅ
```
Input is in form of a list of integers. [Try it online!](http://jelly.tryitonline.net/#code=4biF4oG5QsK1NDM3NDczMjIxNULDl-G4ouG4il7CtUzCoeG4hA&input=&args=Wzk5LCAxMTEsIDEwMCwgMTAxLCA0NSwgMTAzLCAxMTEsIDEwOCwgMTAyXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=4biF4oG5QsK1NDM3NDczMjIxNULDl-G4ouG4il7CtUzCoeG4hApPw4figqxH&input=&args=WyJjb2RlLWdvbGYiLCAiamVsbHkiLCAiIl0).
### How it works
While Jelly has bitwise XOR, padding the input with zeroes and aligning the polynomial with the most significant binary digit makes this approach, which uses lists of bits instead, a tad shorter.
```
ḅ⁹Bµ4374732215B×ḢḊ^µL¡Ḅ Main link. Argument: A (list of bytes)
ḅ⁹ Convert A from base 256 to integer.
B Convert the result to binary, yielding a list.
µ Begin a new, monadic chain. Argument: B (list of bits)
4374732215B Convert the integer to binary, yielding a list.
Ḣ Pop and yield the first, most significant bit of B.
× Multiply each bit in the polynomial by the popped bit.
^ Compute the element-wise XOR of both lists.
If one of the lists is shorter, the elements of the other
lists do not get modified, thus avoiding the necessity
of right-padding B with zeroes.
µ Convert the previous chain into a link.
L¡ Execute the chain L times, where L is the number of bits
in the original bit list.
Ḅ Convert from binary to integer.
```
[Answer]
# Pyth, 42 bytes
```
?!Q0h<#^2 32.uxN.<4374732215.as-lN32.<CQ32
```
[Test suite.](http://pyth.herokuapp.com/?code=%3F!Q0h%3C%23%5E2+32.uxN.%3C4374732215.as-lN32.%3CCQ32&test_suite=1&test_suite_input=%22code-golf%22%0A%22jelly%22%0A%22%22&debug=0)
[Answer]
## CJam, ~~37~~ 36 bytes
```
q256b32m<{Yb4374732215Yb.^Yb_Yb32>}g
```
[Test it here.](http://cjam.aditsu.net/#code=q256b32m%3C%7BYb4374732215Yb.%5EYb_Yb32%3E%7Dg&input=code-golf)
### Explanation
```
q e# Read input.
256b e# Convert to single number by treating the character codes
e# as base-256 digits.
32m< e# Left-shift the number by 32 bits, effectively appending 32
e# zeros to the binary representation.
{ e# While the condition on top of the stack is truthy...
Yb e# Convert the number to base 2.
4374732215Yb e# Convert the polynomial to base 2.
.^ e# Take the bitwise XOR. If the number is longer than the
e# polynomial, the remaining bits will be left unchanged.
Yb e# Convert the list back from base 2, effectively stripping
e# leading zeros for the next iteration.
_ e# Duplicate the result.
Yb e# Convert back to base 2.
32> e# Remove the first 32 bits. If any are left, continue the loop.
}g
```
[Answer]
# Pyth, 28 bytes
```
uhS+GmxG.<C"Á·"dlhG.<Cz32
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=uhS%2BGmxG.%3CC%22%01%04%C3%81%1D%C2%B7%22dlhG.%3CCz32&input=code-golf&test_suite_input=code-golf%0Ajelly%0A&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=uhS%2BGmxG.%3CC%22%01%04%C3%81%1D%C2%B7%22dlhG.%3CCz32&input=code-golf&test_suite=1&test_suite_input=code-golf%0Ajelly%0A&debug=0)
### Explanation:
```
uhS+GmxG.<C"..."dlhG.<Cz32 implicit: z = input string
Cz convert to number
.< 32 shift it by 32 bits
u apply the following expression to G = ^,
until it get stuck in a loop:
m lhG map each d in range(0, log2(G+1)) to:
C"..." convert this string to a number (4374732215)
.< d shift it by d bits
xG xor with G
+G add G to this list
hS take the minimum as new G
```
[Answer]
## JavaScript (ES6), 180 bytes
```
f=(s,t=(s+`\0\0\0\0`).replace(/[^]/g,(c,i)=>(c.charCodeAt()+256*!!i).toString(2).slice(!!i)))=>t[32]?f(s,t.replace(/.(.{32})/,(_,m)=>(('0b'+m^79764919)>>>0).toString(2))):+('0b'+t)
```
The lack of a 33-bit XOR operator, or even an unsigned 32-bit XOR operator, is unhelpful.
[Answer]
# CJam, 33 bytes
```
q256bYb_,{(4374732215Ybf*1>.^}*Yb
```
Input is in form of a string. [Try it online!](http://cjam.tryitonline.net/#code=cTI1NmJZYl8seyg0Mzc0NzMyMjE1WWJmKjE-Ll59Klli&input=Y29kZS1nb2xm)
### How it works
```
q Read all input from STDIN.
256bYb Convert it from base 256 to base 2.
_,{ }* Compute the length and repeat that many times:
( Shift out the first bit.
4374732215Yb Convert the integer to base 2.
f* Multiply each bit by the shifted out bit.
1> Remove the first bit.
.^ Compute the element-wise XOR of both lists.
If one of the lists is shorter, the elements
of the other lists do not get modified, thus
avoiding the necessity of right-padding B with
zeroes.
Yb Convert the final result from base 2 to integer.
```
] |
[Question]
[
# Introduction
You're playing a matching game, in which coins are inserted at the top and fall to the bottom (onto the top coin) due to gravity.
So this
```
O <- inserting this coin
OO O
OOOOO
```
will become this
```
O
OO O
OOOOO
```
Now imagine someone rotates the board clockwise. The following will happen:
### 1. The board is rotated
```
OOO
OO
O
OO
O
```
### 2. Coins fall down due to gravity
```
O
O
OO
OO
OOO
```
# Your task
Your task is to simulate the rotation of the board by writing a program or a function. For the sake of simplicity we're only dealing with one kind of coin (it's not a too exciting matching game, is it…). You can assume that gravity is applied only after the rotation is complete. The board is rotated clockwise.
# Input
The input is going to be a string, which contains 3 types of characters:
* O (capital o) OR 0 (zero) - a coin (you decide which one your solution supports)
* (space) - an empty field
* \n (new line) - end of row
The input represents the state of the board. You can assume, the input is well formed and contains a valid state of the board (no coins are floating).
The input can be a function parameter, or can be read from the standard input or from a file.
# Output
The output is the new state of the board after rotation. The output contains the same 3 types of characters as the input. The output can be returned from your function or can be written to the standard output or to a file.
# Sample
Input1:
```
O
OO O
OOOOO
```
Output1:
```
O
O
OO
OO
OOO
```
Input2:
```
O O
O O
```
Output2:
```
OO
OO
```
You can use any language and the standard library of the chosen language. Shortest program in bytes wins.
[Answer]
### GolfScript, 14 12 characters
```
' '-n%zip$n*
```
Input must be given on STDIN, the character for coins can be any non-whitespace characters. Try [here](http://golfscript.apphb.com/?c=OydPCk9PIE8KT09PT08nCgonICctbiV6aXAkbioK&run=true). Thanks to Peter for pointing out a two character reduction.
[Answer]
# Javascript (E6) 103
First try, just matrix operations. Each row in input string need to be padded.
Quite wordy.
```
R=t=>(x=t.split('\n').reverse().map(x=>[...x].sort()),x.map((c,i)=>x.map(r=>r[i]).join('')).join('\n'))
```
**Pseudo code**
1. string -> array of rows
2. up/down reverse array
3. each row -> char array
4. sort each row (coins 'fall' to right)
5. transpose
6. each char array in a row -> a string
7. join array -> single string
[Answer]
## Ruby 2.0, 59 characters
```
puts$<.map(&:chars).reverse.transpose.sort[1,50].map &:join
```
Input via stdin, assumes lines all have the same length. This is probably much longer than necessary. But at least it's readable ...
[Answer]
## J - ~~49~~ ~~31~~ 24 bytes
I think there might be unnecessary rotations in there, but otherwise it works fine. It's a function that takes the input as specified, coins being `O`. No trailing whitespace is required in the input.
New version, inspired by [edc65's Javascript answer](https://codegolf.stackexchange.com/a/32644/20356):
```
f=:[:|."1@|:[:/:~"1,;._2
```
Explanation:
```
f=:[:|."1@|:[:/:~"1,;._2
,;._2 Split the string at every fret, which is the last character in the string (newline).
/:~"1 Sort every row separately.
|."1@|: Rotate the array clockwise.
```
---
Old version:
```
f=:[:|:((#~=&' '),=&'O'#])"1@|:@(|."1@|:)@(,;._2)
```
Explanation:
```
f=:[:|:((#~=&' '),=&'O'#])"1@|:@(|."1@|:)@(,;._2)
(,;._2) Split the string at every fret, which is the last character in the string (newline).
(|."1@|:)@ Rotate the array clockwise.
|:@ Reverse the axes (columns become rows and vice-versa).
((#~=&' '),=&'O'#])"1 Function that applies the "gravity"
"1 Apply to every row separately:
=&'O'#] Get the O's in the row.
(#~=&' ') Get the spaces in the row.
, Join them, spaces come first.
[:|: Reverse axes again.
```
---
Examples (note that multiline strings start with `0 : 0` and end withh a bracket):
```
f 0 : 0
O
OO O
OOOOO
) NB. output starts now
O
O
OO
OO
OOO
f 0 : 0
O O
O O
) NB. Output starts now.
OO
OO
```
[Answer]
### Haskell — 86
Just learning, so I'm sure this can be improved.
```
import Data.List
c=putStr.unlines.filter(/="").sort.map(filter(/=' ')).transpose.lines
```
Sample Input:
```
let a = "O \nOO O \nOOOOO"
let b = " O O \n O O "
c a
c b
```
Sample Output:
```
O
O
OO
OO
OOO
OO
OO
```
[Answer]
# Python 2 (69) (79)
```
for c in sorted(zip(*raw_input().split("\\n"))):print''.join(c[::-1])
```
Takes input padded with spaces so all lines have equal length. The `split` creates an arrat of each line. The `zip` effectively transposes the array. Then, the `sorted` sorts tuples in lexicographic order, causing all coins to fall to the bottom. Finally, we print each line, turning it back into a string, though we must reverse it first. Doing `print'O'*c.count('O')` is equivalent and uses the same number of characters.
Example run:
```
>> O \nOO O \nOOOOO
O
O
OO
OO
OOO
```
[Answer]
## C, ~~167~~ 119 bytes
This shorter version is (unfortunately?) much clearer than the original too.
```
m;j;b[99];r;main(){while(j=getchar()+1)j-11?m+=j-33&&++b[r]>m:++r;for(j=r;m+1;putchar(j--?m<b[j]?79:32:(j=r,m--,10)));}
```
[Answer]
# Racket: 130
```
(let l((a'()))(let((b(sort(string->list(read-line))char<?)))(if
(null? b)(apply map(λ x(map display x)(newline))a)(l(cons b a)))))
```
It requires you pad with spaces so the lines are equal lemgth.
[Answer]
## C# - ~~209~~ 174 bytes
Right, I have to try this Code golf at some point I reckon. Created a function (r) that rotates the board and prints it. I guess I'm cheating a little when I am printing my char array, but if you cannot figure out why you shouldn't be mad :)
Thanks to ProgramFOX for the tips :)
```
void r(string s){int x=s.IndexOf('\n'),j,i=-1,k,z=x+1;var y=new char[x*x+x];for(;++i<x;y[z*(i+1)-1]='\n')for(k=j=x;j>0;)if(s[i*z+--j]=='0')y[k--*z-i-2]='0';Console.Write(y);}
```
Cheat
>
> `new char[x*x+x]` fills the array with `'\0'` and not `' '`
>
>
>
] |
[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 1 year ago.
[Improve this question](/posts/11791/edit)
If you use OS X then you might be familiar with the infamous hidden ".DS\_Store" files that are produced as a result of using Finder.
The challenge is to write code that will go through the entire file system and delete any file named ".DS\_Store".
Classic code golf - shortest code wins.
---
**Clarifications:**
* The code does *not* need to delete any .DS\_Store files that require superuser; assume no such files exist.
* The code should *only* delete the relevant .DS\_Store files and nothing else.
[Answer]
# zsh, 19
```
rm -f /**/.DS_Store
```
(Make that 16 if it's ok to leave out `-f`.)
[Answer]
### Bash\*, 40 30
```
find / -name .DS_Store -delete
```
```
find / -name .DS_Store -exec rm -f {} \;
```
This should handle it (not very golfed, not.to.mention marvelously slow).
Bash seems right because we don't have to deal with any "import system" nonsense. If you want to require execution in any environment, add 4 chars for `bash` and 1 for a line feed.
\*any shell I guess, just can't get out of the habit assuming the bourne again shell is the only one.
[Answer]
# Ruby: ~~38~~ 33 characters
```
File.delete *Dir['/**/.DS_Store']
```
[Answer]
# fish, 16
```
rm /**/.DS_Store
```
(Make that 19 if `-f` is required to delete `.DS_Store` in read-only directories.)
[Answer]
# Shell, 25
```
locate .DS_Store|xargs rm
```
Requires working `locate` database.
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
```
import os
d='.DS_Store'
for r,_,f in os.walk('/'):
if d in f:os.remove(r+'/'+d)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCG/mCvFVl3PJTg@uCS/KFWdKy2/SKFIJ14nTSEzDyirV56Yk62hrq@uacWlkJmmkAISTrMCShSl5uaXpWoUaQMltVM0//8HAA "Python 3 – Try It Online")
By no means competable, but just for the sake of it :)
[Answer]
# CMD, 17
```
del/s "/.DS_Store
```
Pretty straight-forward.
`/s` is required for searching within subdirectories as well.
`"` is used to escape the `/` char which would otherwise be interpreted as an (invalid) argument.
[Answer]
# find, 38
The previus `find` solution is plain wrong: it's mean to delete everything named `.DS_Store` including directory, links, special file etc.
But:
```
find / -type f -name .DS_Store -delete
```
it's the minimal solution using `find`.
**DISCLAMER**: I strongly advice against really using this solution on a real \*nix box: trying to delete something recursively from `/` is a very **bad** idea. You are warned.
**EDIT** :
If the differences among files, directorys, links (hard and symbolic), named pipes, sockets, special files, pseudo-file systems is not clear to you, I suggest to google some of this unknown terms. You'll be surprise, wiser, and less prone to (catstrofic) errors.
**EDIT2** :
Even more relevant : the OP wrote "The code should only delete the relevant .DS\_Store files and nothing else." : so, if someone care to read the **boring** requirements, all solutions that remove more than this files hare funny, smart, ect. but *wrong*.
] |
[Question]
[
The task is simple, divide, get the quotient and the remainder, and if the remainder isn't 1 or 0, do the same thing (quotient divmod remainder) until the remainder is 1 or 0, then get the remainder. If the last input number is 1 or 0, output it.
If the input is `[15, 4]`, then the output would be `0`, because the divmod of `15` and `4` is `[3, 3]` which if you do it again, you get `[1, 0]`, and you can't divmod further, then get the last element, and you got `0`.
Another example would be `[102, 7]`, which if you divmod, you get `[14, 4]`, which if you do again, you get `[3, 2]`, which if you divmod again, you get `[1, 1]`, and you get the last element `1`, which is the output.
Both input numbers are assumed to be non-negative integers less than 1000.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program/function in bytes wins.
## Testcases:
```
[15, 4] => 0
[102, 7] => 1
[20, 2] => 0
[10, 0] => 0
[11, 1] => 1
[99, 7] => 1
[45, 45] => 0
[31, 30] => 1
[999, 7] => 0
[999, 6] => 1
[88, 7] => 0
[1, 999] => 1
[98, 7] => 0
[999, 998] => 1
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
ʷ{Ƶþ
```
```
ʷ{Ƶþ
ʷ{ While; run the following code until it fails
Ƶ Check if the absolute value of the top of the stack is greater than 1
þ Divmod
```
Both `Ƶ` and `þ` are new built-ins in [Nekomata 0.5.1](https://github.com/AlephAlpha/Nekomata/releases/tag/v0.5.1.0), which is not yet on ATO.
[Answer]
# JavaScript (ES6), 27 bytes
```
f=(p,q)=>q>1?f(p/q|0,p%q):q
```
[Try it online!](https://tio.run/##hc9NDoIwEAXgvaeYjUmbVDvDj7Ym4FkIgtEQ2opx5d0rVTcYiusv772Za/Wohvp2sfdNb06N923BrHC8KF1Jx5ZZ6Z4o7Nrxg/O16QfTNdvOnFnLgHIBABnnICXgaqqESdD9R@lHIcGgyXwW6K0YUwpKkWatl3azcHOWR5rT0JzifFZPmnFed5FdpRay4zNivFvHPlL/drVW36x/AQ "JavaScript (Node.js) – Try It Online")
Or **[25 bytes](https://tio.run/##jY/LDoIwEEX3fsVsTNqkSqegUhPwWwhSoyF9iPH3K1Q2kgxxM5sz99yZR/NuhvZ596@dddcuRlMxLwKv6lDjxTCfBeG3gZ9DbJ0dXN/te3djhgEerACAwnIOWQZy88tRqsRPM8cFByUTV0Qe8MslyTFxpPxar/cX6f5xEv48@XNJ5PXCLwl@pPrLcjU/fSZgslD/lX/063FrzscP)** with BigInts.
[Answer]
# [Python 2](https://docs.python.org/2/), 35 bytes
```
f=lambda a,b:f(a/b,a%b)if b>1else b
```
[Try it online!](https://tio.run/##XY/RasMgFIbvfYpDYESH6zRttyRgXyQtQ1nchNRIYqF7@kyXasvO3c//fedw3I//Hm21LFoM8qw@JUiqWo3lq6LySRGjQR14P8w9qMWDgKIoOr6nsDuBOABDHWcVhfe/xFFXMQrVvaLAcuAUeMKa5sHZxXX7xG0Dt2V3MJPslt5SV9cPVbBCm7X6v9U09VqGBxDS4wSDsT0YC34zu8F4XB5tSVoEYeT0NX/4/uopjBfvLvHxiCcyLipJRkN7lg4bG/isdrx94adk0MCvgpsChzV@jiQBISDm9Qwhyy8 "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org), 33 bytes
```
f=\(x,y)`if`(y>1,f(x%/%y,x%%y),y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWNxXTbGM0KnQqNRMy0xI0Ku0MddI0KlT1VSt1KlRVKzWBEhCFG9I0DA2MdMw1uYAMUx0TqDDMHAA)
A recursive function taking two arguments and returning 1 or 0.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 27 bytes
```
f(a,b){a=b>1?f(a/b,a%b):b;}
```
[Try it online!](https://tio.run/##NY7JjsJADETv/ooSKCgtNUw6bGkyCR8yM4deWFqCBrGIA8q3BzcafLBcz1WW3XjnXN9vcyOteJrGtmrN4stKk1mxsnXXD0N0h7vf4Pt68@E02bdEId5wNCHmAk8CVwJGwtb0lo99OGyQX52J23yQeWT@Nw4kRuwZWYGmQfmJpjpf@AA7fzIv2fuHpv1E0lWJ9CCsEPU70lHXqzlmpIoSSyoLlDyiIKWgSGtmM17PaaowLRgkkvqCqopHBRakq3@qdUUv "C (gcc) – Try It Online")
[Answer]
# x86-32 machine code, 9 bytes
## x86-64 machine code, 10 bytes, same asm source
Args in EAX (dividend), ECX (divisor), return value in ECX (0 or 1 final remainder).
To call from C, `gcc -mregparm=3` will put args in EAX, EDX, ECX in that order (so a dummy second arg works), but won't look for retval in ECX. Returning in EAX costs 1 extra byte for `xchg eax,ecx` at the end.
Args must be signed non-negative. (At least the dividend must be; the divisor can be full-range 32-bit unsigned. And the first remainder must also be non-negative). Divisor must be non-zero or the first iteration will fault.
```
divmod_repeat:
.loop:
99 cdq ; zero-extend (for numbers that fit as non-negative integers)
F7F1 div ecx ; EAX = EDX:EAX/ecx unsigned; EDX = remainder
89D1 mov ecx, edx
4A dec edx ; 1 byte instruction in 32-bit mode
7FF8 jg .loop ; }while(remainder-- > 1); or }while(--rem > 0)
C3 ret
; cmp ecx, 2 ; simple but less golfed version
; jae .loop ; }while(new_divisor >= 2);
```
This shows a hexdump of the 32-bit machine code on the left, from a NASM listing. The x86-64 version (still using 32-bit operand-size) uses `FFCA dec edx`.
Not much scope for golfing, other than choosing a good calling convention. `div` only works with EDX:EAX / src, producing its outputs in EDX (remainder) and EAX (quotient). We don't want to touch quotient, so all the special-case accumulator short-form encodings of instructions like `xchg eax, reg` and `cmp al, imm8`.
But we can destroy the old copy of the remainder in EDX after copying it to ECX as the new divisor (or return value). So we can use 1-byte (in 32-bit mode) `dec reg` to set FLAGS instead of `cmp`. The next iteration's `cdq` will overwrite EDX anyway, and we need `cdq` anyway.
We can only use signed conditions with `dec` because it leaves CF unmodified, but is otherwise like `sub` or `cmp ecx, 1`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes
```
.+
$*
+`(..+)¶(\1)*(.*)
$3¶$#2$*
^.
```
[Try it online!](https://tio.run/##XYxNCsIwEEb3OcWAEfLHkElbTRZ6kVSpoAs3LsSz9QC9WIzVpMXV8PHem@ftdX9c0lYMKPqrlgbmg4pxN42cEmrGFdODQNRyGkVPUglUkvEm843L8IwpReoMtCc4HMGySNYZ2M@LWHTWgFuQAVsHGaCihbBq2s@7rnhN9hq7iNW0v7UrzPsVylWmNfP/VQj@C98 "Retina 0.8.2 – Try It Online") Takes the integers in reverse order on separate lines but link is to test suite that takes input in the format given in the question. Explanation:
```
.+
$*
```
Convert to unary.
```
(..+)¶(\1)*(.*)
$3¶$#2$*
```
If the denominator is at least `2`, divmod the numerator by the denominator, replacing the denominator by the remainder and the numerator by the quotient.
```
+`
```
Repeat until the denominator is reduced to less than `2`.
```
^.
```
Convert the denominator to `0` or `1`.
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 13 bytes
```
⊙◌⍢(:⌊⊃÷◿|>1)
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4oqZ4peM4o2iKDrijIriioPDt-KXv3w-MSkKCmYgNCAxNQpmIDcgMTAyCmYgMiAyMApmIDAgMTAKZiAxIDExCmYgNyA5OQpmIDQ1IDQ1CmYgMzAgMzEKZiA3IDk5OQpmIDYgOTk5CmYgNyA4OApmIDk5OSAxCmYgNyA5OApmIDk5OCA5OTkK)
```
⊙◌⍢(:⌊⊃÷◿|>1)
⍢( | ) # while
>1 # top of stack is greater than one
⊃÷◿ # quotient and remainder
⌊ # take the floor of the quotient
: # swap so remainder is on top
⊙◌ # drop the quotient from the stack
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[`D!#‰
```
[Try it online](https://tio.run/##yy9OTMpM/f8/OsFFUflRwwYgy9DASMc8FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/6AQXReVHDRv@1@r8j442NNUxidWJNjQw0jEH0kYGOkZgro4BiDLUMQRSlpZgOROgUlMgbWyoY2wAFoaIg2gzIG1hAeYa6gAFQMIWcFlLSwuwBMgwkMmxAA).
**Explanation:**
```
[ # Start an infinite loop:
` # Pop and push both values in the pair separately to the stack
# (which will use the implicit input-pair in the first iteration)
D # Duplicate the top value (the remainder)
! # Take its factorial (0 becomes 1; 1 remains 1; ≥2 becomes larger)
# # If it's truthy (==1), stop the infinite loop
# (after which the duplicated remainder is output implicitly as result)
‰ # (else) Divmod the two values
```
[Answer]
# [Funge-98](https://esolangs.org/wiki/Funge-98), 51 bytes
```
v >.@ @.<
> "HTRF"4 (&& v
\/RRw1`1:%OOw1`1:<
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//8vU1BQsNNzAJIOejZcdkBaQckjJMhNyURBQ01NoYwrRj8oqNwwwdBK1d8fTNv8/29oymXCBQA)
[Answer]
# Scratch, ~~77~~ 70 bytes
Ports @enzo's answer. Run without screen refresh.
```
define(x)(y
if<(y)>(1)>then
([floor v]of((x)/(y)))((x)mod(y
else
say(y
```
[](https://i.stack.imgur.com/yOTqr.png)
[Answer]
# [Go](https://go.dev), 47 bytes
```
func(a,b int)int{for b>1{a,b=a/b,a%b}
return b}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVHNSsQwEMZrnmIsFloYu-3-aFfIgqBXEe1NRZJusxTdbMmmooQ-hicvi-BDrU9j0tZd9JDJzHzfN5mZfHwuVpvtUcXyJ7YoYMlKSUi5rFZKR55Yao-QF6ZAAIWvWovjdDsQtcwDhhxKqUN7jFgp4LPE2BxlA47M5w1Rha6VBN50su-Dd_1WFZDBWqs61-DYWLxWrkpDiCvavh6EYIgu1noNZxTuHjJDTDJBGCPEDVo_HiKcIiQuGMYIwx1gnV8_sYSeM53u-WNXaNKTRpYxinesjhbvgpMeSdM9YBUt1knSf4qpyzjIznOt7FzPMvAopXCbnd9kYD0vJG5Zj6jdcIpJu_JuVkNY3iZFoCOGOuIhKQW45CEFHblNGWirisDz5wj-HOjM2cCfh_fSQ3BCazg6GXaiEBrbzp9u4PLqAvpu-t_ZbLr7Bw)
[Answer]
## Google Sheets, 74 bytes
```
=LET(F,LAMBDA(F,d,m,LET(x,MOD(d,m),IF(x<2,x,F(F,INT(d/m),x)))),F(F,A1,A2))
```
Simple recursive function that stops the execution when the remainder is 0 or 1.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
eu?>eG1.DF
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72koLIkY8ESt0C9wKWlJWm6FqtSS-3tUt0N9VzcIAILINSyaCXdFKXYm9XRsVzRhqY6CiYg2sBIR8EcyDAy0FEwAgvoKBiAaEMdBUMgbWkJkTcBaTAFMoyBEsYGYBmoFJhhBmRYWEAEgCqAYiAZCyQVlpYWsRCXAAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
d/ỊṪ¬Ɗ¿Ṫ
```
[Try it online!](https://tio.run/##y0rNyan8/z9F/@Huroc7Vx1ac6zr0H4g4//DnfusHzXMUdC1U3jUMNf6cDtQQIXr6OSHOxeDhG3tgKIPdyw6OinscDvXw91bDrc/aloT@f9/tKGpjoJJLFCBggFXtKGBkY6COZhnyBVtZKCjYISQ0lEwgHMMdRQMYcosLZH0mICMM4WpMwaqMzZAKISrNIDyzGByFhZIUkBdQFm4Ngt0XZaWFhBJAA "Jelly – Try It Online")
A monadic link taking a pair of non-negative integers and returning 1 or 0.
## Explanation
```
Ɗ¿ | While the following is true:
Ị | - <= 1
Ṫ | - Tail (i.e. second list member)
¬ | - Not
d/ | … Reduce using divmod
Ṫ | Tail
```
If we were allowed to guarantee the second input were non-zero, this is shorter:
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
d/%/¿ṪỊ
```
[Try it online!](https://tio.run/##y0rNyan8/z9FX1X/0P6HO1c93N31/@HOfdaPGuYo6NopPGqYa324HSigwnV08sOdi0HCtnZA0Yc7Fh2dFHa4nevh7i2H2x81rYn8/z/a0FRHwSQWqEDBgCva0MBIR8EczDPkijYy0FEwgksZ6igYwmQsLZGUmYBMMIWpMwaqMzZAKISrNIDyzGByFhZIUkBdQFm4Ngt0XZaWFhBJAA "Jelly – Try It Online")
[Answer]
# TI-BASIC, 37 bytes
```
While 1<Ans(2
Ans→L
Ans(1)/Ans(2
int({Ans,ʟL(2)fPart(Ans
End
Ans(2
```
Takes input in `Ans`. Replace the second to fourth lines with `int({Ans(1)/Ans(2),remainder(Ans(1),Ans(2` for -2 bytes if `remainder(` is supported.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
NθNηW∧⊖ηη«≔﹪θιη≔÷θιθ»Iη
```
[Try it online!](https://tio.run/##Tc29CsIwFIbh2VxFxhOos4VMxS4dLN5CTA4mkJ7Y/NRBvPYYBcXx5YHv01ZFHZSvdaJbyXNZLhhhFZL9t219t84jh4EMjKgjLkgZTaOOWyH4g@2GlNyV4BRM8QHWjruPyZ9MlEe3OYNffP882Tk6ynBUKbc1IWvte3ao@82/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Lack of divmod and recursion makes this annoyingly long.
```
NθNη
```
Input the two values.
```
W∧⊖ηη«
```
Compare the second value against both `1` and `0`, but in such a way that if it is neither than the implicit loop variable has the same value.
```
≔﹪θιη≔÷θιθ
```
Modulo and divide the first value by the copy of the second, thus allowing the second and first values to be safely overwritten.
```
»Iη
```
Output the final value.
[Answer]
# [Perl 5](https://www.perl.org/) `-Minteger -ap`, 37 bytes
```
@F=("@F"/$_,"@F"%$_)while($_=$F[1])>1
```
[Try it online!](https://tio.run/##K0gtyjH9/9/BzVZDycFNSV8lXgdEq6rEa5ZnZOakaqjE26q4RRvGatoZ/v9vaGCko2D@L7@gJDM/r/i/rq@pnoGhAZDOzCtJTU8t@q@bWJADAA "Perl 5 – Try It Online")
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 18 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{1<⍵:(⌊⍺÷⍵)∇⍵|⍺⋄⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qza0edS71UrjUU/Xo95dh7cDOZqPOtqBVA2Q/6i7BciqBQA&f=TYqxEQAhDMN6T8EIcYD/ZCH2HwETGiqdJXO21QZoLv5wE1xTMJACkVlt1HWiH9tN@vrLDxE1T5VCxlMzYwM&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f)
A dfn that takes the first number as the left argument and the second number as the right argument.
[Answer]
# [TypeScript](https://www.typescriptlang.org/)'s type system, 97 bytes
```
//@ts-ignore
type M<A,B,T=[]>=A extends[...B,...infer I]?M<I,B,[...T,1]>:A extends[1]|[]?A:M<T,A>
```
[Try it at the TypeScript playground!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAWQB4BBAGgCFKAVAXgG0BdAPgfMPQA9x1EAE0hMAdONrjRsRADN0qQgEkWAfjJKalMeLqUAjOwBcXXvyEjDAH1aryRsnvJtMmEIQBiyZP0XBCdOiQ4IQAxgCGkEGuuASEAKqI4ag4pABy3HwCwoSIAK4AtgBGCpSEAPKZ5jn6rIQMhKxs9RVV2ZCEAN6EADYC8OAAFkaEGQC+hKqtI4nJqWllOqLlZYYusUSBwRRtFrmFJahl1Ls5+cUKzQ1ksykUbGW3qdRsbADcMfibQeD6LVvgUj6ACsZQALC53IRCAA9VTYL4BH4AJn+PyBAAZkWUAOyQ-zQuEIuIAgDMaO2yIxZWR+OhsPhGyRwTBFMB+n0qzphMZiIBwLZpAAnELcdyGcTvsEAGyCsGgwjy8VEoA)
I/O is unary numbers / tuples of 1s.
Modified from [my solution](https://codegolf.stackexchange.com/a/263394) to [Division and remainder](https://codegolf.stackexchange.com/questions/114003/division-and-remainder).
[Answer]
**[T-SQL](https://learn.microsoft.com/en-us/sql/t-sql/language-reference?view=sql-server-ver16) 77 bytes**
```
declare @x int = 88, @y int = 7, @z int
```
```
while @y > 1 BEGIN
select @z = @x/@y, @y = @x-(@z*@y)
set @x = @z
end
select @y
```
[Try it!](https://sqlfiddle.com/sql-server/online-compiler?id=399555d9-70e3-4389-9dca-957c17a46d9b)
] |
[Question]
[
A cyclic [difference set](https://en.wikipedia.org/wiki/Difference_set) is a set of positive integers with a unique property:
1. Let `n` be the largest integer in the set.
2. Let `r` be any integer (not necessarily in the set) greater than 0 but less than or equal to `n/2`.
3. Let `k` be the *number of solutions* to `(b - a) % n = r` where `a` and `b` are any members of the set. Each solution is an ordered pair `(a,b)`. (Also note that this version of modulo makes negative numbers positive by adding `n` to it, unlike the implementations in many languages.)
4. Finally, if and only if this is a cyclic difference set, the value of `k` does not depend on your choice of `r`. That is, all values of `r` give the same number of solutions to the above congruence.
This can be illustrated with the following example:
```
Cyclic difference set: {4,5,6,8,9,11}
0 < r <= 11/2, so r = 1,2,3,4,5
r=1: (4,5) (5,6) (8,9)
r=2: (4,6) (6,8) (9,11)
r=3: (5,8) (6,9) (8,11)
r=4: (4,8) (5,9) (11,4) since (4-11)%11=(-7)%11=4
r=5: (4,9) (6,11) (11,5)
```
Each value of `r` has the same number of solutions, 3 in this case, so this is a cyclic difference set.
## Input
Input will be a list of positive integers. Since this is a set property, assume that input is *not* sorted. You can assume that `n` is at least `2`, although `k` may be zero.
## Output
Your program/function should output a truthy value if the set is a cyclic difference set, or a falsey value otherwise.
## Test Cases
Valid cyclic difference sets:
```
10,12,17,18,21
7,5,4
57,1,5,7,17,35,38,49
1,24,35,38,40,53,86,108,114,118,135,144,185,210,254,266,273
16,3,19,4,8,10,15,5,6
8,23,11,12,15,2,3,5,7,17,1
```
([data source](https://www.ccrwest.org/diffsets.html), although their convention is different)
Invalid cyclic difference sets:
```
1,2,3,4,20
57,3,5,7,17,35,38,49
3,4,5,9
14,10,8
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 7 bytes
```
_þ%ṀṬSE
```
[Try it online!](https://tio.run/##bY6xEcIwDEV7pkhD9wvLtmxnAI4BKH05KhouC9BxNCyTBdLQZJKwiPlOCBV31lnS/5Le9dL3t1LO02s/j/d5HE6HMj3fj4HvWErOWQzEQiIkwUqHXdPkCIVfU6XAKlaHU7gE366KwPqtZaAOKUBMgohn8KcmnnlSLjaw6mFDgI3uuyDAQVp40EwK5Z2wSkShJAsZp@n7IiyANXK9zz53mh@p@09aXYoN29djiUXXfQA "Jelly – Try It Online")
### How it works
```
_þ%ṀṬSE Main link. Argument: A (array of unique elements / ordered set)
_þ Subtract table; yield a 2D array of all possible differences of two
(not necessarily distinct) elements of A.
%Ṁ Take the differences modulo max(A).
Ṭ Untruth; map each array of differences modulo max(A) to a Boolean array
with 1's at the specified indices. Note that all 0's in the index array
are ignored, since indexing is 1-based in Jelly.
S Take the sum of these arrays, counting occurrences.
E Test if all resulting counts are equal.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
Ë#m%▲¹×-¹¹ḣ½▲
```
[Try it online!](https://tio.run/##bU4xCgIxEOx9hSCCwgjZZJPLveWwF8TGwwdoa68P8AcW4hU2uZfoR@LE085i2d2Z3ZlZ7dp1Hm9m7euw387TLffHyWb6Ol1T158XqUvd835JDwI550bhERBRQ2Q5asRALKSCRNgCVOSV3RPiWBXOebgIrcs9rP52A@8QA8REiimLnZwo5@ipZ2C9woYAW7nyHeAgNZQBirMvYYjTm7h8ovCPR19nGSwJUMYMsdyfWIX3@ATUohyXbw "Husk – Try It Online")
The three superscript 1s seem wasteful...
## Explanation
```
Ë#m%▲¹×-¹¹ḣ½▲ Input is a list, say x=[7,5,4]
▲ Maximum: 7
½ Halve: 3.5
ḣ Inclusive range from 1: [1,2,3]
Ë All elements are equal under this function:
Argument is a number, say n=2.
×-¹¹ Differences of all pairs from x: [0,-2,2,-3,0,3,-1,1,0]
m%▲¹ Map modulo max(x): [0,5,2,4,0,3,6,1,0]
# Count occurrences of n: 1
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~53~~ 52 bytes
```
SameQ@@Counts@Mod[#-#2&@@@#~Permutations~{2},Max@#]&
```
[Try it online!](https://tio.run/##bU7LasMwELzrNwyhLVPqXT0sUwoLPQdSeiw9iMahOdiGRIGCcX7dXQX3VoSk0cysZvqUv7s@5eNXWg4vd8t76rs3kdfxMuSzbMf9R/VY8UZEquuuO/WXrN5xOF8nnrFNP1J9bpb7Z7M7HYcsD4cnmczk4BEQ0YJohpkafbsCfANSrGcD62EjXFt4Ars/ooa3iAFURx13uvVWjZzi6MFUg70DhwBu7G08wIJaOM1UlXzJL0IEq0AgLiSraw1fa@lScMtXTf@s15b2v5bF4dHOxszLLw "Wolfram Language (Mathematica) – Try It Online")
Note, we don't need to divide the max element by two due to symmetry (we may check counts of all modulos `1` to `max(input) - 1`).
### Explanation
```
#~Permutations~{2}
```
Take all length-2 permutations of the input.
```
#-#2&@@@
```
Find differences of each
```
Mod[ ... ,Max@#]
```
Mod the result by the maximal element of the input.
```
Counts@
```
Find the frequencies of each element.
```
SameQ@@
```
Return whether all of the numbers are the same.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~86~~ ~~84~~ 81 bytes
-3 bytes thaks to JungHwan Min
```
lambda x:len({*map([(b-a)%max(x)for a in x for b in x].count,range(1,max(x)))})<2
```
[Try it online!](https://tio.run/##bVDLboMwELz7K7hUMdW0Yv0AUjVfQjmYNiRIvEQciajqt9M1JIdKlWV5NDO7O97x5s9Dr5f68LG0rqu@XDS/tcdefj93bpSFrF5c/NS5Wc5xPUyRi5o@mqMAqxWWr5/DtfeYXH86SsJmjeOf@F0tfrr68@1QiIISkAJloByKSogig4UJwDLJOAuqttA5zD7wBGUeRAKrkaegJAeR4csva2QY55ZbJlDWQKUpVKbX8hQatIcBW3m65RlpEDgAC7Tm4Up23YffY/EpRSlq11626KuHeyf3tPq/tMFhEWApxDg1vZe77fs7tM3Fy7DOGhvF@3l41jF/LCvDjuUX "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), 87 bytes
Returns **0** or **1**.
```
a=>a.map(b=>a.map(c=>x[c=(c-b+(n=Math.max(...a)))%n-1]=-~x[c]),x=[])|!x.some(v=>v^x[0])
```
### Test cases
```
let f =
a=>a.map(b=>a.map(c=>x[c=(c-b+(n=Math.max(...a)))%n-1]=-~x[c]),x=[])|!x.some(v=>v^x[0])
console.log('[Truthy]')
console.log(f([10,12,17,18,21]))
console.log(f([7,5,4]))
console.log(f([57,1,5,7,17,35,38,49]))
console.log(f([1,24,35,38,40,53,86,108,114,118,135,144,185,210,254,266,273]))
console.log(f([16,3,19,4,8,10,15,5,6]))
console.log(f([8,23,11,12,15,2,3,5,7,17,1]))
console.log('[Falsy]')
console.log(f([1,2,3,4,20]))
console.log(f([57,3,5,7,17,35,38,49]))
console.log(f([3,4,5,9]))
console.log(f([14,10,8]))
```
[Answer]
# Perl, ~~68~~ ~~67~~ 66 bytes
Includes `+2` for `ap`
```
perl -apE '\@G[@F];pop@G;s:\d+:$G[$_-$&].=1for@F:eg;$_="@G"=~/^1*( 1*)\1*$/' <<< "4 5 6 8 9 11"
```
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
lambda x:len({sum(1+(a+r)%max(x)in x for a in x)for r in range(max(x))})<3
```
[Try it online!](https://tio.run/##bVC7bsMwDJzjr9BSQEJuMPWwFaP9EsWDisZtgNgJHBdwUfTbXTJOOnUgdOSdjgdevqaP8@CWTr2o/XLK/etbVnNzOgz6@/rZa9rqvB3NU59nPZvjoGbVnUeVlUAjcBQ45uH9oFeR@THPbMjUJNS@SClRCbKgGhRhqUWhVKoR4FcYmOCuFoULcBF@tzIE6x@jEsEhVqAygshz8cscecYxsHEJGzxsVcHW7m5QwYF28GAxpwi8p1opjsIU3ZLxb9bdI9wCSiXZz3P2LP@Suv@TiirgEdvLsshN2zbFRo4xyzGmRl3G4zDpTg5VbNbGLL8 "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 81 bytes
```
->s{n=s.max
(1..n/2).map{|r|s.permutation(2).count{|a,b|(b-a)%n==r}}.uniq.size<2}
```
[Try it online!](https://tio.run/##lY9NboMwEIX3PoUVqRKRJi42Nhip9CKIBSREYRFDsZHaYs5Ox5B01U0XlufNm59vxqn5Wq/Fenq3syksu9efJOKMmVdxRDHMfvSWDe14n1ztut5EmD/3k3Gzr6HxUXOqjy@mKMZlYZPpPpjtvts3saxlKUFBChpy4LwCQkseAxfAM@AaxJ7KsEZukcI0iiz4iYJEg8z3LhDymYlBJaBT4LHGoRIf/uhxibFWODUGoSSINAWRJXt/CgnwHCSiBAIVsDYHKdDhGxT2YtljP69Ixdr6fKOXnnrbOk8oHcbOOHotUVa/8kAPpDUXQobJWULKQItzkCB@XpX8eVWoUfC4UAYw/d@l6/oD "Ruby – Try It Online")
Ungolfed:
```
->s{
n=s.max
(1..n/2).map{|r| # For each choice of r
s.permutation(2).count{|a,b| # Count the element pairs
(b-a)%n==r # for which this equality holds
}
}.uniq.size<2 # All counts should be identical.
}
```
[Answer]
# Haskell, 84 bytes
```
l s=all((g 1==).g)[1..t-1]where t=maximum s;g j=[1|x<-s>>=(`map`s).(-),x==j||x+t==j]
```
l is the function that does the check. It just computes all differences and counts.
] |
[Question]
[
This question is heavily based off [this question](https://codegolf.stackexchange.com/questions/125879/find-all-the-anagrams), but should pose a number of additional difficulties.
## Your Task
You must write a program or function that, when receiving a string, prints out all possible anagrams of it. For the purpose of this question, an anagram is a string that contains the same character as the original string, but is not the original string. A subanagram is an anagram of a substring of an inputted string. Anagrams and subanagrams do not have to be or contain actual words.
## Input
You may accept a string, which may be of any length > 0, by any standard input method. It may contain any ASCII characters.
## Output
You may output all of the possible anagrams and subanagrams of the inputted string in any standard way. You must not output the same string twice, or output a string equal to the input.
## Other Rules
[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), least bytes wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
Œ€œ˜Ù¹K
```
A function that accepts a string from input and leaves a list of strings on the stack. As a full program a representation of the list is printed.
**[Try it online!](https://tio.run/##ARwA4/8wNWFiMWX//8WS4oKsxZPLnMOZwrlL//90ZXh0)**
### How?
```
- push input
Œ - all substrings
€œ - for €ach: all permutations
˜ - flatten
Ù - de-duplicate
¹ - push 1st input onto top of stack
K - pop a,b; push a without any b's (remove the copy of the input from the list)
- as a full program: implicit print of the top of the stack
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 7 bytes
```
{sp}ᶠdb
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7q4oPbhtgUpSf//KyUmJaakKv2PAgA "Brachylog – Try It Online")
## Explanation
```
{sp}ᶠdb
{ }ᶠ Find all
p permutations of
s a substring of {the input}
d Remove duplicates (leaving the list otherwise in the same order)
b Remove the first (the input itself)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẆŒ!€;/QḟW
```
A monadic link accepting a list and returning a list of all distinct sub-anagrams except the input itself.
**[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bqGxZIh4oKsOy9R4bifV//Dh1n//3RleHQ)** (the footer pretty-prints the resulting list by joining with newlines.)
### How?
```
ẆŒ!€;/QḟW - Link: list of characters, s
Ẇ - all contiguous sublists of s
Œ!€ - all permutations for €ach sublist now a list of lists of lists)
/ - reduce by:
; - concatenation (flattens the list by one level)
Q - de-duplicate (gets the unique entries)
W - wrap s in a list (otherwise filtering will attempt to remove characters)
ḟ - filter discard from left if in right (remove the one equal to the input)
```
[Answer]
# Pyth, 12
```
-{.n.pM.:Q)]
```
[Online test](https://pyth.herokuapp.com/?code=-%7B.n.pM.%3AQ%29%5D&input=%27aabc%27&debug=0).
```
Q # input
.: ) # all substrings
.pM # all permutations of all substrings
.n # flatten
{ # deduplicate
- ]Q # subtract (list of) (implicit) input
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
```
à má c â Å
```
[Try it online!](https://tio.run/##y0osKPn///AChdzDCxWSFQ4vUjjc@v@/UmJSohIA "Japt – Try It Online")
I got to use `à`, `á`, and `â` all in one answer, in order too. What a coincidence...
### Explanation
```
à má c â Å
Uà má c â s1 // Ungolfed
// Implicit: U = input string
Uà // Take all combinations of characters in the input string.
má // Map each combination to all of its permutations.
c // Flatten into a single array.
â // Uniquify; remove all duplicates.
s1 // Remove the first item (the input) from the resulting array.
// Implicit: output resulting array, separated by commas
```
[Answer]
## Mathematica, 60 bytes
```
DeleteCases[""<>#&/@Permutations[c=Characters@#,Tr[1^c]],#]&
```
`Permutations` takes an optional numerical argument which tells it how many of the input values to use for the permutations. If we give it the length of the input, it will generate the permutations for all subsets of the input without duplicates. All we need to do is remove the input.
[Answer]
# Java 8, ~~313~~ ~~312~~ ~~306~~ 297 bytes
```
import java.util.*;s->{Set l=new HashSet();for(int z=s.length(),i=0,j;i<z;i++)for(j=i;j<z;)p("",s.substring(i,++j),l);l.remove(s);l.forEach(System.out::println);}void p(String p,String s,Set l){int n=s.length(),i=0;if(n<1)l.add(p);for(;i<n;p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,n),l));}
```
Modified version of [my answer here](https://codegolf.stackexchange.com/a/125953/52210), where `p("",s,l);` has been replaced with `for(int z=s.length(),i=0,j;i<z;i++)for(j=i;j<z;p("",s.substring(i,j+++1),l));`
-6 bytes thanks to *@OlivierGrégoire* in my linked answer
-9 bytes thanks to *@ceilingcat*
[Try it online.](https://tio.run/##XZBBb8IgFMfvfoqXnWAg6nFil@ywZJd58Wg8UIqWjgIp1EWNn72Dqsm2BAL/F97jl18jjmLqvLJN9TXo1rsuQpNqrI/asGcOMJsBWbxAdBBrBeUpqql0vY0TaUQI8Cm0vUwAtI2q2wupYJ0jwNHpCiTaxE7bAwTMU/WadlprsFDAEKavl42KYAqrvuFDhDolhPnedSiNg3MRmFH2EGuEqS7mtOF6deaaEJyfNIXmTcrYo6cnGljoyzB@hjQlpMHUYG5Yp1p3VCjke@p6F7JGm1OIqmWuj8ulTx3RWMyvfCT2D2JPH@h0hMSXzGT/MXG9R3a1wIaJqkL@Bp8wLffIk8BkLbq3iDT@AzinGpPfBUI0tZk4cQwAvi@NlhCiiOkYudrk@Y623YHAN8nZPrRJZjaYAxo9A7TMMonEdr67i78OgyhL@QM)
**Explanation of this part:**
```
for(int z=s.length(),i=0,j;i<z;i++) // Loop `i` in the range [0,length):
for(j=i;j<z;) // Inner loop `j` in the range [i,length):
p("", // Call the permutation-method,
s.substring(i,++j),l)); // with a substring at index-range [i,j]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
ǎƛṖ;fU'⁰≠
```
## Explanation
```
<implicit input>
ǎ - Get substrings
ƛṖ; - Map over substrings: Get permutations
f - Flatten it
U - Uniquify, remove all duplicates
'⁰≠ - Filter lambda: Keep all elements that don't equal input
<implicit output>
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C7%8E%C6%9B%E1%B9%96%3BfU%27%E2%81%B0%E2%89%A0&inputs=Abcde&header=&footer=)
[Answer]
# [Perl 6](https://perl6.org), 75 bytes
```
{unique(flat $_,.comb.combinations.skip».permutations.map(*».join)).skip}
```
[Try it](https://tio.run/##LYw7CgIxEEB7TzGFSCIy5TbiWSSbzMJofiYZQWRPtp0XixJsXvF4vEzFT10qwXNCe96FFxxscgSX/pbIDyG1eNNgfz2hTWEe4Ggap1ix3jl/NsxUgrS/Cyar40/eEketR7J2HFPM0mBJBTxHqkp3M1vnvg "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
unique( # return each (sub)anagram once
flat # unstructure the following (List of Lists into flat List)
$_, # the input (so we can skip it at the end)
.comb # split the input into graphemes
.combinations # get all the combinations
.skip\ # skip the first empty combination
».permutations # get all the permutations of each combination
.map(*».join) # join the inner permutations
).skip # skip the first value (the input)
}
```
] |
[Question]
[
I made my own sequence recently (called the Piggyback sequence), and it works like this:
`P(1)`, `P(2)` and `P(3)` = `1`.
For all `P(n)` where `n>3`, the sequence works like this:
```
P(n) = P(n-3) + P(n-2)/P(n-1)
```
So, continuing the sequence:
`P(4)` = `1 + 1/1` = `2`
`P(5)` = `1 + 1/2` = `3/2`
= `1.5`
`P(6)` = `1 + 2/(3/2)` = `7/3`
= `2.33333...`
`P(7)` = `2 + (3/2)/(7/3)` = `37/14` = `2.6428571428...`
`P(8)` = `3/2 + (7/3)/(37/14)` = `529/222`
= `2.3828828828...`
Your task is, when given `n`, calculate `P(n)` either as a floating point number or an (im)proper fraction.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
*If anyone can find the name of the sequence, please edit the post accordingly.*
## Current leaders: MATL and Jelly (both at 15 bytes).
[Answer]
# Python 2, 40 39 bytes.
```
f=lambda x:x<4or.0+f(x-3)+f(x-2)/f(x-1)
```
Gives `True` instead of 1, if this isn't allowed we can have this for 42 bytes:
```
f=lambda x:.0+(x<4or f(x-3)+f(x-2)/f(x-1))
```
The way it works is pretty straightforward, the only trick is using `.0+` to cast the result to a float.
[Answer]
## Haskel, 32 bytes
```
(a#b)c=a:(b#c)(a+b/c)
((0#1)1!!)
```
Usage example: `((0#1)1!!) 7` -> `2.642857142857143`. I start the sequence with `0, 1, 1` to fix `!!`'s 0-based indexing.
Edit: @xnor found a way to switch from 0-based to 1-based index, without changing the byte count.
[Answer]
# Ruby, 34 bytes
Since Ruby uses integer division by default, it turns out that it's shorter to use fractions instead. Golfing suggestions welcome.
```
f=->n{n<4?1r:f[n-3]+f[n-2]/f[n-1]}
```
[Answer]
# [Perl 6](http://perl6.org), ~~25~~ 23 bytes
```
{(0,1,1,1,*+*/*...*)[$_]}
```
```
{(0,1,1,*+*/*...*)[$_]}
```
## Explanation:
```
# bare block lambda with implicit parameter 「$_」
{
(
# initial set-up
# the 「0」 is for P(0) which isn't defined
0, 1, 1, 1,
# Whatever lambda implementing the algorithm
* + * / *
# { $^a + $^b / $^c }
# keep using the lambda to generate new values until
...
# Whatever (Forever)
*
# get the value indexed by the argument
)[ $_ ]
}
```
This returns a [Rat](https://docs.perl6.org/type/Rat) ([Rational](https://docs.perl6.org/type/Rational)) for inputs starting with 3 up until the result would start having a denominator bigger than can fit in a 64 bit integer, at which point it starts returning [Num](https://docs.perl6.org/type/Num)s (floating point).
The last [Rat](https://docs.perl6.org/type/Rat) it will return is `P(11) == 8832072277617 / 2586200337022`
If you want it to return [Rational](https://docs.perl6.org/type/Rational) numbers rather than floats you can swap it for the following which will return a [FatRat](https://docs.perl6.org/type/FatRat) instead.
```
{(0.FatRat,1,1,*+*/*...*)[$_]}
```
## Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my &piggyback = {(0,1,1,*+*/*...*)[$_]}
# */ # stupid highlighter no Perl will ever have C/C++ comments
my @test = (
1, 1, 1, 2,
3/2, 7/3, 37/14,
529 / 222,
38242 / 11109,
66065507 / 19809356,
8832072277617 / 2586200337022,
);
plan +@test;
for 1..* Z @test -> ($input,$expected) {
cmp-ok piggyback($input), &[==], $expected, $expected.perl;
}
```
[Answer]
## C, 46 bytes
```
float P(n){return n<4?1:P(n-3)+P(n-2)/P(n-1);}
```
[Ideone](https://ideone.com/aFNfck)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 15 bytes
```
llli3-:"3$t/+]&
```
[Try it online!](http://matl.tryitonline.net/#code=bGxsaTMtOiIzJHQvK10m&input=NQ)
### Explanation
```
lll % Push 1, 1, 1
i % Take input n
3-: % Pop n and push range [1 2 ... n-3] (empty if n<4)
" % For each
3$t % Duplicate the top three numbers in the stack
/ % Pop the top two numbers and push their division
+ % Pop the top two numbers and push their addition
] % End
& % Specify that the next function, which is implicit display, will take
% only one input. So the top of the stack is displayed
```
[Answer]
# [Cheddar](https://github.com/cheddar-lang/Cheddar), 31 bytes
```
n P->n<4?1:P(n-3)+P(n-2)/P(n-1)
```
The ungolfed version is so clear imo you don't need explanation:
```
n P->
n < 4 ? 1 : P(n-3) + P(n-2) / P(n-1)
```
basically after the function arguments you can specify the variable to use which will be set to the function itself. Why? because this function will be tail-call-optimized, or at least should be.
[Answer]
# Javascript (ES6), 31 bytes
```
P=n=>n<4?1:P(n-3)+P(n-2)/P(n-1)
```
A simple function.
```
P=n=>n<4?1:P(n-3)+P(n-2)/P(n-1)
var out = '';
for (var i=1;i <= 20;i++) {
out +='<strong>'+i+':</strong> '+P(i)+'<br/>';
}
document.getElementById('text').innerHTML = out;
```
```
div {
font-family: Arial
}
```
```
<div id="text"></div>
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes
```
3Ld # push list [1,1,1]
¹ÍG } # input-3 times do
D3£ # duplicate list and take first 3 elements of the copy
R` # reverse and flatten
/+ # divide then add
¸ì # wrap in list and prepend to full list
¬ # get first element and implicitly print
```
[Try it online!](http://05ab1e.tryitonline.net/#code=M0xkwrnDjUdEM8KjUmAvK8K4w6x9wqw&input=OA)
Saved 1 byte thanks to Luis Mendo
[Answer]
# Pyth, 20 bytes
```
L?<b4h0+y-b3cy-b2ytb
```
[Try it online!](http://pyth.herokuapp.com/?code=L%3F%3Cb4h0%2By-b3cy-b2ytb%0AyQ&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6&debug=0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ạ2,1,3߀÷2/SµḊ¡
```
[Try it online!](http://jelly.tryitonline.net/#code=4bqhMiwxLDPDn-KCrMO3Mi9TwrXhuIrCoQ&input=&args=OA) or [verify all test cases](http://jelly.tryitonline.net/#code=4bqhMiwxLDPDn-KCrMO3Mi9TwrXhuIrCoQo4w4figqxZ&input=).
### How it works
```
ạ2,1,3߀÷2/SµḊ¡ Main link. Argument: n (integer)
Ḋ Dequeue; yield [2, ..., n].
µ ¡ If the range is non-empty (i.e., if n > 1), execute the chain to
the left. If n is 0 or 1, return n.
Note that P(3) = P(0) + P(2)/P(1) if we define P(0) := 0.
ạ2,1,3 Take the absolute difference of n and 2, 1, and 3.
This gives [0, 1, 1] if n = 2, and P(0) + P(1)/P(1) = 0 + 1/1 = 1.
߀ Recursively apply the main each to each difference.
÷2/ Perform pairwise division.
This maps [P(n-2), P(n-1), P(n-3)] to [P(n-2)/P(n-1), P(n-3)].
S Sum, yielding P(n-2)/P(n-1) + P(n-3).
```
[Answer]
# Mathematica, 36 bytes
```
P@n_:=If[n<4,1,P[n-3]+P[n-2]/P[n-1]]
```
Here are the first few terms:
```
P /@ Range[10]
{1, 1, 1, 2, 3/2, 7/3, 37/14, 529/222, 38242/11109, 66065507/19809356}
```
[Answer]
# R, ~~53~~ 47 bytes
```
f=function(N)ifelse(N>3,f(N-3)+f(N-2)/f(N-1),1)
```
This answer made use of the pretty neat function `ifelse` : `ifelse(Condition, WhatToDoIfTrue, WhatToDoIfNot)`
[Answer]
# Dyalog APL, 25 bytes
`⊃{1↓⍵,⍎⍕' +÷',¨⍵}⍣⎕⊢0 1 1`
] |
[Question]
[
There are N doors and K monkeys. Initially, all the doors are closed.
**Round 1:** The 1st monkey visits every door and toggles the door (if the door is closed, it gets opened it; if it is open, it gets closed).
**Round 2**: The 1st monkey visits every door and toggles the door. Then The 2nd monkey visits every 2nd door and toggles the door.
. . .
. . .
**Round k:** The 1st monkey visits every door and toggles the door . . . . . . . . . . The kth monkey visits every kth door and toggles the door.
**Input :**
N K (separated by a single space)
**Output:**
Door numbers which are open, each separated by a single space.
**Example**:
Input:
3 3
Output:
1 2
**Constraints**:
0< N<101
0<= K<= N
**Note**:
* Assume N doors are numbered from 1 to N and K monkeys are numbered from 1 to K
* The one with the shortest code wins. Also, display output for N=23, K=21
[Answer]
## APL, ~~32~~ ~~28~~ 26
```
{(2|+/(⍳⍺)∘.{+/0=⍺|⍨⍳⍵}⍳⍵)/⍳⍺}/⎕
```
---
```
⎕:
23 21
1 2 4 8 9 16 18 23
```
---
**Explaination**
* `{+/0=⍺|⍨⍳⍵}` is a function that returns the number of times door `⍺`(left argument) is toggled on round `⍵`(right argument), which equal the number of factors of `⍺` that is ≤`⍵`:
+ `⍳⍵` Generate numerical array from 1 to `⍵`
+ `⍺|⍨` Calculate `⍺` modulus each every item of that array
+ `0=` Change to a 1 where there was a 0, and a 0 for every thing else
+ `+/` Sum the resulting array
* The outer function:
+ `(⍳⍺)` , `⍳⍵` Generate arrays from 1 to N and 1 to K
+ `∘.{...}` For every pair of elements of the two arrays, apply the function. This gives a matrix of number of times toggled, each row represents a door and each column represents a round.
+ `+/` Sum the columns. This gives an array of the number of times each door is toggled over all rounds.
+ `2|` Modulus 2, so if a door is open, it's a 1; if it's closed, it's a 0.
+ `(...)/⍳⍺` Finally, generate an array from 1 to N and select only the ones where there is a 1 in the array on the previous step.
* `/⎕` Finally, insert the function between the numbers from input.
---
## EDIT
```
{(2|+⌿0=(,↑⍳¨⍳⍵)∘.|⍳⍺)/⍳⍺}/⎕
```
* `,↑⍳¨⍳⍵` Generate all "monkeys" (If K=4, then this is `1 0 0 0 1 2 0 0 1 2 3 0 1 2 3 4`)
+ `⍳⍵` Array from 1 to `⍵` (K)
+ `⍳¨` For each of those, generate array from 1 to that number
+ `,↑` Convert the nested array into a matrix (`↑`) and then unravel to a simple array (`,`)
* `(,↑⍳¨⍳⍵)∘.|⍳⍺` For each number from 1 to `⍺` (N), mod it with each monkey.
* `0=` Change to a 1 where there was a 0, and a 0 for every thing else. This gives a matrix of toggles: Rows are each monkey on each round, columns are doors; 1 means a toggle, 0 means no toggle.
* `+⌿` Sum the rows to get an array of number of times each door is toggled
Other parts are not changed
---
## EDIT
```
{(≠⌿0=(,↑⍳¨⍳⍵)∘.|⍳⍺)/⍳⍺}/⎕
```
Use XOR reduce (`≠⌿`) instead of sum and mod 2 (`2|+⌿`)
[Answer]
### GolfScript, 33 characters
```
~:k;),1>{0\{1$)%!k@-&^}+k,/}," "*
```
If doors were numbered starting with zero it would save 3 characters.
Examples ([online](http://golfscript.apphb.com/?c=OyIyMyAyMSIKCn46azspLDE%2BezBcezEkKSUha0AtJl59K2ssL30sIiAiKgoK&run=true)):
```
> 3 3
1 2
> 23 21
1 2 4 8 9 16 18 23
```
[Answer]
# Mathematica, 104 chars
```
{n,k}=FromDigits/@StringSplit@InputString[];Select[Range@n,OddQ@DivisorSum[#,If[#>k,0,k+1-#]&]&]~Row~" "
```
---
Example:
>
> In[1]:= {n,k}=FromDigits/@StringSplit@InputString[];Select[Range@n,OddQ@DivisorSum[#,If[#>k,0,k+1-#]&]&]~Row~" "
>
>
> ? 23 21
>
>
> Out[1]= 1 2 4 8 9 16 18 23
>
>
>
[Answer]
## Ruby, 88
Based on @manatwork's answer.
```
gets;~/ /
$><<(1..$`.to_i).select{|d|(1..k=$'.to_i).count{|m|d%m<1&&(k-m+1)%2>0}%2>0}*$&
```
Those dodgy globals always break syntax highlighting!
[Answer]
## Python 3, ~~97~~ 84
If a monkey appears in an even number of rounds, that's no change at all.
If a monkey appears in an even number of times, that's the same as in exactly one round.
Thus some monkeys can be left out, and the others just have to switch doors once.
```
N,K=map(int,input().split())
r=set()
while K>0:r^=set(range(K,N+1,K));K-=2
print(*r)
```
Output for `23 21`:
```
1 2 4 8 9 16 18 23
```
[Answer]
## R - 74
```
x=scan(n=2);cat(which(colSums((!sapply(1:x[1],`%%`,1:x[2]))*x[2]:1)%%2>0))
```
Simulation:
```
> x=scan(n=2);cat(which(colSums((!sapply(1:x[1],`%%`,1:x[2]))*x[2]:1)%%2>0))
1: 23 21
Read 2 items
1 2 4 8 9 16 18 23
```
[Answer]
## javascript ~~148~~ 127
```
function e(n,k){b=array(n);d=[];function a(c){for(i=0;i<n;i+=c)b[i]=!b[i];c<k&&a(c+1)}a(1);for(i in b)b[i]&&d.push(i);return d}
```
here is a (tiny bit) readable version:
```
function e(n, k) { //define N and K
b = array(n); //declare all doors as closed
d = []; //create array later used to print results
function a(c) { //(recursive) function that does all the work
for (i = 0; i < n; i += c) //increment by c until you reach N and...
b[i] = !b[i]; //toggle said doors
c < k && a(c + 1) //until you reach k, repeat with a new C (next monkey)
}
a(1); //start up A
for (i in b) b[i] && d.push(i); //convert doors to a list of numbers
return d //NO, i refuse to explain this....
} //closes function to avoid annoying errors
```
[DEMO fiddle](http://jsfiddle.net/mendelthecoder/T3bVE/2/)
i should note that it starts counting from 0 (technically a off-by-one error)
[Answer]
### JavaScript, 153
```
(function(g){o=[],f=g[0];for(;i<g[1];i++)for(n=0;n<=i;n++)for(_=n;_<f;_+=n+1)o[_]=!o[_];for(;f--;)o[f]&&(l=f+1+s+l);alert(l)})(prompt().split(i=l=s=' '))
```
Output for N=23, K=21:
```
1 2 4 8 9 16 18 23
```
Tested in Chrome, but doesn't use any fancy new ECMAScript features so should work in any browser!
I know I'll never win against the other entries and that @tryingToGetProgrammingStrainght already submitted an entry in JavaScript, but I wasn't getting the same results for N=23, K=21 as everyone else was getting with that so I thought I'd have a go at my own version.
**Edit**: annotated source (in looking over this again, I spotted places to save another 3 characters, so it can probably be improved still...)
```
(function(g) {
// initialise variables, set f to N
o = [], f = g[0];
// round counter
// since ++' ' == 1 we can use the same variable set in args
for (; i < g[1]; i++)
// monkey counter, needs to be reset each round
for (n = 0 ; n <= i; n++)
// iterate to N and flip each Kth door
for (_ = n; _ < f; _ += n + 1)
// flip the bits (as undef is falsy, we don't need to initialise)
// o[_] = !~~o[_]|0; // flips undef to 1
o[_] = !o[_]; // but booleans are fine
// decrement f to 0, so we don't need an additional counter
for (;f--;)
// build string in reverse order
o[f] && (l = f + 1 + s + l); // l = (f + 1) + ' ' + l
alert(l)
// return l // use with test
// get input from user and store ' ' in variable for use later
})(prompt().split(i = l = s = ' '))
// })('23 21'.split(i = l = s = ' ')) // lazy...
// == '1 2 4 8 9 16 18 23 '; // test
```
[Answer]
Ruby - 65 characters
```
(1..n).each{|d|
t=0
(1..k).each{|m|t+=n-m+1 if d%m==0}
p d if t%2>0}
n = 23, k = 21 # => 1 2 4 8 9 16 18 23
```
Here is the calculation, in pseudo-code:
* Let s(d) be the number of times door d is touched after k rounds.
* s(d) = sum(m=1..m=k)(d%m==0 ? (n-m+1): 0)
* door d is open after k rounds if s(d) % 2 = 1 (or > 0)
If you are not convinced that the expression for s(d) is correct, look at it this way:
* Let s(d,r) be the number of times door d is touched after r rounds.
* s(d,k) - s(d,k-1) = sum(m=1,..,m=k)(d%m==0 ? 1 : 0)
* s(d,k-1) - s(d,k-2) = sum(m=1,..,m=(k-1))(d%m==0 ? 1 : 0)
* ...
* s(d,2) - s(d,1) = d%2==0 ? 1 : 0
* s(d,1) = 1
* sum both sides to obtain the above expression for s(d), which equals s(d,k)
[Answer]
## PowerShell: 132
**Golfed Code:**
```
$n,$k=(read-host)-split' ';0|sv($d=1..$n);1..$k|%{1..$_|%{$m=$_;$d|?{!($_%$m)}|%{sv $_ (!(gv $_ -Va))}}};($d|?{(gv $_ -Va)})-join' '
```
**Un-Golfed, Commented Code:**
```
# Get number of doors and monkeys from user as space-delimited string.
# Store number of doors as $n, number of monkeys as $k.
$n,$k=(read-host)-split' ';
# Store a list of doors in $d.
# Create each door as a variable set to zero.
0|sv($d=1..$n);
# Begin a loop for each round.
1..$k|%{
# Begin a loop for each monkey in the current round.
1..$_|%{
# Store the current monkey's ID in $m.
$m=$_;
# Select only the doors which are evenly divisible by $m.
# Pass the doors to a loop.
$d|?{!($_%$m)}|%{
# Toggle the selected doors.
sv $_ (!(gv $_ -Va))
}
}
};
# Select the currently open doors.
# Output them as a space-delimited string.
($d|?{(gv $_ -Va)})-join' '
# Variables cleanup - don't include in golfed code.
$d|%{rv $_};rv n;rv d;rv k;rv m;
# NOTE TO SELF - Output for N=23 K=21 should be:
# 1 2 4 8 9 16 18 23
```
[Answer]
# Powershell, 66 bytes
>
> Based on Cary Swoveland's [answer](https://codegolf.stackexchange.com/a/13021/80745).
>
>
>
```
param($n,$k)1..$n|?{$d=$_
(1..$k|?{($n-$_+1)*!($d%$_)%2}).Count%2}
```
Test script:
```
$f = {
param($n,$k)1..$n|?{$d=$_
(1..$k|?{($n-$_+1)*!($d%$_)%2}).Count%2}
}
@(
,(3, 3 , 1,2)
,(23, 21 , 1, 2, 4, 8, 9, 16, 18, 23)
) | % {
$n,$k,$expected = $_
$result = &$f $n $k
"$("$result"-eq"$expected"): $result"
}
```
Output:
```
True: 1 2
True: 1 2 4 8 9 16 18 23
```
] |
[Question]
[
Inspired by [reddit](http://www.reddit.com/r/programming/comments/gvnfk/i_submit_a_hangman_game_i_made_in_c_about_15/).
Write a program which plays [Hangman](http://en.wikipedia.org/wiki/Hangman_%28game%29).
* The program chooses a random word from a list of N words, where N > 2.
* The word list can be provided to the program in any way you choose.
* At each iteration
+ Print out the state of the game using underscores for letters not yet discovered:`H _ N _ _ _ N`
+ Print the number of remaining attempts`10`
+ Read a letter from stdin, and update the state of the game, subtracting an attempt if they guess an incorrect letter.`A` *(input)*
`H A N _ _ A N`
`10`
+ Repeat until all letters are guessed or attempts reaches 0
* Use any language
* Fewest number of characters wins.
* Drawing the gallows is not necessary, but will earn you upvotes and kudos.
[Answer]
Darn, I thought it said "fewest number of lines wins." I'm not going to win any fewest-character contests here, but this Common Lisp program is only one line.
```
(let ((words (list "that" "help" "rent" "chair" "octopus" "monitor" "manual" "speakers" "onomatopoeia" "regardless" "irresponsible" "cornerstone"))) (let ((word (nth (random (length words)) words))) (format t "~a~%" (funcall (defun play (word current remaining-attempts) (progn (if (not (find #\_ current)) (return-from play "You win!")) (if (equalp remaining-attempts 0) (return-from play "You lose!")) (format t "~a~%~d~%" current remaining-attempts) (let ((guess (char (read-line) 0)) (index 0) (found nil)) (loop for letter across word do (if (equalp guess letter) (progn (setf (char current index) letter) (setf found t))) (setf index (+ index 1))) (if found (play word current remaining-attempts) (play word current (- remaining-attempts 1)))))) word (map 'string #'(lambda (c) #\_) word) 10))))
```
[Answer]
Python 3.
```
from random,sys import *
w=choice(*argv)
L=set(w)
a=10
while L and a:
print(" ".join("_"if x in L else x for x in w),a)
try:L-=set(input()[0])
except:a-=1
```
I prefer this one though: longer but nicer.
```
import random
w=random.choice(list(open("/usr/dict/words")))[:-1]
L=set(w)
a=10
while L and a:
print(" ".join("_"if x in L else x for x in w),a)
try:L.remove(input()[0])
except:a-=1
print w
```
[Answer]
## Ruby 1.9, 134 132 120 117 108 107
Word list provided in ARGV. The words and the entered letters must match in case.
```
r=w=$*.sample
t=10
loop{puts [*w.tr(r,?_).chars]*' ',t
t>0&&r>''?w[l=STDIN.gets[0]]?r=r.tr(l,''):t-=1:exit}
```
[Answer]
c++ (-headers)
```
struct h{h(char a):b(a){}char operator()(char c,char d){return d!='_'?d:c==b?c:'_';}char b;};
int main(int a,char**b){
srand(time(0));string c=*(b+rand()%(a-1)+1),d(c.size(),'_'),e;
char f=10,g;
while(f){
cout<<"> ";cin>>g;e=d;
transform(c.begin(),c.end(),d.begin(),d.begin(),h(g));if(e==d)--f;
cout<<d<<endl<<(int)f<<endl;if(d==c)break;
}return 0;}
```
cat /usr/dict/words | xargs hangman
[Answer]
## Python
```
import random
DEFAULT_ATTEMPTS = 10
def print_word(word, uncovered):
for c in word:
if c not in uncovered:
c = '_'
print c,
print ''
def get_letter():
letter = None
while letter is None:
letter = raw_input('> ')
if len(letter) != 1:
print 'Letters must be 1 character. Try again.'
letter = None
return letter
if __name__ == '__main__':
import sys
if len(sys.argv) != 2: sys.exit(1)
with open(sys.argv[1], 'r') as f:
words = [word.strip() for word in f.readlines() if word.strip()]
word = random.choice(words)
uncovered = set([' '])
attempts = DEFAULT_ATTEMPTS
while attempts > 0 and any(letter not in uncovered for letter in word):
print_word(word, uncovered)
print attempts
letter = get_letter()
if letter in uncovered:
print 'You have already tried that letter.'
elif letter in word:
print 'You got it!'
else:
print 'Wrong!'
attempts -= 1
uncovered.add(letter)
if attempts == 0:
print 'You lose!',
else:
print 'You win!'
print 'The phrase was "%s".' % word
```
I didn't really try for the fewest characters, just wanted to make it as small as possible without sacrificing anything.
[Answer]
Perl, 112 char. I feel like I can do better - perhaps I'll try again later
```
$_=$ARGV[rand@ARGV];$a=10;while($a&&/[a-z]/){print map/[A-Z]/?$_:'_',split'';$x=<STDIN>;chop$x;s/$x/$x/ig||$a--}
```
Words are given on the command line, letters typed upper case
[Answer]
**Clojure**
This is 400 bytes gzipped, which is still quite a lot, probably because of how Clojure handles mutable state.
```
(def m ["will" "work" "for" "food"])
(def w (nth m (rand-int (count m))))
(def *s* (atom (replicate (count w) "_")))
(def *a* (atom 10))
(defn g [s a]
(str (apply str (interpose " " s)) "\n" a))
(loop [n (read-line)]
(if (some (set n) w)
(swap! *s* (fn [s]
(map
(fn [i]
(if (= n (str (nth w i)))
n
(nth s i)))
(range 0 (count s)))))
(swap! *a* dec))
(println (g (deref *s*) (deref *a*)))
(if (and (< 0 (deref *a*)) (some #{"_"} (deref *s*)))
(recur (read-line))))
```
[Answer]
C# 370
```
using System;namespace h{class P{static void Main(string[]a){int c=10,d,l;char y=' ';string w=a[new Random().Next(a.Length)];l=w.Length;char[]x=new char[l];for(d=-1;++d<l;x[d]='-');while(c>0){for(d=-1;++d<l;x[d]=(y==w[d]||x[d]!='-')?w[d]:x[d]);Console.WriteLine(new string(x)+" "+c);if(w==new string(x))return;y=Console.ReadKey(true).KeyChar;if(!w.Contains(y+""))c--;}}}
```
wordlist as argument
[Answer]
# VB.NET
~~I haven't tried shrinking it yet, but:~~
~~First shrinking:~~
Second shrinking (3759 characters):
```
Module Hangman
Sub Main()
Dim m As Int32, w = "banana|apple|pear|dog|cat|orange|monkey|programming|hangman".Split("|")(New Random().Next(9)), g = "", e = "", x, c As Char, f As Boolean, r = Sub(z) Console.Write(z), p = Sub(y, h) Console.SetCursorPosition(y, h), a = Sub() Console.Clear(), q = Function() Console.ReadKey(1), d = Sub()
r(" +--------+S | |S |S |S |S |S |S |S |S |S |S |S |S |S |S |S |S |S |S |S |S |S |S ---------------------".Replace("S", vbCrLf))
p(0, 2)
r(String.Join(vbCrLf, " /------\S | O O|S \ ... /S ------ S | S | S | S | S -------+-------S | S | S | S / \ S / \ S / \ S / \ ".Split("S").Take(m * 4)))
End Sub
Console.CursorVisible = 0
Do
a()
d()
p(30, 10)
f = 0
For Each x In w
If g.Contains(x) Then
r(x)
Else
r(" ")
f = 1
End If
Console.CursorTop += 1
Console.CursorLeft -= 1
r("_")
Console.CursorTop -= 1
r(" ")
Next
If Not f Then
a()
d()
p(30, 10)
r("You win! Press any key to close.")
q()
End
End If
p(30, 13)
r(e)
Do
c = q().KeyChar
Loop Until Char.IsLetter(c)
If g.Contains(c) Then
e = "You have already guessed that letter."
Else
g &= c
If w.Contains(c) Then
e = "There is a" & If("aehilmnorsx".Contains(c), "n", "") & " """ & c & """ in the word."
Else
e = "There is no """ & c & """ in the word. Try again."
m += 1
End If
End If
Loop Until m = 4
a()
d()
p(30, 10)
r("You lose! Press any key to close.")
q()
End Sub
End Module
```
[Answer]
# Powershell, 125 bytes
```
$w=$h=$args|random|% t*y
for($n=10){$w-replace"[ $h]",'_'-join' ';$n
if(!$h+!$n){break}$n-=($c=Read-Host)-notin$h
$h=$h-ne$c}
```
Less golfed test script:
```
$f = {
$word=$hidden=$args|random|% toCharArray # let $word and $hidden are a random word chars
#$word # uncomment this to cheating
for($n=10){ # forever for with init section
$word-replace"[ $hidden]",'_'-join' ' # display the word with hidden letters
$n # display $n
if(!$hidden+!$n){break} # break loop if hidden array is empty or n equal to 0
$n-=($c=Read-Host)-notin$hidden # input $c from user, decrease $n if $c does not in $hidden array
$hidden=$hidden-ne$c # recreate $hidden array with removed $c
}
}
$words = gc .\wordlist.txt
&$f $words
```
Output example when the guessing player has *lost*:
```
_ _ _ _ _ _ _ _
10
i
_ _ _ _ _ _ _ _
9
e
_ _ e _ _ _ _ e
9
o
o _ e _ _ o _ e
9
a
o _ e _ _ o _ e
8
q
o _ e _ _ o _ e
7
q
o _ e _ _ o _ e
6
q
o _ e _ _ o _ e
5
q
o _ e _ _ o _ e
4
q
o _ e _ _ o _ e
3
q
o _ e _ _ o _ e
2
q
o _ e _ _ o _ e
1
q
o _ e _ _ o _ e
0
```
Output example when the guessing player has *win*:
```
_ _ _ _ _ _ _ _ _ _
10
e
_ _ _ _ e _ _ _ _ _
10
o
_ o _ _ e _ _ _ _ _
10
i
_ o _ _ e _ _ i _ _
10
a
_ o _ _ e _ _ i a _
10
l
_ o _ _ e _ _ i a l
10
c
c o _ _ e _ c i a l
10
m
c o m m e _ c i a l
10
t
c o m m e _ c i a l
9
r
c o m m e r c i a l
9
```
] |
[Question]
[
I know, a bit late.
# Challenge
Your challenge is, given a date, output if it's not an [Advent Sunday](https://en.wikipedia.org/wiki/Advent_Sunday), or the Advent Sunday of the year.
# Rules
* The \$4^\text{th}\$ Advent is determined by the Sunday before Christmas day (the \$25^\text{th}\$ of December). The \$3^\text{rd}\$ Advent is the Sunday before the \$4^\text{th}\$ Advent, and so on until the \$1^\text{st}\$ Advent.
* If Christmas Day falls on a Sunday, then the Sunday before is still the \$4^\text{th}\$ Advent.
* Input will consist of day, month and year, as an iterable with any order, or a string, or 3 separate integers.
* Input will be a valid date, numerically and also calendrically.
* Output should be falsey (0 or Boolean False) if the date is not an Advent Sunday, or else an integer denoting which Advent Sunday it is.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
# Examples
```
[In]: [2, 12, 2021]
[Out]: 0
[In]: [6, 5, 2023]
[Out]: False
[In]: [12, 12, 2021]
[Out]: 3
[In]: [30, 11, 1997]
[Out]: 1
[In]: [25, 12, 2011]
[Out]: false
[In]: [21, 12, 3000]
[Out]: 4
```
Good Luck!
[Answer]
# Excel, ~~71~~ 66 Bytes
Saved 5 bytes thanks to Taylor Raine
*Aside: At the time of posting, this answer has the smallest byte count. That is baffling. Score one for Excel's date handling, I guess.*
```
=LET(a,4-(INT(("12/23/"&YEAR(A1))/7)*7+1-A1)/7,(LEN(a)=1)*(a<5)*a)
```
Input is in cell `A1`. Output is wherever the formula is. Returns a number 1-4 for advent Sundays and a 0 for all other dates.
```
LET(a,4-(INT(("12/23/"&YEAR(A1))/7)*7+1-A1)/7
```
The first part calculates which advent Sunday an input is and does most of the heavy lifting.
* `("12/23/"&YEAR(A1))` finds Christmas Eve Eve (CEE) in the year of the input. We find Eve Eve hear because it saves us some extra bytes of adjustment later.
* `INT(~/7)*7` takes that date, divides by 7 (b/c 7 days per week), rounds it down, then multiplies it by 7. This finds the Saturday before CEE. If CEE *is* a Saturday, then it returns that date.
* `(INT(~/7)*7+1-A2)/7` adds one to get Sunday, subtracts the input, and divides by 7 to get the number of weeks between the input and the Sunday before Christmas. This may not be a whole number.
* `4-(~)` subtracts that result from 4 to invert the result. I.E., the Sunday before Christmas needs to be the 4th Sunday, not the 1 week before.
```
LET(a,~,(LEN(a)=1)*(a<5)*a)
```
Now that the heavy lifting is out of the way, we can examine the results. Note that using TRUE and FALSE values in math will treat TRUE = 1 and FALSE = 0. By multiplying various statements that will evaluate to either TRUE or FALSE, we can filter out undesirable results.
* `(LEN(a)=1)` filters out any non-integers as well as negative integers. This removes every non-Sunday in the advent calendar and all dates before the first Sunday. This does *not* filter out the 0th Sunday but the end result will still be 0 so it works.
* `(a<5)` filters out Sundays *after* the 4th Sunday.
* `(~)*(~)*a` returns the value if it has passed both those filters. Otherwise, it returns 0.
In this screenshot, I have added a column to return the value of `a` since that's so much of the calculation. I have also extended the data beyond the samples above to show some edge cases.
[](https://i.stack.imgur.com/TlIqU.png)
[Answer]
# [Factor](https://factorcode.org/) + `calendar.holidays.us`, 85 bytes
```
[ <date> dup christmas-day 4 [ dup last-sunday ] times 0 5 narray reverse nip index ]
```
Takes input as three integers in <year> <month> <day> order. The `last-sunday` word postdates build 1525, the one TIO uses, so here's a screenshot of running the above code in build 2101's listener:
[](https://i.stack.imgur.com/spScU.png)
## Explanation
```
! 2021 12 12
<date> ! 2021-12-12
dup ! 2021-12-12 2021-12-12
christmas-day ! 2021-12-12 2021-12-25
4 [ dup last-sunday ] times ! 2021-12-12 2021-12-25 2021-12-19 2021-12-12 2021-12-5 2021-11-28
0 5 narray ! 2021-12-12 2021-12-25 { 2021-12-19 2021-12-12 2021-12-5 2021-11-28 0 }
reverse ! 2021-12-12 2021-12-25 { 0 2021-11-28 2021-12-5 2021-12-12 2021-12-19 }
nip ! 2021-12-12 { 0 2021-11-28 2021-12-5 2021-12-12 2021-12-19 }
index ! 3
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 78 bytes
```
(y,m,d)=>/Su/.test(c=new Date(y,m-1,d))*'01234'[(c-new Date(y,9,51))/6048e5|0]
```
[Try it online!](https://tio.run/##dc2xCsIwEMbx3afI1kTS5i5pq0Xq5Bs4ikNJU1FqIzYqgu9eI0QQS4eb/j@@O1X3qtfX48XFna3N0JQDffIzr1m5FtubSJzpHdVlZx5kUznziTH6zOYRoFRptKM6/qkFz5AxkUO6NNkL9oO2XW9bk7T2QBsqQSInKDkhkrEVEYLAbESUz5m/fJqEFfyuqD@CRbHw2TMFgeBoBcOKzCYeKQAIBANJhzc "JavaScript (Node.js) – Try It Online")
Falsy may be 0 or NaN. Add 2 bytes (append `|0`) to always get 0. User must run this program with computer configured to UTC timezone or any other timezone that: 1. No DST shift during Nov 20 to Dec 31, 2. Name of timezone (in system language) does not contain substring `"Su"` (case sensitive).
`new Date(y,9,51)` is Nov 20 in JavaScript.
[Answer]
# Python3, 152 bytes:
```
from datetime import*
t=lambda x:0if x>=date(x.year,12,25)else 1+t(x+timedelta(days=7))
f=lambda x:(s:=date(*x)).weekday()==6and(0<(j:=(5-t(s)))<5)and j
```
[Try it online!](https://tio.run/##fY3LbsIwEEX3fMUsZyAg25GhWJgfQSxc2VEDeckZqc7XB1NUuom6mM0999wZJv7qu/JjiPNcxb4F7zhw3Qao26GPvF6xbVz76R0kI@oK0tk@K5h2U3CxkKpQmkIzBpAbxrR5uj407NC7abQHolX1t4CjeenrRLT7DuGeW0jW7l3nUZzwZizqLeNIRCdNOYXbPMS6Y6zwogrID0EJJa8XY7bymuffdF@A/oHlApT/u6XIWOY7Hg8LWOlfWy7ZSr5wKYR44/kB)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 116 bytes
```
3=`
;
\d+
$*_
((_*)\2\2\2_*);((_*)\4\4\4_*)
$4$3$2$1$1$1$1$1
\G_{7}
-_{12}-
____
-_{11}-_{26}
^(_{7}){1,4}$|.+
$#1
```
[Try it online!](https://tio.run/##NY3NCsJADITv8xqusK1Gkmx/KMVzX6K4FfTgpQfxVvfZ17TSDIRvJgN5Pz@v@Z6PfphyuE7oMT5OcGWE97EsRl1l0P9ttcoArnLBqZNdGIe4tAmguIgmQrTZjCTb2tjp5tdKsci5Su57sTcHyVlZhUSJFYaBuCZusKeikK5rSYQCWypbqjUCM28oPw "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in ISO date format. Explanation:
```
3=`
;
```
Separate the year from the century.
```
\d+
$*_
```
Convert to unary.
```
((_*)\2\2\2_*);((_*)\4\4\4_*)
$4$3$2$1$1$1$1$1
\G_{7}
```
Perform Zeller's congruence on the 25th of December of the input year.
```
-_{12}-
____
-_{11}-_{26}
```
Add this to the day of the month, adding an extra 4 for December or subtracting 26 for November 26 or later. Other months get ignored and fail to match the next stage at all.
```
^(_{7}){1,4}$|.+
$#1
```
Count the number of whole weeks, but the result must be an integer between `1` and `4` inclusive.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~215~~ ~~202~~ 192 bytes
```
#import<time.h>
i;*t;*l;f(d,m,y){5[t=calloc(9,8)]=y-1900;t[4]=m-1;t[3]=d;l=mktime(t);i=6[t=gmtime(&l)];y=t[7];t[4]=11;t[3]=25;l=mktime(t);d=7[t=gmtime(&l)]-y;m=4-d/7-!t[6];i=i|!d|m<1|m>4?0:m;}
```
[Try it online!](https://tio.run/##bVLtbqMwEPyfp3Bz6glSc7EhH6WOcz9O9xQEnSLbpFYxRGDpwiV59aMLMVGpisx6vDOzXq0sgoMQbftNm2NZ2Y3VRv143U40m1k2y1nmSWxw45@XieVin@el8GL87Ke8CWhMCLPJIuUmoACilEuWc/PWFfGszzRfgetg@vP33E9Zw22yTm8m6jzhcmSSfD02BQ0zfBHI@Tp4sMkqhbL68iAvZkMvZrv4SV4Mu7a6sMjsdeH56DxB8HUJq2r7p0lSxNE5JCHFCGLUR8A0jtcdpoAjQsiVjY3mZqQhRktQw9Yp@z38rJXuEoxWN0lEoDTYQvpBqk5HJaxyYlDAgnZoDxZOKMqitki87qsZRCXeVHXTT3en3@HuFP@CfznF6OM5mjp3VlbI6@7ShVQnsBHm4AbV@p8qM2/owp@7xOyeYejpqVcPUxw6b6CSm2bPp2xEm4E2X9JyoOWXdA308NDGjALmPrTP1mMFksybPsp5v1CwRRAf610B02kwdIUlRjW@j7HmXKXuiuvk2v4XWb4/1G3w9x0 "C (gcc) – Try It Online")
*Saved 13 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs the day, month and year as separate parameters.
Returns which Advent Sunday it is or \$0\$ otherwise.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~88~~ 79 bytes
>
> Input format should be `{year, month, day}`.
>
>
>
```
Ramp[4-DayCount[#,{#&@@#,12,24},s=Sunday]]Boole[DayName@#==s&&Rest@#!={12,25}]&
```
[Try it online!](https://tio.run/##XY2xCsIwFEV3vyISyBQhSVulQyCos0gdY4aHBiyYVmw6lNJvjwl0qB3ecu657zrwL@vA1w8IXt5DBe6j890ZhlPbN15jOmKiFKZcUJFPtJO3vnnCYMyxbd9WR/ECziosZUdIZTuv8FaOyS4mQ8L1W8cvXo@CCU5R5EhMxmyWPKOooGi/xrPO/31elocIY5ixVSPBdGl5EWSMsXmZxyD8AA "Wolfram Language (Mathematica) – Try It Online")
Output:
```
0
0
3
1
0
4
```
79 bytes - Thanks to [@att](https://codegolf.stackexchange.com/users/81203/att)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 114 bytes
```
lambda a,b,c:(y:=int((c+10.5)/7))%5+y//5 if date(a,b,c).weekday()==6 and[b,c]!=[12,25]else 0
from datetime import*
```
[Try it online!](https://tio.run/##Vc1LCoMwEIDhvaeYLgqZGjSJRKuQk1gXUSMN9YUNFE9vrVjQ7Tf/zIyzew59dB@nxanH0uqurDVoWtIqI3OmbO8IqXzOAolhgniV/hyGEmwDtXaGbCUGH2NetZ4JKhWD7ut81eKici6okIVp3waY10xDt2052xmw3ThM7raM0@@HI4IJTmFdAIHoHTSiICnEZ9xTfmx5miYrraOInWr@PywPHDHGduaIyxc "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~128~~ 116 bytes
```
lambda q:max(x*(date(*q)==(M:=date(q[0],11,27))+timedelta(7*x+~M.weekday()))for x in(1,2,3,4))
from datetime import*
```
**[Try it online!](https://tio.run/##NY1LboMwEIb3OcXs4iHTyo8mBCRyg5yAsHCFUVBiHq6lwiZXJzals5pv/scMs7/3nToPbmmK2/LU9rvWMOZWT2xKWK29YcmIRcGuebHSWPKKhCCZIh58a01tnl6zNJkOr@vnrzGPWs8MEZvewQRtx4KXFH0h7hrXW4gtMQetHXrnkyUavfnxwQtlKbkUBEISyIogoiI4Epw22kSxqiLL0rCHm@J/uvgPHyMrzvnGoqryHYQZXNt5Fh8S7D8ue4JmJcTlDQ "Python 3.8 – Try It Online")**
[Answer]
# [Perl 5](https://www.perl.org/), 144 bytes
```
sub{$_=join$",map{@t=gmtime$_*604800+3e5;19000100+$t[5]*1e4+$t[4]*100+$t[3]}1..6e4;pop=~/..../;/ $&$'( $&\d+)+/;$_=6-$&=~y///c/9;/^[1-4]$/?$_:0}
```
[Try it online!](https://tio.run/##bZHbbsIwDIbv@xQWMhRoIYceRqkydj9p3OwOOrRBQN3Ww6BIQwhenbllgFYtURLbn2z/SXK9/vROuFSnzfZtjzP1nsUpNuzkNd8/FGqVFHGicdb1uTvg3HK0F4qAcy7IwWLiRV2h3dJyyTrHnOgg@n1fu2Ge5erI@jRYyABbaLZpny6sjsVC6uX3sKWOO8bYnAUhe5mInhshG@FsyA@n0Fhm67YBE5rSBkFLcikiUPfAIbLPxLcBvIo4f4mo5zgX4nAiglYQ3FVEXIh0auRaTXqXaqKmQIozcehVKuJetXk1BfKfan5N9aBGbtWoT3lbyfngltPZGwDJro2xjbqjHnAWVgHAFSho4ZJePFb0M5x3EeOJjCzxa4rIKg8S3Slz8nWcFstGcwMAcZpviyE0e8ItXf2d63mhFxQp3VVWss00bVBP0F/Ua2RmH@bQfBo/w/jRtCs1Nq5C43D6AQ "Perl 5 – Try It Online")
] |
[Question]
[
Your task is to create a good multiplication table for others to use. Given an integer \$n\$, generate a multiplication table that displays products up to \$n×n\$. You should start with \$2×2\$ as 1 times any number is itself and that is reflected in the row/column indices. Scientific notation and floating-points are NOT allowed. You must print every digit with no decimals (.00 or .00000034).
Formatting is a crucial component (after all, mutiplication tables are notorious for their formatting). The formatting criteria are listed below:
* At the top left corner or \$ \text{table}[0][0] \$, there will be a single number `1`.
* Each row and column index will be \$n\$ digits + one whitespace.
* There is one row of hypens/dashes that span from the beginning of the table and ends at the last digit of the number who has the largest amount of digits in the rightmost column.
* There is 1 column of pipes `|` that start from the top of the multiplication table and ends at the \$n\$th row. This column of pipes should not get in the way of the row indices' formatting.
* The values of the table should have its leftmost digit aligned with the leftmost digit of the column index.
* Between each value in each column, there should be one whitespace seperating the value. There will be NO newlines seperating each row.
Below is an example the covers all of the above points. **Note: for brevity, the example table skips from 2 directly to 54, your actual program should include ALL digits from 2 to 54 and onwards to 654546.**
```
1 | 2 54 3443 654546
-------------------------------------------------
2 | 4 108 6886 1309092
54 | 108 2916 185992 35345484
3443 | 6886 185992 11854249 2260487878
654546 | 1309092 35345484 2260487878 431052650116
```
1. Observe how in the above table, the hypens take priority over the pipes.
2. Notice how, no matter the size of the numbers, each column has at least 1 whitespace seperating it.
3. The hypen row ends at the last digit of \$431052650116\$ NOT \$654546\$.
4. Each column has its leftmost digit aligned with the leftmost digit of the column index (ex. the "6" in 6886 is aligned with the "2" in the column index).
5. Refer to the above table when in doubt. Comment for any clarifications.
## SAMPLE INPUT
```
5
```
## SAMPLE OUTPUT
```
1 | 2 3 4 5
---------------
2 | 4 6 8 10
3 | 6 9 12 15
4 | 8 12 16 20
5 | 10 15 20 25
```
## Constraints
You will possibly need unsigned 64-bit integers.
$$ 2 \leq n \leq 10^9 $$
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 52 bytes ([SBCS](https://github.com/abrudz/SBCS))
Full program. Requires fully printing high-precision floats.
```
r←' (\d)'⋄'-'@2↑r⎕R' |&'⍠'ML'1⊢r⎕R'\1'↓⍕⍕¨1(,∘.×⊢)⍳⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbmCo965yqk5iUm5aQqAPm6SZklCmk5@YklxVxAZQEBQGXGJgoKYGXFGfnlCqUFCiX5CkCxlMz0TJCqjvaC/0VAZeoKGjEpmuqPulvUddUdjB61TSwCmhCkrlCjpv6od4G6r4@64aOuRRDBGEP1R22TH/VOBaJDKww1dB51zNA7PB0or/modzNQyX@guf8VwKCAy9AAAA "APL (Dyalog Unicode) – Try It Online")
`r←' (\d)'` create the PCRE regex `r` as a space followed by a digit
`⎕` prompt for \$n\$
`⍳` **i**ndices 1 through \$n\$
`1(`…`)` apply the following tacit function with that as right argument and 1 as left argument:
`,` the concatenated arguments
`∘.×` as vertical axis for the multiplication table with horizontal axis being…
`⊢` the right argument
(now we have the number we need, including an extra row which will be replaced by dashes)
`⍕¨` format each number as text (since strings are left-justified)
`⍕` format the entire matrix (leaves double-spaces between columns)
`↓` split matrix into list of strings
`r⎕R'\1'` replaces matches for `r` with their digit (reduces column spacing to 1)
`⊢` on that…
`r⎕R' |&'⍠'ML'1` insert a space and a pipe before the first `r` match on each line
`↑` mix list of strings into matrix
`'-'@2` replace with dashes **at** the second row
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~27~~ 26 bytes
```
ṇ'|,¤+ṡ
ׇ€[¦t↑¦ṇ:l'-×,¤+ṣ
```
[Try it online!](https://tio.run/##S0/MTPz//@HOdvUanUNLtB/uXMh1ePqjhoWPmtZEH1pW8qht4qFlQFmrHHXdw9MhKhb//28KAA "Gaia – Try It Online")
[`ׇ€[¦tụ`](https://tio.run/##ARgA5/9nYWlh///Dl@KAoeKCrFvCpnThu6X//zU) generates the table without the lines.
**Commented**:
```
ṇ'|,¤+ṡ -- helper function to insert '|' at the second position
ṇ -- extract first element from list
'|, -- pair with "|"
¤+ -- prepend to the remaining list
ṡ -- join by spaces
ׇ -- multiplication table for 1..input
€[¦ -- left-align each row to its maximum length
t -- transpose to swap rows/columns
↑¦ -- map helper function over each row
ṇ -- extract first row from table
:l -- duplicate and take the length of the copy
'-× -- push a string of that many dashes
, -- pair with first row
¤+ -- and prepend to table
ṣ -- join the table by newlines
```
---
My attempt of adding a helper function to insert both `-` and `|` is two bytes longer:
```
¤ṇ:l4ṁ×,¤+
ׇ€[¦t⟨'|⇈ṡ⟩¦'-⇈ṣ
```
[Try it online!](https://tio.run/##S0/MTPz//9CShzvbrXJMHu5sPDxd59ASba7D0x81LHzUtCb60LKSR/NXqNc8au94uHPho/krDy1T1wVzFv//bwoA "Gaia – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~174~~ ~~172~~ ~~166~~ ~~164~~ 163 bytes
```
#define X u-=printf("\n\0-\0%-*i"
s(n){return!n?:s(n/10)+1;}i,j,u;t(n){for(i=0,u=2;j=i<n;X)){for(X"| "+4,s(n),++i);j<n;)X+4,s(n*n),i*++j);if(i<2)for(X);X+2)-2;);}}
```
[Try it online!](https://tio.run/##JY7LboMwEEX3@QpCFcnjh4qtrjIh/Q1LoQvkABmkOpFj2FC@3TXJbu65Olfj1OBcSh/XriffFbaYVP0I5GPPysY3lWqqg@JU7p7MwxK6OAW/99/HHD91BULjSnKUE8at7@@BUV3JqTY41nTyaOFNbflXlOJLbjNSCAIccwv2jXiGxIUYAalndDLwcgCtMKAMAq5r@m3Js/xZ0YbBSXdrA@f5nGHJzsbOGiJr4522NF/0D2QvJW3@AQ "C (gcc) – Try It Online")
-2 thanks to ceilingcat, by initialising `j` off the loop condition. -6 by introducing the macro `X` with a few changes to fit it in; -2 by extending it with some more changes. -1 thanks to ceilingcat, shortening `s` with `?:`.
Fairly straightforward:
* `s` produces the number of digits in a number plus 1, used to determine the column widths. `?:` is [a GCC extension](https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html), producing the same value as the left expression if it's nonzero (and the value of the right expression otherwise).
* The macro `X` contains multiple (null-terminated) strings run together, allowing it to be used for any of those strings – `X` alone prints a line feed, while `X+2` (adding 2 to the pointer) prints a hyphen, and `X+4` uses the format string `%-*i`; in one place, `|` is added to it, using concatenation of adjacent string literals.
* The return value of `printf` is the number of characters printed; `u` starts at 2 and has those values subtracted from it, making `u` 1 greater than the negative of the length of the first row excluding the extra space at the end. Using `X` to print a line feed subtracts the extra 1 from `u`, and then the row of hyphens is produced using `u`, subtracting -1 each iteration.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29 28 27~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Probably not the right tool for the job.
```
Zż€Ẏ€
×þ`Dz€⁶Z€ç”|K€ç”-ZY
```
A full program that accepts a positive integer and prints the formatted multiplication table.
**[Try it online!](https://tio.run/##y0rNyan8/z/q6J5HTWse7uoDklyHpx/el@BSBWQ@atwWBaQOL3/UMLfGG8bSjYr8//@/kQEA "Jelly – Try It Online")**
### How?
```
Zż€Ẏ€ - Link 1: transpose & insert chars: list of lists, M; character, C
Z - transpose M
ż€ - zip each with C
Ẏ€ - tighten each
×þ`Dz€⁶Z€ç”|K€ç”-ZY - Main Link: integer N
` - use N as both arguments of:
þ - table using:
× - multiplication
D - covert to decimal digits (vectorises)
€ - for each (list of digit lists):
z ⁶ - transpose with filler of a space character
Z€ - transpose each
ç”| - call last Link (1) as a dyad, f(that, pipe charater)
K€ - join each with space characters
ç”- - call last Link (1) as a dyad, f(that, dash charater)
Z - transpose
Y - join with newline characters
- implicit, smashing print
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~105 97~~ 96 bytes
```
->n{(r=1..n).map{|x|A=r.map{|y|"%-*s"%["#{y*n}".size,y*x]}.insert(1,?|)*" "}.insert 1,?-*A.size}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWqPI1lBPL09TLzexoLqmosbRtgjCrKxRUtXVKlZSjVZSrq7UyqtV0ivOrErVqdSqiK3Vy8wrTi0q0TDUsa/R1FJSUIKJKABFdLUcwUpr/xeUlhQrpOklJ@bkaBgaaP4HAA "Ruby – Try It Online")
* Saved 8 +1 thanks to @Dingus !
```
->n{...} # lambda retuning an array of strings.
(a=r=1..n) # a: used to take a line length to add '----...
r: range used 2 times to build a table
"#{y*x}".ljust # every value of table is converted to string and left-jusified by:
"#{y*n}.size " #> length of max value of column
we insert a | at index 1
and finally we insert a row line--- of length a
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ ~~28~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Lć'|‚ìDδ*€.Bø¬»g'-×1ǝ»
```
-6 bytes thanks to *@Grimmy*.
[Try it online.](https://tio.run/##AS8A0P9vc2FiaWX//0zEhyd84oCaw6xEzrQq4oKsLkLDuMKswrtnJy3DlzHHncK7//8xNQ)
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
ć # Extract head; pop and push [2,input]-list and 1 separated
'|‚ '# Pair this 1 with "|"
ì # And prepend it back: [1,"|",2,3,4,...,input]
Dδ* # Make a multiplication table:
D # Duplicate the list
δ # Apply over the two lists double-vectorized:
* # Multiply
# (we'll have a second row of single "|"s now)
€.B # Box each inner list, appending leading spaces to make all values the same
# length
ø # Zip/transpose; swapping rows/columns
¬ # Get the first row (without popping)
» # Pop and join it with newline delimiter
g # Pop and push its length (including those newlines)
'-× '# Pop and push a string with that many "-"
1è # Insert it at the second position in the list of lists
» # Join each inner list by spaces; and then every string by newlines
# (after which the result is output implicitly)
```
[Answer]
# [Factor](https://factorcode.org/), 153 bytes
```
[ [1,b] dup outer [ "|"1 rot insert-nth ] map [ simple-table. ] with-string-writer "\n"split harvest dup last [ drop 45 ] map 1 rot insert-nth "\n"join ]
```
[Try it online!](https://tio.run/##ZY@xbsMwDER3fwXhOTaQIl6apVvRJUuRyfEgJ2zMRqYUik5QoP/uUnG2AoR4OOneQV/uqEHm/efH7v0VRqdDLY7PmOCCwugXyw6ho5kJrxNyVlFQ9ScKsQIFmzqpoBtT3sRnSNGTalbbomiKl2ZuoV2v@g5OU4QwKQq0UP6Wa5BgDE4oWrEO0FlptLtEY/RYqes91ubeSYdqoVd3oQwoD1w@imBwcsOkD7h3Jlo4SYiwaZ68fzU5@x2IoZt7erP3y2fYW8CM@Q8 "Factor – Try It Online")
## Explanation
It's a quotation (anonymous function) that takes a number from the data stack and leaves a string on the data stack as output. Assuming `5` is on top of the data stack when this quotation is called...
| Snippet | Data stack |
| --- | --- |
|
```
[1,b]
```
|
```
{ 1 2 3 4 5 }
```
|
|
```
dup
```
|
```
{ 1 2 3 4 5 }{ 1 2 3 4 5 }
```
|
|
```
outer
```
|
```
{ { 1 2 3 4 5 } { 2 4 6 8 10 } { 3 6 9 12 15 } { 4 8 12 16 20 } { 5 10 15 20 25 }}
```
|
|
```
[ "|"1 rot insert-nth ] map
```
|
```
{ { 1 "|" 2 3 4 5 } { 2 "|" 4 6 8 10 } { 3 "|" 6 9 12 15 } { 4 "|" 8 12 16 20 } { 5 "|" 10 15 20 25 }}
```
|
|
```
[ simple-table. ] with-string-writer
```
|
```
"1 | 2 3 4 5\n2 | 4 6 8 10\n3 | 6 9 12 15\n4 | 8 12 16 20\n5 | 10 15 20 25\n"
```
|
|
```
"\n"split
```
|
```
{ "1 | 2 3 4 5" "2 | 4 6 8 10" "3 | 6 9 12 15" "4 | 8 12 16 20" "5 | 10 15 20 25" ""}
```
|
|
```
harvest
```
|
```
{ "1 | 2 3 4 5" "2 | 4 6 8 10" "3 | 6 9 12 15" "4 | 8 12 16 20" "5 | 10 15 20 25"}
```
|
|
```
dup last
```
|
```
{ "1 | 2 3 4 5" "2 | 4 6 8 10" "3 | 6 9 12 15" "4 | 8 12 16 20" "5 | 10 15 20 25"}"5 | 10 15 20 25"
```
|
|
```
[ drop 45 ] map
```
|
```
{ "1 | 2 3 4 5" "2 | 4 6 8 10" "3 | 6 9 12 15" "4 | 8 12 16 20" "5 | 10 15 20 25"}"---------------"
```
|
|
```
1 rot insert-nth
```
|
```
{ "1 | 2 3 4 5" "---------------" "2 | 4 6 8 10" "3 | 6 9 12 15" "4 | 8 12 16 20" "5 | 10 15 20 25"}
```
|
|
```
"\n"join
```
|
```
"1 | 2 3 4 5\n---------------\n2 | 4 6 8 10\n3 | 6 9 12 15\n4 | 8 12 16 20\n5 | 10 15 20 25"
```
|
[Answer]
# [jq](https://stedolan.github.io/jq/), 217 bytes
```
. as$m|[1+range(.)]|map(["\(.*range($m)+.)"|split("")])|(.[$m-1]|map(keys))as$l|map([to_entries[]|[.value[$l[.key][]]|values//" "]|join("")]|[.[0],"|",.[1:][]]|join(" "))|[.[0],"-"*(.[$m-1]|length),.[1:][]]|join("\n")
```
[Try it online!](https://tio.run/##Xc1NDsIgEAXgqzSTLpj@UBvjxqtMiWFBKhVoLWhiwtnFpkQXbt/75s10T4kX0pc2Ul@v0o2KcRTRyoURDIxXOSst1hwh@sXowABQYGScStv2Gd/UyyNuQybfhvmiXFi18iQi8ac0D0WlIb5BQULEPfFdBwWIOM3a7asbpYNoIELDqT/vMpcFIH7bFqrfc6PcGK74zwcHmNLx9J6XoGfnU7t@AA "jq – Try It Online")
## What
```
. as $m
| [ 1 + range(.) ] # Convert to rows
| map(["\(.*range($m)+.)" | split("")]) # Multiply, then convert numbers to lists of digits
| (.[$m-1] | map(keys)) as $l # Store indices into last (longest) row, for padding
| map( [
to_entries[]
| [.value[$l[.key][]] | values // " "] # Pad with nulls, then replace those with spaces
| join("")
]
| [.[0], "|", .[1:][]] # Insert vertical rule
| join(" ") # Join lines into single strings
)
| [.[0], "-"*(.[$m-1] | length), .[1:][]] # Insert horizontal rule
| join("\n")
```
[Answer]
# [jq](https://stedolan.github.io/jq/) `-r`, 142 bytes
```
def f:transpose[];[range(.)+1]|. as$r|[.[]|[.*$r[]|@sh/""]|[f|map(.//" ")]|[f|add]]|[f|[.[0],"|"]+.[1:]|join(" ")]|(.[0]|.,"-"*length),.[1:][]
```
[Try it online!](https://tio.run/##JYvNDoMgEIRfxWw8gCLo1V76Hps9kAj@pAUFjzx7KaWXmfkyM8eV82JsY@c7aBdPHw3SA0teDZO8nyjJRsc2JJRIRbo2FH/GTQEUtumtTyaVggZ4Zb0sVEM5jCQgAfUSp5nS4XfH/jv265IUMED3Mm69Ny7qCCnnafz48969i3kIXw "jq – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
Nθ≔E⊕θ↔⁻ι‹ι²ηFη«M→⪫⎇ι×ηιEη|¦¶Mθ↑»↙←ⅈ
```
[Try it online!](https://tio.run/##LY0xC8IwEIVn@ytCpyvERXCpk@CiWBFRcHCp9TSB9tImaUXU3x4v6vTu8fG@q1RpK1PWISyp7f2mb85ooctmydw5fSMoyhaWVFlskDxeGEkxPztT9x6h0NQ70FKs0X1zkmXMFc@vxgpQmXgmo8IMCPlO35RnMNpaTR5WRhPs0VJpH3G51w06UFJoFsSnfKavNOrSE3HO/qJOivzQcn0nP/HC3GmN1@j@qfPYpDgCj0KYhvFQfwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
≔E⊕θ↔⁻ι‹ι²η
```
Create a range from `0` to `n`, but swap the first two elements.
```
Fη«
```
Iterate over the range.
```
M→
```
Leave an empty column.
```
⪫⎇ι×ηιEη|¦¶
```
If this is the `0` column, print a column of `|`s, otherwise multiply the range by the column and print it joined with newlines. This leaves the cursor to the right of the bottom number.
```
Mθ↑
```
Move back to the top row.
```
»↙←ⅈ
```
Overwrite the row of `0`s with a line of `-`s.
[Answer]
# [R](https://www.r-project.org/), 157 bytes
Or **[R](https://www.r-project.org/)>4.1, 150 bytes** by replacing the word `function` with `\`.
```
function(n,x=outer(1:n,1:n),y=apply(apply(cbind(x[,1],"|",x[,2:n]),2,format),1,paste,collapse=" "))paste(c(y[1],strrep("-",nchar(y[1])),y[2:n]),collapse="
")
```
[Try it online!](https://tio.run/##RY3BCoMwEETvfkXZ0y5swQi9CPkS6yFNEyrYTYgRFPrvaaqHHmZ4DMxMKl4Xv4rNUxAU3nRYs0uoeuEq4l2bGOcdT7ePSZ64DaxGhg9wpa6XkbhjH9LbZGLF0SzZsQ3zbOLiNFyA6MjQ4j7U5pJTchHhCiz2ZdKRUv0azrF/tQEq1mT0eCNqfgR3gZM8qpaofAE "R – Try It Online")
### Explanation outline:
1. Compute the (unformatted) multiplication table using `outer`.
2. Add a column of `|`s, conveniently converting the array to type character.
3. Apply `format` to columns, which for character vectors does exactly what we need.
4. Collapse rows using spaces.
5. Add a row of `-`s.
6. Collapse everything using newlines.
[Answer]
# JavaScript (ES8), 138 bytes
```
n=>(g=i=>i++<n?(h=k=>s=++k<n?(k*i+'').padEnd((k*n+c).length)+[[,'| '][k]]+h(k):k*i)(c=`
`)+c+g(i):'')``.replace(c,c+s.replace(/./g,'-')+c)
```
[Try it online!](https://tio.run/##PcuxDsIgFEDR3a9w4z1fS41jI3XyK5omEEopQqApjZP/jrg4nuTel3qrrHe3HW1MsymLKFEMYIUTgyO6xweswoshCyL/k784Ygz5puZnnKE6kkYeTLTHijSODfuc2TT6aaIVPPZ1QNBCniSSJgsO@/pLyXezBaUN6EZT/qvjnW1Yy2qMRaeYUzA8JAsL3K6I5Qs "JavaScript (Node.js) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 137 bytes
```
!n=[(A=split(replace(repr("text/plain",[1:n fill(text"|",n) (1:n)*(2:n)']),r"( +)(\S+) ?"=>s"\2\1"),'
'))[2];"-"^~-length(A[2]);A[3:end]]
```
[Try it online!](https://tio.run/##FchBDoIwEEDRvacos2FGigbYQdBwBpelJkSr1jQTUmrCwnj1Wjb/J@/9cXaq1hgz7hUO/TI7G9Cb2U03s90jBLOGYwLLIFXVsnhY53BT@IJkEpiQ9lin5pqkBxQF4XgpSJyhPy0w1mMFJPNdTqRq3UEJ11/pDD/DC4ck1A2qaQ3ftY6ztxwcHzBraop/ "Julia 1.0 – Try It Online")
### Explanation:
* `[1:n fill(text"|",n) (1:n)*(2:n)']` creates a matrix: (here for n=5)
```
5×6 Matrix{Any}:
1 | 2 3 4 5
2 | 4 6 8 10
3 | 6 9 12 15
4 | 8 12 16 20
5 | 10 15 20 25
```
* the `@text_str` macro allows to hide the `"` around the `|`
* `repr("text/plain", ... )` formats it like seen above in a string
* since there is too many spaces and numbers are adjusted right instead of left, we apply the following regex: `replace( ... , r"( +)(\S+) ?" => s"\2\1")`
```
"""5×6Matrix{Any}:
1 | 2 3 4 5
2 | 4 6 8 10
3 | 6 9 12 15
4 | 8 12 16 20
5 | 10 15 20 25 """
```
* then we `split( ... , '\n')`, remove the first line and insert a line of `-`
* output is a list of strings:
```
6-element Vector{AbstractString}:
"1 | 2 3 4 5 "
"---------------"
"2 | 4 6 8 10 "
"3 | 6 9 12 15 "
"4 | 8 12 16 20 "
"5 | 10 15 20 25 "
```
[Answer]
# [Perl 5](https://www.perl.org/), 128 bytes
```
$_='';for$i(@n=1.."@F"){$_.=pack(join('',map A.length$n[-1]*$_.0,@n),map$i*$_,@n).$/}s/.*/"$&
-".$&=~s|.|-|gr/e;s/^\d+ +/$&| /mg
```
[Try it online!](https://tio.run/##FcrdDoIgGIDhc6@CsW/iHxCzjhybnXQT/ThXZpQCE8@iLj3Sw2fva7tp2IUAjSSkupsJVFJrKRjD9QGnb2iYtO31lTyN0gkhxdhatGdDp/v5AfpIxTlbnk1R63RtoBauYMA/jrOMY4gjihnE8us889T3E@8qxy@nW45yDrFHfOxD2KJIiKgsf8bOymgXaDvYPw "Perl 5 – Try It Online")
```
$_=''; # empty $_, to be used for building output
for$i(@n=1.."@F"){ # loop $i as 1 → n, "@F" is the input N, init array @n=1→N
$_.=pack( # add a new line to output in $_ with a pack template
join( # ...by joining
'', # ...without delimiter
map A.length$n[-1]*$_.0, # ...the template AxAyAz where x,y,z,... is the col widths
# ...of current $_ which is the widest cells which is
# ...always on last line
@n # map 1 → N to create a widths template string
),
map$i*$_,@n # fill template with the multiplications of this line
).$/ # add newline at end of each line
}
s/.*/"$&\n-".$&=~s|.|-|gr/e; # add ------... second line, same width as first plus one -
s/^\d+ +/$&| /mg # add | between col 1 and col 2 where col 1 is a number
# $_ now has the table string printed due to perl option -p
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 166 bytes
```
n->{var s="";for(int i=0,j;i++<n;s+=i<2?"\n"+"-".repeat(s.length()-1)+"\n":"\n")for(j=0;j++<n;)s+=s.format("%-"+((j*n+"").length())+"d ",i*j)+(j<2?"| ":"");return s;}
```
[Try it online!](https://tio.run/##nY89T8MwEIb3/oqTJSS7bqxQiQU3sCExMHUEBtN8YONcIvsSqSr57cEpHxtLF5/s957nfM6MJnPlx2zbvgsELt3VQNaresAD2Q7VWq8O3sQIT8YinFYA/fDm7QEiGUpl7GwJbcr4noLF5vkVTGiiOLcCPCI9/KighmLG7O40mgCxYEzXXeAWCWyRb5y2Uu5QR1nY3faevSCTLGMqVH1liEflK2zonYvsWsglvV0OsShckWt3hkWio0pvbULYVcYk526NkjHxxye6BLaxayckd8uoT0gyJnSoaAgIUU@zPn9@f4xUtaobSPVpN/LIa2X63h/5jRD/9lyS/Hq3@bd4Wk3zFw "Java (JDK) – Try It Online")
## Credits
* -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
] |
[Question]
[
# Output Distinct Factor Cuboids
Today's task is very simple: given a positive integer, output a representative of each cuboid formable by its factors.
## Explanations
A cuboid's volume is the product of its three side lengths. For example, a cuboid of volume 4 whose side lengths are integers can have sides `[1, 1, 4]`, `[1, 2, 2]`, `[1, 4, 1]`, `[2, 1, 2]`, `[2, 2, 1]`, or `[4, 1, 1]`. However, some of these represent the same cuboid: e.g. `[1, 1, 4]` and `[4, 1, 1]` are the same cuboid rotated. There are only two distinct cuboids with volume 4 and integer sides: `[1, 1, 4]` and `[1, 2, 2]`. The output can be any representation of the first cuboid, and any representation of the second cuboid.
## Input
Your program must take a single positive integer \$1 \le n \le 2^{31}‚àí1\$.
## Output
You will need to output all possible cuboids in a list or any other acceptable way. E.g.
```
Input Output
1 [[1, 1, 1]]
2 [[1, 1, 2]]
3 [[1, 1, 3]]
4 [[1, 1, 4], [1, 2, 2]]
8 [[1, 1, 8], [1, 2, 4], [2, 2, 2]]
12 [[1, 1, 12], [1, 2, 6], [1, 3, 4], [2, 2, 3]]
13 [[1, 1, 13]]
15 [[1, 1, 15], [1, 3, 5]]
18 [[1, 1, 18], [1, 2, 9], [1, 3, 6], [2, 3, 3]]
23 [[1, 1, 23]]
27 [[1, 1, 27], [1, 3, 9], [3, 3, 3]]
32 [[1, 1, 32], [1, 2, 16], [1, 4, 8], [2, 2, 8], [2, 4, 4]]
36 [[1, 1, 36], [1, 2, 18], [1, 3, 12],[1, 4, 9], [1, 6, 6], [2, 2, 9], [2, 3, 6], [3, 3, 4]]
```
Sub-lists don't need to be sorted, just as long as they are unique.
## Scoring
This is code golf, so shortest answer in bytes wins. Standard loopholes are forbidden.
*[Here](https://tio.run/##VVDbSgQxDH3vVwREaHVZdlyfhHlS9NEPWAapvWhgTEsnA@vXj2lnL5iXkJOT5JzkX/5OtF@Wm/eZ88zwghMjOYZX6zgVeJ4/E/oJ3gKFYgVRytkpQA9IrJFkRhujfIgQkfxHbGOTPponBRKnWviHYQVkKcowFEtfQXcbOMI9dCd6DYwC3Qqp72F3ha/LtjbnQF6jac0SeC50bioV5dg/LVWwUfiTU2FADoVTGiuxE@YohvUF3OaS/OxYx43szcFyvxd7yjoX8mqiGhirgdit4kTveNgNcCepW9PDUMW3R1nyMMnh4PVogBLX0bbuaq2VZ1cXslG51Ce3rlHL8vgH "Python 3 – Try It Online") is a test case generator*
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=192852;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~ 61 ~~ 60 bytes
Prints the cuboids to STDOUT.
```
n=>{for(z=n;y=z;z--)for(;(x=n/y/z)<=y;y--)x%1||print(x,y,z)}
```
[Try it online!](https://tio.run/##JYxNCoMwGET3PUU2xYSOlST9EdLPXbe9QOlCBKldpGJFTNSzpxE3w8wbeJ9yKH9V17R9OuShpmCpmOpvxz1Z48gbn6Zi3YaPZDOXeXEjZ1yk417Oc9s1tucjHLxYgnlKKGickEMqSA15hsyhNNQVOl6X1@4YdfeyenPLqGAT2xTJgxJ2YFYYVvM1NxzLIsIf "JavaScript (V8) – Try It Online")
### Commented
```
n => { // n = input
for( // outer loop:
z = n; // start with z = n
y = z; // set y to z; stop if we've reached 0
z-- // decrement z after each iteration
) //
for( // inner loop:
; // no initialization code
(x = n / y / z) // set x to n / y / z
<= y; // stop if x > y
y-- // decrement y after each iteration
) //
x % 1 || // unless x is not an integer,
print(x, y, z) // print the cuboid (x, y, z)
} //
```
[Answer]
# [Haskell](https://www.haskell.org/), 52 bytes
```
f n=[[a,b,c]|a<-[1..n],b<-[1..a],c<-[1..b],a*b*c==n]
```
[Try it online!](https://tio.run/##JcYxCoAwDADAr2RwkiiI4GRfUjKkwWqxhmIdfbtx6E13cD23nM0iqPOeMaDQy@vgp3FUwtDGhNIWCLkPvTinZBcnBQflTvpABxHmxT6Jmfdqg5TyAw "Haskell – Try It Online")
Tuples are in descending order. "3" seems to be a small-enough number that writing out the 3 loops was shorter than anything general I could come up with.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~83~~ 80 bytes
```
lambda n:[[i,j,k]for i in(r:=range(n+1))for j in r[i:]for k in r[j:]if i*j*k==n]
```
**[Try it online!](https://tio.run/##JYs9EsIgGAVrPcXXBeKzAPzJMIMXiSniGBSiJIM0nh5DLHf3vfmbnlNQzRyzNdf86t@3e09Bt62Dx9jZKZIjF1jUJvbhMbCwE5wX7RdNsXV6HY1/8rpzllzt69GY0OWS0vBJpTIBCYUDGggJoSCOEA2kgjxDLenE9XYzRxcSKx9Qtb9UILsS5/kH "Python 3.8 (pre-release) – Try It Online")**
---
...beating a two-loop version by three bytes:
```
lambda n:[[i,j,n//i//j]for i in(r:=range(1,n+1))for j in r if(i<=j<=n/i/j)>n%(i*j)]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œċ3P⁼¥Ƈ
```
A monadic Link accepting a positive integer which yields a list of 3-lists of positive integers.
**[Try it online!](https://tio.run/##y0rNyan8///o5CPdxgGPGvccWnqs/f///8ZGAA "Jelly – Try It Online")**
### How?
```
œċ3P⁼¥Ƈ - Link: positive integer, N
3 - literal three
œċ - all combinations (of [1..N]) of length (3) with replacement
i.e. [[1,1,1],[1,1,2],...,[1,1,N],[1,2,2],[1,2,3],...,[1,2,N],...,[N,N,N]]
Ƈ - filter keep those for which:
¥ - last two links as a dyad:
P - product
⁼ - equals (N)?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ÆDṗ3Ṣ€QP=¥Ƈ
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//w4ZE4bmXM@G5ouKCrFFQPcKlxof///8zNg "Jelly – Try It Online")
A monadic link taking an integer as its argument and returning a list of lists of integers.
## Explanation
```
ÆD | Divisors
·πó3 | Cartesian power of 3
Ṣ€ | Sort each list
Q | Unique
¥Ƈ | Keep only where the following is true (as a dyad, using the original argument as right argument)
P | - Product
= | - Is equal (to original argument)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~67 60~~ 59 bytes
For a given \$n\$, this produces all 3-tuples of with entries in \$\{1,2,\ldots,n\}\$ and filters out the valid ones. To guarantee uniqueness we require that the tuples are sorted.
```
f n=[x|x@[a,b,c]<-mapM id$[1..n]<$":-)",a*b*c==n,a<=b,b<=c]
```
[Try it online!](https://tio.run/##BcFBCoAgEADAryzhJdmE6hYu9IFeIB5WS5JqierQob/bzMr3tux7KQmE3Pu9o2MMGL1tDj4nyLNyrTHiraqGpq6QddCRSJAtBQyWoi8HZwGC88rygIIEfVd@ "Haskell – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 59 bytes
```
.+
*
2+%L$`(?<=(_+))(?=(\1)*$)
$` _$#2*
A`_(_+) \1\b
_+
$.&
```
[Try it online!](https://tio.run/##Fck9CsJAEIDR/jtFwInsDwRmVmMKQ7Cy8QgLuwoWNhaSs3kAL7bqa9/rvj6eV229O9c2RAIW@4tUtxxnV6L3bpldVh/EI7UrsrHAqZb/dVnzjRKRYduEz7spRmLHhBqa0D06YQk7kH41fgE "Retina – Try It Online") Link includes test suite. Explanation:
```
.+
*
```
Convert to unary.
```
2+%L$`(?<=(_+))(?=(\1)*$)
$` _$#2*
```
Repeating twice, divide the last number on each line into all of its possible pairs of factors. The lookbehind is greedy and atomic, so once it's matched the prefix of the last number it won't backtrack. This generates all possible permutations of three factors.
```
A`_(_+) \1\b
```
Delete lines where the factors are not in ascending order.
```
_+
$.&
```
Convert to decimal.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
fqQ*FT.CSQ3
```
[Try it online!](https://tio.run/##K6gsyfj/P60wUMstRM85OND4/39jMwA "Pyth – Try It Online")
```
SQ # range(1, Q+1) # Q = input
.C 3 # combinations( , 3)
f # filter(lambda T: vvv, ^^^)
qQ # Q ==
*FT # fold(__operator_mul, T) ( = product of all elements)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
Ò3.ŒP€{ê
```
```
Ò # prime factors of the input
3.Œ # all 3-element partitions
P # take the product of each inner list
€{ # sort each inner list
ê # sort and uniquify the outer list
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8CRjvaOTAh41rak@vOr/f2MzAA "05AB1E – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 89 bytes
```
a,b,x;f(n){for(a=n;a;a--)for(b=a;b&&(x=n/a/b)<=b;b--)x*b*a-n||printf("%d,%d,%d ",x,b,a);}
```
[Try it online!](https://tio.run/##HUztCsIgFP3vU1wGDR3Kcg5pmA9zXRlBWcgCYduz2y04nE84s5ofmG61ogyyuMiTWOMrc/TJoUOlxC8Fjy60LS8@9dgHcfbBBdpKFzpUadve@Z6WyJvDRf4BjSx0iMLtlRZ44j1xsTIWubHCMZavyycnODq2Vw0ajGUaBtAnEgN6IBlhYgN1E3kLlrwhNsTjFw "C (clang) – Try It Online")
Port of @Arnauld üëç
Saved 1 thanks to @Jonathan Frech better output format
[Answer]
# [Icon](https://github.com/gtownsend/icon), 87 bytes
```
procedure f(n)
k:=[]
a:=1to n&b:=1to a&c:=1to b&a*b*c=n&k|||:=[[a,b,c]]&\z
return k
end
```
[Try it online!](https://tio.run/##TY7BDoIwDIbve4qGwzIIF/VGwpOMHbZRk7HYmQkaFZ8dB4vEnv6/X/u3zgZalmsMFvspIpwFlcw3rVRMN@1hDEDcZKG5zcJwXZnKtsT9PM9pVura1FYp3r1YxHGKBJ4h9X@5F@1IlAxSpfR05nTMDu8Yn@BSMqToykMf4L2RHQ47lE6t/BHdiDexWjmouoCi/G1sSBQd5dZne@ML "Icon – Try It Online")
Close to Python :)
] |
[Question]
[
*Based on a [chat message](https://chat.stackexchange.com/transcript/message/39355755#39355755)*
## The Challenge
Given an input number \$n > 9\$, construct its reverse, ignoring leading zeros. Then, construct a list of all prime factors that the number and its reverse *don't* have in common. Multiply those factors together to create the ***Uncommon Factor Number*** of the input.
Or, to put it another way: if \$\text{rev}(n)\$ denotes the decimal reversal of integer \$n\$, calculate the product of \$n\$ and \$\text{rev}(n)\$ divided by the square of the \$\gcd(n, \text{rev}(n))\$.
Output that number.
### Worked examples
For example, \$2244\$ reverses to \$4422\$. The prime factors of the first are \$[2, 2, 3, 11, 17]\$ and the prime factors of the reverse are \$[2, 3, 11, 67]\$. The numbers not in common multiplicities are \$[2, 17, 67]\$, so \$2278\$ is the output.
For another example, \$1234\$ reverses to \$4321\$. The product is \$5332114\$ and the GCD is \$1\$, so the output is \$5332114\$.
## Further clarifications
Obviously a palindromic number will have all its factors in common with its reverse, so in such a case the output is \$1\$ \$\left(\frac{n\times n}{n^2}\right)\$. Obviously, it's also possible for the output to be the multiplication all factors (i.e., the gcd is \$1\$ -- the input and its reverse are co-prime), as in the case of the \$1234\$ example.
## Rules
* The input and output can be assumed to fit in your language's native integer type.
* The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
## Examples
```
in
out
17
1207
208
41704
315
1995
23876
101222302
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
### Code
```
‚D¿÷P
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//cNOjhlkuh/Yf3h7w/7@xoSkA "05AB1E – Try It Online")
### Explanation
```
‚ # Get the array [input, reversed(input)]
D # Duplicate that array
¬ø # Calculate the GCD of the array
√∑ # Divide each element in the array by the GCD
P # Product of that array
```
[Answer]
# J, 18 bytes
```
".@|.@":(*%*:@+.)]
```
[Try it online!](https://tio.run/##y/r/P03BVk9BSc@hRs9ByUpDS1XLykFbTzOWiys1OSNfIU3B0MjYBJldoeDnpKdQWpyqkFpRkpqXkpqiUFCUmpxZnJmfp5CZplCZX6qQkp@nXqJQnphXolCcnKmQl1@SWAKUhhljZGABYxobmv7/DwA)
Alternatively (credit to @Adnan's approach for the second one),
```
".@|.@":(*%2^~+.)]
".@|.@":*/@(,%+.)]
```
# J, 15 bytes (@miles's solution)
```
*/@(,%+.)|.&.":
```
# Explanation
This is just a straightforward implementation of the algorithm given by the OP.
```
".@|.@":(*%*:@+.)]
] n (input)
".@|.@": n reversed
* Product of the two
% Divided by
+. GCD
*: Squared
```
# Explanation, @miles's solution
Very clever.
```
*/@(,%+.)|.&.":
|.&.": Reverse digits
&.": Convert to string, apply next function, and undo conversion
|. Reverse
(,%+.) Divide n and reverse(n) by GCD of both
*/ Product
```
[Answer]
# Mathematica, 33 bytes
```
#(s=IntegerReverse@#)/GCD[#,s]^2&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvtfWaPY1jOvJDU9tSgotSy1qDjVQVlT393ZJVpZpzg2zkjtf0BRZl6JgkNatJGxhblZ7P//AA "Mathics – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
,ṚḌµ:g/P
```
[Try it online!](https://tio.run/##y0rNyan8/1/n4c5ZD3f0HNpqla4f8P//f0NzAA "Jelly – Try It Online")
[Answer]
## Haskell, 44 bytes
```
f x|r<-read$reverse$show x=x*r`div`gcd x r^2
```
[Try it online!](https://tio.run/##BcFLDkAwFAXQrdxBR1IJFZ8BKxGi0YfGN69CB/Ze5yzarbRtIUzwH9cxkzaC6SF2JNxyvvCNj3gw9hnm0cCDexV2bQ80uNgeNwR2fWFCm5ZSJZXM0lyqrCqLLvw "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~108~~ 89 bytes
*-19 bytes thanks to plannapus for his gcd algorithm*
```
function(n){k=1:nchar(n)-1
q=1:n
(r=sum(n%/%10^k%%10*10^rev(k)))*n/max(q[!r%%q&!n%%q])^2}
```
This will attempt to allocate at least one vector of size `4*n` bytes (and I think as many as 4), so this will throw a memory error for sufficiently large `n`.
[Try it online!](https://tio.run/##JcjRCoJAEIXhe59CLzZmBHFnRDejfZJIEGkpFifcMoLo2bcNb37Od0J0@bGKbpXpebsLCH68pYNM1zEkVJQtf2YQ7GOdQVStSA9epZZphMsLPCKWUs/jG5ZTEZRadoWknnHgb3RABnNrc2JtMgcNtRv7vk3kZm@67dDEzI3m@AM "R – Try It Online")
[Answer]
# JavaScript, ~~67~~ ~~64~~ ~~60~~ 59 bytes
So many bytes just to reverse the number :(
Takes input as a string. 1 byte saved thanks to l4m2.
```
f=(n,x=n,y=r=[...n].reverse().join``)=>y?f(n,y,x%y):n*r/x/x
```
[Try it online!](https://tio.run/##bcrRCoIwFADQ9z5DCLZY10xSEW59SASK3YUid3Ensn398jl8PZypX3s/yPhdzuzelJJFxSYgm4iCTwDgFwitJJ6UhsmN3HUa7/FhtxdNOEbd8knykIc0OPZuJpjdR1mVFXWm9eEPr5dmR8vitnfLpq42Tz8)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~73~~ 68 bytes
*-5 bytes thanks to Mr. Xcoder.*
```
import math
def f(n):g=int(str(n)[::-1]);print(n*g/math.gcd(n,g)**2)
```
[Try it online!](https://tio.run/##PY/BboMwDIbveQqLCwSlnShaOzGx@56h6iEjTogECUtCpT49c0CaT7/9f/ptL680etduRVGwbw0Bn5XjoND5hBHSiKQHO8spWxgiCa/BuoQGAzgBg5yGdZIJd3gJXq1DyowD6dR/oH1ahQp@XjsWf1cZMFO5M4OqKOlA@ZnRLZudFx8SzDKNTKEGTVZnelpcxRSouXfdqXnwzyXkmavNW2bPR5bhdX3hG72QIvRwb24C2uZdwKX9uF0fjGkfwNIbsCMdA6ojyQooT19QCkA6v4ey5LurK8u3Pw "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ ~~12~~ 11 bytes
```
tVPU*1MZdU/
```
[Try it online!](https://tio.run/##y00syfn/vyQsIFTL0DcqJVT//38jIxMTAA) Or [verify all test cases](https://tio.run/##y00syfmf8L8kLCBUy9A3KiVU/79LyH9Dcy4jAwsuY0NTLiNjC3MzAA).
### Explanation
```
t % Imoplicit input: number. Duplicate
VPU % String representation, flip, evaluate. This reverses digits
* % Multiply input and reversed-digit version
1M % Push the input and reversed-digit version again
Zd % Greatest common divisor
U % Square
/ % Divide. Implicit display
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 11 bytes
```
ùïìùïã‚ÇÅùê´ùêï‚ÇÅùêïùïåùꆷõ¶ùïç
```
[Try it online!](https://tio.run/##y0vNzP3//8PcqZOBuPtRU@OHuRNWA/FUCHMqULQHSC94OHsZkNn7/7@hOQA "Neim – Try It Online")
No GCD built-in. ;-;
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
S¤§÷o□⌋*i↔
```
[Try it online!](https://tio.run/##ASEA3v9odXNr//9TwqTCp8O3b@KWoeKMiypp4oaU////IjMxNSI "Husk – Try It Online")
-1 thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz).
-1 thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb).
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~13~~ ~~12~~ 11 bytes
```
sw
*V/yU ²
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=CnN3CipWL3lVILI=&input=MTIzNA==)
---
## Explanation
Implicit input of integer `U`. The empty line at the beginning, prevents the following line from overwriting `U`
```
sw
```
Convert `U` to a string (`s`), reverse it (`w`), convert back to an integer and assign to variable `V`.
```
*V
```
Multiply `U` by `V`.
```
/
```
Divide.
```
yU
```
GCD of `V` and `U`.
```
²
```
Squared. Implicit output of resulting integer.
---
## Alternative, 13 bytes
Just because I like being able to use `N`.
```
NpUsw)mxNry)√ó
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=TnBVc3cpbXpOcnkp1w==&input=MjA4)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
/*QKs_`Q^iKQ2
```
**[Try it here!](https://pyth.herokuapp.com/?code=%2F%2aQKs_%60Q%5EiKQ2&input=123&test_suite=1&test_suite_input=17%0A315%0A23876&debug=0)**
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
This uses Adnan's approach and takes input as a String.
```
KsM_BQ*Fm/diFKK
```
**[Try it here](https://pyth.herokuapp.com/?code=KsM_BQ%2aFm%2FdiFKK&input=%22315%22&debug=0)**
[Answer]
# x86 Machine Code, 39 bytes
```
;;; Obtain a "reversed" version of the input value.
;;;
;;; To do this, each iteration of a loop, we take the input value modulo 10,
;;; add that to our accumulator (EDI), multiply the accumulator by 10, and
;;; divide the input value by 10. x86's DIV instruction does both modulo and
;;; division as a single operation, with the cost of clobbering two output
;;; registers (EAX and EDX). We clobber the input value throughout the loop
;;; (the way we know we're done is when it becomes 0---that means that we have
;;; pulled all of the digits off of it), so we need to save a copy of it first.
89 C8 mov eax, ecx ; make copy of input
31 FF xor edi, edi ; clear accumulator
6A 0A push 10
5E pop esi ; set ESI to 10
Reverse:
0F AF FE imul edi, esi ; accumulator *= 10
99 cdq ; zero EDX in preparation for division
F7 F6 div esi ; EDX:EAX / 10 (EAX is quot, EDX is rem)
01 D7 add edi, edx ; accumulator += remainder
85 C0 test eax, eax ; was quotient 0?
75 F4 jnz Reverse ; if not, keep looping and extracting digits
;;; At this point, EAX is 0 (clobbered throughout the loop),
;;; ECX still contains a copy of our original input, and
;;; EDI contains the 'reversed' input.
89 C8 mov eax, ecx ; make another copy of the input
F7 E7 mul edi ; multiply input (implicit EAX operand)
; by 'reversed', with result in EDX:EAX
; (note: EDX will be 0)
;;; Compute the greatest common denominator (GCD) of the input and
;;; the 'reversed' values, using a subtraction-based algorithm.
GCD_0:
39 CF cmp edi, ecx ; compare the two values
72 02 jb GCD_1 ; go to GCD_1 if less than
87 F9 xchg ecx, edi ; swap values
GCD_1:
29 F9 sub ecx, edi ; subtract
75 F6 jnz GCD_0 ; if sum != 0, go back to the top
;;; Square the GCD.
0F AF FF imul edi, edi
;;; Divide the product of input and 'reversed' by the square of the GCD.
;;; Remember from above that the product of input and 'reversed' is in
;;; the EAX register, and we can assume EDX is 0, so we don't need to do
;;; a CDQ here in preparation for the division. Using EAX as the implicit
;;; source operand saves us a byte when encoding DIV.
F7 F7 div edi
;;; The DIV instruction placed the quotient in EAX,
;;; which is what we want to return to the caller.
C3 ret
```
The above function computes the "uncommon factor number" of the specified input parameter. Following the register-based [\_\_fastcall calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall), the parameter is passed in the `ECX` register. The result is returned in the `EAX` register, as with all x86 calling conventions.
**[Try it online!](https://tio.run/##bY/baoNAEIav3acYLAUtTbOu0VVsAyGNL9Etsl1NsmA2RVdYKH312smJ5CIXP3P455th1GSj1DiqvektqK3swGXpcl83H5/wBr5wWS7cMhMujoQrS@HShXAUlawwYr1AlZjnOFdyVIp9nH3HPEuQpcJxjOXsuuswt0LFhxp5zpBBZQceeyw/xSOX3twpzzdQy9gvSG@l1QoG0@uNaWqoKmltp78G21RVEKxlb5Vs2zCE4An/Kp0Jg8twiP@dfy3GB21UO9QNvPa21vuX7ZwQbSzspDZBSH6I991hvQ58AIi4sJO5sI@1MP4znBYHRyMMC286hYhRfoswmt1H0Dgjs4jT2S0TR8l9Bo3LmTxPrgiLM57eQ47GBaERYyymjHjE6xo7dAZoQX7HP7Vu5aYfJ7uY/QM)**
This took an awfully long time to write in such a compact form, but it was a fun exercise. Lots of contortions to get the most optimal register scheduling possible, within the constraints of the x86 `DIV` instruction's implicit operands and trying to use short encodings of `MUL` and `XCHG` instructions whenever possible. I'd be very curious to see if someone can think of another way to shorten it further. My brain was quite fried by the end. Thank a compiler next time you see one! (Although this is *way* better code than what a compiler would generate... Especially if you tweaked it slightly without size constraints, removing things like `XCHG`.)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
```
⊢(∧÷∨)⌽⍢⍕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXIo1HHcsPb3/UsULzUc/eR72LHvVO/Z/2qG3Co96@R31TPf0fdTUfWm/8qG0ikBcc5AwkQzw8g/@nHVqhYGiuYGRgoWBsaKpgZGxhbgYA "APL (Dyalog Extended) – Try It Online")
$$\text{UCF}(n) = \frac{n\times \text{rev}(n)}{\gcd(n, \text{rev}(n))^2} = \frac{\text{lcm}(n,\text{rev}(n))}{\gcd(n,\text{rev}(n))} = \frac{\text{lcm}}{\gcd}(n,\text{rev}(n))$$
`⌽` reverse `⍢` under `⍕` conversion to string, then apply `∧÷∨` (lcm ÷ gcd) between the result and and the original argument.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ṚḌæl:gɗ
```
[Try it online!](https://tio.run/##y0rNyan8///hzlkPd/QcXpZjlX5y@v/D7Y@a1vz/b2iuo2BkYKGjYGxoCmQZmZjoKBgaGQNJI2MLczMA "Jelly – Try It Online")
-1 byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
Similar to Erik's Jelly answer, but uses a dyadic route rather than monadic lists.
Uses the formula [found by ovs](https://codegolf.stackexchange.com/a/233489/66833)
$$\text{UCF}(n) = \frac{\text{lcm}(n,\text{rev}(n))}{\gcd(n, \text{rev}(n))}$$
## How it works
```
ṚḌæl:gɗ - Main link. Takes n on the left
·πö - Split n into digits and reverse
Ḍ - Convert back into an integer; rev(n)
…ó - Combine the previous three links into a dyad
with n on the right and rev(n) on the left:
√¶l - lcm(n,rev(n))
g - gcd(n, rev(n))
: - Divide lcm(n,rev(n)) by gcd(n, rev(n))
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 11 bytes
```
ĐĐ₫Đ3Ș*↔Ǥ²/
```
[Try it online!](https://tio.run/##ASAA3/9weXT//8SQxJDigqvEkDPImCrihpTHpMKyL///MjI0NA "Pyt – Try It Online")
| Code | Stack | Description |
| --- | --- | --- |
| Đ | n,n | Implicit input; duplicate top of stack |
| Đ | n,n,n | Duplicate top of stack |
| ‚Ç´ | n,n,rev(n) | Reverse the digits of the top of the stack |
| Đ | n,n,rev(n),rev(n) | Duplicate top of stack |
| 3»ò | n,rev(n),rev(n),n | Flip the order of the top three items on the stack |
| \* | n,rev(n),rev(n)\*n | Multiply the top two items on the stack |
| ‚Üî | rev(n)\*n,rev(n),n | Flip the stack |
| Ǥ² | rev(n)\*n,gcd(n,rev(n))^2 | Take the gcd of n and rev(n) and square it |
| / | rev(n)\*n/(gcd(n,rev(n))^2) | Divide; implicit print |
[Answer]
# [Perl 5](https://www.perl.org/), 72 bytes
71 bytes of code + 1 flag (`-p`)
```
$t=$_*($b=reverse);($_,$b)=(abs$_-$b,$_>$b?$b:$_)while$_-$b;$_=$t/$_**2
```
[Try it online!](https://tio.run/##HcvhBoAwFAbQl/l@bNmkSJTVo1xdLkVqtqm375b@Hk6UtHeqKAFUGXBIcknKYkcDcmAbzMIZ5MEONIFn8ACy97rt8vMICij116tWtemfM5btPLL6@AI "Perl 5 – Try It Online")
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 8 bytes
```
_]FbP).^B
```
[Try it here!](http://pyke.catbus.co.uk/?code=5F+5D+46+62+50+29+DE+42&input=%222244%22&warnings=0&hex=1)
Takes input as a string.
```
_ - reversed(input)
] - [^, input]
FbP) - for i in ^:
b - int(^)
P - factors(^)
.^ - xor_seq(^)
B - product(^)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
Thanks to [i cri everytim](https://codegolf.stackexchange.com/users/68615/i-cri-everytim).
```
def f(n):g=int(`n`[::-1]);print n*g/gcd(n,g)**2
from fractions import*
```
[Try it online!](https://tio.run/##HcpBCsMgEEDRvaeYpYqlmNCmGHKSEEhJMnYWGUVn09Pb0L98/PyVT@Kutf1AQM0mxIlY9MrrHMLNL2bM5QJgG@9x2zW7aKztFJZ0Apb3JpS4Ap05FbFNjioVJpj94KD3Dwdd/xqei1KYChAQw38JCq5Qk2k/ "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 77 bytes
Note that in Python 2, you cannot use the `math.gcd()` method, and you must do it "by hand".
```
y=lambda a,b:b and y(b,a%b)or a
def f(n):g=int(`n`[::-1]);print n*g/y(n,g)**2
```
[Try it online!](https://tio.run/##HYxBCoMwFAX3OcXbFBJJKSqtJSUnEcEfNGmg/Ypmk9OnobMchtlzem/clZLth75uIZB2xoF4QZZO08Wp7QCJZfXwkpUJNnKSM8@jMdd2Uq/9qALchFuWrINqmq6k9UwnLMZ20Ojbu0bXP4fHJISvt4jI@CdGoOJlVOUH "Python 2 – Try It Online")
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm/tree/v1), 9 bytes
```
DR«D]Æ┴/µ
```
[Try it online!](https://tio.run/##y8/I/f/fJejQapfYw22PpmzRP7T1/39DIwA "Ohm – Try It Online")
[Answer]
# Java 8, ~~158~~ ~~150~~ ~~148~~ ~~138~~ ~~125~~ ~~123~~ ~~116~~ 107 ~~+ 19~~ bytes
```
i->{int o,r,f,t=f=i;i=r=i.valueOf(""+new StringBuffer(t+"").reverse());while(t>0)t=i%(i=t);return f/i*r/i;}
```
[Try it online!](https://tio.run/##LY8xT8MwEIX3/IpTJCS7TV0EY3AGBiQGxNARMZjUDhcc23LOqaIqvz24kDednj7pfderSR180K4//6w4BB8J@tyJRGiFSa4l9E7s6qII6ctiC61V4whvCh1cC8gZSVHuXzb26dWR7nSsYDsamEHCiofmio7AV7EyFUkjsUYZJYpJ2aTfDSvLvdMXOFFE1z0nY3RktC9LLqKedBw147y@fKPVjJp7ThLvGEriddSUogNzxF08Yr2s2fZmthlvgpPHMwzZm/0vfHyCit3ItzduOc0j6UH4RCJkhNgsVAh2Zo8PefoPW4pl/QU "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
Ṙ∆Ŀ?Ḃġ/
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B9%98%E2%88%86%C4%BF%3F%E1%B8%82%C4%A1%2F&inputs=17&header=&footer=)
```
·πò # Reverse
∆Ŀ # LCM with that
? # Take input
Ḃ # Dupe-reverse
ƒ° # GCD
/ # Quoitent
```
Would be [5 bytes](https://lyxal.pythonanywhere.com?flags=&code=%E1%B9%98%E2%82%8C%E2%88%86%C4%BF%C4%A1%2F&inputs=17&header=&footer=) if parallel apply worked with digraphs.
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 25 bytes
Uses [ovs' technique](https://codegolf.stackexchange.com/questions/142177/the-uncommon-factor-number/233489#233489).
```
:/%[:lcm%r=S|:~|Z,:gcd%r]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBYjdbjaWlJWm6Fjut9FWjrXKSc1WLbINrrOpqonSs0pNTVItiIfKrNbkKFNyiDY2MTaAiCxZAaAA)
## Explanation
```
:/ % [:lcm % r = S | :~ | Z, :gcd % r]
r = S | :~ | Z # Helper function: Convert to string, reverse, convert back to int
:/ % [ , ] # Divide...
:lcm % r # LCM of input and its reverse by
:gcd % r # GCD of input and its reverse
```
## J-uby, 32 bytes
We can get rid of the awkward helper function `r` but at a cost of seven bytes:
```
:/%(-[:%&:lcm,:%&:gcd]^(S|:~|Z))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWNxWs9FU1dKOtVNWscpJzdUB0enJKbJxGcI1VXU2UpiZE3coCBbdoQyNjk1gIf8ECCA0A)
] |
[Question]
[
## Definitions
* A **bijection** from a set `S` to a set `T` is a function from `S` to `T` such that one element in `T` is mapped by exactly one element in `S`.
* A **bijection within a set** `S` is a bijection from `S` to `S`.
* The **natural numbers** are the integers which are greater than or equal to `0`.
* A **subset** of a set `S` is a set such that every element in the set is also in `S`.
* A **proper subset** of a set `S` is a set that is a subset of `S` which is not equal to `S`.
## Task
Write a program/function that takes a natural number as input and outputs a natural number. It must be a bijection, and the image of the primes under the program/function, `{f(p) : p ∈ ℙ}`, must be a proper subset of `ℙ`, where `ℙ` is the prime numbers.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
[Answer]
## Mathematica, ~~54~~ 48 bytes
```
±(t=x_?PrimeQ)=NextPrime@x
±n_:=Abs[n-1]/.t:>x-1
```
Defines the following bijection:
```
n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ...
±n 1, 0, 3, 5, 2, 7, 4, 11, 6, 8, 9, 13, 10, 17, 12, 14, 15, 19, ...
```
The basic idea is to map each prime to the next, to ensure that they are mapped to a proper subset. This results in a "gap" at **2**. To fill that gap, we want to map **4** to **2** and then each other composite number to the previous composite number, to "bubble up" the gap. Since **2** and **3** are the only two adjacent primes, we can express both of those mappings as "**n-1** or if that's a prime then **n-2**". Finally, this mapping ends up sending **1** to **0** and we make it send **0** back to **1** by taking the absolute value of **n-1**.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 21 bytes
*Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for spotting a mistake, now corrected*
```
tZp?_Yq}q:Zp~fX>sG~E+
```
[Try it online!](https://tio.run/##y00syfn/vySqwD4@srC20CqqoC4twq7Yvc5V@/9/Q0MA)
This implements the following bijection. Write the primes in a row and the non-primes below:
```
2 3 5 7 11 13 17 ...
0 1 4 6 8 9 10 ...
```
Then the output is obtained by following the arrow from the input:
```
2 > 3 > 5 > 7 > 11 > 13 > 17 ...
^
0 < 1 < 4 < 6 < 8 < 9 < 10 ...
```
### Explained code
```
t % Implicit input. Duplicate
Zp % Is it a prime? Gives true / false
? % If so
_Yq % Next prime
} % Else
q % Subtract 1
: % Range from 1 to that
Zp~ % Is each entry not a prime? Gives an array of true / false
f % Find non-zero entries, i.e. non-primes. Will be empty for input 1
X> % Maximum. This gives the greatest non-prime less than the input.
% Will be empty for input 1
s % Sum. This is to transform empty into 0
G~E % Push input, negate, times 2. This gives 2 for input 0, or 0 otherwise
E % Add. This handles the case of input 0, so that it outputs 2
% End (implicit). Display (implicit)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Æn’’ÆP¿$ÆP?2¹?
```
[Try it online!](https://tio.run/##y0rNyan8//9wW96jhplAdLgt4NB@FSBpb3Rop/3///8NAA "Jelly – Try It Online")
Uses Luis's algorithm.
[Answer]
## JavaScript (ES6), ~~82~~ ~~77~~ 75 bytes
Implements the same logic as [Luis Mendo's answer](https://codegolf.stackexchange.com/a/125331/58563).
```
f=(n,i=(P=(n,x=n)=>n%--x?P(n,x):x==1||-1)(x=n))=>x?x==n|P(n)-i?f(n+i,i):n:2
```
### Formatted and commented
```
f = ( // given:
n, // - n = input
i = // - i = 'direction' to move towards
(P = (n, x = n) => // - P = function that returns:
n % --x ? // - 1 when given a prime
P(n, x) // - -1 when given a composite number
: //
x == 1 || -1 //
)(x = n) // - x = copy of the original input
) => //
x ? // if the input is not zero:
x == n | P(n) - i ? // if n equals the input or doesn't match its primality:
f(n + i, i) // do a recursive call in the chosen direction
: // else:
n // return n
: // else:
2 // return 2
```
### Demo
```
f=(n,i=(P=(n,x=n)=>n%--x?P(n,x):x==1||-1)(x=n))=>x?x==n|P(n)-i?f(n+i,i):n:2
for(n = 0; n < 50; n++) {
console.log(n, '->', f(n));
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Æn_ḍ@¡ÆP?2»0
```
[Try it online!](https://tio.run/##ASgA1/9qZWxsef//w4ZuX@G4jUDCocOGUD8ywrsw/zByMjDCtSzDh@KCrEf/ "Jelly – Try It Online")
### How it works
```
Æn_ḍ@¡ÆP?2»0 Main link. Argument: n (non-negative integer)
ÆP? If the input is prime:
Æn Compute the next prime after n.
Else:
ḍ@¡ 2 Do once if n is divisible by 2, zero times if not.
_ 2 Subtract 2.
So far, we've mapped all primes to the next prime, all even integers
(except 2) to the previous even integer, and all composite, odd,
positive integers to themselves. In particular, 0 -> 2, but 0 doesn't
have a preimage, so we need 0 -> 0.
»0 Take the maximum of the result and 0, mapping 0 -> max(-2, 0) = 0.
```
] |
[Question]
[
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.:
```
1 = 1
2 = 2
3 = 3
4 = 3 + 1
12 = 8 + 3 + 1
13 = 13
100 = 89 + 8 + 3
```
Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$.
Write a program or function that given a positive integer *n* returns the Fibonacci product of that number.
---
Testcases:
```
1: 1
2: 2
3: 3
4: 3
5: 5
6: 5
7: 10
8: 8
9: 8
42: 272
1000: 12831
12345: 138481852236
```
[Answer]
## Python, 54 bytes
```
f=lambda n,a=1,b=1:n<1or b>n and a*f(n-a)or f(n,b,a+b)
```
Just some good old recursion.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Rf1+С¤ṪạµÐĿIAP
```
Not particularly fast or memory friendly, but efficient enough for all test cases. [Try it online!](http://jelly.tryitonline.net/#code=UmYxK8OQwqHCpOG5quG6ocK1w5DEv0lBUA&input=&args=MTIzNDU)
### How it works
```
Rf1+С¤ṪạµÐĿIAP Main link. Argument: n (integer)
µ Combine the chain to the left into a link.
ÐĿ Apply that link until the results are no longer unique.
Return the list of unique results.
¤ Combine the two links to the left into a niladic chain.
1 Set the left (and right) argument to 1.
+D¡ Apply + to the left and right argument, updating the left
argument with the sum, and the right argument with the
previous value of the left one. Return the list of results.
Repeat this process n times.
This yields n + 1 Fibonacci numbers, starting with 1, 2.
R Range; map k to [1, ..., k].
f Filter; keep the items in the range that are Fibonacci numbers.
Ṫ Tail; yield the last one or 0 if the list is empty.
ạ Absolute difference with k.
This is the argument of the next iteration.
I Compute the increments of the arguments to the loop, yielding
the selected Fibonacci numbers (with changed sign).
A Apply absolute value to each.
P Compute their product.
```
[Answer]
# Perl, ~~69~~ 63 + 4 (`-pl61` flag) = 67 bytes
```
#!perl -pl61
while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{
```
Using:
```
> echo 42 | perl -pl61e 'while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{'
```
Ungolfed:
```
while (<>) {
# code above added by -p
# $_ has input value
# $\ = 1 by -l61
while ($_ != 0) {
my $n = 1;
my $m = 1;
while ($m <= $_) {
($n, $m) = ($m, $n + $m);
}
$_ -= $n;
$\ *= $n;
}
} {
# code below added by -p
print; # prints $_ (undef here) and $\
}
```
[Ideone](http://ideone.com/Bt2ueH).
[Answer]
## JavaScript (ES6), ~~78~~ 42 bytes
```
f=(n,a=1,b=1)=>n?b>n?a*f(n-a):f(n,b,a+b):1
```
Port of @Sp3000's answer. Original 78 byte version:
```
f=(n,a=[2,1])=>n>a[0]?f(n,[a[0]+a[1],...a]):a.map(e=>e>n?0:(r*=e,n-=e),r=1)&&r
```
[Answer]
# Haskell, 44 bytes
Yay for mutual recursion:
```
(a&b)c|c<1=1|b>c=a*f(c-a)|d<-a+b=b&d$c
f=0&1
```
* `a` is the previous Fibonacci number
* `b` is the current Fibonacci number
* `c` is the input
* `f` is the desired function
Less golfed:
```
(a & b) c | c == 0 = 1
| c < b = a * f (c-a)
| otherwise = b & (a + b) $ c
f x = (0 & 1) x
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 57 bytes
```
111\ ;n{/
:@+>:{:})?\$:@@
~{*}:0=?\}>:0${:})?$~:{$-$:1@?$
```
Expects the input number to be present on the stack at program start.
Builds up the Fibonacci sequence (`f0, f1, f2, ..., fn`) on the stack until a number is reached that is greater than the the input (`i`). Then, with a product (`p`) initialised to `1`...
```
while (i != 0)
if (fn <= i)
i = i - fn
p = p * fn
else
i = i - 0
p = p * 1
discard fn
output p
```
[Try it out online!](http://fish.tryitonline.net/#code=MTExXCA7bnsvCjpAKz46ezp9KT9cJDpAQAp-eyp9OjA9P1x9PjowJHs6fSk_JH46eyQtJDoxQD8k&input=&args=LXYgMTA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ŒṗḟÐḟÆḞ€ṪP
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pz/cMf/wBBDR9nDHvEdNax7uXBXw//9/MwMA "Jelly – Try It Online")
Times out for \$n > 60\$
## How it works
```
ŒṗḟÐḟÆḞ€ṪP - Main link. Takes n on the left
Œṗ - Integer partitions of n
ÆḞ€ - First n Fibonacci numbers
Ðḟ - Keep the partitions p which yield an empty list under:
ḟ - Remove all elements of p which are in the first n Fibonacci numbers
Ṫ - Take the last element
P - Product
```
[Answer]
# Pyth, 28 bytes
```
K1WQJ0 .WgQH+Z~JZ1=*KJ=-QJ;K
```
I think it can be golfed much further...
[Try it online!](http://pyth.herokuapp.com/?code=K1WQJ0+.WgQH%2BZ%7EJZ1%3D%2aKJ%3D-QJ%3BK&input=42&debug=0)
[Answer]
# Pyth, 24 bytes
```
W=-QeaYh.WgQeH,eZsZ1;*FY
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=W%3D-QeaYh.WgQeH%2CeZsZ1%3B*FY&input=42&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A42%0A1000%0A12345&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=W%3D-QeaYh.WgQeH%2CeZsZ1%3B*FY&input=42&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A42%0A1000%0A12345&debug=0)
### Explanation:
`Q` is assigned with the input number.
The part `h.WgQeH,eZsZ1` calculates the biggest Fibonacci number, that is smaller or equal to `Q`
```
h.WgQeH,eZsZ1
1 start with H=Z=1
.WgQeH while Q >= end(H):
,eZsZ H=Z=(end(Z), sum(Z))
h first
```
So if `Q = 10`, it generates the numbers/pairs:
```
1 -> (1,1) -> (1,2) -> (2,3) -> (3,5) -> (5,8) -> (8,13) -> 8
```
The rest of the code calculates the partition and multiplies the numbers together:
```
W=-QeaY...;*FY implicit: Y = empty list
aY... add the calculated Fibonacci number to the empty list
e take the last element of Y (yes the number we just added)
=-Q and update Q with the difference of Q and ^
W ; continue until Q == 0
*FY multiply all number in Y and print
```
There are obviously a lot of shorter solutions (with really bad run-times though), like `*FhfqQsTyeM.u,eNsNQ1`.
[Answer]
## Actually, 22 bytes
```
W;╗uR♂F;`╜≥`M░M;╜-WXkπ
```
[Try it online!](http://actually.tryitonline.net/#code=VzvilZd1UuKZgkY7YOKVnOKJpWBN4paRTTvilZwtV1hrz4A&input=MTAw)
Explanation:
```
W;╗uR♂F;`╜≥`M░M;╜-WXkπ
(implicit input)
W W while top of stack is truthy:
;╗ push a copy of n to reg0
uR♂F; push 2 copies of [Fib(a) for a in range(1, n+2)]
`╜≥`M░ filter: take values where n <= Fib(a)
M; two copies of maximum (call it m)
╜- subtract from n (this leaves n-m on top of the stack to be the new n next iteration, with a copy of m below it)
X discard the 0 left over after the loop ends
kπ product of all stack values
```
[Answer]
# Javascript (ES6) ~~134~~ ~~106~~ 92 bytes
Thanks for @cat for spotting a space.
```
n=>{for(c=[a=b=s=1,1];a+b<=n;)a+=b,c.unshift(b+=a,a);c.map(i=>i<=n&&(n-=i)&(s*=i));alert(s)}
```
Just an unoptimized version made on my phone, I golf it down, once I get home. Ideas are welcome.
[Answer]
# [RETURN](https://github.com/molarmanful/RETURN), 44 bytes
```
[a:[a;][1$[¤¤+$a;->~][]#%$␌a;\-a:]#␁[¤][×]#]
```
`[Try it here.](http://molarmanful.github.io/RETURN/)`
Astonishingly inefficient anonymous lambda that leaves result on Stack2. Usage:
```
12345[a:[a;][1$[¤¤+$a;->~][]#%$␌a;\-a:]#␁[¤][×]#]!
```
NOTE: ␌ and ␁ are placeholders for their respective unprintable chars: [Form Feed](http://unicode-table.com/en/240C/) and [Start of Heading](http://unicode-table.com/en/2401/).
# Explanation
```
[ ] lambda
a: store input to a
[ ][ ]# while loop
a; check if a is truthy
1$[¤¤+$a;->~][]#% if so, generate all fibonacci numbers less than a
$␌ push copy of TOS to stack2
a;\-a: a-=TOS
␁[¤][×]# get product of stack2
```
[Answer]
# PHP, 119 bytes
The code (wrapped on two lines for readability):
```
for($o=$c=1;$c<=$n=$argv[1];$f[++$k]=$c,$a=$b,$b=$c,$c+=$a);
for($i=$k;$i;$i--)for(;$n>=$d=$f[$i];$n-=$d,$o*=$d);echo$o;
```
The first line computes in `$f` the Fibonacci numbers smaller than `$n` (the argument provided in the command line). The second line computes the Fibonacci factors (by subtraction) and multiplies them to compute the product in `$o`.
Prepend the code with `<?php` (technically not part of the program), put it in a file (`fibonacci-factors.php`) then run it as:
```
$ php -d error_reporting=0 fibonacci-factors.php 100
# The output:
2136
```
Or run it using `php -d error_reporting=0 -r '... code here ...' 100`.
The ungolfed code and the test suite can be found [on Github](https://github.com/axiac/code-golf/blob/master/fibonacci-products.php).
[Answer]
## Q, 47 Bytes
```
m:{*/1_-':|(0<){y-x x bin y}[*+60(|+\)\1 0]\x}
```
**Test**
```
+(i;m'i:1 2 3 4 5 6 7 8 9 42 1000 12345)
```
read it as pairs (i,map(m,i)), where m is the calculating function and i the different args
writes
```
1 1
2 2
3 3
4 3
5 5
6 5
7 10
8 8
9 8
42 272
1000 12831
12345 138481852236
```
**Explanation**
`n funtion\arg` applies function(function(function(...function(args))) n times (internally uses tal recursion), and returns the sequence of results. We calculate the 60 first items of fibonnaci series as `*+60(|+\)\1 0`. In that case the function is (|+): +\ applied over a sequence calculates partial sums (ex +\1 2 3 is 1 3 6), and | reverses seq. So each 'iteration' we calculate partial sums of the two previous fibonacci number and return the partial sums reversed. `60(|+\)\1 0` generates sequences 1 0, 1 1, 2 1, 3 2, 5 3, 8 5, 13 8, 21 13, ... `*+` applied over this result flip (traspose) it and takes the first. Result is sequence 1 1 2 3 5 8 13 21 34 55 ..
`(cond)function\args` applies function(function(..function(args))) while cond true, and returns the sequence of partial results
`function[arg]` applied over a function of more than one argument creates a projection (partial application)
We can give name to the args, but the implicit names are x,y,z
`{y-x x bin y}[*+60(|+\)\1 0]` declares a lambda with args x,y with partial projection (arg x is fibonacci series, calculates as \*+60(|+)\1 0). x represent fibonacci values, and y the number to process. Binary search (bin) is used to locate the index of the greater fibonacci number <=y (`x bin y`), and substract the corresponding value of x.
To calculate product from partial resuls we reverse them and calculate difference of each pair (`-':|`), drop the first (`1_` because is 0) and multiply over (`*/`).
If we are interested in accumulated sum the code is the same, but with `+/` instead of `*/`. We can also use any other diadic operator instead of + or \*
**About execution efficiency**
I know that in this contest efficiency is not an issue. But in this problem we can range from lineal cost to exponential cost, so i'm curious about it.
I developed a second version (length 48 Bytes excluding comment) and repeated test cases battery 1000 times on both versions.
```
f:*+60(|+\)\1 0;m:{*/1_-':|(0<){x-f f bin x}\x} /new version
```
execution time is: original version 0'212 seg, new version 0'037 seg
Original version calculates fibbonaci serie once per function application; new version calculates fibonacci just one.
In both cases calculation of fibonacci series uses tail recursion
] |
[Question]
[
Your task is to convert a given **positive integer** from Arabic numeral to Roman numeral.
Things get difficult when you count to 4000.
The romans did this by adding a line above a symbol to multiply that symbol by `1 000`. However, overlines aren't exactly displayable in ASCII. Also, there are double overlines to multiply a symbol by `1 000 000`, and then triple overline to multiply a symbol by `1 000 000 000`, etc...
Therefore, I decided to use **parentheses** to replace overlines.
The symbols can be **individually** placed in parentheses. For example, both `(VI)` and `(V)(I)` are valid representations of `6 000`. `(V)M` is also a valid representation of 6000.
`(I)` is a valid way to represent `1 000`.
### Testcases
```
Input: 1
Output: I
Input: 2
Output: II
Input: 3
Output: III
Input: 4
Output: IV
Input: 15
Output: XV
Input: 40
Output: XL
Input: 60
Output: LX
Input: 67
Output: LXVII
Input: 400
Output: CD
Input: 666
Output: DCLXVI
Input: 3000
Output: MMM
Input: 3999
Output: MMMCMXCIX
Input: 4000
Output: M(V)
Input: 4999
Output: M(V)CMXCIX
Input: 6000
Output: (VI)
Input: 6000000
Output: ((VI))
Input: 6006000
Output: ((VI)VI)
Input: 6666666666
Output: (((VI)DCLXVI)DCLXVI)DCLXVI
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes win.
[Answer]
## Mathematica, 67 bytes
```
Fold["("<>#<>")"<>#2&,RomanNumeral[#~IntegerDigits~1000]/."N"->""]&
```
Avoids all trouble with `M` by converting the input to base 1000 and converting each digit separately with `RomanNumeral`. Then we fold them up by inserting `(...)` from the left.
Unfortunately, Mathematica represents zeros as `N` so we need to get rid of those.
[Answer]
## JavaScript (ES6), 136 bytes
```
f=n=>n<4e3?"M1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1".replace(/(\D+)(\d+)/g,(_,r,d)=>r.repeat(n/d,n%=d)):`(${f(n/1e3)})`+f(n%1e3)
```
For numbers under 4000, repeats each Roman "letter" as many times as possible, using the list of Roman "letters" and their decimal values. Otherwise recursively builds up the answer from the division and modulo with 1000. Fortunately `repeat` truncates so I don't have to do it myself.
[Answer]
## Common Lisp, 108
```
(defun p(n)(if(> n 0)(if(< n 4000)(format()"~@R"n)(format()"(~A)~@[~A~]"(p(floor n 1000))(p(mod n 1000))))))
```
## Ungolfed
```
(defun p(n)
(if (> n 0)
(if (< n 4000)
;; Built-in Roman formatter (between 1 and 3999)
(format () "~@R" n)
;; Divide N by 1000, as 1000*Q + R.
;; First print (p Q) in parentheses (recursively)
;; Then, if it is not NIL, the remainder R.
(format () "(~A)~@[~A~]"
(p (floor n 1000))
(p (mod n 1000))))))
```
## Tests
Two tests give different outputs than the ones from the question:
```
(loop for (in out) in '((1 "I")
(2 "II")
(3 "III")
(4 "IV")
(15 "XV")
(40 "XL")
(60 "LX")
(67 "LXVII")
(400 "CD")
(666 "DCLXVI")
(3000 "MMM")
(3999 "MMMCMXCIX")
(4000 "M(V)")
(4999 "M(V)CMXCIX")
(6000 "(VI)")
(6000000 "((VI))")
(6006000 "((VI)VI)")
(6666666666 "(((VI)DCLXVI)DCLXVI)DCLXVI"))
for computed = (p in)
unless (string= out computed)
collect (list in out computed))
=> ((4000 "M(V)" "(IV)")
(4999 "M(V)CMXCIX" "(IV)CMXCIX"))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~137~~ ~~134~~ ~~130~~ 129 bytes
Recursive function that returns the string. I'm trying to golf down the numeral encodings a bit more if possible, but I'm not sure how.
Whoops, it's practically a direct port of @Neil's ES6 answer now.
```
f=->x{(x<t=1e3)?"CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1".gsub(/(\D+)(\d+)/){s=x/v=eval($2);x%=v;$1*s}:"(#{f[x/t]})#{f[x%t]}"}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY7BasJAEIbv-xQhRtitxMy6m7RbG3tILgFLbxLQIrUmKtgqzSbdEnLwOXrJoX0o36a7mmH45-Nn_mF-fj_L1Xfb_pUyd-_Opzx0J6rG6kGGNGPk0Y6eBEDsA0Qx10IB0kjA1Id0yiGlkKRi5icznlB7uCnKFfbwIh4QvFgPiEfqIlReFWbV6x47IzJW_bAaO_SmaO5t3KvzufLkS0Mu1NdkN90j7Gu722fWJpMFso6lLCy7VzvL4dv28H5sLHdimYw25GG50zmUfayv0fb8TNEIMcQR9REHFOi-1aBHECAGGpgQwjiAuKHAkJFumjbLXV3v_gM)
[Answer]
# R, 134
```
m=1000;x=scan();while(x[1]>=m)x=c(floor(x[1]/m),x[1]%%m,x[-1]);cat(rep("(",length(x)),sep="");cat(as.character(as.roman(x)),sep=")")
```
It's pretty much not the best option, but I think the idea should go pretty similar to this.
[Answer]
# Ruby, ~~185 161~~ 144 bytes
```
r=->i{i>(t=1e3)? "(#{r[i/t]})"+r[i%t]:(s=?I*i;"IVXXLCCDM".scan(/(.)(.)(.)/){|x,y,z|{x*5=>y,x*4=>x+y,y*2=>z,y+x+y=>x+z}.map{|x,y|s.gsub!x,y}};s)}
```
Over a year after the original post, I think I learned something about golfing.
Thank you Value Ink for your valuable comments.
[Answer]
## TCL 134 bytes
```
proc f r {
set map {M 1000+ CM 900+ D 500+ CD 400+ C 100+ XC 90+ L 50+ XL 40+ X 10+ IX 9+ V 5+ IV 4+ I 1+}
expr [string map $map $r]0}
```
Try it here: <https://rextester.com/BJC92885>
[Answer]
## Python, 188 ~~194~~
*-6 bytes from getting rid of some whitespace*
This challenge brought me back to when I was first learning to program...
```
def f(x,s=zip("M CM D CD C XC L XL X IX V IV I".split(),[1e3,900,500,400,100,90,50,40,10,9,5,4,1])):
r=""if x<4e3else"("+f(x/1e3)+")";x%=1e3
for a,b in s:
while x>=b:r+=a;x-=b
return r
```
It might not be the shortest solution, but I had fun golfing this problem.
[Try it out!](https://repl.it/CHJj/2)
] |
[Question]
[
# The Challenge
Write a program that can take an input of a single-line string containing any ASCII printable characters, and output the same string encoded in [Base85](https://en.wikipedia.org/wiki/Ascii85) (using a big-endian convention). You can assume that the input will always be ≤ 100 characters.
---
# A Guide to Base85
* Four octets are encoded into (usually) five Base85 characters.
* Base85 characters range from `!` to `u` (ASCII 33 - 117) and `z` (ASCII 122).
* To encode, you continuously perform division by 85 on the four octets (a 32-bit number), and add 33 to the remainder (after each division) to get the ASCII character for the encoded value. For example, the first application of this process produces the rightmost character in the encoded block.
* If a set of four octets contains only null bytes, they are encoded as a `z` instead of `!!!!!`.
* If the last block is shorter than four octets, it's padded with null bytes. After encoding, the same number of characters that were added as padding, are removed from the end of the output.
* The encoded value should be preceded by `<~` and followed by `~>`.
* The encoded value should contain no whitespace (for this challenge).
---
# Examples
```
In: easy
Out: <~ARTY*~>
In: test
Out: <~FCfN8~>
In: code golf
Out: <~@rGmh+D5V/Ac~>
In: Programming Puzzles
Out: <~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>
```
The following snippet will encode a given input to Base85.
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>String.prototype.toAscii85=function(){if(""==this)return"<~~>";for(var r=[],t=0;t<this.length;t+=4){for(var i=(this.substr(t,4)+"\x00\x00\x00").substr(0,4),o=0,n=0;4>n;n++)o=256*o+i.charCodeAt(n);var s=[];for(n=0;5>n;n++){var e=o%85;o=(o-e)/85,s.unshift(String.fromCharCode(e+33))}r=r.concat(s)}var a=4-this.length%4;return 4!=a&&r.splice(-a,a),"<~"+r.join("").replace(/!!!!!/g,"z")+"~>"};</script><style>#in,#out{margin:20px;width:400px;resize:none}</style><input id="in" type="text" value="Base85"><button onclick="$('#out').text($('#in').val().toAscii85())">Submit</button><br><textarea id="out" rows=5 disabled></textarea>
```
[Answer]
# CJam, ~~43~~ ~~39~~ 35 bytes
```
"<~"q4/{:N4Ue]256b85b'!f+}/N,)<"~>"
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22%3C~%22q4%2F%7B%3AN4Ue%5D256b85b'!f%2B%7D%2FN%2C)%3C%22~%3E%22&input=Programming%20Puzzles).
### How it works
```
"<~" e# Push that string.
q4/ e# Read all input from STDIN and split it into chunks of length 4.
{ e# For each chunk:
:N e# Save it in N.
4Ue] e# Right-pad it with 0's to a length of 4.
256b85b e# Convert from base 256 to base 85.
'!f+ e# Add '!' to each base-85 digit.
}/ e#
N,) e# Push the length of the last unpadded chunk, plus 1.
< e# Keep that many chars of the last encoded chunk.
"~>" e# Push that string.
```
If the input was empty, `N,)` will apply to the string `"<~"`. Since `N` initially holds a single character, the output will be correct.
We don't have to deal with **z** or pad the encoded chunks to length 5, since the input will contain only printable ASCII characters.
[Answer]
# Python 3, 71 bytes
```
from base64 import*
print(a85encode(input().encode(),adobe=1).decode())
```
I've never golfed in Python, so this is probably sub-optimal.
*Thanks to @ZachGates for golfing off 3 bytes!*
[Answer]
# Pure bash, ~738
Encoder first (something golfed):
```
#!/bin/bash
# Ascii 85 encoder bash script
LANG=C
printf -v n \\%o {32..126};printf -v n "$n";printf -v m %-20sE abtnvfr;p=\<~;l()
{ q=$(($1<<24|$2<<16|$3<<8|$4));q="${n:1+(q/64#378iN)%85:1}${n:1+(q/614125)%85:1
}${n:1+(q/7225)%85:1}${n:1+(q/85)%85:1}${n:1+q%85:1}";};k() { ((${#p}>74))&&ech\
o "${p:0:75}" && p=${p:75};};while IFS= read -rd '' -n 1 q;do [ "$q" ]&&{ print\
f -v q "%q" "$q";case ${#q} in 1|2)q=${n%$q*};o+=($((${#q}+32)));;7)q=${q#*\'\\}
o+=($((8#${q%\'})));;5)q=${q#*\'\\};q=${m%${q%\'}*};o+=($((${#q}+07)));;esac;}||
o+=(0);((${#o[@]}>3))&&{ [ "${o[*]}" = "0 0 0 0" ]&& q=z|| l ${o[@]};p+="${q}";k
o=(); };done;[ "$o" ]&&{ f=0;for((;${#o[@]}<4;)){ o+=(0);((f++));};((f==0))&&[ \
"${o[*]}" = "0 0 0 0" ]&&q=z||l ${o[@]};p+="${q:0:5-f}";};p+="~>";k;[ "$p" ]&&e\
cho "$p"
```
Tests:
```
for word in easy test code\ golf Programming\ Puzzles ;do
printf " %-24s %s\n" "$word:" $(./enc85.sh < <(printf "$word"))
done
easy: <~ARTY*~>
test: <~FCfN8~>
code golf: <~@rGmh+D5V/Ac~>
Programming Puzzles: <~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>
```
and decoder now:
```
#!/bin/bash
# Ascii 85 decoder bash script
LANG=C
printf -v n "\%o" {33..117};printf -v n "$n";o=1 k=1;j(){ read -r q||o=;[ "$q" \
]&&[ -z "${q//*<~*}" ]&&((k))&&k= q="${q#*<~}";m+="$q";m="${m%~>*}";};l(){ r=;f\
or((i=0;i<${#1};i++)){ s="${1:i:1}";case "$s" in "*"|\\|\?)s=\\${s};;esac;s="${\
n%${s}*}";((r+=${#s}*(85**(4-i))));};printf -v p "\%03o" $((r>>24)) $((r>>16&255
)) $((r>>8&255)) $((r&255));};for((;(o+${#m})>0;)){ [ "$m" ] || j;while [ "${m:0
:1}" = "z" ];do m=${m:1};printf "\0\0\0\0";done;if [ ${#m} -ge 5 ];then q="${m:0
:5}";m=${m:5};l "$q";printf "$p";elif ((o));then j;elif [ "${m##z*}" ];then pri\
ntf -v t %$((5-${#m}))s;l "$m${t// /u}";printf "${p:0:16-4*${#t}}";m=;fi;}
```
Copy this in `enc85.sh` and `dec85.sh`, `chmod +x {enc,dec}85.sh`, then:
```
for string in 'ARTY*' 'FCfN8' '@rGmh+D5V/Ac' ':i^JeEa`g%Bl7Q+:j%)1Ch7Y' ;do
printf " %-42s %s\n" "<~$string~>:" "$(./dec85.sh <<<"<~$string~>")"
done
<~ARTY*~>: easy
<~FCfN8~>: test
<~@rGmh+D5V/Ac~>: code golf
<~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>: Programming Puzzles
./enc85.sh <<<'Hello world!'
<~87cURD]j7BEbo80$3~>
./dec85.sh <<<'<~87cURD]j7BEbo80$3~>'
Hello world!
```
But you could do some stronger test:
```
ls -ltr --color $HOME/* | gzip | ./enc85.sh | ./dec85.sh | gunzip
```
## Reduced to 724 chars:
```
printf -v n \\%o {32..126};printf -v n "$n";printf -v m %-20sE abtnvfr;p=\<~
l(){ q=$(($1<<24|$2<<16|$3<<8|$4))
q="${n:1+(q/64#378iN)%85:1}${n:1+(q/614125)%85:1}${n:1+(q/7225)%85:1}${n:1+(q/85)%85:1}${n:1+q%85:1}"
};k() { ((${#p}>74))&&echo "${p:0:75}" && p=${p:75};};while IFS= read -rd '' -n 1 q;do [ "$q" ]&&{
printf -v q "%q" "$q";case ${#q} in 1|2)q=${n%$q*};o+=($((${#q}+32)));;7)q=${q#*\'\\}
o+=($((8#${q%\'})));;5)q=${q#*\'\\};q=${m%${q%\'}*};o+=($((${#q}+07)));;esac;}||o+=(0)
((${#o[@]}>3))&&{ [ "${o[*]}" = "0 0 0 0" ]&&q=z||l ${o[@]};p+="${q}";k
o=();};done;[ "$o" ]&&{ f=0;for((;${#o[@]}<4;)){ o+=(0);((f++));}
((f==0))&&[ "${o[*]}" = "0 0 0 0" ]&&q=z||l ${o[@]};p+="${q:0:5-f}";};p+="~>";k;[ "$p" ]&&echo "$p"
```
[Answer]
## Python 2, ~~193~~ 162 bytes
```
from struct import*
i=raw_input()
k=4-len(i)%4&3
i+='\0'*k
o=''
while i:
b,=unpack('>I',i[-4:]);i=i[:-4]
while b:o+=chr(b%85+33);b/=85
print'<~%s~>'%o[k:][::-1]
```
This is my first code golf, so I'm sure there's something wrong with my approach. I also wanted to actually implement base85 rather than just call the library function. :)
[Answer]
# Octave, ~~133~~ 131 bytes
Thanks to @ojdo for suggesting I take input from argv rather than stdin, saving me 2 bytes.
```
function g(s) p=mod(-numel(s),4);s(end+1:end+p)=0;disp(['<~' dec2base(swapbytes(typecast(s,'uint32')),'!':'u')'(:)'(1:end-p) '~>'])
```
### Ungolfed:
```
function g(s) %// function header
p=mod(-numel(s),4); %// number of missing chars until next multiple of 4
s(end+1:end+p)=0; %// append p null characters to s
t=typecast(s,'uint32'); %// cast each 4 char block to uint32
u=swapbytes(t); %// change endian-ness of uint32's
v=dec2base(u,'!':'u'); %// convert to base85
w=v'(:)'(1:end-p); %// flatten and truncate resulting string
disp(['<~' w '~>']); %// format and display final result
```
I've posted the code on [ideone](http://ideone.com/dC7lqx). The standalone function doesn't require and `end` statement, but because ideone has the function and the calling script in the same file it requires a separator.
I still haven't been able to figure out how to get `stdin` to work on ideone. If anyone knows, I'm still interested, so please drop me a comment.
Sample output from [ideone](http://ideone.com/dC7lqx):
```
easy
<~ARTY*~>
test
<~FCfN8~>
code golf
<~@rGmh+D5V/Ac~>
Programming Puzzles
<~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>
```
[Answer]
# Matlab, 175 bytes
```
s=input('','s');m=3-mod(numel(s)-1,4);s=reshape([s zeros(1,m)]',4,[])';t=char(mod(floor(bsxfun(@rdivide,s*256.^[3:-1:0]',85.^[4:-1:0])),85)+33)';t=t(:)';['<~' t(1:end-m) '~>']
```
Example:
```
>> s=input('','s');m=3-mod(numel(s)-1,4);s=reshape([s zeros(1,m)]',4,[])';t=char(mod(floor(bsxfun(@rdivide,s*256.^[3:-1:0]',85.^[4:-1:0])),85)+33)';t=t(:)';['<~' t(1:end-m) '~>']
code golf
ans =
<~@rGmh+D5V/Ac~>
```
[Answer]
# PHP, 181 Bytes
```
foreach(str_split(bin2hex($argn),8)as$v){for($t="",$d=hexdec(str_pad($v,8,0));$d;$d=$d/85^0)$t=chr($d%85+33).$t;$r.=str_replace("!!!!!",z,substr($t,0,1+strlen($v)/2));}echo"<~$r~>";
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/6c6c334b71a30a8cfdce0390a2181c09b0e98c3b)
Expanded
```
foreach(str_split(bin2hex($argn),8)as$v){
for($t="",$d=hexdec(str_pad($v,8,0));$d;$d=$d/85^0)
$t=chr($d%85+33).$t;
$r.=str_replace("!!!!!",z,substr($t,0,1+strlen($v)/2));
}
echo"<~$r~>";
```
[Answer]
# [PHP](https://php.net/), 171 bytes
```
foreach(unpack('N*',str_pad($argn,($m=4-($l=strlen($argn))%4&3)+$l,"\0"))as$c){for($a=$c?'':z;$c|0;$c/=85)$a=chr($c%85+33).$a;$b.=$a;}echo'<~',$m?substr($b,0,-$m):$b,'~>';
```
[Try it online!](https://tio.run/##JY1BasMwEEX3PoUIk0pq7NjgBEIcx7suSw5QKLIysUNsSUgypWmbo9cd6ObP/PdgxvVuPjSO8mI9Kt2LyTilb4K/PvM0RP/u1FmA8p1JBYz1JhMw1MQHNP9YyuXmqZQrGNLFW7GQUgXQ8ovOka9BN5zv7xXo74Iir3dbSVj3ZPVyt12VpVyDqqBd1zR@UPeWHx48hbEJU0uPBLRpkWYwyj1t/HHk1TyZgJGErBjLc@aRKmsxfiAa5skmzZElM6rwmUQMMdH2jKyzwyU5edt5NY5X07HTdL8PGH6ti1drwpy9/AE "PHP – Try It Online")
[Answer]
## JavaScript, 314 Bytes
```
a=>(g="<~",h="~>",r=[],t=0,[...a].map((d,h)=>{if(0==h%4){for(n=0,o=0,f=0,s=[],e=0;4>n;)o=256*o+(a.substr(t,4)+"\0\0\0").substr(0,4).charCodeAt(n),n++;for(;5>f;)e=o%85,o=(o-e)/85,s.unshift(String.fromCharCode(e+33)),f++;r=[...r,...s],t+=4}}),d=4-a.length%4,4!=d&&r.splice(-d,d),g+r.join("").replace(/!!!!!/g,"z")+h)
```
This is my first code golf :)
### Try It‽
```
<h2>Type Below</h2><input oninput='document.querySelector("p").innerText = (a=>(g="<~",h="~>",r=[],t=0,[...a].map((d,h)=>{if(0==h%4){for(n=0,o=0,f=0,s=[],e=0;4>n;)o=256*o+(a.substr(t,4)+"\0\0\0").substr(0,4).charCodeAt(n),n++;for(;5>f;)e=o%85,o=(o-e)/85,s.unshift(String.fromCharCode(e+33)),f++;r=[...r,...s],t+=4}}),d=4-a.length%4,4!=d&&r.splice(-d,d),g+r.join("").replace(/!!!!!/g,"z")+h))(this.value)'><p>Stuff will go here...</p>
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~169~~ ~~165~~ ~~162~~ 160 bytes
```
$ofs=''
"<~$($args-replace'.{1,4}',{$v=$_
&{0..3|%{$n=256*$n+"$v"[$_]}
0..4|%{$r=[char]($n%85+33)+$r;$n-=$n%85;$n/=85}
$r[0..$v.Length]-replace'!!!!!','z'}})~>"
```
[Try it online!](https://tio.run/##PZBbT8JAEIXf91eszZSltIAIVVRqQLwkxguKMTEEtZahhZQWdwsqpf3ruBRwnna/c86cZKbhN3Lhoe@vYEgtGq8gHAqLMaI0UsiDzV1R5Dj1bQdZKa4YtYQZMcwteCe5eL9Uqi7VGALrwDwsQKArMFd68N5PiJRqa4lbPcezeT8PgVo39WpV04GfQlC0MiBfZatuJgR4T0ZgXrrFwI28/n/p3nqYwRYsSbT0TFklhDTzxMizOzugzKCskR6Pv8K39Ixpa4y2@N3g1tPza2GHIxTRBl@1h/f1HXbCAVI39IeyopE2@fXE0y/Ml3LL2Tk6PHS5PZmMApd2ZouFjyLznozebvDS/nDVc//oUT8Zq1ql7R29ZjmNLqlKY0LlgIi4DBsU8GeKToQDeWh5v0zjKGZ@JEFO3n/rzJRep9ueiSicPHyOZajfjGl35jgohDQr25xCiw5@ye9us3JKz22BdXNdsd2dkGT1Bw "PowerShell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~128~~ 114 bytes
```
$_="<~#{$_.gsub(/.{1,4}/){$&.ljust(4,?\0).unpack1("L>").digits(85).reverse.map{(_1+33).chr}.join[..$&.size-5]}}~>"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5LCsIwFAD3PYXEognap8UKLvxcwIV7ldJPGqNtU_IRbKgXceNC8Uy9jULdDzPzeEkT3z575FU5Oj7fRmfeopVuuELLe9-6ITBlYjwB64-DZkKsO4D8bJTGwXhzmBIwZRUlFx-j7RoRSDnjWuHFnICkVyoVhSKqLA790WxGIDnJBs6Cl3uAn0jxmnrzY9Pc16gr_wee7ZBG6uZoqrSTiJT2mMgzZycFk1FR8JL1dqauc6o6_gs)
] |
[Question]
[
# The Question
A *[Sophie Germain prime](http://en.wikipedia.org/wiki/Sophie_Germain_prime)* is a prime \$p\$ such that \$2p+1\$ is prime as well. For example, 11 is a Sophie Germain prime because 23 is prime as well. Write the shortest program to calculate Sophie Germain primes in ascending order
# Rules
* The Sophie Germain primes must be generated by **your** program, not from an external source.
* Your program **must** calculate all Sophie Germain primes under \$2^{32}-1\$
* You must print each distinct Sophie Germain prime your program finds.
* The person with the lowest score wins
# Scoring
* 2 points per byte of your code
* -10 if you can show a prime generated by your program greater than \$2^{32}-1\$
[Answer]
# Pyth, 19 bytes \* 2 - 10 = 28
Note that the online compiler/executor doesn't show output because it's an infinite loop.
```
K1#~K1I&!tPK!tPhyKK
```
Explained:
```
K1 K=1
# While true:
~K1 K+=1
I If
& logical AND
!tPK K is prime
!tPhyK 2*K+1 is prime (y is double, h is +1)
K Print K
```
[Answer]
# CJam
For 17 chars we get full enumeration up to 2^32:
```
G8#,{_mp*2*)mp},`
```
For 4 chars more, we get a range just large enough to include an SG prime greater than 2^32:
```
G8#K_*+,{_mp*2*)mp},`
```
since 4294967681 = 2^32 + 385 < 2^32 + 400.
Of course, we could equally extend the range for free as
```
C9#,{_mp*2*)mp},`
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~16~~ ~~8~~ 7 \* 2 - 10 = 4
*~~-8~~ 12 thanks to @[Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)*
```
fȯṗ→Dİp
```
[Try it online!](https://tio.run/##ARoA5f9odXNr///ihpE1MGbIr@G5l@KGkkTEsHD//w "Husk – Try It Online")
A list of all natural numbers that are Sophie Germain primes. I hope it's valid, because it doesn't terminate when you try to show the entire list, but Husk lazily evaluates it, so you can just take the required amount.
```
fȯṗ→Dİp
f Filter
İp the prime numbers
D that, when doubled
→ and incremented by 1
ȯṗ are prime
```
Another way to do it, also 7 bytes:
```
fṗm÷2İp
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes, score = 4
*Thanks to @ovs for -1 byte!*
```
∞ʒx>‚pP
```
(Technically) Prints an infinite list of Sophie Germain primes! (Hence, score is subtracted by 10)
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8U5Mq7B41zCoI@P8fAA)
## How?
```
∞ʒ # For each natural number 'p'...
x>‚ # Pair p with 2p + 1 (The ‚ is not a comma, it is a weird sort of quotation)
p # Are they both prime?
P # Then multiply the boolean values! (And implicitly print if the product is 1)
```
[Answer]
# Pyth - 2 \* 16 bytes - 10 = 22
Uses the customary method of prime checking in Pyth with the `!tP` and applies it both to the number and its safe-prime, with a little trick to check both at once. Goes up to `10^10`, so I'm going for the bonus.
```
f!+tPTtPhyTr2^TT
```
Explanation coming soon.
```
f r2^TT Filter from 2 till 10^10
! Logical not to detect empty lists
+ List concatenation
tP All but the firs element of the prime factorization
T The filter element
tP All but the firs element of the prime factorization
hyT 2n+1
```
[Try under 1000 online](http://pyth.herokuapp.com/?code=f!%2BtPTtPhyTr2%5ET3).
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), `10 - ⍨ 2 × 27` = 44
```
f←{⎕←⍵⍴⍨⌽∧\1⍭⍵,1+2×⍵⋄∇⍵+1}1+⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qW9CjtgmGRhbmXEBOQACQY2zyPw1IVQP5QOpR79ZHvVse9a541LP3UcfyGMNHvWuBYjqG2kaHp4Mku1sedbQDGdqGtYbaj7oW/f@fpmAIAA "APL (Dyalog Extended) – Try It Online")
Made with some golfing help and general APL help from dzaima.
## Explanation
```
{⎕←⍵⍴⍨⌽∧\1⍭⍵,1+2×⍵⋄∇⍵+1}1+⊢
1+⊢ add 1 to the input (initially, 1)
1+2×⍵ double and increment it
1⍭⍵, prepend the primality check(1 or 0)
∧\ and scan with LCM
⍵⍴⍨⌽ reverse & reshape using self
(if test is falsy, then this results in ⍬)
⎕← and display it with newline
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes, score 2
```
Þp:d›↔
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnnA6ZOKAuuKGlCIsIiIsIiJd)
```
↔ # Union of...
Þp # Primes
:d› # Primes * 2 + 1
```
-10 score because it prints an infinite list.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes, score -2
```
Ƥ←½Q
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FiuOLXnUNuHQ3sAlxUnJxVBBmCQA)
```
Ƥ←½Q
Ƥ Non-deterministically choose a prime number
← Decrement
½ Divide by 2
Q Check if result is a prime
```
By default, Nekomata prints all possible results.
[Answer]
# CJam, 34 (2 \* 22 - 10)
```
C9#{ImpI2*)mp&{Ip}&}fI
```
Prints all Sophie Germain primes under `12 ** 9`, which includes `4294967681 > 2 ** 32`.
I estimate that this will take roughly 8 hours on my machine. I'll run it tonight.
[Answer]
# Haskell, 2\*54-10 = 98 ~~132~~
```
i a=all((>0).rem a)[2..a-1]
p=[n|n<-[2..],i n,i$2*n+1]
```
`i` is a prime check. `p` takes all numbers `n` where both `n` and `2*x+1` are prime. `p` is an infinite list.
Edit: better way for checking if `2*n+1` is prime.
[Answer]
# Julia, 2\*49 - 10 = 88
```
p=primes(2^33)
print(p[map(n->isprime(2n+1),p)])
```
Prints them in list format, `[2,3,5,11,...]`. If that format, using the `primes` function, or waiting until all the computation is done to print isn't acceptable, this prints them one per line as it runs.
```
isprime=f
for i=1:2^33;f(i)&&f(2i+1)&&println(i)end
```
It's a little longer, 52 chars. Both compute all the Sophie Germain primes up to `2^33`, so they should get the 10 point discount.
[Answer]
# Python 3, ~~124~~ 123 bytes
```
i=3
q=[2]
while 1:
p=1
for x in range(2,round(i**.5)+1):p=min(p,i%x)
if p:
q+=[i];s=(i-1)/2
if s in q:print(s)
i+=2
```
How does it work?
```
i=3 # Start at 3
q=[2] # Create list with first prime (2), to be list of primes.
while 1: # Loop forever
p=1 # Set p to 1 (true)
for x in range(2,round(i**0.5)+1): # Loop from 2 to the number's square root. x is the loop value
p=min(p,i%x) # Set p to the min of itself and the modulo of
# the number being tested and loop value (x).
# If p is 0 at the end, a modulo was 0, so it isn't prime.
if p: # Check if p is 0
q+=[i] # Add the current number (we know is prime) to list of primes (q)
s=(i-1)/2 # Generate s, the number that you would double and add 1 to make a prime.
if s in q:print(s) # If (i-1)/2 is a prime (in the list), then that prime satifies
# the condition 2p+1 is prime because i is 2p+1, and i is prime
i+=2 # Increment by 2 (no even numbers are prime, except 2)
```
Try it online [here](http://repl.it/n4F).
---
My computer says it is has generated 0.023283 % of all the Sophie Germain primes below 2^32.
When it's finished, I'll post it on pastebin if there are enough lines. You can use it to check you've got them all.
[Answer]
# Perl, 2\*57-10 = 104
```
use ntheory":all";forprimes{say if is_prime(2*$_+1)}2**33
2
3
5
11
...
8589934091
8589934271
```
42 seconds to 2^32, 1m26s to 2^33. Will run 50% faster if `2*$_+1` is written as `1+$_<<1` but that's one more byte.
The module also installs `primes.pl` which has lots of filters including one for Sophie-Germain primes. So: `primes.pl --so 2**33` (20 bytes)
[Answer]
# Ruby, 61\*2 - 10 = 112
```
require'prime';Prime.each(1.0/0)do|n|p Prime.prime?(n*2+1)end
```
It would take forever to print out all values up to 2\*\*32
# Edit
Shaved off a few bytes substituting Float::INFINITY for 1.0/0
[Answer]
# PARI/GP, 46 \* 2 - 10 = 82
```
forprime(p=2,2^33,if(isprime(2*p+1),print(p)))
```
[Answer]
# [Python 3](https://docs.python.org/3/), 2 \* 64 bytes - 10 = 118
```
n=1
while 1:n+=1;all((n-~n)*n%k for k in range(2,n))>0!=print(n)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8/WkKs8IzMnVcHQKk/b1tA6MSdHQyNPty5PUytPNVshLb9IIVshM0@hKDEvPVXDSCdPU9POQNG2oCgzr0QjT/P/fwA "Python 3 – Try It Online")
It turns out a normal prime test is shorter.
---
# [Python 3](https://docs.python.org/3/), 2 \* 67 bytes - 10 = 124
```
P=k=1
d=[]
while 1:P*=k*k;k+=1;P%k*k//2in d!=print(k//2);d+=P%k*[k]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8A229aQK8U2OparPCMzJ1XB0CpAyzZbK9s6W9vW0DpAFcjU1zfKzFNIUbQtKMrMK9EA8TWtU7RtQZLR2bH//wMA "Python 3 – Try It Online")
This uses Wilson's theorem to generate a list of primes. When `k` is prime and `k//2` is prime as well (`in d`), this prints `k//2`.
This can be done a little more memory efficient by not collecting a list of primes but rather doing two prime tests at once at the cost of 4 bytes:
```
P=k=1
m=3;R=4
while 1:P*=k*k;k+=1;R*=m*m*-~m*-~m;m+=2;P%k*R%m>0!=print(k)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8A229aQK9fW2DrI1oSrPCMzJ1XB0CpAyzZbK9s6W9vW0DpIyzZXK1dLtw6MrXO1bY2sA1SztYJUc@0MFG0LijLzSjSyNf//BwA "Python 3 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü♀σJàx╧☺▼∟╓X≥╣
```
[Run and debug it](https://staxlang.xyz/#p=810ce54a8578cf011f1cd658f2b9&i=&a=1)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 85 bytes, score 170
```
2
for($i=2){if((&($p={param($a)+!(2..($a-1)|?{!($a%$_)})})(++$i))*(&$p(2*$i+1))){$i}}
```
[Try it online!](https://tio.run/##DcZBCsMgEAXQvbcI/MpMJIG4lx6lSFEykKDYRRdTz27lbV4t39Q@Z7qu7V1aGshBhze5NIIEzyqZyBJq0BpbvAmR3UJ@3@e2g39PXeYeeHGfyDkI80oWlfwKcQczK6T30Y2xyOMP "PowerShell Core – Try It Online")
A bit faster, but longer for [93 bytes](https://tio.run/##HcpBCsMgEEbhfW4R@CszGbJItsXDSFEqSVAM0oXM2Y10@76X08@X@@vPc/2k4juCbT2kQoh25xYDkSFk27Ir7iI4/mO121sEdR2h4RA7D3qhssqMQ5kGRuaFDDLtC6JszOOMql2nySD0Bw "PowerShell Core – Try It Online")
```
for($i=2){if((&($p={param($a)for($u=1;++$u-$a){$k+=!($a%$u)}+!$k})(++$i))*(&$p(2*$i+1))){$i}}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes => score 10
```
ȷ10ÆRḤ‘ẒƊƇ
```
Generates primes up to 10^10 > 2^32.
[Try it online!](https://tio.run/##ARsA5P9qZWxsef//yLfDhlLhuKTigJjhupLGisaH//8 "Jelly – Try It Online") (TIO link is to a shorter version that generates only up to 1000, so it doesn't time out)
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 11 bytes, score 12
```
9ᴇřᵽĐ2*⁺ṗ*ž
```
[Try it online!](https://tio.run/##K6gs@f/f8uGW9qMzH27de2SCkdajxl0Pd07XOrrv//9oQx1jIDTUMYkFAA "Pyt – Try It Online")
```
9ᴇřᵽ generates the first 1,000,000,000 primes (there are 203,280,221 primes less than 2^32)
Đ2*⁺ calculates 2*p+1 for each prime
ṗ is each 2*p+1 prime
* multiply the two lists one element at a time
ž remove all zeroes from list; implicit print
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 20 \log\_{256}(96) \approx \$ 16.46 bytes, score \$ \approx \$ 22.92
```
[xNx2*1+N&?xZK((x1+X
```
#### Explanation
```
[ # while True:
xN # x is prime?
x2*1+N # x*2+1 is prime?
&? # if both are true:
xZK # print x
(( # endif
x1+X # x=x+1
```
#### Screenshot
[](https://i.stack.imgur.com/5OlVl.png)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax), score 10
*2\*10=20 score, -10 because it prints infinitely.*
```
▓i☼=ö│╪¥♠p
```
[Run and debug it](https://staxlang.xyz/#p=b2690f3d94b3d89d0670&i=)
This is a PackedStax program, which unpacks to the following:
```
VIfc|psH^|pI
```
[Run and debug it](https://staxlang.xyz/#c=VIfc%7CpsH%5E%7CpI&i=)
# Explanation
```
f # filter from 1 to...
VI # infinity by..
|p # is prime
I # and
c sH^ # 2*p+1
|p # is prime
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 34 bytes, score 58
Prints infinitely and should be able to exceed `2**32` due to native support for large numbers, although I haven't bothered to actually wait around to check.
```
Prime.each{p _1 if(2*_1+1).prime?}
```
[Attempt This Online! (with a timeout)](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7E2dotTC0syiVAX1EqBAfmmJOlcIhGFlBRXRMNAzMDDVVEjJX1pakqZrcVMpAKRZLzUxOaO6QCHeUCEzTcNIK95Q21BTD2yufS1E5eLUvBQIa8ECCA0A)
] |
[Question]
[
# Input
Two positive integers `a > b`
# Output
The smallest integer `c >= a` so that `c` can be factored into two parts with one part an integer power of two (that is at least two) and the other part no larger than `b`.
# Examples
If `b = 100` and `a = 101` , then the output should be 102 as 102 is 2 times 51.
For the same `b`, if `a = 201` then the output should be 204 as that equals 4 times 51.
For the same `b`, if `a = 256` then the output should be 256.
[Answer]
# JavaScript (ES6), 27 bytes
Expects `(b)(a)` as either numbers or BigInts (ES11).
```
b=>g=a=>a/(a&-a)>b?g(-~a):a
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/J1i7dNtHWLlFfI1FNN1HTLsk@XUO3LlHTKvF/cn5ecX5Oql5OfrpGmoahgYEmkDDU1OTCImGEU8LUTFPzPwA "JavaScript (Node.js) – Try It Online")
### How?
We recursively increment `a` while `a / (a & -a)` is greater than `b`.
The bitwise trick `a & -a` isolates the least significant `1` in the binary representation of `a`, i.e. the largest divisor or `a` which is a power of 2.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 8 bytes
```
L/.²îoƶß
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fR1/v0KbD6/KPbTs8//9/QwMDLiMDQwA "05AB1E (legacy) – Try It Online")
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
L/.²îïoƶß
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fR1/v0KbD6w6vzz@27fD8//8NDQy4jAwMAQ "05AB1E – Try It Online")
`ï` is now needed due to a bug, since `o` takes forever without it.
## Explanation
Goes over all possible values \$d\$ in \$c = d 2^s\$, by looking at the first power of \$2\$ which is \$\geq \lceil \frac a d \rceil\$.
```
L range [1, 2, 3, ..., b]
/ [a/1, a/2, a/3, ..., a/b]
.² [log2(a/1), log2(a/2), ..., log2(a/b)]
î [ceil(log2(a/1)), ceil(log2(a/2)), ..., ceil(log2(a/b))]
o [2^ceil(log2(a/1)), 2^ceil(log2(a/2)), ..., 2^ceil(log2(a/b))]
ƶ [1*2^ceil(log2(a/1)), 2*2^ceil(log2(a/2)), ..., b*2^ceil(log2(a/b))]
ß min([1*2^ceil(log2(a/1)), 2*2^ceil(log2(a/2)), ..., b*2^ceil(log2(a/b))])
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `M`, 9 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
R/Æḷ€ṃOż×
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPXJhbmdlJTIwJTJGJTIwbG9nMiUyMCVFMiU4MiVBQyUyMGNlaWwlMjB0d29fcG93ZXIlMjBsZW5ndGhfcmFuZ2Vfbm9fcG9wJTIwdGltZXMmZm9vdGVyPSZpbnB1dD0xMDAlMEEyMDEmZmxhZ3M9dk0=)
Port of Command Master's 05AB1E answer.
#### Explanation
```
R/Æḷ€ṃOż× # Implicit input
R/ # Divide b by [1..a]
Æḷ # Log base 2 of each
€ṃ # Ceiling of each
O # Two power of each
ż× # Multiply by index
# Take the minimum
# Implicit output
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~38~~ 37 bytes
Saved 1 byte thanks to the comment of @xnor
[Try it online!](https://tio.run/##dYwxC8IwFIT3/Io3yXtYMRF0KLTg6OAkTuLwWpOSEqOkQZDS3x5TZz24g7sPbmjZcXo0vW4jHNl6GIV4sQNT4sHHIpuqOidUkLApODdrEHmNK14wUd2QmfelIu0GDZwAbtrAPX8hh24oYR8Cvy@nGKzvrlTC2dv5bhSQ9cxrdB4NKikLUFIR/QKbv2C7@4JJTOkD)
```
(b,a)=>if((a/(-a&a))>b)f(b,a+1)else a
```
[Answer]
# JavaScript, 46 bytes
```
o=a=>a&1n?a:o(a/2n)
f=(a,b)=>o(a)<b?a:f(++a,b)
```
takes big integers as Input
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN_XybRNt7RLVDPPsE63yNRL1jfI0udJsNRJ1kjRt7YACmjZJQJk0DW1tkBBUl29yfl5xfk6qXk5-ukaahqGBYZ6OoYFBnqYmF6qMEW4ZUzOYDMRQmJMA)
## Explanation
`o` gets the odd part of a number (product of all odd prime factors)
`f` increments `a` until its odd part is less than `b`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
Nθ≔±X²L↨⊕÷θ±N²ζI×ζ÷θζ
```
[Try it online!](https://tio.run/##VYzNCsMgEITveQqPG7BgvObUn0ughBz6AtYsRoim0U0Kvry1tId2LjMMM5@eVNCLmnPu/GOjfnN3DLDWbXWM0RoPPRpFCMPyLL3k7Ire0AQnFRE6rwM69IRjyXSxux0RVs6@p19kXcSZ/Fgq/CFYT3BWkeBmHUZInP1B0nvb5ixFUzVC5MM@vwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `a`.
```
≔±X²L↨⊕÷θ±N²ζ
```
Calculate the smallest power of `2` not less than `a/b`.
```
I×ζ÷θζ
```
Round `a` up to that power of `2`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Họ¡2’<ð1#
```
A dyadic Link that accepts \$a\$ on the left and \$b\$ on the right and yields \$c\$ as a singleton list. Alternatively, a full program that prints the result.
**[Try it online!](https://tio.run/##y0rNyan8/9/j4e7eQwuNHjXMtDm8wVD5////hgaGQGwAAA "Jelly – Try It Online")**
### How?
```
Họ¡2’<ð1# - Link: integer, a; integer b
1# - starting at k=a and incrementing find the first k for which:
ð - dyadic chain - f(k, b):
¡ - repeat...
ọ 2 - ...times: order-multiplicity 2
H - ...action: halve
-> divides k by two until we have an odd number
’ - decrement
< - is less than {b}? (i.e. k <= b ?)
```
---
Same method `Bt0Ḅ’<ð1#` or `BTṬḄ’<ð1#` - remove trailing zeros from the binary representation and convert back.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-1`, 7 bytes
```
Ň+ᵖ{ʷ½≥
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpKuoVLsgqWlJWm6FuuOtms_3Dqt-tT2Q3sfdS5dUpyUXAyVWrDd0MBQwdDAgMsIRpuagWiINAA)
```
Ň+ᵖ{ʷ½≥
Ň Find a natural number
+ Plus the first input
ᵖ{ Check that:
ʷ½ Repeatedly divide by 2 until the number is odd
≥ The second input is greater than or equal to the result
```
`-1` prints the first solution.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 57 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.125 bytes
```
ɾ/2•⌈EÞż
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJnPSIsIiIsIsm+LzLigKLijIhFw57FvCIsIiIsIjEwMFxuMjAxIl0=)
Ports the 05AB1E answer.
[Answer]
# [C89](https://gcc.gnu.org/), 36 bytes
*port of [Arnauld's JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/263779/112488).*
```
f(a,b){return(a&-a)*b<a?f(a+1,b):a;}
```
[Try it online!](https://tio.run/##ZY7BDoIwEETP7Fc0GE2rxVATjQrqj3hZWsAmWAwUL4RftxaIJ0@7eTO7MzIqpXSuoMgz1je57RpDcRUhW2cp3jzfCK@cMRncQhtZdSonaWuVrrePK8C71gps3lqqjSXIyTgyBj0Er8bvBQ2X6m5CTsYIr7AEBgCvwBO1oZNzuhex4ETEsTfMYPcH9ocfgGCuSmL/zn1kUWHZusj3usjj6Qs "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 30 bytes
*ommiting the return statement and the unchanged trailling parameter in the recursive call*
```
f(a,b){a=(a&-a)*b<a?f(a+1):a;}
```
[Try it online!](https://tio.run/##ZY5NDoIwEIXXzCkajKbVYqiJRgX0Im6GFrAJFgPFDeHq1oJx5epNvveTkVElpXMlRZ6zATOKqwjZOk/x6tlGsDMmo1toI@teFSTtrNLN9n4BeDVagS06S7WxBDmZJGcwQPBs/V3ScKluJuRkGvcOS2AE8A48UBs6J@e@iAUnIo594At2f2B/@AEI2sL2rSGxn3NvWdZYdS7yf2XyePoA "C (gcc) – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 41 bytes
```
f(a,b)=min(2^{ceil(log_2a/L)}L)
L=[1...b]
```
[Try It On Desmos!](https://www.desmos.com/calculator/w2ov82onsz)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/wzbablmymr)
Port of 05AB1E
] |
[Question]
[
Your task is to output a square sandbox of size `n+2` with `/` characters in the corners and `|` for the sides, and `-` for the top, with `n**2` layers of sand (`.`) overflowing out of the sandbox of width `n+2`
# Testcases
```
1
->
/-/
|.|
/./
...
2
->
/--/
|..|
|..|
/../
....
....
....
....
3
->
/---/
|...|
|...|
|...|
/.../
.....
.....
.....
.....
.....
.....
.....
.....
.....
```
Trailing spaces and newlines are allowed
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
n=input()
i=2
while~n*n<i:i-=1;d='/.|'[~-i*(i+n)and~(i<-n)];print d+'-.'[i<1]*n+d
```
[Try it online!](https://tio.run/##BcHdCkAwAAbQe0/hbn@NcMf2JHKhpnylz9Ikpb36nBPftJ/sS6EH452kquD76tlxbJmaDiOs76bgRdt8Ys4WWsJQrQxZwlmqZYoXmOpghG3EDNctmiaUMvw "Python 2 – Try It Online")
[Answer]
# [Python](https://www.python.org), 69 bytes
```
lambda n:[f"/{'-'*n}/",*n*[f"|{(c:='.'*n)}|"],f"/{c}/",*n*n*[c+'..']]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3XXMSc5NSEhXyrKLTlPSr1XXVtfJq9ZV0tPK0gAI11RrJVrbqekBBzdoapVgdkJpkqDxQRbK2up6eemws1DCdtPwihTyFzDyFosS89FQNQx0TTauCosy8Eg2tNI08TR0lJZ3i1AJbpZg8JU2IngULIDQA)
-2 bytes thanks to @ophact.
Outputs a list of lines, as [allowed by standard I/O rules](https://codegolf.meta.stackexchange.com/a/17095).
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~30~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'-×'/.ø©Ð„|.‡I.D®W'.:ÐW‡In.D»
```
Uses the legacy version of 05AB1E because it can take the minimum character of a string (based on its unicode value), saving 2 bytes over repushing the characters.
[Try it online](https://tio.run/##MzBNTDJM/f9fXffwdHV9vcM7Dq08POFRw7wavUcNCz31XA6tC1fXszo8IRzEzQPyd///bwQA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/iruSZV1BaYqWgZO@nw6XkX1oC4en4/VfXPTxdXV/v8I5DKw9PeNQwr0bvUcNCPz2XQ@vC1fWsDk8IB3HzgPzd/3UObbP/bwQA).
**Explanation:**
```
'-× '# Repeat "-" the (implicit) input amount of times as string
'/.ø '# Surround it with leading/trailing "/"
© # Store this string in variable `®` (without popping)
Ð # Triplicate it
„|.‡ # Transliterate the "/" to "|" and "-" to "." in the other copy (the
# transliterate ignores the trailing "…---/" since the strings are
# of unequal length)
I.D # Duplicate it the input amount of times
® # Push string `®`
W # Push the minimum (without popping): "-"
'.: '# Replace all "-" with "." in string `®`
Ð # Triplicate it
W # Push the minimum (without popping): "."
‡ # Replace all "/" with "." (transliterate again ignores the trailing
# "…---/")
In # Push the input, and square it
.D # Duplicate this string of "."s that many times
» # Join all strings on the stack by newlines
# (after which the result is output implicitly)
```
[Answer]
# Excel, ~~96~~ 95 bytes
```
=LET(r,REPT(".",A1),"/"&REPT("-",A1)&"/"&REPT("
|"&r&"|",A1)&"
/"&r&"/
"&REPT("."&r&".
",A1^2))
```
[](https://i.stack.imgur.com/6RJgG.png)
[Answer]
# Java 11, 121 bytes
```
n->"/"+"-".repeat(n)+"/\n"+("|"+".".repeat(n)+"|\n").repeat(n)+"/"+".".repeat(n)+"/\n"+(".".repeat(n+2)+"\n").repeat(n*n)
```
[Try it online.](https://tio.run/##fZCxTsNAEET7fMVqqztOvgjoMKanIBSUIcXhXNAGZ23Z60go8bc7G9sFFoLmpJt5I83sPhxDst9@9XkRmgZeAvFpAUAssd6FPMLq@gV4k5r4E3KjDrBNVewW@jQShHJYAUPWc/KES3SYoK9jFYMYtg6X74zO4FkNPzPOatgZ@QuZsj9Ed6fyLHjDtk@vXar2o9AuU6VjSVs46B4zdl9vgh237Mp6mEHZbUqP2X1Kzk2WDv1uJB582YqvNCYFG3zmqpUHQEfD8L@w11ZG7j@Kvd7QTkQ3nLHrLw)
Straight-forward approach using Java 11+'s [`String#repeat`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#repeat(int)).
[Answer]
# APL+WIN, 58 bytes
Prompts for n
```
o,(⍉(n,⍴c)⍴c←'-',((n+1)+n*2)⍴'.'),o←(1,n,1,(n←⎕)*2)/'/|/.'
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tf76OxqPeTo08nUe9W5I1QQRQTl1XXUdDI0/bUFM7T8sIJKqup66pkw@U0jDUydMx1NHIA7KBRmkCpfXV9Wv09dT/A83j@p/GZcilrqDOlcZlBKWNuQA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Nθ↶UB.×.×θθ/F³«θ↶²/
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orILMsv8QnNa1EA8gJTi1xSkzOTi/KL81L0VDSUwIpKMrMK9EIycxNLQaJ6ChAmIU6CoWamnB5JX2Q2rT8IgUNY02Fai5OiDDIBk6EFUZgLpKG2v//jf/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
↶
```
Change the default drawing direction to up. (I do it here because I can use the default pivot of 90°.)
```
UB.
```
Set the default character for unpainted areas to `.`.
```
×.×θθ
```
Draw the right-hand edge of the overflowing sand. (The rest of the sand gets drawn as part of the unpainted area.)
```
/
```
Draw the bottom right `/`.
```
F³«
```
Repeat three times.
```
θ
```
Draw the right `|`s, the top `-`s or the left `|`s as appropriate.
```
↶²
```
Pivot the default drawing direction by another 90°.
```
/
```
Draw the top right, top left or bottom right `/` as appropriate.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 42 bytes
```
.+
/$&*-/¶$&*$(|$&*.|¶)/$&*./$&**$(¶.$&*..
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS19FTUtX/9A2IKWiUQMk9WoObdMEieqBCKDgoW16IJ7e//@GXEZcxgA "Retina – Try It Online") Link includes test cases. Explanation: Straightforward application of Retina 1's string repeat operator, except that `**` is shorthand for `*$&*` thus squaring the input.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 77 bytes
```
n=>`/${(C=D=>D.repeat(n))('-')}/
${C(`|${a=C('.')}|
`)}/${a}/
`+C(C(a+`..
`))
```
[Try it online!](https://tio.run/##DcmxCoQwDADQ3e8oNEWMw81xiR@S4NXjRFpRcal@e8363qKXHtP@384u5W@sM9VEg/SuANNIw4h73KKekEIA3/nw9I0rDHK7osTg0ehuxNzAUloGBm0F0TTUKacjrxHX/IMZPiYv "JavaScript (Node.js) – Try It Online")
Constructs a large template string using a function `C` to shorten the usage of `repeat`.
Thanks @Arnauld for -4 bytes by reminding me that literal linefeeds exist. (I've been doing way too much Python recently.)
[Answer]
# [Rust](https://www.rust-lang.org/), ~~140~~ 134 bytes
```
|i|{let r=".".repeat(i);print!("/{}/
{}/{}/
{}
","-".repeat(i),format!("|{}|
",r).repeat(i),r,(".".repeat(i+2)+"
").repeat(i.pow(2)))}
```
[Try it online!](https://tio.run/##TYwxDoMwDEX3nCL1ZAsIKt2K6FUqhkSKVAIyQUhNcvYU2qEZ/P7wnszb6rNxchqtQ5JBvLSX5m4cbqt9a5LN4ykHmaON4VQ8gALFetGjR0v9wtb5C0IbUiuO@42AGpoiq83M03h2MaR4WKZCco3l06qjCgT8C7XMO3ZElHIvDF7pZPfl7WDKHw "Rust – Try It Online")
**To 134 bytes:** I was able to save 6 bytes by using type hinting.
The link includes a header and a footer for calling the closure, and I call it for `1`, `2`, and `3`, to prove that it works!
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~143~~ 137 bytes
*saved 6 bytes thanks to @ceilingcat*
```
j;main(n){scanf("%d",&n);char s[n+=2];for(;j<n;puts(s))memset(s,46-!j,n),*s=s[n-1]="/|"[j++&&j^n];*s=s[--n]=46;for(j=--n*n;j--;)puts(s);}
```
[Try it online!](https://tio.run/##LYxBCsIwEAC/ogFD0mYRS@llzUtKhBBbdSFb6daT@vZYisdhhklwS6kUwhwfbNi@JUUejTpcldNsMd3jvJOea98EHKfZIJ0Zn69FjFibhyzDYsS1HezJsXWV@LWGU/Dq@FE91bXWdOGAmwDg4NtuG5FfqWIkALT/IX5LaX4)
Indented version:
```
j;
main(n){
scanf("%d",&n);
char s[n+=2];
for(;j<n;puts(s))
memset(s,46-!j,n),
*s=s[n-1]="/|"[j++&&j^n];
*s=s[--n]=46;for(j=--n*n;j--;)puts(s);
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `J`, 32 bytes
```
¤-\/pǏD£‛/-‛|.Ŀ⁰Ḋ¥:g\.VDg\/$V⁰²Ḋ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJKIiwiIiwiwqQtXFwvcMePRMKj4oCbLy3igJt8LsS/4oGw4biKwqU6Z1xcLlZEZ1xcLyRW4oGwwrLhuIoiLCIiLCIzIl0=)
## How?
```
¤-\/pǏD£‛/-‛|.Ŀ⁰Ḋ¥:g\.VDg\/$V⁰²Ḋ
¤ # Push an empty string
- # Push "-" * a + b (where a is the (implicit) input, and b is the empty string)
\/p # Prepend "/"
Ǐ # Append its first character (the slash)
D # Triplicate
£ # Pop and store in the register
‛/- # Push string "/-"
‛|. # Push string "|." (for input 3, stack e.g. ["/---/", "/---/", "/-", "|."])
Ŀ # Transliterate (stack e.g. ["/---/", "|...|"])
⁰Ḋ # Duplicate the top value of the stack the input amount of times (stack e.g. ["/---/", "|...|", "|...|", "|...|"])
¥ # Push contents of register (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/---/"])
: # Duplicate (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/---/", "/---/"])
g # Take the minimum by character code, which is "-" (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/---/", "-"])
\.V # Replace with a period (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../"])
D # Triplicate (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../", "/.../", "/.../"])
g # Take the minimum by character code, which is "." (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../", "/.../", "."])
\/ # Push "/"
$ # Swap with the period (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../", "/.../", "/", "."])
V # Replace (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../", "....."])
⁰² # Push the input squared
Ḋ # Duplicate the top value of the stack that many times
# J flag joins the stack by newlines
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 37 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
'.*'|▌'|+k(Ä_'-k*'/▌'/+_¬'.k⌠*k²(Ä_]n
```
[Try it online.](https://tio.run/##y00syUjPz0n7/19dT0u95tG0HvUa7WyNwy3x6rrZWur6IAF97fhDa9T1sh/1LNDKPrQJJBmb9z/vvyGXEZcxlwkA)
**Explanation:**
```
'.* '# Push a string with the (implicit) input amount of "."
'|▌ '# Prepend "|"
'|+ '# Append "|"
k(Ä # Loop the input-1 amount of times,
# using a single character as inner code-block:
_ # Duplicate the "|...|" string
'-k* '# Push a string with the input amount of "-"
'/▌'/+ # Surround it with leading "/"
_ # Duplicate it
¬ # Rotate the items on the entire stack once
'.k⌠* '# Push a string with the input+2 amount of "."
k²(Ä # Loop input²-1 amount of times,
# using a single character as inner code-block:
_ # Duplicate the "." string
] # Wrap the stack into a list
n # Join this list with newline delimiter
# (after which the entire stack is output implicitly)
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-pl`, 66 bytes
```
$;=c x$_;$_=a."-"x$_.ad."b$;bd"x$_.a.$;.a."dcc$;"x$_**2;y;a-d;/|..
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJDs9YyB4JF87JF89YS5cIi1cIngkXy5hZC5cImIkO2JkXCJ4JF8uYS4kOy5hLlwiZGNjJDtcIngkXyoqMjt5O2EtZDsvfC5cbiIsImFyZ3MiOiItcGwiLCJpbnB1dCI6IjMifQ==)
## Explanation
Generates the output, char by char, replacing characters used multiple times with bareword letters to avoid additional quotes or brackets. Makes use of operator precedence in that `x**y` works without quotes, but `x*x` doesn't. Also makes use of the fact that `-p` adds `;}` to the code and uses `;` as the separator for `y///`, saving another byte.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 38 bytes
```
QQttGU+&O46+47blht&(45G:Q(!'|'5MlOh&(c
```
[Try it online!](https://tio.run/##y00syfn/PzCwpMQ9VFvN38RM28Q8KSejRE3DxNTdKlBDUb1G3dQ3xz9DTSP5/39jAA "MATL – Try It Online")
] |
[Question]
[
A ***truncated square-pyramid*** of height \$h\$ has \$h\$ square layers where each layer has a side \$1\$ greater than the one above it, apart from the top layer which is a square of blocks with a given side length.
Here is a truncated square-pyramid of height \$7\$ and top side-length \$4\$ viewed from the side:
```
side length blocks
████ 4 16
▐████▌ 5 25
██████ 6 36
▐██████▌ 7 49
████████ 8 64
▐████████▌ 9 81
██████████ 10 100
Total = 371
```
It requires \$\sum\_{i=4}^{10}i^2=371\$ blocks to construct.
---
A ***truncated square-pyramid garden*** of size \$N\$ consists of truncated, square-pyramids of heights \$1\$ to \$N\$ where the \$n^{th}\$ tallest pyramid has a top side-length of \$x\$ where \$x\$ is the remainder after dividing \$N\$ by \$n\$ unless there is no remainder in which case \$x=n\$.
Here is a side-on view of a pyramid garden with \$N=6\$ pyramids, arranged from tallest to shortest:
```
N=6 ▐▌
██ ██
▐██▌ ▐██▌ ▐██▌
████ ████ ████ ██
▐████▌ ▐████▌ ▐████▌ ▐██▌ ▐▌
██████ ██████ ██████ ████ ██ ██████
height 6 5 4 3 2 1
n 1 2 3 4 5 6
remainder of N/n 0 0 0 2 1 0
top side-length 1 2 3 2 1 6
```
This garden takes \$337\$ blocks to construct.
### Task
Given a positive integer, \$N\$, calculate the number of blocks required to build a *truncated square-pyramid garden* of size \$N\$.
You are not required to handle size zero (just in case that causes an edge case for anyone).
Since this is a sequence, you may instead opt to output the block counts for all gardens up to size \$N\$ (with or without a leading zero, for size zero), or generate the block counts indefinitely without input (again a leading zero is acceptable). It's not currently in the [OEIS](https://oeis.org/), and neither is its two-dimensional version.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in each language wins.
### Test cases
The first \$100\$ terms of the sequence are (starting with \$N=1\$):
```
1, 9, 28, 80, 144, 337, 455, 920, 1251, 1941, 2581, 4268, 4494, 7065, 9049, 11440, 13299, 19005, 20655, 28544, 31140, 37673, 45305, 59360, 59126, 73289, 86256, 101124, 109647, 136805, 138364, 170780, 184520, 211485, 241157, 275528, 272869, 326729, 368320, 414692, 424823, 499261, 510708, 596140, 636361, 680537, 753508, 867036, 857345, 966889, 1027920, 1130172, 1197747, 1358369, 1393684, 1528840, 1571095, 1712605, 1860668, 2083248, 2023267, 2261821, 2445122, 2584136, 2685714, 2910217, 2980225, 3298056, 3459910, 3719313, 3824917, 4206640, 4128739, 4534965, 4846194, 5081240, 5308615, 5695545, 5827090, 6349936, 6395099, 6753185, 7173903, 7783720, 7688846, 8192521, 8679955, 9202980, 9429730, 10177969, 10090513, 10725680, 11134432, 11766133, 12407705, 13134004, 13024244, 13979357, 14523352, 15111244
```
---
Note: there is a surprisingly terse Jelly solution to find for this one, happy hunting!
Here's a hint that might help get you thinking about a different approach:
>
> In Jelly lists are 1-indexed and indexing is modular, so finding the top side-length could be calculated by using \$N\$ to index into a list of `[1,2,...,n]`.
>
>
>
*2022-03-15*: If you just want to see this solution I have now posted it [below](https://codegolf.stackexchange.com/a/244169/53748).
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
-2 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!
```
lambda N:sum((N%~n-~h)**2for n in range(N)for h in range(n,N))
```
[Try it online!](https://tio.run/##RcixDkAwEADQ3VfcIr2TSpRN4hf6BZaKVptwpGqw@PWKyRvfcSe/c5fdMObVbNNsQPfntSHq8uH68VRVrdsjMASGaHixqOkL/wdLTZS/DH8qqRpFfQFwxMAJHQaSYHkehARB@QU "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~63~~ 61 bytes
```
n=>eval("for(x=y=0;x++<n;)for(z=0;z++<=n-x;)y+=(~-n%x+z)**2")
```
[Try it online!](https://tio.run/##LVPbbloxEHzPV7hIlSBA5b3Ya4ucvvUrojxELVRUCCqSRiQP/XU6Y6ojHa@9693ZmfWv57fnl@/n/e/X9fH0Y3vdTdfj9HX79nyYz3an8/wyvU95c1kuH46bBQ8@sP3AdjquL5vF@3Ka/10fP1@WH4v7e50trpu7O1z@s31JU3qUVeqrpG2VWl4lcV8ls1glLwUe5ZkWBEl3/LU0/F0r4t07giNXBmZHFsF1XjDt3PWc4VIEcGll5EYMQixqGIsYQ0q3mrmIVmQ0bbjeqhbsJIuoc@3Vg8lr4x2xZpXnkWMgb16IVlGgsZ6LFMRrlMLuNLRVpDWtoVxrM8a7eO3KnrwpIfWuFT0WyZEbQdWBuBo@nLM6@Ylihf5WIxtwthLmZKLWRviSNW70iWUJpdEjbi0UYGeMofHGJgCxDepKoFG2F@Bi9NlqrqRbMwD7MJRNwADQplTFvYjqkMeFaCAQMiGzdgARBveWVQsJgEVmAbfDSzGkm6B3a@qdwQ7Rqg92tIX1oZR3Ku3Nq1B4dA9hKJvlVoUy1l4KOShNI/dBGugknmq9ZA5FBW9CfUKQN6NoRLMgUQHikBxUStfCvsBt7//nkKhhuPawPMYiog8SM0oVwodiGJkxDCDd3QbpUasYvQAbcRsdeHMm75YVwg@rRzcOjGCOzArvFuHs@RMeDN5Vmh@2r2mPRyMbLA8TS8NaLhd3Ke13ab6b7xfp05Rur@txv5YnulL6fjq@nA7bL4fTz/ns2/l8Os8Wm@s/ "JavaScript (Node.js) – Try It Online")
Shortened by @ophact.
[Answer]
# [R](https://www.r-project.org/), ~~58~~ 49 bytes
```
function(N){for(i in 1:N)F=F+(x=i:N+N%%-i)%*%x
F}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NPszotv0gjUyEzT8HQyk/TzdZNW6PCNtPKT9tPVVU3U1NVS7WCy632f3FiQUFOpYahlaGBTprmfwA "R – Try It Online")
Relatively straightforward implementation of the spec.
# [R](https://www.r-project.org/), ~~58~~ 54 bytes
```
function(N)sum(unlist(Map(seq,N%%-(1:N)+1:N,l=N:1))^2)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NPs7g0V6M0LyezuETDN7FAozi1UMdPVVVXw9DKT1MbSOjk2PpZGWpqxhlp/k/TMNP8DwA "R – Try It Online")
Slightly more interesting but longer; relies on the same logic as above to generate the size of the top of each tower.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
Rr_"N%RƊF²S
```
[Try it online!](https://tio.run/##y0rNyan8/z@oKF7JTzXoWJfboU3B////NwMA "Jelly – Try It Online")
```
R Range [1..n]
r Range each to n: [[1..n], [2..n], …, [n]]
N%RƊ [(-n)%1, …, (-n)%n]
_" Vectorize subtract
F²S Flatten, square, sum
```
[Answer]
# APL+WIN, ~~47~~ 38 bytes
Prompts for N
```
+/∊((((n=0)×i)+n←i|N)+¯1+⌽⍳¨i←⍳N←⎕)*¨2
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7b@o44uDSDIszXQPDw9U1M7DyiZWeOnqX1ovaH2o569j3o3H1qRCRQEMvxAVN9UTa1DK4z@A/Vz/U/jMuRK4zICYmMgNgFiUyA2NDDgAgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L(%ā.sR+˜nO
```
[Try it online](https://tio.run/##yy9OTMpM/f/fR0P1SKNecZD26Tl5/v//mwEA) or [verify the first 25 test cases](https://tio.run/##yy9OTMpM/W9k6upnr6TwqG2SgpK9n8t/Hw3VI416xUHap@fk@f/X@Q8A).
**Explanation:**
```
# e.g. input=6
L # Push a list in the range [1, (implicit) input]
# STACK: [1,2,3,4,5,6]
( # Negate each value
# STACK: [-1,-2,-3,-4,-5,-6]
% # Modulo the implicit input by these values
# STACK: [0,0,0,-2,-4,0]
ā # Push a list in the range [1,length] (without popping)
# STACK: [0,0,0,-2,-4,0],
# [1,2,3,4,5,6]
.s # Get its suffixes
# STACK: [0,-4,-2,0,0,0],
# [[6],[5,6],[4,5,6],[3,4,5,6],[2,3,4,5,6],[1,2,3,4,5,6]]
R # Reverse the list of suffixes
# STACK: [0,-4,-2,0,0,0],
# [[1,2,3,4,5,6],[2,3,4,5,6],[3,4,5,6],[4,5,6],[5,6],[6]]
+ # Add the values in the two lists at the same positions together
# STACK: [[1,2,3,4,5,6],[2,3,4,5,6],[3,4,5,6],[2,3,4],[1,2],[6]]
˜ # Flatten to a single list
# STACK: [1,2,3,4,5,6,2,3,4,5,6,3,4,5,6,2,3,4,1,2,6]
n # Square each integer
# STACK: [1,4,9,16,25,36,4,9,16,25,36,9,16,25,36,4,9,16,1,4,36]
O # Sum them together
# STACK: 337
# (after which the result is output implicitly)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
N=>eval('for(k=n=0;n++<N;)for(c=e=N%n||n;c<=e+N-n;)k+=c*c++')
```
[Try it online!](https://tio.run/##FctNDoIwEEDhq8zG0NrBgP@mjEfoBYyLprZGqVMDyIq7V9i@fO9tR9u77vUdSk4PnwNlQ1c/2iiKkDrRElOlWanGaLkER57MiqeJtWvIK1Oylq0it3ZKFTLPBoRL3A/Avw@kALcaYYuwQ9gjHBCOCCeEM8IFoa7uEhadot/E9BRBzJeUOv8B "JavaScript (Node.js) – Try It Online")
-2 by Polichinelle.
Iteratively calculates sum, which is shorter than direct calculation.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 37 bytes
```
N->sum(n=1,N,sum(i=n,N,(i-(-N)%n)^2))
```
[Try it online!](https://tio.run/##FcoxCoAwDEDRqwRBSKCB1r09Qo4guLRkMJaq569x@bzh92Motz4r5Clc7vdEyylI@KXZXKiMLLQa7RvRrNdA8QVSjAH6UHtQYAEunopC/nw "Pari/GP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 71 bytes
```
s;h;n;x;f(N){for(s=n=0;N/++n;)for(h=-~N-n,x=N%n?:n;h--;++x)s+=x*x;n=s;}
```
[Try it online!](https://tio.run/##VVTBbtswDL33K4QABZLaQSVSEqV53g7DrvmBtYfCdZpgm1vEAWasyD592aOStmuCyDL5SD0@UumWD113PI7NphmaqVnPV4vn9eNuPrZDa5vVdVUNzUINm3b5Z7Uc6qldXQ6fPwzNZrlsqmpajFU7XU3N0I7N4bgd9ubn3XaYL8zzhcFHDf301Hf7/v7brWnNs6tNrg2l2iRbG@d9bZilNj4EeEhtFABy2WOlkLB6isB7nwEWGxVoPbI4hGsAU9a3bC1cBIA@Uii5gQGEJQrrIayQkDlafTiKyMiUEJ4iBbw56xx5feboRZPHpDGOE0e1i5XCPPmgbAkHJD3POxeAJwlBqyOhFJGWKQrpMyZWvHc@ZtKafCKllDNF1BicFZuUVCyMI@MLu56u@kjgoP4UxTJ4piDsVYkYk9J3luQkn2PrhHSTRU4lBHBXDKPwpEWAYirSBUGhWp5Ai1Jnijaq3GRB2JcNaRHYgGgi7Yr3wRGV9ninbNAgZEJmyiDiFJyTJQoqAHaqLOhmeLUZLrND7ZzIZwV7NC36og4l4Vw65bN22icfnTYe1aMx2ja2KTptY8whqAYhkdhcRIOcyidyDlaHIkI3p/0Rh7wWh4okFhVKIBySQ0qXKWhd0Dbn8xwqa2w8ZWFbxkIkFxEtjgpKHx3DyJRhgOjecxFdYnSsXpAVOY0OvNaq7mwJjS@7LJl1YBzmiDlobHA6e/7QlLvTPQ7j3nSbu90V1r773u9OV2h2M32lmyl/wS/MavP/O8/O0bi0Zq7Xbzvc9xPCbHPefjTj9nf/uJ6/XMzF9dlw9WppTFUV9KIkO13mlwu9R7ZTqsq45p1rhGs93y/eW3tYX/8FSuTtG@BpB8h6Pru8N8tPBuvleDOgqn1txvq18L5tx9tz2sPF4fi3W/@4exiPy1//AA "C (gcc) – Try It Online")
Inputs an integer \$N>0\$.
Returns the number of blocks needed to make a truncated square pyramid garden of size \$N\$.
[Answer]
# JavaScript (ES6), 56 bytes
```
f=(N,n=N)=>n&&f(N,n-1)+(g=k=>n++<=N&&k*k+g(k+1))(N%n||n)
```
[Try it online!](https://tio.run/##FYpBDoIwEEX3nmIW2Mw4YmAt4xF6BhqkjZZMCRg3wNlrXf33Xv7bfd06LK/5U2t6jjl7QXtVsSQPNcb/pW6JMUgshbkTa0y8RA4YuSVCe9Z9V8o@Lagg0N5BoSvbNIWY6QQwJF3TNN6mFLB3WG16ULlWm0elo6f8Aw "JavaScript (Node.js) – Try It Online")
---
# Faster, 66 bytes
A longer version that works in \$O(N)\$:
```
f=(N,n=N,k=N%n||n)=>n&&f(N,n-1)-(g=x=>x*(x+++x)*x/6)(k-1)+g(k+N-n)
```
[Try it online!](https://tio.run/##FYpBDoIwEEX3nqILJDMMVdiw0eEIPQMNUqKQqQFjmgBnr3X1X977L/u1a7883x8t/jHE6BhMKWzKic1Z9l2QW8lz97e6Rg0jB25DAYGIAhbh2iBMqdAIExktGJ1fQBSr@qZE3dNWVSIiPCnVe1n9PFxmP0JnIdvkwHTNNgeCR4fxBw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ịṡ¥Ɱ¹²FS
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//4buL4bmhwqXisa7CucKyRlP/w4cpWf//MTAw "Jelly – Try It Online")
Uses the very clever tip supplied, but I'm not sure this quite inspires the description "surprisingly terse" yet... that `¹` just smells wrong!
More equivalent 8-byters:
* `ṡR⁸ịⱮ²FS`
* `ịⱮṡR$²FS`
* `ịⱮṡⱮ`²FS`
* `RɓịⱮṡ²FS`
```
Ɱ¹ For each n in [1 .. N],
ṡ get a list of all substrings of [1 .. N] of length n,
ị ¥ and take the one at modular 1-index N.
² Square each,
F flatten,
S and sum.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
NθIΣEθΣX⁺⊕…ιθ﹪θ±⊕ι²
```
[Try it online!](https://tio.run/##Vcs7DsIwEEXRnlW4nJFMQ0GTkipFIousYHBGwZI/sWPD8gdMx6tucZ59UrGJvMgY91bnFh5cIONwMsXFCjc6KiwtwEQ7ZK16mvT@GuPbAWO0hQPHyivcKW4MTquMqNWU1uZTv8y8UeU/6hC7ueBvg8hVzi//AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Inspired by @KevinCruijssen's and @ovs's answers. Explanation:
```
Nθ Input `N` as a number
θ Input `N`
E Map over implicit range
… Range from
ι Current value
θ To input `N`
⊕ Vectorised Increment
⁺ Vectorised Plus
θ Input `N`
﹪ Modulo
ι Current value
⊕ Incremented
± Negated
X ² Vectorised Squared
Σ Take the sum
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~54~~ 46 bytes
```
->n{(1..n).sum{|x|(x..n).sum{|y|(n%-x+y)**2}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9PU6@4NLe6pqJGowLBq6zRyFPVrdCu1NTSMqqtrf1foABSbGigqZebWKChlqb5HwA "Ruby – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 27 bytes
```
roJngsaj.%jiS~]q?+Z]FLqS[ms
```
[Try it online!](https://tio.run/##SyotykktLixN/V9WZmhgUP2/KN8rL704MUtPNSszuC620F47KtbNpzA4Orf4f627/38A "Burlesque – Try It Online")
Port of [Kevin Cruijssen's](https://codegolf.stackexchange.com/a/243170/91386) answer
```
ro # Range [1..N]
J # Dup
ng # Negate
sa # Non-destructive length
j.% # Modulo (implicit zip)
j # Reorder stack
iS # Generate tails
~] # Drop final
q?+Z] # Zip and sum
FL # Flatten
qS[ # Square
ms # Map sum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly)
Much of this post is in spoiler blocks, just in case anyone wants to try to find it for themselves since I mentioned it in the question.
>
>
> ```
> ịⱮẆ²S
> ```
>
>
>
>
**[Try it online!](https://tio.run/##AR4A4f9qZWxsef//4buL4rGu4bqGwrJT/8OH4oKs//8xMDA "Jelly – Try It Online")**
### How?
>
> Unrelated String got to the method [in their answer](https://codegolf.stackexchange.com/a/243269/53748), just not to the golfed code!
>
>
> ```
> ịⱮẆ²S - Link: integer, N
> Ẇ - all sublists of [1..N]
> e.g. N=6 -> [[1],[2],[3],[4],[5],[6]
> ,[1,2],[2,3],[3,4],[4,5],[5,6]
> ,[1,2,3],[2,3,4],[3,4,5],[4,5,6]
> ,[1,2,3,4],[2,3,4,5],[3,4,5,6]
> ,[1,2,3,4,5],[2,3,4,5,6]
> ,[1,2,3,4,5,6]
> ]
> i.e. for size in [1..N]:
> for start in [1..N+1-len]
> [start..start+size]
> Ɱ - for each sublist:
> ị - N index into sublist
> - indexing in Jelly is 1-indexed and modular so...
> e.g 6 ị [3,4,5,6] -> 4
> i.e N ị [start..start+size]
> -> (N mod size)+start-1 if (N mod size) != 0 else start+size
> e.g. 6 ịⱮ (6Ẇ) -> [1,2,3,4,5,6,2,3,4,5,6,3,4,5,6,2,3,4,1,2,6]
> ...if these were grouped in lengths of [N..1] they
> are our tower level side lengths:
> [[1,2,3,4,5,6] (height 6: [top..bottom])
> ,[2,3,4,5,6] (height 5: [top..bottom])
> ,[3,4,5,6] (height 4: [top..bottom])
> ,[2,3,4] (height 3: [top..bottom])
> ,[1,2] (height 2: [top..bottom])
> ,[6] (height 1: [top..bottom])
> ]
> ² - square (vectorises)
> S - sum
>
> ```
>
>
>
>
] |
[Question]
[
Given an integer **N** from 1-9, you must print an **N**x**N** grid of **N**x**N** boxes that print alternating 1s and **N**s, with each box having an alternating starting integer.
**Examples**
```
Input: 1
Output:
1
Input: 2
Output:
12 21
21 12
21 12
12 21
Input: 3
Output:
131 313 131
313 131 313
131 313 131
313 131 313
131 313 131
313 131 313
131 313 131
313 131 313
131 313 131
Input: 4
Output:
1414 4141 1414 4141
4141 1414 4141 1414
1414 4141 1414 4141
4141 1414 4141 1414
4141 1414 4141 1414
1414 4141 1414 4141
4141 1414 4141 1414
1414 4141 1414 4141
1414 4141 1414 4141
4141 1414 4141 1414
1414 4141 1414 4141
4141 1414 4141 1414
4141 1414 4141 1414
1414 4141 1414 4141
4141 1414 4141 1414
1414 4141 1414 4141
```
An array (of NxN arrays) or text in this format is acceptable.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~30~~ 29 bytes
```
#^Array[Plus,#+0{,,,}]~Mod~2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XznOsagosTI6IKe0WEdZ26BaR0enNrbONz@lzkjtf0BRZl6JQ0h@cAmQkR7tXpSZ4pDm4Jqcke@grONfWlJQWuKWX5Qbq1YHNqXO8j8A "Wolfram Language (Mathematica) – Try It Online")
Returns a \$(N\times N)\times(N\times N)\$ array.
```
Array[ ,#+0{,,,}] N x N x N x N array, where values are
#^ N^
Plus (sum of indices
~Mod~2 mod 2)
```
[Answer]
# [J](http://jsoftware.com/), 33 23 19 bytes
```
]^2|i.+/2|+/^:2~@i.
```
[Try it online!](https://tio.run/##XYyxCsIwGIT3PsXRJUhtKtGpUhCFTuLgbiHUPyaijSRREIqvHmu7Odxw993dNaacKVQlGOZYoByUc@yO@zqeGtEbnhWiz4qmFJ@N4XGWHLYctXV3GYLpLgia4Mg/b8HDW5jAPEh6Qw7BwhP9Gu9xdR5wByXbAC1fI0BrnaMh8Fo@iCdqPK441kUqEmq1xRRBYTl5lufsj6ziFw "J – Try It Online")
*Note: In TIO I added a formatting function to box each element, which is now a list of digits, to make the correctness more obvious. If you remove it, the results will still be correct but because of the way J prints by default it won't be immediately clear.*
*-10 thanks to power trick stolen from [att's Wolfram answer](https://codegolf.stackexchange.com/a/241893/15469)*
* `2|...+/^:2~@i.` Creates a 0-1 checkerboard in the n x n x n dimensions of the input
* `i.+` Creates n versions of that, adding 0, 1, ... n elementwise.
* `]^` Raises input to those 0-1 matrices, creating matrices of 1 and n. This is really the end of the golf.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
```
₀Ẏ:v꘍:£vv‡¥꘍?‹*›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoDhuo46duqYjTrCo3Z24oChwqXqmI0/4oC5KuKAuiIsIiIsIjQiXQ==)
A huge mess.
[Answer]
# [GeoGebra](https://geogebra.org/), 92 bytes
```
n=2
a=Zip(Zip(Mod(b-a,2),b,1…n),a,1…n)
b=(n-1)a+1
l=Zip(Zip(b+Mod(d,2)(n+1-2b),d,c),c,a)
```
[Try It On GeoGebra!](https://www.geogebra.org/calculator/qqnk4cqu)
`n` is the input, and `l` is the output.
The output is in the form of an array of depth 4:
* Inside the outermost list (layer 1) is the rows of the supersquare (layer 2)
* Inside the second layer is each individual matrix in the supersquare (layer 3)
* Insde the third layer is each row of a particular matrix entry in the supersquare (layer 4)
The default input is `n=2`, but you can change this to whatever input you want.
Output for `n=2` (layers labelled):
```
{{{{1, 2}, {2, 1}}, {{2, 1}, {1, 2}}}, {{{2, 1}, {1, 2}}, {{1, 2}, {2, 1}}}}
||||__4_| | | |
|||______3_______| | |
||_______________2__________________| |
|____________________________________1_____________________________________|
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 48 bytes
```
n->matrix(n,,i,j,matrix(n,,k,l,n^((i+j+k+l)%2)))
```
[Try it online!](https://tio.run/##RcpBCoAgEEDRqwxBMIPjomirRwncGKM2ibjo9larNh8e/Bqa2KOOCG6o9WfoTW5UZuHEvzIX1h1RTDLZFJpXIhrxaqjgYGHYGGoT7a8nsP5NRP2eBw "Pari/GP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L4ãOÉmIFIô
```
The modulo-2 exponent trick is taken from [*@att*'s Mathematica answer](https://codegolf.stackexchange.com/a/241893/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f/fx@TwYv/Dnbmebp6Ht/yvteVS4gooSi0pqdQtKMrMK0lNUcgvLSkoLbFSUNLxOj0HqOjwhsN7gdSjpjWHdh/aZnR4@uG99v9NAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/qquSZV1BaYqWgZO93eMKhlTpcSo7JJaWJOQr5pSVQif8@JocX@x/uzD20zu3QusNb/tfacikFFKWWlFTqFhRl5pWkpiBU63idngNSdHjD4b0g@lHTmkO7D20zOjz98F6dQ9vs/wMA).
**Explanation:**
```
L # Push a list in the range [1,(implicit) input]
4ã # Create all possible quartets of these values,
# by using the cartesian power of 4
O # Sum each inner list
É # Check for each sum whether it's odd
m # Take the (implicit) input to the power of these 0s/1s,
# so all 0s become 1 and all 1s become the input-digit
IF # Loop the input amount of times:
Iô # Split the list into an input amount of parts
# (after which the multi-dimensional matrix is output implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~114~~ 111 bytes
```
k;j;i;f(n){for(i=0;n*n/++i;puts(i%n?"":"\n"))for(j=0;n/++j;putchar(32))for(k=0;n/++k;)printf("%d",i+j+k&1?:n);}
```
[Try it online!](https://tio.run/##RY/BDoIwDIbvPEWzBLM5iCA3KuFFvJAhONBKAKMJ4dWdmxDsae33/WmnwlopY1psUGPFSUzVo@c6i5D2dJBSY/ccB659yhlL2ZmYEM5onGF547i6Fj1PjgtpV9Ki6HpNY8WZX7JAy0a2uzhPSeBs7BzuhSYuYPLAlk0Cd1NN5eUNGUS4Pk@QINhDXCN@7pJw5QJk5cWUEOOG/rshBXt2AHbxRt1Pl272ZvNR1a2oBxO@vg "C (gcc) – Try It Online")
*Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
NθEθEθ⪫Eθ⭆θ∨¬﹪⁺⁺⁺ιλνπ²θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDN7FAo1BHAUp55WfmwYSCS4AK0qEc/yINv3yg6vyU0px8jYCc0mIkIlNHIUdTRyEPiAuA2EgTSBRqgkglBSUgrWn9/7/Jf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ Input `n` as an integer
θ Input `n`
E Map over implicit range
θ Input `n`
E Map over implicit range
θ Input `n`
E Map over implicit range
θ Input `n`
⭆ Map over implicit range and join
⁺⁺⁺ιλνπ Sum of all indices
¬﹪ ² Is divisible by `2`
∨ Logical Or
θ Input `n`
⪫ Join with spaces
Implicitly print
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
f=(n,w=4,y)=>w?[...Array(n)].map(_=>f(n,w-1,y=!y)):y?n:1
```
[Try it online!](https://tio.run/##bY3NCoJAFIX3PsVtNxd0QGqlXKXnqMjBNBS7I@OoDNGzT9oPbVqd78D5adWkhtI0vY1YXyrvaxIczrQLHVI25wcp5d4Y5QTjSd5UL86U1WskikNHG4eYuJyT2Ncjl7bRDHq0/WiXPNwDgEkZsECwdDBdfKl50F0lO30V9jVoKfsHrW64KPCt8IUj/2jl4BF8/raY@ic "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), 89 bytes
```
f=lambda n,s=" \n\n",p=0:s.join(j[s>"":]or f(n,s[:-1],j>"1")for j in(n*str(10+n))[p:n+p])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3I9NscxJzk1ISFfJ0im2VFGLyYvKUdApsDayK9bLyM_M0sqKL7ZSUrGLzixTSNIBqoq10DWN1suyUDJU004CCWQpARXlaxSVFGoYG2nmamtEFVnnaBbGaUAuMC4oy80o00jQMNTW5IGwYnaZhjEXMRBOqFeZGAA)
Returns a single string. Most lines have a trailing space.
[Answer]
# **Python 3, 181 bytes**
```
def s(n):
a=f'1{n}'*n
b,c=' '.join(([a[:n],a[1:n+1]]*n)[:n]),' '.join(([a[1:n+1],a[:n]]*n)[:n])
return '\n\n'.join((['\n'.join(([b,c]*n)[:n]),'\n'.join(([c,b]*n)[:n])]*n)[:n])
```
1. Creates a single row for a single box
2. Makes a complete row (N rows) of alternating boxes
3. Return a string containing N rows of N-rows boxes
[Answer]
# [Labra](https://esolangs.org/wiki/Labra), 69 bytes
```
()[]([])
()[<><{}>]<[{}<[]>]>
<[]><<>>[](<>[])<<>>
{}(())<<><<>><<>>>
```
I've been waiting for a month and a half for a question Labra could actually compete in.
Prints as a list: [[[[1, 2], [2, 1]], [[2, 1], etc...
```
For input = 3 (Which Labra receives as [3])
()[]([]) [1,0]
()[<><{}>] Starting at n=1, n=[1,0][n]: [1,0,1,0,1,...]
<[{}<[]>]> Index with [1...input[1]]: [0,1,0]
<[]><<>> Index into first line: [1,0,1]
[](<>[]) Put in list and add [0,1,0]: [[1,0,1],[0,1,0]]
<<>> Index with [0,1,0]: [[1,0,1],[0,1,0],[1,0,1]]
{}(()) Input (already a list) + 1: [3,1]
< > Index that with
<> previous line: [[1,0,1],[0,1,0],[1,0,1]]
<<>> indexed with itself: [[[0,1,0],[1,0,1],[0,1,0]],[[1,0,1],[0,1,0],...
<<>> twice: [[[[1,0,1],[0,1,0],[1,0,1]],[[0,1,0],[1,0,1],[0,1,0]],...
giving: [[[[1,3,1],[3,1,3],[1,3,1]],[[3,1,3],[1,3,1],[3,1,3]],...
(implicit output)
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 111 bytes
```
param($a)($s=1..($a*$a))|%{$b++
-join($s|%{"1$a"[($_+$b)%2]
.($g={if(!($_%$a)){$args;$b+=1-$a%2}})' '})
.$g ''}
```
[Try it online!](https://tio.run/##NYtNDsIgEEb3cwokg4ANTUB3hpMYY6hpa5tqG7pwgZwdR5Pu3vt@lvndxvXRTpO5z7Et2PlUlhDDU2HQCldv65rwQKY/ImFTVWDGeXhRR84tBn5ReKuw0cJdgca9T0OndhSK3ythiP16pqe3BoNwOWvJZNZQY8@kzCUD7LFjFjj/g9vguMEJyhc "PowerShell Core – Try It Online")
-2 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy)!
-9 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy) again!
[Answer]
# [PHP](https://php.net/), 129 bytes
```
for(;$a++<$n=$argn;){for($b=0;$b++<$n;){for($c=0;$c++<$n;){for($d=0;$d++<$n;)echo($a+$b+$c+$d)%2?$n:1;echo" ";}echo"
";}echo"
";}
```
I feel like there's probably a way that this could be done better with a recursive function, but I can't wrap my head around it.
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVErW1bVTybFUSi9LzrDWrQYIqSbYG1ipJYAmYUDJIKBlFKAUklAIVSk3OyNcAGgbUBlSmkqKpamSvkmdlaA2SUFJQsq4FM7iQGf//m/zLLyjJzM8r/q/rBgA "PHP – Try It Online")
] |
[Question]
[
The *xorspace* of a set of integers is the set of all integers that can be obtained by combining the starting integers with the usual bitwise xor operator (`^`). For example, the xorspace of `(8, 4)` is `(0, 4, 8, 12)`: 0 is 4^4, 12 is 4^8, and no other numbers can be reached. Note that the starting numbers are always included, by this definition (for example, 4 is 4^4^4).
Your goal is to write the shortest program that takes a list of non-negative integers as input, and outputs the number of elements in their xorspace.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Input and output can be in any of the [usual formats](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Input is guaranteed to be valid, non-empty, and without duplicates.
* **Your code should be able to process all test cases in less than a day**.
### Test cases
```
Input: 0
Output: 1
Input: 6
Output: 2
Input: 8 4
Ouput: 4
Input: 0 256
Output: 2
Input: 256 259 3
Output: 4
Input: 60 62 94 101 115
Output: 32
Input: 60 62 94 101 115 40 91
Output: 32
Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
Output: 64
Input: 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384
Output: 32768
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
t"G!Z~Ghu]n
```
[Try it online!](https://tio.run/##y00syfn/v0TJXTGqzj2jNDbv//9oMwMFMyMFSxMFQwNDBUND01gA "MATL – Try It Online")
The last test case doesn't run in the online interpreter because of memory limitations, but runs offline in less than 2 seconds on a modern computer.
### Explanation
For input of size `n`, this does the following:
1. Initiallize result to input.
2. Repeat `n` times:
1. Apply bitwise XOR to all pair of entries from current result and input.
2. Attach input values to the result.
3. Deduplicate.
3. The output is the number of elements of the final result.
Commented code.
```
t % Implicit input: row vector. Duplicate
" % For each (i.e. do as many times as the input size)
G! % Push input as a column vector
Z~ % Bitwise XOR with broadcast, i.e. for all pairs of entries of the
% two arguments. The first argument is the accumulated result
% from the previous iteration, the second is the input vector
G % Push input again
h % Postpend
u % Unique values. Gives a row vector
] % End
n % Number of entries. Implicitly display
```
### Example
The intermediate results (steps 2.1 and 2.3) for input `[256 259 3]` are:
First iteration: `[256 259 3]` with `[256 259 3]`: computing all pairs of bitwise-XOR gives the matrix
```
0 3 259
3 0 256
259 256 0
```
Attaching `[256 259 3]` and deduplicating
```
0 3 259 256
```
Second iteration: current result `[0 3 259 256]` with `[256 259 3]`. After deduplicating this again gives
```
0 3 259 256
```
Third iteration: again
```
0 3 259 256
```
So the output is `4` (number of entries of result).
[Answer]
# [Haskell](https://www.haskell.org/), 64 bytes
`f` takes a list of integers and returns an integer.
```
import Data.Bits
f l|m<-maximum l,m>0=2*f(min<*>xor m<$>l)|0<1=1
```
[Try it online!](https://tio.run/##ZY89b8IwEIZ3/4p3YABUIp@/YqOQoerSub/AagNYjROUBMHAf6dn1g6WrbvzPc97jvNv1/fPZ8qXcVrwEZdYvadlFkf0j9zscrynfM3o33IrD2p7XOc0NNv2Pk7IzartNw/Z0IGeOabhkIalm@L3sroOfRq6ucrxsp7P4606vp5TF3/2@69lSsNp137y9KmbNtVtnH7mTfX68pTCCQ8jJJR1gg/fAVo4CacQDEgSiOy/AoxEIEFQ0DCwcKjhEbjPbZACaRCPW5AD1SAPClAM4j8KSkMZhkExsobyUMyV0ATNKzW0gbbQDrqG9tChEA3BKBgmGhh2cDA1DAcIsBKWYBWshmUhCw5ja1gPTlT0qSRw@uVs2JW9GOXYsdDLdLGWRUuWnTI4eApcc9ob8Qc "Haskell – Try It Online")
This doesn't handle an empty list, for that you can but `$0:` instead of the space after `maximum`.
# How it works
* If the maximum `m` of the list is zero, returns 1.
* Otherwise, xors every element with the maximum.
+ If the result is smaller than the element, the element is replaced by it.
+ This necessarily zeroes the most significant bit set anywhere in the list.
+ Then recurses on the resulting list, doubling the result of the recursion.
* This process essentially performs [Gaussian elimination](https://en.wikipedia.org/wiki/Gaussian_elimination) (although throwing away the final rows by setting them to 0) modulo 2, on the matrix whose rows are the bit representations of the list of numbers. The set of bit representations of the "xorspace" is the vector space modulo 2 spanned by the rows of this matrix, and whose number of elements is 2 to the power of the matrix's row rank.
* This algorithm is polynomial time, so should definitely be better than O(2^n).
[Answer]
# Mathematica, 52 bytes
```
2^MatrixRank[PadLeft@IntegerDigits[#,2],Modulus->2]&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
vDy^ìÙ}g
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/zKUy7vCawzNr0///jzYz0FEwM9JRsDTRUTA0MAQShqY6CiZAUUvDWAA "05AB1E – Try It Online")
All test-cases finish in under 1 minute on TIO.
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
r={0}
for n in input():r|={x^n for x in r}
print len(r)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8i22qCWKy2/SCFPIROECkpLNDStimpsqyvi8hRAEhUgiaJaroKizLwShZzUPI0izf//o80MdBTMjHQULE10FAwNDIGEoamOgglQ1NIwFgA "Python 2 – Try It Online")
Beats out functions:
```
f=lambda l,r={0}:l and f(l[1:],r|{x^l[0]for x in r})or len(r)
f=lambda l:len(reduce(lambda r,n:r|{x^n for x in r},l,{0}))
```
---
Ørjan Johansen's [beautiful row elimination method](https://codegolf.stackexchange.com/a/124797/20260) is one byte shorter.
**[Python 2](https://docs.python.org/2/), 54 bytes**
```
f=lambda l:1-any(l)or 2*f([min(x,x^max(l))for x in l])
```
[Try it online!](https://tio.run/##DchBCoQwDADAr@SYSBZMcQUFXyIKlaVsoY1FKtTX117mMOnJ/1NNrW4JNh4/C2GWj9UHA50XmM7hGr1i4bJHW9qSa1/AK4SNarq8ZnDoNd0Zieo69gyjYZgGBumlIV@Goe0k2ws "Python 2 – Try It Online")
[Answer]
# Pyth, 8 bytes
```
lu{+xM*Q
```
[Test suite](https://pyth.herokuapp.com/?code=lu%7B%2BxM%2aQ&test_suite=1&test_suite_input=%5B0%5D%0A%5B6%5D%0A%5B8%2C+4%5D%0A%5B0%2C+256%5D%0A%5B256%2C+259%2C+3%5D%0A%5B60%2C+62%2C+94%2C+101%2C+115%5D%0A%5B60%2C+62%2C+94%2C+101%2C+115%2C+40%2C+91%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%2C+11%2C+12%2C+13%2C+14%2C+15%2C+16%2C+17%2C+18%2C+19%2C+20%2C+21%2C+22%2C+23%2C+24%2C+25%2C+26%2C+27%2C+28%2C+29%2C+30%2C+31%2C+32%2C+33%2C+34%2C+35%2C+36%2C+37%2C+38%2C+39%2C+40%2C+41%2C+42%2C+43%2C+44%2C+45%2C+46%2C+47%2C+48%2C+49%2C+50%2C+51%2C+52%2C+53%2C+54%2C+55%2C+56%2C+57%2C+58%2C+59%2C+60%2C+61%2C+62%2C+63%5D&debug=0)
Explanation:
To generate the xorspace, we find the fixpoint of taking the xor of every pair of numbers, adding in every number, and deduplicating. Then, we take the length of the result. This runs in 20 seconds (offline only) on the final test case.
```
lu{+xM*Q
lu{+xM*QGGQ Implicit variable introduction
u Q Find the fixed point of the following, starting with the input,
where the current value is G.
*QG Form the Cartesian product of Q (input) and G (current)
xM Take the xor of every pair
+ Add the current values
{ Deduplicate
l Output the length of the result.
```
---
# [Packed Pyth](https://github.com/isaacg1/pyth/blob/master/packed-pyth.py), 7 bytes
Hexdump:
```
0000000: d9d7 dabf 1355 51 .....UQ
```
The same as the above, with a 7-bit ASCII encoding.
Put the above in a file with `xxd -r`, and run it as follows:
```
py packed-pyth.py xorspace.ppyth '[256, 259, 3]'
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
0œ|⁺^¥/L
```
Finishes all test cases in under **8** seconds on TIO, with negligible memory requirements.
[Try it online!](https://tio.run/##y0rNyan8/9/g6OSaR4274g4t1ff5f7j9UdOayP//o6MNYnW4FKLNwKSFjoIJmGGgo2BkChED0iCOpY6CMUQlUM7MSEfB0kRHwdDAEEgYmuKUAJoHFLU0BCkoSsxLT9UAipuZaAK5uYkFGhpGmnrx8QX55fHxOjB5U01NrlgA "Jelly – Try It Online")
### How it works
```
0œ|⁺^¥/L Main link. Argument: A (array)
0œ| Perform multiset union with 0, prepending 0 if A doesn't contain it.
/ Reduce A by the link to the left.
¥ Combine the previous two links into a dyadic chain.
Left argument: V (array). Right argument: n (integer)
^ Bitwise XOR each element in V with n.
⁺ This quick refers to the previous link, making it a shorthand for
the link 'œ|'. Thus, it performs multiset union on V and the array
of bitwise XORs.
L Compute the length of the result.
```
[Answer]
# Python, 113 bytes
```
def f(x):
u,s=[0],{0}
while u:
a=u.pop()
for b in x:
c=a^b
if c not in s:u+=[c]
s.add(c)
return len(s)
```
] |
[Question]
[
An algebraic curve is a certain "1D subset" of the "2D-plane" that can be described as set of zeros `{(x,y) in R^2 : f(x,y)=0 }`of a polynomial `f`. Here we consider the 2D-plane as the real plane `R^2` such that we can easily imagine what such a curve could look like, basically a thing you can draw with a pencil.
Examples:
* `0 = x^2 + y^2 -1` a circle of radius 1
* `0 = x^2 + 2y^2 -1` an ellipse
* `0 = xy` a *cross* shape, basically the union of the x-axis and the y-axis
* `0 = y^2 - x` a parabola
* `0 = y^2 - (x^3 - x + 1)` an [elliptic curve](https://codegolf.stackexchange.com/questions/75786/addition-on-elliptic-curves)
* `0 = x^3 + y^3 - 3xy` the folium of Descartes
* `0 = x^4 - (x^2 - y^2)` a lemniscate
* `0 = (x^2 + y^2)^2 - (x^3 - 3xy^2)` a trifolium
* `0 = (x^2 + y^2 - 1)^3 + 27x^2y^2` an astroid
### Task
Given a polynomial `f` (as defined below), and the x/y-ranges, output an black and white image of at least 100x100 pixels that shows the curve as black line on a white background.
### Details
**Color**: You can use any two other colours of your choice, it should just be easy to tell them apart.
**Plot**: Instead of a pixel image you can also output this image as ascii-art, where the background "pixels" should be space/underline or an other character that "looks empty" and the line can be made of a character that looks "full" like `M` or `X` or `#`.
You do not have to worry about aliasing.
You only need to plot lines where the sign of the polynomial changes from one side of the line to the other (that means you could e.g. use the marching square algorithm), you do not have to correctly plot "pathological cases like `0 = x^2` where the sign does *not* change when going from one side of the line to the other. But the line should be continuous and separating the regions of the different signs of `f(x,y)`.
**Polynomial**: The polynomial is given as a `(m+1) x (n+1)` matrix/list of lists of (real) coefficients, in the example below the terms of the coefficients are given in their position:
```
[ 1 * 1, 1 * x, 1 * x^2, 1 * x^3, ... , 1 * x^n ]
[ y * 1, y * x, y * x^2, y * x^4, ... , y * x^n ]
[ ... , ... , ... , ... , ... , ... ]
[ y^m * 1, y^m * x, y^m * x^2, y^m * x^3 , ..., y^m * x^n]
```
If you prefer, you can assume the matrix to be square (which can always be done with the necessary zero-padding), and if you want, you can also assume that the size of the matrix is given as aditional inputs.
In the following, the examples from above are represented as a matrix defined like this:
```
Circle: Ellipse: Parabola: Cross: Elliptic Curve: e.t.c
[-1, 0, 1] [-1, 0, 1] [ 0,-1] [ 0, 0] [-1, 1, 0,-1]
[ 0, 0, 0] [ 0, 0, 0] [ 0, 0] [ 0, 1] [ 0, 0, 0, 0]
[ 1, 0, 0] [ 2, 0, 0] [ 1, 0] [ 1, 0, 0, 0]
```
Test cases with x-range / y-range:
(In a not so readable but better copy-paste-able format available [here on pastebin](http://pastebin.com/1DPkjZHP).)
```
Circle:
[-1, 0, 1] [-2,2] [-2,2]
[ 0, 0, 0]
[ 1, 0, 0]
Ellipse:
[-1, 0, 1] [-2,2] [-1,1]
[ 0, 0, 0]
[ 2, 0, 0]
Cross:
[ 0, 0] [-1,2] [-2,1]
[ 0, 1]
Parabola:
[ 0,-1] [-1,3] [-2,2]
[ 0, 0]
[ 1, 0]
Elliptic Curve:
[-1, 1, 0,-1] [-2,2] [-3,3]
[ 0, 0, 0, 0]
[ 1, 0, 0, 0]
Folium of Descartes:
[ 0, 0, 0, 1] [-3,3] [-3,3]
[ 0, -3, 0, 0]
[ 0, 0, 0, 0]
[ 1, 0, 0, 0]
Lemniscate:
[ 0, 0, -1, 0, 1] [-2,2] [-1,1]
[ 0, 0, 0, 0, 0]
[ 1, 0, 0, 0, 0]
Trifolium:
[ 0, 0, 0,-1, 1] [-1,1] [-1,1]
[ 0, 0, 0, 0, 0]
[ 0, 3, 2, 0, 0]
[ 0, 0, 0, 0, 0]
[ 1, 0, 0, 0, 0]
Astroid:
[ -1, 0, 3, 0, -3, 0, 1] [-1,1] [-1,1]
[ 0, 0, 0, 0, 0, 0, 0]
[ 3, 0, 21, 0, 3, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ -3, 0, 3, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 1, 0, 0, 0, 0, 0, 0]
```
I've got the inspiration for some curves from [this pdf.](https://elepa.files.wordpress.com/2013/11/fifty-famous-curves.pdf)
[Answer]
# Haskell, ~~283~~ 275 bytes
The function `g` should be called with the matrix and the two ranges as arguments. The matrix is just a list of lists, the ranges each a two element list.
```
import Data.List
t=transpose
u=tail
z=zipWith
l%x=sum$z(*)l$iterate(*x)1 --generate powers and multiply with coefficients
e m y x=[l%x|l<-m]%y --evaluate the encoded polynomial
a#b=[a,a+(b-a)/102..b] --create a range
g m[u,w][i,j]=unlines$v[map((0<).e m y)$u#w|y<-i#j] --evaluate the function on the grid, get the sign
f g=u[u$u$map fst$scanl(\(r,l)c->(c==l,c))(1<0,1<0) l|l<-g] --find +- or -+ transitions within lines
a&b|a&&b=' '|0<1='#' --helper function for creating the string
v g=z(z(&))(f g)(t$f$t g) --create the string
```
Here the outputs for the more interesting cases: Note that I had to downsize the resultion from 100x100 to about 40x40 such that it sill fits in the console (just change the hardcoded 102 to a smaller number). Also note that the y-axis is pointing downwards.

[Answer]
# Matlab, ~~114~~ ~~100~~ 92 bytes
The right tool for the job? I use the interesting way Matlab does `printf` to generate a polynomial as a string. This polynomial can be provided to `ezplot` which plots the implicit curve on the specified domain. For readability the code is presented with newlines after ; which isn't needed and isn't counted towards the size.
```
function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%.0f*y^%d',[A(:)';t/h;rem(t,h)]),[W,H])
```
---
## Golfing progress as expandable snippet.
```
Iteration 1, clean arguments, 114 bytes
---------------------------------------
function P(A,W,H)
h=size(A,1);
t=0:numel(A)-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H])
Iteration 1.5, historical revisionism (thanks @flawr), 111 bytes
--------------------------------------------------------------
function P(A,W,H)
[h,w]=size(A);
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H])
Iteration 2, playing dirty, 100 bytes
-------------------------------------
The code can be golfed further if I use that taking matrix sizes as inputs are
fair game, but it feels sad to ruin such neat input arguments. However,
this is code golf and I'll abuse anything I can and I end up at a nice 100 bytes:
function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H]);
Iteration 2.5, fix your code (thanks @LuisMendo), 98 bytes
----------------------------------------------------------
function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';fix(t/h);rem(t,h)]),[W,H]);
Iteration 3, more power to printf, 92 bytes [current best]
----------------------------------------------------------
Use `%.0f` instead of `fix`/`floor`.
function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%.0f*y^%d',[A(:)';t/h;rem(t,h)]),[W,H])
```
---
Output of the test cases (click for full view):
[](https://i.stack.imgur.com/gL6qy.png)
[Answer]
# Python 2, 261 bytes
```
E=enumerate
M,[a,c],[b,d]=input()
e=(c-a)/199.
I=200
J=-int((b-d)/e-1)
print'P2',I,J,255
i=I*J
while i:i-=1;x,y=c-i%I*e,b+i/I*e;u,v,w=map(sum,zip(*((z*p/x,z*q/y,z)for q,R in E(M)for p,t in E(R)for z in[t*x**p*y**q])));print int(255*min(1,(w*w/(u*u+v*v))**.5/e))
```
Input format: `matrix,xbounds,ybounds` (e.g. `[[-1,0,1],[0,0,0],[1,0,0]],[-2,2],[-2,2]`). Output format: [plain PGM](http://netpbm.sourceforge.net/doc/pgm.html).
This estimates the distance from every pixel center to the curve using the first-order approximation *d*(*x*, *y*) = |*p*(*x*, *y*)| / |∇*p*(*x*, *y*)|, where ∇*p* is the gradient of the polynomial *p*. (This is the distance from (*x*, *y*) to the intersection of the tangent plane at (*x*, *y*, *p*(*x*, *y*)) with the *xy*–plane.) Then the pixels where *d*(*x*, *y*) is less than one pixel width of the curve proportionally to *d*(*x*, *y*), resulting in nice antialiased lines (even though that isn’t a requirement).
[](https://i.stack.imgur.com/uicKV.png)
Here are the [same graphs with the distance function divided by 16](https://i.stack.imgur.com/HekPI.png) to make it visible.
[Answer]
# Python 3.5 + MatPlotLib + Numpy, 352 bytes:
```
from matplotlib.pyplot import*;from numpy import*
def R(M,S,U,r=range):N=linspace;E='+'.join([str(y)+'*'+m for y,m in[q for i,g in zip(M,[[i+'*'+p for p in['1']+['x^%d'%p for p in r(1,len(M[0]))]]for i in['1']+['y^%d'%i for i in r(1,len(M))]])for q in zip(i,g)if q[0]]]);x,y=meshgrid(N(*S,200),N(*U,200));contour(x,y,eval(E.replace('^','**')),0);show()
```
A named function. Pretty long, but hey, I'm just happy I was able to accomplish the task. Takes 3 inputs, which are the `m by n` matrix, the `x`-range, and `y`-range, which should all be in arrays (for example, `[[-1,0,1],[0,0,0],[1,0,0]],[-2,2],[-2,2]`). Outputs the completed graph in a new, graphical, interactive window. Will golf this down more of time when I can, but for now, I'm happy with it.
**Final Outputs for the Test Cases:**
[](https://i.stack.imgur.com/MNTLz.png)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~67~~ 61 bytes
```
8Wt:qwq/t2:"wid*2M1)+i:q!^]!2&!w[1IK2]&!**ss&eZS5Y62&Y+|4=0YG
```
This code runs in release 18.5.0 of the language, which precedes the challenge. Input uses the optional `m`, `n` parameters. The matrix has semicolons as row separators. The exact input format (using the parabola as an example) is
```
[-1,3]
3
[-2,2]
2
[0,-1; 0, 0; 1, 0]
```
The code produces an **image** with size 255×255. This can be tested using [@Suever](https://codegolf.stackexchange.com/users/51939/suever)'s **MATL Online** compiler, which, among other very interesting features, includes graphical output. See for example
* [Elliptic curve](https://matl.suever.net/?code=8Wt%3Aqwq%2Ft2%3A%22wid%2a2M1%29%2Bi%3Aq%21%5E%5D%212%26%21w%5B1IK2%5D%26%21%2a%2ass%26eZS5Y62%26Y%2B%7C4%3D0YG&inputs=%5B-2%2C2%5D%0A3%0A%5B-3%2C3%5D%0A4%0A%5B-1%2C+1%2C+0%2C-1%3B+0%2C+0%2C+0%2C+0%3B+1%2C+0%2C+0%2C+0%5D&version=18.5.0);
* [Folium of Descartes](https://matl.suever.net/?code=8Wt%3Aqwq%2Ft2%3A%22wid%2a2M1%29%2Bi%3Aq%21%5E%5D%212%26%21w%5B1IK2%5D%26%21%2a%2ass%26eZS5Y62%26Y%2B%7C4%3D0YG&inputs=%5B-3%2C3%5D%0A4%0A%5B-3%2C3%5D%0A4%0A%5B0%2C++0%2C++0%2C++1%3B+0%2C+-3%2C++0%2C++0%3B+0%2C++0%2C++0%2C++0%3B+1%2C++0%2C++0%2C++0%5D&version=18.5.0).
This compiler is still in an experimental stage. Please report any issues to @Suever in the [MATL chatroom](https://chat.stackexchange.com/rooms/39466/matl-chatl). If the "Run" button doesn't work, try refreshing the page and clicking again.
If you prefer **ASCII output**, the code needs to be modified a little (the changes only affect the first two and last four characters of the code above):
```
101t:qwq/t2:"wid*2M1)+i:q!^]!2&!w[1IK2]&!**ss&eZS5Y62&Y+|4<42*c
```
This produces a 100×100 ASCII grid which uses character `*` to represent the curve. You can also test this with [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis)' **Try it online!** platform:
* [Elliptic curve](http://matl.tryitonline.net/#code=MTAxdDpxd3EvdDI6IndpZCoyTTEpK2k6cSFeXSEyJiF3WzFJSzJdJiEqKnNzJmVaUzVZNjImWSt8NDw0Mipj&input=Wy0yLDJdCjMKWy0zLDNdCjQKWy0xLCAxLCAwLC0xOyAwLCAwLCAwLCAwOyAxLCAwLCAwLCAwXQ);
* [Folium of Descartes](http://matl.tryitonline.net/#code=MTAxdDpxd3EvdDI6IndpZCoyTTEpK2k6cSFeXSEyJiF3WzFJSzJdJiEqKnNzJmVaUzVZNjImWSt8NDw0Mipj&input=Wy0zLDNdCjQKWy0zLDNdCjQKWzAsICAwLCAgMCwgIDE7IDAsIC0zLCAgMCwgIDA7IDAsICAwLCAgMCwgIDA7IDEsICAwLCAgMCwgIDBd).
Note that the aspect ratio of ASCII output is altered because the characters are slightly higher than are wide.
### Explanation
The code first computes the two-variable polynomial on an *x*-*y* grid. This makes heavy use of [broadcasting](https://www.gnu.org/software/octave/doc/v4.0.0/Broadcasting.html), computing an intermediate 4D array where each dimension represents *x* values, *y* values, *x* exponents, *y* exponents respectively.
From that function, the zero level line is computed. Since the challenge specifes that only sign changes need to be detected, the code applies [2D convolution](https://en.wikipedia.org/wiki/Kernel_(image_processing)) with a 2×2 block of ones, and marks a pixel as belonging to the line if not the four values of the block have the same sign.
```
8W % Push 2^8, that is, 256. (The ASCII-output version pushes 101 instead)
t:q % Duplicate. Push range [0 1 ... 255]
wq % Swap. Subtract 1 to obtain 255
/ % Divide. Gives normalized range [0 1/255 2/255... 1]
t % Duplicate
2:" % For loop: do this twice
w % Swap top two elements in the stack
i % Input two-number array defining x range (resp. y in second iteration)
d % Difference of the two entries
* % Multiply by normalized range
2M1) % Push the array again and get its first entry
+ % Add. This gives the range for x values (resp. y)
i % Input m (n in second iteration)
:q % Range [0 1 ...m-1] (resp. [0 1 ...n-1])
! % Convert to column array
^ % Power, element-wise with broadcast. This gives a matrix of size m×256
% (resp. n×256) of powers of x (resp. y) for the range of values computed
% previously
] % End for loop
! % Transpose. This transforms the n×256 matrix of powers of y into 256×n
2 % Push 2
&! % Permute dimensions 1 and 3: transforms the 256×n matrix into a 4D array
% of size 1×n×256×1
w % Swap top two elements in the stack: bring 256×m matrix to top
[1IK2] % Push vector [1 3 4 2]
&! % Permute dimensions as indicated by the vector: transforms the m×256 matrix
% into a 4D array of size m×1×1×256
* % Multiply element-wise with broadcast: gives 4D array of size m×n×256×256
% with mixed powers of x and y for at the grid of x, y values
* % Implicitly input m×n matrix. Multiply element-wise with broadcast: gives
% 4D array of size m×n×256×256
ss % Sum along first two dimensions: gives 4D array of size 1×1×256×256
&e % Squeeze singleton dimensions: gives matrix of size 256×256. This is the
% two-variable polynomial evaluated at the x, y grid.
% Now we need to find the zero level curve of this function. We do this by
% detecting when the sign of the function changes along any of the two axes
ZS % Matrix of sign values (1, 0 or -1)
5Y6 % Predefined literal: matrix [1 1; 1 1]
2&Y+ % Compute 2D convolution, keeping only the valid (central) part
|4= % True if absolute value of result is 4, which indicates no sign changes.
% (The ASCII version computes a negated version of this, for better display)
0YG % Display as image. (The ASCII-output version does the following instead:
% multiply by 42 and convert to char. 42 is ASCII for '*', and character 0
% is shown as space. The 2D char array is then implicitly displayed)
```
### All test cases
Here are all inputs in the appropriate format, in case you want to try:
```
Circle:
[-2,2]
3
[-2,2]
3
[-1, 0, 1; 0, 0, 0; 1, 0, 0]
Ellipse:
[-2,2]
3
[-1,1]
3
[-1, 0, 1; 0, 0, 0; 2, 0, 0]
Cross:
[-1,2]
2
[-2,1]
2
[0, 0; 0, 1]
Parabola:
[-1,3]
3
[-2,2]
2
[0,-1; 0, 0; 1, 0]
Elliptic Curve:
[-2,2]
3
[-3,3]
4
[-1, 1, 0,-1; 0, 0, 0, 0; 1, 0, 0, 0]
Folium of Descartes:
[-3,3]
4
[-3,3]
4
[0, 0, 0, 1; 0, -3, 0, 0; 0, 0, 0, 0; 1, 0, 0, 0]
Lemniscate:
[-2,2]
3
[-1,1]
5
[0, 0, -1, 0, 1; 0, 0, 0, 0, 0; 1, 0, 0, 0, 0]
Trifolium:
[-1,1]
5
[-1,1]
5
[0, 0, 0,-1, 1; 0, 0, 0, 0, 0; 0, 3, 2, 0, 0; 0, 0, 0, 0, 0; 1, 0, 0, 0, 0]
Astroid
[-1,1]
7
[-1,1]
7
[-1, 0, 3, 0, -3, 0, 1; 0, 0, 0, 0, 0, 0, 0; 3, 0, 21, 0, 3, 0, 0; 0, 0, 0, 0, 0, 0, 0; -3, 0, 3, 0, 0, 0, 0; 0, 0, 0, 0, 0, 0, 0; 1, 0, 0, 0, 0, 0, 0]
```
] |
[Question]
[
Given a string, consisting of a prefix and then "illion", convert this number into standard form.
For example:
```
"million" -> 10^6
"trillion" -> 10^12
"quattuordecillion" -> 10^45
```
The program needs to be able to handle input going up to Centillion, which is 10^303. A list of names and their standard form values can be found [here](http://polytope.net/hedrondude/illion.htm) - note that this gives values for every 10^3 increment up to 10^63, but then gives them in 10^30 increments, however the pattern is fairly straightforward.
The program needs to handle all 100 cases (even the ones not explicitly given by the website provided) - here are some examples of this:
```
"sexvigintillion" -> 10^81
"unnonagintillion" -> 10^276
"octotrigintillion" -> 10^117
```
Input can be given via STDIN, function argument or hard-coded as a string.
This is code-golf, so shortest code wins!
[Answer]
# Python 2 (~~384~~ ~~368~~ ~~365~~ ~~348~~ 347 bytes)
```
def c(s):
s=s[:-6].replace('int','');k=0;d=dict(un=1,doe=2,tre=3,quattuor=4,quin=5,sex=6,septen=7,octo=8,novem=9,b=3,tr=4,quadr=5,qu=6,sext=7,sept=8,oct=9,non=10,dec=11,vig=21,trig=31,quadrag=41,quinquag=51,sexag=61,septuag=71,octog=81,nonag=91,cent=101)
for p in(s!='m')*list(d)*2:
if s.endswith(p):s=s[:-len(p)];k+=3*d[p]
return 10**(k or 6)
```
(The `if` line is indented with a single tab, and the rest with single spaces.)
Here `c('million') == 10**6` has to be a special case because `'novem'` also ends in `'m'`.
Examples:
```
c('million') == 10**6
c('trillion') == 10**12
c('quattuordecillion') == 10**45
c('novemnonagintillion') == 10**300
c('centillion') == 10**303
```
Thanks to Falko for obfuscating it down to 350 bytes.
---
For practice I tried rewriting this as a one-liner using lambdas. It's ~~404~~ ~~398~~ ~~390~~ ~~384~~ ~~380~~ 379 bytes:
```
c=lambda s:(lambda t=[s[:-5].replace('gint',''),0],**d:([t.__setslice__(0,2,[t[0][:-len(p)],t[1]+3*d[p]])for p in 2*list(d)if t[0].endswith(p)],10**t[1])[1])(un=1,doe=2,tre=3,quattuor=4,quin=5,sex=6,septen=7,octo=8,novem=9,mi=2,bi=3,tri=4,quadri=5,qui=6,sexti=7,septi=8,octi=9,noni=10,deci=11,vii=21,trii=31,quadrai=41,quinquai=51,sexai=61,septuai=71,octoi=81,nonai=91,centi=101)
```
[Answer]
## JS (ES6), ~~292~~ 270
Understands only the numbers written in the given list. The OP isn't clear about the others.
```
z=b=>{a="M0B0Tr0Quadr0Quint0Sext0Sept0Oct0Non0Dec0Undec0Doedec0Tredec0Quattuordec0Quindec0Sexdec0Septendec0Octodec0Novemdec0Vigint0Trigint0Quadragint0Quinquagint0Sexagint0Septuagint0Octogint0Nonagint0Cent".split(0);for(i in a)if(~b.indexOf(a[i]))return"10^"+(20>i?3*i+6:93+30*(i-20))}
```
Example:
```
z("Billion") // "10^9"
z("Centillion") // "10^303"
```
[Answer]
# C, 235
Handles all 100 cases.
Program uses stdin and stdout.
Who needs regexes for camel-case splitting?
```
char*Z="UUUi+W<)E(<7-7-++*)('&%$,*$&%$",u[999]="\0MBRilDriPtiNiUnOeReTtUiXTeCtVeCiGRigRaUagInquiXaXsexPtuOgOoNaCeCeK1",s[99],*U=u+67;
main(n){
for(gets(s);*--U;)
*U<95?
*U|=32,
n+=!!strstr(s,U)*(*Z++-35),
*U=0:
3;puts(memset(u+68,48,3*n)-1);
}
```
### Example
```
octoseptuagintillion
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
[Answer]
# Clojure, 381 377 bytes
```
(defn c[x](let[l{"M"6"B"9"Tr"12"Quadr"15"Quint"18"Sext"21"Sept"24"Oct"27"Non"30"Dec"33"Undec"36"Doedec"39"Tredec"42"Quattuordec"45"Quindec"48"Sexdec"51"Septendec"54"Octodec"57"Novemdec"60"Vigint"63"Trigint"93"Googol"100"Quadragint"123"Quinquagint"153"Sexagint"183"Septuagint"213"Octogint"243"Nonagint"273"Cent"303}v(l(clojure.string/replace x #"illion$" ""))](Math/pow 10 v)))
```
Example:
`(c "Septuagintillion") ;; 1.0E213`
[Answer]
# Haskell, 204 bytes (+9 for formatted String)
```
import Data.List
x s=10^(f$[a|k<-tails s,i<-inits k,(b,a)<-zip["ce","ad","un","do","b","mi","vi","tr","at","ui","x","p","oc","no","ec","g"]$100:4:1:2:2:[1..],b==i])
f[]=3
f(x:11:r)=30*x+f r
f(x:r)=3*x+f r
```
In GHCi:
```
*Main> x "decillion"
1000000000000000000000000000000000
```
Replacing `10^(` with `"10^"++(show.` adds another 9 bytes:
```
import Data.List
x s="10^"++(show.f$[a|k<-tails s,i<-inits k,(b,a)<-zip["ce","ad","un","do","b","mi","vi","tr","at","ui","x","p","oc","no","ec","g"]$100:4:1:2:2:[1..],b==i])
f[]=3
f(x:11:r)=30*x+f r
f(x:r)=3*x+f r
```
In GHCi:
```
*Main> x "decillion"
"10^33"
```
**Edit:** I had to correct for `"quinquagintillion"` which contains `"qua"`.
] |
[Question]
[
You may have seen this one in *Die Hard: With a Vengeance*... This question is based on the famous 3 and 5 Litre Jug Puzzle, but with a slightly different slant.
Golf up some code that when given an integer between 1 and 100 will provide you with the quickest instructions to measure out into a tank, the corresponding number of litres of water from a fountain, using a 3 litre jug and a 5 litre jug.
There are no gradations on either of the jugs; the fountain is abundant in supply of water, and the tank is assumed to be emptied out upon the start of each execution of the code.
You cannot access water from the tank once it goes into the tank.
The format of execution is as follows:
**Input:**
`4` for example.
**Output**
Output each numbered step, as shown, followed by a tally of the volumes of the 5L jug, the 3L jug and the tank. Tally format also shown below. The number of steps must also be outputted at the end of the steps.
`1) Fill 5L jug`
`5L: 5, 3L: 0, T: 0`
`2) Pour from 5L jug into 3L jug`
`5L: 2, 3L: 3, T: 0`
`3) Empty 3L jug`
`5L: 2, 3L: 0, T: 0`
`4) Pour from 5L jug into 3L jug`
`5L: 0, 3L: 2, T: 0`
`5) Fill 5L jug`
`5L: 5, 3L: 2, T: 0`
`6) Pour from 5L jug into 3L jug`
`5L: 4, 3L: 3, T: 0`
`7) Pour from 5L jug into tank`
`5L: 0, 3L: 3, T: 4`
`Volume measured out in 7 turns`
Example 2
Input: `8`
Output:
`1) Fill 5L jug`
`5L: 5, 3L: 0, T: 0`
`2) Pour from 5L jug into tank`
`5L: 0, 3L: 0, T: 5`
`3) Fill 3L jug`
`5L: 0, 3L: 3, T: 5`
`4) Pour from 3L jug into tank`
`5L: 0, 3L: 0, T: 8`
`Volume measured out in 4 turns`
**Conventions**
1. `Fill xL jug` - fills the associated jug to the top from the fountain
2. `Empty xL jug` - empties the contents of the associated jug into the fountain
3. `Pour from xL jug into yL jug` - Pours the contents of the xL jug into the yL jug
4. `Pour from xL jug into tank` - Pours the contents of the xL jug into the tank
Shortest code wins.
[Answer]
## Ruby, ~~407~~ ~~376~~ ~~365~~ ~~331~~ ~~324~~ 323
This is getting kind of hard to read...
```
x=y=n=d=0
g=gets.to_i
"#{[43435,102,t=45,t,12,t,12,t,t][g+~d]||12}".chars{|c|n+=1
puts [eval(["x-=t=[3-y,x].min;y+=t"+t=";'Pour from 5L jug into 3L jug'","x=5;'Fill 5L jug'","d+=x;x=0"+t.sub(/3.+/,"tank'")][c.ord%3].tr t='35xy',c<?3?t:'53yx'),"5L: #{x}, 3L: #{y}, T: #{d}"]}while g>d
$><<"Volume measured out in #{n} turns"
```
Takes input on STDIN. Example run for N=10:
```
Fill 5L jug
5L: 5, 3L: 0, T: 0
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 5
Fill 5L jug
5L: 5, 3L: 0, T: 5
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 10
Volume measured out in 4 turns
```
[Answer]
# T-SQL 2012: ~~1410~~ 1302
Another quixotic attempt at a question in SQL, but this one offered an enjoyable opportunity to play with some of the new window function options in version 2012. In addition, it exploits recursive CTEs, which may be nothing impressive in most programming languages, but recursion in SQL is like switching from horse and buggy to a Ferrari.
The engine at the heart of this is in lines 5-12, which uses a recursive CTE and a window function to build a table of most of the numbers needed to solve the problem. Note in particular the test for 3, 4, 6, or 9, which ensures an optimal approach to the solution by 3s from those numbers onward. (Technically, it's a tie for 4 between the 3-1 approach and the 2-2, but doing it this way golfed me a lot of characters.) Then it's a simple matter to join to a lookup table of the optimal steps for different chunks of the problem and use another window function to properly number the steps.
If you don't have MS SQL lying around, [play with it on SQLFiddle.](http://sqlfiddle.com/#!6/d41d8/15050)
```
DECLARE @i INT=42,@l VARCHAR(9)='L jug ',@k VARCHAR(99)='into tank
5L: 0, 3L: 0, T: ',@o VARCHAR(99)='
5L: 5, 3L: 0, T: ',@n CHAR(1)='
',@5 VARCHAR(99)=') Pour from 5',@3 VARCHAR(99)=') Pour from 3'
;WITH t AS (SELECT @i i,(@i-@i%5)%5 j
UNION ALL
SELECT i-5,(i-i%5)%5+5 FROM t WHERE i>=5 AND i NOT IN(6,9)
UNION ALL
SELECT i-3,3FROM t WHERE i in(3,4,6,9)
UNION ALL
SELECT i-i,i FROM t WHERE i<3 AND i>0)
SELECT t.i,t.j,v.s,ROW_NUMBER()OVER(PARTITION BY t.j ORDER BY t.i DESC)x,SUM(t.j)OVER(ORDER BY t.i DESC ROWS UNBOUNDED PRECEDING)y INTO #q FROM(VALUES(1,5),(2,3),(3,2),(5,2))v(i,s) JOIN t ON t.j = v.i
SELECT z.b FROM(SELECT ROW_NUMBER()OVER(ORDER BY q.i DESC,w.s)a,CAST(ROW_NUMBER()OVER(ORDER BY q.i DESC,w.s)AS VARCHAR)+w.v+CAST(y-CASE WHEN q.s!=w.s THEN q.j ELSE 0 END AS VARCHAR)b
FROM(VALUES(5,1,') Fill 5'+@l+@o),(5,2,@5+@l+@k),(3,1,') Fill 3'+@l+@n+'5L: 0, 3L: 3, T: '),(3,2,@3+@l+@k),(2,1,') Fill 5'+@l+@o),(2,2,@5+@l+' into 3'+@l+@n+'5L: 2, 3L: 3, T: '),(2,3,@5+@l+@k),(1,1,') Fill 3'+@l+@n+'5L: 0, 3L: 3, T: '),(1,2,@3+@l+'into 5'+@l+@n+'5L: 3, 3L: 0, T: '),(1,3,') Fill 3'+@l+@n+'5L: 3, 3L: 3, T: '),(1,4,@3+@l+'into 5'+@l+@n+'5L: 5, 3L: 1, T: '),(1,5,@3+@l+'into tank'+@o))w(i,s,v)JOIN #q q ON w.i=q.j
UNION
SELECT 99,'Volume measured out in '+CAST(COUNT(*)AS VARCHAR)+' turns'
FROM #q)z
```
Results for the input 42:
```
1) Fill 5L jug
5L: 5, 3L: 0, T: 0
2) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 5
3) Fill 5L jug
5L: 5, 3L: 0, T: 5
4) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 10
5) Fill 5L jug
5L: 5, 3L: 0, T: 10
6) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 15
7) Fill 5L jug
5L: 5, 3L: 0, T: 15
8) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 20
9) Fill 5L jug
5L: 5, 3L: 0, T: 20
10) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 25
11) Fill 5L jug
5L: 5, 3L: 0, T: 25
12) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 30
13) Fill 5L jug
5L: 5, 3L: 0, T: 30
14) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 35
15) Fill 5L jug
5L: 5, 3L: 0, T: 35
16) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 40
17) Fill 5L jug
5L: 5, 3L: 0, T: 40
18) Pour from 5L jug into 3L jug
5L: 2, 3L: 3, T: 40
19) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 42
Volume measured out in 9 turns
```
### Edit:
Golfed out a decent score improvement by
* eliminating an unnecessary +5 in the first row of the CTE, and the WHERE clause it necessitated
* in-lining the VALUES tables, saving costly DECLARE statements
* remembering to convert Windows double-byte CRLFs to Unix style this time.
[Answer]
# Javascript: 481
First attempt at golfing, advice appreciated
```
n=["3L jug","5L jug","tank"];l=[0,0,0];t=[3,5,0];h=0;c=console;function e(d){l[d]=t[d];c.log(++h+") Fill "+n[d]);k()}function m(d,g){s=l[d];f=l[g];b=s+f>t[g];l[g]=b?t[g]:f+s;l[d]=b?s-(t[g]-f):0;c.log(++h+") Pour from "+n[d]+" into "+n[g]);k()}function k(){c.log("5L: "+l[1]+", 3L: "+l[0]+", T: "+l[2])}a=prompt();for(t[2]=a;4<a;)e(1),m(1,2),a-=5;2<a&&(e(0),m(0,2),a-=3);1<a&&(e(1),m(1,0),m(1,2),a=0);0<a&&(e(0),m(0,1),e(0),m(0,1),m(0,2));c.log("Volume measured out in "+h+" turns")
```
It messes up with some numbers because it doesn't check if it's better to pour 3 or 5, example: 9 gives 9 turns instead of 6, I might fix it later
Paste it in console
From 553 to 481 thanks to @WallyWest
[Answer]
## **Java, 610**
```
class X{int n,c=0,t=0;public void static main(String[]a){n=Integer.parseInt(a[0]);String s,b,f,k,m,u;b="5L";s="3L";k="tank";u="Fill %s jug\n5L: %d, 3L: %d, T: %d";m="\nPour from %s jug into %s\n5L: %d, 3L: %d, T: %d";f=u+m;for(;n>4;)z(f,2,5,b,5,0,t,b,k,0,0,t+=5);while(n!=0){if(n==1)z(f+f+m,5,1,s,0,3,t,s,b,3,0,t,s,3,3,t,s,b,5,1,t,s,k,5,0,t+1);if(n==3)z(f,2,3,s,0,3,t,s,k,0,0,t+3);z(f+m,3,2,b,5,0,t,b,s,2,3,t,b,k,0,3,t+=2);if(n==2)z("Empty 3L jug\n5L: 0, 3L: 0,T: %d",1,0,t)}z("Volume measured out in %d turns",0,0,c)}void z(String s,int o,int w,Object...a){c+=o;n-=w;System.out.println(String.format(s,a))}}
```
I took the solution of [Sumedh](https://codegolf.stackexchange.com/a/20811/25024) and golfed it. I wanted to put it in the comments but my reputation isn't enough :( . It's a 40% less, I think it should at least be shared. Still far from first though...
Here is ungolfed:
```
class X{
int n,c=0,t=0;
public void static main(String[] a){
n=Integer.parseInt(a[0]);
String s,b,f,k,m,u;
b="5L";
s="3L";
k="tank";
u="Fill %s jug\n5L: %d, 3L: %d, T: %d";
m="\nPour from %s jug into %s\n5L: %d, 3L: %d, T: %d";
f=u+m;
for(;n>4;)z(f,2,5,b,5,0,t,b,k,0,0,t+=5);
while(n!=0)
{
if(n==1)z(f+f+m,5,1,s,0,3,t,s,b,3,0,t,s,3,3,t,s,b,5,1,t,s,k,5,0,t+1);
if(n==3)z(f,2,3,s,0,3,t,s,k,0,0,t+3);
z(f+m,3,2,b,5,0,t,b,s,2,3,t,b,k,0,3,t+=2);
if(n==2)z("Empty 3L jug\n5L: 0, 3L: 0,T: %d",1,0,t);
}
z("Volume measured out in %d turns",0,0,c);
}
void z(String s,int o, int w,Object... a){
c+=o;
n-=w;
System.out.println(String.format(s,a));
}
}
```
**NB:** it works only on the first run. Rerun it and the result will be wrong (due to a global variable).
The following version is safe, but we lose 2 char, going from 610 to 612:
```
class X{
int n,c,t;
public void static main(String[] a){
n=Integer.parseInt(a[0]);
String s,b,f,k,m,u;
t=c=0;
b="5L";
s="3L";
k="tank";
u="Fill %s jug\n5L: %d, 3L: %d, T: %d";
m="\nPour from %s jug into %s\n5L: %d, 3L: %d, T: %d";
f=u+m;
for(;n>4;)z(f,2,5,b,5,0,t,b,k,0,0,t+=5);
while(n!=0)
{
if(n==1)z(f+f+m,5,1,s,0,3,t,s,b,3,0,t,s,3,3,t,s,b,5,1,t,s,k,5,0,t+1);
if(n==3)z(f,2,3,s,0,3,t,s,k,0,0,t+3);
z(f+m,3,2,b,5,0,t,b,s,2,3,t,b,k,0,3,t+=2);
if(n==2)z("Empty 3L jug\n5L: 0, 3L: 0,T: %d",1,0,t);
}
z("Volume measured out in %d turns",0,0,c);
}
void z(String s,int o, int w,Object... a){
c+=o;
n-=w;
System.out.println(String.format(s,a));
}
}
```
Sample output for N=69:
```
Fill 5L jug
5L: 5, 3L: 0, T: 0
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 5
Fill 5L jug
5L: 5, 3L: 0, T: 5
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 10
Fill 5L jug
5L: 5, 3L: 0, T: 10
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 15
Fill 5L jug
5L: 5, 3L: 0, T: 15
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 20
Fill 5L jug
5L: 5, 3L: 0, T: 20
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 25
Fill 5L jug
5L: 5, 3L: 0, T: 25
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 30
Fill 5L jug
5L: 5, 3L: 0, T: 30
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 35
Fill 5L jug
5L: 5, 3L: 0, T: 35
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 40
Fill 5L jug
5L: 5, 3L: 0, T: 40
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 45
Fill 5L jug
5L: 5, 3L: 0, T: 45
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 50
Fill 5L jug
5L: 5, 3L: 0, T: 50
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 55
Fill 5L jug
5L: 5, 3L: 0, T: 55
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 60
Fill 5L jug
5L: 5, 3L: 0, T: 60
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 65
Fill 5L jug
5L: 5, 3L: 0, T: 65
Pour from 5L jug into 3L
5L: 2, 3L: 3, T: 65
Pour from 5L jug into tank
5L: 0, 3L: 3, T: 67
Empty 3L jug
5L: 0, 3L: 0,T: 67
Fill 5L jug
5L: 5, 3L: 0, T: 67
Pour from 5L jug into 3L
5L: 2, 3L: 3, T: 67
Pour from 5L jug into tank
5L: 0, 3L: 3, T: 69
Volume measured out in 33 turns
```
[Answer]
# Java: 984
Here's the code
```
class X{public static void main(String[] s){int n=Integer.parseInt(s[0]);int t=0;int c=0;while(n>4){n-=5;System.out.println("Fill 5L jug\n5L: 5, 3L: 0, T: "+t+"\nPour from 5L jug into tank\n5L: 0, 3L: 0, T: "+(t+5));t+=5;c+=2;}while(n!=0){switch(n){case 1:System.out.println("Fill 3L jug\n5L: 0, 3L: 3, T: "+t+"\nPour from 3L jug into 5L jug\n5L: 3, 3L: 0, T: "+t+"\nFill 3L jug\n5L: 3, 3L: 3, T: "+t+"\nPour from 3L jug into 5L jug\n5L: 5, 3L: 1, T: "+t+"\nPour from 3L jug into tank\n5L: 5, 3L: 0, T: "+(t+1));n=0;c+=5;break;case 3:System.out.println("Fill 3L jug\n5L: 0, 3L: 3, T: "+t+"\nPour from 3L jug into tank\n5L: 0, 3L: 0, T: "+(t+3));n=0;c+=2;break;default:System.out.println("Fill 5L jug\n5L: 5, 3L: 0, T: "+t+"\nPour from 5L jug into 3L jug\n5L: 2, 3L: 3, T: "+t+"\nPour from 5L jug into tank\n5L: 0, 3L: 0, T: "+(t+2));n-=2;c+=3;t+=2;if(n==2){System.out.println("Empty 3L jug\n5L: 0, 3L: 0,T: "+t);c++;}break;}}System.out.println("Volume measured out in "+c+" turns");}}
```
Input is from command line. for example: java X 4
[Answer]
## Python 2.7 - 437
Not the shortest code, but I think this is the most optimal way of solving this.
As I stated in the comments, the most optimal way to calculate this:
1. Take as many chunks of 5L as possible - `divmod(amount,5)`. This will give you one of 4,3,2,1 as the remainder.
2. Take 3 (if possible) from the remainder.
3. Which leaves either 1 or 2 as the remainder. Use the optimal solution for either which can be known ahead of time as:
1. 1L, 5 steps : 3L -> 5L, 3L -> 5L, leaving 1L in the 3L, 3L (holding 1L) -> tank
2. 2L, 3 steps : 5L -> 3L, leaves 2L in the 5L, 5L (holding 2L) -> tank
The code:
```
j,T="%dL jug","tank"
A="\n5L: %d, 3L: %d, T: %d"
F,P="Fill "+j+A,"Pour from "+j+" into %s"+A
f,r=divmod(input(),5)
o,t=f*5,[]
for i in range(f):o+=[F%(5,5,0,5*i),P%(5,T,0,0,5*i+5)]
if r>2:o+=[F%(3,0,3,t),P%(3,T,0,0,t+3)];r-=3;t+=3
if r==2:o+=[F%(5,5,0,t),P%(5,j%3,2,3,t),P%(5,T,0,3,t+2)]
if r==1:o+=[F%(3,0,3,t),P%(3,j%5,3,0,t),F%(3,3,3,t),P%(3,j%5,5,1,t),P%(3,T,5,0,t+1)]
print"\n".join(o),'\n',"Volume measured out in %d turns"%len(o)
```
And an output for 4L in 7 steps:
```
Fill 3L jug
5L: 0, 3L: 3, T: 0
Pour from 3L jug into tank
5L: 0, 3L: 0, T: 3
Fill 3L jug
5L: 0, 3L: 3, T: 3
Pour from 3L jug into 5L jug
5L: 3, 3L: 0, T: 3
Fill 3L jug
5L: 3, 3L: 3, T: 3
Pour from 3L jug into 5L jug
5L: 5, 3L: 1, T: 3
Pour from 3L jug into tank
5L: 5, 3L: 0, T: 4
Volume measured out in 7 turns
```
[Answer]
# Smalltalk (Smalltalk/X), 568 560 516
input in n:
```
T:=j:=J:=c:=0.m:={'Pour from'.' into'.' 3L jug'.' 5L jug'.[j:=j+3.'Fill'].[J:=J+5.'Fill'].[t:=j.j:=0.''].[t:=J.J:=0.''].[r:=j min:5-J.j:=j-r.J:=J+r.''].[r:=J min:3-j.J:=J-r.j:=j+r.''].[T:=T+t.' into tank'].[c:=c+1.'\5L: %1 3L: %2 T: %3\'bindWith:J with:j with:T].['Volume measured out in %1 turns'bindWith:c]}.[n>=0]whileTrue:[s:=n.n:=0.(s caseOf:{0->[n:=-1.'<'].1->'42;02813;42;02813;062:;'.2->'53;03912;073:;'.3->'42;062:;'.4->[n:=1.'42;062:;']}otherwise:[n:=s-5.'53;073:;'])do:[:c|(m at:c-$/)value withCRs print]]
```
boy this is definitely the most obfuscated program I've ever written...
Edit: Some other Smalltalks may not allow autodeclared workspace variables and you'll have to prepend declarations. Also bindWith: may be different (expandWith:'<p>').
sample output for n=17:
```
Fill 5L jug
5L: 5, 3L: 0, T: 0
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 5
Fill 5L jug
5L: 5, 3L: 0, T: 5
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 10
Fill 5L jug
5L: 5, 3L: 0, T: 10
Pour from 5L jug into tank
5L: 0, 3L: 0, T: 15
Fill 5L jug
5L: 5, 3L: 0, T: 15
Pour from 5L jug into 3L jug
5L: 2, 3L: 3, T: 15
Pour from 5L jug into tank
5L: 0, 3L: 3, T: 17
Volume measured out in 9 turns
```
[Answer]
# C, 567 609
```
#define r printf
#define l r("5L: %d, 3L: %d, T: %d\n", a, b, T);
#define j(x,y,z,w) r("%d) "#x" %dL jug\n", i++, y),z=w,l
#define e j(Empty,3,b,0)
#define f j(Fill,5,a,5)
#define g j(Fill,3,b,3)
#define o(x,y,z,w) r("%d) Pour from %dL jug into "x"\n", i++, y,z),w;l
#define t(x,y) T+=x,o("tank",y,0,x=0)
#define p(x) o("%dL jug",5,3,(a-=x,b+=x))
int N,T,i;q(x){int a=0,b=0;switch(x){case 5:f t(a,5) break;case 3:g t(b,3) break;case 1:case 2:case 4:f if(x-2){e p(2)f p(1)if(x-4){e p(3)}}t(a,5)}N-=x;}main(){T=0,i=1,scanf("%d",&N);while(N>5)q((N-6)&&(N-9)?5:3);q(N);r("Volume measured out in %d turns",i-1);}
```
previous invalid version:
```
#define r printf
#define l r("5L: %d, 3L: %d, T: %d\n", a, b, T);
#define j(x,y,z,w) r("%d) "#x" %dL jug\n", i++, y),z=w,l
#define e j(Empty,3,b,0)
#define f j(Fill,5,a,5)
#define g j(Fill,3,b,3)
#define o(x,y,z,w) r("%d) Pour from %dL jug into "x"\n", i++, y,z),w;l
#define t o("tank",5,0,a=0)
#define p(x) o("%dL jug",5,3,(a-=x,b+=x))
int N,T,i;q(x){int a=0,b=0;switch(x){case 5:f t break;case 3:g t break;case 1:case 2:case 4:f if(x-2){e p(2)f p(1)if(x-4){e p(3)}}t}N-=x;}main(){T=0,i=1,scanf("%d",&N);while(N>5)q(5);q(N);r("Volume measured out in %d turns",i-1);}
```
and here is the code degolfed:
```
#define r printf
#define l r("5L: %d, 3L: %d, T: %d\n", a, b, T);
#define j(x,y,z,w) r("%d) "#x" %dL jug\n", i++, y),z=w,l
#define e j(Empty,3,b,0)
#define f j(Fill,5,a,5)
#define g j(Fill,3,b,3)
#define o(x,y,z,w) r("%d) Pour from %dL jug into "x"\n", i++, y,z),w;l
#define t o("tank",5,0,a=0)
#define p(x) o("%dL jug",5,3,(a-=x,b+=x))
int N,T,i;
q(x)
{
int a=0,b=0;
switch(x)
{
case 5:
f
t
break;
case 3:
g
t
break;
case 1:
case 2:
case 4:
f
if(x-2)
{
e
p(2)
f
p(1)
if(x-4)
{
e
p(3)
}
}
t
}
N-=x;
}
main()
{
T=0,i=1,scanf("%d",&N);
while(N>
5)q(5);
q(N);
r("Volume measured out in %d turns",i-1);
}
```
[Answer]
# C (480 465 bytes)
```
#define P printf(
#define O(x) P"%d) Pour from %dL jug into "x"\n"
#define S P"5L: %d, 3L: %d, T: %d\n",F,H,g);}
F,H,s,g,x;l(j){P"%d) Fill %dL jug\n",++s,j);St(j,o,m){O("%dL jug"),++s,j,(j^5)?5:3);Se(j,i){O("tank"),++s,j);Smain(){scanf("%d",&x);while(x>4){x-=5;l(F=5);g+=5;e(5,F=0);}while(x>2){x-=3;l(H=3);g+=3;e(3,H=0);}(x^2)?(x^1)?0:(l(H=3),t(3,H=0,F=3),l(H=3),t(3,H=1,F=5),g++,e(3,H=0)):(l(F=5),t(5,F=2,H=3),g+=2,e(5,F=0));P"Volume measured out in %d turns",s);}
```
**Optimal version (adds 10 bytes)**
```
#define P printf(
#define O(x) P"%d) Pour from %dL jug into "x"\n"
#define S P"5L: %d, 3L: %d, T: %d\n",F,H,g);}
F,H,s,g,x;l(j){P"%d) Fill %dL jug\n",++s,j);St(j,o,m){O("%dL jug"),++s,j,(j^5)?5:3);Se(j,i){O("tank"),++s,j);Smain(){scanf("%d",&x);while(x>4&&x^6&&x^9){x-=5;l(F=5);g+=5;e(5,F=0);}while(x>2){x-=3;l(H=3);g+=3;e(3,H=0);}(x^2)?(x^1)?0:(l(H=3),t(3,H=0,F=3),l(H=3),t(3,H=1,F=5),g++,e(3,H=0)):(l(F=5),t(5,F=2,H=3),g+=2,e(5,F=0));P"Volume measured out in %d turns",s);}
```
Likely more golfing to be done here - the output functions were killing me. This should give the optimal solution (least number of steps). Similar to other code here, it fills and empties 5L jugs until it gets below 5 and then switches to 3L jugs. It tests for 2 special cases (6 and 9) and if it finds them switches to 3L jugs. The instructions for getting 1L and 2L are hard coded.
**More readable version:**
```
#define P printf(
#define O(x) P"%d) Pour from %dL jug into "x"\n"
#define S P"5L: %d, 3L: %d, T: %d\n",F,H,g);}
F,H,s,g,x;
l(j)
{
P"%d) Fill %dL jug\n",++s,j);S
t(j,o,m)
{
O("%dL jug"),++s,j,(j^5)?5:3);S
e(j,i)
{
O("tank"),++s,j);S
main()
{
scanf("%d",&x);
//while(x>4&&x^6&&x^9) <--optimal version
while(x>4)
{
x-=5;l(F=5);g+=5;e(5,F=0);
}
while(x>2)
{
x-=3;l(H=3);g+=3;e(3,H=0);
}
(x^2)?
(x^1)?
0
:
(l(H=3),t(3,H=0,F=3),l(H=3),t(3,H=1,F=5),g++,e(3,H=0))
:(l(F=5),t(5,F=2,H=3),g+=2,e(5,F=0));
P"Volume measured out in %d turns",s);
}
```
**Edits:**
* Removed 10 bytes that gave the optimum performance for the scored version
based on the OP's clarification.
* Shave 5 bytes by converting function to definition.
**Test output for n = 11 (optimal version):**
```
11
1) Fill 5L jug
5L: 5, 3L: 0, T: 0
2) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 5
3) Fill 3L jug
5L: 0, 3L: 3, T: 5
4) Pour from 3L jug into tank
5L: 0, 3L: 0, T: 8
5) Fill 3L jug
5L: 0, 3L: 3, T: 8
6) Pour from 3L jug into tank
5L: 0, 3L: 0, T: 11
Volume measured out in 6 turns
```
[Answer]
## T-SQL(2012): 794 689 580
Inspired by [@Jonathan-Van-Matre](https://codegolf.stackexchange.com/users/3363/jonathan-van-matre) 's T-SQL answer in combination with [@Lego-Stormtroopr](https://codegolf.stackexchange.com/users/8777/lego-stormtroopr)'s algorithm. I wanted to do this because I enjoyed the [99 Bottles of Beer](https://codegolf.stackexchange.com/a/11844) challenge so much.
I tried to keep window (`OVER`) functions at a minimum in preference of math/bool functions.
SQLFiddle is [here](http://sqlfiddle.com/#!6/d41d8/19191/0).
```
WITH n AS(SELECT 11 n UNION ALL SELECT n-IIF(n>4,5,3)FROM n WHERE n>2)SELECT n, a,LEN(a)L,i=IDENTITY(INT,1,1),'L jug'j INTO #t FROM n JOIN(VALUES(3303),(33900),(5550),(55900),(2550),(259323),(25903),(1303),(139530),(1333),(139551),(13950))x(a)ON RIGHT(LEFT(12335,n),1)=LEFT(a,1)ORDER BY n DESC SELECT LTRIM(i)+') '+REPLACE(IIF(L=4,'Fill ','Pour ')+RIGHT(a/100,L-3),9,j+' into ')+IIF(L=5,'tank',j) +'
5L: '+LTRIM((A%100)/10)+', 3L: '+LTRIM(A%10)+', T: '+LTRIM(SUM(IIF(L=5,LEFT(a,1),0))OVER(ORDER BY i))FROM #t UNION SELECT 'Volume measured out in ' +LTRIM(MAX(i))+' turns'FROM #t
```
Input: `11`
```
1) Fill 5L jug
5L: 5, 3L: 0, T: 0
2) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 5
3) Fill 5L jug
5L: 5, 3L: 0, T: 5
4) Pour from 5L jug into tank
5L: 0, 3L: 0, T: 10
5) Fill 3L jug
5L: 0, 3L: 3, T: 10
6) Pour from 3L jug into
5L jug 5L: 0, 3L: 3, T: 10
7) Fill 3L jug
5L: 3, 3L: 3, T: 10
8) Pour from 3L jug into 5L jug
5L: 5, 3L: 1, T: 10
9) Pour from 3L jug into tank
5L: 5, 3L: 0, T: 11
Volume measured out in 9 turns
```
Human-readable:
```
WITH n AS(
SELECT 11 n
UNION ALL
SELECT n-IIF(n>4,5,3)
FROM n
WHERE n>2
)
SELECT n, a,LEN(a) L, i = IDENTITY(INT,1,1), 'L jug'j
INTO #t
FROM n
JOIN(VALUES
(3303),(33900),
(5550),(55900),
(2550),(259323),(25903),
(1303),(139530),(1333),(139551),(13950)
)x(a)
ON RIGHT(LEFT(12335,n),1) = LEFT(a,1)
ORDER BY n DESC
SELECT LTRIM(i)+') '
+ REPLACE(IIF(L=4,'Fill ','Pour ')
+ RIGHT(a/100,L-3),9,j+' into ')+IIF(L=5,'tank',j)
+'
5L: ' + LTRIM((A%100)/10) + ', 3L: ' + LTRIM(A%10) + ', T: '
+ LTRIM(SUM(IIF(L=5,LEFT(a,1),0))OVER(ORDER BY i)) FROM #t
UNION ALL
SELECT 'Volume measured out in ' +LTRIM(MAX(i))+' turns'FROM #t
DROP TABLE #t
```
[Answer]
# Python 3 (417 chars)
```
P=print
D=divmod
N=['3L jug','5L jug','tank',0]
M=999
R=[0,0,0,M]
F=[3,5,M,M]
def o(a,b):k=a==3;P(['Pour from %s into %s','Empty %s','Fill %s'][k*2+(b==3)]%[(N[a],N[b]),(N[b])][k]);d=min(R[a],F[b]-R[b]);R[a]-=d;R[b]+=d;P('5L:',R[1],'3L:',R[0],'T:',R[2]);N[3]+=1
k,r=D(int(input()),5)
for i in'0'*k:o(3,1);o(1,2)
for x in['','c1c12','d46','c2','d434d46'][r]:o(*D(int(x,16),4))
P('Volume measured out in',N[3],'turns')
```
## Explained
Note that we have 4 objects, namely, the 3L jug, the 5L jug, the tank, and the foutain. The only operations we can do is to move water from object `a` to object `b`. This is what function `o(a, b)` do in my code, it move water and print it and keep counting.
## Tricks
* `N=['3L jug','5L jug','tank',0]`. Here I need the last element to avoid `IndexError`. Also, it can be used as the global counting variable, without the expansive `global` keyword. For example, `N[3] += 1`
* Since `0 <= a < 4, 0 <= b < 4` in function `o(a, b)`, we can encode `(a, b)` into a hex digit using `(a << 2) | b`, and decode it using `divmod(x, 4)`. With this trick, all 5 solutions(`reminder=0, 1, 2, 3, 4`), can be encoded into array `['','c1c12','d46','c2','d434d46']`, which is a little bit shorter than it's original form:
`A=[
(),
((3,0),(0,1),(3,0),(0,1),(0,2)),
((3,1),(1,0),(1,2)),
((3,0),(0,2)),
((3,1),(1,0),(0,3),(1,0),(3,1),(1,0),(1,2))
]`
## Sample Output(n = 17)
```
17
Fill 5L jug
5L: 5 3L: 0 T: 0
Pour from 5L jug into tank
5L: 0 3L: 0 T: 5
Fill 5L jug
5L: 5 3L: 0 T: 5
Pour from 5L jug into tank
5L: 0 3L: 0 T: 10
Fill 5L jug
5L: 5 3L: 0 T: 10
Pour from 5L jug into tank
5L: 0 3L: 0 T: 15
Fill 5L jug
5L: 5 3L: 0 T: 15
Pour from 5L jug into 3L jug
5L: 2 3L: 3 T: 15
Pour from 5L jug into tank
5L: 0 3L: 3 T: 17
Volume measured out in 9 turns
```
[Answer]
COBOL (IBM Enterprise COBOL) 192 *lines* of 72 characters
This is a Proof of Concept for the Question, and the start of one for Golf-COBOL :-)
The question asks for the quickest. So, implement parallelism. Even one person can readily fill one 3L jug and one 5L jug at the same time.
Simply divide the input by eight, also leaving the remainder. Do some quick 5L/3L fills to the number of times eight fits exactly, then deal with the one through seven litres remaining.
The most interesting of the remainder is for four litres. Doing it as one litre plus three litres pushes a lot less water around, only 18 litres vs 23 for the other possibilities.
The Code (working)
```
ID DIVISION
PROGRAM-ID
DATA DIVISION
WORKING-STORAGE SECTION
1.
88 g1 VALUE ' '.
2 PIC X
88 H VALUE 'F'.
88 I VALUE 'E'.
88 J VALUE 'T'.
2 PIC X
88 K VALUE 'F'.
88 L VALUE 'E'.
88 M VALUE 'T'.
1 R
2 A1 PIC 999
2 B PIC 99
2 C PIC 9
1 E
2 e2 PIC X(120) VALUE " ) Fill both jugs"
2 e3 PIC X(120)
88 O VALUE "5L: 0, 3L: 0, T: 000".
2 e4 PIC X(120) VALUE " ) Empty both jugs"
2 e5 PIC X(120)
2 e1 occurs 32 depending on p pic x(240)
2 e6 pic x(99)
1 F PIC 999 VALUE 0
1 P PIC 99 VALUE 0
1 P1 PIC 99
PROCEDURE DIVISION
ACCEPT A1
DIVIDE A1 BY 8 GIVING B REMAINDER C
set o to true
move e3 to e5
move 5 to e3(5:1)
move 3 to e3(12:1)
PERFORM D1 B TIMES
EVALUATE C
WHEN 1
MOVE ZERO TO R
SET K TO TRUE
PERFORM N
SET M TO TRUE
PERFORM N
SET K TO TRUE
PERFORM N
SET M TO TRUE
PERFORM N
SET L TO TRUE
PERFORM N
WHEN 2
MOVE ZERO TO R
SET H TO TRUE
PERFORM N
SET J TO TRUE
PERFORM N
SET I TO TRUE
PERFORM N
WHEN 3
MOVE ZERO TO R
SET K TO TRUE
PERFORM N
SET L TO TRUE
PERFORM N
WHEN 4
MOVE ZERO TO R
SET K TO TRUE
PERFORM N
SET M TO TRUE
PERFORM N
SET K TO TRUE
PERFORM N
SET M TO TRUE
PERFORM N
SET L TO TRUE
PERFORM N
SET K TO TRUE
PERFORM N
SET L TO TRUE
PERFORM N
WHEN 5
MOVE ZERO TO R
SET H TO TRUE
PERFORM N
SET I TO TRUE
PERFORM N
WHEN 6
MOVE ZERO TO R
SET K TO TRUE
PERFORM N
SET L TO TRUE
PERFORM N
SET K TO TRUE
PERFORM N
SET L TO TRUE
PERFORM N
WHEN 7
MOVE ZERO TO R
SET H TO TRUE
PERFORM N
SET I TO TRUE
PERFORM N
SET H TO TRUE
PERFORM N
SET J TO TRUE
PERFORM N
SET I TO TRUE
PERFORM N
END-EVALUATE
string "Volume measured out in " delimited size P " turns"
delimited size into e6
if e6(24:1) = 0
move e6(25:) to e6 (24:)
end-if
move p to p1
perform d2 p times
DISPLAY E(481:)
GOBACK
D1
ADD 1 TO P
MOVE P TO E(1:2)
move e2 to e1(p)
move e3 to e1(p)(121:)
ADD 1 TO P
MOVE P TO E(241:2)
ADD 8 TO F
MOVE F TO E(378:3)
move e4 to e1(p)
move e5 to e1(p)(121:)
MOVE F TO E(138:3)
N
ADD 1 TO P
SET O TO TRUE
EVALUATE TRUE
WHEN K
MOVE 3 TO B
string p delimited size ") Fill 3L jug" delimited by size
into e1(p)
WHEN M
COMPUTE C = C + B
IF C > 5
COMPUTE B = C - 5
MOVE 5 TO C
ELSE
MOVE 0 TO B
END-IF
string P delimited size ") Pour from 3L jug into 5L jug"
delimited size into e1(p)
WHEN L
ADD B TO F
MOVE 0 TO B
string P delimited size ") Empty 3L jug into tank"
delimited size into e1(p)
END-EVALUATE
EVALUATE TRUE
WHEN H
MOVE 5 TO C
string P delimited size ") Fill 5L jug"
delimited size into e1(p)
WHEN J
COMPUTE B = C + B
IF B > 3
COMPUTE C = B - 3
MOVE 3 TO B
ELSE
MOVE 0 TO C
END-IF
string P delimited size ") Pour from 5L jug into 3L jug"
delimited size into e1(p)
WHEN I
ADD C TO F
MOVE 0 TO C
string P delimited size ") Empty 5L jug into tank"
delimited size into e1(p)
END-EVALUATE
string "5L: " delimited size
C delimited size ", 3L: " delimited size B(2:)
", T: " delimited size F delimited size
into e1(p)(121:)
SET g1 TO TRUE
d2
perform d3 2 times
if e1(p1)(1:1) = 0
move e1(p1)(2:) to e1(p1)(1:120)
end-if
subtract 1 from p1
d3
if e1(p1)(138:1) = 0
move e1(p1)(139:) to e1(p1)(138:)
end-if
```
This gets an absolute shed-load of diagnostic messages for code starting in the wrong place and shortage of required full-stops.
None of the diagnostics indicate any impact on the object code. So, despite it being a busted RC=8 I know the object will be OK, so linked it and ran it.
Here are the outputs for one to eight litres. After that, all results can be intuited. 17 and 100 are included as examples of the parallelism.
There is still much that can be done to squeeze the program down in characters, the correct output was the important thing first. Counting the characters when they are on fixed-length lines is another thing entirely.
Sample output:
```
1) Fill 3L jug
5L: 0, 3L: 3, T: 0
2) Pour from 3L jug into 5L jug
5L: 3, 3L: 0, T: 0
3) Fill 3L jug
5L: 3, 3L: 3, T: 0
4) Pour from 3L jug into 5L jug
5L: 5, 3L: 1, T: 0
5) Empty 3L jug into tank
5L: 5, 3L: 0, T: 1
Volume measured out in 5 turns
1) Fill 5L jug
5L: 5, 3L: 0, T: 0
2) Pour from 5L jug into 3L jug
5L: 2, 3L: 3, T: 0
3) Empty 5L jug into tank
5L: 0, 3L: 3, T: 2
Volume measured out in 3 turns
1) Fill 3L jug
5L: 0, 3L: 3, T: 0
2) Empty 3L jug into tank
5L: 0, 3L: 0, T: 3
Volume measured out in 2 turns
1) Fill 3L jug
5L: 0, 3L: 3, T: 0
2) Pour from 3L jug into 5L jug
5L: 3, 3L: 0, T: 0
3) Fill 3L jug
5L: 3, 3L: 3, T: 0
4) Pour from 3L jug into 5L jug
5L: 5, 3L: 1, T: 0
5) Empty 3L jug into tank
5L: 5, 3L: 0, T: 1
6) Fill 3L jug
5L: 5, 3L: 3, T: 1
7) Empty 3L jug into tank
5L: 5, 3L: 0, T: 4
Volume measured out in 7 turns
1) Fill 5L jug
5L: 5, 3L: 0, T: 0
2) Empty 5L jug into tank
5L: 0, 3L: 0, T: 5
Volume measured out in 2 turns
1) Fill 3L jug
5L: 0, 3L: 3, T: 0
2) Empty 3L jug into tank
5L: 0, 3L: 0, T: 3
3) Fill 3L jug
5L: 0, 3L: 3, T: 3
4) Empty 3L jug into tank
5L: 0, 3L: 0, T: 6
Volume measured out in 4 turns
1) Fill 5L jug
5L: 5, 3L: 0, T: 0
2) Empty 5L jug into tank
5L: 0, 3L: 0, T: 5
3) Fill 5L jug
5L: 5, 3L: 0, T: 5
4) Pour from 5L jug into 3L jug
5L: 2, 3L: 3, T: 5
5) Empty 5L jug into tank
5L: 0, 3L: 3, T: 7
Volume measured out in 5 turns
1) Fill both jugs
5L: 5, 3L: 3, T: 0
2) Empty both jugs
5L: 0, 3L: 0, T: 8
Volume measured out in 2 turns
1) Fill both jugs
5L: 5, 3L: 3, T: 0
2) Empty both jugs
5L: 0, 3L: 0, T: 8
3) Fill both jugs
5L: 5, 3L: 3, T: 8
4) Empty both jugs
5L: 0, 3L: 0, T: 16
5) Fill 3L jug
5L: 0, 3L: 3, T: 16
6) Pour from 3L jug into 5L jug
5L: 3, 3L: 0, T: 16
7) Fill 3L jug
5L: 3, 3L: 3, T: 16
8) Pour from 3L jug into 5L jug
5L: 5, 3L: 1, T: 16
9) Empty 3L jug into tank
5L: 5, 3L: 0, T: 17
Volume measured out in 9 turns
1) Fill both jugs
5L: 5, 3L: 3, T: 0
2) Empty both jugs
5L: 0, 3L: 0, T: 8
3) Fill both jugs
5L: 5, 3L: 3, T: 8
4) Empty both jugs
5L: 0, 3L: 0, T: 16
5) Fill both jugs
5L: 5, 3L: 3, T: 16
6) Empty both jugs
5L: 0, 3L: 0, T: 24
7) Fill both jugs
5L: 5, 3L: 3, T: 24
8) Empty both jugs
5L: 0, 3L: 0, T: 32
9) Fill both jugs
5L: 5, 3L: 3, T: 32
10) Empty both jugs
5L: 0, 3L: 0, T: 40
11) Fill both jugs
5L: 5, 3L: 3, T: 40
12) Empty both jugs
5L: 0, 3L: 0, T: 48
13) Fill both jugs
5L: 5, 3L: 3, T: 48
14) Empty both jugs
5L: 0, 3L: 0, T: 56
15) Fill both jugs
5L: 5, 3L: 3, T: 56
16) Empty both jugs
5L: 0, 3L: 0, T: 64
17) Fill both jugs
5L: 5, 3L: 3, T: 64
18) Empty both jugs
5L: 0, 3L: 0, T: 72
19) Fill both jugs
5L: 5, 3L: 3, T: 72
20) Empty both jugs
5L: 0, 3L: 0, T: 80
21) Fill both jugs
5L: 5, 3L: 3, T: 80
22) Empty both jugs
5L: 0, 3L: 0, T: 88
23) Fill both jugs
5L: 5, 3L: 3, T: 88
24) Empty both jugs
5L: 0, 3L: 0, T: 96
25) Fill 3L jug
5L: 0, 3L: 3, T: 96
26) Pour from 3L jug into 5L jug
5L: 3, 3L: 0, T: 96
27) Fill 3L jug
5L: 3, 3L: 3, T: 96
28) Pour from 3L jug into 5L jug
5L: 5, 3L: 1, T: 96
29) Empty 3L jug into tank
5L: 5, 3L: 0, T: 97
30) Fill 3L jug
5L: 5, 3L: 3, T: 97
31) Empty 3L jug into tank
5L: 5, 3L: 0, T: 100
Volume measured out in 31 turns
```
] |
[Question]
[
The smallest code that gives the area between the curve p(x) = a0 + a1\*x + a2\*x2 + ..., the line y = 0, the line x = 0 and the line x = C
(i.e. something like this:
)
You can assume that p(x) >= 0 for x < C (bonus points if your code works for negative values of p(x)).
### Input
C, a0, a1, ...
### Output
a real number - the area
Example 1:
```
input: 2, 0, 1
output: 2.0
```
Examlpe 2:
```
input: 3.0, 0, 0.0, 2
output: 18
```
UPDATE:
* C > 0 is also assumed
* the area is between the curve, y=0, x=C **and x = 0**
* the input can be a list of any form; not necessarily comma separated.
* the output can be a real of any form (thus, '18' is a valid output, as is '18.0')
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 [bytes](https://github.com/abrudz/SBCS)
```
⊃⊥∘⌽⊢÷⍳∘≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGCo@6WxSAPBfPMCDX8P@jruZHXUsfdcx41LP3Udeiw9sf9W4G8ToX/U8DKnjU2wdUcWi98aO2iUBdwUHOQDLEwzP4f5qCkYKBgiFXmoIxkDZQMAKyzBUMgaLGCiYKpgpmAA "APL (Dyalog Unicode) – Try It Online")
A tacit function that takes `C, a0, a1, ...` as a single vector argument.
**12 bytes** if a full program is needed. Note that, while the default representation for a numeric vector is the numbers separated by spaces (no comma or anything), it accepts comma-separated ones since `⎕` evals the input and `,` is the "concatenate" function.
```
(⊃⊥∘⌽⊢÷⍳∘≢)⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGCo@6WxSAPBfPMCDXkOtRR3vaf41HXc2PupY@6pjxqGfvo65Fh7c/6t0M4nUu0gSq/Q9U9J8zjctIwUDBkAvIMAYyDBSMQExzBUMFIwVjBRMFUwUzAA "APL (Dyalog Unicode) – Try It Online")
Uses `⎕IO←0` and `⎕DIV←1`, so that the range generation is 0-based and division by zero gives 0.
Because the polynomial is nonnegative and the integral starts at 0, it suffices to evaluate the antiderivative of the given polynomial at C.
The antiderivative of \$a\_0 + a\_1x + a\_2x^2 + \dots\$ is \$a\_0x + \frac{a\_1}{2} x^2 + \frac{a\_2}{3} x^3 + \dots\$. Because we have C attached to the start of the vector, we simply divide the entire array by their 0-based indexes:
```
C a0 a1 a2
input: 3 0 0 2
div : 0 1 2 3
res : 0 0 0 2/3
0 a0/1 a1/2 a2/3
```
Then we simply evaluate the resulting polynomial at C.
### How it works: the code
```
⊃⊥∘⌽⊢÷⍳∘≢ ⍝ Input: single array of C, a0, a1, a2, ...
⍳∘≢ ⍝ 0-based range 0, 1, 2, 3, ...
⊢÷ ⍝ Divide self by above
∘⌽ ⍝ Reverse
⊃⊥ ⍝ Convert from base C to real number
⍝ i.e. evaluate the polynomial, lowest term given last
```
[Answer]
**Python - 71 63 chars:**
```
a=input()
print sum(1.*a[i]*a[0]**i/i for i in range(1,len(a)))
```
It's a simple integration of a polynomial function between `0` and `C`.
And I haven't tested it, but I'm quite sure it works for negative values.
[Answer]
## J, 26 characters
```
f=:3 :'((1}.y)&p.d._1)0{y'
```
e.g.
```
f 2 0 1
2
f 3 0 0 2
18
```
[Answer]
## Mathematica: 48 Chars
.
```
Sum[#[[i+1]]#[[1]]^i/i,{i,Length@#-1}]&@Input[]
```
[Answer]
## Haskell, 85 characters
```
f(c:l)=sum.map(\(i,x)->x*c**i/i)$zip[1..]l
main=getLine>>=print.f.read.('[':).(++"]")
```
[Answer]
# APL(NARS), 8 chars, 16 bytes
```
∘{⍵⊥⌽⍺}∫
```
The new NARS2000 function integrate, ∫.
it seems f∫b is integrate(f, 0..b)=∫\_0^b f
Here i don't know if can be ok, the right argument is the max of interval of integration [0, max]
and the left argument is the list of numbers represent polinomy...
```
f←∘{⍵⊥⌽⍺}∫
0 1 f 2
2
0 0 2 f 3
18
1 2 3 4 5 6 f 7
137256
```
[Answer]
## Ruby, 65 chars
```
i=s=0
c=gets(q=",").to_f
$<.each(q){|a|s+=a.to_f*c**(i+=1)/i}
p s
```
The code reads until the end of input, not the end of the line. So you need to hit `Ctrl`+`D` to terminate input. (Pipe the input in using `echo` or from a file.)
[Answer]
## C GCC ~~186~~ 182 bytes
```
f(){i=0,l=1;float *d,s=0.0;d=malloc(sizeof(float)*50);scanf("%f",&d[0]);while(getchar()!='\n'){scanf("%f",&d[l]);l++;}for(i=0;i<l;i++)s+=d[i+1]*pow(d[0],(i+1))/(i+1);printf("%f",s);}
```
This program gives an output (area) for any curve between the curve, y=0, x=C and x=0. It can take coefficients (`float` as well) from a0 to a48. The first accepted input is `C` followed by coefficients. Press `Ènter` after the last coefficient.
```
void f()
{
int i=0,l=1;
float *d,s=0.0;
const int sz=100;
d=malloc(sizeof(float)*sz);
scanf("%f",&d[0]);
while(getchar()!='\n')
{
scanf("%f",&d[l]);
l++;
}
for(i=0;i<l;i++)
s+=d[i+1]*pow(d[0],(i+1))/(i+1);
printf("%f",s);
}
```
[Answer]
# Mathematica, 48 bytes
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8tOjE@1so2uDQ3OjE6OlPbMDZWC8gAUnGZ@pk61Zk6hjo@qXnpJRkOibqGtbFADdUKRjoKBjoKQJ6@fkBRZl4JF1DQWM8ALGoAoo3gUv8B)
```
f[a_]:=Sum[a[[i+1]]*a[[1]]^i/i,{i,1,Length@a-1}]
```
] |
[Question]
[
Sometimes I feel like the conversation is going down the wrong path and take it upon myself to steer it in another direction. And this conversation is going wrong real fast, so I need to change the subject in as few characters as possible.1
## Task
Given a list of sentences, return the sentences ordered such that each sentence "connects" to the next.
For the purposes of this challenge, a sentence is a string, starting with a capital letter, containing words separated by spaces (there won't be punctuation between words), and ending with a period.
Two sentences "connect" if they share at least two common words. For example, the sentences "Once upon a time giraffes roamed the land freely." and "Another species that roamed freely were elephants." connect because they share the words "roamed" and "freely", while the latter sentence does not connect with "I love eating sandwiches." because they do not share any words. Note that the first and last words of the sentence can be compared with the others as well, and the first word starts with a capital letter while the last word ends with a period.
The input is guaranteed to have a valid output. Both an output and its reverse will be valid, so you may output either or both. The input may have multiple valid orders.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
## Test cases:
You must output the sorted list, but for the sake of brevity I will write the test cases as returning a list of zero-based indices of the original list.
```
"Once upon a time giraffes roamed the land freely."
"An awful lot of stories start with the phrase once upon a time."
"Another species that roamed freely were elephants."
-> [1, 0, 2] or [2, 0, 1]
"I hear that he is the worst."
"Did you hear that Mr. Jones is running for president."
"He should not be in charge of making our sandwiches."
"The worst sandwiches in the world."
-> [1, 0, 3, 2] or [2, 3, 0, 1]
Please comment suggested test cases, I suck at this.
```
---
1 This is a totally logical explanation for why this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). üôà üôâ
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
Ṗ'ɽ⌈Ǎ¨p‡↔ḢA
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4bmWJ8m94oyIx43CqHDigKHihpThuKJBIiwiIiwiW1wiT25jZSB1cG9uIGEgdGltZSBnaXJhZmZlcyByb2FtZWQgdGhlIGxhbmQgZnJlZWx5LlwiLCBcIkFuIGF3ZnVsIGxvdCBvZiBzdG9yaWVzIHN0YXJ0IHdpdGggdGhlIHBocmFzZSBvbmNlIHVwb24gYSB0aW1lLlwiLCBcIkFub3RoZXIgc3BlY2llcyB0aGF0IHJvYW1lZCBmcmVlbHkgd2VyZSBlbGVwaGFudHMuXCJdXG5bXCJJIGhlYXIgdGhhdCBoZSBpcyB0aGUgd29yc3QuXCIsIFwiRGlkIHlvdSBoZWFyIHRoYXQgTXIuIEpvbmVzIGlzIHJ1bm5pbmcgZm9yIHByZXNpZGVudC5cIiwgXCJIZSBzaG91bGQgbm90IGJlIGluIGNoYXJnZSBvZiBtYWtpbmcgb3VyIHNhbmR3aWNoZXMuXCIsIFwiVGhlIHdvcnN0IHNhbmR3aWNoZXMgaW4gdGhlIHdvcmxkLlwiXSJd)
Inputs list of all sentences, outputs all ways the sentences could be joined together as sentences.
## Explained
```
Ṗ'ɽ⌈Ǎ¨p‡↔ḢA
·πñ' # Keep permutations of the input where:
ɽ⌈Ǎ # Each lowercased sentence split on spaces with punctuation removed
‡ # With:
‚Üî·∏¢ # Set intersection and head remove (which can be used as a len(x) > 1 check)
¨p # Applied to all overlapping pairs
A # Is all truthy.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
≈ì 팵l¬®#}√º√•O2@P
```
Input as a list of sentences. Outputs all possible results as a list of lists of sentences.
[Try it online](https://tio.run/##XY27DcIwEEBXOZkWpWACmCD0iOIgZ2zJ8UXniyIKloAZkFiAjoqIhoKVTCCioX8fTrjxlPPj9Dy@ruF@mRz6W38uZ/NlzitTxi1B23AEBPU1wc4LWksJhLGmCtQRBIwVWCEK@8JMzWKAO9sGCKzAFpKy@MFIiqLQeXVfq3GCiYD/DmOBB0IgNbT9mOpQf8PxAx0JAQVqHEZNhVm/AQ) or [verify all test cases](https://tio.run/##XZAxTgMxEEV7TjEyBc2SIhJCogEkCoKEQkEXpXCys7GF41mNbVYp0nAEKHICJApa0gSaXdFQcAgustgJQYjOGv0374/JyZHG9lb0bBm8OwKRzepVVi@Pd0Q/@N9Z@/7wcf/5Yuqn3Xnz2jz2uydX7fzr7rle1ctus2jeErO3f3jQLNKrHQxE344RQkkWJHg9RZholkWBDpjkFHPwCsFIm0PBiGbWEZk4jeGqCAYMeaACnCfWkXBesodKe7WmSsXSIdA/w2YDxQSDK3GcSK@k3wo3HqiQEdBgqaT1riOG2UD0QKHkTToKtFt7KmLn09YzncOMwp/QJXfggmw0xCwHa7WdQEEMJaPTOdo1d47gFAWTQ6wFo7jYwlhJnmC6bipvEkUh1o3/UOmxQpew6637zzyhP51MHksPvwE).
**Explanation:**
```
œ # Get all permutations of the (implicit) input-list of sentences
í # Filter it by:
ε # Map over each sentence in the current list:
l # Convert it to lowercase
¨ # Remove the trailing period
# # Split it by spaces to a list of words
}ü # After the map: loop over overlapping pairs of lists of words:
å # Check for each word in the second list if it occurs in the first list
O # Sum each inner list of truthy/falsey results together
2@ # Check for each inner sum whether it's >= 2
P # Product to check whether it's truthy for every overlapping check
# (after which the filtered list is output implicitly as result)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 131 bytes
Prints all valid solutions.
```
f=(a,o,p)=>a.map((s,i)=>s.split` `.map(q=w=>q[v=parseInt(w,36)]=v).filter(v=>p?p[v]:1)[1]&&f(a.filter(_=>i--),[o]+s,q))+a||print(o)
```
[Try it online!](https://tio.run/##XZBPa@MwEMXv@RRDDsWijqEUSmlxlsIetgtLL70Z087ao0hbRVJmZJtCv3sq508pe5Tm/d6bN/9wROnYxrQab/d7XRdYhjKqeo3VFmNRSGnzQyqJzqZXeD387uqpXu@asY7IQo8@FVN5faPaelSVti4RF2O9jj9iM7Z3V6q5ai8udIHn2Uu9tquVKpvQXkq5U@oSPz4i2@wT1F4XzQJg@eQ7giEGDwjJbgk2llFrEuCAW@ohGQKHvgfNRO69WpYz9pD1kx4cuJAgaJAU2GZIEnKCySZzAKNhFILwX8iXScgiBonUzXAymM6xxzSYiAnIUTTok1TLRavu4dhB3S9OHR7BEPIRz6FWDtlTYEmnpJ@2h/cwfNP94Qp@B59Ts5wH763fgA6czUlsT/6M/iIQEwbXQ94W/mZ7D51B3tDce4tvMxiG3CIfabKdITmRz@clvo1m@rSc64919p8 "JavaScript (V8) – Try It Online")
### How?
The good thing about `parseInt(s, 36)` is that the strings `"abc"`, `"Abc"` and `"abc."` are seen as three variants of the same base-36 number and therefore evaluate to the same value (`13368` in that case).
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = list of sentences
o, // o = output string
p // p = lookup object for the words in the previous
) => // selected sentence
a.map((s, i) => // for each sentence s at index i in a[]:
s.split` ` // turn s into an array of words
.map(q = // let q be an object
w => // for each word w:
q[ //
v = // v = result of ...
parseInt(w, 36) // ... base-36 parsing of w
] = v // save it in q
) // end of map()
.filter(v => // filter the result:
p ? // if this is not the first iteration:
p[v] // see if v was defined in the previous sentence
: // else:
1 // keep all entries
)[1] && // end of filter; if we have at least 2 matches:
f( // do a recursive call:
a.filter(_ => // pass a copy of a[] where
i-- // the i-th entry is removed
), //
[o] + s, // append s to o
q // set p = q
) // end of recursive call
) + a || // end of map(); if a[] was empty:
print(o) // print the output string
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
á f_˸mn36Ãäf mÅeÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=4SBmX8u4bW4zNsPkZiBtxWXK&input=WyJPbmNlIHVwb24gYSB0aW1lIGdpcmFmZmVzIHJvYW1lZCB0aGUgbGFuZCBmcmVlbHkuIgoiQW4gYXdmdWwgbG90IG9mIHN0b3JpZXMgc3RhcnQgd2l0aCB0aGUgcGhyYXNlIG9uY2UgdXBvbiBhIHRpbWUuIgoiQW5vdGhlciBzcGVjaWVzIHRoYXQgcm9hbWVkIGZyZWVseSB3ZXJlIGVsZXBoYW50cy4iXQotUQ)
[Answer]
# [Python](https://www.python.org), ~~181~~ 157 bytes
```
lambda l:[p for p in permutations(l)if(z:=[s.lower()[:-1].split()for s in p],all(sum(k in i for k in j)>1for i,j in zip(z,z[1:])))[1]]
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZHBahwxDIbpdZ5C7MlTNgN7KwspFHpoCyWX3KZzcHbktROPZWSZYfcJ-g4lsBDad2qfpp5xUkJPlrA-_fqlH7_iSSyFy5O5_vYzi7l69_vR6-lu1OD3fQRDDBFcgIg8ZdHiKCTlW2fUeX_dp87TjKzafn-1G7oUvRPVLlBaoWGrvVcpT-phyd3abw3v2_e7JXHb-yU9u6jO23O_2w9t2_a7YWgM0wROkIXIl3ZTJJa3dcg_b75HdkGUUX2zuQkHhBwpgAZxE8LRsTYGEzDpCUcQi-B1GMEwoj91m22z-VCqZ5M9eBIgA0mIXUGSaBaYndgVi5Z1QqD_JJ5bUCkpXiMeFlSslhfJqgRlOQjoMVodJHWbpthrmjr7v2A18Rksaq49iq5Lq_xMnGQV--hGOFF-VfWVO_hCoQiXYs4huHCsB2NMbsRQwU8IyVL2I5Rx4Q6XdR-s5iMutif9sGCUi42yodkdLKaVu32Rf_WxsM9j-bG6qQe5XOr7Fw)
Returns all valid orders.
* -14 thanks to Steffan
## [Python](https://www.python.org), ~~165 163~~ 159 bytes
```
def f(l):
for p in permutations(l):m=[s.lower()[:-1].split()for s in p];any(sum(k in i for k in j)<2for i,j in zip(m,m[1:]))or print(p)
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZKxbhsxDIaR9Z6C8HQXOAckU-EkQ4AObYEgSzfDg-KjLCWSKFAUDs6rdEiW9p3ap6mki4Egmwjy4_-T1K8_8SiGwtvb7yz64svf1wk16N4Nmw40MUSwASKyz6LEUkg15W-3aXQ0I_fDdnNxuRtTdFb6oRKpEbtrFY59yr5_rrFtzdrzabi5qoFdP9Xwxcber_32crMbhirINkgfh04zebCCLESuNPWRWM4Xm__OXnS_7VYPYY-QIwVQINYjHCwrrTEBk_I4gRgEp8IEmhHdcVytu9VdqZ51duBIgDQkIbYFSaJYYLZiGhYNq4RAnyTeW1ApKbNG3FdUjJKT5KIEZTkI6DAaFSSNq243dN0yXHk099_BoOIFLoI2Nd2ZOElT-WonOFL-UHXPI_ygUBRLMecQbDgsZ2JMdsKwgN8QkqHsJig-4RHrnvdG8QHrvF49V4xy8V9WM9u9wdS4nyf5D4nKvttyUxtjOcHpx_wH)
Based off Kevin Cruijssen's 05AB1E answer. Prints all valid orders.
* -4 thanks to Steffan
[Answer]
# [Rust](https://www.rust-lang.org), 375 bytes
```
|a:Vec<&str>|{let b=a.iter().map(|i|&i[..i.len()-1]).collect::<Vec::<_>>();f(&b.join(" "),b)};fn f(w:&str,p:Vec<&str>)->bool{p.len()<1||match p.iter().find(|k|{w.split(" ").collect::<HashSet<_>>().intersection(&k.split(" ").collect()).count()>1&&f(k,p.clone().into_iter().filter(|d|d!=*k).collect::<Vec<_>>())}){Some(u)=>print!("{u}.
")==(),_=>false}}use std::collections::*;
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZHBitswEIbp1U8x8cFISyLIrTixodDDtlB62NLLsgTFHsVqZMlIcs1i59536CWH9gX6OH2aynbShqUXe8TM_3_zS99_2Nb58y-hoeZSEwp9pNDDIfvZerF6_ftVN_D0MxbbxHmbD_3Y3GecSY-WUFbzhgxySOQjY5IpDA6r9RNlhVEKC5-m26AN312eE7oRJNmzLyZwYojpck9PmwAWpEtH92XzD0RX-d4Y1Tez53Y9DDX3RQXNlSykLslwHPqOuUZJP1necO-5qx7Qz2QmdVC50JFGk-T4HwmhY9nqUOTrJBHkuGxYoYzGWW52f8FqLIZyKBfZ3fFF1plHT7R_MDWSlmZ5Y4N8QeK-PbEopllG6HKX5YIrh6dT6xCcL9P0YhMWdGl6t7ne_7cD-YrF4jH-qAuEtjEaOHhZIxyk5UKgA2t4jSX4CkFxXYKwiOqZxcsofhOmO9EqUMaDEYFkrAwS57n10ElfTbKmsjzsYV4gLhYmjFhwDRaj1FfcX5EzCTq0CKiwqbj2jsVPdBNFU2ylQ_A4HC8povgdVMjt7BLI0k0LdMY6P-HeyhKeTXsz9cEyeB_ewY3DttVa6gMIY6Gx6GSJehbeh3usTKtKCAvDPlhrKCpuDzgGr_lxlJk2BAl31MmiQjfpPl3xN41Re1lLlXOe0_wg5_P8_wM)
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, ~~76~~ 73 bytes
```
[ [ [ " "split ] map 2 clump [ last2 ∩ { } = ] ∄ ] find-permutation ]
```
[Try it online!](https://tio.run/##XVLBjtMwEL33Kx45b6Pd7g0EAmklWCTgAJyqHlxnkljr2GY8VlSteuOwv8Jv7Y@USdtAtYkUKZ735r03ntZYiXz4@f3@68fXyMk7ERc6ZPpVKFjK6DiWdDqSjMFIX9s4bF0wSnT2fFSCs7EhPBAH8khMIrvELggUnZwnroWJ6sQxmc6Ii6G2xvsltS1ZwZvF4nEBfapvKouSYoCBuIHQOTYKyuBoBmogPcGb0KDVhn5XVyfeByWMbfHwURBb5MmfsrIYFoxO@iMz9WwyIb5Q@d8lKop1FGQntvRGZuGTHkZiAnlKvQmSz8RXWL7D@uYK11dYbRAZ69Xx52az2M/R7tGT4VNPteLy0dEYOcusf@ca7GK5AH7hGp9jUC@K5xLCdBmtCuiQs2so/ON@IuQ@Ft9AQ2CrAgG2N9zRNI/BPEzMWDScTm90tqfZffVj9nFRm@hnf75R4P5FzNvLpLfnsIc1prdCdVwmbFQ3YQXry5C04E2WFZ6f/uARe7zV@vPTb/22LjTLRDwUOS4Hpk51XWtpWqCoV7Z17w9/AQ "Factor – Try It Online")
* `[ ... ] find-permutation` Find the first permutation of the input that...
* `[ " "split ] map` ...when all sentences are split into words...
* `2 clump` ...and grouped into overlapping pairs...
* `[ last2 ∩ { } = ] ∄` ...none of the intersections between pairs of sentences are empty.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 41 bytes
```
PMgFI{$&((LC(aM H_^s)MP{YbaM_Ny})M1N_>1)}
```
Very golfable, but I'm happy with it.
[Attempt This Online!](https://ato.pxeger.com/run?1=Xc_NagIxFIbhW_kIIjOggruuClIoLTTqVqQdTvXEBOIkJGcYRLySbgql3fWCvJtO_emi--85L-ftI7r4tVTDqJ7fPxsxw5tjOdeb-8d9r18UT3cFaTxUL7nU8_3ilXQ13R1KPZ5Wt-PycAZX971Us3rFaGKoQRC3ZWxcImM4IwXa8hpiGZ7qNUxi9ruRGkBNunVrGg8fBMEgS0iuI1koCVon9sSiTZQZ4V_iciJ0k4QcefVLxZJck-cSWk4M9hwt1ZL_vv0B)
**Explanation**:
```
PMgFI{$&((LC(aM H_^s)MP{YbaM_Ny})M1N_>1)}
PMgFI{ } Filter out permutations of the input by ...
LC(aM H_^s) Remove dot, split by space and lowercase each sentence
MP{ } For consecutive pairs of all sentences,
YbaM_Ny Does each word of the first pair appear in the second pair?
M1N_>1 Is the count of 1s greater than 1 (>= 2)
$& Are all elements truthy?
```
] |
[Question]
[
You are given a non-empty list of positive integers. Your task is to figure out how many **distinct** numbers can be obtained by applying the following algorithm:
1. Remove either the first or the last item from the list and initialize **N** to the corresponding value.
2. Remove either the first or the last item from the list. Let's call its value **v**.
3. Update **N** to either **N + v** or **N \* v**.
4. If the list is empty, stop here and return **N**. Otherwise, resume at step 2.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Detailed example
Let's say that the input is:
```
[ 1, 5, 2, 3 ]
```
We can do, for instance:
```
[ 1, 5, 2, 3 ] - choose 3 ==> n = 3
[ 1, 5, 2 ] - multiply by 2 ==> n = 6
[ 1, 5 ] - add 1 ==> n = 7
[ 5 ] - multiply by 5 ==> n = 35
[] - done
```
That's the only way of getting 35. But there are many different ways of getting, say, 11:
```
1 +5 +2 +3
3 +2 +1 +5
3 *2 +5 *1
etc.
```
All in all, we can generate 19 distinct numbers with this list. Only one example solution is given below for each of them.
```
10 : 3 +2 +5 *1 | 16 : 3 *1 +5 *2 | 22 : 3 +1 *5 +2 | 31 : 3 *2 *5 +1
11 : 3 *2 +5 *1 | 17 : 3 *1 *5 +2 | 24 : 1 +5 +2 *3 | 35 : 3 *2 +1 *5
12 : 3 *2 +5 +1 | 18 : 3 +1 +5 *2 | 25 : 3 +2 *5 *1 | 36 : 1 +5 *3 *2
13 : 3 +1 *2 +5 | 20 : 1 +5 *3 +2 | 26 : 3 +2 *5 +1 | 40 : 3 +1 *2 *5
15 : 1 +5 *2 +3 | 21 : 1 *5 +2 *3 | 30 : 3 *2 *5 *1 |
```
So, the expected answer for this input is **19**.
Below are two examples of **invalid** solutions:
```
32 : 5 *3 +1 *2 -> 5 can't be chosen at the beginning
32 : 3 *5 +1 *2 -> 5 can't be chosen after 3
```
## Test cases
```
[ 7 ] -> 1
[ 1, 1 ] -> 2
[ 2, 2 ] -> 1
[ 1, 2, 3 ] -> 5
[ 7, 77, 777 ] -> 8
[ 1, 5, 2, 3 ] -> 19
[ 2, 2, 11, 2, 2 ] -> 16
[ 2, 2, 2, 2, 11 ] -> 24
[ 21, 5, 19, 10, 8 ] -> 96
[ 7, 7, 7, 7, 7, 7 ] -> 32
[ 6, 5, 4, 3, 2, 1 ] -> 178
[ 1, 3, 5, 7, 5, 3, 1 ] -> 235
[ 9, 8, 6, 4, 5, 7, 3 ] -> 989
[ 7, 4, 6, 8, 5, 9, 3 ] -> 1003
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes
```
{{|{|↔}~c₂l₁ʰ↰ᵗc}{+|×}ˡ}ᶜ¹
```
[Try it online!](https://tio.run/##AUMAvP9icmFjaHlsb2cy//97e3x7fOKGlH1@Y@KCgmzigoHKsOKGsOG1l2N9eyt8w5d9y6F94bacwrn//1sxLDUsMiwzXf9a "Brachylog – Try It Online")
Times out on test cases of length 5 or greater.
It can probably be golfed further; the first half feels clunky.
# Explanation
```
{…}ᶜ¹ Count unique outputs for predicate.
{|{|↔}~c₂l₁ʰ↰ᵗc} First part: permute list by reversing and recursing.
{| } Either return input unchanged, or
{|↔} possibly reverse it,
~c₂ split it into two parts,
l₁ʰ check that the first part has length 1,
↰ᵗ call this sub-predicate on the second part,
c and plug the first part back.
{+|×}ˡ Second part:
{ }ˡ left fold by
+|× addition or multiplication (chosen separately for each element).
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~102~~ 99 bytes
```
lambda v:len({*f(v,0)})
f=lambda v,N:v and sum([f(k,N*a)*N+f(k,N+a)for a,*k in(v,v[::-1])],[])or[N]
```
[Try it online!](https://tio.run/##TY5BDoIwEEX3nGJ2tDgktsaQNOIRuEDtokaKRi2GVhJDODsWCMpiMvPfn5/818dfa7sbqvw0PPTzfNHQikdpSZcY0uKW9jQy@eJgIVrQ9gLu/STSkDsWiaZJsZnOjaambkBjcoebDelWCpEyRRVKRetGFmrwpfMOcpARgMwUjoshsPniCPzHgtjNIkPIpvkH9mufT4LNGb5mixOYiqKx3VggtJu2E@Hz1dysJybunG/ISKk4cNZDeoSumkEf0@EL "Python 3 – Try It Online") Runs out of resources for the larger test cases on TIO.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~40~~ 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„RćD¦‚Ig©ãεvy.Vˆ]¯®ô„+*®<ãðδšδ.ιJ˜€.VÙg
```
[Try it online](https://tio.run/##AWQAm/9vc2FiaWX//@KAnlLEh0TCpuKAmklnwqnDo861dnkuVsuGXcKvwq7DtOKAnisqwq48w6PDsM60xaHOtC7OuUrLnOKCrC5Ww5ln//9bNyw0LDYsOCw1LDksM13/LS1uby1sYXp5) or [verify most test cases](https://tio.run/##yy9OTMpM/V9W6RJqr6TwqG2SgpL9/0cN84KOtLscWvaoYVZl@qGVhxef2xpRXFapF3a6rbb20PpD6w5vAarR1jq0zubw4sMbzm05uvDcFr1zO71Oz3nUtEYv7PDM9P86h7b8j442j9WJNtQxBJJGOkZgtpGOMZA21zEHIYi0KVQQqETHEKTCCMqBCIA4IEWGljqGBjoWEN0wCOSZAeVMdIxBamNj/@vq5uXr5iRWVQIA). (The last three test cases are too large for the test suite due to the `ã` builtin, although can still be verified in the loose TIO.)
**Explanation:**
```
„Rć # Push string "Rć"
D # Duplicate it
¦ # Remove the first character: "ć"
‚ # Pair them together: ["Rć","ć"]
Ig # Get the length of the input-list
© # Store this length in variable `®` (without popping)
ã # Get the cartesian power of the ["Rć","ć"] with this length
ε # For-each over the list of list of strings:
v # Inner loop over each string `y` in the list:
y.V # Evaluate/execute `y` as 05AB1E code on the (implicit) input-list:
# `ć` extracts the head; it pops the list and pushes the remainder-list
# and first item separated to the stack
# `Rć` reverses the list first, before doing the same
ˆ # Pop and store this top value in the global array
] # Close the nested loops
¯ # Push the global array
®ô # Split it into parts equal to the length `®`
„+* # Push string "+*"
®< # Push length `®` minus 1
ã # Get the cartesian power of the "+*" with this length-1
δ # For each list in this list of strings:
ð š # Convert the string to a list of characters, and prepend a space character
δ # Apply on the two lists double-vectorized:
.ι # Interweave the two lists
J # Join each list of strings together to a single string
˜ # Flatten this list of lists of strings
€ # Map over each string:
.V # And execute/evaluate it as 05AB1E code
Ù # Then uniquify the list of resulting values
g # And take its length to get the amount of unique values
# (after which it is output implicitly as result)
```
Example input: `[1,5,2,3]`
Example list of strings: `["ć","Rć","Rć","ć"]`
Example operations: `["+","*","+"]`
This will become string `"1 3+5*2+"`, which evaluated/executed as 05AB1E (Reverse Polish notation) results in `22`.
[Answer]
# [J](http://jsoftware.com/), ~~88~~ 71 bytes
```
([:#@~.@,(+`*>@{~])}.@,@,."2/&.:":(,:@{~(+&(|*+/\.-0&<)<:)"1))2#:@i.@^#
```
[Try it online!](https://tio.run/##NY3NDoIwEITvPsUEEmgFKm1RYAXTxMSTJ6/@xJNEX0Hl1XEpmO1s@s3Otq8hUPEDLSFGihzEyhT2p@NhEGcKXa9cKpL7cufe/VV@mVyqArOKFAUkUmJbJJH4LJPVRWV51MiGZKClNCG5p3K3cJBD19L2sehQsjQ0dwPj7wZ29FGOZxqvZ5Mj0HpOmrm0Xx5DuobOUU3b/2La8KyAHbP@OctcsqznGhUnCu9NPxfMFXMN@wM "J – Try It Online")
### How it works
From the permutations of taking the first/last element, we calculate absolute indices. With this we get all possible orders of selecting elements without recursion. Converted to strings and interwoven with `+` or `-`, we can execute them to get all numbers to count the unique.
```
2#:@i.@^#
```
Build up all boolean possibilities up to the length of the input.
```
(+&(|*+/\.-0<])<:)"1)
```
The boolean lists get added from right to left and then multiplied with its absolute value (thus zeroing itself out): `0 1 1 0 0 1 -> 3 3 2 1 1 1 -> 0 3 2 0 0 1`. The same happens with the decremented list, so `_1 0 0 _1 _1 0 -> … -> _3 0 0 _2 _1 0`. If the numbers are positive, we decrement them `-0<]` to account for 0-based indices. We then add both lists up: `_3 2 1 _2 _1 0`. This is the reverse of numbers to pick as J binds right to left.
```
,:@{~
```
Get the numbers at the indices, with `_1` taking the last and so on. Itemize each number.
```
(+`*>@{~])
```
The original boolean lists mapped to operators, `0 -> +, 1 -> *`.
```
}.@,@,."2/&.:":
```
Interpret each number as a string, make a table of all numbers and the operators, dropping the first operator with `}.` (`7 + 777 * 77`). With `&.:` the right operator gets reversed, and thus J interprets this string as a number.
```
[:#@~.@,
```
With the list of possible numbers, remove duplicates and get the length.
[Answer]
# T-SQL, 228 bytes
Input is a table variable:
```
WITH C as(SELECT v u,1/i+1f,@@rowcount-sign(i-1)t FROM @
WHERE i in(1,@@rowcount)UNION ALL SELECT o,f+SIGN(t-i),t-i/t
FROM c JOIN @ ON i in(f,t)and f<=t
CROSS APPLY(values(v*u),(v+u))p(o))SELECT
count(distinct u)FROM C WHERE f>t
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1258427/how-many-numbers-can-we-make)**
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes
```
≔E³Eθ§θ⁺ιμθFθ¿⊖Lι«≔E²⊟ιηF⟦ΣηΠη⟧F²⊞θ⁺⎇λ⮌ιι⟦κ⟧»F¬№υι⊞υιILυ
```
[Try it online!](https://tio.run/##TY7NS8QwEMXP279ijhOIB3fx1NOyXgSVot5KD6Gd3QTTZJuPRRH/9jipHzgQ5iXv5ccbtQqjV7aUfYzm5PBBnXEnoa5Fwj7duYnequxsjmgkzIJHwiLa5ugD4CLAHAFvaQw0k0s04T25U9JoOAgfzeYfecscf66OBM2EzYron/OMmp@64Kc8JtaDgNXaCuhy1H8FXig4Fd7RSniiC4VIDJNQT/86CEZ@NmQjff9@9AkPPruEuWbED2y9tE0XDDsHFdNv48yRtpS@h2sJNxK47g6GoVxd7Bc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔E³Eθ§θ⁺ιμθ
```
The first two numbers to be added or multiplied can either be the last two numbers in the list, the last and the first, or the first two. Create three cyclic rotations of the list with each combination ending up at the end of the list.
```
Fθ
```
Start a breadth-first search.
```
¿⊖Lι«
```
If this entry still has 2 or more numbers, then...
```
≔E²⊟ιη
```
... remove the last 2 numbers into a separate list, ...
```
F⟦ΣηΠη⟧
```
... take their sum and product, ...
```
F²⊞θ⁺⎇λ⮌ιι⟦κ⟧
```
... and append that to both the remaining numbers and their reverse, so that the number at either end gets to be combined on the next iteration.
```
»F¬№υι
```
Otherwise if this entry hasn't yet been seen, then...
```
⊞υι
```
append it to the list of distinct entries.
```
ILυ
```
Print the length of the final list.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~235~~ 232 bytes
```
#include<set>
using I=int;
void g(I n,I*f,I*l,std::set<I>&s){if(f-l){g(n**f,f+1,l,s);g(n+*f,f+1,l,s);g(n*l[-1],f,l-1,s);g(n+l[-1],f,l-1,s);}else s.insert(n);}I f(I*f,I*l){std::set<I>s;g(*f,f+1,l,s);g(l[-1],f,l-1,s);return s.size();}
```
[Try it online!](https://tio.run/##lVVtj6IwEP7Or5jzcm6RuhHxXZfv/gbXXDwobhOuGFq95Ai/3ZsWUHDB7DVSh84888yLHYPTaXgMguv1OxdBfA7ZRjLlW2fJxRG2b1yotXVJeAhHsgVBt4MIn5hKFa5WaLnZ@n1pZzwi0TC2syMRA7SIHJeijb3Gd@fhfRDvhu6eRjQeupXJw1HOYslAvnIhWaqIwJMtRKTktrMauUR8k@DBV8rUORXoTPK/jKCnW6KwCdART3zrfnJhgUpS38K0kRB39K332F5b5vCU4v4TzUiQCKnAhFKgNqjxoX@xIbOgXDcIC@GtkCLSy6CH/iqbw1klwBXqL6@/2JEL8qhkIjRa/K7reARE4960QZ21WhWzc6fO68w5mEJ/Cfgj7FEYcOU4NQfV@vPBY2aC@dYZzBPfFJ56z78SHzQzu0ll/0vE2sqLPv4@YJ3177oear2ZRj4deCnVWkx1V30fFJNKYl8@p5pl85xC93Jz2oJxqVZ0YcatmDHViv/mQZjXAZu2YuYU5uZpTWzRxTPtpnKXnQlhHYoYP6Xmzp6AKugjaDxpBxXxuUt8RlTnUNcvZ511qH@aIK@9STNDNMFCFBE2Qe68s3yeAc7N7jWBY6@9UZjNgsLM0BXYevWXi2VXWhODWhjUsolyRyOvBstxFFZylKRAzIzq7/R9oHjf5DlWe1gV96NtErQMRTNRNaB7uJQIx4ENjKc2nM4q@Dik5AVeWkD3sQW9KqgWMx2KwCAi0tfsu9GeQiHprfzP2D/1/y6QQDRmT379Bw "C++ (gcc) – Try It Online")
Usage: `int result_count = f((int*) first, (int*) last);` where `first` is a pointer to the first element of an `int` array, and `last` is the pointer to one past the end of the array.
Assumes all results an intermediate values will fit in an `int`.
Explanation: Using a `std::set<int>` to keep track of which results have been found, recursively checks each possible path, then returns the size of the set of results.
Ungolfed:
```
#include <set>
void helper(int N, int *first, int *last, std::set &results){
if (first != last) {
helper(n * first[0], &first[1], last, results); // v = beginning; N = N * v
helper(n + first[0], &first[1], last, results); // v = beginning; N = N + v
helper(n * last[-1], f, &last[-1], results); // v = end; N = N * v
helper(n + last[-1], f, &last[-1], results); // v = end; N = N + v
} else {
results.insert(N);
}
}
int f(int *first, int *last){
std::set results;
helper(first[0], &first[1], last, results); // N = beginning
helper(last[-1], first, &last[-1], results); // N = end
return results.size();
}
```
[Answer]
# perl -alp, 176 bytes
```
@t=([@F],[reverse @F]);while(@t){($N,@l)=@{shift@t};@l?push@t,([$N+$l[0],@l[1..$#l]],[$N*$l[0],@l[1..$#l]],[$N+$l[-1],@l[0..$#l-1]],[$N*$l[-1],@l[0..$#l-1]]):$s{$N}++}$_=keys%s
```
[Try it online!](https://tio.run/##bY3BTsQgFEX3fMVLZBKwnUmBmWlr08jKZX@ANBMXmDYSpymoMU1/XXzU6EYDBM65F5js7E5x56EFxpuoQ8uMfuhzM9s3O3sLCLx5H0ZnmQ58YbTLteOtXvwwPgUd1ka7@@nVDzrkzNAuo84UPXaMOBzojevxLdrd/mtTdy82XWwa4bf@J@B31C@0W7NspZf22X74nY@xJAIEkSBxl6BICWWaSZ82gRGIlMnt@I1EpljUIAqo0p2fQc7oj6BSC59QSCUuhVRDBWfMkkn/HJEqpBrU53UK4/XFx/2jm74A "Perl 5 – Try It Online")
This just tries all possibilities (all \$\frac{2 \cdot (4^n -1)}{3}\$ of them), where \$n\$ is the number of items on the input.
[Answer]
# [Io](http://iolanguage.org/), 157 bytes
(Sort of) a port of ovs's answer, go upvote them!
```
method(v,f(v,0)size)
f :=method(v,N,if(v size>0,list(v,v reverse)map(i,k :=i slice(1);a :=i at(0);list(if(N>0,f(k,N*a),f(k,N+a)),f(k,N+a)))flatten unique,N))
```
[Try it online!](https://tio.run/##bYwxEoJADEV7TpFyoylYUAsZPQInsNnRBTMsC8JC4eUxro5DYZGZn7z/wt1Sw/EEl6W14d7d1EyVTIojPy0mlbAfKImFwZucU3I8BjnOMNjZDqPF1vSKqRGDYXR8tUpjYeJqgkqxiIa8KMWuVEPlxuAnbA2uElbOhGA9TJ4fk6UScalVtDVllCNCP7APziffM2iCPUFGkMMfeoh0JzR29KqzvAA "Io – Try It Online")
# [Io](http://iolanguage.org/), 272 bytes
First time doing BFS, I'm definitely not good at it anyway.
```
method(x,f(0,x,1))
f :=method(L,x,N,if(x size<1,return N)if(L<1,list(f(L+1,x slice(1),x at(0)),f(L+1,x slice(0,-1),x at(-1)))flatten unique size,list(f(L+1,x slice(1),N*x at(0)),f(L+1,x slice(1),N+x at(0)),f(L+1,x slice(0,-1),N*x at(-1)),f(L+1,x slice(0,-1),N+x at(-1)))))
```
[Try it online!](https://tio.run/##fY5NDoIwEIX3nGKWHRkT6t/C6A0IJ3BDtMUmtSiUhHj5OjQQNRF3b973Zt6YOlSwP8Ip3JS/1hfRkxYZ9SQRE81ktHO2CjJa9NCapzpIapTvGgcFspnzbE3rBctUEmesOSshkWXpRYZI3ySj5QRZIGpbeq8cdM48OhUrZg4Wi5mTA0v/1o2rQ@Fvnr4fQgyViB@AJNgSrAjWgAj3xjhvXTLRXaQbpjEjPzLhBQ "Io – Try It Online")
] |
[Question]
[
You're organizing a treasure hunt for your friends. To conduct things more easily, you want to draw a map of all locations where you hid the precious objects.
## Input
Any form of input denoting a list of points consisting of (nonnegative) x- and y-coordinate, `0 0` being the upper left corner is permitted (Note: You may also use 1-based indexing in your answer, please comment on that if you do). Example:
```
1 2
3 0
0 1
```
## Challenge
Your function or program should be able to construct a map denoting every given location with an `x` where the mark is found in row y + 1 and column x + 1 in the output. Unmarked locations are represented with a . The map also consists of a frame where the corners are `+`s, the vertical lines are `|`s and the horizontal lines are `-`s. Your solution should output the smallest possible frame. Map for the input example given above:
```
+----+
| x|
|x |
| x |
+----+
```
## Possible Test Cases
---
```
"0 0"
=>
+-+
|x|
+-+
```
---
```
"0 10
5 5
10 0"
=>
+-----------+
| x|
| |
| |
| |
| |
| x |
| |
| |
| |
| |
|x |
+-----------+
```
---
```
""
=>
++
++
```
---
```
"0 0
0 2
2 0"
=>
+---+
|x x|
| |
|x |
+---+
```
---
Of course, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), meaning that the solution with the lowest byte count wins! Explanations of your solution are encouraged.
[Answer]
# [J](http://jsoftware.com/), ~~37~~ 34 bytes
```
0<@|:' x'{~((i.@]e.#.~)1+>./) ::#:
```
[Try it online!](https://tio.run/##TcoxCoAwEAXR3lN8sIjism4Um0UlF7GSiNrYCkquHlMo2A2P2WNcBob07laD01yhKDZ2k@ecQ2mrkesSqrlGP68HFgisEDp0pKkg2esWDaGFJE7Lp8Z8RfqbSVvY@AA)
```
1+>./ maximum for each coordinate + 1
i.@] make an array with these dimensions filled with 0..x*y
/* if the input is empty,
1+>./ is negative infinity
and i.@] throws an error */
#.~ mixed base conversion of input
e. replace the elements of i.@]
with 1 if it's present in the
converted input, 0 otherwise
( ) :: if there's an error do the other thing instead
#: "to binary", for empty input this returns a 0x0 matrix
0<@|:' x'{~ index into character string, transpose and put in a box
```
[Answer]
# JavaScript (ES6), 150 bytes
Takes input as a list of 1-indexed coordinates in `[x,y]` format. Returns a string.
```
a=>(g=w=>y<h?' |-+x'[4*a.some(a=>a+''==[x,y])|2*(-~y%h<2)|++x%w<2]+[`
`[x=x<w?x:+!++y]]+g(w):'')((M=i=>Math.max(2,...a.map(a=>a[i]+2)))(x=y=0),h=M(1))
```
[Try it online!](https://tio.run/##dYzBisIwFEX3foWzkLznS8M0igvpq1/QLwgBg1PbDq2RqdgEir9e6zCrATeHy72H@@3urj/9NNdbcvFf5XTmyXEOFQ@cx6w@iOWYUBBmu3aq910J8@pICGYTZLQ46jUkj7iqM40jUVgNmbZkjoujCRyy4RD29EEUraUKBtwLgQAFN5wX7larzgXQUinl5nj9PTeNJY2IEDjyJ8qaC0gRp5O/9L4tVesrOIOxiIt/lUllat/1cuZm5ua985J2cvdS/56mJw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~127~~ 123 bytes
This defines the operator `(!)` which takes a list of *x*-coordinates and a list of the corresponding *y*-coordinates:
```
x!y|l<-'+':('-'<$m x)++"+"=unlines$l:['|':[last$' ':['x'|(i,j)`elem`zip x y]|i<-m x]++"|"|j<-m y]++[l];m x=[1..maximum$0:x]
```
[Try it online!](https://tio.run/##PY6xboMwEIZ3nuJPhGQQcVSWDhSydO3WkSLFCk7q1AZkG9WueHd6ZIiXu/t8n@7/Fu5Har2uYRcXXXNWsCpjnNWpQciLYl/sm3nQapAu1VXLFla1WjifMlDHAlsydbjnZ6mlOf@pCQGxW1TNSe9IX/bLfRsiDa3u3gg3bXk8GhGUmU36UoVuNUINaNCPCRCiQ81hxAQrRf9Bl3HEIwDq9ISb9O/j4OXgHW1r6REcuVfnH9@kE95e3LAb@icmPs3@01tkpOxoIU8SznEZB@ftfPHw86QlrnY0cJO4SDg5CSu87KHo5E1alzxDNci@2nCIHT8h2yjC4VFinlPi39H2bi1RlskrXpOSun8 "Haskell – Try It Online")
### Ungolfed/Explanation
The helper function `m` expects a list and returns indices (1-based) up to the maximum, if the list is empty it returns `[]`:
```
m x | null x = []
| otherwise = [1 .. maximum x]
```
The actual operator `(!)` is just a list-comprehension, traversing all the coordinates and choosing a or `x` character, which gets joined with newlines:
```
x ! y
-- construct the top and bottom line
| l <- "+" ++ replicate (maximum (0:x)) '-' ++ "+"
-- join the list-comprehension with new-lines
= unlines $
-- prepend the top line
[l]
-- the actual map:
-- begin the line with | and add the correct chars for each coordinate
++ [ "|" ++ [ if (i,j) `elem` zip x y then 'x' else ' '
-- "loop" over all x-coordinates
| i <- m x
]
-- end the line with a |
++ "|"
-- "loop" over all y-coordinates
| j <- m y
]
-- append the bottom line
++ [l]
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 22 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
ø╶{X;┤╋}l|*eL┤-×+e:└∔∔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JUY4JXUyNTc2JXVGRjVCWCV1RkYxQiV1MjUyNCV1MjU0QiV1RkY1RCV1RkY0QyU3QyV1RkYwQSV1RkY0NSV1RkYyQyV1MjUyNC0lRDcrJXVGRjQ1JXVGRjFBJXUyNTE0JXUyMjE0JXUyMjE0,i=JTVCJTVCMiUyQzIlNUQlMkMlNUIyJTJDMyU1RCUyQyU1QjMlMkMyJTVEJTJDJTVCMTAlMkMxMCU1RCU1RA__,v=2)
Takes 1-indexed inputs.
Finally decided to fix a bug that's been annoying me for ages and golfed this down to [21 bytes](https://dzaima.github.io/Canvas/?u=JUY4JXUyNTc2JXVGRjVCJXUyNTI0WCV1MjU0QiV1RkY1RCV1RkY0QyU3QyV1RkYwQSV1RkY0NSV1RkYyQyV1MjUyNC0lRDcrJXVGRjQ1JXVGRjFBJXUyNTE0JXUyMjE0JXUyMjE0,i=JTVCJTVCMiUyQzIlNUQlMkMlNUIyJTJDMyU1RCUyQyU1QjMlMkMyJTVEJTJDJTVCMTAlMkMxMCU1RCU1RA__,v=2).
Explanation (half-ASCII-fied for monospace):
```
ø╶{X;┤╋}l|*eL┤-×+e:└++ full program, implicitly outputting ToS at the end
ø push an empty Canvas - the map
╶{ } for each array in the input array
X push "X"
;┤ and push the two coordinates separately on the stack
╋ and overlap the "X" there in the map
l get the vertical length of the map
|* repeat "|" vertically that many times
e encase the map in two of those vertical bars
L get the horizontal length of the map
┤ subtract 2 (leave place for the "+"es)
-× repeat "-" that many times
+e encase that line in "+"es
:└ push a copy of that below the map
++ and join the 3 items vertically
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~151~~ ~~140~~ 138 bytes
-2 bytes thanks to Jo King.
Input is 1-indexed.
```
m=input()
w,h=map(max,zip((0,0),*m))
b=['+'+'-'*w+'+']
M=b+['|'+' '*w+'|']*h+b
for x,y in m:M[y]=M[y][:x]+'x'+M[y][x+1:]
print'\n'.join(M)
```
[Try it online!](https://tio.run/##PU6xbsMgEN35ipMXwNAqdqoMlhiTzerSjTLYLpVpY4wQkXGVf3cNVaOT7r27997p3BrG2dbbMH9o4Yui2CZhrLsFQtHCRzF1jkxd5D/GEXLgB8rLiVLUC4nZXk@4XBIq1IqeSXzfOeTdHatyZD36nD1EvoKxMDWtXJVITTZRMRwxy0NkVaOQ88YG/G7x89dsLGnptr@D0DKaq4Y3f9MNAgh@TQCgox4gfZ2nnEVpO2gX4Px6OXs/@z9r73X3vUlSczhSTl44VDtUHGqqkEykepCknDickuFfeJhyKJ04ZuUX "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
≔E²⁺²⌈Eθ§λιηB⊟⮌η⊟ηFθ«J⊟⮌ι⊟ιx
```
[Try it online!](https://tio.run/##VY5Bi8IwEIXPya8Yepqw8aDubU96U1SKeCs9hO7YBtKkNqkUxN8eE8GDc/mG9x4zr@nU2DhlYtRXwJMLeCDbhg5vQgg4UxOUbQ3hSkLxU4g/TsYTPDjbeK9bi0c1ZK80k888qln3U/@WbxI2YWf/aUYjQYs8Erp0g23djKUb8Ex3Gj1hl50spCXZVzdCKpDfsP3UDxf3ldaftH6nWTlqG7CYcz325M8Yq4pXqc26lrz6lbDMXEpYJdZ1XNzNCw "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Explanation:
```
¿¬LθUR²+«
```
Special-case empty input by drawing a 2x2 rectangle of `+`s.
```
≔E²⁺²⌈Eθ§λιη
```
Transpose the input, take the maximum of each column (now row) and add 2 to get the box size in Charcoal co-ordinates.
```
B⊟⮌η⊟η
```
Draw the box.
```
Fθ«
```
Loop over each co-ordinate.
```
J⊟⮌ι⊟ι
```
Jump to its position.
```
x
```
Mark with a cross.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~32~~ ~~31~~ 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╩╠ee%╙æM■↓^⌐╧ΩΓ¡c¥èf¢○ [
```
[Run and debug it](https://staxlang.xyz/#p=cacc656525d3914dfe195ea9cfeae2ad639d8a669b09205b&i=[[0,10],[5,5],[10,0]]%0A[]%0A[[0,0],[0,2],[2,0]]&a=1&m=2)
Takes 0-based indices as array of `[y, x]` pairs.
Explanation:
```
zs'X&|<cM%'-*'+|S]s{'||Smn++m Unpacked program, implicit input
zs Tuck empty array under input
'X Push "X"
& Assign element at all indices (create map)
As the indexing arrays are an array of arrays, treat them as a path to navigate a multidimensional array.
Extend array if needed.
|< Left-align all to the length of the longest.
cM% Copy, transpose, length (width)
'-* Repeat "-"
'+|S Surround with "+"
]s Make a singleton and tuck it below the map
{ m Map:
'||S Surround with "|"
n++ Surround with the above/below border (built above)
m Map:
Implicit output
```
[Answer]
# [R](https://www.r-project.org/), ~~133 125~~ 122 bytes
```
function(m)cat(z<-c("+",rep("-",u<-max(m[,1])),"+","
"),rbind("|",`[<-`(matrix(" ",u,max(m[,2])),m,"x"),"|","
"),z,sep="")
```
[Try it online!](https://tio.run/##ZYzLCoMwEEX3fkWYbiY4KcbiptgvkYJpjK2LqGgEkf67TeyD0sLMYu6Zc4e1ZrlY66nVrulatFwrh0suNEIMNJgeQQBNubBqRluQPHNOAUEEnIZL01YId6CyyEWJVrmhmRGYV@hlpMGwBLP/D5@buNBo@hMAX3dS@A4zm@rIVFU17ZXFkrmOuZthzoyOaTWacR/V73aNkg6UUOpX8tgfnH/ThJKQyt80I5mEyZ7839oa0w9dHw "R – Try It Online")
1-indexed. Takes a matrix as argument. Saved 8 bytes thanks to digEmAll, 3 thanks to Giuseppe!
Explanation (earlier version of code):
```
function(m){ #x and y are the 1st and 2nd col of m
s=matrix(32,u<-max(m[,1]),max(m[,2])) #s (treasure map) has dim max(x), max(y)
s[m]=120 #place the X's on the map
cat( #print:
z<-c("+",rep("-",u),"+","\n"), #the top line
intToUtf8(rbind(124,s,124,13)), #the map
z, #the bottom line.
sep="")
}
```
[Answer]
coords taken of the format [y,x]
# [JavaScript (Node.js)](https://nodejs.org), 191 184 bytes
```
c=f=a=>{a.map(([y,x])=>(c[M<++y?M=y:y]=c[y]||[])[m<++x?m=x:x]="x",M=m=0)
m++
M++
s=""
for(i=0;i<=M;s+=`
`,i++)for(j=0;j<=m;j++)s+=(c[i]||0)[j]||(j%m?i%M?" ":"-":i%M?"|":"+")
return s}
```
[Try it online!](https://tio.run/##bY1BasMwEEX3OoURBCSkBCWQje2JT6ATCEGEaheJyA52UiTqnt2dtLvSxfz5vPkzE92HW/wc7o/9OL312wCbhwEcXD7dIbk7Y6bIbDlcmDe6FaJ0GkpdLHhT7Loay01CnLsEuc4WaKZSQwLFSRKCaKwFKCXDNLMAqgkt6GYRcCVXGYTgLx6RxxZSExHgDF8FvK24idhY3KUu7HRHK1rTPa1//IpeUF6RuX8857FavjY/jct06w@36Z0NzBglj8pKc5Zn1KOSylrOyZ/UP8i8ohL1hHr6Xdu@AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript, 180 bytes
```
F =
s=>s.map(([x,y])=>(t[y]=t[Y<y?Y=y:y]||[])[X<x?X=x:x]='x',t=[X=Y=0])&&[...t,0].map((_,y)=>[...Array(X+2)].map((_,x)=>[(t[y]||0)[x]||' ',...'-|+'][!(y%~Y)+2*!(x%~X)]).join``).join`
`
console.log(F([[1,11],[6,6],[11,1]]))
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 246 234 bytes
Thanks to ceilingcat for the suggestion.
Zero-indexed. The function takes a list of co-ordinates and buffer, finds the maximum x and y values, fills the buffer with spaces, generates the frame, and then plots the 'x's.
```
f(int*a,char*c){int*b=a,x,y=x=-1,i=0;for(;~*b;*++b>y?y=*b:0,++b)*b>x?x=*b:0;for(x+=4,y+=3,memset(c,32,x*y);++i<x;c[i]=c[y*x-i]=45);for(i=0;i<y;c[x*++i-1]=10*(i<=y))c[x*i]=c[x*i+x-2]=i&&y/i?124:43;for(b=a;~*b;b+=2)c[*b+1-~b[1]*x]='x';}
```
[Try it online!](https://tio.run/##XVHdbpswGL3nKdxObf1HhyFZpxonV9vtHgBxYRxIjRKogFb2qvTV2WeStdosYXzO8fH3HdvEe2PmL7Yzh5ddjfJx2tn@/mkT/UMdbPU/N9huD9zcYNtNVHPzpAdqyFtAldLcca@cigW3KpFNP2D5TitJGas2fusVrR4TDoDQauO2bsHLNsfUinumMn6sj2M9YcOzlDvqiWTM5k6awpbKFJ66GBarNVlsoYrNPagOathYlEokFNtceUICuZjgx1yclsre3vqvdivS1eMqWw6AnpcOK6ZSMNCKifi9KkRJXanu3J08zRANHbXtQmKkh71ZQiNKYf1K0FuEUFDgMixvJaBFHossffj2vZRR0BscjBtx3g6E0lNvA/kKtYg8kw3GWh314dAbjC1NmSB0tL/rfrltAuNiRyj03kL4NodMo9Fdg69vduhmd801a2l6nuGAK/Xj10/ZMnYpgpAuQCnhjf4S0BwfP@Tnl2nEn7AZ6hrrCzxF4TvNIkFJtEbrKEEimbM/ "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~44~~ 42 bytes
```
ζεZ}>`UX'-×'+.ø©,F'|NVXF¹YN‚.å„ xè}'|J,}®,
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3LZzW6Nq7RJCI9R1D09X19Y7vOPQSh039Rq/sAi3Qzsj/R41zNI7vPRRwzyFisMratVrvHRqD63T@f8/OtpAxyBWJ9pUxxRIGhroGIJ4hoY6ZkDKTMcIxDMx0DEyiY0FAA "05AB1E – Try It Online")
---
```
ζεZ}>` # Push the max of X and Y to the stack +1.
UX # Store the max X.
'-×'+.ø©, # Print the top border.
F } # From 0 to Y...
'| # Push left border.
NV # Store current Y in Y.
XF } # From 0 to X...
¹ # Push input.
YN‚ # Group current X and Y.
.å # Exists in original input ? 1 : 0
„ xè # Exists ? 'X' : ' '
'|J, # Right border, join, print.
®, # Print bottom border.
```
X and Y may be reversed, didn't know if that mattered at all.
---
~~I think I have this in less bytes, but we'll see...~~ ***Nope.***
```
ζεZ}>`D'-×'+.øUð×'|.øs.D)X.ø©svy>`s®sUXès'xsǝXǝ}
```
[Answer]
# Java 10, ~~238~~ ~~223~~ ~~220~~ 219 bytes
```
c->{var r="";int w=0,h=0,x,y;for(var l:c){w=(x=l.get(0))>w?x:w;h=(y=l.get(1))>h?y:h;}for(w++,h-=x=-1;x++<w;r+="\n")for(y=-1;y++<h;)r+=x%w+y%h<1?"+":x%w<1?"-":y%h<1?"|":(c+r).contains("["+x+", "+y+"]")?"x":" ";return r;}
```
-3 bytes thanks to *@ceilingcat*.
1-indexed coordinates.
[Try it online.](https://tio.run/##zVLBauMwED1vvmIYKEhINnVSSrGihD0utL3sse1BVdzYWVcpshJbeP3tWSkN7NJDkz1k2YNA82beaOY9rdRWJavFj52uVdPAnapMPwKojCvsi9IF3McQ4LuzlVmCJqtASDeuqtPbqnHTD@G3wFsWdjYDTUUgDuE0TrlKwz0YudPJrN8qC1YiivAItPKSl@F03IuXtSUxWeea9q0knazTZeHIJaWzdt7lrSgl8QcwC2A593kphshrGeNlIjuZZKJjbNoKyyQ@GqQx6yPsA1wKGvDuomX@opxmc2SYhyjeEswP2E/MiWaWpnptXBCkIfiArGPIAZln@IR0jh3mCChs4TbWgBXDLu77tnmuw66HlbfragGvoQN5l@/hCRQ96OkbV7ym641L30LK1YaYVBNTtPBb0q/WKh91JZTu5fx7Xt@PvqjFgnxINqlq9gVjPomtP6254tnRmoyPQ80wnGvObD/DWfsfX/KaXx8X4h9MeoIbx12dnHnO8bl/xEmW/Rd2TE6w45S/dcNv/thlGA27Xw)
**Explanation:**
```
c->{ // Method with 2D Lists as parameter and String return-type
var r=""; // Result-String, starting empty
int w=0,h=0, // Width and height, starting at 0
x,y; // Temp x,y coordinates
for(var l:c){ // Loop over the Inner Lists containing the coordinates
w=(x=l.get(0))>w?x:w; // Determine width based on max x-coordinate
h=(y=l.get(1))>h?y:h;}// Determine height based on max y-coordinate
for(w++,h-= // Increase both the width and height by 1
x=-1;x++<w; // Loop `x` in the range [0, width]:
r+="\n") // After every iteration: append a new-line to the result
for(y=-1;y++<h;) // Inner loop `y` in the range [0, height]:
r+= // Append the following character to the result-String:
x%w+y%h<1? // If it's one of the corners:
"+" // Append "+"
:x%w<1? // Else-if it's the top or bottom row:
"-" // Append "-"
:y%h<1? // Else-if it's the right or left column:
"|" // Append "|"
:(c+r).contains("["+x+", "+y+"]")?
// Else-if the current `x,y` is part of the input-coordinates:
"x" // Append "x"
: // Else:
" "; // Append " "
return r;} // Return the result-String
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~229~~ ~~220~~ 216 bytes
-9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
Zero-indexed. Takes coordinates as list of numbers, where even numbers are X and odd numbers are Y.
```
X,Y,i,j,k,x,z;f(l,n)int*l;{for(X=Y=0,i=n*=2;i--;X=fmax(l[i],X))Y=fmax(l[i--],Y);n&&X++-Y++;for(--i;i++<Y;puts(""))for(j=-1;j<=X;z=i<0|i==Y,putchar(j++<0|j>X?z?43:'|':x?z?45:32:'x'))for(x=k=n;k--;)x*=l[k--]-i|l[k]-j;}
```
[Try it online!](https://tio.run/##XU/LboMwEDyHr0A5BAy2xCsXlm1@wxbigFBJDIZWhUqIx6@XGqImSqWxtDOembULdi2KdeVUUEkrWtOBjlDairZEtr2jYCo/vmyOAj0qsXUwAMkYcCybfLBVKjPKCREPylhGBYH2dOKuy4TrwpZnTIJ03UTA53ff2ccjIZtcIfOhSpDDiDLxZokoqHYUt1xfar83V2/8Ml6iMLZmKx628RyHQWwN1r1iwBpbqPWTyOCgSvWUMTnrIWMVLKv@hNnksrWJMRmHjfXvXe@nmYnm5FHTW@ApBw/Z1@e8w/9vCp/ZHcGOF0t0t2yScSjtfaNuIvDHdCB8svCFRbpMs2X9KUqVX7uVqeYX "C (gcc) – Try It Online")
] |
[Question]
[
Given an integer `n`, return the number of ways that n can be written as a list of prime numbers. For example, `2323` can be written as `(2,3,23)`, `(23,23)` or `(2,3,2,3)` or `(23,2,3)`, so you would output `4`. If it can not be written in this way, you should output `0`.
A prime number such as `019` or `00000037` is a valid prime for this problem.
Test cases:
```
5 -> 1
55 -> 1
3593 -> 4 (359 and 3, or 3 and 593, or 3 and 59 and 3, or 3593)
3079 -> 2 (3 and 079, or 3079)
119 -> 0
5730000037 -> 7 (5,7,3,000003,7, 5,7,3,0000037, 5,73,000003,7, 5,73,0000037, 5,73000003,7, 5,7,30000037, 5730000037)
0-> undefined (you do not have to handle this case)
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes in each language wins!
Edit: now I know why I should use the sandbox next time
[Answer]
# [Haskell](https://www.haskell.org/), ~~96~~ 89 bytes
*5 bytes saved thanks to H.PWiz's primality test*
```
p x=[1|0<-mod x<$>[2..x]]==[1]
f[]=1
f b=sum[f$drop i b|i<-[1..length b],p$read$take i b]
```
[Try it online!](https://tio.run/##FcoxCsMgFADQPaf4BMdGaraCvxeRPyhqI1EjxoJD7m6b9fE2fe4uxjEKdFTiesolHRa6ZG@1ct6J8M80eUUoJg8Gz29Sntl6FAhgriAXJTiPLn/aBoYehVWnLWt6d3egkXTIWGrIjflZiNc8fg "Haskell – Try It Online")
## Explanation
The first thing that's done is creating a prime test function ~~using Wilson's theorem~~ using the definition of prime.
```
p x=[1|0<-mod x<$>[2..x]]==[1]
```
Then begin defining `f`. The first thing I thought when I saw this problem was to use dynamic programming. However dynamic programming costs bytes so this uses a "psuedo-dynamic programming" algorithm. Whereas in dynamic programming you would store a Directed Acyclic graph in memory here we just use recursion and recalculate each node every time we need it. It loses all of the time benefits of dynamic programming, but this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so who cares. (still better than brute force search though)
The algorithm is as follows, we construct a Directed Acyclic Graph, **L**, where each node represents a substring of the number. In particular **Li** represents the last **i** digits of our input (lets call it **n**).
We define **L0** to have a value of 1 and each other value in **L** to have the sum of each **Lj** such that **j < i** and the substring of **n** from **i** to **j** is prime.
Or in a formula:

We then return the value at the largest largest index of **L**. (**Lk** where **k** is the number of digits of **n**)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒṖḌÆPẠ€S
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//xZLhuZbhuIzDhlDhuqDigqxT////MzU5Mw "Jelly – Try It Online")
-1 byte thanks to Leaky Nun
-1 byte thanks to Dennis
# Explanation
```
ŒṖḌÆPẠ€S Main Link
ŒṖ List Partitions (automatically converts number to decimal digits)
Ḍ Convert back to integers (auto-vectorization)
ÆP Are they primes? (auto-vectorization)
Ạ€ For each, are they all truthy (were the numbers all primes?); 1/0 for truthy/falsy
S Sum; gets number of truthy elements
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
ṫ{~cịᵐṗᵐ}ᶜ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO1dV1yQ93dz/cOuHhzulAsvbhtjn//xsbmFv@jwIA "Brachylog – Try It Online")
First `ṫ` converts the input into a string. `{…}ᶜ` Counts the number of possible outputs for `…`.
Inside `{…}` the output of `ṫ` is fed to `~c`. The output of this predicate satisfies that, when concatenated, it is equal to the input. This is fed into `ịᵐ`, which specifies that its output is it's input with each string converted into an integer. `ṗᵐ` specifies that its input consists of primes
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
lf.AmP_sdT./`
```
[Test suite.](http://pyth.herokuapp.com/?code=lf.AmP_sdT.%2F%60&test_suite=1&test_suite_input=2323%0A5%0A55%0A3593&debug=0)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~105~~ ~~95~~ 91 bytes
```
f=lambda n:sum(0**k|f(n%10**k)for k in range(n)if sum(n/10**k%j<1for j in range(1,n+2))==2)
```
This is *very* slow.
[Try it online!](https://tio.run/##Tc0xDsIwEETRGk4xzSreEERsughzFyMwOCGbyMQFEnc3mAa6kd6XZn4ut0lMzt7e3Xg6O0j3SKNq63p4eSWky2I/RQwIgujkelHCwaNksvs69Qddkv6X6EY2htlaw7mQ/BO0ablbr@YYZEFF@4TtEZQqEJQ0@Bwz5zc "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 161 bytes
```
lambda n:sum(all(d>1and all(d%i>0for i in range(2,d))for d in v)for v in g(`n`))
g=lambda s:[[int(s[:i])]+t for i in range(1,len(s))for t in g(s[i:])]+[[int(s)]]
```
[Try it online!](https://tio.run/##XYxLCoMwEIbXzSlmU8hQFxqR0oAuvYQNmBJjAzGKsUJPnxp11c3/Yuabvst7dCzo8hmsHF5KguP@M1BpLVVVJp2CPV5NlepxBgPGwSxd31GWKMS4qbite1xj7GnrWkTSlyfS86YxbqG@4UaguC3wh8oS2znqD9xyMHxjeDw@X1GIoDoNNZXIyWWatxVkAnrrhNS0wCi7spzl0fPicXh6f0RPkYQf "Python 2 – Try It Online")
The function `g` creates the partitions recursively (it takes a string as input but outputs a list of lists of ints). Most of the remaining code is just to implement 'is `d` a prime?'.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 12 bytes
```
₸B¦ṗ¦Π
$ḍ↑¦Σ
```
[Try it online!](https://tio.run/##S0/MTPz//1HTDqdDyx7unH5o2bkFXCoPd/Q@apsIZC/@/9/Y1NIYAA "Gaia – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~199~~ ~~141~~ 131 bytes
```
import StdEnv
?n|n<2=0|and[gcd n i<2\\i<-[2..n-1]]=1=0
@n#s=toString n
#f=toInt o(%)s
= ?n+sum[@(f(0,i))\\i<-[0..n]| ?(f(i+1,n))>0]
```
[Try it online!](https://tio.run/##JY67CoMwFEB3v@KCFAw@iHY11aEdhG6O6hB8ccHcFBMLBb@9aaDjOcPhjNssySk9HdsMSiI5VC@9W2jt9KB3UNFJZSH4KWnq1nECAiyLvscy7YosozQfBpELHtQUGmF1a3ekFSgIF08NWdDRhZlAQEWxOVRXR0vEE2Ts3@C@MZxQeYtxnhBjNz641kq/IKCG4uq@47LJ1bi0ebr7h6TC0fwA "Clean – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 65 64 bytes
```
(1#.[:*/"1*/@>)@(#`(1,.[:#:[:i.2^#-1:)@.(1<#)(1:p:&.>".);.1])@":
```
[Try it online!](https://tio.run/##PchRCsIwEATQ/55iScDulrrNGkLoakvuURRBbNUfvYBnjxUxAwNv5pGXQcHB2oxiedKmM9J0aaSE9ozSrpfVSe@8O9mtKCVGOVhC0ZdueDRMe5YjJaOZKsNQzwPX0MJbYamul9sTZggFRT70Hspwsf9bpDBE777x8fe4/AE "J – Try It Online")
[Answer]
# Pyth, 12 bytes
```
lf*FmP_sdT./
```
Takes input as an integer, outputs `True` or `False`
[Try it online!](http://pyth.herokuapp.com/?code=lf%2aFmP_sdT.%2F&input=3593&test_suite=1&test_suite_input=%225%22%0A%0A%2255%22%0A%0A%223593%22%0A%0A%223079%22%0A%0A%22119%22%0A%0A%225730000037%22&debug=0&input_size=2)
] |
[Question]
[
## Challenge
Given an input `n`, print an ASCII art cake `n` layers tall, viewed from the side, with two candles on top. Refer to the examples below for details.
## Output
```
>> cake(1)
_|_|_
| |
+-----+
>> cake(3)
_|_|_
| |
+---------+
| |
+-------------+
| |
+-------------+
```
...and so on.
## Rules
* Standard loopholes prohibited
* Please make an attempt at a clever solution
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. However, the answer will not be selected.
## Have fun!
[Answer]
# Python 2, 238 chars
```
i=input()
m=["+"+"-"*(i*4+1)+"+","|"+" "*(i*4+1)+"|"]
for v in range(i,1,-1):
m+=[" "*(i-v)*2+"+"+"-"*(v*4+1)+"+"," "*(i-v+1)*2+"|"+" "*((v-1)*4+1)+"|"]
m.pop()
m+=[" "*(i-1)*2+"|"+" "*5+"|"," "*(i-1)*2+" _|_|_"]
print'\n'.join(m[::-1])
```
The missing example of Cake 2:
```
_|_|_
| |
+---------+
| |
+---------+
```
[Answer]
# Ruby, 109 107 bytes
```
->n{p=->t{puts t.center 3+4*n}
p['_|_|_']
(1..n).map{|i|p[?|+' '*(1+4*i)+?|]
p[?++?-*((i<n ?5:1)+4*i)+?+]}}
```
[Answer]
## JavaScript (ES6), 134 bytes
A recursive cake.
```
f=(n,i=--n,r=(n,c)=>'- '[+!c].repeat(n),p=r((i-n)*2),j=n*4+5,x=p+`+${r(j,1)}+
`)=>(n?f(n-1,i)+x:p+` _|_|_
`)+p+`|${r(j)}|
`+(n-i?'':x)
```
### Demo
```
let f=(n,i=--n,r=(n,c)=>'- '[+!c].repeat(n),p=r((i-n)*2),j=n*4+5,x=p+`+${r(j,1)}+
`)=>(n?f(n-1,i)+x:p+` _|_|_
`)+p+`|${r(j)}|
`+(n-i?'':x)
console.log(f(4))
```
[Answer]
## Batch, 233 bytes
```
@echo off
set i=
for /l %%j in (2,1,%1)do call set i= %%i%%
echo %i% _^|_^|_
set s=-----
for /l %%j in (2,1,%1)do call:l
echo ^|%s:-= %^|
echo +%s%+
exit/b
:l
echo %i%^|%s:-= %^|
set i=%i:~2%
set s=----%s%
echo %i%+%s%+
```
Shorter than Python? Something must be wrong...
[Answer]
# Haskell, 103 bytes
```
f(a:b)n=a:([0..4*n]>>b)++[a]
x!n=x:[f"| "n,f"+-"n]
g 1=" _|_|_"!1
g n=map(" "++)(init.g$n-1)++f"+-"n!n
```
Defines a function `g` which returns a list of strings containing the lines of the output
[Answer]
# 05AB1E, ~~115~~, 101 chars
```
>UXð×?" _|_|_",Xð×?"| |",X<U0<VXGNVXY-ð×?'+?8Y·+G'-?}'+,XY-ð×?'|?7Y·+ð×?'|,}XY-ð×?'+?8Y·+G'-?}'+,
```
Saved 14 chars thanks to Adnan!
Definitely some room for golfing here.
[Try it online!](http://05ab1e.tryitonline.net/#code=PlVYw7DDlz8iIF98X3xfIixYw7DDlz8ifCAgICAgfCIsWDxVMDxWWEdOVlhZLcOww5c_Jys_OFnCtytHJy0_fScrLFhZLcOww5c_J3w_N1nCtyvDsMOXPyd8LH1YWS3DsMOXPycrPzhZwrcrRyctP30nKyw&input=MQ)
Note that this does print everything offset by one space.
[Answer]
# Python 2, 122 bytes
```
a=' '*input()
b='+-+'
c=d=' '
while a:b='+----'+b[1:];c=d*4+c;a=a[2:];print a+[' _|_|_',b][c>d*5]+'\n%s|%%s|'%a%c
print b
```
[Answer]
# Python 3, 162 characters
```
p=print
t=int(input())
d=4*'-'
s=' '
a='+\n'
r=(t-1)*s
p(r+' _|_|_\n'+r+'| |')
for i in range(2,t+1):b=(t-i)*s;p(b+'+-'+i*d+a+b+'| '+i*2*s+'|')
p('+-'+t*d+a)
```
It's not very clever, but I've never done one of these before. (Edit: removed unnecessary parentheses; reduced by one more character)
[Answer]
# Pyth, 73 bytes
```
+K*dtyQ"_|_|_"+tK"| |"jP.iJms[*\ yt-Qd\+*+5*4d\-\+)+StQtQmXd"+-""| "J
```
A program that takes input of an integer on STDIN and prints the result.
There is probably still some golfing to be done here.
[Try it online](https://pyth.herokuapp.com/?code=%2BK%2adtyQ%22_%7C_%7C_%22%2BtK%22%7C+++++%7C%22jP.iJms%5B%2a%5C+yt-Qd%5C%2B%2a%2B5%2a4d%5C-%5C%2B%29%2BStQtQmXd%22%2B-%22%22%7C+%22J&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5&debug=0)
*Explanation coming later*
[Answer]
# JavaScript (ES6), 171 bytes
```
n=>[(s=" "[R='repeat'](n-1))+" _|_|_",s+"| |",...Array(n-1),`+${"-"[R](n*4+1)}+`].map((_,i)=>_||(s=" "[R](n-i))+`+${"-"[R](i=i*4+1)}+`+`
${s}|${" "[R](i)}|`).join`
`
```
First pass, probably not optimal...
[Answer]
# PHP, ~~150~~ ~~147~~ ~~138~~ ~~136~~ ~~130~~ 140 bytes
new approach:
```
echo$p=str_pad("",-2+2*$n=$argv[1])," _|_|_";for($x=" ",$b=$y="----";$n--;){$a.=$x;if($n)$b.=$y;echo"
$p| $a|
",$p=substr($p,2),"+-$b+";}
```
old version for reference:
```
$p=str_pad;for($o=["_|_|_"];$i++<$n=$argv[1];$o[]="+".$p("",($i<$n)*4+$e,"-")."+")$o[]="|".$p("",$e=$i*4+1)."|";foreach($o as$s)echo$p($s,$n*4+3," ",2),"
";
```
[Answer]
# Vimscript, ~~116~~ 115 bytes
Pretty messy but it works!
```
fu A(n)
let @z="Vkyjply4lpjy4hp"
exe "norm 2i+\e5i-\eo||\e5i \e".a:n."@zddl4xggd$i_|_|_"
exe "%ce ".(a:n*4+3)
endfu
```
To call it: `call A(3)` in an *empty* buffer. To load the function, `source cake.vim`
## Explanation
* `2i+<Esc>5i-<Esc>` writes the first line `+-----+`
* `o||<Esc>5i<Space><Esc>` adds `| |` on the second line
* `Vkyjply4lpjy4hp` is saved in the macro `@z` - it visually selects both lines, yanks them, pastes them under and adds 4 dashes and spaces to them.
* `#@z` repeats this `#` times
* `ddl4x` deletes the last lines and remove for dashes to the bottom of the cake to make it equal with the top of the bottom layer
* `ggd$i_|_|_` replaces the first line by the top of the cake
* `%ce` then centers the whole cake to the width of the bottom layer! !
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~27~~ 26 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
∫4*I:┌*╗1Ο;@*┐1Ο}⁴¹k┐╔2ΟΚ╚
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjJCNCpJJTNBJXUyNTBDKiV1MjU1NzEldTAzOUYlM0JAKiV1MjUxMDEldTAzOUYlN0QldTIwNzQlQjlrJXUyNTEwJXUyNTU0MiV1MDM5RiV1MDM5QSV1MjU1QQ__,inputs=Mw__)
Explanation:
```
∫ } for each in 1..input inclusive, pushing counter
4* multiply by 4
I increase by 1
: duplicate; this will be used later
┌* repeat a dash pop times
╗1Ο encase them in plusses
; get the duplicate on the stacks top
@* repeat a space pop times
┐1Ο encase in vertical bars
⁴ duplicate the item below ToS - the last line
¹ wrap the stack in an array
k remove the arrays first item
┐ push "_"
╔ push "|"
2Ο encase 2 copies of the vertical bar in underscores
Κ and prepend that to the array
╚ center the array horizontally
```
[Answer]
# Excel VBA, ~~139~~ ~~130~~ 127 Bytes
Anonymous VBE immediate window that takes input from cell `A1` and outputs a cake to the VBE immediate window
```
For i=1To[A1]:s=Space(2*([A1]-i)):x=String(1+4*i,45):?s &IIf(i=1," _|_|_","+" &x &"+"):?s"|"Replace(x,"-"," ")"|":Next:?s"+"x"+
```
[Answer]
# CJam, 79 bytes
```
l~4*):Z5:X{D'+'-C}:A{D'|SC}:B{X*1$N}:C];{SZX-Y/*}:D~" _|_|_"NB{XZ<}{X4+:X;AB}wA
```
[Try it online](http://cjam.aditsu.net/#code=l~4*)%3AZ5%3AX%7BD'%2B'-C%7D%3AA%7BD'%7CSC%7D%3AB%7BX*1%24N%7D%3AC%5D%3B%7BSZX-Y%2F*%7D%3AD~%22%20_%7C_%7C_%22NB%7BXZ%3C%7D%7BX4%2B%3AX%3BAB%7DwA&input=5)
[Answer]
# QBasic, 115 bytes
```
INPUT n
?SPC(n*2-1)"_|_|_
FOR i=1TO n
s=n*2-i*2
?SPC(s)"|"SPC(i*4+1)"|
?SPC(s-2)"+"STRING$(i*4+(i=n)*4+5,45)"+
NEXT
```
### Ungolfed
Print the top line with the candles; then print the rest of the cake two lines at a time.
```
INPUT n
PRINT SPC(n * 2 - 1); "_|_|_"
FOR i = 1 TO n
indent = n * 2 - i * 2
PRINT SPC(indent); "|"; SPC(i * 4 + 1); "|"
PRINT SPC(indent - 2); "+"; STRING$(i * 4 + (i = n) * 4 + 5, 45); "+"
NEXT
```
`SPC`, when used in a `PRINT` statement, emits the given number of spaces. Conveniently, when given a negative argument, it treats it as 0, so the fact that `indent - 2` is `-2` in the last iteration isn't a problem. `STRING$` takes a count and a character code (here, 45 for `-`) and repeats the character that number of times. Here, we have to special-case the last line (when `i=n`) to be 4 hyphens shorter than it would otherwise be.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~158~~ 153 bytes
-5 bytes thanks to ceilingcat.
```
i,l,s;p(c,s){printf("%*c%*.*s%c\n",i-~i,c,l,l,s,c);}f(n){s=memset(malloc(5*n),45,5*n);l=1;for(i=n;i--;p('|',""))l+=4,n+~i?p(43,s):p(32,"_|_|_");p(43,s);}
```
[Try it online!](https://tio.run/##LY7BasNADETP9lcsCyaSLRfS2JeoS3@kUIKIi2C9WbLuyXF@3VWgzOHBMMyM9D8i@64UqXAGoYJrvmtaJvBNK0371pZGvpIn7Z9KYjlLkiBvEyRcS5ivc7kuMF9ivAmMbUIaRnqRYzjydLuDhsTa99Z/eBzIe8TYhYFS99TPDMPJRs8ZTu/kvx8mj/zv8rbbFTdfNAHWa11Zm4OXpS64Ixs@ghuNXYd1VU2gSC7/LgVshett/wM "C (gcc) – Try It Online")
] |
[Question]
[
## The challenge
Given an input string, and an integer *n* - truncate any runs of consecutive characters to a maximum of *n* length. The characters can be anything, including special characters. The function should be case sensitive, and *n* can range from 0 to infinity.
Example inputs/outputs:
```
f("aaaaaaabbbccCCCcc", 2) //"aabbccCCcc"
f("aaabbbc", 1) //"abc"
f("abcdefg", 0) //""
f("aaaaaaabccccccccCCCCCC@", 4) //"aaaabccccCCCC@"
```
## Scoring
The scoring is based on the number of bytes used.
Thus
```
function f(s,n){return s.replace(new RegExp("(.)\\1{"+n+",}","g"),function(x){return x.substr(0, n);});}
```
would be 104 points.
Happy golfing!
*Edit: removed language restriction, but I still would love to see javascript answers*
[Answer]
## Python 2, 52 bytes
```
lambda s,n:reduce(lambda r,c:r+c*(r[-n:]!=c*n),s,'')
```
Written out as a program (54 bytes):
```
s,n=input();r=''
for c in s:r+=c*(r[-n:]!=c*n)
print r
```
Iterates through the input string `s`, appending each character to the output string `r` unless that last `n` characters of `r` are that character.
I though this would fail `n==0` because `r[-0:]` is not the last 0 characters (empty string), but the entire string. But, it works because the string remains empty, so its keeps matching the 0-character string.
A recursive `lambda` gave 56 because of the repetition
```
f=lambda s,n:s and s[:f(s[1:],n)[:n]!=s[0]*n]+f(s[1:],n)
```
An alternate strategy to keep a counter `i` of repeats of the last character also turned out longer than just checking the last `n` characters directly.
[Answer]
# C, ~~81~~ 78
Modifies the incoming string.
```
c,a;f(p,n)char*p;{char*s=p;for(;*p;s+=c<n)*s=*p++,a^*s?c=0:++c,a=*s;c=a=*s=0;}
```
## Test Program
Requires two parameters, the first is the string to truncate, the second is the length limit.
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, const char **argv)
{
char *input=malloc(strlen(argv[1])+1);
strcpy(input,argv[1]);
f(input,atoi(argv[2]));
printf("%s\n",input);
free(input);
return 0;
}
```
## Explanation:
```
c,a; //declare two global integers, initialized to zero.
//c is the run length, a is the previous character
f(char*p,int n){...} //define function f to truncate input
char*s=p; //copy p to s; p is source, s is destination
for(;*p //while there is a source character
;s+=c<n) //increment copied pointer if run is under the limit
*s=*p++, //copy from source to destination, increment source
a^*s?c=0:++c, //if previous character != current then run=0 else increment run
a=*s; //previous character = current source character
c=a=*s=0; //after loop, terminate destination string with NUL and reset c and a.
```
This works because the source pointer will always be equal to or greater than the destination pointer, so we can write over the string as we parse it.
[Answer]
# Haskell, 36 bytes
```
import Data.List
(.group).(=<<).take
```
Point-free version of `\n s -> concatMap (take n) (group s)`.
[Answer]
# Javascript ES6, ~~60~~ ~~54~~ ~~55~~ 43 bytes
-12 bytes thanks to @TestSubject06 and @Downgoat
```
(s,n)=>s.replace(/(.)\1*/g,x=>x.slice(0,n))
```
Example runs:
```
f("aaaaaaabbbccCCCcc" , 2) -> "aabbccCCcc"
f("aaabbbc" , 1) -> "abc"
f("abcdefg" , 0) -> ""
f("aaaaaaabccccccccCCCCCC@", 4) -> "aaaabccccCCCC@"
f("a" , 1) -> "a"
```
[Answer]
# MATL, 9 bytes
```
Y'i2$X<Y"
```
[**Try it Online**](http://matl.tryitonline.net/#code=WSdpMiRYPFki&input=J2FhYWFhYWFiY2NjY2NjY2NDQ0NDQ0NAJwo0)
**Explanation**
```
% Implicitly grab input as a string
Y' % Perform run-length encoding. Pushes the values and the run-lengths to the stack
i % Explicitly grab the second input
2$X< % Compute the minimum of the run lengths and the max run-length
Y" % Perform run-length decoding with these new run lengths
% Implicitly display the result
```
[Answer]
## CJam, 12 bytes
```
{e`\af.e<e~}
```
[Try it online!](http://cjam.aditsu.net/#code=2%20%22aaaaaaabbbccCCCcc%22%0A%7Be%60%5Caf.e%3Ce~%7D%0A~)
### Explanation
```
e` e# Run-length encode the input. Gives a list of pair [length character].
\a e# Swap with maximum and wrap in an array.
f.e< e# For each run, clamp the run-length to the given maximum.
e~ e# Run-length decode.
```
[Answer]
# Pyth, ~~16~~ 12 bytes
```
~~rm,hS,Qhdedrz8 9~~
ss<RQmM_Mrz8
```
[Try it online!](http://pyth.herokuapp.com/?code=ss%3CRQmM_Mrz8&input=4%0AaaaaaaabccccccccCCCCCC%40&debug=0)
[Answer]
# Python 2, 56 bytes
```
import re
lambda s,n:re.sub(r'(.)(\1{%d})\1*'%n,r'\2',s)
```
[Answer]
# gs2, 6 bytes
Encoded in [CP437](https://en.wikipedia.org/wiki/Code_page_437):
```
╠c╨<ΘΣ
```
This is an anonymous function (block) that expect a number on top of the stack and a string below it.
```
Σ Wrap previous five bytes in a block:
╠ Pop number into register A.
c Group string.
Θ Map previous two bytes over each group:
╨< Take the first A bytes.
```
[Try it online.](http://gs2.tryitonline.net/#code=KuKZq1bilaBj4pWoPM6YzqMg&input=YXNzZGRkZGRkZmZmCjM) (The code here is `lines, dump, read number, [the answer], run-block`.)
[Answer]
# [Perl 6](http://perl6.org), ~~38~~ 36 bytes
```
~~->$\_,$n {S:g/(.)$0\*\*{$n..\*}/{$0 x$n}/}~~
->$_,\n{S:g/(.)$0**{n..*}/{$0 x n}/}
```
### Explanation:
```
-> $_, \n { # pointy block lambda
# regex replace ( return without modifying variant )
# globally
S:global /
# a char
(.)
# followed by 「n」 or more identical chars
$0 ** { n .. * }
/{
# repeat char 「n」 times
$0 x n
}/
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my &truncate-char-runs-to = ->$_,\n{S:g/(.)$0**{n..*}/{$0 x n}/}
my @tests = (
("aaaaaaabbbccCCCcc", 2) => "aabbccCCcc",
("aaabbbc", 1) => "abc",
("abcdefg", 0) => "",
("aaaaaaabccccccccCCCCCC@", 4) => "aaaabccccCCCC@",
);
plan +@tests;
for @tests -> $_ ( :key(@input), :value($expected) ) {
is truncate-char-runs-to(|@input), $expected, qq'("@input[0]", @input[1]) => "$expected"';
}
```
```
1..4
ok 1 - ("aaaaaaabbbccCCCcc", 2) => "aabbccCCcc"
ok 2 - ("aaabbbc", 1) => "abc"
ok 3 - ("abcdefg", 0) => ""
ok 4 - ("aaaaaaabccccccccCCCCCC@", 4) => "aaaabccccCCCC@"
```
[Answer]
# Javascript ES5, 73
```
function f(s,n){return s.replace(RegExp("(.)(\\1{"+n+"})\\1*","g"),"$2")}
```
Re-uses Lynn's regex from her [Python answer](https://codegolf.stackexchange.com/a/84924/31625).
[Answer]
## Perl 5, 50 bytes
**46 bytes code + 3 for `-i` and 1 for `-p`**
Takes the number to truncate to via `-i`.
```
s!(.)\1+!$&=~s/(.{$^I}).+/$1/r!ge
```
### Usage
```
perl -i4 -pe 's!(.)\1+!$&=~s/(.{$^I}).+/$1/r!ge' <<< 'aaaaaaabccccccccCCCCCC@'
aaaabccccCCCC@
```
[Answer]
# Bash 46 bytes
```
read c;sed -r ":l;s/(.)(\1{$c})(.*)/\2\3/;t l"
```
Usage: Enter the number of characters to limit, press enter and enter the string. `Ctrl` + `D` to exit `sed` (send EOF).
[Answer]
# Java 7, ~~107~~ 106 bytes
```
String c(String s,int i){String x="";for(int i=-1;++i<j;)x+="$1";return s.replaceAll("(.)\\1{"+i+",}",x);}
```
Previous alternative inline for-loop for String concatenation (which is 1 byte more than `String s="";for(int i=-1;++i<j;)s+="$1";` unfortunately):
```
String c(String s,int i){return s.replaceAll("(.)\\1{"+i+",}",new String(new char[i]).replace("\0","$1")));}
```
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/NFvlKE)
```
class Main {
static String c(String s, int i){
String x="";
for(int j = -1; ++j < i;){
x += "$1";
}
return s.replaceAll("(.)\\1{"+i+",}", x);
}
public static void main(String[] a){
System.out.println(c("aaaaaaabbbccCCCcc", 2));
System.out.println(c("aaabbbc", 1));
System.out.println(c("abcdefg", 0));
System.out.println(c("aaaaaaabccccccccCCCCCC@", 4));
System.out.println(c("@@@@@bbbbbcccddeegffsassss", 5));
}
}
```
**Output:**
```
aabbccCCcc
abc
aaaabccccCCCC@
@@@@@bbbbbcccddeegffsassss
```
[Answer]
## Javascript (using external library) (115 bytes)
```
(s,r)=>_.From(s).Aggregate((c,n)=>{if(c.a!=n){c.c=1;c.a=n}else{c.c++}if(c.c<=r){c.b+=n}return c},{a:"",b:"",c:0}).b
```
Link to lib: <https://github.com/mvegh1/Enumerable>
Code explanation: Load the string into library, which internally parses as char array. Apply an accumulator on the sequence, passing in a custom object as a seed value. Property a is the current element, b is the accumulated string, and c is the sequential count of the current element. The accumulator checks if the current iteration value, n, is equal to the last element value, c.a. If not, we reset the count to 1 and set the current element. If the count of the current element is less than or equal to the desired length, we accumulate it to the return string. Finally, we return property b, the accumulated string. Not the golfiest code, but happy I got a solution that works...
[](https://i.stack.imgur.com/MGH1T.png)
[Answer]
# J, ~~31~~ 30 bytes
```
((<.#@>)#{.@>@])]<;.1~1,2~:/\]
```
Groups the input string into runs (substrings) of identical characters, and takes the minimum of the length of that run and the max length that was input for truncating the string. Then copies the first character of each run that many times.
### Usage
```
f =: ((<.#@>)#{.@>@])]<;.1~1,2~:/\]
2 f 'aaaaaaabbbccCCCcc'
aabbccCCcc
1 f 'aaabbbc'
abc
0 f 'abcdefg'
4 f 'aaaaaaabccccccccCCCCCC@'
aaaabccccCCCC@
```
### Explanation
```
((<.#@>)#{.@>@])]<;.1~1,2~:/\] Input: k on LHS, s on RHS
] Get s
2~:/\ Test if each pair of consecutive chars are not equal
1, Prepend a 1
] Get s
<;.1~ Chop s where a 1 occurs to get the runs in s
#@> Get the length of each run
<. Take the min of the length and k
{.@>@] Get the head of each run
# Copy the head of each run min(k, len(run)) times
Return that string as the result
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~22~~ 20 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
(∊⊢↑¨⍨⎕⌊⍴¨)⊢⊂⍨1,2≠/⊢
```
Prompts for *n* and takes input string as argument.
`(` the tacit function ...
`∊` flatten
`⊢↑¨⍨` each element of the argument (i.e. each partition) truncated to
`⎕⌊⍴¨` the minimum of the numeric input and the current length
`)` [end of tacit function] applied to
`⊢⊂⍨` the input partitioned at the *ᴛʀᴜᴇ*s of
`1,` *ᴛʀᴜᴇ* prepended to (the first character is not equal to its non-extant predecessor)
`2≠/⊢` the pair-wise not-equal of characters in the input
[Answer]
# Ruby, 32 bytes
```
->s,n{s.gsub(/(.)\1*/){$&[0,n]}}
```
[Answer]
## TCC, ~~7~~ 5 bytes
```
$~(;)
```
Input is a string and a number, seperated by space.
[Try it online!](https://www.ccode.gq/projects/tcc.html?code=%24~(%3B)&input=aaaaaaabccccccccCCCCCC%40%204)
```
| Printing is implicit
$~ | Limit occurence
(; | First part of input
) | Second part of input
```
] |
[Question]
[
**This question already has answers here**:
[Are the brackets fully matched?](/questions/77138/are-the-brackets-fully-matched)
(48 answers)
Closed 7 years ago.
The contest is to make a program or function that takes an arbitrary string
resembling source code and checks to see if the "braces" follow the basic rules for
brace matching. That is, the number of left braces and right braces have to match, and you
can't have a right brace without a corresponding prior left brace.
You may choose to use any "brace" among `(` `[` `{` `<`
Your program must output/return a true-y value or 'Y' if the input is legal and a false-y value or 'N' if the input is illegal.
**Scoring**
Your score is the number of bytes in your source minus bonuses.
**Bonuses**
* -20 per each additional brace type handled among `(` `[` `{` `<`
* -30 if you handle multiple brace types and don't allow mismatched braces like `<(>)`
* -50 points if you handle `/* */` or `//` comments (the same way C or Java does)
* -20 points if you handle both types of comments
* -50 if you ignore braces inside `'` and `"` quotes. To get the points you also have to check that quotes properly match. Eg: `("')"')` is not a valid "program" but `("')")` is. You do not have to worry about escaped characters. `"\""` is an illegal program if you go for this bonus.
So if your program is 327 ASCII characters long, handles `(` and `[`, doesn't check mismatching, and handles `//` comments and quotes, you get:
327 - 20 \* 1 - 0 - 50 - 0 - 50 = **207** points
**EDIT:** Added bonuses for ignoring braces inside `'` and `"` quotes
**EDIT 2:** Return values cannot be any string. Must be true/false 1/0 'Y'/'N' ect.
**EDIT 3:** Since there is some confusion, here is some pseudo-BNF to give an idea of what is expected.
Grammar for minimal program:
exprs = expr exprs
expr = ( exprs ) || not\_braces\* || nil
Grammar for all bonuses:
exprs = expr exprs
expr = ( exprs ) || [ exprs ] || { exprs } || < exprs > || // not\_newline\* \n || /\* not\_end\_comment\* \*/ || not\_braces\* || nil
Note that if you do the bonuses, you will both accept and reject things that the basic program would not.
[Answer]
## PHP, -4 (156 - 20\*3 - 30 - 50 - 20)
```
<?php $x=preg_replace("!(//.*|/\*.*\*/|[^()[\]{}<>])!sm",'',$argv[1]);while(strlen($x)!=strlen($x=str_replace(str_split('()[]{}<>',2),'',$x)));print $x?0:1;
```
1. It removes comments
2. It filters out all characters different than (, ), [, ], {, }, <, >
3. It replaces all (), [], {}, <> pairs until there are no matches
4. Prints 1 if the string is empty, 0 otherwise
(*Edit: changed the regex; the source code is now 156 instead of 175*)
[Answer]
# GolfScript, 38 chars − 3 × 20 − 30 = −52 points
```
0\{")]>}([<{"?.4/"4^^{0}*
;"n/=~}/;]!
```
Prints `1` if all the braces in the input are correctly balanced, `0` otherwise.
Bonus points for:
* handling all four types of braces: 3 × 20 points
* not allowing mismatched braces: 30 points
This solution uses the GolfScript internal stack to keep track of which braces have been seen so far. When an opening brace is encountered, it is pushed onto the stack; when a closing brace is encountered, the code checks if there's a matching opening brace on the stack. If there is, it is popped off; otherwise a sentinel value (0) matching no brace is push onto the stack, ensuring that it cannot ever be popped off.
One such sentinel value is pushed onto the stack at the beginning, to guard against stack underflow if there are too many closing braces. At the end, the program simply checks whether the stack is empty except for the initial sentinel value.
[Answer]
# Perl, (~~136~~ ~~130~~ 129 chars - (20\*3) - 30 - 50 - 20 - 50) == -81
<3 recursive REs.
```
$/=$_;print!(<>!~m#^(([^][<{('"/)}>]|'[^']*'|"[^"]*"|/((?![*/])|\*((?!\*/).)*\*/|/[^\n]*+)|<(?1)>|\((?1)\)|\[(?1)]|{(?1)})*)$#s)
```
[Answer]
# Lua - 51
```
print(not not("("..io.read"*a"..")"):match"^%b()$")
```
What this program is doing, is wrapping the input string in `()`, then it matches it against a [pattern](http://www.lua.org/manual/5.2/manual.html#6.4.1) (not a regex). The pattern matches beginning of string followed by string containing balanced parentheses, followed by end of string.
On a successful match, the whole string is returned, which is turned into `true` by `not not`. If match is unsuccessful, `nil` is returned, which turns info `false` because of `not not`.
[Answer]
## C, 70 62 61
```
A;main(c){for(;~c&~A;c=getchar())A-=c==41,A+=c==40;exit(!A);}
```
Alternatively, supporting all bracket types: 147 - (3\*20) = 87
```
A,B,C,D;main(c){for(;~(c=getchar())&~A&~B&~C&~D;)c-40?c-41?c-91?c-93?c-'{'?c-'}'?c-60?c-62||D--:D++:C--:C++:B--:B++:A--:A++;puts(A|B|C|D?"N":"Y");}
```
The program reads in a single character at a time. Every time a `(` is found a counter is incremented. Similarly, every time a ')' is found a counter is decremented. If the counter ever drops below `0`, we know a `)` was found without a prior `(`. When we reach EOF, if the counter equals `0`, we have success!
EDIT: A big thanks to @ugoren!
[Answer]
## Common Lisp (???)
The idea here was to highlight the flexibiliity of the Lisp reader and actually allow other characters as list delimiters. Unfortunately, it seems like too much of the other parts of the language syntax (e.g., using `'foo` as an abbreviation for `(quote foo)` and different comment syntaxes (`;` rather than `//` for end-of-line comments, and `#| … |#` instead of `/* … */`)) probably disqualify this from being a "working" entry.
```
(defun check-source (x)
(labels ((s (x y)
(set-macro-character x y))
(r (e)
(s e (get-macro-character #\) nil))
(lambda (s c)
(read-delimited-list e s t)))
(p (b e)
(s b (r e))))
(map 'nil #'p "[{<" "]}>")
(listp (read-from-string (concatenate 'string "(" x ")")))))
```
```
(defun check-source(x)(labels((s(x y)(set-macro-character x y))(r(e)(s e(get-macro-character #)()))(lambda(s c)(read-delimited-list e s t)))(p(b e)(s b(r e))))(map'nil #'p"[{<""]}>")(listp(read-from-string(concatenate'string"("x")")))))
```
This uses the standard Lisp reader (which already handles `(` and `)`, of course), and defines each new set of a delimiters as another list construction syntax. These are automatically matched (i.e., mismatches result in an error). This doesn't handle `/* ... */` and `//` comments, but it handles `#| ... |#` and `//` comments. Double quoted strings are handled, including escapes.
[Answer]
## GolfScript 37
```
{[40.)]&},.,,\`{\>}+%{0\~}%(!\{0<},!&
```
Suppose the input to the program is `'(123(abc)(hello))'`. First, filter out all characters that are not `(` (ASCII 40) or `)` (ASCII 41):
```
{[40.)]&}, #Stack is now '(()())'
```
Next, generate an array from `0` to the length of the array:
```
.,, #Stack is now '(()())' [0, 1, 2, 3, 4, 5]
```
Now, generate all suffixes of the filtered string
```
\`{\>}+% #Stack is now ['(()())', '()())', ')())', '())', '))', ')' ]
```
Recall that in GolfScript, `(` decrements integers and `)` increments them.
So, checking if the parentheses are valid is equivalent to checking if that no suffix, when treated as a code block and applied to 0, dips below 0 (so that there are more close braces than open braces) and that the whole string, when treated as a code block and applied to 0, return 0 (so that there is an equal number of open and close parenthesis).
So, apply each suffix to `0`:
```
{0\~}% #Stack is now [0, 1, 2, 1, 2, 1]
```
And then check that the first element (where the entire string treated as a function) returns 0, and that no elements are below 0 (recall that the empty array `[]` is falsey in GolfScript):
```
(!\{0<},!&
```
[Answer]
## flex, (70+4)-50=24
```
%{
a;
%}
%%
"(" a++;
")" a?a--:exit(0);
"//".*
.
<<EOF>> exit(!a);
%%
```
In order for compilation to succeed, you need to use flag `-lfl` so I added 4 to my character count.
```
flex flex.l
gcc lex.yy.c -lfl
```
The code reads character by character, incrementing a counter if a `(` is detected and decrementing a counter if a `)` is detected. If the counter is zero when a `)` is detected, then we know we don't have a matching `(` and can exit. Simple `//` comments are matched (and ignored) via a regular expression for the minus fifty bonus.
[Answer]
# Bash: 369 bytes - 110 bonus = 259
```
e=exit;function f(){ s=$1;a=X;until [ "$a" = "" ];do a=${s::1};s=${s:1}
if [ "$a" = \( ];then f "$s" \)||$e 1
elif [ "$a" = [ ];then f "$s" ]||$e 1
elif [ "$a" = \< ];then f "$s" \>||$e 1
elif [ "$a" = { ];then f "$s" }||$e 1
elif [ "$a" = \) ]||[ "$a" = ] ]||[ "$a" = \> ]||[ "$a" = } ]
then [ $a = "$2" ]&&return||$e 1;fi;done;[ "$2" = "" ]||$e 1;};f "$1"&&$e 0||$e 1
```
Scoring:
* Handles all four brace types, **4x -20 = -80**
* handles mismatched brackets, **-30**
There's probably room to further golf the chain of elifs into && and ||'s, but some odd behaviour started creeping in when I tried so I gave up :)
[Answer]
## Javascript: ~~392~~ ~~383~~ ~~387~~ 345 characters - 210 bonus = 135 points
```
function x(a){z=1;k="",a=a.replace(/\/\*.*?\*\/|\/\/.*?\n|".*?"|'.*?'/mg,"").split('');try{for(d in a){eval("c=a[d]//%(')k='(%[')k='[%{')k='{%<')k='<%)_(#%]_[#%}_{#%>_<#".replace(/#/g,"')k=k.substr(1);else z=0//").replace(/%/g,"'+k\nif(c=='").replace(/_/g,"')if(k.charAt(0)=='"))}}catch(e){z=0}return''==k&z==1&a.indexOf("'")<0&a.indexOf('"')<0}
```
It is a function that returns 0 if the input is not valid and 1 if it is.
First, it uses regular expressions to remove the `/* ... */`, `// ... \n`, `' ... '` and `" ... "` sequences.
Second, it decompresses and run a code that iterates the input string, char-by-char, looking for `(`, `[`, `{` and `<`, stacking them into a string `k`. When he founds `)`, `]`, `}` and `>`, it looks the top of the stack and if they match, he pops the stack, otherwise he sets a variable `z` to zero. If any exception happens, `z` is set to zero.
In the end, he checks if the stack is empty and no `'` or `"` are left, returning 1 if this is the case and 0 otherwise.
Thanks to @Charles for pointing out bugs in earlier versions.
[Answer]
# JavaScript (ES6), ~~92~~ 115 Bytes
Oh look, I beat the other JavaScript answer without any bonuses.
```
c=s=>{d=0;s=s.split("");for(z=0;z<s.length;z++){if(s[z]=="{")d++;if(s[z]=="}")--d;if(d<0)a="N"}return a||d?"N":"Y"}
```
Ungolfed, dev-friendly, and ES5-(-friendly) version:
```
function check(str){
depth = 0;
str = str.split("");
for(var z=0;z<str.length;z++){
if(str[z]=="{") str[z]+=depth++;
if(str[z]=="}") str[z]+=--depth;
if(depth<0) return "unmatched";
}
return depth;
}
```
Returns a version of the string with the "depth" of the bracket afterword. I am using this function for evaluation purposes. I might try for some bonuses later.
[Answer]
# Bash - 4 chars
```
cc f
```
Assuming `f` is your c source code file
If you want it to print 'yes' or 'no', 43 chars:
```
cc f;if $?=0;then echo yes;else echo no;fi
```
[Answer]
# Python 2.7: 171 bytes - 60 - 30 = 81 points
```
import sys
b=[]
for c in sys.stdin.read():
if c in '([{<':b+=[c]
if c in ')]}>':
if b[-1]!='([{<'[list(')]}>').index(c)]:print 0==1;break
b.pop()
else:print len(b)==0
```
Handles all bracket types and doesn't allow mismatched brackets.
[Answer]
## VB.net 93c
This check to see if BrainF\*ck code has balanced square braces.
```
Function(c$)c.Aggregate(Of Int32)(0,Function(s,i)If(s<0,s,If(i="["c,s+1,If(i="]"c,s-1,s))))=0
```
[Answer]
## Perl, 106 bytes − (3\*20 + 30 + 50 + 0 + 0) bonus = −34 points
```
$_=join"",<>;$a='[^()<>{}[\]]*';while(s|//.*||+s/\($a\)//+s/\[$a]//+s/{$a}//+s/<$a>//){}exit!/[()<>{}[\]]/
```
Input is expected from STDIN (multiple lines) and the return is given as exit code, 1 for successful validation and 0 for unmatched braces.
Example for calling:
```
perl bracevalidator.pl<inputfile;echo $?
```
The following is supported/validated:
* Balanced braces: `(`..`)`, `<`..`>`, `{`..`}`, `[`..`]`.
* No mismatch for different brace types.
* C++ style comments `//`.
The idea is to match the innermost balanced braces first and removes them from the string until all brace pairs are gone. If a brace is left, then the return value is 0, otherwise all braces are properly nested and 1 is returned.
First the whole file is read in variable `$_`:
```
$_join'',<>;
```
Variable `$a` serves as abbreviation for the brace free stuff between an innermost brace pair:
```
$a='[^()<>{}[\]]*';
```
The main loop removes the C++ comments and the brace pairs bottom-up:
```
while(s|//.*||+s/\($a\)//+s/\[$a]//+s/{$a}//+s/<$a>//){}
```
Then the remaining string is checked for any remaining brace:
```
exit!/[()<>{}[\]]/
```
[Answer]
**C# - 380 characters**
Continuously reads the user's input until they quit, each time giving back true or false as to whether their input is valid.
```
using C = System.Console;
namespace P
{
class P
{
static void Main(string[] a) { while(true) C.WriteLine(F(C.ReadLine())); }
static bool F(string x)
{
int l = 0, r = 0;
foreach (var c in x) { if (c == '[') l++; if (c == ']') { r++; if ( r > l ) return false; }
return l == r;
}
}
}
```
**Condensed form - 239 characters**
```
using C = System.Console;
namespace P{class P{static void Main(string[] a){while(true)C.WriteLine(F(C.ReadLine()));}static bool F(string x){int l=0,r=0;foreach(var c in x){if(c=='[')l++;if(c==']'){r++;if(r>l)return false;}}return l==r;}}}
```
And lastly
**the function itself - 112 characters (condensed form)**
```
bool F(string x){int l=0,r=0;foreach(var c in x){if(c=='[')l++;if(c==']'){r++;if(r>l)return false;}return l==r;}
```
[Answer]
# EcmaScript 6:
```
!(_=x[z='replace'](/("|').*?\1|\/\*.*?\*\/|[^({<[\]>})]/g,''),_.length-_[z](/[^({<[]/g,'').length)
```
[Answer]
# TI-BASIC, 39 bytes
```
cumSum(iPart(2sin(2seq(inString("()",sub(Ans,X,1)),X,1,length(Ans
not(min(Ans or Ans(dim(Ans
```
`cumSum(` keeps a running total of the number of braces, then the second line checks if both the minimum and the last element are zero.
Two tricks used:
* `iPart(2sin(2*` maps `{0,1,2}` to `{0,1,-1}` so I don't need to match `{` and `}` separately.
* I `or` the last element with the whole list, rather than `min(Ans)`, to save a close-paren.
[Answer]
# Python, 7 bytes
```
eval(i)
```
Where `i` is the input. It handles `{`, `[` and `(`, ignores braces in quotes, and, does to allow mismatched braces.
On an error, a Syntax error is generated!
Example:
```
>> eval('([{"("}])')
>> eval('([{(}])')
^
SyntaxError: invalid syntax
```
Edit: This is just a fun partial solution. It does not handle cases such as `[` inside `{`, and `{}[]` etc.
] |
[Question]
[
You will need to evaluate the definite integral (bounded by \$a\$ and \$b\$) of a certain polynomial function that takes the form of:
$$\int\_a^b \left( k\_n x^n + k\_{n-1} x^{n-1} + \cdots + k\_2x^2 + k\_1x + k\_0 \: \right) dx$$
Normally, this can be done using the fundamental theorem of calculus and power rules. For example:
$$\int\_b^c ax^n dx = a \frac{x^{n+1}} {n+1} \Big|^c\_b = a\left[ \frac{c^{n+1}} {n+1} - \frac{b^{n+1}} {n+1} \right]$$
The challenge here is to replicate that process using the shortest amount of code as possible. You will decide the degree your program can solve. Somewhere in your answer, specify how many degrees your program can solve up to. For example:
>
> My program can solve all polynomials up to the 5th degree. (quintic polynomial)
>
>
>
## Input
Input will be two arrays consisting of bounds and coefficients. For example:
```
bounds = [2, 3]
coefficients = [4, 5, 2, 7]
```
The above input will yield this expression:
$$
\int\_2^3 (4x^3 + 5x^2 + 2x + 7) \mathop{dx}
$$
## Output
The output will be a single decimal number rounded to at least 3 decimal places. So the above expression will yield:
```
108.666666666667 // correct
108.6667 // correct
109 // wrong
```
## Constraints
$$
-10^9 < k\_n, ..., k\_1, k\_0 < 10^9
$$
$$
0 < N < 30
$$
Integral bounds \$a, b\$ satisfy no additional constraints.
## Rules & Scoring
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here as it does anywhere else.
* You may not write a program that only solves a specific integral. Once you pick your degree, that program must work under all constraints up to that degree.
* Your score will be calculated by this equation: `degree of polynomial / num of bytes`, and the highest score wins.
* If your program works for all degrees above 30, set your numerator to be 30, otherwise 29 is the maximum possible numerator.
* Please post a working version of your code on any website so that it can be tested.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), \$\frac {30} 7 = 4.29\$
```
÷J$ŻUḅI
```
[Try it online!](https://tio.run/##y0rNyan8///wdi@Vo7tDH@5o9fz//7@5jpGOqY7JfyMdYwA "Jelly – Try It Online")
Takes the polynomial as a list of coefficients in little-endian format (i.e. the example is `7,2,5,4`). This can handle any (positive) degree you want, but I've limited it at 30 as the question states \$0 < N < 30\$
[+2 bytes](https://tio.run/##y0rNyan8/98r9PB2h2Nd1gYPd7R6/v//30THVMdIx/y/kY4xAA) and a score of \$3.33\$ if the polynomial must be taken in big-endian format
## How it works
```
÷J$ŻUḅI - Main link. Takes coeffs on the left and [a, b] on the right
$ - To the coeffs:
J - Yield [1, 2, 3, ..., N]
÷ - Divide each coeff by the orders
Ż - Prepend 0
U - Reverse
ḅ - Calculate as polynomials, with x = a and x = b
I - Reduce by subtraction
```
[Answer]
# [J](http://jsoftware.com/), \$\frac{30}{12}\approx2.5\$
```
[:-/[-p..p.[
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6109aN1C/T0CvSi/2typSZn5CsYKRgrpCmYA2lTBZP/AA "J – Try It Online")
*-1 thanks to Bubbler*
* `p..` Integral of a polynomial. Returns a list representing the solution polynomial.
* `p.` Evaluate polynomial at given bounds.
* `[-` Subtract from constant terms (makes both values negative).
* `-/` And subtract negative ending bound answer from negative starting bound answer.
[Answer]
# [Factor](https://factorcode.org/), \$\frac{30}{56}\approx0.5357\$
```
[ [ 1 + 3dup nip v^n first2 - swap / * ] map-index sum ]
```
[Try it online!](https://tio.run/##HY2xDoIwGAZ3nuKbNWAEjQk@AGFhMU4Ek6b8hMZS69@CGsKzV3S5G264Tkj/4HC9lFWR405sSGMQvv8jmeiXHSyT9x/Lyng4eo5kJDmco7LK4SQLL/toRoYUC2acVh9xwBJq1Nhji6wdLYyymG4GnWLnU8RwL2GxwwbNerOxMi294cYBTZBCaySQmgSHLw "Factor – Try It Online")
Takes the bounds and coefficients in reverse, e.g. `{ 3 2 } { 7 2 5 4 }`, and returns a rational number, e.g. `108+2/3`.
To take the inputs as given and return a float, add a `reverse`, a `neg`, and a `>float` to get 75 bytes:
# [Factor](https://factorcode.org/), \$\frac{30}{75}=0.4\$
```
[ reverse [ 1 + 3dup nip v^n first2 - swap / * ] map-index sum neg >float ]
```
[Try it online!](https://tio.run/##HY3BCoJAGAbvPsV3LjTSIjDoGl68RCcxWNbfXFrX7d/VCvHZzboMA3OYWkjf8Xy9ZPk5xYPYkEYrfPNHNNAvO1gm7z@WlfFw9OzJSHI4BlmewkkWXjbBiBgJJozYYb/4AdNcgGkgdoQCW6yRVL2FURbDzaBW7HyMEO4lLDZYoVyuNlSmojdc38LQHadad8KjnKXQGhGkJsHzFw "Factor – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), \$ \frac {30} {20} = 1.5 \$
```
UMθ∕ι⁻Lθκ⊞θ⁰I⁻↨θζ↨θη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/983scA5Pzc3MS9Fo1BHwSWzLDMlVSNTR8E3M6@0WMMnNS@9JEOjUFNHIVtTU9OaK6C0OAOk0ADELsrMK9FwTiwu0YCodkosTgVJVgGVw9gZmiB9//9HR5voKJjqKBjpKJjHginj2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
UMθ∕ι⁻Lθκ
```
Divide each element of the polynomial by the 1-indexed reverse index.
```
⊞θ⁰
```
Append a zero.
```
I⁻↨θζ↨θη
```
Calculate the value at each bound and take the difference.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~30/32=0.9375~~ \$\frac{30}{31}\approx0.9677\$
```
c(a=0;c^++a.{-1,1}/a&/@#).#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P/n9pIUaibYG1slx2tqJetW6hjqGtfqJavoOypp6ymr/A4oy80qi/RzSoquNdIxrY6OrzXWMdEx1TGpjY/8DAA "Wolfram Language (Mathematica) – Try It Online")
Accepts coefficients in ascending (lower to higher exponent) order. Input `[{a, b}][coeff]`.
---
some 32-byters:
```
FromDigits[#,]~Integrate~{,##2}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7360oP9clMz2zpDhaWSe2zjOvJDW9KLEkta5aR1nZqFbtf0BRZl5JtJ9DWnS1iY6pjpGOeS2QMI6N/Q8A "Wolfram Language (Mathematica) – Try It Online") Integrates using `Null` as the variable.
```
#2-#&@@Sum[i/++a#2^a,{i,a=0;#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lIV1nNwSG4NDc6U19bO1HZKC5RpzpTJ9HWwFq5Nlbtf0BRZl5JtJ9DWnS1uY6RjqmOSa1OtZGOcW1s7H8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), \$\frac{30}{20}=1.5\$
```
{-/⌽⊥∘(0,⍨⍵÷⌽⍳≢⍵)¨⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqXf1HPXsfdS191DFDw0DnUe@KR71bD28HifVuftS5CMjTPAQU21X7/7@RgrFCmoKJgqmCkYI5AA "APL (Dyalog Unicode) – Try It Online")
Takes the bounds on the left and the coefficients on the right. This is a great place to use APL's ⊥, which can evaluate polynomials (although appending a zero is necessary because we want to use n+1 and not n).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), \$\frac{30}{8} = 3.75\$
```
āR/0ªIβÆ
```
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/219106/52210), so make sure to upvote him as well!
First input is the list of coefficients; second is a pair of \$[b,a]\$ bounds.
[Try it online.](https://tio.run/##yy9OTMpM/f//SGOQvsGhVZ7nNh1u@/8/2kTHVMdIxzyWK9pYxygWAA)
**Explanation:**
```
ā # Push a list in the range [1, (implicit) coefficients-length]
R # Reverse this range to [length,1]
/ # Divide the coefficients by the ranged list (at the same postitions)
0ª # Append a 0 at the end of this list
Iβ # Convert this list to base-b and base-a using the second input-pair
Æ # And reduce that pair by subtracting
# (after which the result is output implicitly)
```
[Answer]
# [SageMath](https://doc.sagemath.org/), \$\frac{30}{67}\approx 0.44776\$
```
lambda c,b:RR(integrate(sum(a*x**e for e,a in enumerate(c)),[x]+b))
```
[Try it online!](https://sagecell.sagemath.org/?z=eJw9jkEKgzAQRfeeYnZO7BSithQEewi3VkpiRwloKiaC9PSNVjq7z7zP-135iAY16peClnRRVWis535WntEtI6pkTRKG7j0DkwJjge0y8v5vhaB6bU5aiMiz888WSsAIwtU3yuhKl4b2OBjncVa2Z8yllKF3NPS_kFF-wLWktAnA5gybNufHTPgzEPx6othZF4wdBkrscZrDemzrIpUNgSaI4XyHmMCJL7fiP4E=&lang=sage&interacts=eJyLjgUAARUAuQ==)
Inputs the coefficients (from the constant to the highest degree) and bounds as lists.
Can surely work for much higher degrees of a polynomial but got tired waiting for it to finish \$10000\$.
Works quite quickly for degree of \$3000\$.
[Answer]
# JavaScript, score: \$\frac{30}{71}\approx 0.42\$
```
n=>k=>(x=y=>k.reduce((a,b,c)=>a+b*y**(z=k.length-c)/z,0))(n[1])-x(n[0])
```
Demonstration:
```
f=n=>k=>(x=y=>k.reduce((a,b,c)=>a+b*y**(z=k.length-c)/z,0))(n[1])-x(n[0]);
// test case
console.log(f([2,3])([4,5,2,7]));
// large polynomial of degree 30
console.log(f([3,5])(new Array(31).fill(1) /*shortcut*/));
```
## How it works
Constructs a function dynamically which calls reduce on the coefficients array. Then invokes it on both bounds and takes the difference.
[Answer]
# [C (gcc)](https://gcc.gnu.org/) (`-lm`), score: \$\frac{30}{90}= 0.\bar3\$
Sums the bounds for each term in descending order. Due to quirks with `-O0`, I was able to write this function without the usual return or explicit value assignment at the end of the function.
```
double f(b,t,n,i,j)int*b,*t;{for(double s=i=0;j=n-i;)s+=t[i++]*(pow(b[1],j)-pow(*b,j))/j;}
```
[Try it online!](https://tio.run/##pVHLTsMwELz7K1ZBSHayAfoSB5N@QcWNU5QDceLiKLWr2qaHyL9OcNpSKq7Il53RzD7GIt8KMY6N8XXfgqQ1OtSosGNKu7TG1PFBmgO9CGyhiifeFTpXnNmscKXKsiqle3OkdTmroi@f6ujsGHvseBjvlBa9b1p4sa5R5uFjTYh1By8cSK8FDAQgzoK0Nl43lv9AYVopr1D7HSeBEzKB3bvS9NOohp3ct91ca50tq2LiAQagUV9WbJjjIuAVLXGFc3yOzBIC/pEucHUjneE/XuyzmP1OeH3bbCBEEPkYLInVlK0rTltzcPn6EgK4LEPYe2dpkrDzmQD7Q1xK0uReJhj/6irHyXnO61TGsBibkgskjF9C9u9bO@b9bsyP3w "C (gcc) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 55 bytes, score: \$\frac{30}{55}=0.\overline{54}\$
```
function(b,k)diff(outer(b,a<-rev(seq(!k)),"^")%*%(k/a))
```
[Try it online!](https://tio.run/##DchBCoAgEADAr5Qg7MZKYEUX3xKYuSCCkmXfN48zpfFg1NC4JveGnOCkiFdghlxfXzqtUcV/8PgbxohI4hAoJwlxtoiNwYGmBcnBShtp2nv@ "R – Try It Online")
If we could take the coefficients in ascending order of degree, this would be 5 bytes shorter and get a score of \$0.6\$ instead, by removing the `rev()`.
[Answer]
# Scala, \$\frac{30}{88}\approx0.3409\$
```
p=>_.:\(.0)((x,r)=>p.reverse.zipWithIndex.map{case(k,n)=>k*math.pow(x,n+1)/(n+1)}.sum-r)
```
[Try it in Scastie](https://scastie.scala-lang.org/3y7Vl7MIQQqmhLmqAR1wWw)
The question's IO format actually works out quiet well here (although I could save 8 bytes by taking the coefficients in reverse to avoid `.reverse`).
[Answer]
# APL(NARS), 14 chars
```
a←⎕⋄-/{⍵⊥a}∫¨⎕
```
For the input of polynom the list
$$ a\_n a\_{n-1} ... a\_1 a\_0 $$
means polynom
$$ a\_n X^n+a\_{n-1} X^{n-1} ... a\_1 X+a\_0 $$
test:
```
a←⎕⋄-/{⍵⊥a}∫¨⎕
⎕:
4 5 2 7
⎕:
3 2
108.6666667
```
] |
[Question]
[
Leonardo of Pisa (ca. 1175 - ca. 1245) is better known as **Fibonacci**. But this is actually a short for the Latin "filius Bonacci" (the son of Bonacci) which was made up during the 18th century (according to [Wikipedia](https://en.wikipedia.org/wiki/Fibonacci)).
In this challenge, you'll be given an ordinal number (in the literal sense) between ***1***st and ***20***th and you have to return the corresponding term in the [Fibonacci sequence](http://oeis.org/A000045).
The twist is that the ordinal number will be given in Latin.
**Example**: "duodecimus" → \$89\$.
## Full I/O table
```
input | meaning | output
--------------------+---------+--------
"primus" | 1st | 0
"secundus" | 2nd | 1
"tertius" | 3rd | 1
"quartus" | 4th | 2
"quintus" | 5th | 3
"sextus" | 6th | 5
"septimus" | 7th | 8
"octavus" | 8th | 13
"nonus" | 9th | 21
"decimus" | 10th | 34
"undecimus" | 11th | 55
"duodecimus" | 12th | 89
"tertius decimus" | 13th | 144
"quartus decimus" | 14th | 233
"quintus decimus" | 15th | 377
"sextus decimus" | 16th | 610
"septimus decimus" | 17th | 987
"duodevicesimus" | 18th | 1597
"undevicesimus" | 19th | 2584
"vicesimus" | 20th | 4181
```
## Rules
* The input is guaranteed to be *exactly* one of the strings described above.
* If that helps, you may take it in full uppercase instead. But it must be consistent for all entries. Mixed cases are not allowed.
* Depending on your algorithm and language, hardcoding or computing the terms of the sequence may either win or lose bytes. Both approaches are explicitly allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")!
[Answer]
# [R](https://www.r-project.org/), ~~91~~ 86 bytes
Look up the index of the sum of bytes in a brute-forced UTF8 lookup table and use the [magic Fibonacci generating function](https://austinrochford.com/posts/2013-11-01-generating-functions-and-fibonacci-numbers.html) to give the answer.
```
function(x)round(1.618^match(sum(!x)%%93,!'%(-1!5
+3JOSCW6')*.2765)
"!"=utf8ToInt
```
[Try it online!](https://tio.run/##XY6xj4IwGMWTS1zYHBwcLoEmxPZEEzSgDkxO3uLg5W67hJQSO9Bi@WqI/zyitYJuv/d9L@891dQJxahUvNAVClxUMapFZhiYAm7wpFMFFrkAa64N3bAEmyEppGeDQgoDGaP23eZ3ItOyU89Kt@d4VL@e7hP6JzPF7WfZSe573ZlTVvXXvBw6QRwnT5pcCwpcClwTJVs3DudxuP4vUqBHXOkCezXx/c0y8CYjH89CL/ocfEyX3/vD9m88jCfka75YxRFxkIcSDfn6R@4ENL@MglT8wnBO2minuQI "R – Try It Online")
Edit: -2 bytes by improved numeric rounding
Edit: -3 bytes with a change to the lookup (thanks for the hint, @Giuseppe!)
[Answer]
## Ruby, ~~104~~ 93 bytes
```
->x{[8,4181,3,144,21,13,0,1,233,5,987,0,377,55,0,89,1,1597,34,610,0,2,2584][x.sum%192%76%23]}
```
[Try it online!](https://tio.run/##bdPdboIwFAfwe56iwRk1q8y2IHDh9iDOLAxwI5HCaDEu4rOzUwLla1wdOD/68U9blJ@/9Rkd6u3r7X70sE08ghkmto0pwYThHSaYMoYd7HsuvDHXxY4DhedDhzi@i5mN92QHnyimjmefjjdLlOmS@HTp7peUnR71KuF5KdHoqVAaBzzhX1BlpYS@sf3neZ5XBjLzIklLYY6GQ4gI2VZoB0jEYcmjIVMtyqMOEUAyLmQyGkq1WDFCP2VQyBmy5XeHaIMSPkdOj1izppucL3zfI6dBuRzvT7XcHnmAslAG19l0nkZETcczPp6tafkaUbW7KA4naUKL7DRiNiBIcsIUIho5auFRmU2UQlQjz@8TR71UiHUIzl6f@ATpxOFI9olPkE4czqpOfGAapBOHoztIvGcK6cTh7He7uyZhLIYjdYmru9DmNDIN6hJXFwTQGLSIdomrS7iyRH5J5PrpZWNFRZav6cZKgxxFGaouCY8rQ/0lMPrAiKMDUt/aX96qTdOEGyWQubifj/E1uCBxerzLxb2p@cM0Yh7Vfw)
Simply takes the sum of the bytes, modulo 192 modulo 76 modulo 23, and indexes into a lookup table. (Magic numbers found by brute force.)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 87 bytes
*All escapes except `\n` are treated as one byte, since the compiler's fine with the actual raw values. (TIO and SE have issues with it not being valid UTF-8 though, and so it's escaped here)*
[FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) made a nice demonstration / workaround: [here](https://tio.run/##ZVPvj5pAEP3OXzGxl6LxEBGx9SKXGCWpyR1eBS9NwDTLAr2tsBDAqyb3v9sV@SXHh8284b03k9lZB6Vv53OcEJr50Akj9xB4ECJCbdqBR4ilAQ48RDmupJAwjpIMjMzV6Dtn36Xqm2sR@/KRmbAHCYZf8Ux4sDu5ftTWe8MJkoeyIk89/A2NlKms4ImHXH@kIMWfyNIEjUdTb@x878AHHI8uCHEKQnIxk9tmducDq2p6CCHdcXtwAKkWeth3Ud/pObu8gfEnDTUylGTcF4gSl1AUpKCCZfEvm9Xz1uB39xZvaIutviyAqW3MVRH/3M43ZhWvdLMS/KrDF7MyWi/M@WsR62u9iJbaomKwOg203K6bsCgNzVzRQiuXt3KTu7bUSl1bg08lX1cLzbjp6TbTQDs2OP9AcUYiygZn33Fset3k7yHNiH8CaVKOFaDfB4tnHGZRS4q/98CzjaF8D/LVqUQzobqW6/0p5f1hlMGseznLpeqVWG7hcYkfwXFPhcE/DAJu4AuzRvV2sMW/KSbdmleSqppSV4uTPw33GrXcvWP@hhZP2lz//WP9rKliFGfilRtQEPxamz/GAcEBV3NEh1AWhSCsnmB5oigkmL0RJ@eCEOVqxmEdia73LtJDEHADsciez/8B)
```
import StdEnv
$s=hd[i\\i<-k 1 0&c<-:"\340\152\060\065\071\354\172\045\223\n\255\362\132\137\143\026\244\051\344\270"|c==sum s]
k b a=[a:k(a+b)b]
```
[Try it online!](https://tio.run/##ZVHLasJAFN37FRcrjaLC5GVAzEKSLAJttCaRQm4WY9R2qhlLHgWh3950WtP46GKYc87cx@FMst9QXqWHdbnfQEoZr1j6fsgK8Iu1wz9andx8XUcMkU2GO5CB3CeT4biNqkZQ1hUkIyKOjsSQUdU1lA2haToqioocFV1HdaSgrP4cA2VNRaKMUNE0JLroELdikPZnYpp5mUIet3awAmpGdLzr0v6qt4orv6BZ0bqDQ7ZmnO5zMCGKpPnCfQx9KR5Eku9YoWfXJHAWgVvjp3C6CBrsekHT8HyG86AZNLOC6bLG3syrke1YTYXYc8HscHZJ69VwqdUWbrRfK1faydKNdLIG/1YuXcvxrzxdKxcsFsFtS54U7MBFcJ2WCK@bvZV5wbZHkEd/qQL0@xBJokRMOHfUrwOQkEs9QGzqJ8PmQ@LqK9nu6UteDd2Hyj5ymrJEkNU3 "Clean – Try It Online")
Defines the function `$ :: [Char] -> Int`, which uses the uniqueness in the summation of the uppercase character values to determine which term in the sequence (generated by the helper function `k`) to return.
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 82 bytes
```
00 C0 20 9E AD 20 A3 B6 A8 88 A9 05 4A 90 02 49 B1 71 22 88 10 F6 29 1F C9 07
B0 02 69 0D A8 BE 32 C0 B9 1E C0 4C CD BD 00 00 00 00 03 00 0A 00 06 10 01 00
FF 00 02 00 00 00 00 00 08 00 15 0D DB 02 18 90 3D 55 79 05 FF E9 62 22 01 59
01 37 FF 03
```
This uses hashing (of course), but optimized for short implementation on the 6502, taking advantage of the carry flag set by shifting and used in addition. Magic numbers for hashing were found by brute forcing with a little C program; the `FF` bytes are unfortunate holes in the hash table ;)
Byte count: 2 bytes load address, 38 bytes code, 42 bytes hashtable for values.
### [Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22fibhash.prg%22:%22data:;base64,AMAgnq0go7aoiKkFSpACSbFxIogQ9ikfyQewAmkNqL4ywLkewEzNvQAAAAADAAoABhABAP8AAgAAAAAACAAVDdsCGJA9VXkF/+liIgFZATf/Aw==%22%7D,%22vice%22:%7B%22-autostart%22:%22fibhash.prg%22%7D%7D)
Usage: `SYS49152"[ordinal]"`, for example `SYS49152"DUODECIMUS"`. (note the letters appear upper case in the default C64 configuration).
**Important**: Before the first start, issue a `NEW` command. This is needed because the C64 BASIC `LOAD` command fiddles with some BASIC vectors, even when loading a machine program to some absolute address (like here `$C000`/`49152`).
**Commented disassembly**:
```
00 C0 ; load address
.C:c000 20 9E AD JSR $AD9E ; evaluate expression
.C:c003 20 A3 B6 JSR $B6A3 ; evaluate as string
.C:c006 A8 TAY ; length to y register
.C:c007 88 DEY ; decrement (start at last char)
.C:c008 A9 05 LDA #$05 ; start value for hash
.C:c00a .hashloop:
.C:c00a 4A LSR A ; shift right
.C:c00b 90 02 BCC .skip ; shifted bit zero? -> skip xor
.C:c00d 49 B1 EOR #$B1 ; xor "magic" value
.C:c00f .skip:
.C:c00f 71 22 ADC ($22),Y ; add current character (plus carry)
.C:c011 88 DEY ; previous character
.C:c012 10 F6 BPL .hashloop ; pos >= 0? -> repeat
.C:c014 29 1F AND #$1F ; mask lowest 5 bits
.C:c016 C9 07 CMP #$07 ; larger than 7 ?
.C:c018 B0 02 BCS .output ; -> to output
.C:c01a 69 0D ADC #$0D ; add 13
.C:c01c .output:
.C:c01c A8 TAY ; hash to y register
.C:c01d BE 32 C0 LDX .lb-8,Y ; load low byte from hashtable
.C:c020 B9 1E C0 LDA .hb-8,Y ; load high byte from hashtable
.C:c023 4C CD BD JMP $BDCD ; to output of 16bit number
.C:c026 .hb:
.C:c026 00 00 00 00 .BYTE $00,$00,$00,$00
.C:c02a 03 00 0A 00 .BYTE $03,$00,$0A,$00
.C:c02e 06 10 01 00 .BYTE $06,$10,$01,$00
.C:c032 FF 00 02 00 .BYTE $FF,$00,$02,$00
.C:c036 00 00 00 00 .BYTE $00,$00,$00,$00
.C:c03a .lb:
.C:c03a 08 00 15 0D .BYTE $08,$00,$15,$0D ; second byte used in .hb as well
.C:c03e DB 02 18 90 .BYTE $DB,$02,$18,$90
.C:c042 3D 55 79 05 .BYTE $3D,$55,$79,$05
.C:c046 FF E9 62 22 .BYTE $FF,$E9,$62,$22
.C:c04a 01 59 01 37 .BYTE $01,$59,$01,$37
.C:c04e FF 03 .BYTE $FF,$03
```
---
### C64 BASIC V2 test suite
(containing the machine program in `DATA` lines)
### [Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22fibtest.prg%22:%22data:;base64,AQgeCAAAgUGyNDkxNTKkNDkyMzE6h0I6l0EsQjqCAD4IAQCZIlBSSU1VUyIsOp40OTE1MiJQUklNVVMiOpkAYggCAJkiU0VDVU5EVVMiLDqeNDkxNTIiU0VDVU5EVVMiOpkAhAgDAJkiVEVSVElVUyIsOp40OTE1MiJURVJUSVVTIjqZAKYIBACZIlFVQVJUVVMiLDqeNDkxNTIiUVVBUlRVUyI6mQDICAUAmSJRVUlOVFVTIiw6njQ5MTUyIlFVSU5UVVMiOpkA6AgGAJkiU0VYVFVTIiw6njQ5MTUyIlNFWFRVUyI6mQAMCQcAmSJTRVBUSU1VUyIsOp40OTE1MiJTRVBUSU1VUyI6mQAuCQgAmSJPQ1RBVlVTIiw6njQ5MTUyIk9DVEFWVVMiOpkATAkJAJkiTk9OVVMiLDqeNDkxNTIiTk9OVVMiOpkAbgkKAJkiREVDSU1VUyIsOp40OTE1MiJERUNJTVVTIjqZAJQJCwCZIlVOREVDSU1VUyIsOp40OTE1MiJVTkRFQ0lNVVMiOpkAvAkMAJkiRFVPREVDSU1VUyIsOp40OTE1MiJEVU9ERUNJTVVTIjqZAO4JDQCZIlRFUlRJVVMgREVDSU1VUyIsOp40OTE1MiJURVJUSVVTIERFQ0lNVVMiOpkAIAoOAJkiUVVBUlRVUyBERUNJTVVTIiw6njQ5MTUyIlFVQVJUVVMgREVDSU1VUyI6mQBSCg8AmSJRVUlOVFVTIERFQ0lNVVMiLDqeNDkxNTIiUVVJTlRVUyBERUNJTVVTIjqZAIIKEACZIlNFWFRVUyBERUNJTVVTIiw6njQ5MTUyIlNFWFRVUyBERUNJTVVTIjqZALYKEQCZIlNFUFRJTVVTIERFQ0lNVVMiLDqeNDkxNTIiU0VQVElNVVMgREVDSU1VUyI6mQDmChIAmSJEVU9ERVZJQ0VTSU1VUyIsOp40OTE1MiJEVU9ERVZJQ0VTSU1VUyI6mQAUCxMAmSJVTkRFVklDRVNJTVVTIiw6njQ5MTUyIlVOREVWSUNFU0lNVVMiOpkAOgsUAJkiVklDRVNJTVVTIiw6njQ5MTUyIlZJQ0VTSU1VUyI6mQCLCxUAgzMyLDE1OCwxNzMsMzIsMTYzLDE4MiwxNjgsMTM2LDE2OSw1LDc0LDE0NCwyLDczLDE3NywxMTMsMzQsMTM2LDE2LDI0Niw0MSwzMQDbCxYAgzIwMSw3LDE3NiwyLDEwNSwxMywxNjgsMTkwLDUwLDE5MiwxODUsMzAsMTkyLDc2LDIwNSwxODksMCwwLDAsMCwzLDAsMTAsMCw2ACwMFwCDMTYsMSwwLDI1NSwwLDIsMCwwLDAsMCwwLDgsMCwyMSwxMywyMTksMiwyNCwxNDQsNjEsODUsMTIxLDUsMjU1LDIzMyw5OCwzNCwxAD8MGACDODksMSw1NSwyNTUsMwAAAA==%22%7D,%22vice%22:%7B%22-autostart%22:%22fibtest.prg%22%7D%7D)
```
0fOa=49152to49231:rEb:pOa,b:nE
1?"primus",:sY49152"primus":?
2?"secundus",:sY49152"secundus":?
3?"tertius",:sY49152"tertius":?
4?"quartus",:sY49152"quartus":?
5?"quintus",:sY49152"quintus":?
6?"sextus",:sY49152"sextus":?
7?"septimus",:sY49152"septimus":?
8?"octavus",:sY49152"octavus":?
9?"nonus",:sY49152"nonus":?
10?"decimus",:sY49152"decimus":?
11?"undecimus",:sY49152"undecimus":?
12?"duodecimus",:sY49152"duodecimus":?
13?"tertius decimus",:sY49152"tertius decimus":?
14?"quartus decimus",:sY49152"quartus decimus":?
15?"quintus decimus",:sY49152"quintus decimus":?
16?"sextus decimus",:sY49152"sextus decimus":?
17?"septimus decimus",:sY49152"septimus decimus":?
18?"duodevicesimus",:sY49152"duodevicesimus":?
19?"undevicesimus",:sY49152"undevicesimus":?
20?"vicesimus",:sY49152"vicesimus":?
21dA32,158,173,32,163,182,168,136,169,5,74,144,2,73,177,113,34,136,16,246,41,31
22dA201,7,176,2,105,13,168,190,50,192,185,30,192,76,205,189,0,0,0,0,3,0,10,0,6
23dA16,1,0,255,0,2,0,0,0,0,0,8,0,21,13,219,2,24,144,61,85,121,5,255,233,98,34,1
24dA89,1,55,255,3
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 62 bytes
```
{(0,1,*+*...*)[index '%(-1!5
+3JOSCW6',chr .ords.sum%93]}
```
[Try it online!](https://tio.run/##ZY47C8IwGEVBcHFzcHAQYsG@DYpYcHByc3FwcCgdShIxYNOaR2kRf3sVG/rQ7dzLl9yTEX4PqqQE5hXsQfW0V/7adz0XQug6IWWYFMCaLOzler6dDQfe5ng6Hy7TcWD56MYBTDkWUKhksdtEryo0Mk4TJQx/BAxBkGJYB0m4pJofKuayYcpk86BoMZPNRymSca6ZpUwTJqi5@Ox0ElZpN@pp0O20wk/3Vel1tdJPVauBv8mcIiJ6Tv2mTRFM4sw2rw4UcVm9AQ "Perl 6 – Try It Online")
Uses a lookup table in a string, as well as a short fibonacci sequence generator.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~135~~ 129 bytes
6 bytes down by suggestion of ceilingcat and Logern
```
f;i;b;o;n(char*a){for(f=i=b=o=0;*a;o+=21*b+++*a++-70);for(b=1,o="TACIHAAJQFSAAARCAMGKDANPEAOAAL"[o%30];--o>65;f=b,b=i)i=f+b;a=i;}
```
[Try it online!](https://tio.run/##ZZJJb4MwEIXP5VdYSJEAExUCBFLXlazu@3pLc2BtfajdghNVavvbU4MJpPSC0feePTNPk45f0nS9LhBFCeKIGelrXFqx@VXw0igwxQnm2EFWjDjEE9dKIIRWDOE4dExUexLs2hzrT@Tw/IyQi/uTR0LIwyG5Pr08Ijd3x@SWkCt9zkees0DjMT@YBqjAiZ1galJcwATFmKKfdV0XWCKvRDVfAKx9aTv6e0nflpVu7@6Cb@BWQn4dias8XbKsEyYsq2UpiLwUtONeueEfy7gUHffFa32r4ZT1PGi41xT47PG0wUGD38VWQ2EjRFLgqYhXHY8a7tYPMc46PFNl636yPN0ezFGFfanIuf5qrqpel8@WfCBOVAezfnQwcHiqF9/vUxha2jg8rw9kaGmTCcMum6FDhTR1na2Yhh6V1ywKN7OsaJpX2442uWAWtlH8c7QhBlE90FCdqCB9N3K1H6RpbzFlhtpkORagAAMHyWNfOuUJoQnkhjFRAEMfZXtglD2LUfXMdBtQGzBDLSNdmDbofuWm/gI "C (gcc) – Try It Online")
Explanation:
```
f; i; b; o; // Variables
n (char *a)
{
// Calculate a silly hash of incoming string
for (f = i = b = o = 0; *a; o += 21 * b++ + *a++ - 70);
// Use the hash to index into the array of number values
// and calculate the corresponding Fibonacci sequence element
for
(
b = 1,
o = "TACIHAAJQFSAAARCAMGKDANPEAOAAL"[o % 30];
--o > 65;
f = b, b = i
)
i = f + b;
// implicit return
a = i;
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 54 bytes
```
L?>b1+ytbyttbbyxc."axnÛ±r†XVW‹(„WîµÏ£"2+hQ@Q618
```
[Test suite](http://pyth.herokuapp.com/?code=L%3F%3Eb1%2Bytbyttbbyxc.%22axn%10%C3%9B%C2%B1%7Fr%19%0E%C2%86XVW%C2%8B%05%28%C2%84W%C3%AE%C2%B5%C3%8F%07%C2%A3%04%222%2BhQ%40Q618&test_suite=1&test_suite_input=%22primus%22%0A%22secundus%22%0A%22tertius%22%0A%22quartus%22%0A%22quintus%22%0A%22sextus%22%0A%22septimus%22%0A%22octavus%22%0A%22nonus%22%0A%22decimus%22%0A%22undecimus%22%0A%22duodecimus%22%0A%22tertius+decimus%22%0A%22quartus+decimus%22%0A%22quintus+decimus%22%0A%22sextus+decimus%22%0A%22septimus+decimus%22%0A%22duodevicesimus%22%0A%22undevicesimus%22%0A%22vicesimus%22&debug=0)
**Notice:** as the code makes use of some unprintable characters, it may not display correctly on Stack Exchange. The link provided leads to a working and copy-pastable source.
Long story short, `Q[0]+Q[618%len(Q)]` gives unique results for all accepted inputs `Q`.
[Answer]
# [Python 2](https://docs.python.org/2/), 292 bytes
```
f=lambda x:x>1and f(x-1)+f(x-2)or x
def g(t):
for i,c in zip("pr secun ter qua qui sex sep oc no ec".split(),range(1,11))+zip("un duo es ev".split(),(1,2,20,"-")):t=t.replace(i,str(c))
return f(abs(eval("+".join("".join((" ",c)[c in"0123456789-"]for c in t).split()).replace("+-+","-")))-1)
```
[Try it online!](https://tio.run/##VVLbboMwDH0eX2HlKRZpVdilXaXuR6Y9ZCHdMrHAElOx/XxnAm3hIYrOsWOfY6f9pc/Gl@fz8VDr7/dKQ7/vXwrtKzjKflVgPlwlNgH6rLJH@JCE@@zuyIRTBpyHP9dK0QaI1nQeyAb46TQfx0zPp4XGgG/AGrGObe1Iograf1hZqKJAzFMBflp1nBTBnm55nFKqcqPESiDu6UDrYNtaGyudihSkQczugqUueNar36O0J11LkYv1V@O8FNMtBQhl8HUQLDZFef/w@LTdPa/E22Ak2SC8dMVrE5GvcjE2R57FmWykCAd4HQy77y4KBQWqTIpkvkpEmQieA7mE7xPmmQRK@GHCzo/4cSrQj/Bpgi1NDbaJaAzpU8K7hH3jE3pOqLLmImeTCBZzo0aJPN4Zt1AJs8BC7jyw0D0PzA3M@aWTawQ4tL0pOjlj4@XJ7ip@QY8m51S5wbcsG5Y37ERBsLGrKe1x2BH/UF6Qp@G7MsbzPw "Python 2 – Try It Online")
Fibonacci generator shamelessly stolen from [this answer](https://codegolf.stackexchange.com/a/87/73368).
Breaks each word down into its meaningful component parts and discards the rest (in "duodevicesimus", for example, we only care about "duo ev es "-> "2 - 20 " - > abs("2-20") -> 18).
Passes the calculated value (minus 1 to 0-offset) to the Fibonacci generator function.
## Ungolfed Explanation:
```
# Fibonacci function
f=lambda x:x>1and f(x-1)+f(x-2)or x
def g(t):
# generates a list of key, value pairs like [("pr", 1, ..., ("ec", 10)] +
values = zip("pr secun ter qua qui sex sep oc no ec".split(), range(1,11))
# adds values to existing list
values += zip("un duo es ev".split(),(1,2,20,"-"))
# replace the matching values in the string with the appropriate number/sign.
# ORDER MATTERS - if "un" is searched for before "secun", this generates incorrect values.
for i,c in values:
t = t.replace(i,str(c))
# replace each non-digit, non-minus character in string with "c"
t = [(" ",c)[c in"0123456789-"]for c in t]
# convert space-replaced array back to a string
# then split it on spaces, creating an array of values
t = "".join(t).split()
# turn the array back into a string, with each individual item separated by "+"
# this will cause "-" to become "+-+" (since "-" is ALWAYS between two numbers), so prelace that sequence with "-"
t = "+".join(t).replace("+-+","-")
# evaluate the string as an expression, and take the absolute value for when - occurs
t = abs(eval(t))
# pass the value, minus 1 for 0-offset, to the Fibonacci function.
return f(t-1)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~97~~ 79 bytes
```
lambda s:int(1.618**('RV3NJ^[KDP=Z62AWeG<C'.find(chr(hash(s)%69+48)))*.4474+.5)
```
[Try it online!](https://tio.run/##VZFfS8MwFMXf@ynCQJZso6xp1j/iHkRBUBDxQcE6obYpLWzpbNKhn77e3nVbCqHkdw5Jz8nd/5myVrwr1p/dNt195ynR15Uy1HMDL5rN6PT1zX9@/Eqe7l/WHwG/fZcPN3dTt6hUTrOyoWWqS6rZVRDPRcQYm7lChGLurlhnpDaarElCJ/um2rV6siAeWzh0omXWqhwFjoKRjamQfeSfNm0MshgYMiGvhgt@jxgMuDfDD0IU6sykB@QIWdUKKUbKZXaKs0QBwlykY8S8rS1tlJJYxiiubYxy24ZdwNbHTc4OASu8JDpUmdSnI9E5/Eg@lrQlvmQbx4EhKEOSgvaDYaSoG9LvFqSRut0aUilkvXGSJVyDi8NE4NHhHfuywKD5ApReivueANwHxw9DGIcHJ@Mo7HvG8OWrCHzhRd6m@wc "Python 2 – Try It Online")
First, we want to convert from latin to a number `n`; this is accomplished by ~~replicating the input string enough times to ensure that there are at least 11 characters total; and then the `3`rd and `10`th characters (zero indexed) form a unique pair~~ taking the hash mod 69 and turning that into a printable char.
Now we have `n`. To find the `n`th Fibonacci number, we can use the [rounding method](https://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding), using only as many digits of precision as we need up to Fib(20).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~100~~ ~~97~~ ~~95~~ ~~92~~ 91 bytes
```
x=>1.618**(p=parseInt)("1 jgf7 ei 490dbch62385a"[p(x.length+x,32)%12789%24],36)*.4474+.5|0
```
[Try it online!](https://tio.run/##XY7RboMgGIVfhZA0AetIVao2i7vfMzS9YICWxgIDNF7s3d0y6qq7@84H@c@5sZF57pQNL9oIObfNPDVvGSmzOkmQbSxzXr7rgBHMwK1rKwCkAvR0EB/8WuZFfWTwbNFEeqm7cN1PaZHjXZZX9WmX00talDghlFZ0T45fh/mVG@1NL0lvOnSG1qn74GEKoJd80CJykC6oiJ8Dc2FBpcPyefojG5YThgc2RtRGRxCSL88/559BDGaVHoVgpR7FW/U7YK3ikK2Jg8D/slFx6ddbNuIZLuTOLGoxnr8B "JavaScript (Node.js) – Try It Online")
**Warning: WORKS BECAUSE OF FLOATING POINT INACCURACY**
JavaScript has neither a built-in hash function, nor a short enough character-to-ASCII function (`String.charCodeAt` is the shortest already), so I need to define a simple hash function by myself.
Used the same rounding method as Chas Brown did after calculating the hash.
**After a whole day of brute-forcing a better is found:**
`b32_to_dec(x.length + x) % 12789 % 24` (\*floating point inaccuracy)
~~`b32_to_dec(x.length + x) % 353 % 27` (\*floating point inaccuracy)~~
~~`b36_to_dec(x.length + x[2]) % 158 % 29 - 4`~~
~~`b36_to_dec(x[2] + x.length) % 741 % 30`~~
~~`b36_to_dec(x[0] + x[2] + x.length) % 4190 % 27`~~
**`parseInt(x.length + x, 32)` result**
```
primus 7310236636
secundus 9773632960476
tertius 272155724764
quartus 269453490140
quintus 269461747676
sextus 7054
septimus 9774067964892
octavus 266721394652
nonus 192700380
decimus 254959770588
undecimus 350449413217244
duodecimus 36520018280274912 **NOT PRECISE**
tertius decimus 1302947875804
quartus decimus 1300245641180
quintus decimus 1300253898716
sextus decimus 37774
septimus decimus 42759416798172
duodevicesimus 43016381192006637977600 **NOT PRECISE**
undevicesimus 1326703556626028691456 **NOT PRECISE**
vicesimus 351376069188572
```
## Version without exploitation of floating point inaccuracy: 95 bytes
```
x=>1.618**(p=parseInt)("52d7i 6 he 8309jafc 41bg"[p(x.length+x[2],36)%158%29-4],36)*.4474+.5|0
```
[Try it online!](https://tio.run/##XY7BjoMgFEV/hZA0QduSatHaTJz9fIPpggJaGgsMoHEx/@40pbba3bkH8u690p46ZqXxW6W5GOtyHMrvBOdJEcfIlIZaJ36UjxDMUn6QIAfgIkCx3x2vtGaAJOcGVgYNuBWq8Zf1UKWnzT6PVklWrNLjljxSjAk5kDXO/nbjF9PK6VbgVjeogsbKW@fgBkAnWKd4YC@slwF/O2r9hFL56fPwIuOnE5p52gdUWgXggk3P9/PvwDs9S89CMFPP4qV6DJirMGRpwiDwWdZLJtx8y0K8wwnfqEF1FI3/ "JavaScript (Node.js) – Try It Online")
`b36_to_dec(x.length + x[2]) % 158 % 29 - 4`
**Hash Table**
```
Latin word | Length | 3rd | Hash | Decimal | %158 | %29-4
----------------------+--------+-----+------+---------+------+-------
primus | 6 | i | 6i | 234 | 76 | 14
secundus | 8 | c | 8c | 300 | 142 | 22
tertius | 7 | r | 7r | 279 | 121 | 1
quartus | 7 | a | 7a | 262 | 104 | 13
quintus | 7 | i | 7i | 270 | 112 | 21
sextus | 6 | x | 6x | 249 | 91 | 0
septimus | 8 | p | 8p | 313 | 155 | 6
octavus | 7 | t | 7t | 281 | 123 | 3
nonus | 5 | n | 5n | 203 | 45 | 12
decimus | 7 | c | 7c | 264 | 106 | 15
undecimus | 9 | d | 9d | 337 | 21 | 17
duodecimus | 10 | o | 10o | 1320 | 56 | 23
tertius decimus | 15 | r | 15r | 1503 | 81 | 19
quartus decimus | 15 | a | 15a | 1486 | 64 | 2
quintus decimus | 15 | i | 15i | 1494 | 72 | 10
sextus decimus | 14 | x | 14x | 1473 | 51 | 18
septimus decimus | 16 | p | 16p | 1537 | 115 | 24
duodevicesimus | 14 | o | 14o | 1464 | 42 | 9
undevicesimus | 13 | d | 13d | 1417 | 153 | 4
vicesimus | 9 | c | 9c | 336 | 20 | 16
```
] |
[Question]
[
You will be given a 2-D array A of integers, and a length N. Your task is to find within the array the straight line (horizontal, vertical or diagonal) of N elements that yields the highest total sum, and return that sum.
### Example
```
N = 3, A =
3 3 7 9 3
2 2 10 4 1
7 7 2 5 0
2 1 4 1 3
```
This array has 34 valid lines, including
```
Vertical
[3] 3 7 9 3
[2] 2 10 4 1
[7] 7 2 5 0
2 1 4 1 3 [3,2,7] = 12
Horizontal
3 3 7 9 3
2 2 10 4 1
7 7 [2] [5] [0]
2 1 4 1 3 [2,5,0] = 7
Diagonal
3 3 [7] 9 3
2 2 10 [4] 1
7 7 2 5 [0]
2 1 4 1 3 [7,4,0] = 11
```
The maximum line is
```
3 3 7 [9] 3
2 2 [10] 4 1
7 [7] 2 5 0
2 1 4 1 3 [7,10,9] = 26
```
Note: lines may not wrap around the edges of the array.
### Inputs
* A X by Y 2-D array A, with X,Y > 0. Each element of the array contains an integer value which may be positive, zero or negative. You may accept this array in an alternative format (e.g. list of 1-D arrays) if you wish.
* A single, positive integer N, no greater than max(X,Y).
### Output
* A single value representing the maximal line sum that can be found in the array. Note that you do **not** need to provide the individual elements of that line or where it is located.
### Test cases
```
N = 4, A =
-88 4 -26 14 -90
-48 17 -45 -70 85
22 -52 87 -23 22
-20 -68 -51 -61 41
Output = 58
N = 4, A =
9 4 14 7
6 15 1 12
3 10 8 13
16 5 11 2
Output = 34
N = 1, A =
-2
Output = -2
N = 3, A =
1 2 3 4 5
Output = 12
N = 3, A =
-10 -5 4
-3 0 -7
-11 -3 -2
Output = -5
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
,ZṚ¥;ŒD$+⁹\€€FṀ
```
[Try it online!](https://tio.run/##TVAxbgJBDOzvFS7o2BXYtwuHaFH@EC5X0kR8IF2SJ6RMH9HwgWuJ8hD4yDLjW0VIluwdj2fsfT0cj2@lhP11/L78bP@@drP57WN8uX2eEU/X8b38nmzxXErfSN@3QRCyDrJBNYRGpLcgCF0GSUgTBgKCeA6y/OcpsOSpHQi2gaKx64CzEW2FSllt6lRMbCrUYoJWXMNHujw1xSAasxEiw7icWZ00UOOqI0NZubu6cXJjHuH7JN5UJbGBZloiVyXerO6LXK9WbgqeUtUeROP0UH@o/03rX5Onk5vhDg "Jelly – Try It Online")
### How it works
```
,ZṚ¥;ŒD$+⁹\€€FṀ Main link. Left argument: M (matrix). Right argument: n (integer)
ZṚ¥ Zip/transpose and reverse M. This is equivalent to rotating M 90°
counterclockwise.
, Pair M and the result to the right.
;ŒD$ Append the diagonals of both matrices to the pair.
+⁹\€€ Take the sums of length n of each flat array.
FṀ Flatten and take the maximum.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 73 bytes
```
Max[Tr/@Join[#,#,{#,Reverse@#}]&/@Join@@Partition[#2,{#,#},1,1,-∞]]&
```
[Try it online!](https://tio.run/##VY2xCsIwFEV3fyPgdIPNa9rGQcgsCEXcSocgFTNYoUYRSmbd/AM/zh/wE@orDiJvuHDu5byDC/vm4ILfumF3bhfDyl2rTTezy6NvKwHxftzQC6ybS9OdGitiPf2W1pauCz74I@9o3IgIxSdf92ddT4ey822wLK00@l4aAw1JORTHPInopTZQBaTOIIsEJmNGBJkRDGNKQTTOKIHMDXN25wpaxVhPfnY12umfpcwUCCn/zLgaPg "Wolfram Language (Mathematica) – Try It Online")
## How it works
Takes first `N` and then the matrix `A` as input.
`Join@@Partition[#2,{#,#},1,1,-∞]` finds every `N` by `N` submatrix of the matrix `A`, padded with `-∞` where necessary to ensure that lines running out of the grid will be out of the running.
For each of those blocks we compute `Tr/@Join[#,#,{#,Reverse@#}]`: the trace (i.e. sum) of each row, the trace (i.e. sum) of each column, the trace (*actually* the trace, for the first time in the history of Mathematica code golfing) of the block, and the trace of the block reversed. `#` is `Transpose@#`.
Then we find the `Max` of all of these.
[Answer]
# Mathematica, ~~135~~ 123 bytes
```
Max[(s=#;r=#2;Max[Tr/@Partition[#,r,1]&/@Join[s,s~Diagonal~#&/@Range[-(t=Tr[1^#&@@s])+2,t-1]]])&@@@{#|#2,Reverse@#|#2}]&
```
[Try it online!](https://tio.run/##ZY/BasMwEETv/QqBICR0RKyVHTsEgw49FQoh5GZUEMVJDY0DsikF17n22E/tJ7irnBoKErszO3qsTr5/rU@@b178dBClmJ78RzXvSrkJpaRNVPuwtFsf@qZvzm0lEaDdbGkfz01bdeguD40/nlv/dpHs7nx7rCs178t9qPSznFnbucU9oVfaObdgbQf58/31KQm7@r0OXW0li9HNpm1o2l7YQzUMBgY51jAjBgJBJ0ihWeRsEzIk14GOLodGGHf357kqCp4oWkFzWcewSgvoHCrNoPIERRYBBJURCrbJgCjGKIFaFexrrszXDE9v4GuIFILBIh8hhhX3GV8@FLXhJoEouJioNQfinAPELHELU1dP33iaf2h4/@z/v5isMqRxUQPu89gxmtWVZNz0Cw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
µ;Z;Uµ;ŒDðṡ€ẎS€Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8///QVuso61AgeXSSy@END3cufNS05uGuvmAQtbPh////0cY6CkBkrqNgCWTE6ihEG@koAJGhgY6CCZACiZiD5YGCpjoKBlAlhhBpkJ7/xgA "Jelly – Try It Online")
[Answer]
# JavaScript, ~~151~~ 129 bytes
```
a=>n=>a.map((l,x)=>l.map((v,y)=>[...'01235678'].map(d=>m=(g=i=>i--&&g(i)+(a[x+d%3*i-i]||[])[y+i*~-(d/3)])(n)>m?g(n):m)),m=-1/0)|m
```
Curry function takes two arguments, first one is an array of array of numbers, second one is a number.
Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), save 20+ bytes.
```
f=
a=>n=>a.map((l,x)=>l.map((v,y)=>[...'01235678'].map(d=>m=(g=i=>i--&&g(i)+(a[x+d%3*i-i]||[])[y+i*~-(d/3)])(n)>m?g(n):m)),m=-1/0)|m
```
```
<p><label>N = <input id="N" type="number" min="1" value="3" /></label></p>
<p><label>A = <textarea id="A" style="width: 400px; height: 200px;"> 3 3 7 9 3
2 2 10 4 1
7 7 2 5 0
2 1 4 1 3
</textarea></label></p>
<input value="Run" type="button" onclick="O.value=f(A.value.split('\n').filter(x=>x.trim()).map(x=>x.trim().split(/\s+/).map(Number)))(+N.value)" />
<p>Result = <output id="O"></output></p>
```
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), 211 bytes
```
def R:reverse;def U:[range(length)as$j|.[$j][$j:]]|transpose|map(map(select(.))|select(length>=N));def D:U+([R[]|R]|U|map(R)[1:]);[A|.,transpose,D,(map(R)|D)|.[]|range(length-N+1)as$i|.[$i:$i+N]]|max_by(add)|add
```
Expects input in `N` and `A`, e.g:
```
def N: 3;
def A: [
[ 3, 3, 7, 9, 3 ],
[ 2, 2, 10, 4, 1 ],
[ 7, 7, 2, 5, 0 ],
[ 2, 1, 4, 1, 3 ]
];
```
Expanded
```
def chunks: .[] | range(length-N+1) as $i | .[$i:$i+N] ;
def flip: [ reverse[] | reverse ] ;
def upperdiag: [ range(length) as $j | .[$j][$j:] ] | transpose | map(map(select(.))|select(length>=N)) ;
def lowerdiag: flip | upperdiag | map(reverse)[1:] ;
def diag: upperdiag + lowerdiag ;
def allchunks: A | ., transpose, diag, (map(reverse)|diag) | chunks ;
[allchunks]|max_by(add)|add
```
Note this challenge is basically the same as [Project Euler problem 11](https://projecteuler.net/problem=11)
[Try it online!](https://tio.run/##XU5Na4QwEL37K3LwkGCUtbulNLKFBc8eBE8hlLSmu4obrYn9gPz22km2LEvDTOYNb@bN69/XVr2hiqFtEXl0YIhHKDyOttQHeqDoERAS9MrcUR/5hqIdlFsGhiE8e0/R5t9ODswuFFCLRBGO12xWH2o2qvBdw/gs9VHhQemjPRFp4t5lPO4FJBPCWaDNNBrlznLCPo0a1KvFGSHuD152n/YVIUG0ZE2Cec2Fq4VrwmJNeM4EKfjBZfSqSUuKL6wrCZwV7tZMWiW5N9R5Qx2Lu6QCQ2f59fzyjWXbEgffuv6Mk@1GbdY01cswpJ2eFgvNLD/TcbHQ/AI "jq – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~208~~ ~~184~~ ~~183~~ 176 bytes
* Saved 24 bytes by using `-float("inf")` to represent that the checked line reached outside the matrix instead of computing the negative sum of all matrix elements.
* Saved a byte by defining `R,L=range,len` to shorten built-in functions and using `y in R(L(A))...R(L(A[y]))` instead of `y,Y in e(A)...x,_ in e(Y)`.
* Saved seven bytes by golfing `float("inf")` to `9e999`.
```
lambda N,A:max(sum(A[y+q*j][x+p*j]if-1<x+p*j<L(A[y])>-1<y+q*j<L(A)else-9e999for j in R(N))for y in R(L(A))for x in R(L(A[y]))for p,q in[(1,0),(0,1),(1,1),(1,-1)]);R,L=range,len
```
[Try it online!](https://tio.run/##tVFLb4MwDL73V0Q9kTWZcCA8tjKp96qHXhkHpsFG1QKFTmp/PbNN1Wk9bNOmoeDYnx@f7bSnw2tTm6FMHodtvnt6zsVKLe52@dHp33bOIj3N9jebLD3OWryqUsOc1fmSfJl8QIBDCJDFti90XMRxXDad2IiqFmtnJSVZp9GiMLaPF5vqMNSqPYKpA8qVynEVoISz1CAzeb9Wy6TL65dCbYt6yPu@6A6idDwl0hQFnlCJGJUMEaMEHnCV8PEiJGQ/glYJ9xwCo5tyMim@/pJEmGByofWJVkcRV9AmwDKkxFxa@4gD0mkf2XSIbUSWOZFUWxQROQ32bAwnGAzRQUReII06A2oKaW10RRuPbeMfUjJxWx4DuJg3Dk4t8C4g4KEBA8z3c16m9fwPWuBpf5z96w9ptZl8flvgV/N4Zvs/HSAtXNNq2qHGvfn8QIiRzQvXtEpC/rgRmtZO2q6qD2K6asTYQNXUoui6putvp8M7 "Python 2 – Try It Online")
# Explanation
```
lambda N,A: ;R,L=range,len # lambda function, golfed built-ins
max( ) # return the maximum line sum
for y in R(L(A)) # loop through matrix rows
for x in R(L(A[y])) # loop through matrix columns
for p,q in[(1,0),(0,1),(1,1),(1,-1)] # loop through four directions; east, south, south-east, north-east
sum( ) # matrix line sum
for j in R(N) # loop through line indices
if-1<x+p*j<L(A[y])>-1<y+q*j<L(A) # coordinates inside the matrix?
A[y+q*j][x+p*j] # true; look at the matrix element
else-9e999 # false; this line cannot be counted, max(...) will not return this line
```
[Answer]
# [R](https://www.r-project.org/), 199 bytes
```
function(m,n,i=1,j=1){y=1:n-1
x=j-y;x[x<1]=NA
y=i-y;y[y<1]=NA
'if'(i>nrow(m)|j>ncol(m),NA,max(c(v(m[i,x]),v(m[y,j]),v(m[b(y,x)]),v(m[b(y,rev(x))]),f(m,n,i+1,j),f(m,n,i,j+1)), na.rm=T))}
v=sum
b=cbind
```
[Try it online!](https://tio.run/##fVLbTsMwDH3PV0QIiUQkCId2K4Mg8QM88VYmtBUKqZZMKmO0Ar59JHYZ4yL64No5ts@xk3ZT2039HKqVWwbhVVDOgmosyNfewiRoYJ1tdH/Wld05TO3VJeuti3Ff9kN84OoD4S5Cu3wRXr41F6FaLqKnri6Vn3WiEmvhS6e6qVTJ61UzeHPRq07uBO39WnQyndSk5TBq2QaqOQQpFQ@zo9bbaynf2do@PXs2t9XchbuN55Yv3NNKMEY/b9sECMZ5JU4Ujx/ZMdpTOpEKcYMRWjhGP0MLAz7eqaTcHO3xt3rYrRz6x4RgE81PWZXQRbEt0GaE5OifprYRzxCHRKuzRKjHKK7IEecm0eocyQvMMjiiMVRvUrYeFZgF6KOsDEhW9qesYTXZVk8cnPhIYv41HxARLXZYHGk@QQBGX7sC2ogZqNlvbm0Qgt9I7DTJ/10lkWvSlpEqTfdNCI2gSQUh2ny2lIzVy1a4W89d4DBZ3IeH1WN8x5LxarYS8RGWZUSn032vtm6Qau8m7Em2@QA "R – Try It Online")
A recursive solution. For each element (i,j) of the matrix it returns the max between the sum along the row, the sum along the column, the sum along either diagonal, and the result of the function applied to (i+1,j) and (i,j+1).
Results for the test cases are shown in the TIO.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
▲mΣṁX⁰ṁëIT∂(∂↔
```
[Try it online!](https://tio.run/##yygtzv7//9G0TbnnFj/c2RjxqHEDkDq82jPkUUeTBhA/apvy//9/4//R0cY6xjrmOpY6xrE60UY6RjqGBjomOoZAjjlQ2EjHVMcALGEIEgUqigUA "Husk – Try It Online")
Thanks to the new anti∂iagonals builtin this is a quite short answer :)
[Answer]
# JavaScript 170 bytes
still wip on the golf part
added 4 more chars because i didnt managed a case where the max is negative and N is bigger than 1
```
M=-1e9
G=(A,N)=>eval(`for(y in m=M,A)
for(x in R=A[y])
{for(a=b=c=d=j=0;j<N;d+=Y[x-j++])
{a+=R[X=+x+j]
b+=(Y=A[+y+j]||[])[x]
c+=Y[X]}
m=Math.max(m,a||M,b||M,c||M,d||M)}`)
console.log(G([ [3,3,7,9,3],
[2,2,10,4,1],
[7,7,2,5,0],
[2,1,4,1,3]],3)==26)
console.log(G([[-88,4,-26,14,-90],
[-48,17,-45,-70,85],
[22,-52,87,-23,22],
[-20,-68,-51,-61,41]],4)==58)
console.log(G([[9,4,14,7],[6,15,1,12],[3,10,8,13],[16,5,11,2]],4)==34)
console.log(G([[-2]],1)==-2)
console.log(G([[1,2,3,4,5]],3) ==12)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~222~~ 218 bytes
```
n,a=input()
W=len(a[0]);Q=['']*W;R=range;a+=[Q]*n
for l in a:l+=Q
print max(sum(x)for y in[zip(*[(a[j][i+k],a[j+k][i],a[j+k][i+k],a[j+k][i+n+~k])for k in R(n)])for j in R(len(a)-n)for i in R(W)]for x in y if''not in x)
```
[Try it online!](https://tio.run/##TU9Nb4JAEL3zKyZeAJlN2JUvNfwIvXjY7IFY1FVciMUUe@hfpzPQpk0IO/PevDdvuld/aZ0aj@1bXS4Wi9FhVVrXPfsg9A5lU7ug0rEJt7tS@75ZHrb78lG5c72tolLvzNJ5p/YBDVgH1aaJyp3XPazr4V4NwfvzHgwh8y/i9aftgqUmv6vRNroZpIoebf@q/2jkoq@bmeQ3tt8HLpzb69xO4ULhJszO2CE03A3c0dKT77u252YIRzrP8z4utqlBbuqhPgJfPa4QtKYffTnCmgpDiEJQKGOEBEEykE80wSlC/DMhZ5olxkvYRxQFAoFCZUTQu6ZZLRJCZY4iSVHkZFqkhIJSKFKyKYhRtF4pnlUxiqwgRtLLG@SvOYdLkFwhZ3mGMuXtkmUUn9MWKCm@lhnnlKRWJJZTMq6mWyUqXGGCqTHf "Python 2 – Try It Online")
] |
[Question]
[
# Goal
Sort a list of items ensuring that each item is listed after its specified dependencies.
# Input
An array of arrays of integers, where each integer specifies the 0-based or 1-based index of another item that this item must come after. The input may be an array or string or anything else human readable.
For example, a 0-based input:
```
[
[ 2 ], // item 0 comes after item 2
[ 0, 3 ], // item 1 comes after item 0 and 3
[ ], // item 2 comes anywhere
[ 2 ] // item 3 comes after item 2
]
```
Assume there are no circular dependencies, there is always at least one valid order.
# Output
The numbers in order of dependency. An ambiguous order does not have to be deterministic. The output may be an array or text or anything else human readable.
Only one order should be given in the output, even where there are multiple valid orders.
Possible outputs for the above input include:
```
[ 2, 3, 0, 1 ]
[ 2, 0, 3, 1 ]
```
# Scoring
A function or program that completes this in the least number of bytes wins the glory of acceptance. The deadline is in 6 days.
[Answer]
## Pyth, 21 bytes
```
hf.A.e!f>xYTxkTbQ.plQ
```
```
Q input
l length of input array
.p all permutations of [0, 1, ..., lQ-2, lQ-1]
hf find the first permutation for which...
.e Q map over the input array with indices...
f b find all elements in each input subarray where...
>xYT index of dependency is greater than...
xkT index of item
! check whether resulting array is falsy (empty)
.A is the not-found check true for [.A]ll elements?
```
Test:
```
llama@llama:~$ echo '[[2],[0,3],[],[2]]' | pyth -c 'hf.A.e!f>xYTxkTbQ.plQ'
[2, 0, 3, 1]
```
[Answer]
## Python 2, 73 bytes
```
l=input()
f=lambda n:1+sum(map(f,l[n]))
print sorted(range(len(l)),key=f)
```
Sorts the vertices by their descendant count, which `f` computes recursively. If a vertex points to another vertex, its descendants include the pointed vertex and all of that vertex's descendants, so it has strictly more descendants. So, it is placed later than the pointed vertex in the ordering, as desired.
The descendant count of a vertex is one for itself, plus the descendant counts of each of its children. Note that a descendant can be counted multiple times if there are multiple paths leading to it.
It would have also worked to used depth rather than descendant count
```
f=lambda n:1+max(map(f,l[n]))
```
except the `max` would need to give `0` on an empty list.
[Answer]
# Jelly, 8 bytes
```
ịÐL³ŒḊ€Ụ
```
This is based on the (unimplemented) depth approach from [@xnor's Python answer](https://codegolf.stackexchange.com/a/75785).
[Try it online!](http://jelly.tryitonline.net/#code=4buLw5BMwrPFkuG4iuKCrOG7pA&input=&args=W1s1XSwgWzNdLCBbMV0sIFszLCAyXSwgWzddLCBbNSwgNF0sIFtdXQ)
### How it works
```
ịÐL³ŒḊ€Ụ Main link. Input: A (list of dependencies)
ÐL Apply the atom to the left until a loop is reached, updating the left
argument with the last result, and the right argument with the previous
left argument.
ị For each number in the left argument, replace it with the item at that
index in the right argument.
³ Call the loop with left arg. A (implicit) and right arg. A (³).
ŒḊ€ Compute the depth of each resulting, nested list.
Ụ Sort the indices of the list according to their values.
```
[Answer]
# Pyth, 19 bytes
```
hf!s-V@LQT+k._T.plQ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=hf!s-V%40LQT%2Bk._T.plQ&input=[%20%20[%202%20]%2C%20%20[%200%2C%203%20]%2C%20%20[%20]%2C%20%20[%202%20]]&test_suite=1&test_suite_input=[[2]%2C[0%2C3]%2C[]%2C[2]]&debug=0)
### Explanation:
```
hf!s-V@LQT+k._T.plQ implicit: Q = input list
.plQ all permutations of [0, 1, ..., len(Q)-1]
f filter for permutations T, which satisfy:
@LQT apply the permutation T to Q
(this are the dependencies)
._T prefixes of T
+k insert a dummy object at the beginning
(these are the already used elements)
-V vectorized subtraction of these lists
s take all dependencies that survived
! and check if none of them survived
h print the first filtered permutation
```
[Answer]
# Bash + perl, 35 bytes
```
perl -pe's/^$/ /;s/\s/ $. /g'|tsort
```
### Example run
I/O is 1-indexed. Each array goes on a separate line, with whitespace as item separator.
```
$ echo $'4\n1\n\n3\n1 3 2' # [[4], [1], [], [3], [1, 3, 2]]
4
1
3
1 3 2
$ bash tsort <<< $'4\n1\n\n3\n1 3 2'
3
4
1
2
5
```
### How it works
[`tsort`](https://en.wikipedia.org/wiki/Tsort) – which I learned about in [@DigitalTrauma's answer](https://codegolf.stackexchange.com/a/75749) – reads pairs of tokens, separated by whitespace, that indicate a partial ordering, and prints a total ordering (in form of a sorted list of all unique tokens) that extends the aforementioned partial ordering.
All numbers on a specific line are followed by either a space or a linefeed. The `s/\s/ $. /g` part of the Perl command replaces those whitespace characters with a space, the line number, and another space, thus making sure that each **n** on line **k** precedes **k**.
Finally, if the line is empty (i.e., consists only of a linefeed), `s/^$/ /` prepends a space to it. This way, the second substitution turns an empty line **k** into `k k`, making sure that each integer occurs at least once in the string that is piped to `tsort`.
[Answer]
# Bash + coreutils, 20 80
```
nl -v0 -ba|sed -r ':;s/(\S+\s+)(\S+) /\1\2\n\1 /;t;s/^\s*\S+\s*$/& &/'|tsort|tac
```
Input as space-separated lines, e.g.:
```
2
0 3
2
```
* `nl` adds zero-based indices to all lines
* `sed` splits depedency lists into simple dependency pairs, and makes incomplete dependencies dependent on themselves.
* [`tsort`](https://ideone.com/j5mIHF) does the required topological sort
* `tac` puts the output reverse order
[Ideone.](https://ideone.com/j5mIHF)
[Ideone with @Dennis' testcase](https://ideone.com/4014DN)
[Answer]
# Python 2, 143 118 116 bytes
A slightly more *random* approach.
```
from random import*
l=input()
R=range(len(l))
a=R[:]
while any(set(l[a[i]])-set(a[:i])for i in R):shuffle(a)
print a
```
Edits:
* fixed it, and actually saved some bytes too.
* Saved 2 bytes (thanks @Dennis)
] |
[Question]
[
**RTTTL**, or *Ring Tone Text Transfer Language* is a music format that was invented by Nokia ~~in the dawn of time when dinosaurs roamed the land~~. It allows for fairly crude pieces of music (no chords or anything), and the format is pretty simple which is why I think it's pretty cool. Take a look at this one:
```
DejaVu: d=8,o=5,b=200: e, e, c, e, g, 2g4
```
Let's dissect the format. The "DejaVu" part at the beginning is the title -- this cannot be longer than ten characters. The d and o are the default values for duration and octave -- if a note doesn't specify duration or octave, it'll use these. Finally, the b is the beats per minute.
After that, the actual notes of the song are listed. The format of a note is DPO, where D is the duration of the note (1, 2, 4, 8, 16), P is the pitch (A,B,C,D,E,F,G,A#,B#,C#,D#,E#,F#,G#), and O is the octave (4-8 in the Nokia implementation, however it is different for other implementations. For the purposes of the challenge we'll say it is 1-8). If the duration or the octave is not specified, the defaults are used. Additionally, a note can have a dot after it -- this essentially multiplies the duration by 1.5.
In our example here, we have two E notes with no duration and octave, which mean that they have the default duration and octave (8, or eighth-note and octave 5), a C with no duration and octave, an E and a G. The final note is a G note with a duration of 2 (half-note) and an octave of 4.
Now that we've gone over the format, what's the challenge? The challenge actually doesn't have too much to do with RTTTL. Your task is to create an obfuscated program that outputs "Hello, World!" (exactly) that is also **a valid RTTTL song that is at least five seconds long**.
In order to test your RTTTL song, you can use [this site](http://merwin.bespin.org/t4aphp/) to convert your song to a MIDI file, then listen to it in a MIDI player. This is [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"). Good luck!
EDIT: Here's a website for converting MIDIs to RTTTLs if you so desire. [Link](http://midi.mathewvp.com/midi2RTTL.php)
EDIT2: This shiny bounty will be awarded to the winner (most upvoted post) in 7 days.
[Answer]
# Whitespace, 2748 Bytes
(replace `\t` with actual tabs)
```
Hello:d=4, o=5, b=120:2p, 16a2,
16p, 16a2, 16p, 16a3,\t16p, 16a3, 16p,\t16g2, 16p, 16g2, 16p,
16g3,\t16p,\t16g3, 16p, 16a2, 16p, e3,\td3,
16b2, 16c3, 16b2, 16a2,\t8g2,\t16a2, 16p, 16a2,\t16p, 16a3,\t16p,
16a3,\t16p,\t16g2, 16p, 16g2, 16p, 16g3,\t16p, 16g3,
16p, 16a2, 16p, e3,\td3,\t16b2, 16c3,\t16b2,\t16a2, 8g2, 16a2,
16p,\t16a2,\t16p, 16a3, 16p, 16a3, 16p,\t16g2,\t16p,
16g2, 16p, 16g3, 16p,\t16g3,\t16p, 16a2,\t16p,\te3, d3, 16b2,
16c3,\t16b2,\t16a2, 8g2, 16a2, 16p, 16a2,\t16p, 16a3, 16p,
16a3, 16p, 16g2, 16p,\t16g2,\t16p, 16g3,\t16p,\t16g3,\t16p,\t16a2,
16p,\te3,\td3, 16b2, 16c3, 16b2, 16a2,\t8g2, 16a2,\t16p,
16a2, 16p, 16a3, 16p,\t16a3, 16p,\t16g2,\t16p, 16g2, 16p,
16g3,\t16p,\t16g3, 16p, 16a2, 16p, e3,\td3,\t16b2, 16c3,
16b2, 16a2, 8g2, 16a2,\t16p, 16a2, 16p, 16a3, 16p, 16a3,
16p,\t16g2,\t16p, 16g2, 16p, 16g3, 16p,\t16g3,\t16p,\t16a2,
16p, e3, d3, 16b2,\t16c3,\t16b2,\t16a2, 8g2,\ta2,\t8c#3,\t8e3,
g2,\t8b2,\t8d3, a2, 8c#3, 8e3, g2,\t8b2, 8d3, a2, 8c#3,
8e3, g2, 8b2, 8d3,\ta2,\t8c#3, 8e3,\tg2,\t8b2,\t8d3,\ta2,
8c#3,\t8e3,\tg2, 8b2, 8d3, a2, 8c#3,\t8e3, g2, 8b2,\t8d3,
a2, 8c#3, 8e3, g2,\t8b2,\t8d3,\ta2, 8c#3, 8e3,\tg2, 8b2,
8d3,\t16a2,\t16p, 16a2, 16p, 16a3, 16p,\t16a3, 16p,\t16g2, 16p,
16g2, 16p, 16g3, 16p,\t16g3,\t16p, 16a2,\t16p,\te3, d3, 16b2,
16c3,\t16b2,\t16a2, 8g2, 16a2, 16p, 16a2,\t16p, 16a3,\t16p,\t16a3,
16p, 16g2, 16p, 16g2,\t16p,\t16g3, 16p, 16g3,\t16p, 16a2, 16p,
e3,\td3,\t16b2, 16c3, 16b2, 16a2, 8g2,\t16a2,\t16p, 16a2, 16p,
16a3, 16p, 16a3, 16p,\t16g2, 16p, 16g2, 16p, 16g3,\t16p,
16g3,\t16p,\t16a2, 16p, e3, d3, 16b2,\t16c3,\t16b2, 16a2,\t8g2,
16a2, 16p, 16a2, 16p,\t16a3,\t16p, 16a3,\t16p,
16g2,\t16p,\t16g2, 16p, 16g3, 16p, 16g3,\t16p,\t16a2,\t16p, e3,
d3, 16b2, 16c3, 16b2,\t16a2, 8g2,\ta2, 8c#3,
8e3,\tg2,\t8b2, 8d3, a2, 8c#3, 8e3,\tg2,\t8b2,\t8d3,\ta2,
8c#3, 8e3, g2, 8b2, 8d3,
a2,\t8c#3,\t8e3, g2, 8b2, 8d3, a2, 8c#3,
8e3,
g2, 8b2, 8d3, a2, 8c#3,\t8e3,
g2, 8b2,
8d3, a2,\t8c#3,\t8e3,\tg2, 8b2,
8d3, a2,
8c#3,\t8e3, g2, 8b2,\t8d3, 1a3,
1a2,\td3,
8f#3, 8a3, c3, 8e3, 8g3, d3,\t8f#3,
8a3,\tc3, 8e3, 8g3, d3,
8f#3, 8a3,
c3, 8e3, 8g3,\td3,
8f#3,
8a3, c3, 8e3, 8g3,\td3, 8f#3,
8a3,
c3,
8e3,
8g3,d3,8f#3,8a3,c3,8e3,8g3,d3,8f#3,8a3,c3,8e3,8g3,d3,8f#3,8a3,c3,8e3,8g3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,8c3,274p,8b2,274c3,8p,8c#3,8d3,274p,8f3,274p,8d3,8c#3,
```
It's a horrible ringtone version of The Doors with *Hello, I love you*.
[Download converted MIDI](http://merwin.bespin.org/t4aphp/index.php?rtttlstring=Hello%3Ad%3D4%2C+o%3D5%2C+b%3D120%3A2p%2C+16a2%2C%0D%0A16p%2C+16a2%2C+16p%2C+16a3%2C%0916p%2C+16a3%2C+16p%2C%0916g2%2C+16p%2C+16g2%2C+16p%2C%0D%0A16g3%2C%0916p%2C%0916g3%2C+16p%2C+16a2%2C+16p%2C+e3%2C%09d3%2C%0D%0A16b2%2C+16c3%2C+16b2%2C+16a2%2C%098g2%2C%0916a2%2C+16p%2C+16a2%2C%0916p%2C+16a3%2C%0916p%2C%0D%0A16a3%2C%0916p%2C%0916g2%2C+16p%2C+16g2%2C+16p%2C+16g3%2C%0916p%2C+16g3%2C%0D%0A16p%2C+16a2%2C+16p%2C+e3%2C%09d3%2C%0916b2%2C+16c3%2C%0916b2%2C%0916a2%2C+8g2%2C+16a2%2C%0D%0A16p%2C%0916a2%2C%0916p%2C+16a3%2C+16p%2C+16a3%2C+16p%2C%0916g2%2C%0916p%2C%0D%0A16g2%2C+16p%2C+16g3%2C+16p%2C%0916g3%2C%0916p%2C+16a2%2C%0916p%2C%09e3%2C+d3%2C+16b2%2C%0D%0A16c3%2C%0916b2%2C%0916a2%2C+8g2%2C+16a2%2C+16p%2C+16a2%2C%0916p%2C+16a3%2C+16p%2C%0D%0A16a3%2C+16p%2C+16g2%2C+16p%2C%0916g2%2C%0916p%2C+16g3%2C%0916p%2C%0916g3%2C%0916p%2C%0916a2%2C%0D%0A16p%2C%09e3%2C%09d3%2C+16b2%2C+16c3%2C+16b2%2C+16a2%2C%098g2%2C+16a2%2C%0916p%2C%0D%0A16a2%2C+16p%2C+16a3%2C+16p%2C%0916a3%2C+16p%2C%0916g2%2C%0916p%2C+16g2%2C+16p%2C%0D%0A16g3%2C%0916p%2C%0916g3%2C+16p%2C+16a2%2C+16p%2C+e3%2C%09d3%2C%0916b2%2C+16c3%2C%0D%0A16b2%2C+16a2%2C+8g2%2C+16a2%2C%0916p%2C+16a2%2C+16p%2C+16a3%2C+16p%2C+16a3%2C%0D%0A16p%2C%0916g2%2C%0916p%2C+16g2%2C+16p%2C+16g3%2C+16p%2C%0916g3%2C%0916p%2C%0916a2%2C%0D%0A16p%2C+e3%2C+d3%2C+16b2%2C%0916c3%2C%0916b2%2C%0916a2%2C+8g2%2C%09a2%2C%098c%233%2C%098e3%2C%0D%0Ag2%2C%098b2%2C%098d3%2C+a2%2C+8c%233%2C+8e3%2C+g2%2C%098b2%2C+8d3%2C+a2%2C+8c%233%2C%0D%0A8e3%2C+g2%2C+8b2%2C+8d3%2C%09a2%2C%098c%233%2C+8e3%2C%09g2%2C%098b2%2C%098d3%2C%09a2%2C%0D%0A8c%233%2C%098e3%2C%09g2%2C+8b2%2C+8d3%2C+a2%2C+8c%233%2C%098e3%2C+g2%2C+8b2%2C%098d3%2C%0D%0Aa2%2C+8c%233%2C+8e3%2C+g2%2C%098b2%2C%098d3%2C%09a2%2C+8c%233%2C+8e3%2C%09g2%2C+8b2%2C%0D%0A8d3%2C%0916a2%2C%0916p%2C+16a2%2C+16p%2C+16a3%2C+16p%2C%0916a3%2C+16p%2C%0916g2%2C+16p%2C%0D%0A16g2%2C+16p%2C+16g3%2C+16p%2C%0916g3%2C%0916p%2C+16a2%2C%0916p%2C%09e3%2C+d3%2C+16b2%2C%0D%0A16c3%2C%0916b2%2C%0916a2%2C+8g2%2C+16a2%2C+16p%2C+16a2%2C%0916p%2C+16a3%2C%0916p%2C%0916a3%2C%0D%0A16p%2C+16g2%2C+16p%2C+16g2%2C%0916p%2C%0916g3%2C+16p%2C+16g3%2C%0916p%2C+16a2%2C+16p%2C%0D%0Ae3%2C%09d3%2C%0916b2%2C+16c3%2C+16b2%2C+16a2%2C+8g2%2C%0916a2%2C%0916p%2C+16a2%2C+16p%2C%0D%0A16a3%2C+16p%2C+16a3%2C+16p%2C%0916g2%2C+16p%2C+16g2%2C+16p%2C+16g3%2C%0916p%2C%0D%0A16g3%2C%0916p%2C%0916a2%2C+16p%2C+e3%2C+d3%2C+16b2%2C%0916c3%2C%0916b2%2C+16a2%2C%098g2%2C%0D%0A16a2%2C+16p%2C+16a2%2C+16p%2C%0916a3%2C%0916p%2C+16a3%2C%0916p%2C%0D%0A16g2%2C%0916p%2C%0916g2%2C+16p%2C+16g3%2C+16p%2C+16g3%2C%0916p%2C%0916a2%2C%0916p%2C+e3%2C%0D%0Ad3%2C+16b2%2C+16c3%2C+16b2%2C%0916a2%2C+8g2%2C%09a2%2C+8c%233%2C%0D%0A8e3%2C%09g2%2C%098b2%2C+8d3%2C+a2%2C+8c%233%2C+8e3%2C%09g2%2C%098b2%2C%098d3%2C%09a2%2C%0D%0A8c%233%2C+8e3%2C+g2%2C+8b2%2C+8d3%2C%0D%0Aa2%2C%098c%233%2C%098e3%2C+g2%2C+8b2%2C+8d3%2C+a2%2C+8c%233%2C%0D%0A8e3%2C%0D%0Ag2%2C+8b2%2C+8d3%2C+a2%2C+8c%233%2C%098e3%2C%0D%0Ag2%2C+8b2%2C%0D%0A8d3%2C+a2%2C%098c%233%2C%098e3%2C%09g2%2C+8b2%2C%0D%0A8d3%2C+a2%2C%0D%0A8c%233%2C%098e3%2C+g2%2C+8b2%2C%098d3%2C+1a3%2C%0D%0A1a2%2C%09d3%2C%0D%0A8f%233%2C+8a3%2C+c3%2C+8e3%2C+8g3%2C+d3%2C%098f%233%2C%0D%0A8a3%2C%09c3%2C+8e3%2C+8g3%2C+d3%2C%0D%0A8f%233%2C+8a3%2C%0D%0Ac3%2C+8e3%2C+8g3%2C%09d3%2C%0D%0A8f%233%2C%0D%0A8a3%2C+c3%2C+8e3%2C+8g3%2C%09d3%2C+8f%233%2C%0D%0A8a3%2C%0D%0Ac3%2C%0D%0A8e3%2C%0D%0A8g3%2Cd3%2C8f%233%2C8a3%2Cc3%2C8e3%2C8g3%2Cd3%2C8f%233%2C8a3%2Cc3%2C8e3%2C8g3%2Cd3%2C8f%233%2C8a3%2Cc3%2C8e3%2C8g3%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C8c3%2C274p%2C8b2%2C274c3%2C8p%2C8c%233%2C8d3%2C274p%2C8f3%2C274p%2C8d3%2C8c%233%2C&submitbutton=Choose+Conversion+Method)
[Answer]
# H9+, 157,007 bytes
[MIDI!!!!](https://www.dropbox.com/s/ol5txgvgfn53814/anthem.mid?dl=0)
Is too long for the post. So here, have [a pastebin](http://pastebin.com/n2aCyU19). (The pastebin doesn't have proper capitalization, FYI.) I used the following softwares:
* `[.MP3 => .MID](http://www.ofoct.com/audio-converter/convert-wav-or-mp3-ogg-aac-wma-to-midi.html)`
* `[.MID => .RTL](http://midi.mathewvp.com/midi2RTTL.php)`
The song is "Anthem of our Dying Day", by Story of the Year. It is the full, 3.5 minute song. `^-^`.
It starts out with:
```
ANTHEM:d=4,o=5,b=120:172c#,86f#,86a4,172p,16p,43a4,86p,43f#4,172a4,10p,57a4,...
```
`H`, of course, prints `Hello, World!`. And there are no `9`s nor `+`s in the code, I made sure. Good thing this isn't a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
[Answer]
# [123](https://esolangs.org/wiki/123), 816 Bytes
```
H:d=4,o=4,b=400:2a,2b,2a,2b,1a,1b,2a,1b,1a,2b,1a,1b,1a,2b,1a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,2a,1b,1a,1b,1a,2b,1a,1b,1a,2b,1a,1b,2a,1b,1a,2b,2a,2b,2a,2b,2a,2b,2a,1b,1a,2b,1a,1b,2a,1b,1a,3b,3a,1b,2a,1b,1a,2b,1a,3b,1a,2b,1a,2b,1a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,1a,2b,1a,1b,2a,1b,3a,3b,1a,2b,1a,1b,2a,1b,3a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,1a,2b,1a,1b,3a,3b,2a,1b,1a,3b,3a,1b,2a,1b,1a,2b,2a,2b,2a,2b,2a,1b,1a,1b,2a,1b,1a,2b,3a,3b,1a,1b,2a,3b,3a,2b,2a,2b,2a,2b,2a,2b,1a,1b,1a,1b,2a,1b,1a,1b,1a,1b,2a,1b,1a,2b,2a,2b,2a,2b,1a,1b,1a,1b,2a,1b,1a,2b,1a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,2a,1b,1a,1b,1a,1b,2a,1b,1a,2b,1a,1b,2a,1b,1a,2b,2a,2b,2a,2b,2a,2b,1a,1b,1a,1b,1a,2b,1a,1b,2a,1b,1a,2b,1a,1b,2a,2b,2a,2b,2a,1b,3a,3b,1a,2b,1a,1b,2a,1b,3a,1b,2a,2b,2a,2b,2a,2b,2a,2b,1a,1b,2a,1b,1a,1b,3a,3b,2a,1b,1a,3b,3a,1b,2a,1b,1a,2b,1a
```
[Download tune](http://merwin.bespin.org/t4aphp/index.php?rtttlstring=H%3Ad%3D4%2Co%3D4%2Cb%3D400%3A2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C2a%2C1b%2C1a%2C2b%2C1a%2C1b%2C1a%2C2b%2C1a%2C1b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C2a%2C1b%2C1a%2C1b%2C1a%2C2b%2C1a%2C1b%2C1a%2C2b%2C1a%2C1b%2C2a%2C1b%2C1a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C1b%2C1a%2C2b%2C1a%2C1b%2C2a%2C1b%2C1a%2C3b%2C3a%2C1b%2C2a%2C1b%2C1a%2C2b%2C1a%2C3b%2C1a%2C2b%2C1a%2C2b%2C1a%2C1b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C1a%2C2b%2C1a%2C1b%2C2a%2C1b%2C3a%2C3b%2C1a%2C2b%2C1a%2C1b%2C2a%2C1b%2C3a%2C1b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C1a%2C2b%2C1a%2C1b%2C3a%2C3b%2C2a%2C1b%2C1a%2C3b%2C3a%2C1b%2C2a%2C1b%2C1a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C1b%2C1a%2C1b%2C2a%2C1b%2C1a%2C2b%2C3a%2C3b%2C1a%2C1b%2C2a%2C3b%2C3a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C1a%2C1b%2C2a%2C1b%2C1a%2C1b%2C1a%2C1b%2C2a%2C1b%2C1a%2C2b%2C2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C1a%2C1b%2C2a%2C1b%2C1a%2C2b%2C1a%2C1b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C2a%2C1b%2C1a%2C1b%2C1a%2C1b%2C2a%2C1b%2C1a%2C2b%2C1a%2C1b%2C2a%2C1b%2C1a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C1a%2C1b%2C1a%2C2b%2C1a%2C1b%2C2a%2C1b%2C1a%2C2b%2C1a%2C1b%2C2a%2C2b%2C2a%2C2b%2C2a%2C1b%2C3a%2C3b%2C1a%2C2b%2C1a%2C1b%2C2a%2C1b%2C3a%2C1b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C2a%2C2b%2C1a%2C1b%2C2a%2C1b%2C1a%2C1b%2C3a%2C3b%2C2a%2C1b%2C1a%2C3b%2C3a%2C1b%2C2a%2C1b%2C1a%2C2b%2C1a&submitbutton=Choose+Conversion+Method)
This one is just rhythmic beeping, but the language surely has more potential for this challenge, since in 123, all characters except 1, 2 and 3 are ignored. Credits for the original 123 code go to [Martin Büttner](https://codegolf.stackexchange.com/a/55644/43220).
[Answer]
# Python 2.7, 1606 bytes
Okay, so it's not amazingly obfuscated, but it does work. I've [converted](http://merwin.bespin.org/t4aphp/) it to a midi file and it does play.
The tune is *[Still Alive](https://www.youtube.com/watch?v=Y6ljFaKRTrI)* from [Portal](http://store.steampowered.com/app/400/). I got the tune as a midi file from [here](http://sheethost.com/sheet/ikwE8l), which I then [converted](http://midi.mathewvp.com/midi2RTTL.php) into a RTTL. The last few notes are off, but I think that's okay.
```
print[':d=4,o=5,b=120:2p,8g,8f#,8e,8e,2f#,1p,8a4,8g,8f#,8e,e,f#.,d,8e,1a4,8p,8a4,e,8f#,g.,8e,c#,d.,e,8a4,a4,1f#,2p,8g,8f#,8e,8e,2f#,1p,8a4,8g,8f#,8e,e.,8f#,d.,8e,2a4,2p,e,8f#,g.,8e,c#.,8d,e,8a4,8d,8e,8f,8e,8d,8c,p,8a4,8a#4,c,f,8e,8d,8d,8c,8d,8c,c,c,8a4,8a#4,c,f,8g,8f,8e,8d,8d,8e,f,f,8g,8a,8a#,8a#,a,g,8f,8g,8a,8a,g,f,8d,8c,8d,8f,8f,e,8e,8f#,8f#,8a,8d6,8f#6,8d6,8b,8d6,8f#6,8d6,8a,8d6,8f#6,8d6,8b,8d6,8f#6,8d6,8a,8d6,8f#6,8d6,8b,8d6,8f#6,8d6,p.,8a4,8g,8f#,8e,8e.,2f#,1p,8a4,8g,8f#,8e,e.,8f#,d,e,2a4,2p,e,8f#,g.,e,c#,8d,e.,8a4,a4,2f#,2p,8a4,8p,8b,8p,8a,8p,8g,8p,8g,8p,a,1p,8a4,8p,8b,8p,8a,8p,8g,8p,g.,p.,8a,8p,f#.,p.,8g,8p,2d,2p,e,8f#,g.,e,c#,8d,e,8a4,8d,8e,8f,8e,8d,c.,8a4,8a#4,c,f,8e,8d,8d,8c,8d,8c,c,c,8a4,8a#4,c,f,8g,8f,8e,8d,8d,8e,f,f,8g,8a,8a#,8a#,8a,8a,g,8f,8g,8a,8a,8g,8f,f,8d,8c,8d,8f,8f,e,8e,8f#,2f#,1p,8a4,8g,8f#,8e,8e.,2f#,1p,8a4,8g,8f#,8e,e.,8f#,d,e,2a4,2p,e,8f#,g.,e,c#,8d,e.,8a4,a4,2f#,2p,8a4,8p,8b,8p,8a,8p,8g,8p,8g,8p,a,1p,8a4,8p,8b,8p,8a,8p,8g,8p,g.,p.,8a,8p,f#.,p.,8g,8p,2d,2p,e,8f#,g.,e,c#,8d,e,8a4,8d,8e,8f,8e,8d,c.,8a4,8a#4,c,f,8e,8d,8d,8c,8d,8c,c,c,8a4,8a#4,c,f,8g,8f,8e,8d,8d,8e,f,f,8g,8a,8a#,8a#,8a,8a,g,8f,8g,8a,8a,8g,8f,f,8d,8c,8d,8f,8f,e,8e,8f#,8f#,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,2a,8p,8a,8a,512p,8a,512p,8b,512p,8a,512p,8f#,512p,d,p,8g,8p,8a,8p,a.,p.,8g,8a,a.,p.,8g,8f#,2f#',''.join(map(chr,[72,101,108,108,111,44,32,87,111,114,108,100,33]))][1]
```
[Answer]
# Lenguage
```
Hello: d=8,o=4,b=130: a, b, 4e5, a, b, 4e5, g, b, 4e5, g, b, 4e5, f, a, 4e5, f, a, 4e5, g, b, 4e5, f, a, 4e5, a, b, 4e5, a, b, 4e5, g, b, 4e5, g, b, 4e5, f, a, 4e5, f, a, 4e5, g, b, 4e5, f, a, e5, e, 4e, a, 4a., b, 4b., c5, 4c.5, 4d.5, 4c5, 2d5, p, g, b, 4e5, f, a, e5, e, e, 4a, 4a, 4b, 4b, 4c5, 2c5, b, c5, 4b, 2a, p, g, b, 4e5, f, a, e5, e, 4e, a, 4a., b, 4b., c5, 4c.5, 4d.5, 4c5, 2d5, p, g, b, 4e5, f, a, e5, d5, 2e5, a, b, 4e5, g, b, 4e5, g, b, d5, c5, e5, 4d.5, d5, c5, 4e5, a, c#5, 4e5, a, c#5, d5, e5, f5, e5, e5, d5, 2d5, g, b, 4d5, g, b, c5, d5, e5, d5, d5, c5, c5, g, 4a, f, a, 4c5, f, a, a#, c5, 4d.5, 4c.5, c5, a#, 4a, 2g#, f#, g#, 4a, a, 4b, a, 4c5, a, c5, 4e5, a, c5, d5, e5, 4f5, f5, 4f5, e5, 4d5, g, b, 4d5, g, b, c5, d5, 4e5, f5, 4e5, d5, c5, g, 2a, f, a, a#, c5, 4d5, c5, 4c5, 4a#, 4a, 2g#., 2p., p, f#, g#, 2a, a, b, 4e5, g, b, 4e5, g, b, 4e5, f, a, 4e5, f, a, 4e5, g, b, 4e5, f, a, 4e5, 4a, 4c#5, 1e5
```
Followed by many gazillions of spaces so that the total length is 150306725405247424813082671095009555930972306375297366901721134222563463360025683976401363734706798738542991492
[Convert and download](http://merwin.bespin.org/t4aphp/index.php?rtttlstring=Hello%3A+d%3D8%2Co%3D4%2Cb%3D130%3A+a%2C+b%2C+4e5%2C+a%2C+b%2C+4e5%2C+g%2C+b%2C+4e5%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+4e5%2C+f%2C+a%2C+4e5%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+4e5%2C+a%2C+b%2C+4e5%2C+a%2C+b%2C+4e5%2C+g%2C+b%2C+4e5%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+4e5%2C+f%2C+a%2C+4e5%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+e5%2C+e%2C+4e%2C+a%2C+4a.%2C+b%2C+4b.%2C+c5%2C+4c.5%2C+4d.5%2C+4c5%2C+2d5%2C+p%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+e5%2C+e%2C+e%2C+4a%2C+4a%2C+4b%2C+4b%2C+4c5%2C+2c5%2C+b%2C+c5%2C+4b%2C+2a%2C+p%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+e5%2C+e%2C+4e%2C+a%2C+4a.%2C+b%2C+4b.%2C+c5%2C+4c.5%2C+4d.5%2C+4c5%2C+2d5%2C+p%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+e5%2C+d5%2C+2e5%2C+a%2C+b%2C+4e5%2C+g%2C+b%2C+4e5%2C+g%2C+b%2C+d5%2C+c5%2C+e5%2C+4d.5%2C+d5%2C+c5%2C+4e5%2C+a%2C+c%235%2C+4e5%2C+a%2C+c%235%2C+d5%2C+e5%2C+f5%2C+e5%2C+e5%2C+d5%2C+2d5%2C+g%2C+b%2C+4d5%2C+g%2C+b%2C+c5%2C+d5%2C+e5%2C+d5%2C+d5%2C+c5%2C+c5%2C+g%2C+4a%2C+f%2C+a%2C+4c5%2C+f%2C+a%2C+a%23%2C+c5%2C+4d.5%2C+4c.5%2C+c5%2C+a%23%2C+4a%2C+2g%23%2C+f%23%2C+g%23%2C+4a%2C+a%2C+4b%2C+a%2C+4c5%2C+a%2C+c5%2C+4e5%2C+a%2C+c5%2C+d5%2C+e5%2C+4f5%2C+f5%2C+4f5%2C+e5%2C+4d5%2C+g%2C+b%2C+4d5%2C+g%2C+b%2C+c5%2C+d5%2C+4e5%2C+f5%2C+4e5%2C+d5%2C+c5%2C+g%2C+2a%2C+f%2C+a%2C+a%23%2C+c5%2C+4d5%2C+c5%2C+4c5%2C+4a%23%2C+4a%2C+2g%23.%2C+2p.%2C+p%2C+f%23%2C+g%23%2C+2a%2C+a%2C+b%2C+4e5%2C+g%2C+b%2C+4e5%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+4e5%2C+f%2C+a%2C+4e5%2C+g%2C+b%2C+4e5%2C+f%2C+a%2C+4e5%2C+4a%2C+4c%235%2C+1e5&submitbutton=Choose+Conversion+Method) (note: the code is truncated to save bandwidth, but the resulting midi should be the same)
] |
[Question]
[
The task is simply to see how much faster you can calculate n choose n/2 (for even n) than the builtin function in python. Of course for large n this is a rather large number so rather than output the whole number you should output the sum of the digits. For example, for `n = 100000`, the answer is `135702`. For `n=1000000` it is `1354815`.
Here is the python code:
```
from scipy.misc import comb
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n / 10
return r
sum_digits(comb(n,n/2,exact=True))
```
Your score is `(highest n on your machine using your code)/(highest n on your machine using my code)`. Your code must terminate in 60 seconds or less.
Your program must give the correct output for all even n: 2 <= n <= (your highest n)
You can't use any builtin code or libraries which calculate binomial coefficients or values which can quickly be transformed into binomial coefficients.
You can use any language of your choice.
---
**Leading answer** The current leading answer with an amazing 680.09 is by justhalf.
[Answer]
# C++ (GMP) - (287,000,000 / 422,000) = 680.09
Shamelessly combine Kummer's Theorem by xnor and GMP by qwr.
~~Still not even close to the Go solution, not sure why.~~
**Edit:** Thanks Keith Randall for the reminder that multiplication is faster if the number is similar in size. I implemented multi-level multiplication, similar to memory coalescing concept on memory management. And the result is impressive. What used to take 51s, now takes only 0.5s (i.e., 100-fold improvement!!)
```
OLD CODE (n=14,000,000)
Done sieving in 0.343s
Done calculating binom in 51.929s
Done summing in 0.901s
14000000: 18954729
real 0m53.194s
user 0m53.116s
sys 0m0.060s
NEW CODE (n=14,000,000)
Done sieving in 0.343s
Done calculating binom in 0.552s
Done summing in 0.902s
14000000: 18954729
real 0m1.804s
user 0m1.776s
sys 0m0.023s
```
The run for `n=287,000,000`
```
Done sieving in 4.211s
Done calculating binom in 17.934s
Done summing in 37.677s
287000000: 388788354
real 0m59.928s
user 0m58.759s
sys 0m1.116s
```
The code. Compile with `-lgmp -lgmpxx -O3`
```
#include <gmpxx.h>
#include <iostream>
#include <time.h>
#include <cstdio>
const int MAX=287000000;
const int PRIME_COUNT=15700000;
int primes[PRIME_COUNT], factors[PRIME_COUNT], count;
bool sieve[MAX];
int max_idx=0;
void run_sieve(){
sieve[2] = true;
primes[0] = 2;
count = 1;
for(int i=3; i<MAX; i+=2){
sieve[i] = true;
}
for(int i=3; i<17000; i+=2){
if(!sieve[i]) continue;
for(int j = i*i; j<MAX; j+=i){
sieve[j] = false;
}
}
for(int i=3; i<MAX; i+=2){
if(sieve[i]) primes[count++] = i;
}
}
mpz_class sum_digits(mpz_class n){
clock_t t = clock();
char* str = mpz_get_str(NULL, 10, n.get_mpz_t());
int result = 0;
for(int i=0;str[i]>0;i++){
result+=str[i]-48;
}
printf("Done summing in %.3fs\n", ((float)(clock()-t))/CLOCKS_PER_SEC);
return result;
}
mpz_class nc2_fast(const mpz_class &x){
clock_t t = clock();
int prime;
const unsigned int n = mpz_get_ui(x.get_mpz_t());
const unsigned int n2 = n/2;
unsigned int m;
unsigned int digit;
unsigned int carry=0;
unsigned int carries=0;
mpz_class result = 1;
mpz_class prime_prods = 1;
mpz_class tmp;
mpz_class tmp_prods[32], tmp_prime_prods[32];
for(int i=0; i<32; i++){
tmp_prods[i] = (mpz_class)NULL;
tmp_prime_prods[i] = (mpz_class)NULL;
}
for(int i=0; i< count; i++){
prime = primes[i];
carry=0;
carries=0;
if(prime > n) break;
if(prime > n2){
tmp = prime;
for(int j=0; j<32; j++){
if(tmp_prime_prods[j] == NULL){
tmp_prime_prods[j] = tmp;
break;
} else {
mpz_mul(tmp.get_mpz_t(), tmp.get_mpz_t(), tmp_prime_prods[j].get_mpz_t());
tmp_prime_prods[j] = (mpz_class)NULL;
}
}
continue;
}
m=n2;
while(m>0){
digit = m%prime;
carry = (2*digit + carry >= prime) ? 1 : 0;
carries += carry;
m/=prime;
}
if(carries>0){
tmp = 0;
mpz_ui_pow_ui(tmp.get_mpz_t(), prime, carries);
for(int j=0; j<32; j++){
if(tmp_prods[j] == NULL){
tmp_prods[j] = tmp;
break;
} else {
mpz_mul(tmp.get_mpz_t(), tmp.get_mpz_t(), tmp_prods[j].get_mpz_t());
tmp_prods[j] = (mpz_class)NULL;
}
}
}
}
result = 1;
prime_prods = 1;
for(int j=0; j<32; j++){
if(tmp_prods[j] != NULL){
mpz_mul(result.get_mpz_t(), result.get_mpz_t(), tmp_prods[j].get_mpz_t());
}
if(tmp_prime_prods[j] != NULL){
mpz_mul(prime_prods.get_mpz_t(), prime_prods.get_mpz_t(), tmp_prime_prods[j].get_mpz_t());
}
}
mpz_mul(result.get_mpz_t(), result.get_mpz_t(), prime_prods.get_mpz_t());
printf("Done calculating binom in %.3fs\n", ((float)(clock()-t))/CLOCKS_PER_SEC);
return result;
}
int main(int argc, char* argv[]){
const mpz_class n = atoi(argv[1]);
clock_t t = clock();
run_sieve();
printf("Done sieving in %.3fs\n", ((float)(clock()-t))/CLOCKS_PER_SEC);
std::cout << n << ": " << sum_digits(nc2_fast(n)) << std::endl;
return 0;
}
```
[Answer]
## Go, 33.96 = (16300000 / 480000)
```
package main
import "math/big"
const n = 16300000
var (
sieve [n + 1]bool
remaining [n + 1]int
count [n + 1]int
)
func main() {
println("finding primes")
for p := 2; p <= n; p++ {
if sieve[p] {
continue
}
for i := p * p; i <= n; i += p {
sieve[i] = true
}
}
// count net number of times each prime appears in the result.
println("counting factors")
for i := 2; i <= n; i++ {
remaining[i] = i
}
for p := 2; p <= n; p++ {
if sieve[p] {
continue
}
for i := p; i <= n; i += p {
for remaining[i]%p == 0 { // may have multiple factors of p
remaining[i] /= p
// count positive for n!
count[p]++
// count negative twice for ((n/2)!)^2
if i <= n/2 {
count[p] -= 2
}
}
}
}
// ignore all the trailing zeros
count[2] -= count[5]
count[5] = 0
println("listing factors")
var m []uint64
for i := 0; i <= n; i++ {
for count[i] > 0 {
m = append(m, uint64(i))
count[i]--
}
}
println("grouping factors")
m = group(m)
println("multiplying")
x := mul(m)
println("converting to base 10")
d := 0
for _, c := range x.String() {
d += int(c - '0')
}
println("sum of digits:", d)
}
// Return product of elements in a.
func mul(a []uint64) *big.Int {
if len(a) == 1 {
x := big.NewInt(0)
x.SetUint64(a[0])
return x
}
m := len(a) / 2
x := mul(a[:m])
y := mul(a[m:])
x.Mul(x, y) // fast because x and y are about the same length
return x
}
// return a slice whose members have the same product
// as the input slice, but hopefully shorter.
func group(a []uint64) []uint64 {
var g []uint64
r := uint64(1)
b := 1
for _, x := range a {
c := bits(x)
if b+c <= 64 {
r *= x
b += c
} else {
g = append(g, r)
r = x
b = c
}
}
g = append(g, r)
return g
}
// bits returns the number of bits in the representation of x
func bits(x uint64) int {
n := 0
for x != 0 {
n++
x >>= 1
}
return n
}
```
Works by counting all the prime factors in the numerator and denominator and canceling matching factors. Multiplies the leftovers to get the result.
More than 80% of the time is spent in converting to base 10. There's got to be a better way to do that...
[Answer]
## Python 3 (8.8 = 2.2 million / 0.25 million)
This is in Python, which isn't known for speed, so you can probably do better porting this to another language.
Primes generator taken from this [StackOverflow contest](https://stackoverflow.com/a/3035188).
```
import numpy
import time
def primesfrom2to(n):
""" Input n>=6, Returns a array of primes, 2 <= p < n """
sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)
for i in range(1,int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k/3 ::2*k] = False
sieve[k*(k-2*(i&1)+4)/3::2*k] = False
return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]
t0 = time.clock()
N=220*10**4
n=N//2
print("N = %d" % N)
print()
print("Generating primes.")
primes = primesfrom2to(N)
t1 = time.clock()
print ("Time taken: %f" % (t1-t0))
print("Computing product.")
product = 1
for p in primes:
p=int(p)
carries = 0
carry = 0
if p>n:
product*=p
continue
m=n
#Count carries of n+n in base p as per Kummer's Theorem
while m:
digit = m%p
carry = (2*digit + carry >= p)
carries += carry
m//=p
if carries >0:
for _ in range(carries):
product *= p
#print(p,carries,product)
t2 = time.clock()
print ("Time taken: %f" % (t2-t1))
print("Converting number to string.")
# digit_sum = 0
# result=product
# while result:
# digit_sum+=result%10
# result//=10
digit_sum = 0
digit_string = str(product)
t3 = time.clock()
print ("Time taken: %f" % (t3-t2))
print("Summing digits.")
for d in str(digit_string):digit_sum+=int(d)
t4 = time.clock()
print ("Time taken: %f" % (t4-t3))
print ()
print ("Total time: %f" % (t4-t0))
print()
print("Sum of digits = %d" % digit_sum)
```
The main idea of the algorithm is to use [Kummer's Theorem](http://en.wikipedia.org/wiki/Kummer%27s_theorem) to get the prime-factorization of the binomial. For each prime, we learn the highest power of it that divides the answer, and multiply the running product by that power of the prime. In this way, we only need to multiply once for each prime in the prime-factorization of the answer.
**Output showing time breakdown:**
```
N = 2200000
Generating primes.
Time taken: 0.046408
Computing product.
Time taken: 17.931472
Converting number to string.
Time taken: 39.083390
Summing digits.
Time taken: 1.502393
Total time: 58.563664
Sum of digits = 2980107
```
Surprisingly, most of the time is spent converting the number to a string to sum its digits. Also surprisingly, converting to a string was much faster than getting digits from repeated `%10` and `//10`, even though the whole string must presumably be kept in memory.
Generating the primes takes negligible time (and hence I don't feel unfair copying existing code). Summing digits is fast. The actual multiplication takes one third of the time.
Given that digit summing seems to be the limiting factor, perhaps an algorithm to multiply numbers in decimal representation would save time in total by shortcutting the binary/decimal conversion.
[Answer]
## Java (score 22500 / 365000 = 0.062)
I don't have Python on this machine, so if someone could score this I would be grateful. If not, it will have to wait.
The basis of this implementation is
$$\binom{2n}{n} = \sum\_{k=0}^n \binom{n}{k}^2$$
The bottleneck is the addition to compute the relevant section of Pascal's triangle (90% of running time), so using a better multiplication algorithm wouldn't really help.
Note that what the question calls `n` is what I call `2n`. The command-line argument is what the question calls `n`.
```
public class CodeGolf37270 {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java CodeGolf37270 <n>");
System.exit(1);
}
int two_n = Integer.parseInt(args[0]);
// \binom{2n}{n} = \sum_{k=0}^n \binom{n}{k}^2
// Two cases:
// n = 2m: \binom{4m}{2m} = \binom{2m}{m}^2 + 2\sum_{k=0}^{m-1} \binom{2m}{k}^2
// n = 2m+1: \binom{4m+2}{2m+1} = 2\sum_{k=0}^{m} \binom{2m+1}{k}^2
int n = two_n / 2;
BigInt[] nCk = new BigInt[n/2 + 1];
nCk[0] = new BigInt(1);
for (int k = 1; k < nCk.length; k++) nCk[k] = nCk[0];
for (int row = 2; row <= n; row++) {
BigInt tmp = nCk[0];
for (int col = 1; col < row && col < nCk.length; col++) {
BigInt replacement = tmp.add(nCk[col]);
tmp = nCk[col];
nCk[col] = replacement;
}
}
BigInt central = nCk[0]; // 1^2 = 1
int lim = (n & 1) == 1 ? nCk.length : (nCk.length - 1);
for (int k = 1; k < lim; k++) central = central.add(nCk[k].sq());
central = central.add(central);
if ((n & 1) == 0) central = central.add(nCk[nCk.length - 1].sq());
System.out.println(central.digsum());
}
private static class BigInt {
static final int B = 1000000000;
private int[] val;
public BigInt(int x) {
val = new int[] { x };
}
private BigInt(int[] val) {
this.val = val;
}
public BigInt add(BigInt that) {
int[] left, right;
if (val.length < that.val.length) {
left = that.val;
right = val;
}
else {
left = val;
right = that.val;
}
int[] sum = left.clone();
int carry = 0, k = 0;
for (; k < right.length; k++) {
int a = sum[k] + right[k] + carry;
sum[k] = a % B;
carry = a / B;
}
while (carry > 0 && k < sum.length) {
int a = sum[k] + carry;
sum[k] = a % B;
carry = a / B;
k++;
}
if (carry > 0) {
int[] wider = new int[sum.length + 1];
System.arraycopy(sum, 0, wider, 0, sum.length);
wider[sum.length] = carry;
sum = wider;
}
return new BigInt(sum);
}
public BigInt sq() {
int[] rv = new int[2 * val.length];
// Naive multiplication
for (int i = 0; i < val.length; i++) {
for (int j = i; j < val.length; j++) {
int k = i+j;
long c = val[i] * (long)val[j];
if (j > i) c <<= 1;
while (c > 0) {
c += rv[k];
rv[k] = (int)(c % B);
c /= B;
k++;
}
}
}
int len = rv.length;
while (len > 1 && rv[len - 1] == 0) len--;
if (len < rv.length) {
int[] rv2 = new int[len];
System.arraycopy(rv, 0, rv2, 0, len);
rv = rv2;
}
return new BigInt(rv);
}
public long digsum() {
long rv = 0;
for (int i = 0; i < val.length; i++) {
int x = val[i];
while (x > 0) {
rv += x % 10;
x /= 10;
}
}
return rv;
}
}
}
```
[Answer]
# GMP - 1500000 / 300000 = 5.0
Although this answer won't compete against sieves, sometimes short code can still get results.
```
#include <gmpxx.h>
#include <iostream>
mpz_class sum_digits(mpz_class n)
{
char* str = mpz_get_str(NULL, 10, n.get_mpz_t());
int result = 0;
for(int i=0; str[i]>0; i++)
result += str[i] - 48;
return result;
}
mpz_class comb_2(const mpz_class &x)
{
const unsigned int k = mpz_get_ui(x.get_mpz_t()) / 2;
mpz_class result = k + 1;
for(int i=2; i<=k; i++)
{
result *= k + i;
mpz_divexact_ui(result.get_mpz_t(), result.get_mpz_t(), i);
}
return result;
}
int main()
{
const mpz_class n = 1500000;
std::cout << sum_digits(comb_2(n)) << std::endl;
return 0;
}
```
[Answer]
## Java, custom big integer class: 32.9 (120000000 / 365000)
The main class is pretty straightforward:
```
import java.util.*;
public class PPCG37270 {
public static void main(String[] args) {
long start = System.nanoTime();
int n = 12000000;
if (args.length == 1) n = Integer.parseInt(args[0]);
boolean[] sieve = new boolean[n + 1];
int[] remaining = new int[n + 1];
int[] count = new int[n + 1];
for (int p = 2; p <= n; p++) {
if (sieve[p]) continue;
long p2 = p * (long)p;
if (p2 > n) continue;
for (int i = (int)p2; i <= n; i += p) sieve[i] = true;
}
for (int i = 2; i <= n; i++) remaining[i] = i;
for (int p = 2; p <= n; p++) {
if (sieve[p]) continue;
for (int i = p; i <= n; i += p) {
while (remaining[i] % p == 0) {
remaining[i] /= p;
count[p]++;
if (i <= n/2) count[p] -= 2;
}
}
}
count[2] -= count[5];
count[5] = 0;
List<BigInt> partialProd = new ArrayList<BigInt>();
long accum = 1;
for (int i = 2; i <= n; i++) {
for (int j = count[i]; j > 0; j--) {
long tmp = accum * i;
if (tmp < 1000000000L) accum = tmp;
else {
partialProd.add(new BigInt((int)accum));
accum = i;
}
}
}
partialProd.add(new BigInt((int)accum));
System.out.println(prod(partialProd).digsum());
System.out.println((System.nanoTime() - start) / 1000000 + "ms");
}
private static BigInt prod(List<BigInt> vals) {
while (vals.size() > 1) {
int n = vals.size();
List<BigInt> next = new ArrayList<BigInt>();
for (int i = 0; i < n; i += 2) {
if (i == n - 1) next.add(vals.get(i));
else next.add(vals.get(i).mul(vals.get(i+1)));
}
vals = next;
}
return vals.get(0);
}
}
```
It relies on a big integer class which is optimised for multiplication and `toString()`, both of which are significant bottlenecks in an implementation with `java.math.BigInteger`.
```
/**
* A big integer class which is optimised for conversion to decimal.
* For use in simple applications where BigInteger.toString() is a bottleneck.
*/
public class BigInt {
// The base of the representation.
private static final int B = 1000000000;
// The number of decimal digits per digit of the representation.
private static final int LOG10_B = 9;
public static final BigInt ZERO = new BigInt(0);
public static final BigInt ONE = new BigInt(1);
// We use sign-magnitude representation.
private final boolean negative;
// Least significant digit is at val[off]; most significant is at val[off + len - 1]
// Unless len == 1 we guarantee that val[off + len - 1] is non-zero.
private final int[] val;
private final int off;
private final int len;
// Toom-style multiplication parameters from
// Zuras, D. (1994). More on squaring and multiplying large integers. IEEE Transactions on Computers, 43(8), 899-908.
private static final int[][][] Q = new int[][][]{
{},
{},
{{1, -1}},
{{4, 2, 1}, {1, 1, 1}, {1, 2, 4}},
{{8, 4, 2, 1}, {-8, 4, -2, 1}, {1, 1, 1, 1}, {1, -2, 4, -8}, {1, 2, 4, 8}}
};
private static final int[][][] R = new int[][][]{
{},
{},
{{1, -1, 1}},
{{-21, 2, -12, 1, -6}, {7, -1, 10, -1, 7}, {-6, 1, -12, 2, -21}},
{{-180, 6, 2, -80, 1, 3, -180}, {-510, 4, 4, 0, -1, -1, 120}, {1530, -27, -7, 680, -7, -27, 1530}, {120, -1, -1, 0, 4, 4, -510}, {-180, 3, 1, -80, 2, 6, -180}}
};
private static final int[][] S = new int[][]{
{},
{},
{1, 1, 1},
{1, 6, 2, 6, 1},
{1, 180, 120, 360, 120, 180, 1}
};
/**
* Constructs a big version of an integer value.
* @param x The value to represent.
*/
public BigInt(int x) {
this(Integer.toString(x));
}
/**
* Constructs a big version of a long value.
* @param x The value to represent.
*/
public BigInt(long x) {
this(Long.toString(x));
}
/**
* Parses a decimal representation of an integer.
* @param str The value to represent.
*/
public BigInt(String str) {
this(str.charAt(0) == '-', split(str));
}
/**
* Constructs a sign-magnitude representation taking the entire span of the array as the range of interest.
* @param neg Is the value negative?
* @param val The base-B digits, least significant first.
*/
private BigInt(boolean neg, int[] val) {
this(neg, val, 0, val.length);
}
/**
* Constructs a sign-magnitude representation taking a range of an array as the magnitude.
* @param neg Is the value negative?
* @param val The base-B digits, least significant at offset off, most significant at off + val - 1.
* @param off The offset within the array.
* @param len The number of base-B digits.
*/
private BigInt(boolean neg, int[] val, int off, int len) {
// Bounds checks
if (val == null) throw new IllegalArgumentException("val");
if (off < 0 || off >= val.length) throw new IllegalArgumentException("off");
if (len < 1 || off + len > val.length) throw new IllegalArgumentException("len");
this.negative = neg;
this.val = val;
this.off = off;
// Enforce the invariant that this.len is 1 or val[off + len - 1] is non-zero.
while (len > 1 && val[off + len - 1] == 0) len--;
this.len = len;
// Sanity check
for (int i = 0; i < len; i++) {
if (val[off + i] < 0) throw new IllegalArgumentException("val contains negative digits");
}
}
/**
* Splits a string into base-B digits.
* @param str The string to parse.
* @return An array which can be passed to the (boolean, int[]) constructor.
*/
private static int[] split(String str) {
if (str.charAt(0) == '-') str = str.substring(1);
int[] arr = new int[(str.length() + LOG10_B - 1) / LOG10_B];
int i, off;
// Each element of arr represents LOG10_B characters except (probably) the last one.
for (i = 0, off = str.length() - LOG10_B; off > 0; off -= LOG10_B) {
arr[i++] = Integer.parseInt(str.substring(off, off + LOG10_B));
}
arr[i] = Integer.parseInt(str.substring(0, off + LOG10_B));
return arr;
}
public boolean isZero() {
return len == 1 && val[off] == 0;
}
public BigInt negate() {
return new BigInt(!negative, val, off, len);
}
public BigInt add(BigInt that) {
// If the signs differ, then since we use sign-magnitude representation we want to do a subtraction.
boolean isSubtraction = negative ^ that.negative;
BigInt left, right;
if (len < that.len) {
left = that;
right = this;
}
else {
left = this;
right = that;
// For addition I just care about the lengths of the arrays.
// For subtraction I want the largest absolute value on the left.
if (isSubtraction && len == that.len) {
int cmp = compareAbsolute(that);
if (cmp == 0) return ZERO; // Cheap special case
if (cmp < 0) {
left = that;
right = this;
}
}
}
if (right.isZero()) return left;
BigInt result;
if (!isSubtraction) {
int[] sum = new int[left.len + 1];
// A copy here rather than using left.val in the main loops and copying remaining values
// at the end gives a small performance boost, probably due to cache locality.
System.arraycopy(left.val, left.off, sum, 0, left.len);
int carry = 0, k = 0;
for (; k < right.len; k++) {
int a = sum[k] + right.val[right.off + k] + carry;
sum[k] = a % B;
carry = a / B;
}
for (; carry > 0 && k < left.len; k++) {
int a = sum[k] + carry;
sum[k] = a % B;
carry = a / B;
}
sum[left.len] = carry;
result = new BigInt(negative, sum);
}
else {
int[] diff = new int[left.len];
System.arraycopy(left.val, left.off, diff, 0, left.len);
int carry = 0, k = 0;
for (; k < right.len; k++) {
int a = diff[k] - right.val[right.off + k] + carry;
// Why did anyone ever think that rounding positive and negative divisions differently made sense?
if (a < 0) {
diff[k] = a + B;
carry = -1;
}
else {
diff[k] = a % B;
carry = a / B;
}
}
for (; carry != 0 && k < left.len; k++) {
int a = diff[k] + carry;
if (a < 0) {
diff[k] = a + B;
carry = -1;
}
else {
diff[k] = a % B;
carry = a / B;
}
}
result = new BigInt(left.negative, diff, 0, k > left.len ? k : left.len);
}
return result;
}
private int compareAbsolute(BigInt that) {
if (len > that.len) return 1;
if (len < that.len) return -1;
for (int i = len - 1; i >= 0; i--) {
if (val[off + i] > that.val[that.off + i]) return 1;
if (val[off + i] < that.val[that.off + i]) return -1;
}
return 0;
}
public BigInt mul(BigInt that) {
if (isZero() || that.isZero()) return ZERO;
if (len == 1) return that.mulSmall(negative ? -val[off] : val[off]);
if (that.len == 1) return mulSmall(that.negative ? -that.val[that.off] : that.val[that.off]);
int shorter = len < that.len ? len : that.len;
BigInt result;
// Cutoffs have been hand-tuned.
if (shorter > 300) result = mulToom(3, that);
else if (shorter > 28) result = mulToom(2, that);
else result = mulNaive(that);
return result;
}
BigInt mulSmall(int m) {
if (m == 0) return ZERO;
if (m == 1) return this;
if (m == -1) return negate();
// We want to do the magnitude calculation with a positive multiplicand.
boolean neg = negative;
if (m < 0) {
neg = !neg;
m = -m;
}
int[] pr = new int[len + 1];
int carry = 0;
for (int i = 0; i < len; i++) {
long t = val[off + i] * (long)m + carry;
pr[i] = (int)(t % B);
carry = (int)(t / B);
}
pr[len] = carry;
return new BigInt(neg, pr);
}
// NB This truncates.
BigInt divSmall(int d) {
if (d == 0) throw new ArithmeticException();
if (d == 1) return this;
if (d == -1) return negate();
// We want to do the magnitude calculation with a positive divisor.
boolean neg = negative;
if (d < 0) {
neg = !neg;
d = -d;
}
int[] div = new int[len];
int rem = 0;
for (int i = len - 1; i >= 0; i--) {
long t = val[off + i] + rem * (long)B;
div[i] = (int)(t / d);
rem = (int)(t % d);
}
return new BigInt(neg, div);
}
BigInt mulNaive(BigInt that) {
int[] rv = new int[len + that.len];
// Naive multiplication
for (int i = 0; i < len; i++) {
for (int j = 0; j < that.len; j++) {
int k = i + j;
long c = val[off + i] * (long)that.val[that.off + j];
while (c > 0) {
c += rv[k];
rv[k] = (int)(c % B);
c /= B;
k++;
}
}
}
return new BigInt(this.negative ^ that.negative, rv);
}
private BigInt mulToom(int k, BigInt that) {
// We split each number into k parts of m base-B digits each.
// m = ceil(longer / k)
int m = ((len > that.len ? len : that.len) + k - 1) / k;
// Perform the splitting and evaluation steps of Toom-Cook.
BigInt[] f1 = this.toomFwd(k, m);
BigInt[] f2 = that.toomFwd(k, m);
// Pointwise multiplication.
for (int i = 0; i < f1.length; i++) f1[i] = f1[i].mul(f2[i]);
// Inverse (or interpolation) and recomposition.
return toomBk(k, m, f1, negative ^ that.negative, val[off], that.val[that.off]);
}
// Splits a number into k parts of m base-B digits each and does the polynomial evaluation.
private BigInt[] toomFwd(int k, int m) {
// Split.
BigInt[] a = new BigInt[k];
for (int i = 0; i < k; i++) {
int o = i * m;
if (o >= len) a[i] = ZERO;
else {
int l = m;
if (o + l > len) l = len - o;
// Ignore signs for now.
a[i] = new BigInt(false, val, off + o, l);
}
}
// Evaluate
return transform(Q[k], a);
}
private BigInt toomBk(int k, int m, BigInt[] f, boolean neg, int lsd1, int lsd2) {
// Inverse (or interpolation).
BigInt[] b = transform(R[k], f);
// Recomposition: add at suitable offsets, dividing by the normalisation factors
BigInt prod = ZERO;
int[] s = S[k];
for (int i = 0; i < b.length; i++) {
int[] shifted = new int[i * m + b[i].len];
System.arraycopy(b[i].val, b[i].off, shifted, i * m, b[i].len);
prod = prod.add(new BigInt(neg ^ b[i].negative, shifted).divSmall(s[i]));
}
// Handle the remainders.
// In the worst case the absolute value of the sum of the remainders is s.length, so pretty small.
// It should be easy enough to work out whether to go up or down.
int lsd = (int)((lsd1 * (long)lsd2) % B);
int err = lsd - prod.val[prod.off];
if (err > B / 2) err -= B / 2;
if (err < -B / 2) err += B / 2;
return prod.add(new BigInt(err));
}
/**
* Multiplies a matrix of small integers and a vector of big ones.
* The matrix has a implicit leading row [1 0 ... 0] and an implicit trailing row [0 ... 0 1].
* @param m The matrix.
* @param v The vector.
* @return m v
*/
private BigInt[] transform(int[][] m, BigInt[] v) {
BigInt[] b = new BigInt[m.length + 2];
b[0] = v[0];
for (int i = 0; i < m.length; i++) {
BigInt s = ZERO;
for (int j = 0; j < m[i].length; j++) s = s.add(v[j].mulSmall(m[i][j]));
b[i + 1] = s;
}
b[b.length - 1] = v[v.length - 1];
return b;
}
/**
* Sums the digits of this integer.
* @return The sum of the digits of this integer.
*/
public long digsum() {
long rv = 0;
for (int i = 0; i < len; i++) {
int x = val[off + i];
while (x > 0) {
rv += x % 10;
x /= 10;
}
}
return rv;
}
}
```
The big bottleneck is naïve multiplication (60%), followed by the other multiplication (37%) and the sieving (3%). The `digsum()` call is insignificant.
Performance measured with OpenJDK 7 (64 bit).
[Answer]
# Python 2 (PyPy), 1,134,000 / 486,000 = 2.32
```
#/!usr/bin/pypy
n=input(); a, b, c=1, 1, 2**((n+2)/4)
for i in range(n-1, n/2, -2): a*=i
for i in range(2, n/4+1): b*=i
print sum(map(int, str(a*c/b)))
```
### Result: 1,537,506
Fun fact: The bottleneck of your code is adding the digits, not computing the binomial coefficient.
[Answer]
# Java (2,020,000/491,000) = 4.11
**updated, previously 2.24**
Java `BigInteger` isn't the fastest number cruncher, but it's better than nothing.
The basic formula for this seems to be `n! / ((n/2)!^2)`, but that seems like a bunch of redundant multiplication.
You can get a significant speedup by eliminating all prime factors found in both the numerator and denominator. To do this, I first run a simple prime sieve. Then for each prime, I keep a count of what power it needs to be raised to. Increment each time I see a factor in the numerator, decrement for the denominator.
I handle twos separately (and first), since it's easy to count/eliminate them before factoring.
Once that's done, you have the minimum amount of multiplications necessary, which is good because BigInt multiply is *slow*.
```
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class CentBiCo {
public static void main(String[] args) {
int n = 2020000;
long time = System.currentTimeMillis();
sieve(n);
System.out.println(sumDigits(cbc(n)));
System.out.println(System.currentTimeMillis()-time);
}
static boolean[] sieve;
static List<Integer> primes;
static void sieve(int n){
primes = new ArrayList<Integer>((int)(Math.sqrt(n)));
sieve = new boolean[n];
sieve[2]=true;
for(int i=3;i<sieve.length;i+=2)
if(i%2==1)
sieve[i] = true;
for(int i=3;i<sieve.length;i+=2){
if(!sieve[i])
continue;
for(int j=i*2;j<sieve.length;j+=i)
sieve[j] = false;
}
for(int i=2;i<sieve.length;i++)
if(sieve[i])
primes.add(i);
}
static int[] factors;
static void addFactors(int n, int flip){
for(int k=0;primes.get(k)<=n;){
int i = primes.get(k);
if(n%i==0){
factors[i] += flip;
n /= i;
} else {
if(++k == primes.size())
break;
}
}
factors[n]++;
}
static BigInteger cbc(int n){
factors = new int[n+1];
int x = n/2;
for(int i=x%2<1?x+1:x+2;i<n;i+=2)
addFactors(i,1);
factors[2] = x;
for(int i=1;i<=x/2;i++){
int j=i;
while(j%2<1 && factors[2] > 1){
j=j/2;
factors[2]--;
}
addFactors(j,-1);
factors[2]--;
}
BigInteger cbc = BigInteger.ONE;
for(int i=3;i<factors.length;i++){
if(factors[i]>0)
cbc = cbc.multiply(BigInteger.valueOf(i).pow(factors[i]));
}
return cbc.shiftLeft(factors[2]);
}
static long sumDigits(BigInteger in){
long sum = 0;
String str = in.toString();
for(int i=0;i<str.length();i++)
sum += str.charAt(i)-'0';
return sum;
}
}
```
Oh, and the output sum for n=2020000 is `2735298`, for verification purposes.
] |
[Question]
[
With the recent [Python](https://codegolf.stackexchange.com/q/26323/8766) [bashing](https://codegolf.stackexchange.com/q/26371/8766), here's an attempt to show Python's strengths.
Your challenge is to write a program that calculates the factorial of as high a number `n` as possible within 10 seconds.
Your score will be `(highest n for your program on your machine)/(highest n for my program on your machine)`
## Rules
* You must calculate an exact integer solution. Since the factorial would be much higher than what can fit in a 64 bit unsigned integer, you can use strings if your language does not support large integers
* Standard loopholes are forbidden. Particularly, you cannot use any external resources.
* Only the calculation part(this includes time for any workarounds using strings) adds to the total time which should be under 10 seconds on average.
* Single threaded programs only.
* You must store the output in an easily printable form (as printing takes time) (see my program below), string, variable, character array, etc.
EDIT:
* Your program must give the correct output for all `n`: `1 <= n <= (your highest n)`
EDIT2:
* I hate to say this explicitly but using your language's built-in factorial functions falls under the standard loopholes <http://meta.codegolf.stackexchange.com/a/1078/8766>
Sorry Mathematica and Sage
---
## My program
```
from __future__ import print_function
import time
def factorial( n ):
return reduce( ( lambda x , y : x * y ) , xrange( 1 , n + 1 ) , 1 )
start = time.clock()
answer = factorial( 90000 )
end = time.clock()
print ( answer )
print ( "Time:" , end - start , "sec" )
```
---
Highest score wins.
For the record, my code can manage `n = 90000` in about `9.89` seconds on a Pentium 4 3.0 GHz
---
**EDIT:** Can everyone please add the *score* rather than just the highest *n*. Just the highest `n` has no meaning by itself as it depends on your hardware. It's impossible to have an objective winning criterion otherwise. [ali0sha's anwer](https://codegolf.stackexchange.com/a/26695/8766) does this correctly.
---
We have a winner. I didn't accept the java answer <https://codegolf.stackexchange.com/a/26974/8766> as it kind of skirts close to <http://meta.codegolf.stackexchange.com/a/1080/8766>
[Answer]
## C++ with GMP, score = 55.55 (10,000,000 / 180,000)
```
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <queue>
#include <gmpxx.h>
int main(int argc, char *argv[]) {
uint64_t n = atoi(argv[1]);
// Iterate through 1..n. Strip off powers of 2. Multiply
// remainders together into <= 64 bit chunks.
uint64_t twos = 0;
std::vector<uint64_t> terms;
uint64_t m = 1;
for(uint64_t i = 1; i <= n; i++) {
uint64_t j = __builtin_ctzll(i);
twos += j;
uint64_t k = i >> j;
if(__builtin_clzll(m) + __builtin_clzll(k) >= 64) {
m *= k;
} else {
terms.push_back(m);
m = k;
}
}
if(m != 1) terms.push_back(m);
// convert to gmp
// why isn't there a 64-bit constructor?
std::queue<mpz_class> gmpterms;
for(int i = 0; i < terms.size(); i++) {
mpz_class x = (uint32_t)(terms[i] >> 32);
x <<= 32;
x += (uint32_t)terms[i];
gmpterms.push(x);
}
// pop two from the bottom, multiply them, push on the end.
while(gmpterms.size() > 1) {
mpz_class a = gmpterms.front();
gmpterms.pop();
mpz_class b = gmpterms.front();
gmpterms.pop();
gmpterms.push(a * b);
}
mpz_class r = gmpterms.front();
r <<= twos;
//std::cout << r << std::endl;
}
```
[Answer]
# Python 2.7
# 42.575 = ( 6,812,000 / 160,000 ) *approx*
---
### Code:
```
import gmpy2
def fac1(n):
m=lambda(L):([]if len(L)%2==0 else[L.pop()])+map(lambda(l):l[0]*l[1],zip(L[1::2],L[-2::-2]))
L=map(gmpy2.mpz,xrange(1,n+1))
Number = (len(L)-1).bit_length()
while Number:Number-=1;L=m(L)
return L[0]
def fac2(n):
global E; E=0
def f(i):
global E; E+=i//2
return[]if i==1 else f(i//2)+range(3,i,2)+[[1,i][i%2]]
m=lambda(L):([]if len(L)%2==0 else[L.pop()])+map(lambda(l):l[0]*l[1],zip(L[1::2],L[-2::-2]))
L=map(gmpy2.mpz,f(n))
N=(len(L)-1).bit_length()
while N: N-=1;L=m(L)
return L[0]<<E
```
### Test:
```
import time
start = time.time()
baseline(160000)
print time.time()-start
start = time.time()
fac1(6811000)
print time.time()-start
start = time.time()
fac2(6812000)
print time.time()-start
start = time.time()
gmpy2.fac(26000000)
print time.time()-start
```
### Output:
```
10.0069999695
10.0729999542
10.0360000134
9.98699998856
```
### How it works:
Bigger multiplications take more time, thus we want to do as many small multiplications as possible. This is especially true in Python where for numbers less that `2^64` we use hardware arithmetic, and above that we use software. So, in `m(L)`, we start with a list `L`; if it's odd length we remove one number from consideration to make it even again. Then we multiply element `1` with element `-2`, element `3` with `-4`, etc, so that
```
m([1,2,3,4,5,6,7,8]) = [2*7, 4*5, 6*3, 8*1] = [14, 20, 18, 8]
m([10,12,6]) = [360,112]
m([120,6]) = [40320]
```
This approach ensures we're using hardware arithmetic for as long as possible, following which we switch onto the efficient gmc arithmetic library.
In `fac2`, we take a more classic divide and conquer approach as well, where we split out every multiple of 2 and bitshift them at the end for a trivial performance boost. I've included it here because it's usually around 0.5% faster than `fac1`.
### Golfed Version of `fac1` (because I can), 220B
```
import gmpy2
def f(n):
m=lambda(L):([]if len(L)%2==0 else[L.pop()])+map(lambda(l):l[0]*l[1],zip(L[1::2],L[-2::-2]))
L=map(gmpy2.mpz,xrange(1,n+1));N=(len(L)-1).bit_length()
while N:N-=1;L=m(L)
return L[0]
```
[Answer]
# Java - 125.15 (21,400,000 / 171,000)
Also shamelessly copied from [Peter Luschny's Github repo](https://github.com/PeterLuschny/Fast-Factorial-Functions/tree/master/JavaFactorial) (thanks @semi-extrinsic) and licensed under the MIT license, this uses the "prime factorization nested squaring" algorithm as proposed by Albert Schönhage et al. (according to Luschny's [factorial algorithms description page](http://www.luschny.de/math/factorial/description.html)).
I slightly adapted the algorithm to use Java's BigInteger and to not use a lookup table for n < 20.
Compiled with gcj, which uses GMP for its BigInteger implementation, and ran on Linux 3.12.4 (Gentoo), on a Core i7 4700MQ at 2.40GHz
```
import java.math.BigInteger;
public class PrimeSieveFactorialSchoenhage {
private static int[] primeList, multiList;
public static BigInteger factorial(int n) {
int log2n = 31 - Integer.numberOfLeadingZeros(n);
int piN = log2n < 2 ? 1 : 2 + (15 * n) / (8 * (log2n - 1));
primeList = new int[piN];
multiList = new int[piN];
int len = primeFactors(n);
return nestedSquare(len).shiftLeft(n - Integer.bitCount(n));
}
private static BigInteger nestedSquare(int len) {
if (len == 0) {
return BigInteger.ONE;
}
int i = 0, mult = multiList[0];
while (mult > 1) {
if ((mult & 1) == 1) { // is mult odd ?
primeList[len++] = primeList[i];
}
multiList[i++] = mult / 2;
mult = multiList[i];
}
BigInteger ns = nestedSquare(i);
if (len <= i) {
return ns.multiply(ns);
}
return product(primeList, i, len - i).multiply(ns.multiply(ns));
}
private static BigInteger product(int[] a, int start, int length) {
if (length == 0) {
return BigInteger.ONE;
}
int len = (length + 1) / 2;
long[] b = new long[len];
int i, j, k;
for (k = 0, i = start, j = start + length - 1; i < j; i++, k++, j--) {
b[k] = a[i] * (long) a[j];
}
if (i == j) {
b[k++] = a[j];
}
return recProduct(b, 0, k - 1);
}
private static BigInteger recProduct(long[] s, int n, int m) {
if (n > m) {
return BigInteger.ONE;
}
if (n == m) {
return BigInteger.valueOf(s[n]);
}
int k = (n + m) >> 1;
return recProduct(s, n, k).multiply(recProduct(s, k + 1, m));
}
private static int primeFactors(int n) {
int[] primes = new int[n < 17 ? 6 : (int) Math.floor(n / (Math.log(n) - 1.5))];
int numPrimes = makePrimeList(n, primes);
int maxBound = n / 2, count = 0;
int start = indexOf(primes, 2, 0, numPrimes - 1);
int end = indexOf(primes, n, start, numPrimes);
for (int i = start; i < end; i++) {
int prime = primes[i];
int m = prime > maxBound ? 1 : 0;
if (prime <= maxBound) {
int q = n;
while (q >= prime) {
m += q /= prime;
}
}
primeList[count] = prime;
multiList[count++] = m;
}
return count;
}
private static int indexOf(final int[] data, int value, int low, int high) {
while (low < high) {
int mid = (low + high) >>> 1;
if (data[mid] < value) {
low = mid + 1;
} else {
high = mid;
}
}
if (low >= data.length) {
return low;
}
if (data[low] == value) {
low++;
}
return low;
}
private static int makePrimeList(int n, int[] prime) {
boolean[] composite = new boolean[n / 3];
sieveOfEratosthenes(composite);
boolean toggle = false;
int p = 5, i = 0, j = 2;
prime[0] = 2;
prime[1] = 3;
while (p <= n) {
if (!composite[i++]) {
prime[j++] = p;
}
// -- never mind, it's ok.
p += (toggle = !toggle) ? 2 : 4;
}
return j; // number of primes
}
private static void sieveOfEratosthenes(final boolean[] composite) {
int d1 = 8;
int d2 = 8;
int p1 = 3;
int p2 = 7;
int s1 = 7;
int s2 = 3;
int n = 0;
int len = composite.length;
boolean toggle = false;
while (s1 < len) { // -- scan sieve
if (!composite[n++]) { // -- if a prime is found, cancel its multiples
int inc = p1 + p2;
for (int k = s1; k < len; k += inc) {
composite[k] = true;
}
for (int k = s1 + s2; k < len; k += inc) {
composite[k] = true;
}
}
if (toggle = !toggle) { // Never mind, it's ok.
s1 += d2;
d1 += 16;
p1 += 2;
p2 += 2;
s2 = p2;
} else {
s1 += d1;
d2 += 8;
p1 += 2;
p2 += 6;
s2 = p1;
}
}
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
long nanos = System.nanoTime();
BigInteger fact = factorial(n);
nanos = System.nanoTime() - nanos;
// Commented out because it takes ages to print
//System.out.println(fact);
System.out.println(nanos / 1e9);
}
}
```
[Answer]
## Perl + C, n = about 3 million
Here I'm using the [Math::BigInt::GMP](https://metacpan.org/pod/Math%3a%3aBigInt%3a%3aGMP) library available on CPAN, which provides a massive speed boost for Perl's core Math::BigInt objects.
```
use v5.14;
use Time::HiRes 'time';
use Math::BigInt only => 'GMP';
sub factorial { Math::BigInt::->new(@_)->bfac }
my $start = time;
my $answer = factorial( 3_000_000 );
my $end = time;
say $answer;
say "Time: ", $end - $start, " sec";
```
Bear in mind that my computer is probably quite a bit slower than yours. Using your original Python script, I can only calculate `factorial(40000)` in 10 seconds; `factorial(90000)` takes a lot longer. (I hit Ctrl+C after a minute.) On your hardware, using Math::BigInt::GMP, **you** may well be able to calculate the factorial of **5 million or more** in under 10 seconds.
One thing you may notice is that although the factorial is calculated incredibly quickly, printing out the result is very slow, taking about three times longer than the original calculation. This is because GMP internally uses a binary rather than decimal representation, and printing it out requires binary to decimal conversion.
[Answer]
**Python 2.7
5.94 = 1'200'000/202'000**
```
def fast_fac(n):
def prod(start, fin):
if fin - start <= 50:
return reduce(lambda x,y: x*y, xrange(start, fin+1), 1)
else:
mid = (start+fin) / 2
return prod(start, mid) * prod(mid+1, fin)
return prod(1, n)
```
Makes use of relative ease of multiplication of many groups of small numbers and then multiplying them compared to large number of multiplyings involving huge number.
[Answer]
# bc, score=0.19
What the heck, here's my contender for **"How much can you slowly multiply?"**
bc *is* "An arbitrary precision calculator language", but unfortunately rather slow:
```
n=read()
for(f=i=1;i<=n;i++)f*=i
f
quit
```
In about 10 seconds on my mid 2012 MacBook Pro (2.3 GHz Intel Core i7) the reference python answer can calculate 122000!, but this bc script can only calculate 23600!.
Conversely 10000! takes 1.5s with the python reference script, but the bc script takes 50s.
Oh dear.
[Answer]
## Bash: score = 0.001206 (181/150000)
I stole the math functions from [Rosettacode - Long multiplication](http://rosettacode.org/wiki/Long_multiplication#UNIX_Shell)
I didn't analyzed nor tried to optimize.
You are free to change the algorithm or to try a different strings split method.
```
#!/bin/bash
add() { # arbitrary-precision addition
if (( ${#1} < ${#2} )); then
local a="$2" b="$1" sum= carry=0
else
local a="$1" b="$2" sum= carry=0
fi
while (( ${#a} )); do
local -i d1="${a##${a%?}}" d2="10#0${b##${b%?}}" s=carry+d1+d2
sum="${s##${s%?}}$sum"
carry="10#0${s%?}"
a="${a%?}" b="${b%?}"
done
echo "$sum"
}
multiply() { # arbitrary-precision multiplication
if (( ${#1} < ${#2} )); then
local a="$2" b="$1" product=0
else
local a="$1" b="$2" product=0
fi
local zeroes=
while (( ${#b} )); do
local m1="$a"
local m2="${b##${b%?}}"
local partial=$zeroes
local -i carry=0
while (( ${#m1} )); do
local -i d="${m1##${m1%?}}"
m1="${m1%?}"
local -i p=d*m2+carry
partial="${p##${p%?}}$partial"
carry="10#0${p%?}"
done
partial="${carry#0}$partial"
product="$(add "$product" "$partial")"
zeroes=0$zeroes
b="${b%?}"
done
echo "$product"
}
# 'timerun' function
trap 'echo $((i -1)) $f; exit' USR1
(sleep 9.9; kill -USR1 $$)&
declare -i i
f=1
for ((i=1; i< 10000 ; i++ )) # 10000 is verry optimistic
do
f=$(multiply $f $i)
done
```
[Answer]
# C#: 0,48 (77,000 / 160,000)
I'm not happy with this.
Is C# that slow?
But here is my entry anyway.
```
static void Main(string[] args)
{
Console.WriteLine("Enter N for fatorial:");
int n = Convert.ToInt32(Console.ReadLine());
Stopwatch s = Stopwatch.StartNew();
BigInteger result = 1;
while (0 <-- n) result *= n;
s.Stop();
Console.WriteLine("Output: {0} ", result);
Console.WriteLine("Completed in {0}", s.Elapsed);
}
```
When n = 77000 it takes `00:00:09:8708952` to calculate.
I'm running in Release mode, outside Visual Studio, using a Core i3-2330M @2.2GHz.
**Edit:** Since i'm not doing anything intelligent, I accept that result. Maybe the .NET Framework 4.5 is addind some overhead (or BigInteger isn't that fast).
[Answer]
# Python 3, advanced algo by Peter Luschny: 8.25x (1 280 000/155 000)
Shamelessly copied from Peter Luschny,
<http://www.luschny.de/math/factorial/FastFactorialFunctions.htm>,
who provides this code under the "Creative Commons Attribution-ShareAlike 3.0" license.
This is actually a quite advanced algorithm, using something called the "swinging factorial" and a list of primes. I suspect it could be even faster if it did like many of the other answers and performed most of the multiplications with 32 bit integers.
```
#! /usr/bin/python3
import time
import bisect
def Primes(n) :
primes = [2, 3]
lim, tog = n // 3, False
composite = [False for i in range(lim)]
d1 = 8; d2 = 8; p1 = 3; p2 = 7; s = 7; s2 = 3; m = -1
while s < lim : # -- scan the sieve
m += 1 # -- if a prime is found
if not composite[m] : # -- cancel its multiples
inc = p1 + p2
for k in range(s, lim, inc) : composite[k] = True
for k in range(s + s2, lim, inc) : composite[k] = True
tog = not tog
if tog: s += d2; d1 += 16; p1 += 2; p2 += 2; s2 = p2
else: s += d1; d2 += 8; p1 += 2; p2 += 6; s2 = p1
k, p, tog = 0, 5, False
while p <= n :
if not composite[k] : primes.append(p)
k += 1;
tog = not tog
p += 2 if tog else 4
return primes
def isqrt(x):
'''
Writing your own square root function
'''
if x < 0: raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0: return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a + b)
while True:
y = (x + n // x) // 2
if y >= x: return x
x = y
def product(s, n, m):
if n > m: return 1
if n == m: return s[n]
k = (n + m) // 2
return product(s, n, k) * product(s, k + 1, m)
def factorialPS(n):
small_swing = [1,1,1,3,3,15,5,35,35,315,63,693,231,3003,429,6435,6435,
109395,12155,230945,46189,969969,88179,2028117,676039,16900975,
1300075,35102025,5014575,145422675,9694845,300540195,300540195]
def swing(m, primes):
if m < 33: return small_swing[m]
s = bisect.bisect_left(primes, 1 + isqrt(m))
d = bisect.bisect_left(primes, 1 + m // 3)
e = bisect.bisect_left(primes, 1 + m // 2)
g = bisect.bisect_left(primes, 1 + m)
factors = primes[e:g]
factors += filter(lambda x: (m // x) & 1 == 1, primes[s:d])
for prime in primes[1:s]:
p, q = 1, m
while True:
q //= prime
if q == 0: break
if q & 1 == 1:
p *= prime
if p > 1: factors.append(p)
return product(factors, 0, len(factors) - 1)
def odd_factorial(n, primes):
if n < 2: return 1
return (odd_factorial(n // 2, primes)**2) * swing(n, primes)
def eval(n):
if n < 0:
raise ValueError('factorial not defined for negative numbers')
if n == 0: return 1
if n < 20: return product(range(2, n + 1), 0, n-2)
N, bits = n, n
while N != 0:
bits -= N & 1
N >>= 1
primes = Primes(n)
return odd_factorial(n, primes) * 2**bits
return eval(n)
start = time.time()
answer = factorialPS(1280000)
print(time.time()-start)
```
[Answer]
# Java - 10.9
### n = 885000
Mergesort-y.
```
import java.math.BigInteger;
public class Factorials {
public static BigInteger fac;
public static BigInteger two = BigInteger.valueOf(2);
static BigInteger mul(BigInteger start, BigInteger end) {
if(start.equals(end)) {
return start;
} else {
BigInteger mid = start.add(end.subtract(start).divide(Factorials.two));
return Factorials.mul(start, mid).multiply(Factorials.mul(mid.add(BigInteger.ONE), end));
}
}
public static void main(String[] args) {
Factorials.fac = BigInteger.valueOf(Integer.parseInt(args[0]));
long t = System.nanoTime();
BigInteger result = mul(BigInteger.ONE, fac);
t = System.nanoTime() - t;
System.out.print(String.valueOf(((float) t) / 1000000000)); //result.toString()+" @ "+
}
}
```
`BigInteger`s are slow.
### Recommendations for arbitrary-precision high-speed Java integer libraries? :P
[Answer]
# C++ (x86\_64-specific) - 3.0 (390000/130000)
(easily portable to x86-32, porting to other architectures implies a significant speed loss)
Here's my own micro-implementation of long arithmetic.
The calculation itself takes 10 seconds, and while the output is in easily printable form (see the `operator<<` overload), it takes some more time to print it.
```
#include <vector>
#include <iostream>
#include <stdint.h>
#include <ctime>
typedef uint64_t digit;
typedef std::vector<digit> number;
std::ostream &operator<<(std::ostream &s, const number &x)
{
std::vector<char> o;
size_t size = x.size() * 21;
o.resize(size);
size_t lud = 0;
for(number::const_reverse_iterator i = x.rbegin(), end = x.rend(); i != end; i++)
{
digit carry = 0;
int j;
for(j = 0; j <= lud || carry; j++)
{
digit r = o[j] * (1LL << 32) + carry;
o[j] = r % 10;
carry = r / 10;
}
lud = j;
carry = 0;
for(j = 0; j <= lud || carry; j++)
{
digit r = o[j] * (1LL << 32) + carry;
o[j] = r % 10;
carry = r / 10;
}
lud = j;
carry = *i;
for(j = 0; carry; j++)
{
digit r = o[j] + (carry % 10);
carry /= 10;
carry += r / 10;
o[j] = r % 10;
}
if(j > lud)
lud = j;
}
for(int j = lud; j--;)
s.put(o[j] + '0');
return s;
}
inline uint64_t dmul(uint64_t x, uint64_t y, uint64_t &carry)
{
asm("mulq %2" : "+a"(x), "=d"(carry) : "r"(y));
return x;
}
inline digit dadd(digit x, digit y, digit &carry)
{
asm("movq $0, %1; addq %2, %0; adcq %1, %1" : "+r"(x), "=r"(carry), "+r"(y));
return x;
}
void multiply(number &x, digit y)
{
x.resize(x.size() + 2);
digit carry = 0;
for(number::iterator i = x.begin(), end = x.end(); i != end; i++)
{
digit nc, res = dmul(*i, y, nc);
*i = dadd(res, carry, carry);
carry += nc;
}
size_t sz = x.size();
for(number::const_reverse_iterator i = x.rbegin(), end = x.rend(); i != end; i++)
{
if(*i)
break;
sz--;
}
x.resize(sz);
}
int main()
{
const int r = 390000;
clock_t start = clock();
number n;
digit mult = 1;
n.push_back(1);
for(digit a = 2; a <= r; a++)
{
digit carry, m = dmul(mult, a, carry);
if(carry)
{
multiply(n, mult);
mult = a;
}
else
mult = m;
}
multiply(n, mult);
std::cout << "Took: " << (clock() - start)/((double)CLOCKS_PER_SEC) << std::endl;
std::cout << n << std::endl;
}
```
[Answer]
# Python 3, n = 100000
A simple algorithm change was all that was needed to bump the sample code up by 10000.
```
import time
def factorial(n):
result = 1
while n > 0:
result *= n
n = n - 1
return result
start = time.clock()
answer = factorial(100000)
end = time.clock()
print(answer)
print("Time:", end - start, "sec")
```
Obviously not the most creative answer, but there's really only one way to do a factorial....
[Answer]
# Python 3: 280000 / 168000
Time running your program: between `9.87585953253` and `10.3046453994`. Time running my program: about `10.35296977897559`.
```
import time
def factorial(n):
f = 1
while n > 1:
hn = n >> 1
f = f * 2**hn * double_factorial(n) #dfl[hn + (n & 1) - 1]
n = hn
return f
def double_factorial(n):
#dfl = [1]
p = 1
l = 3
mh = n
while l <= n:
p *= l
l += 2
#dfl.append(p)
return p
start = time.clock()
factorial(280000)
end = time.clock()
print(end - start)
```
I read [this answer on cs.SE](https://cs.stackexchange.com/a/14476) and decided to try to implement it in Python. However, I accidentally discovered that `n! = (⌊n / 2⌋)! * 2**(⌊n / 2⌋) * n!!` (note: `!!` is the [double factorial](http://en.wikipedia.org/wiki/Double_factorial)). So I converted that to a non-recursive form.
The comments show my attempt to avoid recomputing the double factorial, but I discovered that storing every value was too memory-costly that it caused my computer to run even slower. I can improve this by only storing what is needed.
Strangely, I implemented the naive straight multiplication in Python 3, and it does better than your program: `n = 169000` in 10 seconds.:
```
def factorial(n):
p=1
for i in range(n):
p*=i+1
return p
```
[Answer]
# Ruby 2.1
# score = 1.80 = 176\_000 / 98\_000
EDIT: improved from ~~1.35 = 132\_000 / 98\_000~~
I took ideas from the [GMP factorial algorithm](https://gmplib.org/manual/Factorial-Algorithm.html). This program uses the standard library to generate prime numbers. Ruby is a bad choice because multiplication seems slower in Ruby than in Python.
1. My program in Ruby 2.1: score = **1.80** = 176\_000 / 98\_000
2. Trivial algorithm in Python 2.7: score = **1** = 98\_000 / 98\_000
3. Trivial algorithm in Ruby 2.1: score = **0.878** = 86\_000 / 98\_000
Yes, my binary of `ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-openbsd]` links against GMP. Ruby 2.1 added a feature to use GMP for large multiplication, but it still seems slower than Python 2.7.
```
require 'benchmark'
require 'optparse'
require 'prime'
def factorial(n)
# calculate primes up to n, drop the 2
@odd_primes = Prime.each(n).drop(1)
# count prime factors of factorial(n)
@factors = Hash.new(0)
factorial_recurse(n)
shift = @factors.delete(2) || 0
@factors.inject(1) {|product, (base, exp)|
product * base**exp
} << shift
end
def factorial_recurse(n)
return if n < 2
# collect prime factors of 2 * 4 * 6 * .. * n
# = (2 * 2 * 2 * .. * 2) * (1 * 2 * 3 * .. * exp)
# = 2**exp * factorial(exp) where exp = floor(n/2)
exp = n >> 1
factorial_recurse(exp)
@factors[2] += exp
# collect prime factors 3 * 5 * 7 * ... * n
for prime in @odd_primes
break if prime > n
exp = 0
# count occurences of prime, prime**2, prime**3, .. n
prime_power = prime
until prime_power > n
# floor(n / prime_power) occurences in 1 * 2 * .. * n,
# but only ceil(count / 2) occurences in 3 * 5 * .. * n
@factors[prime] += (n / prime_power + 1) >> 1
prime_power *= prime
end
end
end
# usage: factorial.rb [-ct] [number]
cflag = tflag = false
OptionParser.new {|opts|
opts.on('-c', 'Check for bugs') { cflag = true }
opts.on('-t', 'Use trivial algorithm') { tflag = true }
opts.parse!
}
$*[1] and fail 'too many arguments'
n = Integer($*[0] || 176_000)
if cflag
factorial(n) == (1..n).reduce(1, :*) or
fail "bad program: factorial(#{n}) is wrong"
puts "ok"
exit
end
# measure processor time to calculate factorial
f = nil
if tflag
time = Benchmark.measure { f = (1..n).reduce(1, :*) }
else
time = Benchmark.measure { f = factorial(n) }
end
puts f
puts "Time #{time.total} sec"
```
[Answer]
# Julia - Score = 15.194
Utilising the exact same approach as that of the reference program... that is,
```
f(n)=reduce(*,1:big(n))
```
So it uses reduce, the basic binary multiplication operation, and a range (in this case, using big(n) to force the calculation to be done in BigInt rather than Int64). From this, I get
```
julia> @time K=f(2340000);
elapsed time: 9.991324093 seconds (814552840 bytes allocated)
```
On my computer, with reference program running with input of 154000, I get `Time: 10.041181 sec` output (run using `python ./test.py`, where test.py is the name of the file containing the reference code)
[Answer]
# tcl, 13757
My answer is to check the limits of tcl.
The first line is only to set an input parameter:
```
set n 13757
```
The others are the algorithm itself:
```
set r 2
for {set i 3} {$i <= $n} {incr i} {set r [expr {$r*$i}]}
puts $r
```
I tested my code on <http://rextester.com/live/WEL36956>; If I make n bigger, I get a SIGKILL; may n can get bigger on a local tcl interpreter, which I do not have.
] |
[Question]
[
Write a brainfuck program of no more than 256 characters that takes as many steps as possible, but does not loop infinitely. The program may not take any input.
More specifically:
* Assume an infinite number of cells to the right.
* A `<` when at the leftmost cell does nothing.
* A `-` when cell value is zero sets cell to `255`.
* The instructions `+-<>.` all count as one step when executed.
* When a `[` or `]` is encountered, it counts as one step. However, if the condition is true and control flow jumps, the corresponding `]` or `[` does **not** again count as a step.
* The solution that takes the most steps wins.
* If there is some kind of pattern in your solution, giving a function for how many steps a similar program of length `n` would take is appreciated but not mandatory.
* To count instructions, you can use [this modified interpreter](https://github.com/Sevis/Python-Brainfuck):
Example:
```
++[-]
```
The encountered instructions are `++[-]-]`, and the program ran for 7 steps.
[Answer]
Here's a 41-character program that eventually halts, leaving more than 10↑(10↑28) contiguous cells set equal to 1 (so the number of instructions executed is very much greater than that):
```
>+>+>+>+[->[>]+[->[>]+[->[>]+[<]+<]+<]+<]
```
If I'm not mistaken, that's a correct translation of the following program in the BF-variant language that uses a single bit for each memory cell (i.e., cell content 0..1 instead of 0..255, so '+' acts to simply flip the bit-value):
```
>+>+>+>+[+>[>]+[+>[>]+[+>[>]+[<]+<]+<]+<]
```
The exact value (the number of adjacent 1-bits) produced by the latter program is
```
3 * (2 ↑ 118842243771396506390315925503 - 1) + 1.
```
---
The above program initializes & computes a function that grows like 2↑↑x (in [Knuth up-arrow notation](http://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation)). Similar conversion of a variant-BF program that initializes & computes a function that grows like 2↑23x provides the following 256-character program:
```
>+>+>+>+>+>+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[->[>]+[<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+<]+
```
which eventually halts, leaving more than 2↑236 adjacent cells set equal to 1 (so the number of steps is enormously more than that).
**NB-1**: 2↑236 is an "inconceivably large" number; e.g., even 2↑46 = 2↑↑↑↑6 already surpasses the first term (3↑↑↑↑3) in the sequence used to compute [Graham's number](http://en.wikipedia.org/wiki/G64#Magnitude_of_Graham.27s_number).
**NB-2**: I think it's likely that 256 characters is enough for a BF program to initialize & compute a function with output *much larger than Graham's number* — if I find time, maybe I'll try to write one.
**NB-3**: In case anyone is interested in the origin of the above programs, here are some [programming resources for "Brainf\*ck F"](https://sites.google.com/site/res0001/f/), with various programs written in Python. ("Brainf\*ck F", or just "F", is what I called a Turing-complete variant of the [Smallf\*ck](http://esolangs.org/wiki/Smallfuck) esolanguage.) I just now uploaded these files, which have been offline for several years, and for now the linked webpage is just a "file cabinet" -- see the file Busy\_Beavers.txt for a detailed discussion relevant to the above programs.
[Answer]
Here is a nice 39 character one:
```
-[>-[>-[-[>+<-]<[>+<-]<[>+<-]>>>]<-]<-]
```
It basically makes a 3 space wide 'sled' that it moves right and decrements by one. Completed in 31,919,535,558 instructions, with the innermost loop executing 256^3 times. I still have plenty of room to extend this pretty far at a rate of 14 characters to another order of magnitude to the run time.
Works on any interpreter with unbounded memory, or with wrapping memory.
I leave it a an exercise to the reader to determine when the improved by 2 loops version will finish:
```
-[>-[>-[>-[>-[-[>+<-]<[>+<-]<[>+<-]<[>+<-]<[>+<-]>>>>>]<-]<-]<-]<-]
```
It has now run overnight, and it is over 3,000,000,000 steps. Still has not gotten through a single iteration of the outer loop. Has barely made it through 15% of the second loop.
[Answer]
This programs works in infinte number of cells.
Two values are initialized in the
begining with ascii values 255.
The first value at the first rotation of main loop is splited to 255 cell and they are initialized with 255 each, at the second rotation of main loop the each value in 255 cells again splits up to 255\*255 cells, in the same way for 255 rotation of main loop the total cells initialized will be 255^255 .
The second value determines how much times the main loop is to be repeated.
```
>->>-[<<[<]>[[[>]>>>[>]-[<]<<<[<]>-]>]>[>>[>]>+<<[<]<-]>>[>]>-]
```
[Answer]
This program is almost same as my previous program , difference is that the value determining the outer loop remains fixed in a particular cell so both number of cells initialized and total steps at the end of the program can be increased
```
->>-<<[>>[>]<[[>>[>]-[<]<-]>>[[<+>-]>]<<[<]<]>>[[<+>-]>]<<[<]<-]
```
cells initialized at the end of program 255^255
```
-[>-[>->>[-]-<<[>>[>]<[[>>[>]-[<]<-]>>[[<+>-]>]<<[<]<]>>[[<+>-]>]<<[<]<-]<-]<-]
```
cells initialized at the end of program 255^255^3
I further modified it to run for even more number of steps.
```
->>>->>-<<<<<[>>>[>]<[[>>[>]<[[>>[>]-[<]<-]>>[[<+>-]>]<<[<]<]>>[[<+>-]>]<<[<]<-]<[>>>[[<+>-]>]<<[<]]<]>>>>[[<<+>>-]>]<-<<[<]<<-]
```
it initializes 255^255 cells during first rotation of main 255^(255^255\*255) cells during second rotation of main loop 255^{255^(255^255\*255)\*255} cells during third rotation of main loop in this way loop repeats 255 times
] |
[Question]
[
Write a function that takes a number as an argument and makes it a palindrome by appending minimum number of digits. The number will be at max of 100 digits.
```
Sample Inputs
12
122
232
2323
1012121
Sample Outputs
121
1221
232
23232
101212101
```
[Answer]
## Perl, 32 chars
```
s/((.)(?1)\2|.?)$/$&.reverse$`/e
```
Needs Perl 5.10 or later for regex features, but no special command-line switch.
Sample use:
```
$ perl -pe 's/((.)(?1)\2|.?)$/$&.reverse$`/e' << EOT
> 12
> 232
> 2323
> 1012121
> EOT
121
232
23232
101212101
```
Uses Perl 5.10's recursive regex extensions to match the longest trailing palindrome as such:
```
m/
( # paren 1 - a palindrome is either:
(.) # paren 2 - a character
(?1) # a palindrome as defined in paren 1
\2 # the same character as in paren 2
| # or:
.? # a 0- or 1-character string
)
$ # at end of string
/x
```
It then replaces it with itself (`$&`) and appends whatever the string started with (`$``), reversed.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) 2, 8 bytes, language postdates challenge
```
ẹ;AcB↔Bc
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9w105rx2SnR21TnJL//zc0MDQCwv9RAA "Brachylog – TIO Nexus") The question asks for a function, so I provided one; the TIO link takes an argument that runs a function like a full program.
## Explanation
```
ẹ;AcB↔Bc
ẹ Split {the input} into digits
;Ac Append {the shortest possible} list
B↔B to produce a palindrome
c then concatenate the resulting list of digits back into a number
```
[Answer]
## J, 50, 32 26 characters!
```
f=:{.@(,"1(-:|.)\.#|.@}:\)
```
eg
```
f '12'
121
f '232'
232
f '2323'
23232
f '1012121'
101212101
```
### How it works (by example)
```
y =: '1012121'
[\.y NB. Sub lists of y
1012121
012121
12121
2121
121
21
1
|.\. y NB> Reverses of sub lists of y
1212101
121210
12121
1212
121
12
1
([\. y) -:"1 (|. \. y) NB. Which of them are equal? (those are palindromes)
NB. ( -:"1 ) checks equality item by item
0 0 1 0 1 0 1
(-: |.)\. y NB. Shortcut of the above
0 0 1 0 1 0 1
(0 0 1 0 1 0 1) # }:\y NB. Choose (#) the palindrome prefixes (\)
10
1012
101212
y, |.'10' NB. Reverse and append the first prefix.
101212101
```
[Answer]
## Python, 88 chars
```
def f(x):
x,y=list(str(x)),[]
while x!=x[::-1]:y+=x.pop(0)
return''.join(y+x+y[::-1])
```
[Answer]
## Python (101 96)
**edit:** Shortened based on @gnibbler's solution
```
def p(n):s=str(n);r=s[::-1];l=len(s);return[int(s+r[l-i:])for i in range(l)if s[i:]==r[:l-i]][0]
```
Original:
```
def p(n):
s=str(n);r=s[::-1];l=len(s)
for i in range(l):
if s[i:]==r[:l-i]:return int(s+r[l-i:])
```
[Answer]
## Python - 98 chars
Based on Hoa's answer :)
```
def p(n):s=str(n);r=s[::-1];l=len(s);return next(int(s+r[l-i:])for i in range(l)if s[i:]==r[:l-i])
```
[Answer]
## Golfscript - 32 chars
```
{`:s-1%:r,,{s<r+..-1%=*}%{}?~}:f
```
[Answer]
## Haskell, 85
Using the same algorithm as most everyone else:
```
import List
r=reverse
f s=s++(r.snd.head.filter g.zip(tails s)$inits s)
g(s,_)=s==r s
```
Examples from problem description:
```
*Main> map (f.show) [12,232,2323,1012121]
["121","232","23232","101212101"]
```
[Answer]
## Ruby 1.9, 72 chars
```
f=->x{x=x.to_s.split'';99.times{|i|x.insert~i,x[i]if x!=x.reverse};x*''}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
f=->x{x=x.to_s.chars;99.times{|i|x.insert~i,x[i]if x!=x.reverse};x*''}
```
[Try it online!](https://tio.run/##KypNqvz/P81W166iusK2Qq8kP75YLzkjsajY2tJSryQzN7W4uiazpkIvM684taikLlOnIjozNjNNoUIRqLootSy1qDi11rpCS1299v9/AA "Ruby – Try It Online")
Based on [YOU'S answer](https://codegolf.stackexchange.com/questions/1144/make-a-number-palindrome/1154#1154), with chars instead of .split'' to gain 2 chars.
And i'm sure there's way to squeeze just a bit more ><
[Answer]
### JavaScript (ES6), ~~145~~ 126 chars
```
p=a=>{S=x=>x.split``.reverse();for(s=String(a),i=0;i<s.length;i++)if(x=s+S(s.substring(0,i)).join``,x==S(x).join``)return x}
```
Commented:
```
function palindrome(n){
s = String(n);
for(i=0;i<s.length;i++)
{
x=s+s.substring(0,i).split("").reverse().join("") //take first n characters, reverse and append to the end
if(x==x.split("").reverse().join("")) //is the number a palindrome?
return x;
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ 7 bytes
*-18 bytes thanks to [@Razetime](https://codegolf.stackexchange.com/users/80214/razetime).*
```
ηí«.ΔÂQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3PbDaw@t1js35XBT4P//hgaGRkAIAA "05AB1E – Try It Online")
```
ηí«.ΔÂQ # full program
.Δ # find first element in...
« # joined...
í # reversed...
η # prefixes of...
# implicit input...
.Δ # where...
Q # it's equal to...
 # itself reversed
# implicit output
```
[Answer]
# Java, 174 bytes
```
x->{Function<String,String>r=t->new StringBuilder(t).reverse().toString();String y=r.apply(x),z=x;int m=x.length();while(!z.equals(r.apply(z)))z=x+y.substring(--m);return z;}
```
Ungolfed:
```
x -> {
Function<String, String> r = t -> new StringBuilder(t).reverse().toString();
String y = r.apply(x), z=x;
int m = x.length();
while (!z.equals(r.apply(z))) z = x+y.substring(--m);
return z;
}
```
I have a feeling it could be a lot tighter but it's not immediately obvious to me how. The Function eats up a lot of space but I needed it in two places.
This works for any string, not just numbers, and it can be any length.
[Answer]
# PHP, 64 Bytes
```
for(;strrev($p=$argn.strrev(substr($argn,0,$i++)))!=$p;);echo$p;
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTQwNDI0sv6fll@kYV1cUlSUWqahUmALltSD8otLk4AsDbCYjoGOSqa2tqampqKtSoG1pnVqckY@kPH/PwA "PHP – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
D;ⱮUƤ$ŒḂƇḢḌ
```
[Try it online!](https://tio.run/##y0rNyan8/9/F@tHGdaHHlqgcnfRwR9Ox9oc7Fj3c0fP/cPujpjX//xsa6SgYGgEJI2MIYQzkGxgaASEA "Jelly – Try It Online")
## How it works
```
D;ⱮUƤ$ŒḂƇḢḌ - Main link. Takes n on the left
D - Digits of n
$ - To the digits of n:
Ƥ - Yield the prefixes
U - Reverse
;Ɱ - Concatenate with the digits
ŒḂƇ - Keep the palindromes
Ḣ - Take the first (i.e. the shortest)
Ḍ - Convert from digits
```
] |
[Question]
[
*The absolute value of a number \$x\$ is normally written as \$|x|\$. The left and right side of the absolute value uses the same symbol, so it is not immediately obvious how to parse nested absolute values e.g. \$||1-2|+|3-|4-5|||\$*
Your goal is to parse such an expression containing nested absolute values:
The expression will be given as a string of characters.
For simplicity the expression will only contain single-digit numbers (or letters if that is easier in your language),
the operators `+` and `-` (you can use any two distinct characters to represent these operations), and the symbol `|` for the left and right side of an absolute value.
You do *not* need to handle the case where a number is directly adjacent to an absolute value (e.g. `2|3|` or `|2|3`)
Your output should be the same expression in a form that allows you to determine how the absolute values are bracketed.
The output has to satisfy the following rules:
* The expression within an absolute value must not end with an operator ( `+` or `-` )
* The expression within an absolute value cannot be empty
* Each `|` has to be part of exactly one absolute value
You may assume there is a valid way to parse the given input.
Examples:
```
|2| -> (2)
|2|+|3| -> (2)+(3)
||2|| -> ((2))
||2|-|3|| -> ((2)-(3))
|-|-2+3|| -> (-(-2+3))
|-|-2+3|+|4|-5| -> (-(-2+3)+(4)-5)
|-|-2+|-3|+4|-5| -> (-(-2+(-3)+4)-5)
||1-2|+|3-|4-5||| -> ((1-2)+(3-(4-5)))
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution wins.
# Optional additional requirement:
Also support expressions that allow a number direct before or after a bracket.
If the result is not unique, you may return any valid solution.
test-cases (for optional requirement):
```
|2|3|4| -> (2(3)4)
|2|3|4| -> (2)3(4)
||3|4| -> ((3)4)
|2|3-|4| -> (2)3-(4)
|1+|2|3| -> (1+(2)3)
|1+2|3|| -> (1+2(3))
```
[Answer]
# JavaScript (ES6), 52 bytes
```
f=s=>s>(s=s.replace(/\|(.*?[\d)])\|/,"($1)"))?f(s):s
```
[Try it online!](https://tio.run/##ddBLDoJADIDhvacgxEXrWAivjQlwEHFBeBgNAcIYV707FqMCArPt/zUzc0@fqc66W/ugusmLvi9DHUY6Ah1qqyvaKs0KsBMG6xCfkxwvmLB9NGHvoIkYl6DxpPusqXVTFVbVXKEEk102jdlBNGzbMMDF3bJV7E37sVXgLXsB8@3fXsBqTbJ@FJOaZP1SEJOr1gTBMNgWin2mYHB/QoGPFGw4JpEfOHNAItchO/T@NWJfnFz19ygZDL9GIANE7F8 "JavaScript (Node.js) – Try It Online")
### Method
At each iteration, we look for the first substring consisting of:
* `\|` a leading pipe
* `.*?` the shortest possible string
* `[\d)]` either a digit or a closing parenthesis
* `\|` a trailing pipe
and replace the pipes with `(` and `)` respectively.
If a replacement occurs, the new string is *less than* the original string in lexicographical order, because the leading pipe is turned into an opening parenthesis. Hence the test `s > (s = s.replace(...))` which triggers a recursive call if true.
**NB**: A safer way would be to use `[^|]*` instead of `.*?`. If you find a test case where `.*?` fails, please let me know.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~22~~ 16 bytes
```
T`|`)`\d\|+
\|
(
```
[Try it online!](https://tio.run/##bY@xDsIwDET3fEVGW9ENtOnKVzBmSCUYWBgQ4/17uFAqUFuP997J9vP2uj/m1i6V1Wu5FqZQGKw1DoybwTlGGzwIJY48QMlGYXEeNMUXCJW5h1BZAogh7QVYj/@ExExM3ArJsmNaNULi6v00g8SvxxM@/4BZWt@7HKS4/wNT7O5v "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`|`)`\d\|+
```
Replace all `|`s that appear after digits with `)`s.
```
\|
(
```
Replace the remaining `|`s with `(`s.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~27~~ 22 bytes
Based on Arnauld's answer, but without regex.
```
{`c$(84-0=\"0|"'x)!'x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pOSFbRsDDRNbCNUTKoUVKv0FRUr6jl4kpTqjGqUYJQ2jXGyEztGhMIF8iHM3SBEhCObo2ukTYaB6RF1xRJqEYXKIgQqzHUBZutW2MCFALqBQD/sCu7)
Any closing parenthesis in the output directly follows a digit or another closing parenthesis, and none of the opening ones do. This means we can replace all consecutive `|`'s following a digit by closing parentheses. The remaining `|`'s are replaced by opening ones.
---
# [K (ngn/k)](https://codeberg.org/ngn/k), 36 bytes
My first idea, tests all ways of replacing `|` with parentheses using try/eval.
```
{c@*<.[.:;;`]','c:+`c$(83+!2&x)!''x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pOdtCy0YvWs7K2TohV11FPttJOSFbRsDDWVjRSq9BUVFevqOXiSlOqMapRglDaNcbITO0aEwgXyIczdIESEI5uja6RNhoHpEXXFEmoRhcoiBCrMdQFm61bYwIUAuoFAAolLuc=)
It is not very easy to show this is correct, as `(1+)` is a valid expression in K. However after toying around with this for quite some time, I'm convinced that you can't construct a valid input where this actually becomes a problem
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
FS≡ι|§)(‹ψ0«ι≔ιψ
```
[Try it online!](https://tio.run/##JYvLCoMwEEXX@hVDVjPUQJ8bu3IpdFHoF4QYNSCxJLGtdPz2NNDlPedcPSqvZzWl1M8esHXPJT6it25AIghvG/UIaAm@pVbBgGBRwz37iE1sXWc@KAhFBTcTAq4ViL0gomvZmV4tU6zzsfj3NtOiCcEODm0Fa55buaXEfJBH3vFJ8llemDnJ1/QD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FS≡ι
```
Loop over the input characters.
```
|§)(‹ψ0
```
If the current characters is a `|` then output a `)` or `(` depending on whether the last non-`|` was less than `0`.
```
«ι≔ιψ
```
Otherwise output the character and save it as the last non-`|`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 44 bytes
```
s=>s.replace(d=/./g,c=>c>{}?++d?')':'(':d=c)
```
[Try it online!](https://tio.run/##ddBLDoJADIDhvacgbmgzFiKPDcnAWcjwiIYAAePGenYsRgUEZtv/a2bmmt7T3nSX9kZ1k@VDoYdex73T5W2Vmhwy7TpueTI6NvHjmSiVJTbakQ12lGmDg2nqvqlyp2pKKODIHh@txUG0XNeywMPDulXsz/upVeCvewHL7d9ewGZNsn4Ss5pk/VoQk6e2BME42BeKA6ZwdH9CQYAU7jgmkR@4cEAityGf6f1rxIE4uervUTIYf41ABog4vAA "JavaScript (Node.js) – Try It Online")
Look last non-pipe character before each pipe. Converting pipe to `)` only when last non-pipe is a digit, and converting to `(` otherwise. Does not work with the optional additional requirement.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ε'|Qižu®dèëy©
```
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/267303/52210), so make sure to upvote that answer as well!
Outputs as a list of characters.
[Try it online](https://tio.run/##AS4A0f9vc2FiaWX//861J3xRacW@dcKuZMOow6t5wqn//3x8MS0yfCt8My18NC01fHx8) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaWhxqGVMf/PbVWvCcw8uq/00LqUwysOr648tPJ/ba2LvZeSgpXC4f1KOv@jlWqMapR0QKR2jTGYBWTCaF2gEJitW6NrpI3K1q4xqdE1RYjU6ALF4EI1hrpgE3VrTIAiQI2x/3V18/J1cxKrKgE).
**Explanation:**
```
ε # Map over the characters of the (implicit) input:
'|Qi '# If the current character is a "|":
žu # Push builtin string "()<>[]{}"
® # Push variable `®` (which is -1 by default)
d # Check whether it's a non-negative (>=0) number
è # Use that check (0 or 1) to (0-based) index into string "()<>[]{}"
ë # Else:
y # Simply push the current character
© # And store it in variable `®` (without popping)
# (after which the mapped list of characters is output implicitly as result)
```
] |
[Question]
[
*Inspired by this Puzzling SE question: [All distances different on a chess board](https://puzzling.stackexchange.com/q/112705/25128).*
## Introduction
Lets define a sequence \$a(n), n\geqslant 1\$ as how many pawns can you put on a \$n \times n\$ chessboard in such a way that all the distances between two pawns are different.
* Pawns are placed always in the centre of the square.
* The distance is simple [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance).
## Example
\$a(4)=4\$:
```
1100
0000
0010
0001
```
## Challenge
This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge and the [default rules](https://codegolf.stackexchange.com/tags/sequence/info) apply.
This is also [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code per language wins!
## Test cases
First `9` terms:
`1,2,3,4,5,6,7,7,8`.
Some more: [A271490](https://oeis.org/A271490).
## Trivia/hints
* \$a(n) \leqslant n\$
* \$a(n)\$ is weakly increasing, ie. \$a(n) \leqslant a(n+1)\$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
Very inefficient, \$n=4\$ is just on the edge of timing out on TIO.
```
Œc_/€²§QƑ
pµŒPÇƇṪL
```
[Try it online!](https://tio.run/##ATQAy/9qZWxsef//xZJjXy/igqzCssKnUcaRCnDCtcWSUMOHxofhuapM/8OH4oKs//8xLCAyLCAz "Jelly – Try It Online")
**Commented**:
```
Œc_/€²§QƑ -- helper function; verify a set of pawn coordinates is valid
Œc -- unordered pairs of coordinates
_/€ -- reduce each pair by subtraction
² -- square all values
§ -- sum to get the squared euclidean distance between each pair
QƑ -- is this invariant under deduplication?
p -- cartesian product of (implicit) ranges [1..n] and [1..n]
ŒP -- the powerset of this (sorted by length)
ÇƇ -- filter the coordinate subsets on the helper function
ṪL -- get the length of the last subset
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
lef{I.aM.cT2y*=U
```
[Try it online!](https://tio.run/##K6gsyfj/Pyc1rdpTL9FXLznEqFLLNvT/f2MA "Pyth – Try It Online")
Uses the standard algorithm: form all sets of points, form all pairs of points in the set, find distances, check for duplicates, find longest set without duplicates, output length.
However, there are some fun tricks to reduce the length. `*=U` is one I'm proud of.
```
lef{I.aM.cT2y*=U
U From input Q, form list [0..Q-1]
= Assign the result back to Q
* Take the Cartesian product with Q
Now, we have a list of all pairs of points.
The naive way would be ^UQ2, one character longer.
y Powerset, sorted by length
f Filter the powerset on
.cT2 Form all pairs (without repetition) of points in the set
.aM Map the pairs of points to their euclidean distances.
{I Check for duplicates (True if no duplicates)
e Last element, longest remaining subset
l Length
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 126 bytes
```
f=lambda n,i=0,l=[]:i<n*n and max(f(n,i+1,L:=l+[i//n+i%n*1j])-len(l)*len(L)/2+len({abs(p-q)for p in L for q in L}),f(n,i+1,l))
```
[Try it online!](https://tio.run/##NYxBCsIwEEWvMhthpkmpVQQp5ga9QekipY2OpNM0dqGIZ6@N4Oo/eI8fXsttkuM5xHV1xtux6y2IZrPX3jRtxRfJBKz0MNonOtyUKnVdGa8aLgpRvJOsvLeU@0HQU5ampuKgErxt98CQz@SmCAFYoIaE8w8/pP@HnmhNgpOIVq4DlvpEFYTIsiBrcMhb8wU "Python 3.8 (pre-release) – Try It Online")
A very slow \$ O(2^{n^2}) \$ solution. Timeout for \$n>4\$.
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 130 bytes
```
f=lambda n,i=0,l=[]:i<n*n and max(len(l)*len(L:=l+[i//n+i%n*1j])/2<len({abs(p-q)for p in L for q in L})and-~f(n,i+1,L),f(n,i+1,l))
```
[Try it online!](https://tio.run/##NY1BDoIwEEWvMhuTGShBdEMIvQE3ICxKoDqmDKWy0Bi9OlITV/8l/@V//1yvs5xLH7bNamemfjAgivVROd12FdeSCBgZYDIPdKOgoyRGU2mXtpznkvJBkuLWUX6qY/My/R19tpCdA3hggQYiLj980z6WfSzuJ2mhGlJ/dERb9Dh6wchlxEKVVIEPLCuyAou8O18 "Python 3.8 (pre-release) – Try It Online")
A bit faster (though time out for \$n=8\$), *only* need \$ O(n^{2n}) \$ time to rune.
-3 bytes by Jakque
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~139 ...~~ 116 bytes
```
->n{(w=*0...n*n).find{|x|w.combination(x+1).all?{|y|y.combination(2).map{|a,b|(a%n-b%n)**2+(a/n-b/n)**2}.uniq!}}||n}
```
[Try it online!](https://tio.run/##VctBDoIwEEDRq@iCpC0yCDsXyEGIi6mmSRMYwEho05mzV2PcuHz5@c/Nxuy6XF0pqb0zZwAgQxqcp0fiwDvc58l6wpefSYWy0YDj2CeOHP9Sq2HCJTGeLCssqLIFaWPaUmH9Qf2FwEZ@PYowk2TVAFx@W@Dl4IZwk/wG "Ruby – Try It Online")
Should work in theory, times out for n>6.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Lãæʒ.Æ€øÆnODÙQ}éθg
```
Same exact approach as [*@ovs*' Jelly answer](https://codegolf.stackexchange.com/a/237846/52210), and it's even slightly slower, since it'll time out for \$n=4\$.
-1 byte thanks to *@Adnan*.
[Try it online.](https://tio.run/##ASgA1/9vc2FiaWX//0zDo8OmypIuw4bigqzDuMOGbk9Ew5lRfcOpzrhn//8z)
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
ã # Cartesian power with itself to create all pairs
æ # Get the powerset of these coordinates
ʒ # Filter this by:
.Æ # Get all pairs of coordinates from the current list
€ # Map over the pairs of coordinates:
ø # Zip/transpose; swapping rows/columns
Æ # Reduce each inner-most list by substracting
n # Get the square of each integer
O # Sum each together
# Check if all items are unique:
D # Duplicate
Ù # Uniquify the items in this copied list
Q # Check if it's still equal to the original list
}é # After the filter: sort the remaining lists of coordinates by length
θ # Pop and leave the last/longest one
g # Pop and push its length
# (after which this is output implicitly as result)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 203 163 bytes
```
r=range
c=lambda l:len(set(l))==len(l)
f=lambda i:max(bin(j).count("1")for j in r(1<<i*i)if c([abs((a-b)%i*1j+a//i-b//i)for a in r(j)for b in r(a)if j>>a&j>>b&1]))
```
[Try it online!](https://tio.run/##NY1BCoMwEEX3niIIlRmrldSdqBcRFxOr7YQYJVpoT2@j0ll8@Lz/mPm7viabb5urHNlnH3SVoVE9SJjC9BaWfgWDWFV7MRgMf8zFSB9QbEHjrZvedoVQhjhMTmjBVjiQZckxIw@ig4bUAkCpwgvHUl8pyzhVPg6BTkEfRZ2FdlHXNUU@VCRbxG3HvONGJvckb4tA@Jsd@@cDsF/8AA "Python 3 – Try It Online")
A simple brute force solution. The integer `j` is a binary encoded board. Next, all distances for `j` are calculated. The if-guard `j>>a&j>>b&1` checks that both selected squares are in the board `j`. Instead of `for a in r(i*i)` we can use `for a in r(j)`, since only values of `a`, where a bit is set in `j` at index `a`, matter. This means that `a < j` always (for set bits).
[Answer]
# JavaScript (ES6), ~~134 133~~ 130 bytes
*Saved 3 bytes thanks to @tsh*
```
f=(n,a=[],i=0)=>-a.some(o=i=>a.some(j=>j>i&&!(o[(q=i%n-j%n)*q+(j-=i-q)*j/n/n]^=1)))||i<n*n&&Math.max(1+f(n,[...a,i],++i),f(n,a,i))
```
[Try it online!](https://tio.run/##Zc5NDoIwEAXgvbdwAelAW8T/hcMNPAHBpEHQaWAqQowL7o6YuDHdzfsW7401L9OXT3oMit21mqYaBUuDeSEJV4CZMrp3bSUcEma/22JmMwrDpXC56JACVjZgiLpYWIWkOohswgkXF0wBYBzpxBGH4dkMd92at0jjel7JtdZGUiHjmEB@ZU4AU@m4d02lG3cTtZgbFv@y9mTjydaTnSd7Tw6eHOd/Pg "JavaScript (Node.js) – Try It Online")
(This is just fast enough for f(8) but may time out from time to time.)
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
a = [], // a[] = list of pawn positions
i = 0 // i = current position (0 ≤ i < n²)
) => //
-a.some(o = i => // for each position i in a[]:
a.some(j => // for each position j in a[]:
j > i && // test whether j is greater than i
!(o[ // and this is the first time
(q = i % n - j % n) // that the we encounter the
* q + // squared Euclidean distance between:
(j -= i - q) * j // (i % n, j % n) and
/ n / n // (floor(i / n), floor(j / n))
] ^= 1) //
) // end of inner some()
) // end of outer some()
// return -1 if truthy
|| // otherwise:
i < n * n && // return 0 if i is equal to n²
Math.max( // otherwise, return the maximum of:
1 + f(n, [...a, i], ++i), // 1 + recursive call with i added to a[]
f(n, a, i) // recursive call with a[] unchanged
// (i is incremented in both cases)
) // end of Math.max()
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~72~~ 67 bytes
```
Nθ⊞υE²⟦⟧FθFθFυ«≔⁺§λ⁰E§λ¹ΣXEμ⁻ξ⎇πκι²η¿¬⊙η⊖№ημ⊞υ⟦η⁺§λ¹⟦⟦ικ⟧⟧⟧»I⌈EυL⊟ι
```
[Try it online!](https://tio.run/##XY9PSwMxEMXP3U8xxxmIoMVbT0u9FLQs6G3ZQ9ymTXCTrPmjW8TPHicVQT0NvHnvzW9GLcPo5VTKzs057bN9VgFfadN0OWrMAh7kjGsB/UAsHn0A3sKfmQk@mlUbozk57KYcsU07d1ALTgKu6bvil3TD0mO22Pl3vlWXlj3GcXAR8KSCk@GMs4AXAYaI3Wu6DM0EK3ME3PuErTujFnCnxqCsckkdcOuzS1W01U/w80LP0n@uCtH3ho8MAw1c/Nl0wXB8K2NiqMVYRqxwXHCv3ClpBp7RXKppU8ptuXqbvgA "Charcoal – Try It Online") Link is to verbose version of code. No longer manages to complete `n=6` on TIO, but that's code golf for you. Explanation:
```
Nθ
```
Input `n`.
```
⊞υE²⟦⟧
```
Start a breadth-first search with no pawns and no squared distances.
```
FθFθFυ«
```
Loop over all squares and all positions.
```
≔⁺§λ⁰E§λ¹ΣXEμ⁻ξ⎇πκι²η
```
Calculate the augmented set of squared distances that result when adding this pawn.
```
¿¬⊙η⊖№ημ
```
If they are all unique, then...
```
⊞υ⟦η⁺§λ¹⟦⟦ικ⟧⟧⟧
```
... add this with the updated set of pawns to the search list.
```
»I⌈EυL⊟ι
```
Output the maximum number of pawns found.
[Answer]
# [R](https://www.r-project.org/), 112 bytes
Or **[R](https://www.r-project.org/)>=4.1, 105 bytes** by replacing the word `function` with a `\`.
```
function(n){for(i in 0:2^n^2)if(all(table(dist(which(a<-!matrix(i%/%2^(1:n^2-1)%%2,n),T)))<2))T=max(T,sum(a));T}
```
[Try it online!](https://tio.run/##Fcq9CoMwGAXQvU9hh8C9EGlNO/nzFpmF1Db4QYygkQqlz57W5Uxnyb7LfotDkjki8uPnBVJILK616WNvKB4uBCT3CC88ZU14jzKMcG15nlxaZIeoizI9qvr/y4pKGR2pLcnWkLab3A6r122CIxv7zR4VTx7m4HZwZ/4B "R – Try It Online")
My question with no [R](https://www.r-project.org/) answer? No way!
Outputs `n`-th term `1`-indexed.
### Explanation
Straightforward brute-force approach:
* generate all numbers between \$0\$ and \$2^{n^2}\$ and convert to binary of fixed length of \$n^2\$
* reshape to \$n \times n\$ matrix
* get indices of zeros (we have to use `!` as `which` works only for logical input) - two-dimensional with `T` option
* calculate `dist`ances
* are they unique? (`all(table(...)<2)`)
* if so, how many ones did we have and update running max (kept in `T`)
] |
[Question]
[
Write a program or function which takes three positive integers \$a, b, c\$ and returns/outputs one value if there is, and a different value if there isn't, a triangle on the square lattice, whose sides' lengths are \$\sqrt{a}, \sqrt{b}, \sqrt{c}\$. By "on the square lattice" I mean that its vertices are in the \$xy\$ plane, and their \$x\$ and \$y\$-coordinates are all integers
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
Test cases:
* 16 9 25: true (3-4-5 triangle)
* 8 1 5: true (e.g. (0,0), (1,0), (2,2))
* 5 10 13: true (e.g. (0,1), (1,3), (3,0); sides needn't be on grid lines)
* 10 2 1: false (not a triangle: long side is too long for short sides to meet)
* 4 1 9: false (not a triangle: three points in a straight line)
* 3 2 1: false (triangle is on the cubic lattice but not the square lattice)
* 3 7 1: false (triangle is on the hex lattice but not the square lattice)
* 25 25 25: false (no such triangle on this lattice)
* 5 5 4: true (isosceles is OK)
* 15 15 12: false (OK shape, wrong size)
* 25 25 20: true (OK shape and size; common prime factor 5 is OK)
* 4 4 5: false (Bubbler's suggestion)
* 17 17 18: true (acute isosceles with equal short sides OK)
* 26 37 41: true (acute scalene is OK)
These same test cases, but just the numbers. First, those that should return true:
```
16 9 25
8 1 5
5 10 13
5 5 4
25 25 20
17 17 18
26 37 41
```
Then those that should return false:
```
10 2 1
4 1 9
3 2 1
3 7 1
25 25 25
15 15 12
```
[Answer]
# Python3, ~~171~~ ~~151~~ ~~142~~ ~~137~~ 133 bytes
* 151 => 142 Thanks to @user
* 142 => 137 and fixed correctness thanks to @Bubbler
* 137 => 133 thanks to @xnor and @Bubbler
```
lambda l:l in[[d*d+D*D,e*e+E*E,(d-e)**2+(D-E)**2]for d,e,D,E in product(*[range(-max(l),max(l))]*4)if d*E-e*D]
from itertools import*
```
Tests here:
```
TESTS = [
(16,9,25,True),
(8,1,5,True),
(5,10,13,True),
(10,2,1,False),
(4,1,9,False),
(3,2,1,False),
(3,7,1,False),
(25,25,25,False),
(5,5,4,True),
(15,15,12,False),
(25,25,20,True),
(4,4,5,False)
]
for x,y,z,true in TESTS:
print('testing',x,y,z)
computed = f([x,y,z])
assert computed == true
```
[Try it online!](https://tio.run/##bZBNboMwEIX3nMK7GDNI4SdpE4kd7gXCjrJwY5MiGYyMkZJeng6gVqWtNZKtb94bj17/cO@mS6Y6e520aN@kIPqsSdOVpWQyyFkOiqmAMw5UhspnLA5oHvL5UdXGEgkKcuDoIL01crw6ykorupuiYSvuVPuwXn7FUr@piWQ8VCyvvNqaljROWWeMHkjT9sY6NhX8UlxIRkqP4KHREU4QH6Cwo/JhZc8QwZYcINpDlGwYkhiFL0IP3yxFcNqi5K8qgaffCDdYa0MPuEa6/RQ3wYr/de830hStX/O8yvPmNO/wgA9wqJoDXaI4L@reNp2jO6cG13S3HSxCf2ldTduPTknMrKbl0qjWjhgGTPeHICPz6OkT)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ZD(Ÿ4ãʒÁ2ôPÆĀ}ειDøÆªnOQ}à
```
Port of [*@TedBrownlow*'s Python answer](https://codegolf.stackexchange.com/a/217500/52210), so make sure to upvote him as well!
Very slow. The larger the maximum value in the input-list, the slower it is.
[Try it online](https://tio.run/##ATcAyP9vc2FiaWX//1pEKMW4NMOjypLDgTLDtFDDhsSAfc61zrlEw7jDhsKqbk9RfcOg//9bOCwxLDVd) or [verify a few of the smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@jXDSO7jA5vPjUpMONRoe3BBxuO9JQe27ruZ0uh3ccbju0Ks//0LrA2sML/uv8j4620DHUMY3ViTY00DHSMQQyTIAClkDaGMo31jEH06Y6pjomYHkToIZYAA).
**Explanation:**
```
Z # Push the maximum of the (implicit) input-list
D( # Duplicate this maximum, and negate the copy
Ÿ # Pop both, and push a list in the range [max,-max]
4ã # Create all possible quartets of this list with the cartesian product
ʒ # Filter this list of quartets [a,b,c,d] by:
Á # Rotate it once towards the right: [d,a,b,c]
2ô # Split it into parts of size 2: [[d,a],[b,c]]
P # Take the product of each inner pair: [d*a,b*c]
Æ # Reduce the list by subtracting: d*a-b*c
Ā # Check that this is NOT 0 with a Python-style truthify
}ε # After the filter: map each remaining quartet to:
ι # Uninterleave the list: [[a,c],[b,d]]
D # Duplicate it
ø # Zip/transpose the copy, swapping rows/columns: [[a,b],[c,d]]
Æ # Reduce each by subtracting: [a-b,c-d]
ª # Add this pair to the earlier list: [[a,c],[b,d],[a-b,c-d]]
n # Square each: [[a²,c²],[b²,d²],[(a-b)²,(c-d)²]
O # Take the sum of each inner pair: [a²+c²,b²+d²,(a-b)²+(c-d)²]
Q # Check that this list is equal to the (implicit) input-list
}à # After the map: check if any were truthy by taking the maximum
# (after which the result is output implicitly)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ 22 bytes
-1 thanks to @ovs
```
ZÝã3ãεDÁ-nOQ}àIt{R`+‹*
```
[Try it online!](https://tio.run/##AS8A0P9vc2FiaWX//1rDncOjM8OjzrVEw4Etbk9RfcOgSXR7UmAr4oC5Kv//WzQsNCw1XQ "05AB1E – Try It Online")
very very slow.
Explanation:
```
Z maximum
Ý push the range [0, maximum]
ã cartesien power which defaults to 2, returning all pairs
3ã cartesien power with 3, returning all possible traingles in the box (0,0,maximum,maximum)
ε map
D duplicate
Á rotate left 1
- subtract # the offset between the three points
n square
O sum # the side lengths of the triangle
Q check if equals to the implicit input, returning 0/1
}
à maximum # 1 if one of the cases was 1, 0 otherwise
I push the input
t square root
{ sort # increasing order, e.g. [1,2,3]
R reverse # e.g. [3, 2, 1]
` dump # dump the array to stack e.g. 3, 2, 1
+ addition # e.g. 3, 3
‹ is less than
* multiply, works as AND
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~76~~ ~~69~~ 65 bytes
```
{}=!=Solve[Norm/@{a={w,x},b={y,z},a+b}^2==#&&w z!=x y,,Integers]&
```
[Try it online!](https://tio.run/##TczLCoJAFAbgvU9hCG76I2fM0sWE2zZRuJSCUcYSUsGm6zC@uo1GEJzFdy7/qbg8i4rLMud9wXql2YQlzeUu0m3TVvNYcaYeeGpkTL3w1uDTTB8pY47rPuz3hD3tF7CppTiJ9npw@/2tFDLetWUtU2e2LmLn4HZJzutOWYosEYEGGpYKQTAiAPFA/IEGFGTQwmyjAf5v4mP1BQ0w1jcbYDEmzRdT9O/AMzaNyYfa0v0H "Wolfram Language (Mathematica) – Try It Online")
If no solution exists, `Solve` returns an empty list `{}`; otherwise, since the variables to solve for are not given, it remains unevaluated. From there it's just a matter of collapsing unevaluated `Solve`s into a single form.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~281~~ ~~244~~ ~~225~~ ~~215~~ ~~192~~ 179 bytes
-14 thanks to @AZTECCO
-9 thanks to @ceilingcat
```
#define s(x,y)x>y?x^=y^=x^=y:0;
#define f(x,y)for(x=~b;x++<b;)for(y=~b;y++<b;)if(x*x+y*y==
r,i,j,k,l;t(a,b,c){r=0;s(a,c)s(b,c)s(a,b)f(i,j)a)f(k,l)b)r|=j*k&&c-a-b==i*k+j*l<<1;r=r;}
```
[Try it online!](https://tio.run/##dVHtboIwFP3PU9xoNBTKAvi1rdS9gS8wNYECW9XhUjBCHHt1dymgy5I19Nyvc09vi3DehLgOZSYOpziBIC9ieXx4X16HcZLKLIHcLGlFymX1Um55teUNPrvM6OuprqdHZZb8O2KlbQcR03HVxFUbS6RZpV1ZFeeGopLu6J4eWGGGNKKCXBR3WY6BILkZacQCSU0kkhAtkklE1BffWfvxWDihE3Eurb29sw5B4DHFFatvM6/AmxqGzAr4CGVmErgYBuBqMuHragMcLt6cwiOFGQXPpTClMNGfP2tzs9bFvLdAd16zm0LUKcATFtt2X3uIi/8UJotfCqJT6KkT3d7J3dtQz3dbBk469ToFDc0DN1Jn1HEZmgBWaGy7uSx06@Z8KuSm5mDkx9Bvx1nCKF5n62xA8VXOG4o3a1BoxF/zJ0dIe359n0IlxUllOIBRX38A "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~90~~ ~~79~~ ~~73~~ 71 bytes
```
≔⌈θη≔⁻Σθ⁺η⌊θζ≔…·±ζζεFεFε¿⁼⌊θ⁺Xι²Xκ²FεFε¿⁼ζ⁺Xλ²Xμ²¿⁻×ιμ×κλP⁼η⁺X⁺ιλ²X⁺κμ²
```
[Try it online!](https://tio.run/##fY8xC8IwEIV3f8WNV4iDgiA4OTg4KEXdpEMosT1MUpu0Kv3zMUlbqotZkvfy3XtcXnKTV1w6t7WWCo0H/ibVKqwTBmWymY026dbiefhIpRclA@8OcOLdbsL3OvcIPcWJ60LgURS8EdhFiIHw4K0ygCKB8aYb4K5uubQ4pQ5NafUSBonBMjhR3IPwB/7kdD/j8ntcjeMB73e7kBI2lChP9cKXyAAdWtnQw5BuxujyJzo@KcDfHdG993mxbOPc9bpmsGCwyjI3f8oP "Charcoal – Try It Online") Link is to verbose version of code. Output is a Charcoal boolean, i.e. `-` if there is a solution, nothing if not. Edit: Saved 11 bytes by explicitly ranging one coordinate over negative values instead of testing both of its signs. Saved 6 bytes by using a colinearity test instead of a triangle test. Saved 2 bytes by inlining a variable. Made all variables range over negative values to fix the case where the three sides point in different quadrants, fortunately without costing any more bytes. Explanation: Uses brute force to find a solution.
```
≔⌈θη≔⁻Σθ⁺η⌊θζ≔…·±ζζε
```
Get the maximum and middle squared lengths. Call these \$ f \$ and \$ e \$. Create a range from \$ -e \$ to \$ e \$.
```
FεFε¿⁼⌊θ⁺Xι²Xκ²
```
Find integers \$ -e \le g \le e \$ and \$ -e \le h \le e \$ such that \$ d = g^2 + h^2 \$ where \$ d \$ is the minimum squared length.
```
FεFε¿⁼ζ⁺Xλ²Xμ²
```
Find integers \$ -e \le i \le e \$ and \$ -e \le j \le e \$ such that \$ e = i^2 + j^2 \$.
```
¿⁻×ιμ×κλ
```
If the two sides are not colinear, ...
```
P⁼η⁺X⁺ιλ²X⁺κμ²
```
... check whether \$ f = (g + i)^2 + (h + j)^2 \$.
[Answer]
# JavaScript (ES6), 115 bytes
Expects three distinct arguments. Returns either `0` or a non-zero integer.
```
(a,b,c)=>(F=(C,m=M=a|b|c)=>m+M&&C(m)|F(C,m-1))(w=>F(x=>F(y=>F(z=>a-w*w-x*x|b-y*y-z*z|c-a-b^w*y+x*z<<1?0:x*y-w*z))))
```
[Try it online!](https://tio.run/##nVNbb5swFH7frzhPnaGQcgnbeiF7qJSXquo/qGTMCXgCO8NmEJT/ntnQpGJJp2lIBwsffRf7fPygv6hiDd9qX8gcD5v0QKiXecxJV2SdkkevTp9Tus/2dqe@fr66eiS1s1/bjh86DunS1Zr09rWzryFdUb9zO793@33m79ydP7jDnvnUz147d3fdu8PDQ/g9uOtNq3MHxzwHJoWSFS4qWZANCb94ALceRInjwM0N6KZFABL7Sz8xH5yKokLn0xwE3wwoNDUH4aJYAAm8wPGAhNMSeZFzBk88CANT8UV4OMFju8SG5R4Uz1GBQMzFZw0ZghRQNDyHigtUf9Jbaoisw4l@QyuFQITUQE9HuoNKimJkBq5ASzltbGQDqpSNfhPVEmpEfXaE5dsN3P5VQ5cNImwlF1oBF6andEN5UerR@hlrfNH5kc8aNSfXJQJrM86golpzhpC1Gqy07aifLW3w2Lqo8PVfFErs/4M/SmyU3uN0uhdQLStPNzOJGLGPbCY2XKaWs4RwJRXDyozFQF@ezgZvc2Urmom/PJmJ0i160DXTzIePfQczwSMUqMhH3D0wWdfG/bbhNRoFpk1gkst@xpAs33@T0c/hNw "JavaScript (Node.js) – Try It Online")
### How?
This is similar to other answers, but the main test has been modified some more to save a few bytes (at least in JS). Besides, we use `a|b|c` instead of `Math.max(a,b,c)`. This is \$2\cdot\max(a,b,c)-1\$ in the worst case.
Given \$(w,x,y,z)\$, we want to know if we have:
$$w^2+x^2=a\tag{1}$$
$$y^2+z^2=b\tag{2}$$
$$(x+z)^2+(w+y)^2=c\tag{3}$$
\$(3)\$ is turned into:
$$x^2+z^2+2xz+w^2+y^2+2wy=c$$
Provided that \$(1)\$ and \$(2)\$ are true, this becomes:
$$a+b+2(xz+wy)=c$$
or:
$$c-a-b=2(xz+wy)$$
Hence the JavaScript expression:
```
c-a-b^w*y+x*z<<1
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 136 bytes
```
(p,q,r)=>(g=(n,t,x=0,y=(n-x*x)**.5)=>y%1==0&&t(x,y)|t(x,-y)||1/y&&g(n,t,x<0?-x:~x))(p,(a,b)=>g(q,(c,d)=>(a+c)**2+(b+d)**2==r&&a*d!=b*c))
```
[Try it online!](https://tio.run/##jZPRkpMwFIbv9ymOF7ZJm7JAi7qtrFde7cU@gOvMhpBCdmjSklOlWn31eoDSsc7oCMwkQ/7/y3844UV@kV7VZosz63J9WqcnthU7UfP0nhUpswJFk4biQNNZM2n4ZBIktHZ4HaVpOBoha8SBH9thRuMxuj2MRkVvex9@mDXLnw3nhGRSZOQr2E4wJfIWL6eKcPGUZdO8naRpPRrJSf4qzSaK8xNqj0p67SGF5xugK3oDdxAnS8B6r4HNZ4tZQnMjbVFp3kneQQQXgQ6KAFgoQi6ARf0Qi5j30gSiEKL5n@KoF8/bYU6eFXiTUwirdW7HCJkGZ6GoTQ6Vsdr3MELFEC1hLStPMOsQ5CXaEipni44DxgM6179Yuxp86Wo8b4EONlpjT1xQJXd/BWJZaw1bZyx6MJbWPNbSFCV2qXrE/CrTYG4jUAVYalD7zCioJKJRGrI9QrtPu@J3e1nrYWnAvf03rtTNf8PipH9@qxD8XpWXGnsowa9sCd2LoWXGO690RV@OZI8P504k3RNfwI8P9JHlVgv4Wvdt@HadIRx4gxKkzTvZCpTbbCjItjYbTUCF1LJk2O45oLAbxgO/rQyy8ZMd89XN5dwG1N@PUpVseAPpPXzvdq40wif6JYQS@jOd70ERbCSS4fYpnx7bTMeuhtuCsK1NOetdpYPKFexsX7OpFNNM0M9EqOCFTgQFwTEnyw@@Ov0C "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
[*Migrated from chat*](https://chat.stackexchange.com/transcript/message/48293334#48293334)
Given two non-empty non-negative integer matrices ***A*** and ***B***, answer the number of times ***A*** occurs as a [contiguous, possibly overlapping, submatrix](http://mathworld.wolfram.com/Submatrix.html) in ***B***.
## Examples/Rules
### 0. There may not be any submatrices
***A***:
`[[3,1],`
`[1,4]]`
***B***:
`[[1,4],`
`[3,1]]`
Answer:
`0`
### 1. Submatrices must be contiguous
***A***:
`[[1,4],`
`[3,1]]`
***B***:
`[[3,**1,4**,0,5],`
`[6,**3,1**,0,4],`
`[5,6,3,0,1]]`
Answer:
`1` (marked in bold)
### 2. Submatrices may overlap
***A***:
`[[1,4],`
`[3,1]]`
***B***:
`[[3,**1,4**,5],`
`[6,**3,*1***,4],`
`[5,6,*3,1*]]`
Answer:
`2` (marked in bold and in italic respectively)
### 3. A (sub)matrix may be size 1-by-1 and up
***A***:
`[[3]]`
***B***:
`[[**3,**1,4,5],`
`[6,**3**,1,4],`
`[5,6,**3**,1]]`
Answer:
`3` (marked in bold)
### 4. Matrices may be any shape
***A***:
`[[3,1,3]]`
`[[**3,1,*3***,1,**3,1,*3***,1,3]]`
Answer:
`4` (two bold, two italic)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 10 bytes
```
{{s\s\}ᵈ}ᶜ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7q6OKY4pvbh1o7ah9vm/P8fHR1trGOoY6JjGqsTbaYDZgNZpjpgdiyQGQ0RAfNi/0cBAA "Brachylog – Try It Online")
I like how clear and straightforward this program is in Brachylog; unfortunately, it's not that short byte-wise because the metapredicate syntax takes up three bytes and has to be used twice in this program.
## Explanation
```
{{s\s\}ᵈ}ᶜ
s Contiguous subset of rows
\s\ Contiguous subset of columns (i.e. transpose, subset rows, transpose)
{ }ᵈ The operation above transforms the first input to the second input
{ }ᶜ Count the number of ways in which this is possible
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ZẆ$⁺€Ẏċ
```
[Try it online!](https://tio.run/##y0rNyan8/z/q4a42lUeNux41rXm4q@9I9//Dy430I///1@BSiI421DGJ1eFSUIg21jGMjeXSAYmBmGAxkCRCTMdEx0DHFCJjpgMSMIBpNtUBCRggjMBhLNAIFANQtFNHszGyDhSMIgHkaAIA "Jelly – Try It Online")
### How it works
```
ZẆ$⁺€Ẏċ Main link. Arguments: B, A
$ Combine the two links to the left into a monadic chain.
Z Zip; transpose the matrix.
Ẇ Window; yield all contiguous subarrays of rows.
⁺ Duplicate the previous link chain.
€ Map it over the result of applying it to B.
This generates all contiguous submatrices of B, grouped by the selected
columns of B.
Ẏ Tighten; dump all generated submatrices in a single array.
ċ Count the occurrences of A.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
ZyYC2MX:=XAs
```
Inputs are **A**, then **B**.
[Try it online!](https://tio.run/##y00syfn/P6oy0tnIN8LKNsKx@P//aEMdE2sFYx3DWK5oIGmtAOTHAgA) Or [verify all test cases](https://tio.run/##y00syfmf8D@qMtLZyDfCyjbCsfi/S8j/aEMdE2sFYx3DWK5oIGmtAOQDmaiiOiY6Bjqm1gpmOiCOAUjOVAfEMQCrgChWQCiGK4UrBMvhlQcA).
### Explanation
Consider inputs `[1,4; 3 1]`, `[3,1,4,5; 6,3,1,4; 5,6,3,1]`. The stack is shown with the most recent element below.
```
Zy % Implicit input: A. Push size as a vector of two numbers
% STACK: [2 2]
YC % Implicit input: B. Arrange sliding blocks of specified size as columns,
% in column-major order
% STACK: [3 6 1 3 4 1;
6 5 3 6 1 3;
1 3 4 1 5 4;
3 6 1 3 4 1]
2M % Push input to second to last function again; that is, A
% STACK: [3 6 1 3 4 1;
6 5 3 6 1 3;
1 3 4 1 5 4;
3 6 1 3 4 1],
[1 4;
3 1]
X: % Linearize to a column vector, in column-major order
% STACK: [3 6 1 3 4 1;
6 5 3 6 1 3;
1 3 4 1 5 4;
3 6 1 3 4 1],
[1;
3;
4;
1]
= % Test for equality, element-wise with broadcast
% STACK: [0 0 1 0 0 1
0 0 1 0 0 1;
0 0 1 0 0 1;
0 0 1 0 0 1]
XA % True for columns containing all true values
% STACK: [0 0 1 0 0 1]
s % Sum. Implicit display
% STACK: 2
```
[Answer]
# Dyalog APL, ~~6~~ 4 bytes
```
≢∘⍸⍷
```
This is nearly a builtin (thanks [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) and [ngn](https://codegolf.stackexchange.com/users/24908/ngn)).
```
⍷ Binary matrix containing locations of left argument in right argument
≢∘⍸ Size of the array of indices of 1s
```
Alternative non-builtin:
```
{+/,((*⍺)≡⊢)⌺(⍴⍺)*⍵}
```
Dyadic function that takes the big array on right and subarray on left.
```
*⍵ exp(⍵), to make ⍵ positive.
((*⍺)≡⊢)⌺(⍴⍺) Stencil;
all subarrays of ⍵ (plus some partial subarrays
containing 0, which we can ignore)
⍴⍺ of same shape as ⍺
(*⍺)≡⊢ processed by checking whether they're equal to exp(⍺).
Result is a matrix of 0/1.
, Flatten
+/ Sum.
```
Try it [here](https://tryapl.org/?a=%282%202%u23741%204%203%201%29%7B+/%2C%28%28%u237A%u2261%u22A2%29%u233A%28%u2374%u237A%29%29%u2375%7D3%204%u23743%201%204%205%206%203%201%204%205%206%203%201&run).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
øŒεøŒI.¢}O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8I6jk85tBZGeeocW1fr//x8dbaxjqGOiYxqrE22mA2YDWaY6YHZsLFd0NEQEzAMA "05AB1E – Try It Online")
```
øŒεøŒI.¢}O Full program. Takes 2 matrices as input. First B, then A.
øŒ For each column of B, take all its sublists.
ε } And map a function through all those lists of sublists.
øŒ Transpose the list and again generate all its sublists.
This essentially computes all sub-matrices of B.
I.¢ In the current collection of sub-matrices, count the occurrences of A.
O At the end of the loop sum the results.
```
[Answer]
# [Uiua](https://uiua.org), ~~4~~ 3 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⧻⊚⌕
```
[Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAg4qe74oqa4oyVCgpbWzEgNF0KIFszIDFdXQpmW1szIDFdCiAgWzEgNF1dCgpbWzMgMSA0IDAgNV0KIFs2IDMgMSAwIDRdCiBbNSA2IDMgMCAxXV0KZltbMSA0XQogIFszIDFdXQoKW1szIDEgNCA1XQogWzYgMyAxIDRdCiBbNSA2IDMgMV1dCmZbWzEgNF0KICBbMyAxXV0KCltbMyAxIDQgNV0KIFs2IDMgMSA0XQogWzUgNiAzIDFdXQpmW1szXV0KCltbMyAxIDMgMSAzIDEgMyAxIDNdXQpmW1szIDEgM11dCg==)
-1 thanks to Razetime
```
⧻⊚⌕
⌕ # find
⊚ # where
⧻ # length
```
[Answer]
# JavaScript (ES6), 93 bytes
Takes input as `(A)(B)`.
```
a=>b=>b.map((r,y)=>r.map((_,x)=>s+=!a.some((R,Y)=>R.some((v,X)=>v!=(b[y+Y]||0)[x+X]))),s=0)|s
```
[Try it online!](https://tio.run/##rYxBCoMwEEX3nkJ3CU4lonYXD@FKCaFEq6VFjZgiCt7dxloLSumiFDKQ9@fPu4lOqKy9NvdDLc/5VNBJ0DDVz6lEg1ALA6Zhu8AJeg3KppZwlKxyhCJIdBK9qINYU2dRlLLBTvg4Esx6O@YYY1CU4FFNmayVLHOnlBdUIGaYJvPA5TB/XPC5wfGSzgDrWqfYMD7c7ltvI/hAIFh2R5gDslYDmAPyq3Yj3Si/CL3/WHR3Z9rM83J6AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 95 bytes
```
function(A,B,x=dim(A),D=dim(B)-x){for(i in 0:D)for(j in 0:D[2])F=F+all(B[1:x+i,1:x[2]+j]==A);F}
```
[Try it online!](https://tio.run/##pZDRCoIwFIbvfYqBNzt4Aue0C2MXivgS4kUpwsImSIEQPfvaLEsJEurAxvn@w76x9boRurmo6iw7RRNMcRC1PNEEMBubFDYDXJuup5JIRfw4AwvHJxRBCbnIvX3b0rRg8eBJNLuJvWMpRAK7/KYb2h@kqmlFOTLAijIMAZBMqUV8DAHIarnEd97K@eE/lGxVaRBDjOxkiyPYNsIRPm9xSfBScqOZ189K7iz@EjlM5kU6X9/f75JQ3wE "R – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~118~~ ~~97~~ 95 bytes
```
import StdEnv,Data.List
?x=[transpose y\\z<-tails x,y<-inits z]
$a b=sum[1\\x<- ?b,y<- ?x|y==a]
```
[Try it online!](https://tio.run/##JYw7C8IwFEb3/oo7ON4KxcfU0KUOgoPgmGS49iGBJC3NVRrxtxurTt85HPga25FPbmjvtgNHxifjxmFiuHB78A@siWl9MoGzahaSJ/JhHEIHUalnmTMZG2DGWObGGw7w1NmK4CrC3clCqbnMobp@M1TzKwpBOl2YlnsBK5CywK1GucFC68WWxS3uNILc40@WuMMfa53eTW/pFlJ@PKU6enKm@cvZEvfD5D4 "Clean – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 101 bytes
```
lambda a,b:sum(a==[l[j:j+len(a[0])]for l in b[i:i+len(a)]]for i,L in e(b)for j,_ in e(L))
e=enumerate
```
[Try it online!](https://tio.run/##jYxLDoMgFEXHZRUknUD6BvjrwIQduANKGkgxxSgaq4Oungo2UUft4CXvfs4d3tOzd6mv@c23qtMPhRXo8jV3RHEuWtGUzaU1jijBJJV1P@IWW4e1sKVdAyqjbaEKgSGaBtnAfZUVpchw4@bOjGoyfhitm3BNhMggkSASyKUEdBLxg@hKis8Moa26i2J1@SAHBsXiXiEoFhsFBMW@E8nviW1gw1c43cPZn1B2gJbCHjxcrOf@Aw "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~36~~ 27 bytes
```
IΣ⭆η⭆ι⁼θE✂ηκ⁺Lθκ¹✂νμ⁺L§θ⁰μ¹
```
[Try it online!](https://tio.run/##VYzBCsIwEETvfsUet7CCwdaLJxEPgkIhx5BDqKUtptE2ifj3MWkEcWFg3vDYpldz81A6hHoejMOjsg65H5G7yN1VPbEn@MFAcJq80hYngjRwPTRtcu4EtfYWL63pXI9TEacYFpMdQzD@Owd3Nrf2nV5tiuiNi/@9fQhCCEalpBWA2BKTqYnUqKQqzztaMENFC0opw/qlPw "Charcoal – Try It Online") Much shorter now that Equals works for arrays again. Explanation:
```
η Input array B
⭆ Mapped over rows and joined
ι Current row
⭆ Mapped over columns and joined
θ Input array A
⁼ Is equal to
η Input array B
✂ Sliced
¹ All elements from
κ Current row index to
L Length of
θ Input array A
⁺ Plus
κ Current row index
E Mapped over rows
ν Current inner row
✂ Sliced
¹ All elements from
μ Current column index to
L Length of
θ Input array A
§ Indexed by
⁰ Literal 0
⁺ Plus
μ Current column index
Σ Digital sum
I Cast to string
Implicitly printed
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 5 bytes
```
qŤqŤ=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FssLjy4BItslxUnJxVCxBTcPR0cb6xjG6kQb6pjExipEg2kdsFgsF1hOx0THQMcUKGamA-IZgOVNdUA8A5AqHHoQOhDqyVFtDFeFgiFyEBbELwA)
```
qŤqŤ=
q Choose a contiguous subsequences
Ť Transpose
q Choose a contiguous subsequences
Ť Transpose
= Check equality
```
`-n` counts the number of solutions.
[Answer]
# [Python 2](https://docs.python.org/2/), 211 bytes
```
a,b=input()
l,w,L,W,c=len(a),len(a[0]),len(b),len(b[0]),0
for i in range(L):
for j in range(W):
if j<=W-w and i<=L-l:
if not sum([a[x][y]!=b[i+x][j+y]for x in range(l)for y in range(w)]):
c+=1
print c
```
[Try it online!](https://tio.run/##jY/BboMwDIbveQrvRDJcCdayw9S8AXcOkQ@Q0i2IBcSogKdnSbopqrTDDpF/f/5/Rx63@WOwL7seLi1ISJJkr7GRxo63mQvW44IlVqhl31peCwxFZXRXzU8JIGPXYQIDxsJU2/eWl@KNgWddZJVnYK7QnWV1WKC2FzBnWR56z/3ADjN83T65qtVKaqMn2SiTOtmlG/lta9zWCw@2CBZB4QMAncqcjZOxM2jY3V2sXVvN/Z3iGYpdqSPmhCrHExGCCgIDJPbQ@aETeMIMCwdf0XdZMBTou@yP0G8mJqL/7j7@z@VYdD48om8 "Python 2 – Try It Online")
Fairly straightforward. Step through the larger matrix, and check if the smaller matrix can fit.
The only even slightly tricky step is the list comprehension in the 6th line, which relies on Python's conventions for mixing Boolean and integer arithmetic.
[Answer]
# [Groovy](http://groovy-lang.org/), 109 bytes
```
{a,b->(0..<b.size()).sum{i->(0..<b[i].size()).count{j->k=i-1
a.every{l=j;k++
it.every{(b[k]?:b)[l++]==it}}}}}
```
[Try it online!](https://tio.run/##lYtdC4IwFIbv/SUbO46J2kU1@yFjFy40lqbhF9joty8nlUY3deDw8n48p6auh9Hm3JoUlJ8gRule0VbfMoQxbfuL0a9UaPkujnVfdebsJwXXfuClNBuyZjQlP@8KQjzdPQOkRCEPW4VFSYjkXHd3d/ba6KorK5QjIUIIJIgAIjnJrDBnEmNvvVs1MFMQAYN4Mhtwjs19DM6xH/mFXthvMvyfmPqF@ni3tQ8 "Groovy – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 151 bytes
```
(a,b)=>{(0 to b.size-a.size).map(i=>(0 to b(0).size-a(0).size).count(j=>{var k=i-1
a.forall(c=>{var l=j-1;k+=1
c.forall(d=>{l+=1
b(k)(l)==d})})})).sum}
```
[Try it online!](https://tio.run/##rY/BTsQgEIbvfQqOQ5w24O560LCJFxMTfQKzB0rbhJalTUuNcdNnr6XLNumqJ4UwDP8/8wGdkkaOdVrmypFXqS3JP1xus448Ns0pepctKe6fequcru3t24vu3Dk8W3c44PXZRzGCxJSK/QkYcTVJk05/5rGcN5ocZQNa7IMHjAb7ktFE1b11UE4Af30ldMwjmRR1K40BFWQjypg/VDeCR@riZZNnvJJCRcFQIbKB@jmR@@MwNq22zlgowD/5HDbI6fwN4LilIV3OuNRMI/qp/6oKV2TcIsNdEO/QK2yp36FX2B/Ya/Ka@zt183@kqfY7bbXm3mH8Ag "Scala – Try It Online")
] |
[Question]
[
# Definition
* \$a(1) = 1\$
* \$a(2) = 2\$
* \$a(n)\$ is smallest number \$k>a(n-1)\$ which avoids any 3-term arithmetic progression in \$a(1), a(2), ..., a(n-1), k\$.
* In other words, \$a(n)\$ is the smallest number \$k>a(n-1)\$ such that there does not exist \$x, y\$ where \$0<x<y<n\$ and \$a(y)-a(x) = k-a(y)\$.
# Worked out example
For \$n=5\$:
We have \$a(1), a(2), a(3), a(4) = 1, 2, 4, 5\$
If \$a(5)=6\$, then \$2, 4, 6\$ form an arithmetic progression.
If \$a(5)=7\$, then \$1, 4, 7\$ form an arithmetic progression.
If \$a(5)=8\$, then \$2, 5, 8\$ form an arithmetic progression.
If \$a(5)=9\$, then \$1, 5, 9\$ form an arithmetic progression.
If \$a(5)=10\$, no arithmetic progression can be found.
Therefore \$a(5)=10\$.
# Task
Given \$n\$, output \$a(n)\$.
# Specs
* \$n\$ will be a positive integer.
* You can use 0-indexed instead of 1-indexed, in which case \$n\$ can be \$0\$. Please state it in your answer if you are using 0-indexed.
# Scoring
Since we are trying to avoid 3-term arithmetic progression, and 3 is a small number, your code should be as small (i.e. short) as possible, in terms of byte-count.
# Testcases
The testcases are 1-indexed. You can use 0-indexed, but please specify it in your answer if you do so.
```
1 1
2 2
3 4
4 5
5 10
6 11
7 13
8 14
9 28
10 29
11 31
12 32
13 37
14 38
15 40
16 41
17 82
18 83
19 85
20 86
10000 1679657
```
# References
* [WolframMathWorld](http://mathworld.wolfram.com/NonarithmeticProgressionSequence.html)
* OEIS [A003278](https://oeis.org/A003278)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Bḅ3‘
```
[Try it online!](http://jelly.tryitonline.net/#code=QuG4hTPigJg&input=&args=OTk5OQ) or [verify all test cases](http://jelly.tryitonline.net/#code=QuG4hTPigJgKxbzDh0c&input=&args=MCwgMSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOSwgMTAsIDExLCAxMiwgMTMsIDE0LCAxNSwgMTYsIDE3LCAxOCwgMTksIDk5OTk).
### How it works
This uses 0-based indexing and the primary definition from [OEIS](https://oeis.org/A003278):
>
> Szekeres's sequence: **a(n)-1** in ternary = **n-1** in binary
>
>
>
```
Bḅ3‘ Main link. Argument: n
B Convert n to binary.
ḅ3 Convert from ternary to integer.
‘ Increment the result.
```
[Answer]
# Haskell, ~~37 36~~ 32 bytes
Using the given formula in the OEIS entry, using 0-based indices. Thanks @nimi for 4 bytes!
```
a 0=1;a m=3*a(div m 2)-2+mod m 2
```
[Answer]
# Python 3, 28 bytes
```
lambda n:int(bin(n)[2:],3)+1
```
An anonymous function that takes input via argument and returns the result. This is zero-indexed.
**How it works**
```
lambda n Anonymous function with input zero-indexed term index n
bin(n) Convert n to a binary string..
...[2:] ...remove `0b` from beginning...
int(...,3) ...convert from base-3 to decimal...
...+1 ...increment...
:... and return
```
[Try it on Ideone](https://ideone.com/0wspYa)
[Answer]
# Python 3, 113 bytes
```
def f(n):
i=1;a=[]
for _ in range(n):
while any(i+x in[y*2for y in a]for x in a):i+=1
a+=[i]
return a[n-1]
```
[Ideone it!](http://ideone.com/DlS2V9)
[Answer]
# Ruby, ~~28~~ 24 bytes
Using the same method as Dennis, with 0-based indexes:
```
->n{n.to_s(2).to_i(3)+1}
```
Run the test cases on repl.it: <https://repl.it/Cif8/1>
[Answer]
## Pyke, 5 bytes
```
b2b3h
```
[Try it here!](http://pyke.catbus.co.uk/?code=b2b3h&input=10)
0-based indexing
Same formula as jelly answer
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 bytes
```
1+3⊥⊤
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/31Db@FHX0kddS/6nPWqb8Ki371FX86PeNY96txxab/yobeKjvqnBQc5AMsTDM/h/moIBV5qCIRAbAbExEJuA@CYA "APL (Dyalog Extended) – Try It Online")
Jo King's suggestion.
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes
```
1+3⊥2(⊥⍣¯1)⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///31Db@FHXUiMNIPGod/Gh9Yaaj7oW/U971DbhUW/fo67mR71rHvVuObTe@FHbxEd9U4ODnIFkiIdn8P80BQOuNAVDIDYCYmMgNgHxTQA "APL (Dyalog Unicode) – Try It Online")
Based on Dennis' Jelly answer.
Outputs are zero indexed.
```
1+3⊥2(⊥⍣¯1)⊢
⊢ Take argument
2(⊥⍣¯1) Encode in binary
3⊥ Decode from ternary
1+ Add 1
```
[Answer]
# Java 7, ~~60~~ 42 bytes
0 Indexed
```
int s(int n){return n<1?1:3*s(n/2)-2+n%2;}
```
Using the implicit sequence definition from OEIS.
Thanks to Kevin for the improvement using only one return statement.
[Answer]
## Java 8, ~~52~~ 46 bytes
0 indexed.
```
i->Integer.valueOf(Integer.toString(i,2),3)+1;
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 11 bytes
```
1+(aTB2)FB3
```
[Try it online!](https://tio.run/##K8gs@P/fUFsjMcTJSNPNyfg/kGcCAA "Pip – Try It Online")
Based on Dennis' Jelly answer. Zero Indexed.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
0-indexed
```
Ò¢n3
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0qJuMw&input=OA) or [run all test cases from the OEIS entry](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0qJuMw&input=NTgKLW0)
Same as most other solutions:
```
Ò¢n3 :Implicit input of integer U
Ò :Negation the bitwise NOT of
¢ :U converted to a binary string
n3 :Converted from a ternary string
```
] |
[Question]
[
[Fannkuch](http://3e8.org/pub/scheme/doc/lisp-pointers/v7i4/p2-anderson.pdf) is a classic benchmark program. The name comes from the German "Pfannkuchen"- pancakes- for the algorithm's resemblance to flipping stacks of pancakes. A Fannkuch sequence of *numbers* is formed as follows:
>
> Take a permutation of {1.....n}, for example: {4,2,1,5,3}. Take the
> first element, here 4, and reverse the order of the first 4 elements:
> {5,1,2,4,3}. Repeat this until the first element is a 1, so flipping
> won't change anything more: {3,4,2,1,5}, {2,4,3,1,5}, {4,2,3,1,5},
> {1,3,2,4,5}
>
>
>
You are to write a program or function which calculates a Fannkuch-like sequence for strings of alphabetic characters. Instead of using numbers to indicate how many elements of the list should be flipped each time, the position of a letter in the alphabet should be used. For example, a leading `c` would indicate that you should reverse the order of the first 3 elements, while a leading `a` indicates that the sequence is complete.
## Input
Input will be provided as a string via stdin or as a function argument. The string will contain between 1 and 26 distinct lowercase letters. Strings will not contain letters whose equivalent index would cause the Fannkuch algorithm to flip more elements than exist.
## Output
Programs or functions should return or print to stdout the sequence of terms produced by applying the Fannkuch algorithm until a leading `a` is encountered, including the initial string. For example, if the input is `bca`, you might print:
```
bca
cba
abc
```
Printed results can use any reasonable separator- commas, newlines, etc. Any choice of whitespace is acceptable.
As another example, if your input is `eabdc` you might return:
```
("eabdc"
"cdbae"
"bdcae"
"dbcae"
"acbde")
```
## Rules and Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")- the shortest program wins. Standard Loopholes are disallowed.
[Answer]
# Pyth, 16 bytes
```
.u+_<NJhxGhN>NJz
```
[Demonstration.](https://pyth.herokuapp.com/?code=.u%2B_%3CNJhxGhN%3ENJz&input=eabdc&debug=0)
The "repeat until it stops changing" feature of Pyth's reduce functions is really handy here. This is used with `.u`, the cumulative reduce function, to output all results. The body of the reduce is as naive as can be, but I couldn't find anything better.
[Answer]
# T-SQL, 213 bytes
Of course being SQL it's really large, but it was interesting to do.
Created as an inline table function using a recursive CTE query.
```
CREATE FUNCTION F(@ CHAR(26))RETURNS TABLE RETURN WITH R AS(SELECT @ S UNION ALL SELECT CAST(STUFF(S,1,ASCII(LEFT(S,1))-96,REVERSE(LEFT(S,ASCII(LEFT(S,1))-96)))AS CHAR(26))FROM R WHERE LEFT(S,1)<>'a')SELECT*FROM R
```
Expanded
```
CREATE FUNCTION F(@ CHAR(26))
RETURNS TABLE
RETURN WITH R AS(
SELECT @ S -- Initial string as an anchor for the recursion
UNION ALL
SELECT CAST(
STUFF( -- Stuff into
S, -- string S
1, -- from position 1
ASCII(LEFT(S,1))-96, -- to index value of first char
REVERSE(LEFT(S,ASCII(LEFT(S,1))-96)) -- the reverse of the index first chars
)
AS CHAR(26))
FROM R
WHERE LEFT(S,1)<>'a' -- recurse until first char is a
)SELECT*FROM R
```
Used as follows
```
SELECT * FROM F('eabdc')
S
--------------------------
eabdc
cdbae
bdcae
dbcae
acbde
(5 row(s) affected)
```
[Answer]
# CJam, 22 bytes
This is an anonymous function which takes a string on stack and returns a list of string on the stack.
```
{_,{_0='`-/(W%\+s_}*]}
```
[Try it online here](http://cjam.aditsu.net/#code=%22eabdc%22%7B_%2C%7B_0%3D'%60-%2F(W%25%5C%2Bs_%7D*%5D%7D~ed)
[Answer]
# Python 2, 59 bytes
```
def p(l):
print l;o=ord(l[0])-97
if o:p(l[o::-1]+l[o+1:])
```
I guess this is a rather straightforward answer. Uses recursion and Python's slice syntax. Call as: `p('eabdc')`.
[Answer]
## SAS, 131 bytes
```
sub a(s$);outargs s;put s;do while(b ne 1);b=rank(char(s,1))-96;substr(s,1,b)=reverse(substr(s,1,b));if b>1 then put s;end;endsub;
```
An FCMP call routine. Nongolfed below (with an extra check I highly recommend as SAS crashes if an FCMP routine enters an infinite loop).
---
```
options cmplib=work.funcs;
proc fcmp outlib=work.funcs.funcs;
sub a(s$);
outargs s;
put s=;
do while (b ne 1 and z<1e5);
b=rank(char(s,1))-96;
substr(s,1,b) = reverse(substr(s,1,b));
if b>1 then put s=;
z+1;
end;
endsub;
quit;
```
[Answer]
# Haskell, 78 bytes
```
f l@(h:_)|h=='a'=[l]|1<2=l:f(reverse(take d l)++drop d l)where d=fromEnum h-96
```
Usage: `f "eabdc"` -> `["eabdc","cdbae","bdcae","dbcae","acbde"]`.
[Answer]
# K5, 21 bytes
```
{(|v#x),(v:*x-96)_x}\
```
Saved 5 bytes thanks to @JohnE and another byte by rearranging an expression.
For the first time on earth, I think K has beaten CJam!
## 27-byte version
```
(~97=*){(|v#x),(v:-96+*x)_x}\
```
[Answer]
# Haskell, 68
```
f l@(x:_)|x<'b'=[l]|(x,y)<-splitAt(fromEnum x-96)l=l:f(reverse x++y)
```
Any more complicated tactic I thought of took more bytes.
] |
[Question]
[
Write a program that reads from stdin two integers, each newline terminated, hereafter called "number" and "radix", and:
1. Prints any fixed message you want if the number is a palindrome in that radix (e.g. `true`, `t`, `1`)
2. Prints any different fixed message you want if the number is not a palindrome in that radix (e.g. `false`, `f`, `0`, etc.)
3. These messages must be the same per each run, but there are no rules about what they must be (whatever's best for golfing).
4. You may assume the input is valid, two positive integers. "number" will not exceed `2147483647`, "radix" will not exceed `32767`.
5. You may not use external resources, but you may use any math function included by default in your language.
**Note:** [a radix is just the base of the number.](http://en.wikipedia.org/wiki/Radix)
Sample runs:
```
16
10
false
16
3
true
16
20
true
121
10
true
5
5
false
12346
12345
true
16781313
64
true
16781313
16
true
```
[Answer]
### GolfScript, 10 characters
```
~base.-1%=
```
That is an easy one for GolfScript if we do it the straightforward way. The output is `0`/`1` for false/true.
```
~ # Take input and evaluate it (stack: num rdx)
base # Fortunately the stack is in the correct order for
# a base transformation (stack: b[])
. # Duplicate top of stack (stack: b[] b[])
-1% # Reverse array (stack: b[] brev[])
= # Compare the elements
```
[Answer]
# J (23 char) and K (19) double feature
The two languages are very similar, both in general and in this specific golf. Here is the J:
```
(-:|.)#.^:_1~/".1!:1,~1
```
* `,~1` - Append the number 1 to itself, making the array `1 1`.
* `1!:1` - Read in two strings from keyboard (`1!:1` is to read, and `1` is the file handle/number for keyboard input).
* `".` - Convert each string to a number.
* `#.^:_1~/` - `F~/ x,y` means to find `y F x`. Our `F` is `#.^:_1`, which performs the base expansion.
* `(-:|.)` - Does the argument match (`-:`) its reverse (`|.`)? `1` for yes, `0` for no.
And here is the K:
```
a~|a:_vs/|.:'0::'``
```
* `0::'``` - Read in (`0::`) a string for each (`'`) line from console (``` is the file handle for this).
* `.:'` - Convert (`.:`) each (`'`) string to a number.
* `_vs/|` - Reverse the pair of numbers, so that the radix is in front of the number, and then insert (`/`) the base expansion function `_vs` ("vector from scalar") between them.
* `a~|a:` - Assign this resulting expansion to `a`, and then check if `a` matches (`~`) its reverse (`|`). Again, `1` for yes, `0` for no.
[Answer]
## APL (20)
```
⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕
```
Outputs `0` or `1`, e.g:
```
⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕
⎕:
5
⎕:
5
0
⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕
⎕:
16781313
⎕:
64
1
```
Explanation:
* `⎕{`...`}⎕`: read two numbers, pass them to the function. `⍵` is the first number and `⍺` is the second number.
* `⌊1+⍺⍟⍵`: `floor(1+⍺ log ⍵)`, number of digits necessary to represent `⍵` in base `⍺`.
* `⍺/⍨`: the base for each digit, so `⍺` replicated by the number we just calculated.
* `⍵⊤⍨`: represent `⍵` in the given base (using numbers, so it works for all values of `⍺`).
* `≡∘⌽⍨`: see if the result is equal to its reverse.
[Answer]
## Perl, 82 77 73 69 bytes
```
$==<>;$.=<>;push(@a,$=%$.),$=/=$.while$=;@b=reverse@a;print@a~~@b?1:0
```
The input numbers are expected as input lines of STDIN and the result is written as `1` or `0`, the former meaning the first number is a palindrome in its representation of the given base.
**Edit 1:** Using `$=` saves some bytes, because of its internal conversion to int.
**Edit 2:** The smartmatch operator `~~` compares the array elements directly, thus the conversion to a string is not needed.
**Edit 3:** Optimization by removing of an unnecessary variable.
**65 bytes**: If the empty string is allowed as output for `false`, the last four bytes can be removed.
## Ungolfed version
```
$= = <>;
$. = <>;
while ($=) {
push(@a, $= % $.);
$= /= $.; # implicit int conversion by $=
}
@b = reverse @a;
print (@a ~~ @b) ? 1 : 0
```
The algorithm stores the digits of the converted number in an array `@a`.
Then the string representation of this array is compared with the array in reverse order. Spaces separates the digits.
[Answer]
## Javascript 87
```
function f(n,b){for(a=[];n;n=(n-r)/b)a.push(r=n%b);return a.join()==a.reverse().join()}
```
`n` argument is the number, `b` argument is the radix.
[Answer]
## Sage, 45
Runs in the interactive prompt
```
A=Integer(input()).digits(input())
A==A[::-1]
```
Prints `True` when it is a palindrome, prints `False` otherwise
[Answer]
### Perl ~~54 56~~ 62
```
$==<>;$-=<>;while($=){$_.=$/.chr$=%$-+50;$=/=$-}say$_==reverse
```
To be tested:
```
for a in $'16\n3' $'16\n10' $'12346\n12345' $'12346\n12346' $'21\n11' $'170\n16';do
perl -E <<<"$a" '
$==<>;$-=<>;while($=){$_.=$/.chr$=%$-+50;$=/=$-}say$_==reverse
'
done
```
will give:
```
1
1
1
```
So this output `1` for `true` when a palindrome is found and *nothing* if else.
### Ungolfing:
```
$==<>; # Stdin to `$=` (value)
$-=<>; # Stdin to `$-` (radix)
while ( $= ) {
$_.= $/. chr ( $= % $- +50 ); # Add *separator*+ chr from next modulo to radix to `$_`
$=/= $- # Divide value by radix
}
say $_ == reverse # Return test result
```
**Nota**:
* `$_` is the current line buffer and is empty at begin.
* `$=` is a *reserved* variable, originaly used for line printing, this is a line counter. So this variable is an **integer**, any calcul on this would result in a truncated integer like if `int()` was used.
* `$-` was used for fun, just to not use traditional letters... (some more obfuscation)...
[Answer]
# Mathematica ~~77~~ 43
`IntegerDigits[n,b]` represents n as a list of digits in base b. Each base-b digit is expressed decimally.
For example, 16781313 is not a palindrome in base 17:
```
IntegerDigits[16781313, 17]
```
>
> {11, 13, 15, 11, 14, 1}
>
>
>
However, it **is** a palindrome in base 16:
```
IntegerDigits[16781313, 16]
```
>
> {1, 0, 0, 1, 0, 0, 1}
>
>
>
---
If the ordered pairs in the above examples were entered,
```
(x=Input[]~IntegerDigits~Input[])==Reverse@x
```
would return
>
> False (\* (because {11, 13, 15, 11, 14, 1} != {1, 14, 11, 15, 13, 11} ) \*)
>
>
> True (\* (because {1, 0, 0, 1, 0, 0, 1} is equal to {1, 0, 0, 1, 0, 0, 1} ) \*)
>
>
>
[Answer]
**Haskell (80 chars)**
```
tb 0 _=[]
tb x b=(tb(div x b)b)++[mod x b]
pali n r=(\x->(x==reverse x))(tb n r)
```
Call it with `pali $number $radix`. True, when number is a palindrome, False if not.
[Answer]
**Ruby - 76 chars**
```
f=->(n,b){n==0?[]:[n%b,*f.(n/b,b)]};d=f.(gets.to_i,gets.to_i);p d==d.reverse
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes (22 without stdin/out)
```
say (+get).base(get)~~.flip
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVJBQzs9tURTLymxOFUDxKqr00vLySz4/9@UywgA "Perl 6 – Try It Online")
```
get() # pulls a line of stdin
+ # numerificate
( ).base(get()) # pull the radix and call base to
# convert to string with that base
~~ # alias LHS to $_ and smartmatch to
.flip # reverse of the string in $_
```
Perl6, king of readable golfs (golves?) (and also some not so readable).
# [Perl 6](https://github.com/nxadm/rakudo-pkg) function (not stdin/stdout), 22 bytes
```
{$^a.base($^b)~~.flip}
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplmr7v1olLlEvKbE4VUMlLkmzrk4vLSezoPZ/cWKlglqqhqmOkeZ/AA "Perl 6 – Try It Online")
[Answer]
# dg - 97 bytes
Trying out [dg](http://pyos.github.io/dg):
```
n,r=map int$input!.split!
a=list!
while n=>
a.append$chr(n%r)
n//=r
print$a==(list$reversed a)
```
Explained:
```
n, r=map int $ input!.split! # convert to int the string from input
a = list! # ! calls a function without args
while n =>
a.append $ chr (n % r) # append the modulus
n //= r # integer division
print $ a == (list $ reversed a) # check for palindrome list
```
[Answer]
# C, 140 132
```
int x,r,d[32],i=0,j=0,m=1;main(){scanf("%d %d",&x,&r);for(;x;i++)d[i]=x%r,x/=r;i--;for(j=i;j;j--)if(d[j]-d[i-j])m=0;printf("%d",m);}
```
* radix 1 is not supported:)
[Answer]
# Haskell - 59
Few changes to Max Ried's answer.
```
0%_=[]
x%b=x`mod`b:((x`div`b)%b)
p=((reverse>>=(==)).).(%)
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 4 bytes
```
_IjF
```
**[Try it here](https://pyth.herokuapp.com/?code=_IjF&input=16781313%2C+64&test_suite_input=16%2C+10%0A%0A16%2C+3%0A%0A16%2C+20%0A%0A121%2C+10%0A%0A5%2C+5%0A%0A12346%2C+12345%0A%0A16781313%2C+64%0A%0A16781313%2C+16%0A&debug=0&input_size=2)** or check out a **[test suite](https://pyth.herokuapp.com/?code=_IjF&input=16781313%2C+64&test_suite=1&test_suite_input=16%2C+10%0A%0A16%2C+3%0A%0A16%2C+20%0A%0A121%2C+10%0A%0A5%2C+5%0A%0A12346%2C+12345%0A%0A16781313%2C+64%0A%0A16781313%2C+16%0A&debug=0&input_size=2)** (Takes ~10-15 seconds).
[Answer]
# dc, 39 bytes
The length is a palindrome, of course (`33₁₂`).
```
[[t]pq]sgod[O~laO*+sad0<r]dsrx+la=g[f]p
```
The number and radix should be on the top of the stack (in the current number base); number must be at least 0, and radix must be at least 2. Output is `t` if it's a palindrome and `f` if not. As it's not specified in the challenge, I've assumed that numbers never have leading zeros (so any number ending in `0` cannot be a palindrome).
## Explanation
As a full program:
```
#!/usr/bin/dc
# read input
??
# success message
[[t]pq]sg
# set output radix
o
# keep a copy unmodified
d
# reverse the digits into register a
[O~ laO*+sa d0<r]dsrx
# eat the zero left on stack, and compare stored copy to a
+ la=g
# failure message
[f]p
```
[Answer]
# LaTeX, 165 bytes
[Example at desmos.com](https://www.desmos.com/calculator/6unjzuuvtk)
`k`, the radix, is an adjustable input
```
b=\floor \left(\log _k\left(\floor \left(x\right)\right)\right)
f\left(x\right)=k^bx-x-\left(k^2-1\right)\sum _{n=1}^bk^{\left(b-n\right)}\floor \left(xk^{-n}\right)
```
If `f(x)=0`, `x` is a palindrome in base `k`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 34 bytes
*-4 bytes thanks to PhilH*
```
{@(polymod $^a: $^b xx*)~~[R,] $_}
```
[Try it online!](https://tio.run/##XYzBasMwEETv@xV7CLXdCMWSEre0uOQbSm9GDW4rl4ASGcmBhBD9uruqcQ9lYZgZ3mxvvK3GwwXvOqzH6zbvnb0c3Bcu3tsnkg88n@@LGJtXpnGxu42nYPDNhOEZgFbbgWzAGu3@aAL/9qbPV3xVcO8G53NVENbb9ojLiaTYOT/ProC4Dxi7fMmbUjNSoQtuPxlvpGaYypixLKY@Zli/YPJSw20UFYgSutYGA0BBweBPk5Xl7KVI0BQ2dDMu1br61c3f6uFRKKGgWv9v6GFqfgA "Perl 6 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~4~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
вÂQ
```
[Try it online](https://tio.run/##MzBNTDJM/f//wqbDTYH//xsaGZuYcoFIMwA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/hpuRZrKBk7@lir6SQmaeQlFicqgvlJioUJOZk5qUU5eem2isoPGqbpABU@f/CpsNNgf91/huacRkacAFJYxBhBGQaGYJETIHQ0MjYxAxMAtlm5haGxobGXGYmCLahGQA).
**Explanation:**
```
в # The first (implicit) input converted to base second (implicit) input
# i.e. 12345 and 12346 → [1,1]
# i.e. 10 and 16 → [1,6]
 # Bifurcate the value (short for duplicate & reverse)
# i.e. [1,1] → [1,1] and [1,1]
# i.e. [1,6] → [1,6] and [6,1]
Q # Check if they are still the same, and thus a palindrome
# i.e. [1,1] and [1,1] → 1
# i.e. [1,6] and [6,1] → 0
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 79 bytes
```
n,r,m;main(o){for(scanf("%d %d",&n,&r),o=n;n;n/=r)m=m*r+n%r;printf("%d",m==o);}
```
[Try it online!](https://tio.run/##HcpBCoAgEADAe68IwdDaCAkqkH2MKEWHXWPrFr3dIuY6sd9iLIVBgDyFnU2295rFnDHwapROtU4KGoZGLGRk/xlQLCG10rEWf8jO118VEGK2/inFTfPiRjdWbnoB "C (gcc) – Try It Online")
## Rundown
```
n,r,m;main(o){
for(scanf("%d %d",&n,&r), Read the number and the radix.
o=n; ...and save the number in o
n; Loop while n is non-zero
n/=r) Divide by radix to remove right-most digit.
m=m*r+n%r; Multiply m by radix to make room for a digit
and add the digit.
printf("%d",m==o);} Print whether we have a palindrome or not.
```
Based on the fact that for a palindrome, the reverse of the number must equal the number itself.
Suppose you have the three-digit number ABC in some base. Multiplying it by base will always result in ABC0, and dividing it by base in AB with C as remainder. So to reverse the number we pick off the right-most digit from the original number and insert it to the right on the reversed number. To make room for that digit, we multiply the reverse by base before-hand.
Basically:
```
n rev
ABC 0
AB C
AB C0
A CB
A CB0
0 CBA
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
bŒḂ
```
[Try it online!](https://tio.run/##y0rNyan8/z/p6KSHO5r@H16u9P@/oZmOAhwbGeoomIJoYxOwkLmFobGhMYL139BARwHINwJSICZULZAyMwGpAgA "Jelly – Try It Online")
## How it works
```
bŒḂ - Main link. Takes a number n on the left and a radix r on the right
b - Convert n to base r
ŒḂ - Is palindrome?
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~167~~ ~~162~~ ~~65~~ 63 bytes
```
a,b=map(int,open(s:=0))
o=a
while a:s=s*b+a%b;a//=b
print(s==o)
```
[Try it online!](https://tio.run/##DcpBCoAgEADAu6/oEmgJJYKFsY/ZhaCgdFEhev3WnIffduTkVy4iaAluZH2mZjPvSdcIszEqA6rnOK@9w1ihDjRiTxtOE5Di8m9dAbIRcWFZnXdeuSDyAQ "Python 3.8 (pre-release) – Try It Online")
Massive -99 thx to @Steffan
] |
[Question]
[
Your toy in this challenge is a special abacus of 4 rows and 8 positions per row. There's one bead on the first row, 2 beads on the 2nd row, 3 beads on the 3rd row and 4 beads on the 4th row. Beads on a same row are glued together, which means that they can only be moved as a block.
Below is a valid configuration of the abacus:
```
---O----
------OO
-OOO----
---OOOO-
```
Of course, a block cannot be moved beyond the edges of the abacus. So there are 8 possible positions for the block on the first row and only 5 for the block on the last row.
## Task
You'll be given a list of 8 non-negative integers representing the total number of beads in each column of the abacus. Your task is to output the number of configurations that lead to this result.
## Examples
If the input is \$[4,3,2,1,0,0,0,0]\$, the only possible way is to put all blocks at the leftmost position:
```
O-------
OO------
OOO-----
OOOO----
________
43210000
```
If the input is \$[1,0,0,1,2,3,2,1]\$, there are **2** possible configurations:
```
O------- O-------
----OO-- -----OO-
-----OOO ---OOO--
---OOOO- ----OOOO
________ ________
10012321 10012321
```
If the input is \$[1,1,1,2,2,2,1,0]\$, there are **13** possible configurations. Below are just 4 of them:
```
O------- ---O---- ---O---- ------O-
-OO----- ----OO-- ----OO-- OO------
---OOO-- OOO----- ----OOO- ---OOO--
---OOOO- ---OOOO- OOOO---- --OOOO--
________ ________ ________ ________
11122210 11122210 11122210 11122210
```
## Rules
* You can assume that the input is valid: all values are in \$[0\dots4]\$, their sum is \$10\$ and at least one configuration can be found.
* You can take the input list in any reasonable format (array, string of digits, etc.).
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
[4,3,2,1,0,0,0,0] -> 1
[1,1,1,2,0,2,2,1] -> 1
[1,0,0,1,2,3,2,1] -> 2
[1,1,2,2,2,1,0,1] -> 3
[0,2,2,2,2,2,0,0] -> 4
[0,0,0,1,2,2,3,2] -> 5
[1,1,1,1,1,1,2,2] -> 6
[0,2,2,2,2,1,1,0] -> 8
[1,1,1,2,2,1,1,1] -> 10
[1,1,2,2,2,1,1,0] -> 12
[1,1,1,2,2,2,1,0] -> 13
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
żJØ.xⱮS
8Ḷṗ4Ç€ċ
```
[Try it online!](https://tio.run/##y0rNyan8///oHq/DM/QqHm1cF8xl8XDHtoc7p5scbn/UtOZI938w/f9/NFe0iY6xjpGOYawOV7ShDgga6RgAMVzIAAhBgiiqjCAqQFIgIQOoABBCuDBNYG0Io2EWGKFqMkS13giiDt0uNDUQ18QCAA "Jelly – Try It Online")
Takes input without trailing zeros.
## Explanation
```
żJØ.xⱮS Auxiliary monadic link, taking a list of 4 integers
ż Zip with
J indices: [1,2,3,4]
x Repeat
Ø. [0,1]
[a,b] times respectively
Ɱ for each [a,b] in the list
S Sum
8Ḷṗ4Ç€ċ Main monadic link, taking a list of integers
8 8
Ḷ Lowered range: [0,1,2,3,4,5,6,7]
ṗ4 Cartesian 4th power
Ç Apply the auxiliary link
€ to each
ċ Count the occurences of the input
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~33~~ ~~32~~ ~~31~~ 25 bytes
```
8:KZ^!"8:@<1M-K:!<<sGX=vs
```
[Try it online!](https://tio.run/##y00syfn/38LKOypOUcnCysHG0FfX20rRxqbYPcK2rPj//2hDHRA0AkNDHYNYAA "MATL – Try It Online") (but it takes around 50 seconds, and it sometimes times out).
### Explanation
The code `8:` generates the vector `[1 2 ··· 8]`. `K` pushes `4`, `Z^` computes the Cartesian power, and `!` transposes. So this gives the following matrix, of size `4`×`4096`:
```
[1 1 ··· 8 8;
1 1 ··· 8 8;
1 1 ··· 8 8;
1 2 ··· 7 8]
```
Each column represents a possible abacus configuration, defined by the position of the leftmost bead in each row. Some configurations are impossible (for example, values above `5` in the last row are not allowed), but this isn't a problem because the result computed from these configurations will never coincide with the input.
The loop `"` takes each column of this matrix. `8:` pushes `[1 2 ··· 8]` onto the stack, and `@` pushes the current column, say `[1; 1; 1; 1]` in the first iteration. `<` compares these two vectors, of sizes 1×8 and 4×1, element-wise with singleton expansion. This gives a 4×8 matrix with all the comparisons, in this case (\*)
```
[0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0]
```
Then, `1M` pushes the two vectors again and `-` subtracts them element-wise with singleton expansion. This gives, in this case
```
[0 1 2 3 4 5 6 7;
0 1 2 3 4 5 6 7;
0 1 2 3 4 5 6 7;
0 1 2 3 4 5 6 7]
```
`K:!` pushes the column vector `[1; 2; 3; 4]`, and `<` compares the previous matrix with this vector, again element-wise with singleton expansion. The result is (\*\*)
```
[1 0 0 0 0 0 0 0;
1 1 0 0 0 0 0 0;
1 1 1 0 0 0 0 0;
1 1 1 1 0 0 0 0]
```
Now `<` compares matrices (\*) and (\*\*) element-wise. The result will give `1` at entries where the first matrix has a `0` and the second has a `1`. The result represents the beads in the abacus for the current configuration:
```
[1 0 0 0 0 0 0 0;
1 1 0 0 0 0 0 0;
1 1 1 0 0 0 0 0;
1 1 1 1 0 0 0 0]
```
`s` computes the sum of each column: `[4 3 2 1 0 0 0 0]`. Then `GX=` compares this with the input vector. (Note that non-valid abacus configurations such as `[8; 8; 8; 8]` will produce less then `10` entries equal to `1` in the matrix above, and so will never give a result matching the input.) The result is `1` if both vectors are equal or `0` otherwise. `vs` adds this to the accumulated sum of previous iterations.
The final sum is implicitly printed at the end.
[Answer]
# [J](http://jsoftware.com/), 42 41 40 bytes
*-1 thanks to Jonah!*
```
1#.(1680+/@((#:~8&-)I.@,.1+])"{&i.4)e.,:
```
[Try it online!](https://tio.run/##bZDLCoMwEEX3fsWgYBLUNA8rklIQCoVCV913VZS2my50V@ivpzEP@1AHIXDmnszkrmOKOtgqQJADA2X@gsLudNxrnlDMq5plqwbjRL3qtCAH2uSUZ2cSP9MbLUlLc6VJFLWX6wPwpiPAbQlT9uQIGtp@6KEwH/K9HZQgbRdzRaBQod/Q4GHONaNjZuRyouInK/wMzFM5UeaZsHZ3b/lFg9m6LV3/TTXtaGm1YB65M9ezjfzLuI3Y4tAhzMVCWnyw1G8 "J – Try It Online")
* `1680 f"{&i. 4` for each `i` in `0…1679` and `0 1 2 3` run …
* `(#:~8&-)` `i` mixed-base-converted with bases `8 - 0 1 2 3 = 8 7 6 5` so we get every possible configuration, f.e. `2 1 0 1`.
* `,.1+]` append item-wise `1 + 0 1 2 3 = 1 2 3 4`: `2 1, 2 2, 0 3, 1 4`.
* `I.@` for each pair, take that many 0s and 1s (`_` filled with 0s):
```
2 1: 0 0 1 _ _
2 2: 0 0 1 1 _
0 3: 1 1 1 _ _
1 4: 0 1 1 1 1
```
* `+/@` sum `1 2 4 2 1` – because we get every possible configuration, J automatically pads the arrays to length of 8.
* `1#. … e.,:` count the occurrences of the input.
[Answer]
# [Python 3](https://docs.python.org/3/), 72 bytes
```
f=lambda a,n=4:n==a or sum(f(a-int(n*"1"+i*"0"),n-1)for i in range(n*8))
```
[Try it online!](https://tio.run/##ZY0xDsIwDEV3ThFlSkor2U4HhJTDGEEgEnWrtgycPiQDUtP@8fn97@m7vkZxKQX/5uF2Z8Wt@P4q3rMaZ7V8BhMMd1FWI41GfY6NBm1b6dCGLEQVRc0sz0e@X6xN01zcYHpHCDnWnv4IEQmIcIsAkFyNkLIDW0Ql9RTlVj1d1mlXQtz/z@j47GhRQekH "Python 3 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 75 bytes
```
[sum(int(-~j*"1"+n/8**j%8*"0")for j in range(4))for n in range(8**4)].count
```
[Try it online!](https://tio.run/##ZY1BDsIgFET3noKQmABG5f@y6MaTqAtjREvip6F04carI5gYSzvLl5k3/Ss@PGGyh1M6DuNTdBTF9u0UB76hfauUW7eKay6tD8yxjli40P0mjPwS@pPcNfK8u/qRYupDEVlhGgSdI@XqhwAANSJMkdaATY0Ac0dPEZbUKsyrWl3sOBsBzP8zWp4tW1hQ@gA "Python 2 – Try It Online")
This is an expression evaluated to an unnamed function. You can assign it to `f` by prepend `f=`, and then use it as `f(43210000)`. It takes input as a single integer. For example, `[4,3,2,1,0,0,0,0]` becomes `43210000` while `[0,0,0,1,2,2,3,2]` becomes `12232`.
It is interesting that you don't need `lambda` nor `def` to define a function in Python.
[Answer]
# [Haskell](https://www.haskell.org/), 88 bytes
```
0#t=[1|all(==0)t]
m#t=do k<-[0..7];(m-1)#[r-sum[1|j>k,j<=k+m]|(j,r)<-zip[1..]t]
sum.(4#)
```
[Try it online!](https://tio.run/##LYvLCgIhFED3fUVgCyW9XCNokbcfERdCDfmaGRzbxPy7uYizO5zz9lt65dw7skZW7z5nToSiuUMZ5rkck1EWAW7uzovSgtmqtk8ZaXwkGQ2lc3E7j7IKo75htRrAjXuiUQG/MtGLDzOtNcztNFmUlz96gK7/AA "Haskell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ 26 bytes
```
I№E׳φΣE⁴×Xχ﹪÷ιX⁸λ⁸÷Xχ⊕λ⁹N
```
[Try it online!](https://tio.run/##RYtNCsMgFISv4vIFXkFtFyldtpssUgLtBawKFfwJRtPjW00WmcUwzDcjvyLKIGwpUzQ@wV0s1UKucRQzvI3TC5yRMEpph@SV3dZfkOxoCj8dgVEkY1DZBhh8epjVKA0GyU57JLar577ZwY/r4GXUTvukFWzLa9fUwJzTM7tPHbbmVgpjjHPOaDmt9g8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of 8 digits. Explanation: Simply generates the column sums of all configurations and counts the number that match.
```
E׳φ Consider 3,000 configurations
E⁴ Consider 4 rows
÷Xχ⊕λ⁹ Row mask
× Multiplied by
Xχ Shift given by
﹪÷ιX⁸λ⁸ Current base 8 digit
Σ Take the (column) sum
№ Count matches of
N Input cast to integer
I Cast to string
Implicitly print
```
There are only 1680 true configurations but without mixed base conversion they won't be consecutive; in base 8 the last configuration is 2423 but obviously 3000 is golfier (any value up to 4096 would work). The row mask is simply a string of `1`s representing the `O`s, with a shift that represents the number of trailing `0`s representing the `-`s (the leading `-`s are implied). Since the column sums won't be higher than 4 the masks can simply be added as decimal integers (golfier than base 5 of course). False configurations will result in a value greater than 43,210,000 so they which will never match a legal input value.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Started looking for ways to golf [xigoi's great Jelly answer](https://codegolf.stackexchange.com/a/230772/53748) but it took a fair bit of effort so thought I'd post instead.
```
8ṗ4+"JḶ$ṬSƲ€ċ
```
A monadic Link that accepts the list (using the no-trailing zeros option) and yields the count.
**[Try it online!](https://tio.run/##y0rNyan8/9/i4c7pJtpKXg93bFN5uHNN8LFNj5rWHOn@//9/tKEOCBqBoWEsAA "Jelly – Try It Online")**
### How?
```
8ṗ4+"JḶ$ṬSƲ€ċ - Link: list of non-negative integers, Totals
8 - eight
4 - four
ṗ - ([1..8]) Cartesian power (4) -> all length 4 lists using [1..8]
€ - for each (list of four "start indices", I, in that):
Ʋ - last four links as a monad - f(I):
$ - last two links as a monad - g(I):
J - range of length -> [1,2,3,4]
Ḷ - lowered range -> [[0],[0,1],[0,1,2],[0,1,2,3]]
" - (I) zip (that) with:
+ - addition -> [[0+i1],[0+i2,1+i2],[0+i3,1+i3,2+i3],[0+i4,1+i4,2+i4,3+i4]]
Ṭ - un-truth -> [[0...0,1],[0...0,1,1],[0...0,1,1,1],[0...0,1,1,1,1]]
(number of zeros being i1-1, i2-1, i3-1, and i4-1 respectively)
S - sum (column-wise)
ċ - count occurrences (of the input list, Totals)
```
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
(1111%)
0%0=1
0%_=0
k%n=sum[div k 10%(n-k*10^i)|i<-[0..7]]
```
[Try it online!](https://tio.run/##bY65DoJQEEV7vmIKScAEMjPgUvi@BNEQEH1hkYha@e0@B7BhucU0J/fMvSVtcSlLk6ujcUhiuxbaqEjuWaFV2LVqX1WU6TcUQGg7tVesCU/a/eiDF6Hv7@LYVImuQUF2twCah66fsIIcwoAJJaAU0IjII0ZmWiCIxMFAeNJhaWBPghERk2T4E45JZxNdRzbTBd2InmznNqLetp@tFjKsxoVxQ4l43uI/Csw3zcvk2hovbZof "Haskell – Try It Online")
`(1111%)` is the main function. It takes input as an integer, e.g. `(1111%) 11122210 == 13`.
This essentially counts solutions to $$1111a+111b+11c+d=n$$ where \$a,b,c,d\$ range over \$10^0, 10^1 \dots 10^7\$.
[Answer]
# Python 3, 136 bytes
Takes input as an integer (i.e. no leading zeroes). Generates all possible configurations of the abacus, filters down to only those matching the input, returns the count. Loses 23 byes on the itertools import.
```
lambda n:sum([x==n for x in map(sum,product(*([int('1'*i+'0'*(8-j-i))for j in range(9-i)]for i in range(1,5))))])
from itertools import*
```
[Try it online!](https://tio.run/##XZBfa8IwFMXf8ynuizTpIiSpDifkQZywwf74UGGgZWTabhWbljQO9@m7pFrLdp9yfufce3tb/divUkdNJjfNQRUfOwV6Wh8LvD5JqSErDZwg11CoCjtMK1PujluLQ7zOtcUBD8L8JmBBiCfD/TAnxHfsfYdR@jPFd44lnuU943RMXCUEZaYsILepsWV5qCEvqtLYsLFpbbeqTmuQsEZ4FAnOXFHghCLMORdMCN5JxriIvBRnVziPORl5KXz51lFrCpekML6M8ZOcvO2CnLvgpNvhpN/B@qne5uLqi1ZHBCUItSfq9291oJCeKv/wB18vmSJQW9tiCRk@RwmCyrS/cRiEE9bLx5flKnbBQb3Ri7flYh4v7uF1Ffd0No9Xs6e/7HkWzx/adzDA/z6GduuvRMoLIaT5BQ "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `R`, 23 bytes
```
8:Ẋ:Ẋvfƛ‹↵\1dd¦vI*∑⁰=;∑
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=R&code=8%3A%E1%BA%8A%3A%E1%BA%8Avf%C6%9B%E2%80%B9%E2%86%B5%5C1dd%C2%A6vI*%E2%88%91%E2%81%B0%3D%3B%E2%88%91&inputs=10012321&header=&footer=)
A messy attempted port of Lynn's answer.
] |
[Question]
[
In this challenge, bots (consisting of JS functions) move around an infinite factory (playing field), collecting characters. These characters can be used to build worker bots, or dropped for other bots to pick up.
This challenge is a modified redo of [Bot Factory KoTH](https://codegolf.stackexchange.com/questions/201057/bot-factory-koth), which was broken by a mistake in the spec.
## Results
```
[39599.65] Ghost
[12251.15] Shy Guy
[8565.70] Camper
[8339.95] Honnold
[2862.50] True Neutral
[51.575] Rabbit
[10.65] Centrist
[-8.85] The Luggage
[-66.075] The Caveman
```
The bounty went to **@Razetime**, as their bots were consistently in the lead until Shy Guy showed up.
Feel free to keep posting bots, but the scoring might not get updated.
## The Factory
All bots start out randomly placed around the center of the factory, `[0, 0]`, where coordinates are arrays `[x, y]`. North is -Y, and west is -X. Each round consists of up to 100000 turns. A bot may move one space in any cardinal direction (or build a worker, or drop a character) per turn.
Bots can move by returning `north()`, `east()`, `south()`, or `west()`.
## Characters
Characters will be randomly distributed, centered around `[0, 0]`. There are always up to a total of 4 characters per bot at any given time (excluding those from dead bots).
Character's positions may overlap, and their character value (such as `a` or `(`) is selected from a pool of the source code of every bot and worker currently in the factory.
Bots collect characters by moving into the same position in the factory, and these collected characters are stored within the bot.
Bots may also drop a character they have previously collected in any of the four cardinal directions. This character is then removed from the bot's collected characters array.
Bots drop characters by returning `drop.north(c)`, `drop.east(c)`, `drop.south(c)`, or `drop.west(c)`, where `c` is a string.
## Score
Bots have a score, which is initially `-floor(LEN / 2)`, where `LEN` is the length of the bot's source code in characters. Worker bots start with a score of 0 regardless of their length.
Whenever a character is collected, this score value increments; when a character is dropped, it decrements.
## Collisions
When two or more bots collide (occupy the same position), whichever has the highest score survives (if there is a tie, none survive). All bots that die "drop" the characters they have collected, which are randomly distributed centered around the position they collided in.
Bots can switch places by moving into each others' previously occupied positions without colliding. Bots can collide with their own workers.
## Workers
Bots can use the characters they have collected to build a worker bot. A worker bot's source code (provided as a function or arrow function) must be entirely made up of characters its owner has collected, which are then removed. Half of the length of the worker's source code is deducted from the owner's score.
Worker bots are placed randomly around the position of their owner, using the same system as characters, and are not immune to collision. Worker bots can also build worker bots, whose owner would be the worker.
Workers can be built by returning the result of the function `build(source)`, where `source` is a string. If the bot cannot be built (such as not having all necessary characters), nothing happens.
## Functions
All bots are functions. They are provided a single argument, an object that can be used for storage, and can access information about other bots and characters using the following functions:
* `bots()`: Returns an array of bots (as objects)
* `chars()`: Returns an array of characters (as objects)
* `self()`: Returns the bot that called it (as an object)
* `owner()`: Returns the owner of the bot that called it (as an object, `null` if owner is dead, or `self()` if no owner)
A bot object has the following properties:
* `uid`: An integer ID unique to each bot, randomly selected
* `owner`: The UID of the bot's owner
* `score`: The score of the bot
* `pos`: The position of the bot formatted as `[x, y]`
A bot object also has the following properties if it is the owner or worker of the bot:
* `chars`: An array of characters the bot has collected
* `source`: A string with the bot's source code
A character object has the following properties:
* `char`: A string
* `pos`: The position of the character formatted as `[x, y]`
There are also the following library functions:
* `center()`: Get average of bots' positions weighted by score
* `turn()`: Get current turn (starts at 0)
* `at(pos)`: Returns an object:
+ `bot`: The `uid` of the bot at that location, or `null` if there is none
+ `chars`: An array of characters at that location
* `dir(from, to)`: Get direction from `from` to `to`, which should be arrays formatted `[x, y]`
* `dirTo(pos)`: Same as `dir`, uses `self().pos` as `from`
* `dist(from, to)`: Get taxicab distance from `from` to `to`, which should be arrays formatted `[x, y]`
* `distTo(pos)`: Same as `dist`, uses `self().pos` as `from`
## Winning
Once all surviving bots are direct or indirect workers of the same initial bot, characters will no longer generate. Games automatically end when all characters are collected.
At the end of a game, all bots' scores (including their workers) are added up for each round with the highest winning.
## Rules
* Bots may not use global variables in a way which produces side effects other than intended (such as to sabotage other bots or the controller, or communicate with any other bots)
* Bots which error will be killed and drop their characters
* Bots may only attempt to build workers which are valid functions
* Bots may not take an unnecessarily long time to run (no hard limitation, but be reasonable)
* Bots may not team with other which do not originate from the same owner (directly or not)
## Technical Notes
* Character and bot spawning radius is based on a geometric distribution (`p=0.1`), with a random angle. The resulting coordinates are truncated to integers. Repeated until a position is found with no bots within a taxicab distance of 4
* For dead bots' drops, `p=0.2` and there is no distance requirement
* For worker bot spawning, minimum taxicab distance is 3 for the owner
* Every time a character is picked up, one attempt is made to generate another. An attempt will only fail if there are already `4 * botCount` characters not dropped by a bot (or a bots' death), where `botCount` is the total number of alive bots (including workers). `4 * botCount` characters are generated at the start.
## Example Bot
ExampleBot uses an arrow function to keep its starting score higher, but still isn't well golfed. It likes characters which are in the middle of the action, which it finds by sorting the `chars()` array and using the `dist` and `center` library functions. It will not be included in the competition game.
```
() => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)
```
## Other
**Chat:** <https://chat.stackexchange.com/rooms/118871/bot-factory-koth-2-0>
**Controller:** <https://gist.github.com/Radvylf/4d9915632fed1b4d7a7e9407e2a38edf>
[Answer]
# The Caveman (151 bytes)
This is Caveman. Very primitive. Hunt if strong. Eat if weak. Ooga-Booga.
```
{
name: "The Caveman",
color: "#FF0000",
run:()=>{w=bots().sort((a,b)=>a.score-b.score)[0];return self().score<=w.score?dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos):dirTo(w.pos)}
}
```
Try against a bunch of Honnolds:
```
var botData = [
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "The Caveman",
color: "#FF0000",
run:()=>{w=bots().sort((a,b)=>a.score-b.score)[0];return self().score<=w.score?dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos):dirTo(w.pos)}
},
{
name: "The Caveman",
color: "#FF0000",
run:()=>{w=bots().sort((a,b)=>a.score-b.score)[0];return self().score<=w.score?dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos):dirTo(w.pos)}
},
{
name: "The Caveman",
color: "#FF0000",
run:()=>{w=bots().sort((a,b)=>a.score-b.score)[0];return self().score<=w.score?dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos):dirTo(w.pos)}
}
];
{
var game = {
randPos: (center, any = !1, uid = 0, owner = 0, p = 0.1) => {
var theta, radius, pos;
do {
theta = Math.random() * Math.PI * 2;
radius = 0;
while (Math.random() > p)
radius++;
pos = [Math.trunc(center[0] + Math.cos(theta) * radius), Math.trunc(center[1] + Math.sin(theta) * radius)];
} while (!any && game.bots.find(a => a && a.uid != uid && Math.abs(a.pos[0] - pos[0]) + Math.abs(a.pos[1] - pos[1]) < (a.uid == owner ? 3 : 4)));
return pos;
},
debug: function(){},
log: 0 // 0 = NONE, 1 = SUMMARY, 2 = ALL
};
var north = () => ["north"];
var east = () => ["east"];
var south = () => ["south"];
var west = () => ["west"];
var build = code => ["worker", code];
var drop = {
north: char => ["drop.north", char],
east: char => ["drop.east", char],
south: char => ["drop.south", char],
west: char => ["drop.west", char]
};
var bots = () => game.bots.map(a => ({
uid: a.uid,
owner: a.owner,
original: a.original,
score: a.score,
pos: [...a.pos],
chars: game.uid == a.uid ? [...a.chars] : undefined,
source: game.uid == a.uid ? a.source : undefined
})).sort((a, b) => a.uid - b.uid);
var chars = () => game.chars.map(a => ({
char: a.char,
pos: [...a.pos]
}));
var self = () => {
var bot = game.bots.find(a => a.uid == game.uid);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var owner = () => {
var bot = game.bots.find(a => a.uid == game.bots.find(b => b.uid == game.uid).owner);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var center = () => game.center;
var turn = () => game.turns;
var at = pos => ({
bot: (game.bots.find(b => b.pos[0] == pos[0] && b.pos[1] == pos[1]) || {uid: null}).uid,
chars: chars().filter(c => c.pos[0] == pos[0] && c.pos[1] == pos[1])
});
var dir = (posFrom, pos) => {
if (Math.abs(posFrom[0] - pos[0]) <= Math.abs(posFrom[1] - pos[1]))
return posFrom[1] < pos[1] ? ["north"] : ["south"];
else
return posFrom[0] < pos[0] ? ["west"] : ["east"];
};
var dirTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
if (Math.abs(pos[0] - bot.pos[0]) <= Math.abs(pos[1] - bot.pos[1]))
return pos[1] < bot.pos[1] ? ["north"] : ["south"];
else
return pos[0] < bot.pos[0] ? ["west"] : ["east"];
};
var dist = (posFrom, pos) => {
return Math.abs(posFrom[0] - pos[0]) + Math.abs(posFrom[1] - pos[1]);
};
var distTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
return Math.abs(pos[0] - bot.pos[0]) + Math.abs(pos[1] - bot.pos[1]);
};
async function runRound(turns = 100000) {
var uids = [];
game.perf = performance.now();
for (let i = 1; i <= botData.length; i++)
uids[i - 1] = i;
for (let j, i = uids.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
[uids[i], uids[j]] = [uids[j], uids[i]];
}
game.bots = [];
game.chars = [];
game.records = game.records || [];
game.uids = [];
for (let i = 0; i < botData.length; i++) {
game.bots[i] = {
uid: uids[i],
owner: uids[i],
original: uids[i],
score: Math.floor(botData[i].run.toString().length * -1 / 2),
chars: [],
pos: game.randPos([0, 0]),
source: botData[i].run.toString(),
run: botData[i].run,
storage: {},
name: botData[i].name || "Bot",
color: botData[i].color || "#000000"
};
game.uids[uids[i]] = i;
game.records[i] = game.records[i] || 0;
}
game.center = [
game.bots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0),
game.bots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = game.bots.map(a => a.source).join("");
for (let i = 0; i < botData.length * 4; i++)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.cuid = botData.length + 1;
game.turns = 0;
if (!game.fps) {
while (game.chars.length && game.bots.length && game.turns < turns) {
runTurn();
game.turns++;
}
} else {
game.debug();
while (game.chars.length && game.bots.length && game.turns < turns) {
await new Promise(function(resolve) {
setTimeout(resolve, 1000 / game.fps);
});
if (!game.pause) {
runTurn();
game.debug();
game.turns++;
}
}
}
bots().map(b => game.records[game.uids[b.original]] += b.score);
if (game.log)
console.log("Round Completed (" + ((performance.now() - game.perf) / 1000).toFixed(3) + "s):\n" + game.bots.map(a => a).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join("\n"));
}
function runTurn() {
var cbots = [];
var npos = [];
var nposl = [];
var nbots = [];
for (let b, p, m, i = 0; i < game.bots.length; i++) {
b = game.bots[i];
game.uid = b.uid;
try {
m = b.run(b.storage);
} catch(e) {
m = ["dead"];
if (game.log == 2)
console.warn("[" + game.turns + "] Error: " + b.name + "\n" + (e.stack || e.message));
for (let j = 0; j < b.chars.length; j++)
game.chars.push({
char: b.chars[j],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
}
if (!Array.isArray(m))
m = [];
if (m[0] == "north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "west")
p = [b.pos[0] - 1, b.pos[1]];
else
p = [...b.pos];
if (m[0] != "dead")
npos.push({
bot: b.uid,
pos: p
});
if (m[0] == "worker" && m[1].split("").reduce((c, d, e) => d && (e = c.indexOf(d)) != -1 ? c.filter((f, g) => g != e) : null, [...b.chars])) {
p = game.randPos(b.pos, !1, 0, b.uid);
try {
cbots.push({
uid: game.cuid,
owner: b.uid,
original: b.original,
score: 0,
chars: [],
pos: p,
source: m[1],
run: eval(m[1]),
storage: {},
name: b.name + "*",
color: b.color
});
npos.push({
bot: game.cuid++,
pos: p
});
b.score -= Math.floor(m[1].length / 2);
for (let n, j = 0; j < m[1].length; j++) {
n = b.chars.indexOf(m[1][j]);
b.chars = b.chars.slice(0, n).concat(b.chars.slice(n + 1));
}
if (game.log == 2)
console.log("[" + game.turns + "] New Worker: " + b.name);
} catch(e) {
if (game.log == 2)
console.warn("[" + game.turns + "] Invalid Worker: " + b.name + "\n" + (e.stack || e.message));
}
}
if (typeof m[0] == "string" && m[0].match(/^drop.(north|east|south|west)$/) && b.chars.includes(m[1])) {
b.score--;
for (let j = 0; j < b.chars.length; j++) {
if (b.chars[j] == m[1]) {
b.chars = b.chars.slice(0, j) + b.chars.slice(j + 1);
break;
}
}
if (m[0] == "drop.north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "drop.east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "drop.south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "drop.west")
p = [b.pos[0] - 1, b.pos[1]];
game.chars.push({
char: m[1],
pos: p,
game: !1
});
}
}
game.bots.push(...cbots);
for (let f, i = 0; i < npos.length; i++) {
if (!(f = nposl.find(a => a.pos[0] == npos[i].pos[0] && a.pos[1] == npos[i].pos[1])))
nposl.push(f = {
pos: [...npos[i].pos],
bots: []
});
f.bots.push(npos[i].bot);
}
for (let n, m, b, i = 0; i < nposl.length; i++) {
n = nposl[i];
if (n.bots.length > 1) {
m = Math.max(...n.bots.map(a => game.bots.find(b => b.uid == a).score));
if (game.bots.filter(a => n.bots.includes(a.uid) && a.score == m).length > 1) {
m += 1;
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
} else {
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
}
for (let j = 0; j < n.bots.length; j++) {
b = game.bots.find(a => a.uid == n.bots[j]);
if (b.score < m)
for (let k = 0; k < b.chars.length; k++)
game.chars.push({
char: b.chars[k],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
else
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
} else {
b = game.bots.find(a => a.uid == n.bots[0]);
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
game.center = [
nbots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0),
nbots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = nbots.map(a => a.source).join("");
for (let b, c, i = 0; i < game.chars.length; i++) {
c = game.chars[i];
if (b = nbots.find(a => a.pos[0] == c.pos[0] && a.pos[1] == c.pos[1])) {
b.score++;
b.chars.push(c.char);
if (c.game && game.chars.filter(a => a && a.game).length < nbots.length * 4 && game.bots.map(a => a.original).reduce((a, b) => a.includes(b) ? a : a.concat(b), []).length > 1)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.chars[i] = null;
}
}
game.chars = game.chars.filter(a => a);
game.bots = nbots;
};
function drawRound(turns = 100000, log = 2, fps = 60, zoom = 50){
var c, ctx, wdim, scale;
document.body.innerHTML = "<canvas></canvas>";
c = document.body.firstChild;
c.style.position = "absolute";
c.style.top = "0";
c.style.left = "0";
c.style.zIndex = "2";
ctx = c.getContext("2d");
game.records = new Array(botData.length).fill(0);
game.log = log;
game.pause = !1;
game.fps = fps;
(window.onresize = function() {
wdim = [window.innerWidth || 600, window.innerHeight || 400];
scale = Math.ceil(wdim[1] / zoom);
c.width = wdim[0];
c.height = wdim[1];
})();
window.onkeydown = function() {
var key = event.code;
if (key == "Escape")
game.pause = !game.pause;
if (key == "ArrowLeft" && game.fps > 1)
game.fps -= 1;
if (key == "ArrowRight")
game.fps += 1;
};
game.debug = function() {
ctx.clearRect(0, 0, wdim[0], wdim[1]);
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = Math.floor(scale * 0.6) + "px monospace";
for (let x = -Math.ceil(wdim[0] / 2 / scale), i = wdim[0] / 2 - (Math.ceil(wdim[0] / 2 / scale) - 0.5) * scale; i <= wdim[0]; i += scale, x++) {
for (let b, c, y = -Math.ceil(wdim[1] / 2 / scale), j = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; j <= wdim[1]; j += scale, y++) {
if ((c = game.chars.filter(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))).length) {
for (let k = 0; k < c.length; k++)
ctx.fillText(JSON.stringify(c[k].char).slice(1, -1).replace(/\\"/, "\"").replace(/\\\\/, "\\").replace(/ /, "_"), i + scale / 2, j + scale / 2);
}
if (b = game.bots.find(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))) {
ctx.fillStyle = b.color;
ctx.fillRect(i, j, scale, scale);
ctx.fillStyle = "#000000";
}
}
ctx.lineWidth = 0.1;
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, wdim[1]);
ctx.stroke();
}
for (let i = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; i <= wdim[1]; i += scale) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(wdim[0], i);
ctx.stroke();
}
ctx.fillRect(wdim[0] / 2 - 3, wdim[1] / 2 - 3, 7, 7);
};
runRound(turns);
}
function runGame(rounds = 1, turns = 100000, log = 0) {
game.records = new Array(botData.length).fill(0);
game.log = log;
for (let i = 0; i < rounds; i++)
runRound(turns, 0);
console.log("Game Conclusion:\n" + botData.map((a, b) => [a.name, game.records[b]]).sort((a, b) => b[1] - a[1]).map(a => "[" + a[1] + "] " + a[0]).join("\n"));
}
};
drawRound(/*turns =*/ 1000000, /*log =*/ 2, /*fps =*/ 600,/* zoom =*/ 50);
```
```
<body></body>
```
[Answer]
# Honnold (66 bytes, -33 points)
```
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
}
```
Bonus points for guessing the name's origin.
Try it:
```
var botData = [
{
name: "ExampleBot",
color: "#999999",
run: () => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)
},
{
name: "ExampleBot",
color: "#999999",
run: () => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)
},
{
name: "ExampleBot",
color: "#999999",
run: () => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)
},
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
}
];
{
var game = {
randPos: (center, any = !1, uid = 0, owner = 0, p = 0.1) => {
var theta, radius, pos;
do {
theta = Math.random() * Math.PI * 2;
radius = 0;
while (Math.random() > p)
radius++;
pos = [Math.trunc(center[0] + Math.cos(theta) * radius), Math.trunc(center[1] + Math.sin(theta) * radius)];
} while (!any && game.bots.find(a => a && a.uid != uid && Math.abs(a.pos[0] - pos[0]) + Math.abs(a.pos[1] - pos[1]) < (a.uid == owner ? 3 : 4)));
return pos;
},
debug: function(){},
log: 0 // 0 = NONE, 1 = SUMMARY, 2 = ALL
};
var north = () => ["north"];
var east = () => ["east"];
var south = () => ["south"];
var west = () => ["west"];
var build = code => ["worker", code];
var drop = {
north: char => ["drop.north", char],
east: char => ["drop.east", char],
south: char => ["drop.south", char],
west: char => ["drop.west", char]
};
var bots = () => game.bots.map(a => ({
uid: a.uid,
owner: a.owner,
original: a.original,
score: a.score,
pos: [...a.pos],
chars: game.uid == a.uid ? [...a.chars] : undefined,
source: game.uid == a.uid ? a.source : undefined
})).sort((a, b) => a.uid - b.uid);
var chars = () => game.chars.map(a => ({
char: a.char,
pos: [...a.pos]
}));
var self = () => {
var bot = game.bots.find(a => a.uid == game.uid);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var owner = () => {
var bot = game.bots.find(a => a.uid == game.bots.find(b => b.uid == game.uid).owner);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var center = () => game.center;
var turn = () => game.turns;
var at = pos => ({
bot: (game.bots.find(b => b.pos[0] == pos[0] && b.pos[1] == pos[1]) || {uid: null}).uid,
chars: chars().filter(c => c.pos[0] == pos[0] && c.pos[1] == pos[1])
});
var dir = (posFrom, pos) => {
if (Math.abs(posFrom[0] - pos[0]) <= Math.abs(posFrom[1] - pos[1]))
return posFrom[1] < pos[1] ? ["north"] : ["south"];
else
return posFrom[0] < pos[0] ? ["west"] : ["east"];
};
var dirTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
if (Math.abs(pos[0] - bot.pos[0]) <= Math.abs(pos[1] - bot.pos[1]))
return pos[1] < bot.pos[1] ? ["north"] : ["south"];
else
return pos[0] < bot.pos[0] ? ["west"] : ["east"];
};
var dist = (posFrom, pos) => {
return Math.abs(posFrom[0] - pos[0]) + Math.abs(posFrom[1] - pos[1]);
};
var distTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
return Math.abs(pos[0] - bot.pos[0]) + Math.abs(pos[1] - bot.pos[1]);
};
async function runRound(turns = 100000) {
var uids = [];
game.perf = performance.now();
for (let i = 1; i <= botData.length; i++)
uids[i - 1] = i;
for (let j, i = uids.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
[uids[i], uids[j]] = [uids[j], uids[i]];
}
game.bots = [];
game.chars = [];
game.records = game.records || [];
game.uids = [];
for (let i = 0; i < botData.length; i++) {
game.bots[i] = {
uid: uids[i],
owner: uids[i],
original: uids[i],
score: Math.floor(botData[i].run.toString().length * -1 / 2),
chars: [],
pos: game.randPos([0, 0]),
source: botData[i].run.toString(),
run: botData[i].run,
storage: {},
name: botData[i].name || "Bot",
color: botData[i].color || "#000000"
};
game.uids[uids[i]] = i;
game.records[i] = game.records[i] || 0;
}
game.center = [
game.bots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0),
game.bots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = game.bots.map(a => a.source).join("");
for (let i = 0; i < botData.length * 4; i++)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.cuid = botData.length + 1;
game.turns = 0;
if (!game.fps) {
while (game.chars.length && game.bots.length && game.turns < turns) {
runTurn();
game.turns++;
}
} else {
game.debug();
while (game.chars.length && game.bots.length && game.turns < turns) {
await new Promise(function(resolve) {
setTimeout(resolve, 1000 / game.fps);
});
if (!game.pause) {
runTurn();
game.debug();
game.turns++;
}
}
}
bots().map(b => game.records[game.uids[b.original]] += b.score);
if (game.log)
console.log("Round Completed (" + ((performance.now() - game.perf) / 1000).toFixed(3) + "s):\n" + game.bots.map(a => a).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join("\n"));
}
function runTurn() {
var cbots = [];
var npos = [];
var nposl = [];
var nbots = [];
for (let b, p, m, i = 0; i < game.bots.length; i++) {
b = game.bots[i];
game.uid = b.uid;
try {
m = b.run(b.storage);
} catch(e) {
m = ["dead"];
if (game.log == 2)
console.warn("[" + game.turns + "] Error: " + b.name + "\n" + (e.stack || e.message));
for (let j = 0; j < b.chars.length; j++)
game.chars.push({
char: b.chars[j],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
}
if (!Array.isArray(m))
m = [];
if (m[0] == "north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "west")
p = [b.pos[0] - 1, b.pos[1]];
else
p = [...b.pos];
if (m[0] != "dead")
npos.push({
bot: b.uid,
pos: p
});
if (m[0] == "worker" && m[1].split("").reduce((c, d, e) => d && (e = c.indexOf(d)) != -1 ? c.filter((f, g) => g != e) : null, [...b.chars])) {
p = game.randPos(b.pos, !1, 0, b.uid);
try {
cbots.push({
uid: game.cuid,
owner: b.uid,
original: b.original,
score: 0,
chars: [],
pos: p,
source: m[1],
run: eval(m[1]),
storage: {},
name: b.name + "*",
color: b.color
});
npos.push({
bot: game.cuid++,
pos: p
});
b.score -= Math.floor(m[1].length / 2);
for (let n, j = 0; j < m[1].length; j++) {
n = b.chars.indexOf(m[1][j]);
b.chars = b.chars.slice(0, n).concat(b.chars.slice(n + 1));
}
if (game.log == 2)
console.log("[" + game.turns + "] New Worker: " + b.name);
} catch(e) {
if (game.log == 2)
console.warn("[" + game.turns + "] Invalid Worker: " + b.name + "\n" + (e.stack || e.message));
}
}
if (typeof m[0] == "string" && m[0].match(/^drop.(north|east|south|west)$/) && b.chars.includes(m[1])) {
b.score--;
for (let j = 0; j < b.chars.length; j++) {
if (b.chars[j] == m[1]) {
b.chars = b.chars.slice(0, j) + b.chars.slice(j + 1);
break;
}
}
if (m[0] == "drop.north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "drop.east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "drop.south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "drop.west")
p = [b.pos[0] - 1, b.pos[1]];
game.chars.push({
char: m[1],
pos: p,
game: !1
});
}
}
game.bots.push(...cbots);
for (let f, i = 0; i < npos.length; i++) {
if (!(f = nposl.find(a => a.pos[0] == npos[i].pos[0] && a.pos[1] == npos[i].pos[1])))
nposl.push(f = {
pos: [...npos[i].pos],
bots: []
});
f.bots.push(npos[i].bot);
}
for (let n, m, b, i = 0; i < nposl.length; i++) {
n = nposl[i];
if (n.bots.length > 1) {
m = Math.max(...n.bots.map(a => game.bots.find(b => b.uid == a).score));
if (game.bots.filter(a => n.bots.includes(a.uid) && a.score == m).length > 1) {
m += 1;
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
} else {
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
}
for (let j = 0; j < n.bots.length; j++) {
b = game.bots.find(a => a.uid == n.bots[j]);
if (b.score < m)
for (let k = 0; k < b.chars.length; k++)
game.chars.push({
char: b.chars[k],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
else
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
} else {
b = game.bots.find(a => a.uid == n.bots[0]);
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
game.center = [
nbots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0),
nbots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = nbots.map(a => a.source).join("");
for (let b, c, i = 0; i < game.chars.length; i++) {
c = game.chars[i];
if (b = nbots.find(a => a.pos[0] == c.pos[0] && a.pos[1] == c.pos[1])) {
b.score++;
b.chars.push(c.char);
if (c.game && game.chars.filter(a => a && a.game).length < nbots.length * 4 && game.bots.map(a => a.original).reduce((a, b) => a.includes(b) ? a : a.concat(b), []).length > 1)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.chars[i] = null;
}
}
game.chars = game.chars.filter(a => a);
game.bots = nbots;
};
function drawRound(turns = 100000, log = 2, fps = 5, zoom = 50){
var c, ctx, wdim, scale;
document.body.innerHTML = "<canvas></canvas>";
c = document.body.firstChild;
c.style.position = "absolute";
c.style.top = "0";
c.style.left = "0";
c.style.zIndex = "2";
ctx = c.getContext("2d");
game.records = new Array(botData.length).fill(0);
game.log = log;
game.pause = !1;
game.fps = fps;
(window.onresize = function() {
wdim = [window.innerWidth || 600, window.innerHeight || 400];
scale = Math.ceil(wdim[1] / zoom);
c.width = wdim[0];
c.height = wdim[1];
})();
window.onkeydown = function() {
var key = event.code;
if (key == "Escape")
game.pause = !game.pause;
if (key == "ArrowLeft" && game.fps > 1)
game.fps -= 1;
if (key == "ArrowRight")
game.fps += 1;
};
game.debug = function() {
ctx.clearRect(0, 0, wdim[0], wdim[1]);
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = Math.floor(scale * 0.6) + "px monospace";
for (let x = -Math.ceil(wdim[0] / 2 / scale), i = wdim[0] / 2 - (Math.ceil(wdim[0] / 2 / scale) - 0.5) * scale; i <= wdim[0]; i += scale, x++) {
for (let b, c, y = -Math.ceil(wdim[1] / 2 / scale), j = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; j <= wdim[1]; j += scale, y++) {
if ((c = game.chars.filter(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))).length) {
for (let k = 0; k < c.length; k++)
ctx.fillText(JSON.stringify(c[k].char).slice(1, -1).replace(/\\"/, "\"").replace(/\\\\/, "\\").replace(/ /, "_"), i + scale / 2, j + scale / 2);
}
if (b = game.bots.find(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))) {
ctx.fillStyle = b.color;
ctx.fillRect(i, j, scale, scale);
ctx.fillStyle = "#000000";
}
}
ctx.lineWidth = 0.1;
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, wdim[1]);
ctx.stroke();
}
for (let i = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; i <= wdim[1]; i += scale) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(wdim[0], i);
ctx.stroke();
}
ctx.fillRect(wdim[0] / 2 - 3, wdim[1] / 2 - 3, 7, 7);
};
runRound(turns);
}
function runGame(rounds = 1, turns = 100000, log = 0) {
game.records = new Array(botData.length).fill(0);
game.log = log;
for (let i = 0; i < rounds; i++)
runRound(turns, 0);
console.log("Game Conclusion:\n" + botData.map((a, b) => [a.name, game.records[b]]).sort((a, b) => b[1] - a[1]).map(a => "[" + a[1] + "] " + a[0]).join("\n"));
}
};
drawRound(/*turns =*/ 1000, /*log =*/ 2, /*fps =*/ 10,/* zoom =*/ 50);
```
```
<body></body>
```
[Answer]
# Rabbit, 56 bytes(-28 points)
```
{
name: "Rabbit",
color: "#FFC0CB",
run:_=>turn()%1e3?dirTo(chars()[0].pos):build(self().source)
}
```
Why rabbit? Because it runs away, forages for food, and then immediately reproduces.
Fixed with some help from Redwolf, and now works after a fix to the controller.
```
var botData = [
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "The Caveman",
color: "#FF0000",
run:_=>{w=bots().sort((a,b)=>a.score-b.score)[0];return self().score<=w.score?dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos):dirTo(w.pos)}
},
{
name: "Centrist",
color: "#666666",
run:_=>dirTo(center())
},
{
name: "True Neutral",
color: "#400000",
run: _=>dirTo(chars().sort((a,b)=>dist(a.pos,[0,0])-dist(b.pos,[0,0])+distTo(a.pos)-distTo(b.pos))[0].pos)
},{
name: "Rabbit",
color: "#FFC0CB",
run:_=>turn()%1e3?dirTo(chars()[0].pos):build(self().source)
}
];
var game = {
randPos: (center, any = !1, uid = 0, owner = 0, p = 0.1) => {
var theta, radius, pos;
do {
theta = Math.random() * Math.PI * 2;
radius = 0;
while (Math.random() > p)
radius++;
pos = [Math.trunc(center[0] + Math.cos(theta) * radius), Math.trunc(center[1] + Math.sin(theta) * radius)];
} while (!any && game.bots.find(a => a && a.uid != uid && Math.abs(a.pos[0] - pos[0]) + Math.abs(a.pos[1] - pos[1]) < (a.uid == owner ? 3 : 4)));
return pos;
},
debug: function(){},
log: 0 // 0 = NONE, 1 = SUMMARY, 2 = ALL
};
var north = () => ["north"];
var east = () => ["east"];
var south = () => ["south"];
var west = () => ["west"];
var build = code => ["worker", code];
var drop = {
north: char => ["drop.north", char],
east: char => ["drop.east", char],
south: char => ["drop.south", char],
west: char => ["drop.west", char]
};
var bots = () => game.bots.map(a => ({
uid: a.uid,
owner: a.owner,
original: a.original,
score: a.score,
pos: [...a.pos],
chars: game.uid == a.uid ? [...a.chars] : undefined,
source: game.uid == a.uid ? a.source : undefined
})).sort((a, b) => a.uid - b.uid);
var chars = () => game.chars.map(a => ({
char: a.char,
pos: [...a.pos]
}));
var self = () => {
var bot = game.bots.find(a => a.uid == game.uid);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var owner = () => {
var bot = game.bots.find(a => a.uid == game.bots.find(b => b.uid == game.uid).owner);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var center = () => game.center;
var turn = () => game.turns;
var at = pos => ({
bot: (game.bots.find(b => b.pos[0] == pos[0] && b.pos[1] == pos[1]) || {uid: null}).uid,
chars: chars().filter(c => c.pos[0] == pos[0] && c.pos[1] == pos[1])
});
var dir = (posFrom, pos) => {
if (Math.abs(posFrom[0] - pos[0]) <= Math.abs(posFrom[1] - pos[1]))
return posFrom[1] < pos[1] ? ["north"] : ["south"];
else
return posFrom[0] < pos[0] ? ["west"] : ["east"];
};
var dirTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
if (Math.abs(pos[0] - bot.pos[0]) <= Math.abs(pos[1] - bot.pos[1]))
return pos[1] < bot.pos[1] ? ["north"] : ["south"];
else
return pos[0] < bot.pos[0] ? ["west"] : ["east"];
};
var dist = (posFrom, pos) => {
return Math.abs(posFrom[0] - pos[0]) + Math.abs(posFrom[1] - pos[1]);
};
var distTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
return Math.abs(pos[0] - bot.pos[0]) + Math.abs(pos[1] - bot.pos[1]);
};
async function runRound(turns = 100000) {
var uids = [];
game.perf = performance.now();
for (let i = 1; i <= botData.length; i++)
uids[i - 1] = i;
for (let j, i = uids.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
[uids[i], uids[j]] = [uids[j], uids[i]];
}
game.bots = [];
game.chars = [];
game.records = game.records || [];
game.uids = [];
for (let i = 0; i < botData.length; i++) {
game.bots[i] = {
uid: uids[i],
owner: uids[i],
original: uids[i],
score: Math.floor(botData[i].run.toString().length * -1 / 2),
chars: [],
pos: game.randPos([0, 0]),
source: botData[i].run.toString(),
run: botData[i].run,
storage: {},
name: botData[i].name || "Bot",
color: botData[i].color || "#000000"
};
game.uids[uids[i]] = i;
game.records[i] = game.records[i] || 0;
}
game.center = [
game.bots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0),
game.bots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = game.bots.map(a => a.source).join("");
for (let i = 0; i < botData.length * 4; i++)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.cuid = botData.length + 1;
game.turns = 0;
if (!game.fps) {
while (game.chars.length && game.bots.length && game.turns < turns) {
runTurn();
game.turns++;
}
} else {
game.debug();
while (game.chars.length && game.bots.length && game.turns < turns) {
await new Promise(function(resolve) {
setTimeout(resolve, 1000 / game.fps);
});
if (!game.pause) {
runTurn();
game.debug();
game.turns++;
}
}
}
game.bots.map(b => game.records[game.uids[b.original]] += b.score);
if (game.log)
console.log("Round Completed (" + ((performance.now() - game.perf) / 1000).toFixed(3) + "s):\n" + game.bots.map(a => a).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join("\n"));
}
function runTurn() {
var cbots = [];
var npos = [];
var nposl = [];
var nbots = [];
for (let b, p, m, i = 0; i < game.bots.length; i++) {
b = game.bots[i];
game.uid = b.uid;
try {
m = b.run(b.storage);
} catch(e) {
m = ["dead"];
if (game.log == 2)
console.warn("[" + game.turns + "] Error: " + b.name + "\n" + (e.stack || e.message));
for (let j = 0; j < b.chars.length; j++)
game.chars.push({
char: b.chars[j],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
}
if (!Array.isArray(m))
m = [];
if (m[0] == "north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "west")
p = [b.pos[0] - 1, b.pos[1]];
else
p = [...b.pos];
if (m[0] != "dead")
npos.push({
bot: b.uid,
pos: p
});
if (m[0] == "worker" && m[1].split("").reduce((c, d, e) => c && d && (e = c.indexOf(d)) != -1 ? c.filter((f, g) => g != e) : null, [...b.chars])) {
p = game.randPos(b.pos, !1, 0, b.uid);
try {
cbots.push({
uid: game.cuid,
owner: b.uid,
original: b.original,
score: 0,
chars: [],
pos: p,
source: m[1],
run: eval(m[1]),
storage: {},
name: b.name + "*",
color: b.color
});
npos.push({
bot: game.cuid++,
pos: p
});
b.score -= Math.floor(m[1].length / 2);
for (let n, j = 0; j < m[1].length; j++) {
n = b.chars.indexOf(m[1][j]);
b.chars = b.chars.slice(0, n).concat(b.chars.slice(n + 1));
}
if (game.log == 2)
console.log("[" + game.turns + "] New Worker: " + b.name);
} catch(e) {
if (game.log == 2)
console.warn("[" + game.turns + "] Invalid Worker: " + b.name + "\n" + (e.stack || e.message));
}
}
if (typeof m[0] == "string" && m[0].match(/^drop.(north|east|south|west)$/) && b.chars.includes(m[1])) {
b.score--;
for (let j = 0; j < b.chars.length; j++) {
if (b.chars[j] == m[1]) {
b.chars = b.chars.slice(0, j) + b.chars.slice(j + 1);
break;
}
}
if (m[0] == "drop.north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "drop.east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "drop.south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "drop.west")
p = [b.pos[0] - 1, b.pos[1]];
game.chars.push({
char: m[1],
pos: p,
game: !1
});
}
}
game.bots.push(...cbots);
for (let f, i = 0; i < npos.length; i++) {
if (!(f = nposl.find(a => a.pos[0] == npos[i].pos[0] && a.pos[1] == npos[i].pos[1])))
nposl.push(f = {
pos: [...npos[i].pos],
bots: []
});
f.bots.push(npos[i].bot);
}
for (let n, m, b, i = 0; i < nposl.length; i++) {
n = nposl[i];
if (n.bots.length > 1) {
m = Math.max(...n.bots.map(a => game.bots.find(b => b.uid == a).score));
if (game.bots.filter(a => n.bots.includes(a.uid) && a.score == m).length > 1) {
m += 1;
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
} else {
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
}
for (let j = 0; j < n.bots.length; j++) {
b = game.bots.find(a => a.uid == n.bots[j]);
if (b.score < m) {
for (let k = 0; k < b.chars.length; k++)
game.chars.push({
char: b.chars[k],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
game.records[game.uids[b.original]] += b.score;
} else {
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
} else {
b = game.bots.find(a => a.uid == n.bots[0]);
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
game.center = [
nbots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0),
nbots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = nbots.map(a => a.source).join("");
for (let b, c, i = 0; i < game.chars.length; i++) {
c = game.chars[i];
if (b = nbots.find(a => a.pos[0] == c.pos[0] && a.pos[1] == c.pos[1])) {
b.score++;
b.chars.push(c.char);
if (c.game && game.chars.filter(a => a && a.game).length < nbots.length * 4 && game.bots.map(a => a.original).reduce((a, b) => a.includes(b) ? a : a.concat(b), []).length > 1)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.chars[i] = null;
}
}
game.chars = game.chars.filter(a => a);
game.bots = nbots;
};
function drawRound(turns = 100000, log = 2, fps = 5, zoom = 50) {
var c, ctx, wdim, scale;
document.body.innerHTML = "<canvas></canvas>";
c = document.body.firstChild;
c.style.position = "absolute";
c.style.top = "0";
c.style.left = "0";
c.style.zIndex = "2";
ctx = c.getContext("2d");
game.records = new Array(botData.length).fill(0);
game.log = log;
game.pause = !1;
game.fps = fps;
(window.onresize = function() {
wdim = [window.innerWidth || 600, window.innerHeight || 400];
scale = Math.ceil(wdim[1] / zoom);
c.width = wdim[0];
c.height = wdim[1];
})();
window.onkeydown = function() {
var key = event.code;
if (key == "Escape")
game.pause = !game.pause;
if (key == "ArrowLeft" && game.fps > 1)
game.fps -= 1;
if (key == "ArrowRight")
game.fps += 1;
};
game.debug = function() {
ctx.clearRect(0, 0, wdim[0], wdim[1]);
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = Math.floor(scale * 0.6) + "px monospace";
for (let x = -Math.ceil(wdim[0] / 2 / scale), i = wdim[0] / 2 - (Math.ceil(wdim[0] / 2 / scale) - 0.5) * scale; i <= wdim[0]; i += scale, x++) {
for (let b, c, y = -Math.ceil(wdim[1] / 2 / scale), j = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; j <= wdim[1]; j += scale, y++) {
if ((c = game.chars.filter(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))).length) {
for (let k = 0; k < c.length; k++)
ctx.fillText(JSON.stringify(c[k].char).slice(1, -1).replace(/\\"/, "\"").replace(/\\\\/, "\\").replace(/ /, "_"), i + scale / 2, j + scale / 2);
}
if (b = game.bots.find(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))) {
ctx.fillStyle = b.color;
ctx.fillRect(i, j, scale, scale);
ctx.fillStyle = "#000000";
}
}
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, wdim[1]);
ctx.stroke();
}
for (let i = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; i <= wdim[1]; i += scale) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(wdim[0], i);
ctx.stroke();
}
ctx.fillRect(wdim[0] / 2 - 3, wdim[1] / 2 - 3, 7, 7);
};
runRound(turns);
}
function runGame(rounds = 1, turns = 100000, log = 0) {
game.records = new Array(botData.length).fill(0);
game.log = log;
for (let i = 0; i < rounds; i++)
runRound(turns, 0);
console.log("Game Conclusion:\n" + botData.map((a, b) => [a.name, game.records[b]]).sort((a, b) => b[1] - a[1]).map(a => "[" + a[1] + "] " + a[0]).join("\n"));
}
drawRound(/*turns =*/ 1000000, /*log =*/ 2, /*fps =*/ 600,/* zoom =*/ 50);
```
[Answer]
# The Luggage
```
{
name: "The Luggage",
color: "#8B4513",
run:()=>dirTo(bots()[0].pos)
}
```
Bonus points for guessing the name origin
```
var botData = [
{
name: "ExampleBot",
color: "#aaaaaa",
run: () => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)
},
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "The Caveman",
color: "#FF0000",
run:()=>{w=bots().sort((a,b)=>a.score-b.score)[0];return self().score<=w.score?dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos):dirTo(w.pos)}
},
{
name: "True Neutral",
color: "#400000",
run: _=>dirTo(chars().sort((a,b)=>dist(a.pos,[0,0])-dist(b.pos,[0,0])+distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "Centrist",
color: "#666666",
run:_=>dirTo(center())
},
{
name: "Rabbit",
color: "#FFC0CB",
run:_=>turn()%1e3?dirTo(chars()[0].pos):build(self().source)
},
{
name: "The Luggage",
color: "#8B4513",
run:()=>dirTo(bots()[0].pos)
}
];
// _=>{var r,d,e,l,I,N,P,D=distTo,s=self(),p=s[P="pos"],w="_=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)",n=w.split``;s.chars.map(c=>n[n[N="indexOf"](c)]="");if(!n.find(_=>_))return build(w);r=chars().filter(c=>!bots().find(b=>b.uid!=s.uid&&dist(b[P],c[P])-D(c[P])<1));if(r.length)return dirTo(r.sort((a,b)=>D(a[P])-D(b[P])+(n[I="includes"](b)-n[I](a))*10)[0][P]);l={n:-p[1],e:p[0],s:p[1],w:-p[0]};d="nesw".split``.sort((a,b)=>l[a]-l[b]);e=bots().filter(b=>b.uid!=s.uid&&b.score>=s.score&&D(b[P])<5).map(b=>d[d[N](dirTo(b[P])[0][0])]="");return[north,east,south,west]["nesw"[N](d.find(x=>x))]()}
var game = {
randPos: (center, any = !1, uid = 0, owner = 0, p = 0.1) => {
var theta, radius, pos;
do {
theta = Math.random() * Math.PI * 2;
radius = 0;
while (Math.random() > p)
radius++;
pos = [Math.trunc(center[0] + Math.cos(theta) * radius), Math.trunc(center[1] + Math.sin(theta) * radius)];
} while (!any && game.bots.find(a => a && a.uid != uid && Math.abs(a.pos[0] - pos[0]) + Math.abs(a.pos[1] - pos[1]) < (a.uid == owner ? 3 : 4)));
return pos;
},
debug: function(){},
log: 0 // 0 = NONE, 1 = SUMMARY, 2 = ALL
};
var north = () => ["north"];
var east = () => ["east"];
var south = () => ["south"];
var west = () => ["west"];
var build = code => ["worker", code];
var drop = {
north: char => ["drop.north", char],
east: char => ["drop.east", char],
south: char => ["drop.south", char],
west: char => ["drop.west", char]
};
var bots = () => game.bots.map(a => ({
uid: a.uid,
owner: a.owner,
original: a.original,
score: a.score,
pos: [...a.pos],
chars: game.uid == a.uid ? [...a.chars] : undefined,
source: game.uid == a.uid ? a.source : undefined
})).sort((a, b) => a.uid - b.uid);
var chars = () => game.chars.map(a => ({
char: a.char,
pos: [...a.pos]
}));
var self = () => {
var bot = game.bots.find(a => a.uid == game.uid);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var owner = () => {
var bot = game.bots.find(a => a.uid == game.bots.find(b => b.uid == game.uid).owner);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var center = () => game.center;
var turn = () => game.turns;
var at = pos => ({
bot: (game.bots.find(b => b.pos[0] == pos[0] && b.pos[1] == pos[1]) || {uid: null}).uid,
chars: chars().filter(c => c.pos[0] == pos[0] && c.pos[1] == pos[1])
});
var dir = (posFrom, pos) => {
if (Math.abs(posFrom[0] - pos[0]) <= Math.abs(posFrom[1] - pos[1]))
return posFrom[1] < pos[1] ? ["north"] : ["south"];
else
return posFrom[0] < pos[0] ? ["west"] : ["east"];
};
var dirTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
if (Math.abs(pos[0] - bot.pos[0]) <= Math.abs(pos[1] - bot.pos[1]))
return pos[1] < bot.pos[1] ? ["north"] : ["south"];
else
return pos[0] < bot.pos[0] ? ["west"] : ["east"];
};
var dist = (posFrom, pos) => {
return Math.abs(posFrom[0] - pos[0]) + Math.abs(posFrom[1] - pos[1]);
};
var distTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
return Math.abs(pos[0] - bot.pos[0]) + Math.abs(pos[1] - bot.pos[1]);
};
async function runRound(turns = 100000) {
var uids = [];
game.perf = performance.now();
for (let i = 1; i <= botData.length; i++)
uids[i - 1] = i;
for (let j, i = uids.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
[uids[i], uids[j]] = [uids[j], uids[i]];
}
game.bots = [];
game.chars = [];
game.records = game.records || [];
game.uids = [];
for (let i = 0; i < botData.length; i++) {
game.bots[i] = {
uid: uids[i],
owner: uids[i],
original: uids[i],
score: Math.floor(botData[i].run.toString().length * -1 / 2),
chars: [],
pos: game.randPos([0, 0]),
source: botData[i].run.toString(),
run: botData[i].run,
storage: {},
name: botData[i].name || "Bot",
color: botData[i].color || "#000000"
};
game.uids[uids[i]] = i;
game.records[i] = game.records[i] || 0;
}
game.center = [
game.bots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0),
game.bots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = game.bots.map(a => a.source).join("");
for (let i = 0; i < botData.length * 4; i++)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.cuid = botData.length + 1;
game.turns = 0;
if (!game.fps) {
while (game.chars.length && game.bots.length && game.turns < turns) {
runTurn();
game.turns++;
}
} else {
game.debug();
while (game.chars.length && game.bots.length && game.turns < turns) {
await new Promise(function(resolve) {
setTimeout(resolve, 1000 / game.fps);
});
if (!game.pause) {
runTurn();
game.debug();
game.turns++;
}
}
}
game.bots.map(b => game.records[game.uids[b.original]] += b.score);
if (game.log)
console.log("Round Completed (" + ((performance.now() - game.perf) / 1000).toFixed(3) + "s):\n" + game.bots.map(a => a).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join("\n"));
}
function runTurn() {
var cbots = [];
var npos = [];
var nposl = [];
var nbots = [];
for (let b, p, m, i = 0; i < game.bots.length; i++) {
b = game.bots[i];
game.uid = b.uid;
try {
m = b.run(b.storage);
} catch(e) {
m = ["dead"];
if (game.log == 2)
console.warn("[" + game.turns + "] Error: " + b.name + "\n" + (e.stack || e.message));
for (let j = 0; j < b.chars.length; j++)
game.chars.push({
char: b.chars[j],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
}
if (!Array.isArray(m))
m = [];
if (m[0] == "north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "west")
p = [b.pos[0] - 1, b.pos[1]];
else
p = [...b.pos];
if (m[0] != "dead")
npos.push({
bot: b.uid,
pos: p
});
if (m[0] == "worker" && m[1].split("").reduce((c, d, e) => c && d && (e = c.indexOf(d)) != -1 ? c.filter((f, g) => g != e) : null, [...b.chars])) {
p = game.randPos(b.pos, !1, 0, b.uid);
try {
cbots.push({
uid: game.cuid,
owner: b.uid,
original: b.original,
score: 0,
chars: [],
pos: p,
source: m[1],
run: eval(m[1]),
storage: {},
name: b.name + "*",
color: b.color
});
npos.push({
bot: game.cuid++,
pos: p
});
b.score -= Math.floor(m[1].length / 2);
for (let n, j = 0; j < m[1].length; j++) {
n = b.chars.indexOf(m[1][j]);
b.chars = b.chars.slice(0, n).concat(b.chars.slice(n + 1));
}
if (game.log == 2)
console.log("[" + game.turns + "] New Worker: " + b.name);
} catch(e) {
if (game.log == 2)
console.warn("[" + game.turns + "] Invalid Worker: " + b.name + "\n" + (e.stack || e.message));
}
}
if (typeof m[0] == "string" && m[0].match(/^drop.(north|east|south|west)$/) && b.chars.includes(m[1])) {
b.score--;
for (let j = 0; j < b.chars.length; j++) {
if (b.chars[j] == m[1]) {
b.chars = b.chars.slice(0, j) + b.chars.slice(j + 1);
break;
}
}
if (m[0] == "drop.north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "drop.east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "drop.south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "drop.west")
p = [b.pos[0] - 1, b.pos[1]];
game.chars.push({
char: m[1],
pos: p,
game: !1
});
}
}
game.bots.push(...cbots);
for (let f, i = 0; i < npos.length; i++) {
if (!(f = nposl.find(a => a.pos[0] == npos[i].pos[0] && a.pos[1] == npos[i].pos[1])))
nposl.push(f = {
pos: [...npos[i].pos],
bots: []
});
f.bots.push(npos[i].bot);
}
for (let n, m, b, i = 0; i < nposl.length; i++) {
n = nposl[i];
if (n.bots.length > 1) {
m = Math.max(...n.bots.map(a => game.bots.find(b => b.uid == a).score));
if (game.bots.filter(a => n.bots.includes(a.uid) && a.score == m).length > 1) {
m += 1;
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
} else {
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
}
for (let j = 0; j < n.bots.length; j++) {
b = game.bots.find(a => a.uid == n.bots[j]);
if (b.score < m) {
for (let k = 0; k < b.chars.length; k++)
game.chars.push({
char: b.chars[k],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
game.records[game.uids[b.original]] += b.score;
} else {
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
} else {
b = game.bots.find(a => a.uid == n.bots[0]);
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
game.center = [
nbots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0),
nbots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = nbots.map(a => a.source).join("");
for (let b, c, i = 0; i < game.chars.length; i++) {
c = game.chars[i];
if (b = nbots.find(a => a.pos[0] == c.pos[0] && a.pos[1] == c.pos[1])) {
b.score++;
b.chars.push(c.char);
if (c.game && game.chars.filter(a => a && a.game).length < nbots.length * 4 && game.bots.map(a => a.original).reduce((a, b) => a.includes(b) ? a : a.concat(b), []).length > 1)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.chars[i] = null;
}
}
game.chars = game.chars.filter(a => a);
game.bots = nbots;
};
function drawRound(turns = 100000, log = 2, fps = 5, zoom = 50) {
var c, ctx, wdim, scale;
document.body.innerHTML = "<canvas></canvas>";
c = document.body.firstChild;
c.style.position = "absolute";
c.style.top = "0";
c.style.left = "0";
c.style.zIndex = "2";
ctx = c.getContext("2d");
game.records = new Array(botData.length).fill(0);
game.log = log;
game.pause = !1;
game.fps = fps;
(window.onresize = function() {
wdim = [window.innerWidth || 600, window.innerHeight || 400];
scale = Math.ceil(wdim[1] / zoom);
c.width = wdim[0];
c.height = wdim[1];
})();
window.onkeydown = function() {
var key = event.code;
if (key == "Escape")
game.pause = !game.pause;
if (key == "ArrowLeft" && game.fps > 1)
game.fps -= 1;
if (key == "ArrowRight")
game.fps += 1;
};
game.debug = function() {
ctx.clearRect(0, 0, wdim[0], wdim[1]);
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = Math.floor(scale * 0.6) + "px monospace";
for (let x = -Math.ceil(wdim[0] / 2 / scale), i = wdim[0] / 2 - (Math.ceil(wdim[0] / 2 / scale) - 0.5) * scale; i <= wdim[0]; i += scale, x++) {
for (let b, c, y = -Math.ceil(wdim[1] / 2 / scale), j = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; j <= wdim[1]; j += scale, y++) {
if ((c = game.chars.filter(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))).length) {
for (let k = 0; k < c.length; k++)
ctx.fillText(JSON.stringify(c[k].char).slice(1, -1).replace(/\\"/, "\"").replace(/\\\\/, "\\").replace(/ /, "_"), i + scale / 2, j + scale / 2);
}
if (b = game.bots.find(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))) {
ctx.fillStyle = b.color;
ctx.fillRect(i, j, scale, scale);
ctx.fillStyle = "#000000";
}
}
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, wdim[1]);
ctx.stroke();
}
for (let i = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; i <= wdim[1]; i += scale) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(wdim[0], i);
ctx.stroke();
}
ctx.fillRect(wdim[0] / 2 - 3, wdim[1] / 2 - 3, 7, 7);
};
runRound(turns);
}
function runGame(rounds = 1, turns = 100000, log = 0) {
game.records = new Array(botData.length).fill(0);
game.log = log;
for (let i = 0; i < rounds; i++)
runRound(turns, 0);
console.log("Game Conclusion:\n" + botData.map((a, b) => [a.name, game.records[b]]).sort((a, b) => b[1] - a[1]).map(a => "[" + a[1] + "] " + a[0]).join("\n"));
}
drawRound(/*turns =*/ 1000000, /*log =*/ 2, /*fps =*/ 60,/* zoom =*/ 50);
```
```
<body></body>
```
[Answer]
## Shy Guy
```
{
name: "Shy Guy",
color: "#dd0044",
run: _=>{var Z="pos",E=self(),P=E[Z],D=distTo,T=bots().filter(b=>D(b[Z])==2&&b.score>E.score),H=(d,n)=>!T.find(t=>t[Z][d]*n<P[d]*n),N=[north,east,south,west],x=P[0],y=P[1],l={[N[0]]:-y,[N[1]]:x,[N[2]]:y,[N[3]]:-x},S=[H(1,1),H(0,-1),H(1,-1),H(0,1)],U=bots().find(b=>D(b[Z])==1&&b.score>E.score),r=chars().filter(c=>!bots().find(b=>b.uid!=E.uid&&dist(b[Z],c[Z])-D(c[Z])<1));return r.length?(dirTo(r.sort((a,b)=>D(a[Z])-D(b[Z]))[0][Z])):T.length?U?(N.filter((n,i)=>S[i]).sort((a,b)=>l[a]-l[b])[0]||(_=>_))():0:(turn()%20||U?dirTo("00"):build(E.source))}
}
```
Almost unkillable. Avoids dangerous bots, and any characters it knows it can't get. Reproduces insanely fast. Its priorities:
1. If there is a character closer to it than any other bot, go toward it (there is no way this can kill it)
2. If there is a dangerous bot two spaces away, but none one space away, stop for one turn (this makes it so that the dangerous bot will never be able to kill Shy Guy, preventing it from being locked in place)
3. If there is still a dangerous bot but it wouldn't be safe to stop, move in a safe direction, preferably toward `[0, 0]`
4. If it's safe to stop for a turn, and the turn number is divisible by twenty, attempt to create a new worker
5. Go toward `[0, 0]`
[Answer]
# Camper
```
{
name: "Camper",
color: "#00FF00",
run:_=>dirTo(chars().sort((a,b)=>dist("00",a.pos)-dist("00",b.pos))[0].pos)
}
```
Camps the center, and collects the characters closest to it, since the center has a higher density of those.
```
var botData = [
{
name: "ExampleBot",
color: "#aaaaaa",
run: () => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)
},
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "The Caveman",
color: "#FF0000",
run:()=>{w=bots().sort((a,b)=>a.score-b.score)[0];return self().score<=w.score?dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos):dirTo(w.pos)}
},
{
name: "True Neutral",
color: "#400000",
run: _=>dirTo(chars().sort((a,b)=>dist(a.pos,[0,0])-dist(b.pos,[0,0])+distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "Centrist",
color: "#666666",
run:_=>dirTo(center())
},
{
name: "Rabbit",
color: "#FFC0CB",
run:_=>turn()%1e3?dirTo(chars()[0].pos):build(self().source)
},{
name: "Shy Guy",
color: "#dd0044",
run: _=>{var Z="pos",E=self(),P=E[Z],D=distTo,T=bots().filter(b=>D(b[Z])==2&&b.score>E.score),H=(d,n)=>!T.find(t=>t[Z][d]*n<P[d]*n),N=[north,east,south,west],x=P[0],y=P[1],l={[N[0]]:-y,[N[1]]:x,[N[2]]:y,[N[3]]:-x},S=[H(1,1),H(0,-1),H(1,-1),H(0,1)],U=bots().find(b=>D(b[Z])==1&&b.score>E.score),r=chars().filter(c=>!bots().find(b=>b.uid!=E.uid&&dist(b[Z],c[Z])-D(c[Z])<1));return r.length?(dirTo(r.sort((a,b)=>D(a[Z])-D(b[Z]))[0][Z])):T.length?U?(N.filter((n,i)=>S[i]).sort((a,b)=>l[a]-l[b])[0]||(_=>_))():0:(turn()%20||U?dirTo("00"):build(E.source))}
},
{
name: "The Luggage",
color: "#8B4513",
run:()=>dirTo(bots()[0].pos)
},
{
name: "Camper",
color: "#00FF00",
run:_=>dirTo(chars().sort((a,b)=>dist("00",a.pos)-dist("00",b.pos))[0].pos)
}
];
// _=>{var r,d,e,l,I,N,P,D=distTo,s=self(),p=s[P="pos"],w="_=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)",n=w.split``;s.chars.map(c=>n[n[N="indexOf"](c)]="");if(!n.find(_=>_))return build(w);r=chars().filter(c=>!bots().find(b=>b.uid!=s.uid&&dist(b[P],c[P])-D(c[P])<1));if(r.length)return dirTo(r.sort((a,b)=>D(a[P])-D(b[P])+(n[I="includes"](b)-n[I](a))*10)[0][P]);l={n:-p[1],e:p[0],s:p[1],w:-p[0]};d="nesw".split``.sort((a,b)=>l[a]-l[b]);e=bots().filter(b=>b.uid!=s.uid&&b.score>=s.score&&D(b[P])<5).map(b=>d[d[N](dirTo(b[P])[0][0])]="");return[north,east,south,west]["nesw"[N](d.find(x=>x))]()}
var game = {
randPos: (center, any = !1, uid = 0, owner = 0, p = 0.1) => {
var theta, radius, pos;
do {
theta = Math.random() * Math.PI * 2;
radius = 0;
while (Math.random() > p)
radius++;
pos = [Math.trunc(center[0] + Math.cos(theta) * radius), Math.trunc(center[1] + Math.sin(theta) * radius)];
} while (!any && game.bots.find(a => a && a.uid != uid && Math.abs(a.pos[0] - pos[0]) + Math.abs(a.pos[1] - pos[1]) < (a.uid == owner ? 3 : 4)));
return pos;
},
debug: function(){},
log: 0 // 0 = NONE, 1 = SUMMARY, 2 = ALL
};
var north = () => ["north"];
var east = () => ["east"];
var south = () => ["south"];
var west = () => ["west"];
var build = code => ["worker", code];
var drop = {
north: char => ["drop.north", char],
east: char => ["drop.east", char],
south: char => ["drop.south", char],
west: char => ["drop.west", char]
};
var bots = () => game.bots.map(a => ({
uid: a.uid,
owner: a.owner,
original: a.original,
score: a.score,
pos: [...a.pos],
chars: game.uid == a.uid ? [...a.chars] : undefined,
source: game.uid == a.uid ? a.source : undefined
})).sort((a, b) => a.uid - b.uid);
var chars = () => game.chars.map(a => ({
char: a.char,
pos: [...a.pos]
}));
var self = () => {
var bot = game.bots.find(a => a.uid == game.uid);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var owner = () => {
var bot = game.bots.find(a => a.uid == game.bots.find(b => b.uid == game.uid).owner);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var center = () => game.center;
var turn = () => game.turns;
var at = pos => ({
bot: (game.bots.find(b => b.pos[0] == pos[0] && b.pos[1] == pos[1]) || {uid: null}).uid,
chars: chars().filter(c => c.pos[0] == pos[0] && c.pos[1] == pos[1])
});
var dir = (posFrom, pos) => {
if (Math.abs(posFrom[0] - pos[0]) <= Math.abs(posFrom[1] - pos[1]))
return posFrom[1] < pos[1] ? ["north"] : ["south"];
else
return posFrom[0] < pos[0] ? ["west"] : ["east"];
};
var dirTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
if (Math.abs(pos[0] - bot.pos[0]) <= Math.abs(pos[1] - bot.pos[1]))
return pos[1] < bot.pos[1] ? ["north"] : ["south"];
else
return pos[0] < bot.pos[0] ? ["west"] : ["east"];
};
var dist = (posFrom, pos) => {
return Math.abs(posFrom[0] - pos[0]) + Math.abs(posFrom[1] - pos[1]);
};
var distTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
return Math.abs(pos[0] - bot.pos[0]) + Math.abs(pos[1] - bot.pos[1]);
};
async function runRound(turns = 100000) {
var uids = [];
game.perf = performance.now();
for (let i = 1; i <= botData.length; i++)
uids[i - 1] = i;
for (let j, i = uids.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
[uids[i], uids[j]] = [uids[j], uids[i]];
}
game.bots = [];
game.chars = [];
game.records = game.records || [];
game.uids = [];
for (let i = 0; i < botData.length; i++) {
game.bots[i] = {
uid: uids[i],
owner: uids[i],
original: uids[i],
score: Math.floor(botData[i].run.toString().length * -1 / 2),
chars: [],
pos: game.randPos([0, 0]),
source: botData[i].run.toString(),
run: botData[i].run,
storage: {},
name: botData[i].name || "Bot",
color: botData[i].color || "#000000"
};
game.uids[uids[i]] = i;
game.records[i] = game.records[i] || 0;
}
game.center = [
game.bots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0),
game.bots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = game.bots.map(a => a.source).join("");
for (let i = 0; i < botData.length * 4; i++)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.cuid = botData.length + 1;
game.turns = 0;
if (!game.fps) {
while (game.chars.length && game.bots.length && game.turns < turns) {
runTurn();
game.turns++;
}
} else {
game.debug();
while (game.chars.length && game.bots.length && game.turns < turns) {
await new Promise(function(resolve) {
setTimeout(resolve, 1000 / game.fps);
});
if (!game.pause) {
runTurn();
game.debug();
game.turns++;
}
}
}
game.bots.map(b => game.records[game.uids[b.original]] += b.score);
if (game.log)
console.log("Round Completed (" + ((performance.now() - game.perf) / 1000).toFixed(3) + "s):\n" + game.bots.map(a => a).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join("\n"));
}
function runTurn() {
var cbots = [];
var npos = [];
var nposl = [];
var nbots = [];
for (let b, p, m, i = 0; i < game.bots.length; i++) {
b = game.bots[i];
game.uid = b.uid;
try {
m = b.run(b.storage);
} catch(e) {
m = ["dead"];
if (game.log == 2)
console.warn("[" + game.turns + "] Error: " + b.name + "\n" + (e.stack || e.message));
for (let j = 0; j < b.chars.length; j++)
game.chars.push({
char: b.chars[j],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
}
if (!Array.isArray(m))
m = [];
if (m[0] == "north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "west")
p = [b.pos[0] - 1, b.pos[1]];
else
p = [...b.pos];
if (m[0] != "dead")
npos.push({
bot: b.uid,
pos: p
});
if (m[0] == "worker" && m[1].split("").reduce((c, d, e) => c && d && (e = c.indexOf(d)) != -1 ? c.filter((f, g) => g != e) : null, [...b.chars])) {
p = game.randPos(b.pos, !1, 0, b.uid);
try {
cbots.push({
uid: game.cuid,
owner: b.uid,
original: b.original,
score: 0,
chars: [],
pos: p,
source: m[1],
run: eval(m[1]),
storage: {},
name: b.name + "*",
color: b.color
});
npos.push({
bot: game.cuid++,
pos: p
});
b.score -= Math.floor(m[1].length / 2);
for (let n, j = 0; j < m[1].length; j++) {
n = b.chars.indexOf(m[1][j]);
b.chars = b.chars.slice(0, n).concat(b.chars.slice(n + 1));
}
if (game.log == 2)
console.log("[" + game.turns + "] New Worker: " + b.name);
} catch(e) {
if (game.log == 2)
console.warn("[" + game.turns + "] Invalid Worker: " + b.name + "\n" + (e.stack || e.message));
}
}
if (typeof m[0] == "string" && m[0].match(/^drop.(north|east|south|west)$/) && b.chars.includes(m[1])) {
b.score--;
for (let j = 0; j < b.chars.length; j++) {
if (b.chars[j] == m[1]) {
b.chars = b.chars.slice(0, j) + b.chars.slice(j + 1);
break;
}
}
if (m[0] == "drop.north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "drop.east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "drop.south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "drop.west")
p = [b.pos[0] - 1, b.pos[1]];
game.chars.push({
char: m[1],
pos: p,
game: !1
});
}
}
game.bots.push(...cbots);
for (let f, i = 0; i < npos.length; i++) {
if (!(f = nposl.find(a => a.pos[0] == npos[i].pos[0] && a.pos[1] == npos[i].pos[1])))
nposl.push(f = {
pos: [...npos[i].pos],
bots: []
});
f.bots.push(npos[i].bot);
}
for (let n, m, b, i = 0; i < nposl.length; i++) {
n = nposl[i];
if (n.bots.length > 1) {
m = Math.max(...n.bots.map(a => game.bots.find(b => b.uid == a).score));
if (game.bots.filter(a => n.bots.includes(a.uid) && a.score == m).length > 1) {
m += 1;
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
} else {
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
}
for (let j = 0; j < n.bots.length; j++) {
b = game.bots.find(a => a.uid == n.bots[j]);
if (b.score < m) {
for (let k = 0; k < b.chars.length; k++)
game.chars.push({
char: b.chars[k],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
game.records[game.uids[b.original]] += b.score;
} else {
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
} else {
b = game.bots.find(a => a.uid == n.bots[0]);
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
game.center = [
nbots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0),
nbots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = nbots.map(a => a.source).join("");
for (let b, c, i = 0; i < game.chars.length; i++) {
c = game.chars[i];
if (b = nbots.find(a => a.pos[0] == c.pos[0] && a.pos[1] == c.pos[1])) {
b.score++;
b.chars.push(c.char);
if (c.game && game.chars.filter(a => a && a.game).length < nbots.length * 4 && game.bots.map(a => a.original).reduce((a, b) => a.includes(b) ? a : a.concat(b), []).length > 1)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.chars[i] = null;
}
}
game.chars = game.chars.filter(a => a);
game.bots = nbots;
};
function drawRound(turns = 100000, log = 2, fps = 5, zoom = 50) {
var c, ctx, wdim, scale;
document.body.innerHTML = "<canvas></canvas>";
c = document.body.firstChild;
c.style.position = "absolute";
c.style.top = "0";
c.style.left = "0";
c.style.zIndex = "2";
ctx = c.getContext("2d");
game.records = new Array(botData.length).fill(0);
game.log = log;
game.pause = !1;
game.fps = fps;
(window.onresize = function() {
wdim = [window.innerWidth || 600, window.innerHeight || 400];
scale = Math.ceil(wdim[1] / zoom);
c.width = wdim[0];
c.height = wdim[1];
})();
window.onkeydown = function() {
var key = event.code;
if (key == "Escape")
game.pause = !game.pause;
if (key == "ArrowLeft" && game.fps > 1)
game.fps -= 1;
if (key == "ArrowRight")
game.fps += 1;
};
game.debug = function() {
ctx.clearRect(0, 0, wdim[0], wdim[1]);
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = Math.floor(scale * 0.6) + "px monospace";
for (let x = -Math.ceil(wdim[0] / 2 / scale), i = wdim[0] / 2 - (Math.ceil(wdim[0] / 2 / scale) - 0.5) * scale; i <= wdim[0]; i += scale, x++) {
for (let b, c, y = -Math.ceil(wdim[1] / 2 / scale), j = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; j <= wdim[1]; j += scale, y++) {
if ((c = game.chars.filter(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))).length) {
for (let k = 0; k < c.length; k++)
ctx.fillText(JSON.stringify(c[k].char).slice(1, -1).replace(/\\"/, "\"").replace(/\\\\/, "\\").replace(/ /, "_"), i + scale / 2, j + scale / 2);
}
if (b = game.bots.find(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))) {
ctx.fillStyle = b.color;
ctx.fillRect(i, j, scale, scale);
ctx.fillStyle = "#000000";
}
}
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, wdim[1]);
ctx.stroke();
}
for (let i = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; i <= wdim[1]; i += scale) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(wdim[0], i);
ctx.stroke();
}
ctx.fillRect(wdim[0] / 2 - 3, wdim[1] / 2 - 3, 7, 7);
};
runRound(turns);
}
function runGame(rounds = 1, turns = 100000, log = 0) {
game.records = new Array(botData.length).fill(0);
game.log = log;
for (let i = 0; i < rounds; i++)
runRound(turns, 0);
console.log("Game Conclusion:\n" + botData.map((a, b) => [a.name, game.records[b]]).sort((a, b) => b[1] - a[1]).map(a => "[" + a[1] + "] " + a[0]).join("\n"));
}
drawRound(/*turns =*/ 1000000, /*log =*/ 2, /*fps =*/ 240,/* zoom =*/ 50);
```
```
<body></body>
```
[Answer]
## Ghost
```
{
name: "Ghost",
color: "#5599dd",
run: _=>{var f="filter",d=distTo,n=dist,e=self(),p=e.pos,h=bots()[f](b=>b.uid!=e.uid),r=chars()[f](c=>!h.find(b=>n(b.pos,c.pos)<=d(c.pos))),t=h[f](b=>b.score>=e.score),o=(l,i)=>!t.find(t=>n(t.pos,[p[0]+l,p[1]+i])<2),s=(l,i)=>n([0,0],[p[0]+l,p[1]+i]),T=[o(0,0),o(0,-1),o(1,0),o(0,1),o(-1,0)],L=[s(0,0),s(0,-1),s(1,0),s(0,1),s(-1,0)];return r[0]?turn()%50||!o(0,0)?dirTo(r.sort((a,b)=>d(a.pos)-d(b.pos))[0].pos):build(e.source):[_=>_,north,east,south,west][[0,1,2,2+1,5-1][f](i=>T[i]).sort((a,b)=>L[a]-L[b])[0]||0]()}
}
```
A bot loosely inspired by Shy Guy, but with so many optimizations it's almost guaranteed to be unbeatable.
Ghost is similar to Shy Guy in that it's almost unkillable. Except it's way, way smarter. It's shorter. Its source is optimized to use more common characters. It uses much simpler logic.
Here's how it works:
1. If there are any characters closer to Ghost than any other bot, go toward the nearest one
2. Otherwise, stay still or go in any direction which is 100% guaranteed not to kill Ghost (preferring ones which bring it closer to `[0, 0]`)
3. Finally, if there is no safe direction to go, stay still
[Answer]
## True Neutral
```
{
name: "True Neutral",
color: "#400000",
run: _=>dirTo(chars().sort((a,b)=>dist(a.pos,[0,0])-dist(b.pos,[0,0])+distTo(a.pos)-distTo(b.pos))[0].pos)
}
```
Goes for the characters which are:
* Close to itself
* Close to `[0, 0]` (where the most characters are)
[Answer]
# Centrist, 18 bytes(-9 points)
```
{
name: "Centrist",
color: "#666666",
run:_=>dirTo(center())
}
```
Even dumber than our friendly neighbourhood copycat. Just follows the crowd and hopes that he can live. Even his color is dull.
```
var botData = [
{
name: "Honnold",
color: "#0000FF",
run:()=>dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
},
{
name: "The Caveman",
color: "#FF0000",
run:_=>{w=bots().sort((a,b)=>a.score-b.score)[0];return self().score<=w.score?dirTo(chars().sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos):dirTo(w.pos)}
},
{
name: "Centrist",
color: "#666666",
run:_=>dirTo(center())
},
{
name: "True Neutral",
color: "#400000",
run: _=>dirTo(chars().sort((a,b)=>dist(a.pos,[0,0])-dist(b.pos,[0,0])+distTo(a.pos)-distTo(b.pos))[0].pos)
}
];
{
var game = {
randPos: (center, any = !1, uid = 0, owner = 0, p = 0.1) => {
var theta, radius, pos;
do {
theta = Math.random() * Math.PI * 2;
radius = 0;
while (Math.random() > p)
radius++;
pos = [Math.trunc(center[0] + Math.cos(theta) * radius), Math.trunc(center[1] + Math.sin(theta) * radius)];
} while (!any && game.bots.find(a => a && a.uid != uid && Math.abs(a.pos[0] - pos[0]) + Math.abs(a.pos[1] - pos[1]) < (a.uid == owner ? 3 : 4)));
return pos;
},
debug: function(){},
log: 0 // 0 = NONE, 1 = SUMMARY, 2 = ALL
};
var north = () => ["north"];
var east = () => ["east"];
var south = () => ["south"];
var west = () => ["west"];
var build = code => ["worker", code];
var drop = {
north: char => ["drop.north", char],
east: char => ["drop.east", char],
south: char => ["drop.south", char],
west: char => ["drop.west", char]
};
var bots = () => game.bots.map(a => ({
uid: a.uid,
owner: a.owner,
original: a.original,
score: a.score,
pos: [...a.pos],
chars: game.uid == a.uid ? [...a.chars] : undefined,
source: game.uid == a.uid ? a.source : undefined
})).sort((a, b) => a.uid - b.uid);
var chars = () => game.chars.map(a => ({
char: a.char,
pos: [...a.pos]
}));
var self = () => {
var bot = game.bots.find(a => a.uid == game.uid);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var owner = () => {
var bot = game.bots.find(a => a.uid == game.bots.find(b => b.uid == game.uid).owner);
return bot ? {
uid: bot.uid,
owner: bot.owner,
original: bot.original,
score: bot.score,
pos: [...bot.pos],
chars: [...bot.chars],
source: bot.source
} : null;
};
var center = () => game.center;
var turn = () => game.turns;
var at = pos => ({
bot: (game.bots.find(b => b.pos[0] == pos[0] && b.pos[1] == pos[1]) || {uid: null}).uid,
chars: chars().filter(c => c.pos[0] == pos[0] && c.pos[1] == pos[1])
});
var dir = (posFrom, pos) => {
if (Math.abs(posFrom[0] - pos[0]) <= Math.abs(posFrom[1] - pos[1]))
return posFrom[1] < pos[1] ? ["north"] : ["south"];
else
return posFrom[0] < pos[0] ? ["west"] : ["east"];
};
var dirTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
if (Math.abs(pos[0] - bot.pos[0]) <= Math.abs(pos[1] - bot.pos[1]))
return pos[1] < bot.pos[1] ? ["north"] : ["south"];
else
return pos[0] < bot.pos[0] ? ["west"] : ["east"];
};
var dist = (posFrom, pos) => {
return Math.abs(posFrom[0] - pos[0]) + Math.abs(posFrom[1] - pos[1]);
};
var distTo = pos => {
var bot = game.bots.find(a => a.uid == game.uid);
return Math.abs(pos[0] - bot.pos[0]) + Math.abs(pos[1] - bot.pos[1]);
};
async function runRound(turns = 100000) {
var uids = [];
game.perf = performance.now();
for (let i = 1; i <= botData.length; i++)
uids[i - 1] = i;
for (let j, i = uids.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
[uids[i], uids[j]] = [uids[j], uids[i]];
}
game.bots = [];
game.chars = [];
game.records = game.records || [];
game.uids = [];
for (let i = 0; i < botData.length; i++) {
game.bots[i] = {
uid: uids[i],
owner: uids[i],
original: uids[i],
score: Math.floor(botData[i].run.toString().length * -1 / 2),
chars: [],
pos: game.randPos([0, 0]),
source: botData[i].run.toString(),
run: botData[i].run,
storage: {},
name: botData[i].name || "Bot",
color: botData[i].color || "#000000"
};
game.uids[uids[i]] = i;
game.records[i] = game.records[i] || 0;
}
game.center = [
game.bots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0),
game.bots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / game.bots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = game.bots.map(a => a.source).join("");
for (let i = 0; i < botData.length * 4; i++)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.cuid = botData.length + 1;
game.turns = 0;
if (!game.fps) {
while (game.chars.length && game.bots.length && game.turns < turns) {
runTurn();
game.turns++;
}
} else {
game.debug();
while (game.chars.length && game.bots.length && game.turns < turns) {
await new Promise(function(resolve) {
setTimeout(resolve, 1000 / game.fps);
});
if (!game.pause) {
runTurn();
game.debug();
game.turns++;
}
}
}
bots().map(b => game.records[game.uids[b.original]] += b.score);
if (game.log)
console.log("Round Completed (" + ((performance.now() - game.perf) / 1000).toFixed(3) + "s):\n" + game.bots.map(a => a).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join("\n"));
}
function runTurn() {
var cbots = [];
var npos = [];
var nposl = [];
var nbots = [];
for (let b, p, m, i = 0; i < game.bots.length; i++) {
b = game.bots[i];
game.uid = b.uid;
try {
m = b.run(b.storage);
} catch(e) {
m = ["dead"];
if (game.log == 2)
console.warn("[" + game.turns + "] Error: " + b.name + "\n" + (e.stack || e.message));
for (let j = 0; j < b.chars.length; j++)
game.chars.push({
char: b.chars[j],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
}
if (!Array.isArray(m))
m = [];
if (m[0] == "north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "west")
p = [b.pos[0] - 1, b.pos[1]];
else
p = [...b.pos];
if (m[0] != "dead")
npos.push({
bot: b.uid,
pos: p
});
if (m[0] == "worker" && m[1].split("").reduce((c, d, e) => d && (e = c.indexOf(d)) != -1 ? c.filter((f, g) => g != e) : null, [...b.chars])) {
p = game.randPos(b.pos, !1, 0, b.uid);
try {
cbots.push({
uid: game.cuid,
owner: b.uid,
original: b.original,
score: 0,
chars: [],
pos: p,
source: m[1],
run: eval(m[1]),
storage: {},
name: b.name + "*",
color: b.color
});
npos.push({
bot: game.cuid++,
pos: p
});
b.score -= Math.floor(m[1].length / 2);
for (let n, j = 0; j < m[1].length; j++) {
n = b.chars.indexOf(m[1][j]);
b.chars = b.chars.slice(0, n).concat(b.chars.slice(n + 1));
}
if (game.log == 2)
console.log("[" + game.turns + "] New Worker: " + b.name);
} catch(e) {
if (game.log == 2)
console.warn("[" + game.turns + "] Invalid Worker: " + b.name + "\n" + (e.stack || e.message));
}
}
if (typeof m[0] == "string" && m[0].match(/^drop.(north|east|south|west)$/) && b.chars.includes(m[1])) {
b.score--;
for (let j = 0; j < b.chars.length; j++) {
if (b.chars[j] == m[1]) {
b.chars = b.chars.slice(0, j) + b.chars.slice(j + 1);
break;
}
}
if (m[0] == "drop.north")
p = [b.pos[0], b.pos[1] - 1];
else if (m[0] == "drop.east")
p = [b.pos[0] + 1, b.pos[1]];
else if (m[0] == "drop.south")
p = [b.pos[0], b.pos[1] + 1];
else if (m[0] == "drop.west")
p = [b.pos[0] - 1, b.pos[1]];
game.chars.push({
char: m[1],
pos: p,
game: !1
});
}
}
game.bots.push(...cbots);
for (let f, i = 0; i < npos.length; i++) {
if (!(f = nposl.find(a => a.pos[0] == npos[i].pos[0] && a.pos[1] == npos[i].pos[1])))
nposl.push(f = {
pos: [...npos[i].pos],
bots: []
});
f.bots.push(npos[i].bot);
}
for (let n, m, b, i = 0; i < nposl.length; i++) {
n = nposl[i];
if (n.bots.length > 1) {
m = Math.max(...n.bots.map(a => game.bots.find(b => b.uid == a).score));
if (game.bots.filter(a => n.bots.includes(a.uid) && a.score == m).length > 1) {
m += 1;
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
} else {
if (game.log == 2)
console.log("[" + game.turns + "] Collision: " + n.bots.map(a => game.bots.find(b => a == b.uid)).sort((a, b) => b.score - a.score).map(a => a.name + " [" + a.score + "]").join(", "));
}
for (let j = 0; j < n.bots.length; j++) {
b = game.bots.find(a => a.uid == n.bots[j]);
if (b.score < m)
for (let k = 0; k < b.chars.length; k++)
game.chars.push({
char: b.chars[k],
pos: game.randPos(b.pos, !0, 0, 0, 0.2),
game: !1
});
else
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
} else {
b = game.bots.find(a => a.uid == n.bots[0]);
nbots.push({
uid: b.uid,
owner: b.owner,
original: b.original,
score: b.score,
chars: [...b.chars],
pos: n.pos,
source: b.source,
run: b.run,
storage: b.storage,
name: b.name,
color: b.color
});
}
}
game.center = [
nbots.reduce((a, b) => a + b.pos[0] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0),
nbots.reduce((a, b) => a + b.pos[1] * (b.score + 1), 0) / nbots.reduce((a, b) => a + (b.score + 1), 0)
];
game.charPool = nbots.map(a => a.source).join("");
for (let b, c, i = 0; i < game.chars.length; i++) {
c = game.chars[i];
if (b = nbots.find(a => a.pos[0] == c.pos[0] && a.pos[1] == c.pos[1])) {
b.score++;
b.chars.push(c.char);
if (c.game && game.chars.filter(a => a && a.game).length < nbots.length * 4 && game.bots.map(a => a.original).reduce((a, b) => a.includes(b) ? a : a.concat(b), []).length > 1)
game.chars.push({
char: game.charPool[Math.random() * game.charPool.length | 0],
pos: game.randPos([0, 0]),
game: !0
});
game.chars[i] = null;
}
}
game.chars = game.chars.filter(a => a);
game.bots = nbots;
};
function drawRound(turns = 100000, log = 2, fps = 60, zoom = 50){
var c, ctx, wdim, scale;
document.body.innerHTML = "<canvas></canvas>";
c = document.body.firstChild;
c.style.position = "absolute";
c.style.top = "0";
c.style.left = "0";
c.style.zIndex = "2";
ctx = c.getContext("2d");
game.records = new Array(botData.length).fill(0);
game.log = log;
game.pause = !1;
game.fps = fps;
(window.onresize = function() {
wdim = [window.innerWidth || 600, window.innerHeight || 400];
scale = Math.ceil(wdim[1] / zoom);
c.width = wdim[0];
c.height = wdim[1];
})();
window.onkeydown = function() {
var key = event.code;
if (key == "Escape")
game.pause = !game.pause;
if (key == "ArrowLeft" && game.fps > 1)
game.fps -= 1;
if (key == "ArrowRight")
game.fps += 1;
};
game.debug = function() {
ctx.clearRect(0, 0, wdim[0], wdim[1]);
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = Math.floor(scale * 0.6) + "px monospace";
for (let x = -Math.ceil(wdim[0] / 2 / scale), i = wdim[0] / 2 - (Math.ceil(wdim[0] / 2 / scale) - 0.5) * scale; i <= wdim[0]; i += scale, x++) {
for (let b, c, y = -Math.ceil(wdim[1] / 2 / scale), j = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; j <= wdim[1]; j += scale, y++) {
if ((c = game.chars.filter(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))).length) {
for (let k = 0; k < c.length; k++)
ctx.fillText(JSON.stringify(c[k].char).slice(1, -1).replace(/\\"/, "\"").replace(/\\\\/, "\\").replace(/ /, "_"), i + scale / 2, j + scale / 2);
}
if (b = game.bots.find(a => a.pos[0] == Math.floor(x) && a.pos[1] == Math.floor(y))) {
ctx.fillStyle = b.color;
ctx.fillRect(i, j, scale, scale);
ctx.fillStyle = "#000000";
}
}
ctx.lineWidth = 0.1;
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, wdim[1]);
ctx.stroke();
}
for (let i = wdim[1] / 2 - (Math.ceil(wdim[1] / 2 / scale) - 0.5) * scale; i <= wdim[1]; i += scale) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(wdim[0], i);
ctx.stroke();
}
ctx.fillRect(wdim[0] / 2 - 3, wdim[1] / 2 - 3, 7, 7);
};
runRound(turns);
}
function runGame(rounds = 1, turns = 100000, log = 0) {
game.records = new Array(botData.length).fill(0);
game.log = log;
for (let i = 0; i < rounds; i++)
runRound(turns, 0);
console.log("Game Conclusion:\n" + botData.map((a, b) => [a.name, game.records[b]]).sort((a, b) => b[1] - a[1]).map(a => "[" + a[1] + "] " + a[0]).join("\n"));
}
};
drawRound(/*turns =*/ 1000000, /*log =*/ 2, /*fps =*/ 600,/* zoom =*/ 50);
```
] |
[Question]
[
# Context
In this challenge, a random walk is a stochastic process in which a particle at a position with integer coordinates (or a drunk man) moves at each integer time step (that is, at `t = 1, 2, 3, ...`) by taking a step of size `1` to any of its neighbouring positions, with the direction of the step being aligned with the axis, but chosen randomly
For example, in one dimension, we may have the following table of positions at the given times, starting at `t = 0` with the initial condition `p = 2`:
```
----------
| t | p |
----------
| 0 | 2 |
----------
| 1 | 3 |
----------
| 2 | 2 |
----------
| 3 | 3 |
----------
| 4 | 2 |
----------
| 5 | 1 |
----------
| 6 | 0 |
----------
| 7 | -1 |
----------
| 8 | 0 |
----------
| 9 | -1 |
----------
...
```
# Task
Your task is to simulate a random walk in `n` dimensions from a supplied starting point, until the drunk man arrives at the origin **for the first time**, i.e. when we reach the point with coordinates `[0,0,...,0]` for the first time. *If we start at the origin, nothing has to be done because we already arrived.*
In the example above, the program would have stopped at `t = 6`.
You can take whatever probability distribution you want over the possible directions to go, so long as, for any position and any direction, there is a non-zero probability of that direction being picked.
Notice that your program must work for an arbitrary dimension, even though in practice, for higher dimensions it will not stop in a reasonable amount of time.
# Input
Any initial position with integer coordinates, of any positive size (so 1 or more). You can infer the dimensions of the random walk from the size of the input or you can take the dimension as an extra input. If you do, assume the dimension given matches the size of the initial position.
Input of initial position can be in any sensible format, including:
* a list of integers
* one input coordinate per function argument
Your program should work for any `n`, even though in practice it will time out for `n >= 3` unless you are incredibly lucky :)
# Output
You should return or print any of the following:
* all the intermediate positions occupied by the particle until the end of the random walk
* all the intermediate steps taken by the particle until the end of the random walk
The intermediate positions can be displayed in any human-readable way, as long as no two different positions are displayed the same way. Same applies to intermediate steps taken.
# Test cases
These should finish on TIO often:
```
[3]
[1, 0]
[0, -2]
[1, 1]
[-1,1]
[0]
[0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
```
These will probably timeout, but that is fine as long as your program runs:
```
[1, 0, 0, 0]
[0, 0, 3, 0, -2, 100]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
```
You can check [this reference program](https://tio.run/##jU/LioMwFN3nK860m2SaQmx3A36JiIiJNYzmSrSUfr29mnZWLgZCwrnncU/G59xRuC5LG2lArIPlxw8jxXlDPswaTUe@cRqTc1aI9ZYXJYR1LSY/3Pt6dlWyVo@6/5UjTepHAAE5ehc2zJCiv/l1Vhi0FFGBEftuTgZVClaMkfd95I/O9w4M8JW/vWso0BBFyzHvftJohHOmNs76yEwqLItzppGVieGgYnOWOOWrLk3/Ni67XykubE@iw/GAb1yNEvvKTBtt/q3m0vunVMsL) where I set the seed so that you can see it terminating for a random walk of 3 dimensions.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
LXṬ,N$X+µẸп
```
A monadic Link accepting a list of integers which yields a list of lists of integers.
**[Try it online!](https://tio.run/##ASIA3f9qZWxsef//TFjhuawsTiRYK8K14bq4w5DCv////1sxLDBd "Jelly – Try It Online")**
How?
```
LXṬ,N$X+µẸп - Link: list of integers, p (length d)
п - collect up while...
Ẹ - ...condition: any? (when we reach [0]*d this does not hold
µ - ...do: the monadic chain - i.e. f(v); initially v=p:
L - length (of v) = d
X - random integer (in range [1,d])
Ṭ - untruth e.g. 4 -> [0,0,0,1]
$ - last two links as a monad:
N - negate [0,0,0,-1]
, - pair [[0,0,0,1],[0,0,0,-1]]
X - random choice [0,0,0,1] OR [0,0,0,-1]
+ - add (to v) e.g. [0,0,0,-1] + [4,2,3,2,5] = [4,2,3,1,5]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 99 bytes
```
#//.i_/;Union@i!={0}:>(i+RandomChoice@Select[Tuples[{-1,1,0},d=Tr[1^i]],#~Count~0==d-1&])&&Print@i&
```
[Try it online!](https://tio.run/##HczdCoIwGIDhWymEUTTTdZgsBt5AP3Y0VoztQz9wW9g8Er31JZ29J8/rdOzA6YhGp5anrCiO@C6qp8fgBW75VM7nyw4Pd@1tcHUX0IB4QA8mymb89PCVU84oo@VMLW8GyV6oFM2WOow@LiXnNmdE7Qm5DuijQJL@sRG3ESGKVk6rXf1pPaiUfg "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 48 bytes
```
{{[(.rand+|0=>(-1,1).pick){^$_}Z+@$_]}...*.none}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ujpaQ68oMS9Fu8bA1k5D11DHUFOvIDM5W7M6TiW@NkrbQSU@tlZPT09LLy8/L7X2f3FipUKaRrShjkGs5n8A "Perl 6 – Try It Online")
Returns all intermediate positions.
### Explanation
```
{ } # Anonymous list
... # Create sequence
{ } # Compute next item by
( => ) # Create pair with
.rand+|0 # random integer in [0,dim) as key
(-1,1).pick # -1 or 1 as value
{^$_} # Lookup values [0,dim)
Z+@$_ # Add to previous vector
[ ] # Store in array
*.none # Until all coords are zero
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~92~~ ~~87~~ ~~82~~ ~~81~~ 75 bytes
Input: the starting position (as list) and number of dimensions.
```
def f(p,d):
r=id(f)
while any(p):p[r%d]+=r//d%2*2-1;print(p);r=hash((r,))
```
[Try it online!](https://tio.run/##fY7LCoMwEEX3fsVFEJI24mun5EvEhRBDAhLDVCh@fZoodlPocBkOc2dx/LGbzXUhqEVDMy8U7zOQtIppnuFt7LpgdgfzvPcjFWp6SqoqVbSPtmwGT9btsRtImvllGCPBedAbwcM6sAxjN4m4G4H6hFqgbO9Tg5PKhFd7/0RAJCS8gm/1m1gl7eS/Li76RPVLLZf/JufhAw "Python 3 – Try It Online")
## Explanation
I created my own custom random generator as follow:
* `r=id(f)`: seed the generator - this is the source of randomness since the ID of `f` is different each time the program runs.
* `r=hash((r,))` generates the next random by hashing the tuple `(r,)`. This is the shortest I could find, as `hash(r)` just returns `r`, while `hash([r])` is not valid due to list not being hashable.
This ended up being shorter than using `random` or `time` module.
For each iteration, the program simply picks a random coordinate and add `1` or `-1` (randomly) to it.
* `r%d` is a random number between `0` and `d-1` inclusive, used to pick a random coordinate.
* `r//d%2` is a random number in \$\{0,1\}\$, and `(r//d%2)*2-1` maps it to \$\{-1,1\}\$.
`any(p)` checks if `p` has some non-zero coordinate, in which case the programs continue to run.
In case `id` and `hash` are not considered "random" enough, here is the same program but using `time` for randomness
# [Python 3](https://docs.python.org/3/), ~~92~~ ~~87~~ ~~82~~ 81 bytes
*-1 byte thanks to @RGS*
```
import time
t=time.time_ns
def f(p,d):
while any(p):p[t()%d]+=t()%2*2-1;print(p)
```
[Try it online!](https://tio.run/##fY7NCoMwEITveYpBKCRtLP7cLD6JSCkYMaBx0UDx6dOsYi@FLsPOx84ehjY/zK4MwU40Lx7eTkb4mu3O6@lW0ZkevSTdqUrgPdjR4OU2Saqixkt16dpbzV5cizR/0GKdj2Ho5wUE6yAFmrLVceca2Q6ZRlqcpxw7pYxHev5EQCQwHsI3@lWMuCFXHY2LFZTA0Sap/02iwgc "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
W⌈↔θ«≔‽Lθι§≔θι⁺§θι⊖⊗‽²⟦Iθ
```
[Try it online!](https://tio.run/##TY09C8IwGIRn/RUZ30A71NWp2EWwUFxDhzR5aQP5oPnQgvjbYwoK3nLw3HEnFu6F4zrn56I0Euj5pkwy0E7B6RQRVkopeR0PbQhqtnDnVjoDN7RzXPawIoqef3Ebr1biBmuhFRl0CvCPSrlD4dGgjSihc2nSxb@bJ7qrbA1e2QjswkMsD2NB75wZq5uKNOOY64f@AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W⌈↔θ«
```
Repeat until the origin is reached. (`W⊙θκ«` also works for the same byte count.)
```
≔‽Lθι
```
Pick a random dimension.
```
§≔θι⁺§θι⊖⊗‽²
```
Move one step randomly along that dimension.
```
⟦Iθ
```
Output the new coordinates. The `⟦` double-spaces the coordinates for clarity, but if that's not required then it could be removed.
Bonus program:
```
JNNW∨ⅈⅉ✳⊗‽φ¹@
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@rNLcgJF/DM6@gtMSvNDcptUhDU0cBhatpzVWekZmTqqDhX6QRAZKOBApqKgQUZeaVaLhkFqUml2Tm52m45Jcm5aSmaAQl5qXk52qkAdXoKBgCdUMUKjkoaVr//2/IpWv4X7csBwA "Charcoal – Try It Online") Takes two dimensions only. Sample output:
```
|
||----
----@
||
|-
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[=D_P#āDΩQD(‚Ω+
```
Inspired by [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/199921/52210).
[Try it online.](https://tio.run/##MzBNTDJM/f8/2tYlPkD5SKPLuZWBLhqPGmadW6kNFNU11DGMBQA)
**Explanation:**
```
[ # Start an infinite loop:
= # Print the current list with trailing newline (without popping),
# (which will use the implicit input-list in the very first iteration)
D # Duplicate the current list
_ # Check for each value whether it is 0
# i.e. [0,4,0] → [1,0,1]
P # And if all are truthy:
# # Stop the infinite loop
ā # Push a list in the range [1,length] (without popping)
# i.e. [0,4,0] → [1,2,3]
D # Duplicate it
Ω # Pop and push a random value from this list
# i.e. [1,2,3] → 3
Q # Check for equality; the random 1-based position becomes 1, the others 0
# i.e. [1,2,3] and 3 → [0,0,1]
D(‚ # Pair it with a negative copy of itself
# i.e. [0,0,1] → [[0,0,1],[0,0,-1]]
Ω # Pop and push either of these two lists
# i.e. [[0,0,1],[0,0,-1]] → [0,0,-1]
+ # And the values at the same indices
# i.e. [0,4,0] + [0,0,-1] → [0,4,-1]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 161 bytes
```
z(a,l,r)int*a;{for(r=0;l--;)r|=a[l];l=r;}p(a,l)int*a;{for(puts("");l--;)printf("%d,",*a++);}f(a,l)int*a;{for(srand(&l);p(a,l),z(a,l);)a[rand()%l]+=1-rand()%2*2;}
```
Prints all coordinates.
Example output:
```
0,-2,
1,-2,
1,-1,
1,0,
2,0,
1,0,
0,0,
```
*-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
[Try it online!](https://tio.run/##lZHdaoMwFIDvfYpg6cjRhCZ2tIPgkzgvgjZFyFKJ3S7m8uwuagdDHDPh3ITzfTk/qei1qobhE0uiiYXG3BMpenWz2OZMaEoF2K9cFroUOrfCtSP4G2vf7x2OY5jZ1vqUwvG@JjFJZJqCcGqpdFaaGj9pEPNrZKoOAmQxZWCvyzTn9HHJkky4wfvoTTYGf9yaGqI@2jUK8Qj5ozD22aKEHh2RI4iDQD@NvBpKqe9uCXKC2MhmG1hGEM22wv5hvpWlITDbOhoLG@0Ro/EcZJCF/bJm7y66u0SHw8r6/6n7h3Mk83/4XbBJPgXIATFt@7w@kqkbFbnhGw "C (gcc) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~68~~ ~~63~~ ~~61~~ 57 bytes
-4 bytes thanks to mazzy
```
param($n,$d)for(;$n-ne0){$n[(random $d)]+=1,-1|random;$n}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlT0clRTMtv0jDWiVPNy/VQLNaJS9aoygxLyU/VwEoFatta6ija1gDEQEqqv1fy8WlppKmoKFjrKlgyKWuDuEZ6hhoKhjBuQY6UKipYPofAA "PowerShell – Try It Online")
[Less Ugly Form for 2 extra bytes.](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlT0clRTMtv0jDWiVPNy/VQLNaJS9aoygxLyU/VwEoFatta6ija1gDEbFWUslTqv1fy8WlppKmoKFjrKlgyKWuDuEZ6hhoKhjBuQY6UKipYPofAA "PowerShell – Try It Online")
The neat part of this answer is the for conditional, `$n-ne0`. When you apply comparison operations to arrays, it applies it to each element and acts as a filter, in this case filtering out all 0s. If we filter everything out (i.e., we're at `(0,0,...,0)`), we get an empty array and those are considered false. As a side note, for the singleton case, you have to explicitly cast the parameter to a list. Otherwise, it wants to play ball as an int which doesn't go over well.
I reread the comments and noticed you didn't need to print the initial config, saving 5 bytes. This now means things that start at the origin return nothing but that seems up to spec.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
`p(l)` prints the contents of `l` and then returns the same array as well, making things very convenient as we can wrap the print statement into the termination condition.
```
->l,d{l[rand d]+=rand(2)*2-1until[]==p(l)-[0]}
```
[Try it online!](https://tio.run/##FcZBDsIgEADAu6/gCBaocsePbDemhtZsslYC24O2fTvGOU1ZH582x@ZubNPGUMYlqYRd/EcHcw7uui5CDBhj1mwcXPBorKJ6TlJ9zUyie7BDxa43/jXmbaedfJVC2cv7TsdpBraKfaXvhC3Y8AM "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), ~~63~~ 62 bytes
```
f=a=>a.join``==0?[a]:[a,...f(a.map(x=>x+~-(3*Math.random())))]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbR1i5RLys/My8hwdbWwD46MdYqOlFHT08vTSNRLzexQKPC1q5Cu05Xw1jLN7EkQ68oMS8lP1dDEwhi/yfn5xXn56Tq5eSna6RpRBvHampyoYkZ6igYYBE20FHQNcKu3BCLsK6hDjZhHCbjEoYgvJLICKjwPwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~83~~ ~~79~~ 75 bytes
```
For[r=RandomInteger;i=#,!0==##&@@i,j=r@{1,Tr[1^i]};i[[j]]+=2r[]-1,Print@i]&
```
[Try it online!](https://tio.run/##BcHBCsIwDADQu38xCmNihNVrCeQkeBvDW4hQtNMM2kHobezb63s51l/Kseo7tgWHdt@MDedYPlt@lJq@yYKig25EdK4nUljRaPfwNPYvlSMo8ypywZuxXD1MpqWSSt/O4bTQPoI/2h8 "Wolfram Language (Mathematica) – Try It Online")
Omits the last result (which is the origin anyway).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 74 bytes
```
x=input('');do disp(x),x(randi(size(x)))+=2*randi([0 1])-1;until~x;disp(x)
```
[Try it online!](https://tio.run/##y08uSSxL/f@/wjYzr6C0RENdXdM6JV8hJbO4QKNCU6dCoygxLyVTozizKhXI19TUtjXSgghFGygYxmrqGlqX5pVk5tRVWEP1/P8PlgEA "Octave – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~105~~ \$\cdots\$ ~~89~~ 86 bytes
Saved 3 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
```
from random import*
def f(p,l):
while any(p):p[randrange(l)]+=choice((-1,1));print(p)
```
[Try it online!](https://tio.run/##ZY9NCoMwEIX3nmJ2ZmwCRneWnkRciCY1EJMQAsXTpxPFbgrz8zHvLd6EI23e9Tnr6HeIs1tpmT34mJpqVRo0C9ziUMFnM1bB7A4WcAhjsVK/FbM4PV7L5s2iGBOSS8RniMYlMmbtIyQwDlgFYz9xmpJDe0LLQXT3ScJJouCl3h4CIIKCV8FP@i@SStorQMKKHkjcKkeM97kWddP1mL8 "Python 3 – Try It Online")
[Answer]
# BATCH, ~~563 560 539 509~~ 653 bytes
```
@ECHO OFF
Setlocal EnableDelayedExpansion
Set "#=Set "
!#!/P N=D
!#!"F=For /L "
!#!I= in (1,1,
!#!D=) Do (
!#!E=) ELSE (
!#!C=CALL :
!#!Y=2
%F%%%A%I%!N!%D%
!#!O%%A=0
!#!/P S%%A=Ax%%A
!#!H%%A=!S%%A!)
%F%%%A%I%50000%D%
!#!v=0
!C!R U N
!C!M S!U! H!U!
!#!]=@
%F%%%B%I%!N!%D%
!#!"]=!]!!S%%B!,"
IF %%B==!N! !#!]=!]:~,-1!
IF !O%%B!==!S%%B! !#!/A v+=1
IF !v!==!N! GOTO :E
)
ECHO(!]!
)
:E
ECHO(!]!
pause
:M
!C!R R Y
!C!R P Y
IF !R!==1 (IF !%1! LEQ 0 (IF !P!==1 (!#!/A %1+=1%E%!#!/A %1-=1)%E%!#!/A %1-=1)%E%IF !%1! GEQ !%2! (IF !P!==2 (!#!/A %1-=1%E%!#!/A %1+=1)%E%!#!/A %1+=1))
Exit /B
:R
!#!/A %1=!random! %%!%2! +1
Exit /B
```
**Update**
At the cost of alot of bytes, I corrected the issues with zero chance for movement along any axis under the previous conditions, and through the use of an additional random test in an Ugly, byte hungry conditional statement still biased movement (In a non zero manner compliant with the terms outlined).
also modified the output to match the specified form.
[Example Output](https://pastebin.com/A2Zp3i3M)
] |
[Question]
[
Take a string as an input, and perform addition/subtraction of all the digits in the string and output the sum of those operations as the result.
## Rules
* The digits in the string are read from left to right
* If a digit (n) is odd, perform addition with the next digit (n + n1)
* If a digit (n) is even, perform subtraction with the next digit (n - n1)
* If you've reached the last digit in the string, perform the operation with the first digit in the string
* Output will be the sum of all the resulting values
* If there is only one digit in the string, perform the operation with itself (n+n or n-n)
* If there are no digits in the string, output is 0
## Example
```
Input: r5e6o9mm!/3708dvc
Process: (5+6) + (6-9) + (9+3) + (3+7) + (7+0) + (0-8) + (8-5)
Output: 32
```
## Notes
* Either function or full program is accepted
* Maximum input length would depend on your language's limit for a string input
* No restrictions on character input, but only half-width digits count towards the output
* Fewest bytes wins
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17 15~~ 12 bytes
```
fØDV€ḂT‘ịƲSḤ
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//ZsOYRFbigqzhuIJU4oCY4buLxrJT4bik////J3I1ZTZvOW1tIS8zNzA4ZHZjJw "Jelly – Try It Online")
[Try test cases.](https://tio.run/##y0rNyan8/z/t8AyXsEdNax7uaAp51DDj4e7uY5uCH@5Y8v/h7i2H24ES//@rq6sXmaaa5Vvm5irqG5sbWKSUJXOZpJhwmaaacpnr6upyqVmocSUmJXMZchkAFQMA)
The program keeps only the digits that follow an odd digit then computes twice the sum.
```
fØDV€ḂT‘ịƲSḤ
f Remove anything that isn't...
ØD a digit.
V€ Cast each digit to an integer
Ʋ Monad:
Ḃ Parity of each digit.
T Indices of truthy elements (odd digits).
‘ Increment.
ị Index into list of digits.
Wraps to beginning and if there are no digits this returns 0.
S Sum.
Ḥ Double.
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~47~~ ~~43~~ ~~40~~ 31 bytes
**Solution:**
```
{+/(1_x,*x)*2*2!x^:(x-:48)^!10}
```
[Try it online!](https://tio.run/##y9bNz/7/v1pbX8MwvkJHq0JTy0jLSLEizkqjQtfKxEIzTtHQoNZB30pDqcg01SzfMjdXUd/Y3MAipSxZyVopMSnZEEilpKYZAamKyiolzf//AQ "K (oK) – Try It Online")
**Explanation:**
Remove everything from string that isn't a number (whilst also converting), modulo 2, multiply by 2, multiply with x rotated by 1, and sum up.
```
{+/(1_x,*x)*2*2!x^:(x-:48)^!10} / solution
{ } / lambda taking implicit x
!10 / range 0..10
^ / except
( ) / do this together
x-:48 / subtract 48 from x (type fudging char ascii value -> ints), save back into x
x^: / x except right, and save back to x
2! / modulo 2
2* / multiply by 2
* / multiply by
( ) / do this together
*x / first element of x
, / append to
x / x
1_ / drop first (ie rotate everything by 1)
+/ / sum, add (+) over (/)
```
**Naive solution:**
Remove everything from string that isn't a number (whilst also converting), take 2-item sliding window, figure out whether they are odd or even, apply add/subtract as appropriate, then sum up.
```
{+/((-;+)2!x).'2':(1+#x)#x^:(x-:48)^!10}
```
[Try it online!](https://tio.run/##y9bNz/7/v1pbX0ND11pb00ixQlNP3UjdSsNQW7lCU7kizkqjQtfKxEIzTtHQoNZB30pDqcg01SzfMjdXUd/Y3MAipSxZyVopMSnZEEilpKYZAamKyiolzf//AQ "K (oK) – Try It Online")
**Notes:**
* **-4 bytes** thanks to @ngn due to a smarter way of filtering the input
* **-3 bytes** by using sliding window rather than reshape
* **-9 bytes** porting ngn's solution (non-naive approach)
[Answer]
# [Python 2](https://docs.python.org/2/), 86 bytes
```
k=[int(a)for a in input()if'/'<a<':']
print sum(a-(-1)**a*b for a,b in zip(k,k[1:]+k))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9s2OjOvRCNRMy2/SCFRITMPiApKSzQ0M9PU9dVtEm3UrdRjuQqKgIoUiktzNRJ1NXQNNbW0ErWSFMBadJJAmqoyCzSydbKjDa1itbM1Nf//VyoyTTXLt8zNVdQ3NjewSClLVgIA "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 41 bytes
```
{2*sum rotate($!=.comb(/\d/))Z*(@$! X%2)}
```
[Try it online!](https://tio.run/##BcHRCoMgFADQ9/sVCk00UEfLag/BPmOMvZgaDGaGWhBjvz53zuriuyv@QGRGIyqfpk6bRzFknR2t8ChM8BOVTysZe9T0VmF0PzXsWwSZRdJHicp14eo9lpf@PNjdQGtbUE5BzzkHMhDQkwH1C2t@hSUVvvwB "Perl 6 – Try It Online")
Uses the same logic as [dylnan's Jelly answer](https://codegolf.stackexchange.com/a/168042/76162). This sums only digits that follow an odd number and then multiplies by 2.
[Answer]
# Powershell, ~~80~~ ~~78~~ 76 bytes
```
($d="$args"-split'\D*'-ne'')+$d[0]|?{$p-match'[13579]';$p=$_}|%{$s+=2*$_};$s
```
-2 bytes thanks [Neil](https://codegolf.stackexchange.com/users/17602/neil) with Retina solution
-2 bytes thanks [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork)
Test script:
```
$f = {
($d="$args"-split'\D*'-ne'')+$d[0]|?{$p-match'[13579]';$p=$_}|%{$s+=2*$_};$s
}
&$f 'r5e6o9mm!/3708dvc'
```
## Explanation
First of all: it sould add 2\*n if previous digit is odd, and 0 if a previous digit is even.
```
($d="$args"-split'\D*'-ne'')+ # let $d is array contains digits only, each element is a digit
$d[0]| # apend first digit to the end of the array
?{ # where for each digit
$p-match'[13579]' # predicate is 'previous digit is odd' (it is false on the first iteration because $p is null)
$p=$_ # let previous digit is current
}|
%{ # for each digit matched to the predicate
$s+=2*$_ # add current digit multiply 2 to $s.
}
$s # return sum
```
---
## Extra, 99 bytes
Inspired by @Neil. Regex match digits with 'previous digit is odd' only. `Matches` is an [automatic variable](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables).
```
param($d)$d+($d-match'\d')+$Matches[0]|sls '(?<=[13579]\D*)\d'-a|%{$_.Matches.Value|%{$s+=2*$_}};$s
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~18~~ 17 bytes
```
t4Y2m)!Ut1YSof)sE
```
[Try it online!](https://tio.run/##y00syfmf8L/EJNIoV1MxtMQwMjg/TbPY9b9LZkmkn21dbMV/9SLTVLN8y9xcRX1jcwOLlLJkdS51QyNjE1MgnVicBiKTkg0rKtW5/BL9AA "MATL – Try It Online")
*(-1 byte thanks to Luis Mendo/Giuseppe/both!)*
Explanation:
```
% Implicit input
t % duplicate input
% stack: ['r5e6o9mm!/3708dvc' 'r5e6o9mm!/3708dvc']
4Y2 % push inbuilt literal, characters '0':'9'
% stack: ['r5e6o9mm!/3708dvc' 'r5e6o9mm!/3708dvc' '0123456789']
m) % extract only characters from input that belong to '0':'9'
% stack: ['5693708']
!U % transpose and convert each value from string to number
% stack: [5 6 9 3 7 0 8]
t % duplicate that
1YS % circular shift by 1
% stack: [[5 6 9 3 7 0 8] [8 5 6 9 3 7 0]]
o % parity check - 1 for odd, 0 for even
% stack: [[5 6 9 3 7 0 8] [0 1 0 1 1 1 0]]
f % find non-zero value indices in last array
% stack: [[5 6 9 3 7 0 8] [2 4 5 6]]
) % index at those places in the first array
s % sum
E % multiply by 2
% (implicit) convert to string and display
```
The basic idea is that numbers that follow even numbers can be ignored, while those that follow odd numbers are doubled - and the final result is the sum of those doubled values.
I didn't think `f` after the parity check `o` would be necessary, but for some reason MATL doesn't see the array of 0's and 1's that result from the `o` as a logical array, instead takes them as numerical indices and indexes into positions `1` and `end`.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 33 bytes
```
{+/(1_x,*x)*2*2!x:-48+x^x^,/$!10}
```
[Try it online!](https://tio.run/##JcnbCoIwGADg@56iDS88soMdbP@jiKapizAVhsS/xF59Yd198PXJeB@d02qJmC@uGIcYhDKUBFVyyCIssYyZRwRf3awWL7cfo/QeoZp68CtdP56AYMEExbqbc2qO3Wm6DANh6Zln7auhkMpim/rWCAp/t52WFPjPaN8b3Rc "K (ngn/k) – Try It Online")
`{` `}` is a function with argument `x`
`!10` is the list `0 1 ... 9`
`$` convert to strings
`,/` concatenate
`x^` means `x` without what's on the right
`x^x^` means `x` intersected with what's on the right, i.e. keep only the digits from `x`
`-48+` subtract `48`, which is the ASCII code of `"0"`
`x:` assign to `x`
`2!` mod 2
`2*` multiplied by 2
`1_x,*x` is one drop of: `x` followed by the first of `x`; i.e. `x` rotated to the left by one step
`+/` sum
[Answer]
# Japt (v2.0a0), ~~25~~ 19 bytes
*-6 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974).*
```
kè\D
íȰ*2*Y°u}Ué)x
```
Try it [here](https://ethproductions.github.io/japt/?v=2.0a0&code=a+hcRArtyLAqMipZsHV9VekpeA==&input=WyJyIiwiNSIsImUiLCI2IiwibyIsIjkiLCJtIiwibSIsIiEiLCIvIiwiMyIsIjciLCIwIiwiOCIsImQiLCJ2IiwiYyJd).
It works with no digits this time! Input is a list of characters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 9 bytes
Saves 1 byte over the naive method by utilizing [dylnan's parity trick](https://codegolf.stackexchange.com/a/168042/47066)
Saved 3 bytes thanks to *Mr. Xcoder*
```
þDÁ€ÉÏSO·
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8D6Xw42PmtYc7jzcH@x/aPv//0WmqWb5lrm5ivrG5gYWKWXJAA "05AB1E – Try It Online")
**Explanation**
```
þ # push only digits of input
D # duplicate
Á # rotate right
ۃ # get the parity of each
Ï # keep only true items
SO # calculate digit-sum
· # double
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 37 bytes
```
(\d).*
$&$1
L$`(?<=[13579]\D*).
2**
_
```
[Try it online!](https://tio.run/##K0otycxLNPz/XyMmRVNPi0tFTcWQy0clQcPexjba0NjU3DI2xkVLU4/LSEuLK/7//yLTVLN8y9xcRX1jcwOLlLJkAA "Retina – Try It Online") Explanation:
```
(\d).*
$&$1
```
Append a duplicate of the first digit.
```
L$`(?<=[13579]\D*).
```
Match anything whose first previous digit is odd.
```
2**
```
Convert all the matches to unary and double them. (Non-digits are treated as zero.)
```
_
```
Take the sum. If there were no matches, then this produces zero as required.
The best I could do in Retina 0.8.2 was 44 bytes:
```
[^\d]
(.).*
$&$1
(?<![13579]).
.
$*
.
..
.
```
[Try it online!](https://tio.run/##K0otycxL/P8/Oi4mJZaLS0NPU0@LS0VNxZBLw95GMdrQ2NTcMlZTj4tLj0tFC0joAdH//0WmqWb5lrm5ivrG5gYWKWXJAA "Retina 0.8.2 – Try It Online") Explanation:
```
[^\d]
```
Delete non-digits.
```
(.).*
$&$1
```
Append a copy of the first digit.
```
(?<![13579]).
```
Delete digits that do not follow an odd digit.
```
.
$*
```
Convert to unary.
```
.
..
```
Double them.
```
.
```
Take the sum.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
fØDV€1ịṭƊ+_Ḃ?ƝS
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//ZsOYRFbigqwx4buL4bmtxoorX@G4gj/GnVP///9yNWU2bzltbSEvMzcwOGR2Yw "Jelly – Try It Online")
[Answer]
# JavaScript (ES6), 56 bytes
Takes input as an array of characters.
```
s=>s.map(c=>1/c?r+=p*(p=c*2&2,n=n||c,c):0,n=p=r=0)|r+p*n
```
[Try it online!](https://tio.run/##hcpBDsIgEEDRvbewCwO0UqzWqsnUgxgXZEqNpsAETFfcHfUA6u4n7z/0rCOGOz3Xzg8mj5Aj9FFaTQyh39R4DiWQYAQomlVTOXApYYX8pN5NEEDxFEoSLqN30U9GTv7GRnaRUhahNXt/tHZZbzt1GGYsrpwv/o3dj3H3DdoP5Bc "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // given the input array s[]
s.map(c => // for each character c in s[]:
1 / c ? // if c is a digit:
r += // update r:
p * ( // p = either 0 or 2 (always 0 on the 1st iteration)
p = c * 2 & 2, // p = 0 if c is even, 2 if c is odd
n = n || c, // if n is still equal to 0 (as an integer), set it to c
c // compute p * c
) // add the result to r
: // else:
0, // do nothing
n = p = r = 0 // n = first digit, p = previous digit, r = result
) // end of map()
| r + p * n // compute the last operation with the 1st digit and add it to r
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 85 84 83 82 bytes
-1 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
```
s=>(s.match(/\d/g)||[]).reduce((r,n,i,a)=>r+(+n)+a[a[++i]!=null?i:0]*-(1-n%2*2),0)
```
[Try it online!](https://tio.run/##dcrLEoIgFIDhfW/hovEcwUs13Qd7EHPBABoNQgPqynenaW/b7//ffOZBeP0Zc@ukih2LgdUQioGP4gXlU5Y9LkvTYuGVnIQC8NRSTTmy2hMgFglveEOIbhNmJ2Me@la1WQ673G732R5phVE4G5xRhXE9dJD6ozq56zAk5eFcXeQsUsT75t@0Hlf1h/EL "JavaScript (Node.js) – Try It Online")
Takes the string input, finds the digits as an array of characters or returns empty array if none found, and then uses type coercion to ensure the values are added/subtracted correctly. The forward lookup preincrements the index and uses a null check for brevity, and then the final part checks whether number is odd or even to then force addition or subtraction ( + and - is -, etc)
[Answer]
# [R](https://www.r-project.org/), 58 bytes
```
function(x,y=strtoi(x[x%in%0:9]))sum(c(y[-1],y[1])*y%%2*2)
```
[Try it online!](https://tio.run/##tdLRCoIwFAbge5/CiDEnRnOSZeCTiBe1FLxQQ2fMp19/KeGFN6UNvpsd@Hc4Z43JY5N3lVRFXTna6@NWNaouHJ1oUlSEn6OUsbYrHen0yc5PvT7xU@b2hAhXMJPjnjbUowfIIIQaIihHG9hDAEfgcIIbPEBSxuytnel7JlV2swNhvXM1agPUfz2TXD7E@kviZmLHbsXKsZ9uPXoBAddxiPLbpyax4RC7RrMz3fL/DOH1mxavbboyblnmCQ "R – Try It Online")
* using [dylnan's parity trick](https://codegolf.stackexchange.com/a/168042/41725)
* -8 bytes accepting vector of characters instead of strings
* -3 byte thanks to @Giuseppe
[Answer]
## [Perl 5](https://www.perl.org/), 48 bytes
```
$;=$;[++$-%@;],$\+=$_%2?$_+$;:$_-$;for@;=/\d/g}{
```
[Try it online!](https://tio.run/##K0gtyjH9/1/F2lbFOlpbW0VX1cE6VkclRttWJV7VyF4lXlvF2kolXlfFOi2/yMHaVj8mRT@9tvr//yLTVLN8y9xcRX1jcwOLlLLkf/kFJZn5ecX/dQsA "Perl 5 – Try It Online")
I quite like how cryptic this looks, but it's a pretty straightforward loop around all the numbers in the string.
[Answer]
# [Julia 0.6](http://julialang.org/), ~~77~~ 69 bytes
```
s->(s=s.-'0';s=s[0.<=s.<=9];endof(s)>0?sum(2(s%2).*[s[2:end];s[]]):0)
```
[Try it online!](https://tio.run/##TYzZCsIwFETf/YoYkN5IG9PUVrv6ISEPtQtUutFrRb8@VlF0YGAOB@Yyt00emJqkxKCTAabIHUtY8TKU4MmCSRrquOrLoQZkmTjh3IEE3EjGtwqVjBanY1Ras0gw0@UjLE/j1PTXtocaFHLONWM2gRV5h05@FQxh16133kEcy1tB7a9ypbf3f5hj/Qfnwr0/qE3oq4La1KUfx5h5Ag "Julia 0.6 – Try It Online")
[Answer]
### C Sharp 180 bytes
This isn't very good golfing, lol.
```
s=>{var q=new Queue<int>(s.Where(Char.IsNumber).Select(n=>n-48));q.Enqueue(q.First());int t,o=0;o=q.Dequeue();try{while(true){t+=o+(o%2==0?-1:1)*(o=q.Dequeue());}}catch{return t;}}
```
Ungolfed :
```
var q = new Queue<int>(s.Where(Char.IsNumber).Select(n=>n-48));
int t,o=0;
q.Enqueue(q.First());
o=q.Dequeue();
try{
while(true){
t += o + (o%2==0?-1:1) * (o=q.Dequeue());
}
}
catch {
return t;
}
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÿ←«4é■≥B▬ê→█T♥
```
[Run and debug it](https://staxlang.xyz/#p=981bae3482fef24216881adb5403&i=r5e6o9mm%21%2F3708dvc&a=1)
Unpacked, ungolfed, and commented, it looks like this.
```
Vd|& filter out non-digits
c|(\ zip into pairs after rotating right
F for each digit pair
B2%s first-of-pair % 2, then swap top two stack elements
eH* eval digit as integer, double, then multiply
+ add to running total
```
[Run this one](https://staxlang.xyz/#c=Vd%7C%26++%09filter+out+non-digits%0Ac%7C%28%5C++%09zip+into+pairs+after+rotating+right%0AF+++++%09for+each+digit+pair%0A++B2%25s%09first-of-pair+%25+2,+then+swap+top+two+stack+elements%0A++eH*+%09eval+digit+as+integer,+double,+then+multiply%0A++%2B+++%09add+to+running+total&i=r5e6o9mm%21%2F3708dvc&a=1)
[Answer]
# JavaScript (ES6), 52 bytes
```
s=>s.filter(t=>1/t&&~(a+=u*t,u=t%2),a=u=0)[0]*u+a<<1
```
Expects input as an array of characters.
Caveat: Due to use of bit-shifting, the output has an upper bound of `2^31-1`
[Try it online!](https://tio.run/##ZchLCoMwFEDReVeRDmoSjX/sB3zZSCk0aCyWaMS8OOzW04HQSSf3wnmrTbluHRdMZ9vrMEBwIF02jAb1yhBkmWMUfZhKwMcoPOCp4kKBh4Lfi0fsE9W2ZUACxBGQpLOzs0Znxr6YE4SmkgoyMJe5xYz4fHJ@QEbXRp/tbZqOeX0prv3W0X9ufry33ldRHr4 "JavaScript (Node.js) – Try It Online")
# Explanation
Essentially doubles the sum of the digits following odd values.
```
s => s.filter( // filter to preserve the first digit
t =>
1/t && // short-circuits if NaN
~( // coerce to truthy value
a += u * t, // adds value only if previous digit is odd
u = t%2 // store parity of current digit
),
a = u = 0
)[0] // first digit
* u + a
<< 1 // bit-shift to multiply by 2 (also coerces a NaN resulting from a string devoid of digits to 0)
```
] |
[Question]
[
A person has two first names if their last name is also a common first name. You are tasked with determining which full names in a list are two first names.
```
John Smith
John Doe
Luke Ryan
Ryan Johnson
Jenna Jackson
Tom John
```
Any name that occurs in the first name column is potentially a first name. If the number of occurrences of the name in the first name column is *greater* than the number of occurrences in the last name column, it is **definitely** a first name.
In the above list, `John` appears twice in the first names and once in the last names so it is definitely a first name. `Ryan` appears once in the first and once in the last so it is (probably) a first name.
Therefore, `Tom John` definitely has two first names and `Luke Ryan` probably does.
Given the above list, your code should output the follow:
```
Luke Ryan has two first names
Tom John definitely has two first names
```
---
**Input**
As mentioned above, your code will take in a list of full names (from standard input, one per line) separated by spaces. Names can include hyphens or apostrophes, but you will never be given a first or last name that includes spaces (ie no `Liam De Rosa`, but `Liam De-Rosa` or `Liam De'Rosa` are fair game. In other words, names will match `[-'A-Za-z]+`.
Each full name will be unique (ie `John Smith` will not appear twice).
**Output**
Print full names names (once per line) followed by either `has two first names` or `definitely has two first names` if they meet the criteria above. Names should only be printed once.
Names that are not two first names do not need to be printed.
You must preserve the case and special characters of the name.
**Examples**
Input
```
Madison Harris
Riley Hudson
Addison Hills
Riley Phillips
Scott Hill
Levi Murphy
Hudson Wright
Nathan Baker
Harper Brooks
Chloe Morris
Aubrey Miller
Hudson Lopez
Samuel Owen
Wyatt Victoria
Brooklyn Cox
Nathan Murphy
Ryan Scott
```
Output
```
Riley Hudson definitely has two first names
Ryan Scott has two first names
```
Input
```
Owen Parker
Daniel Hall
Cameron Hall
Sofia Watson
Mia Murphy
Ryan Jones
Emily Ramirez
```
Output
```
[no output]
```
Input
```
Olivia Robinson
Jacob van-Dyke
Jacob Ella
Brayden De'Rosa
Levi Brook
Brook Bella
Ella Hill
Ella Anderson
Brook-Anne van-Dyke
```
Output
```
Jacob Ella definitely has two first names
Levi Brook has two first names
```
**Notes and Scoring**
* This is code golf. Lowest score (bytes) wins.
* [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
Good luck!
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~238~~ ~~222~~ ~~221~~ ~~220~~ 212 bytes
```
l->{for(String n:l){int k=0,j=0,q=0;for(String b=n.split(" ")[1];k<l.length;j+=l[k++].matches(b+" .*")?1:0)q+=l[k].endsWith(" "+b)?1:0;if(j>0)System.out.println(n+(j>q?" definitely":"")+" has two first names");}}
```
[Try it online!](https://tio.run/##pVVRb9owEH4uv@KUl5FRIvralFZQOlWobBVM46Hi4UgMMXHsYDt0GeK3MxNoqVabTmokpOi@u8/3fXcmC1xhU@SEL@J0S7NcSA0LEwsKTVnQkRJLFdbeAQ9UaUt4VvBIU8GDLv12eD2VdSu4KjIiT@UceWp5MWU0goihUjBAymFdUxq1ib0wXY20pHz@NLmGGZVKf8eMKGjDljWv1zMh63sc@CXz15RrSNut84X5Ldut8A0@bfNA5Yzqugee/3QxCdMrFjDC5zoJF402e0objUmQoY4SourThgfBV8@/ubhs@csKngSEx2pMdbKjaEwrLKSz@uK65Y9KpUkWiEIHuTlPM17nDYMsbzyIyYxyqgkrvUvP8w1zggr0s9grAr6T5PnhZrMNa2cHTw42rASNITPO1F98AJRz5Rujzs7gNbZzhJPn18C6Bv88Xl8kHEaZad87d6A9QWzYQ5ESGJbIbeAuDrtqJax4n3CO0McodST8FFlV723MQrxEX4Xpj4UNMKaGG@5RSqqsPVJGSrgvYkcLnfjAQBk7QfCYGJzm1oxRJLSuCKwOkhWFQSHzpLTB@85gLOk80baE76gTY3MXUyKtBChzIqErhUit7d0mTBAYCJdDnWIqjcKB6d9xwr7FB/PH8seqH7OCMPjxTKwOj0s09vyikRaSoi2j6p2V3Fz83ycscJtYLWI1BvsmyY83adc9PKJ0uNxDTo3Ge7QPeSRmFGGM2rFlt@aay2pP7fUDU/2BvL7gxDq/u4yyEoaYUWnmY9W//A/9jK5ME0Mxpc7rjJGYwgp5s1emxJ1xx5hjzFjGxuUe@TIUCp2XpVoH555Alzj4d@c6r2EFdnhMpENdRd7scE6OEt@aefwCBRhFJNf1pR8erX7/DXiDvq@Vn6hVn6jVBj3b1Dbbvw "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~141~~ ~~137~~ ~~132~~ 130 bytes
*-2 bytes thanks to @JonathanFrech*
```
n=map(str.split,input())
for f,l in n:
c=cmp(*[x.count(l)for x in zip(*n)])
if~c:print f,l,'definitely '*c+'has two first names'
```
[Try it online!](https://tio.run/##XVJNb@IwEL3zK0ZcTLpQrVY9VeLARyWEym4Fq3JAaDU4k2aEY0eOQ0kP@9dZ20mh2lP8Zt68eTOTsnG50T8u0qQ07vf7Fz0usBxUzt5XpWI3ZF3WbpAkvcxYyIYKWIN@7IEcy6Ic3O3O99LU2g1UEgjnkP5gn9DJPukBZ3/lY2lZu1A7FCllrNmRakDcyW8ixwrcu4GMbeVAY0GVuHgbsdufIGZRv9HgIfEtgc4kITj171ZUjMTdw/fLTixNrmFTsMvFEFo0NxTez/WRYN2gDiB8IWQrE/GStEZYojx2gd@miHmx7@3EClP2cVigtVzFelbUwKJOO/ok7Ris1BfCS@4xlzGykca5SIhu6MSwqm2ZNwG2SrC1/Ja7EPiJLvcWp3gkGwloS7IwtcYco9wsV4ZgZT4dTeqD9R1XXr@raCWfTUkfsT8WNSn49U7R8bZBb@eVpTOWMUSitmo0zMz5i4Wbybi0OEbcSlCCF7Sdwzlq9voLbAec@RvauLMWb0zGCFt03cZWHv0nvTSa4ixPBfsfY40FW@899lJ88gVrc@DryVCaA5xQj@bNkW6RJ6XCOP2pxSb1Duck1qbC/ufS45jXeWFKLV@Euut5IpjolGzXLZJHE63p1nL/Dw "Python 2 – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~127~~ 123 bytes
```
{a[$1]++
b[L[++X]=$2]++
N[X]=$0}END{for(;++i<=X;)if(A=a[L[i]])print N[i],(b[L[i]]<A?"definitely ":"")"has two first names"}
```
Saving 1 byte by not using the built-in `NR` value.
[Try it online!](https://tio.run/##PYxBa4NAEIXv@yuGJVBlE2h7bCJFMVBKsJBTQDyMcaSDm9myKwYJ@e02JqWXx/ceHw/P3TRdsFy8VMaoutyVxhyqZPE616Kc8fm6LfJL63y0NoY3yWEdcxulCd5krqr4x7P0UNx4GdWPbZO@64ZaFu7JjqDftI71Nwbozw5a9qEHwRMFfZ2mL8sDI@xdzRKcqE88uhoGlFU@dvRXt9aiyjyODQnk9LR3AdWOBobMO9epe0JGsza78MHWPiiVhvx8fHdWqQj9v/8C "AWK – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~120~~ 118 + 2 (`-al`) = 120 bytes
```
$f{$F[0]}++;$l{$k{$_}=$F[1]}++}{map{print$_.' definitely'x($f{$t}>$l{$t})." has two first names"if$f{$t=$k{$_}}}keys%k
```
[Try it online!](https://tio.run/##JYyxCsIwEIb3PsVRIlVKSzt0kjqJQ9FF3UQkaEJD2ktpIlpCXt1o6nLcff99/8DGrvKecEt2l@Lq0nRNOkukJTdX/1AZkLM9HewwCjTklifwYFygMKybkvcyqMZtgmXcKo@hpRrMSwEXozaAtGc6Fnx@q//Fzkk26YX0vlEtwqkXpo3mdatYtH9KBseJYhQGBK4VRg1DpNDQuwzXWfVz8lGDEQq1zw5VXpSFz2j3BQ "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~105~~ 129 bytes
+24 bytes because I missed part of the spec
```
->a{a.map{|e|l=e[r=/\S+$/];i=a.count{|n|n[/\S+/]==l};e+"#{' definitely'if i>a.count{|n|n[r]==l}} has two first names"if i>0}-[p]}
```
[Try it online!](https://tio.run/##Vc7BaoNAEAbgu08xpKFpCWrPTTcQSaGUQiE9Gg@jjmTIOiu7ahH12S3aUshlmPn5@BnbpN1UqPPk77HHoMSqH2jQimKrwvPXdh0mO1YYZKaRuh9kkHiOw0QpPe5ou7rrN5BTwcI16W7DBfD@htuFjnBBB/W3gYKtq0GwJLda9NPox1UyTlVTOyji9UugWcjNvzzcP2cXU1aPyfSpuWWEk0lZnBHvHTOTQoviH7sr/Z2vWqMXWexyEjjS5mQceh/UMkTWmKu3TIhoZrOFN9b6dztITnYuXox/EKH/9h8 "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~140~~ ~~127~~ ~~122~~ 131 bytes
```
N=map(str.split,input())
F,L=zip(*N)
for f,l in N:
if l in F:print f,l,'definitely '*(F.count(l)>L.count(l))+'has two first names'
```
[Try it online!](https://tio.run/##XVHLbtswELzrKxa@UHLlHNpbABfwI4YRWG6gAPEhyGEtUdXCFElQlBPl512SUuygt53l7OzMUve2VvLnpVAln08mk8t@3qCOW2vuWi3IpiR1Z@MkiTbpbv5JOp7uk6hSBqpUAEnY30dAFYR6c68NSeufUlbyiiRZLnpg03hzV6hO2lgkv3fXMvnBamzBviuoyLQWJDa8ZZegwmYz5gxFUcQ/eAHe4PTX5ZVlWFKrJGzRGGpZCiwnwXvYdqVre7woRwYJ8Y3wVDtMOnSeC2VtIHi042eCrDO67j0clOBg6G9tfWOPtkYJSzxxEwhoNDewNEqdgtyqFopDpr4cLbqjcRszpz9ODJI7pfln2I9NxwX8eefB8aFHZ@eFCqsMoe8EbdFLWKmPbxZuJvPewRCDvUWvzCvBE5rR4RolOf0tDgFX7q4m3GzAz6oihAPa8WKZQ/9JPyrJQ5aHhtwX5tiQcd7DLkFnN5CrI8lR4BELdYQzytm6P/Fb50EIH2eyNNiXzuGas1y1OPk6eoh5zQtLPvCZn7t@TwALWXIzbgvk2UJKflv59g8 "Python 2 – Try It Online")
[Answer]
# 05AB1E, 144 bytes (Work in progress)
```
|vy#Dθˆн})©gF®®NèQO¯®NèQO-D®¯NèQO¯¯NèQO-D.À>0›s>0›&i0›s0›&i®Nè" "¯Nè" defínítely has two fírst names"J,ë®Nè" "¯Nè" has two fírst names"J,}ë\\}}´
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~53~~ 51 bytes
```
|UXv“€°‚•€ÛŒî“D„´Î ì)yð«ìõ¸ìXð¡øεy#θQO}`.S>sèˆ}¯õK»
```
[Try it online!](https://tio.run/##NU49S8NAGN7fX3Hg5CI6uAptHQo2Vhu0Hb02hzl65sIlqZ5YCA6ODo4qgp0Eg3YwEHC7FyehPyJ/JJ5puz0f7/s8z/YuHe6wqro5GUzK9Lm8zcy8TB/LdGYhPv084IeV98v0xXzhPcFsU@PcvGOGuSkwG1jyisUi1xuL4rg7Pdty9yJ8@72bmk/MD8x3VTnU45EMSJsqxSPoccE0aSee1aDhrTwuxNo68i3hYQTuSMZxbUGHTThxEhX6GpavpK/4uR/DIY19GpAmHTMFtiJkijSVlOMIWr6QjDiyrm0kQ2XDHZv2f7jM6MiQXYNLLxImSPeSBdDX1Hae8lEsFadQJwkdkJa8WletZvS0xfXEPw "05AB1E – Try It Online")
### Explanation
```
| # Take inputs as array
UX # Store in X and push X to stack
v } # For each name, do
“€°‚•€ÛŒî“D # Push "has two first names" twice
„´Î ì # Prepend "definitely " to one of those
)yð«ì # Wrap both strings in an array and prepend (name + " ") to each
õ¸ì # Prepend " " to array
Xð¡øεy#θQO}` # Get occurences in input first and last names
.S> # 0 for not first name, 1 for first name and 2 for definitely first name
sèˆ # Get string at that index and push to global array
¯õK» # Output global array, 1 string per line
```
### Or ~~51~~ 49 bytes, assuming standard I/O Rules (input and output as arrays)
```
UXv“€°‚•€ÛŒî“D„´Î ì)yð«ìõ¸ìXð¡øεy#θQO}`.S>sèˆ}¯õK
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/NKLsUcOcR01rDm141DDrUcMiIPPw7KOTDq8DCrs8aph3aMvhPoXDazQrD284tPrwmsNbD@04vCYCyFl4eMe5rZXK53YE@tcm6AXbFR9ecbqt9tD6w1u9//@PVvfPySzLTFQIyk/KzCvOz1PXUVD3SkzOT1IoS8zTdanMTkWIuObkJAJ5Sk5FiZUpqXkKLqnqQfnFiUpABT6pZZkKTkX5@dkg5WCGglMqRL06SJ@CR2ZODpzjmJeSWgS1DaxY1zEvLxVhZSwA "05AB1E – Try It Online")
[Answer]
# PHP, 172 bytes
```
for(;$s=$argv[++$i];$f[$a]++,$l[$n[]=$b]++)[$a,$b]=explode(" ",$s);for(;$b=$n[+$k++];)$f[$b]<$l[$b]||print$argv[$k].($f[$b]>$l[$b]?" definetly":"")." has two first names
";
```
takes names as separate command line arguments.
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/c7018a9596fd2685316e97fe4f797609cb2dae66).
[Answer]
# Python 3, 187 bytes
```
n={}
c=[]
while 1:
try:a,b=input().split();n[a]=n.get(a,0)+1;n[b]=n.get(b,0)-1;c+=[[a,b]]
except:[print(a,b,'definitely has two first names'[(n[b]>0)*11:])for a,b in c if n[b]>=0];break
```
[Answer]
# [R](https://www.r-project.org/), 207 bytes
```
n=readLines("stdin")
s='definitively has two first names\n'
x=matrix(t(unlist(sapply(n,strsplit,' '))),2)
j=1
for(i in n){a=apply(x[2,j]==x,1,sum)
b=a[2]>=a[1]
if(a[1])cat(paste(i,substr(s,14*b,34)))
j=j+1}
```
[Try it online!](https://tio.run/##JVCxTsMwEN39FVaX2OAloatZAAkhKlAZGEqGS@OoF5xz5HNoAuLbg1GXu3vS03v3XlxXstFB@4zkWG04tUgbLdgWreuQMOGX84s8Act0DrLDyEkSDI4/qBCzHSBFnFVSE3nkpBjG0S@KDKfIo8dkCllorU2lRW9L0YWoUCJJ0j9gL@T5UJm@tnY2peFp0KKxcKjq2zzLWmCn/rc@QlIjcHIKM6vJ@opNub1qzM02G2T1/rr8Fev6cnYkXyF@uijugdB5@Qjei7v8dQx0AW@hQ5DvkDiQ2OVzN8XxtIj9AiSfQi5DPAyYk@9hwOi@/wA "R – Try It Online")
[Answer]
## JavaScript (ES6), 149 bytes
```
s=>s.replace(/(.*) (.*)\n/g,(_,t,u)=>g(`
${u} `)>1?t+` ${u}${v>g(` ${u}
`)?` definitely`:``} has two first names
`:``,g=u=>v=`
${s}`.split(u).length)
```
I/O includes trailing newline. Largely inspired by @RobertoGraham's answer.
[Answer]
# [Haskell](https://www.haskell.org/), ~~144~~ ~~140~~ 139 bytes
```
g.map words.lines
g s=id=<<[n++' ':f++[c|c<-" definitely",t 0>t 1]++" has two first names\n"|[n,f]<-s,let t i=filter(==f)$map(!!i)s,[]<t 0]
```
[Try it online!](https://tio.run/##HU09a8MwFNz9K15MIAmyQ7sWqVMnk6nt5ngQsmQ/LD0ZP4UQyG@vamc57ou7UfNkvc9OXfNwDnqGe1x6Pnsky8UArLBXUrYkxAEOH06I1jyNrEvorUPCZP2jrBK8fSZ474QoYdQM6R7B4cIJSAfLVyqfLVWukzVX3iZIgMqhT3Y5KuVO@/X3uNvhiau2k@tYl4NGAgVIa0ebBHtwuYkjwU/ANBYv@hVtcblNFr4fmooNYPM5UtFYIg2NNtOmfmN4JX/GeT1wrs08/wM "Haskell – Try It Online")
[Answer]
## PowerShell, 176 bytes
```
$n=$args
$s=" has two first names"
$f=$n|%{$_.Split()[0]}
$l=$n|%{$_.Split()[1]}
$i=0
$l|%{switch(($f-match$_).count){{$_-eq1}{$n[$i]+$s}{$_-gt1}{$n[$i]+" definitely"+$s}}$i++}
```
] |
[Question]
[
Andrew is a chemist, interested in the acidity of solutions and in agriculture. After months of research (Google is not his friend), he came up with the following table\* regarding the human-readable level of acidity in terms of the [pH (potential of Hydrogen)](https://en.wikipedia.org/wiki/PH#pH_in_soil):
```
Denomination | pH range
|
-------------------------+-----------------------------
Ultra acidic | below 3.5
-------------------------+------------------------------
Extremely acidic | between 3.5 and 4.4
-------------------------+------------------------------
Very strongly acidic | between 4.5 and 5.0
-------------------------+------------------------------
Strongly acidic | between 5.1 and 5.5
-------------------------+------------------------------
Moderately acidic | between 5.6 and 6.0
-------------------------+------------------------------
Slightly acidic | between 6.1 and 6.5
-------------------------+------------------------------
Neutral | between 6.6 and 7.3
-------------------------+------------------------------
Slightly alkaline | between 7.4 and 7.8
-------------------------+------------------------------
Moderately alkaline | between 7.9 and 8.4
-------------------------+------------------------------
Strongly alkaline | between 8.5 and 9.0
-------------------------+------------------------------
Very strongly alkaline | over 9.0
```
Given a non-negative decimal number representing the pH of a substance, output its Denomination. You can take input and provide output by [any standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). The data types you are allowed to take input with are:
* Float
* Double
* Your language's standard decimal number data type
* String
And you must output a String representing the denomination. Built-ins related to chemistry are forbidden *(Sorry, Mathematica!)*.
***Approximation Rule:*** If the pH you receive is between an upper bound of a denomination and the lower bound of the next one (e.g. between 7.8 and 7.9), it gets approximated to the closest value between the two: if the pH ≥ upperBound of the first + 0.5, then it should receive the second denomination, but if the pH < upperBound of the first + 0.5, then it should receive the first one (e.g 7.85 is approximated to 7.9, but 7.84999 is approximated to 7.8). See the test cases for clarifications.
# Test Cases:
```
Input -> Output
6.40 -> Slightly acidic
8.399 -> Moderately alkaline
3.876 -> Extremely acidic
10.60 -> Very strongly alkaline
0.012 -> Ultra acidic
7.30 -> Neutral
7.85 -> Moderately alkaline (the approximation rule is applied)
7.849 -> Slightly alkaline (the approximation rule is applied)
6.55 -> Neutral (the approximation rule is applied)
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (in bytes) wins!
\**Andrew did not come up with that, it was [Wikipedia](https://en.wikipedia.org/wiki/PH#pH_in_soil)!*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~77 73~~ 71 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“£RĿÐƭðṚ°ƲṂṾẒ=ʂXḣsịɠ<»Ḳµ,Ṛ;€"“¡D⁺“a&»j“¿<z»W¤ṙ3
×20<“FYeoy³ƓɗʋṆ‘Sị¢⁾. y
```
A monadic link taking the number and returning a list of characters; or a full program printing the result.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDi4OO7D884djawxse7px1aMOxTQ93Nj3cue/hrkm2p5oiHu5YXPxwd/fJBTaHdj/csenQVh2gKutHTWuUQHoXujxq3AVkJKod2p0FEthvU3Vod/ihJQ93zjTmOjzdyMAGKOoWmZpfeWjzscknp5/qfriz7VHDjGCgmYcWPWrcp6cAdMZ/QwM9MwA "Jelly – Try It Online")**
### How?
```
“ ... »Ḳµ,Ṛ;€"“¡D⁺“a&»j“¿<z»W¤ṙ3 - Link 1, name list: no arguments
“ ... » - compression of "Ultra Extremely Very.strongly Strongly Moderately Slightly"
Ḳ - split at spaces
µ - monadic chain separation, call that adjectives
Ṛ - reverse adjectives
, - pair these two lists
“¡D⁺“a&» - compression of [" alkaline"," acidic"]
" - zip with:
;€ - concatenate for €ach
¤ - nilad followed by links as a nilad
“¿<z» - compression of "Neutral"
W - wrap in a list
j - join
ṙ3 - rotate left by 3: ["Strongly alkaline","Moderately alkaline","Slightly alkaline","Neutral","Slightly acidic","Moderately acidic","Strongly acidic","Very.strongly acidic","Extremely acidic","Ultra acidic","Ultra alkaline","Extremely alkaline","Very.strongly alkaline"]
×20<“FYeoy³ƓɗʋṆ‘Sị¢⁾. y - Main link: number, pH
×20 - multiply by 20
“FYeqy³ƓɗʋṆ‘ - code-page indexes = [70,89,101,111,121,131,147,157,169,180]
< - less than? (vectorises)
- i.e.: pH < [3.5,4.45,5.05,5.55,6.05,6.55,7.35,7.85,8.45,9]
S - sum
¢ - call last link (1) as a nilad
ị - index into (1-indexed and modular)
- ...note that the sum is never 11 or 12, so "Ultra alkaline" and
- "Extremely alkaline" wont be fetched, but that a sum of 0
- fetches "Very.strongly alkaline", as required.
⁾. - literal list of characters ['.', ' ']
y - translate (replace any '.' with a ' ' i.e. for "Very.strongly")
- if running as a full program, implicit print
```
[Answer]
# [PHP](https://php.net/), 199 bytes
```
foreach([35,9.5,6,5,5,5,8,5,6,5.5]as$l)$p+=$argn*10>=$s+=$l;$p-=$argn==9;echo[Ultra,Extremely,"Very strongly",Strongly,Moderately,Slightly][$p>6?12-$p:$p],[" acidic",Neutral," alkaline"][1+($p<=>6)];
```
[Try it online!](https://tio.run/##LYwxT8MwFIT3/orI8pDQ14hQJaK4TgeUgYEyFFiiqLJSE1uY@OnFSGThr4cQ0C13n@4ODU77AxqMVprI05k0egq27@Lv6nx8en64rxKx4oq6XrJtmjMxvXnSqjVxvc1hl@ZQQL7oFhaf5o0auEs4ruWyu8quS8mHOTnBcfMHpdwJ3Rpfv7hACqqvQPpDuxHYq6YxGgL5vnMjg9O/g0d/0aTCb@fkbGeCG5uaY1kcspsNxzuODdQsUq292JbBUX/Oxw5m4t6Vs71mTZ2tY457WRZJI6bpBw "PHP – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 236 bytes
```
p=>{var l=new[]{70,89,101,111,121,131,147,157,169,180,280};var a="Ultra,Extremely,Very strongly,Strongly,Moderately,Slighty, acidic,Neutral, alkaline".Split(',');int i=0;for(;p*20>=l[i];i++);return i==6?a[7]:i<6?a[i]+a[6]:a[12-i]+a[8];}
```
[Try it online!](https://tio.run/##tVPBbtswDL3nK4Reai@qKjuJ7VR1dhi20zoMCLYdDB9UW0mJKpIhy12NIN@eyZmTotgKxIcSoECK4uMjCRX1VaGN2CMnheR1jb4bvTZ8M@putoezk9pyCwV60lCiOw7K80@hl0edLNvaig350qjittTNvRTYJRtQ6wVaoXS0r9LF9okbJFMlfmf5NqY4meOABjgInIZOJ06nMQ5mTiMXSygOE7pjXRpPL35Iazj@/GyN2AjZ4p/CtF0NrdbOWx6NO10Kw233Yilh/WBbjHgBJRT4m2gchHS@fOQSlLggy0qC9S7xpc9AWQQpZSttPFZ9COkilRnkDMZjnxlhG6NcPI0@8izOb@C2MyAf8yzKb3gWhFcHJ8nZbs9G/xvOJ61qLQX5ZcCKr668t/IiMqW@z9D1NfrLVrY923MREjKZz3uIl95PLZ4LMyFJHPUwpxkPpBJQEh27ebWdwWwooUHYIx32PpBJTCZHIv3Sz89MZm9PE3n2QSBeVUY/w8b9Da2QaaRAUHe3EkTpD6g0nf@z@3coFJHZ7PUwBqHvDtZu/wc "C# (.NET Core) – Try It Online")
This solution considers that `p` cannot be greater than 14.
[Answer]
# T-SQL, ~~305~~ 299 bytes
```
DECLARE @ char(999)=REPLACE(REPLACE(REPLACE(REPLACE('SELECT TOP 1i FROM(VALUES(''Very s$#9&S$#8.4&Moderately#7.8&Slightly#7.3&Neutral'',6.5&Slightly@6&[[email protected]](/cdn-cgi/l/email-protection)&S$@5&Very [[email protected]](/cdn-cgi/l/email-protection)&[[email protected]](/cdn-cgi/l/email-protection)&Ultra@-1))x(i,j),t WHERE j<a','#',' alkaline'','),'@',' acidic'','),'&','),('''),'$','trongly')EXEC(@)
```
Input is via a pre-existing table *t* with `DECIMAL(4,1)` column *a*, [per our Input/Output rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341).
Because of the `DECIMAL(4,1)` data type, any "approximation rule" rounding takes place when the value is entered into the input table, so doesn't need to be explicitly managed by my code.
After the space-saving `REPLACES` are performed, this is a simple SQL query joining our input table with our list of values:
```
SELECT TOP 1 i
FROM(VALUES
('Very strongly alkaline',9),
('Strongly alkaline',8.4),
('Moderately alkaline',7.8),
('Slightly alkaline',7.3),
('Neutral',6.5),
('Slightly acidic',6),
('Moderately acidic',5.5),
('Strongly acidic',5),
('Very strongly acidic',4.4),
('Extremely acidic',3.4),
('Ultra acidic',-1)
) x(i,j), t
WHERE j<a
```
I reverse the order so `TOP 1` picks the first one less than our input value.
Even this form (after removing line breaks and extra spaces) is pretty good, at **318 bytes**. Adding the overhead of the `DECLARE`, `REPLACES` AND `EXEC` only becomes worth it with all the repeated phrases.
**EDIT**: Save 6 bytes by removing unnecessary ".0" on several values
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~81~~ ~~80~~ ~~79~~ ~~77~~ ~~76~~ 74 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
'Ĉ“¢³¿™ly³¾‚Òw““³¾§ÓªÅ“«#¦¦’šÉaƒ£’«Š’w¡Îic’«)˜™'wð:I•t{~À•ST+.¥70+20/‹Oè
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f/XDL6bZHDXMOLTq0@dD@Ry2LciqBjH2PGmYdnlQOFAdJAfmHlh@efGjV4VYQd7Xy4aZDyw4te9Qw8@jCw52JxyYdWgxkH1p9dAGQKj@08HBfZjJYQPP0HKCJ6uWHN1h5PmpYVFJdd7gBSAeHaOsdWmpuoG1koP@oYaf/4RX//5vrWZgCAA "05AB1E – Try It Online")
[Test suite](https://tio.run/##MzBNTDJM/V9T9l/9cMvptkcNcw4tOrT50P5HLYtyKoGMfY8aZh2eVA4UB0kB@YeWH558aNXhVhB3tfLhpkPLDi171DDz6MLDnYnHJh1aDGQfWn10AZAqP7TwcF9mMlhA8/QcoInq5Yc3WFU@alhUUl13uAFIB4do6x1aam6gbWSg/6hhp//hFf8rlQ7vt1I4vF9J57@ZnokBl4WesaUll7GehbkZl6GBnpkBl4GegaERl7mesQGQsDAFESaWXGZ6pqYA)
**Explanation**
```
'Ĉ # push the string "neutral"
“¢³¿™ly³¾‚Òw“ # push the string "slightly moderately strongly veryw"
“³¾§ÓªÅ“ # push the string "strongly extremely ultra"
« # concatenate the top 2 items on the stack
# # split on spaces
 # push a reversed copy
¦¦ # remove the first 2 elements of the copy ("ultra", "extremely")
’šÉaƒ£’« # append the string "walkaline" to each ("walk"+"a"+"line")
Š # move down 2 places on the stack
’w¡Îic’« # append the string "wacidic" to each ("w"+"acid"+"ic")
)˜ # wrap stack in a list and flatten
™ # title case each
'wð: # replace each instance of "w" with a space
I # push input
•t{~À• # push the base 255 compressed number 920006021
ST+ # split to list of digits and add 10 to each
.¥ # undelta (compute increments from 0)
70+ # add 70 to each
20/ # divide each by 20
‹ # compute input less than for each
O # sum
è # use this to index into list of strings
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 228 bytes
```
$
.00
\.(.)\.?(.).*
$1$2
.+
$*
1{900,}
VA
1{845,}
STA
1{785,}
MA
1{735,}
SLA
1{655,}
Neutral
1$
1 acidic
1{605,}
SL
1{555,}
M
1{505,}
ST
1{445,}
V
1{350,}
Extremely
1+
Ultra
M
Moderately
V
Very sT
T
trongly
L
lightly
A
alkaline
```
[Try it online!](https://tio.run/##Jc0/a8MwEAXw/X0KDw6kSTlOseU/U8lQusRd6nrKEJGIVER1QFWhofSzuydnefx4Ot0FG91opsXy5TDlIGbsaUkPe3qSpBVylW9Aa@QrqN@W@fEPw1bYlFr41ifXTXI3s5jrXXKlk1/tdwzGQ@VQmTm6kzumN77PCfU81iXdy15YzusHUaHTzeefGOyn9TeoNd69bJQf3fVkg4mpHTDYcMu@evSI4TqepdvBu/NHFG2RGX8x3o12mioqGQ0VbYuCmrqCYqoYTKw2qKlgiUanKFtUpPU/ "Retina – Try It Online") Link includes test suite. Explanation:
```
$
.00
\.(.)\.?(.).*
$1$2
```
Multiply the input by 100 by suffixing a spare decimal point and two zeros then deleting the decimal point and all but two digits after it.
```
.+
$*
```
Convert to unary.
```
1{900,}
VA
1{845,}
STA
1{785,}
MA
1{735,}
SLA
```
Handle all the alkalis, converting into abbreviations that will be expanded later.
```
1{655,}
Neutral
```
Handle neutral.
```
1$
1 acidic
```
Anything left must be acidic. (But leave the 1 in case the pH is 0.001)
```
1{605,}
SL
1{555,}
M
1{505,}
ST
1{445,}
V
1{350,}
Extremely
1+
Ultra
```
Handle all the acids.
```
M
Moderately
V
Very sT
T
trongly
L
lightly
A
alkaline
```
Expand the abbreviations.
[Answer]
# [Python 2](https://docs.python.org/2/), 202 bytes
*-15 bytes thanks to @JonathanAllan*
```
lambda k:'Neutral_Slightly_Moderately_Strongly_Very strongly_Extremely_Ultra'.split('_')[abs(sum(round(k*10)>ord(i)for i in'",27<AINT')+(k>9)-(3.45<k<3.5)-6)]+(' acidic'*(k<6.55)or' alkaline'*(k>=7.35))
```
[Try it online!](https://tio.run/##NU09b8IwEN37K05dbENiBYJDEoVIHTp0KAu0C0XIEAesODFyjNQI8dtTG6k3vHt3eh/XwV50Nx/r1c@oeHusODQ5WoubNVwdNkqeL1YNh09dCcOtcHRjje7OjnwLM0D/f73/WiNaL/hSzotof1XSYnRAZMePPe5vLTb61lW4mcwiUmpTYUlqbUCC7NBrMF8Wbx/rLSJT3JQZCXFMF6xoipgyEiZkP8UI@ElW8oQmuCkSyhjRxv1Uw5XshP@WqyWNGSGjz7Wity4adgldBJDSOMsCiGm6TAKYRdRhRKPZPADn8ZCyJy6cyod7reeZE@3zF3BzNbKzgO45e0BYwv2BqCtqucW@K4D6uV39Hw "Python 2 – Try It Online")
[Answer]
## JavaScript (ES6), ~~192~~ ~~189~~ ~~185~~ 184 bytes
```
k=>([...'09544474540'].some(n=>(i--,k-=++n)<0,i=7,k=k*10-33.5),'Neutral,Slightly,Moderately,Strongly,Very strongly,Extremely,Ultra'.split`,`[i<0?-i:i]+(i?i>0?' acidic':' alkaline':''))
```
### Test cases
```
let f =
k=>([...'09544474540'].some(n=>(i--,k-=++n)<0,i=7,k=k*10-33.5),'Neutral,Slightly,Moderately,Strongly,Very strongly,Extremely,Ultra'.split`,`[i<0?-i:i]+(i?i>0?' acidic':' alkaline':''))
console.log(f(6.40)) // Slightly acidic
console.log(f(8.399)) // Moderately alkaline
console.log(f(3.876)) // Extremely acidic
console.log(f(10.60)) // Very strongly alkaline
console.log(f(0.012)) // Ultra acidic
console.log(f(7.30)) // Neutral
console.log(f(7.85)) // Moderately alkaline
console.log(f(7.849)) // Slightly alkaline
console.log(f(6.55)) // Neutral
```
[Answer]
# Excel, 240 bytes
```
=CHOOSE((A1<6.55)+(A1<6.05)+(A1<5.55)+(A1<5.05)+(A1<4.45)+(A1<3.5)+(A1>=7.35)+(A1>=7.85)+(A1>=8.45)+(A1>9)+1,"Neutral","Slightly","Moderately","Strongly","Very Strongly","Extremely","Ultra")&IF(A1<6.55," acidic",IF(A1>=7.35," alkaline",""))
```
[Answer]
## Javascript, ~~222~~ 209 bytes
```
x=>'Very strongly,Strongly,Moderately,Slightly,Neutral,Extremely,Ultra'.split(',',7,x-=0.049)[x>9?0:x>8.4?1:x>7.8?2:x>7.3?3:x>6.5?4:x>6?3:x>5.5?2:x>5?1:x>4.4?0:x>3.5?5:6]+(x<6.5?' acidic':x>7.3?' alkaline':'')
```
Still golfing it a little
```
var f = x=>'Very strongly,Strongly,Moderately,Slightly,Neutral,Extremely,Ultra'.split(',',7,x-=0.049)[x>9?0:x>8.4?1:x>7.8?2:x>7.3?3:x>6.5?4:x>6?3:x>5.5?2:x>5?1:x>4.4?0:x>3.5?5:6]+(x<6.5?' acidic':x>7.3?' alkaline':'')
console.log(f(6.40));
console.log(f(8.399));
console.log(f(3.876));
console.log(f(10.60));
console.log(f(0.012));
console.log(f(7.30));
console.log(f(7.85));
console.log(f(7.849));
console.log(f(6.55));
```
] |
[Question]
[
If you look at the Fibonacci Numbers, you will notice a pattern in their parity: `0, 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144`. Every third number is even, and all the others are odd. This makes sense because an even plus an odd is odd, but an odd plus an odd is even and the sum for a term will always include at least one even number unless the last two terms were odd, which happens every three terms.
In this challenge you will have to look at a generalization of this problem.
# Specs
* You will be given as input two positive integers describing the [Fibonacci integer sequence](https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Fibonacci_integer_sequences) you will have to look at.
* For example, `0, 1` describes the original Fibonacci numbers, and `2, 1` would be the [Lucas numbers](https://en.wikipedia.org/wiki/Lucas_number). The sequence is calculated with the recurrence relation: `x(n+2)=x(n+1)+x(n)`.
* You will also take a positive integer `n`.
* Your code has to output the parity of the nth term of the described Fibonacci integer sequence (0 indexed).
* The output format can be any two sane, consistent outputs (e.g. `0` for even and `1` for odd).
# Test Cases
```
(Fibonacci numbers) [0, 1], 4 -> odd
(Lucas numbers) [2, 1], 9 -> even
[14, 17], 24 -> even
[3, 9], 15 -> odd
[2, 4], 10 -> even
```
[Answer]
## Python, 29 bytes
```
lambda a,b,n:[a,b,a+b][n%3]%2
```
The generalized Fibonacci sequence modulo 2 has cycle length of 3. So, we reduce `n` mod 3 and take that element of the first three.
---
**31 bytes:**
```
lambda a,b,n:0<a%2*2+b%2!=n%3+1
```
`True` for odd, `False` for even
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
^¡^Ḃ
```
Prints **0** for even, **1** for odd. [Try it online!](http://jelly.tryitonline.net/#code=XsKhXuG4gg&input=&args=MTQ+MTc+MjQ)
### How it works
The quick `¡` takes a link it applies repeated to the previous output, and optionally a second link that specifies the number of iterations. If that second link is absent (which is the case here), the number of iterations is taken from the last command-line argument.
When the first link is dyadic (which is the case with `^`), `¡` applies that link to the previous return value (which is initialized as the left argument) and the right argument, then updates the return value with the result and the right argument with the previous return value. After doing so as many times as specified in the number of iterations, it returns the last return value.
The quicklink `^¡` is called with the left argument (first command-line argument) and the result of `^` (bitwise XOR of the left and right argument, i.e., the first and second command-line argument). XORing is necessary since the right argument is not among the return values, meaning that the right argument has to be the **x(-1)** in order to return **x(n)** with **x(0) `^` n `¡` x(1)**.
To actually calculate **x(n)**, we'd use the code `+¡_@` (`+¡` instead of `^¡` and `_@` – left argument subtracted from right argument – instead of `^`), but since we're only interested in the parities, any combination of `+`, `_` and `^` will do.
Finally, `Ḃ` (bit) computes and returns the parity of **x(n)**.
[Answer]
# [Factor](https://factorcode.org/), 27 bytes
```
[ [ tuck + ] times . odd? ]
```
[Try it online!](https://tio.run/##LY47D4JAEIR7fsWUGoPhZYxYWBoaGmNFKMhxBMLjzrslkRB@O65is/kyM5mdqhCkzPp8JOk9RivNIDv0BdXQRhJN2jQDwcrXKAchLa5OksawwhQkaicGjaLFDm9McF0@X9ijHDVco4jjM2Z48BFhYQqYLj/yI/hnBJscsuif/gk2PMZlzZBt/QfkoKbn90eosrwhZ69qjKWQHR6qlZW8WuPoiE4WZv0A "Factor – Try It Online")
Well, executing the Fibonacci recurrence directly is way shorter than any other "smart" methods. Takes three items `a0 a1 n` on the stack, and outputs `t` for odd and `f` for even. Prints an unused value as a side effect.
For golfing, `.` is shorter than `drop`, and `odd?` is shorter than `2 mod` or `even?`.
```
[ ! ( a0 a1 n )
[ tuck + ] times ! ( an an+1 ) Execute Fibonacci recurrence n times
. odd? ! drop an+1 by printing and test if an is odd
]
```
[Answer]
# Python, 38 bytes
```
lambda a,b,n:(b*(n%3>0)+a*(~-n%3>0))%2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
+¡Ḃ
```
[Try it online!](https://tio.run/##y0rNyan8/1/70MKHO5r@//9vaPLf0Py/kQkA "Jelly – Try It Online")
Outputs `0` for even and `1` for odd
## How it works
```
+¡Ḃ - Main link. Takes a on the left and b on the right and n on the command line
¡ - Run the following dyad f(x,y) n times, starting with l = a and r = b.
After each step, update l and r to l = r, r = f(l, r):
+ - f(x,y): x+y
This is a generalised n'th Fibonacci "builtin"
Ḃ - Bit; Return 1 for odd, 0 for even
```
[Answer]
# J, 15 bytes
```
2|0{(]{:,+/)^:[
```
Simple method. Computes the *n*th term, and takes it modulo 2 to find its parity. Even parity is represented by `0` and odd parity by `1`.
## Usage
```
f =: 2|0{(]{:,+/)^:[
4 f 0 1
1
9 f 2 1
0
24 f 14 17
0
15 f 3 9
1
```
## Explanation
```
2|0{(]{:,+/)^:[ Input: n on LHS, and initial values [a, b] on RHS
( .... )^:[ Repeat the function n times
+/ Find the sum of a+b
{: Get the value b from the tail of [a, b]
, Join the values to get [b, a+b]
] Return those values as the new [a, b]
0{ Select the first value at index 0 from the list (after n applications)
2| Take that value modulo 2 and return
```
[Answer]
# MATL, ~~10~~ 7 bytes
```
tshwQ)o
```
[Try it online!](http://matl.tryitonline.net/#code=dHNod1Epbw&input=WzE0LCAxN10KMjQ)
Explanation:
```
t #Duplicate the array of numbers
s #Sum them
h #and add that to the end of the array
w #Swap inputs so that the *N* is on top
Q #Increment *N* (Since MATL uses 1-based indexing)
) #Get that element of the array. MATL uses modular indexing.
o #Return it's parity
```
[Answer]
# [Perl 6](http://perl6.org), ~~24~~ 23 bytes
```
~~{(|@^a,sum @a)[$^n%3]%2}
{(|@^a,&[+]...\*)[$^n]%2}~~
{(|@^a,*+*...*)[$^n]%2}
```
### Test:
```
use v6.c;
use Test;
constant even = 0;
constant odd = 1;
my @test = (
([0, 1], 4) => odd,
([2, 1], 9) => even,
([14, 17], 24) => even,
([3, 9], 15) => odd,
([2, 4], 10) => even,
);
my &seq-parity = {(|@^a,*+*...*)[$^n]%2}
for @test -> ( :key($input), :value($expected) ) {
is seq-parity(|$input), $expected, ($input => <even odd>[$expected]).gist
}
```
```
ok 1 - ([0 1] 4) => odd
ok 2 - ([2 1] 9) => even
ok 3 - ([14 17] 24) => even
ok 4 - ([3 9] 15) => odd
ok 5 - ([2 4] 10) => even
```
### Explanation:
```
{
(
# generate the Fibonacci integer sequence
# ( @^a is the first two values )
|@^a, *+* ... *
)[ $^n ] # get the one at the appropriate index
% 2 # modulo 2
}
```
[Answer]
# Julia, 23 bytes
```
x\n=[x;sum(x)][n%3+1]%2
```
[Try it online!](http://julia.tryitonline.net/#code=eFxuPVt4O3N1bSh4KV1bbiUzKzFdJTIKCmZvciAoeCxuKSBpbiAoIChbMCwxXSw0KSwgKFsyLDFdLDkpLCAoWzE0LDE3XSwyNCksIChbMyw5XSwxNSksIChbMiw0XSwxMCkgKQogICAgQHByaW50ZigiJS03cyAlMmQgLT4gJWRcbiIsIHgsIG4sIHhcbikKZW5k&input=)
[Answer]
# Mathematica, ~~38~~ 36 bytes
```
OddQ@({#,#2,+##}&@@#)[[#2~Mod~3+1]]&
```
Anonymous function, based off of @xnor's Python approach. Takes a list and an integer, and outputs either `True` for odd or `False` for even. Not much beyond that.
[Answer]
# [R](https://www.r-project.org/) + pryr, 30 bytes
```
pryr::f(c(x,y,x+y)[n%%3+1]%%2)
```
[Try it online!](https://tio.run/##K/pfkJ9XkpmWWWz7v6CossjKKk0jWaNCp1KnQrtSMzpPVdVY2zBWVdVIE65Qw0THQMdQU0FZwZALLmapYwQRM0CIGZnoGAKROZqwoamOsY4lmn5DA6ABJmCV/wE "R – Try It Online")
Calculates parity of modular index of `(x,y,x+y)`; returns `0` for even and `1` for odd.
Function with arguments `n`,`x` and `y`, where `x` and `y` represent the initial two fibonacci numbers.
The `f()` function from the `pryr` library is a short way to define a function. In code-golf, it's sometimes used simply because `pryr::f` has one less character than `function`. However, it also tries to 'guess' the function arguments from the body of the function if they are not declared (using a mysterious and not well-documented algorithm). This is particularly useful here, where declaring `x,y,n` in a conventional function definition would cost an extra 5 bytes.
Luckily, in this case `f` somehow manages to guess the arguments perfectly.
[Answer]
# [Rust](https://www.rust-lang.org/), 23 bytes
Port of xnor's [answer](https://codegolf.stackexchange.com/a/83224/95792), which you should upvote!
```
|a,b,n|[a,b,a+b][n%3]%2
```
[Try it online!](https://tio.run/##dYzBCoMwEETv/YqpICR0C5pYSlvaHxEPEQwE7FI0Xqp@e5p4rpdZhrdvhmn0wTLexrGQmA9A33nYOywLpxVhi2l0307i/EoVz7AYaomXOh1zapuac93kKjyi/xkc@56PIpvXjGBFQSgJlZR/qdrobYeWVcRXgtrTdXTjy2V/PS0UCa/hBw "Rust – Try It Online")
Rust is [Language of the month for December](https://codegolf.meta.stackexchange.com/q/20531/95792), but it doesn't have a ton of answers, so I'm posting a trivial one to remind y'all that Rust can sometimes beat Python too.
[Answer]
## Pyke, 9 bytes
```
3%QDs+@2%
```
[Try it here!](http://pyke.catbus.co.uk/?code=3%25QDs%2B%402%25&input=%5B0%2C+1%5D%0A4&warnings=0)
```
s+ - input+sum(input)
@ - ^[V]
3% - line_2 % 3
2% - ^ % 2
```
[Answer]
## Actually, 12 bytes
```
╗│+k3╜%@E2@%
```
This uses the same strategy as [xnor's Python answer](https://codegolf.stackexchange.com/a/83224/45941). Input is `a b n`, with the spaces replaced by newlines. Output is `0` for even parity and `1` for odd parity.
[Try it online!](http://actually.tryitonline.net/#code=4pWX4pSCK2sz4pWcJUBFMkAl&input=MAoxCjM)
Explanation:
```
╗│+k3╜%@E2@%
implicit input ([a, b, n])
╗ save n in reg0 ([a, b])
│ duplicate stack ([a, b, a, b])
+k add, push stack as list ([[a, b, a+b]])
3╜% n mod 3 ([[a, b, a+b], n%3])
@E element in list ([[a, b, a+b][n%3])
2@% mod 2 ([[a, b, a+b][n%3]%2)
```
[Answer]
# CJam, 9 bytes
```
q~_:++=2%
```
Even is zero, odd is one.
[Try it online!](http://cjam.aditsu.net/#code=q~_%3A%2B%2B%3D2%25&input=24%20%5B14%2017%5D)
# Explanation
```
q~ e# Read input and evaluate
_ e# Duplicate initial tuple
:+ e# Sum initial values
+ e# Append sum to initial tuple
= e# Take the n-th element (modular indexing)
2% e# Modulo 2
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum -pla`, 21 bytes
A port of @xnor's python answer as a Perl program.
```
$_=(@F,sum@F)[<>%3]%2
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbDwU2nuDTXwU0z2sZO1ThW1ej/fwMFQy4TLiMgacllaKJgaM5lZMJlrADkmAJFTbgMDf7lF5Rk5ucV/9f1NdUzMDQA0j6ZxSVWVqElmTm2QPP@6@YUJAIA "Perl 5 – Try It Online")
Inputs the two starting sequence numbers on the first line and the element to find on the second. Outputs `1` for odd parity and `0` for even.
] |
[Question]
[
For this challenge, we are writing the time in the following form: `hh:mm:ss`
Some examples:
>
> `12:34:08`
>
>
> `06:05:30`
>
>
> `23:59:00`
>
>
>
The challenge is to output the time after an amount of *hours*, *minutes* and *seconds* have elapsed, with as starting time `00:00:00`. You can compare this with a timer that started at `00:00:00`.
Here is an example of inputs (using **STDIN**) and outputs:
```
Input: 1h20m5s
Output: 01:20:05
Input: 0h100m0s
Output: 01:40:00
```
After 24 hours, the timer resets itself:
```
Input: 25h0m0s
Output: 01:00:00
```
The form of the input is always the same: `XhYmZs`, with `X` hours, `Y` minutes and `Z` seconds (assume that `X`, `Y` and `Z` are whole integers less than 100000 and never negative)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least amount of bytes wins this challenge
[Answer]
# CJam, 34 bytes
```
leu~]2%60b86400%60b3Te[{s2Te[}%':*
```
[Try it here](http://cjam.aditsu.net/#code=reu~%5D2%2560b86400%2560b3Te%5B%22%2502d%22fe%25'%3A*&input=0h100m0s).
[Answer]
# Ruby - ~~131~~ ~~115~~ ~~107~~ ~~97~~ 84 bytes
I'm still golfing it.
```
h,m,s=gets.split(/\w/).map &:to_i;$><<"#{(h+m/60+s/3600)%24}:#{(m+s/60)%60}:#{s%60}"
```
Thanks for @Doorknob for /\w/ inshead of /h|m|s/
[Answer]
# Mathematica, ~~133~~ ~~116~~ ~~112~~ 111 bytes
```
IntegerString[(f=FromDigits)[f/@StringSplit[#,_?LetterQ],60]~Mod~86400~IntegerDigits~60,10,2]~StringRiffle~":"&
```
[Answer]
# Python 2, ~~138~~ 126 Bytes
Now I'm using regex, still quite long though..
```
import re
a=input();b=map(int,re.split('h|m|s',a)[:-1])
s=b[0]*3600+b[1]*60+b[2]
print(':%02d'*3)[1:]%(s/3600%24,s/60%60,s%60)
```
Input should be in quotes.
[Answer]
## C ~~149~~ 112 bytes
[Test it here](https://ideone.com/3XPyFd)
```
main(h,m,s){scanf("%dh%dm%ds",&h,&m,&s);s+=h*3600+m*60;h=s/3600;m=s/60;printf("%02d:%02d:%02d",h%24,m%60,s%60);}
```
Credits to @Dennis for getting rid of a lot it.
[Answer]
## JavaScript 110 bytes
Where x is the input
```
x=x.split(/[hms]/).map(Number);for(z=2;z--;)x[z+1]-60&&(x[z]+=~~(x[z+1]/60));y=x[0]%24+":"+x[1]%60+":"+x[2]%60
```
I don't think this is the most efficient way
```
// How it works:
x=x.split(/[hms]/).map(Number); // splitting the string into an array of numbers
for(z=2;z--;)x[z+1]-60&&(x[z]+=~~(x[z+1]/60)); // shifting excess of seconds to minutes, and then minutes to hours
y=x[0]%24+":"+x[1]%60+":"+x[2]%60 // putting them all together
```
[Answer]
# PHP, 80 ~~88~~ ~~93~~ Bytes
```
<?=!$s=split(~¤—’¢,fgets(STDIN)),date(~·Å–ÅŒ,$s[0]*3600+$s[1]*60+$s[2]-date(Z));
```
(saved as ISO-8859-1)
Works only on PHP 5 because of deprecated `split` function. Assumes that notices are not shown.
### How it works:
* `¤—’¢` is `"[hm]"` inverted and a valid constant name, PHP uses undefined constants as string (saves one character for the quotation marks)
* `·Å–ÅŒ` is the same for `"H:i:s"`
* Everything is a single short handed echo statement. `<?=x,y` outputs x and y. Using `!`, the result of the `$s` assignment gets converted to boolean and negated, then converted to string to output. `(string)false === ''`
* `split("[hm]", "XhYmZs")` splits the string to `[X,Y,Zs]`. Then, `3600*X+60*Y+Zs` is the number of seconds. PHP converts `Zs` to integer as `Z`
* We substract the timezone offset `date(Z)`, use this result as a timestamp and print its time part as "hours:minutes:seconds". In UTC (offset 0), the timestamp `0` is `1970/01/01 00:00:00`. Substracting the timezone offset normalizes the date as UTC without changing the actually used timezone (this saved 8 bytes for setting the timezone).
* Conveniently, 25 hours will result in 01:00:00 (on the next day).
[Answer]
# AutoIt, 208 bytes
```
Func _($0)
$1=StringRegExp($0,"[0-9]+",3)
For $2=2 To 1 Step -1
If $1[$2]>59 Then
$1[$2]=Mod($1[$2],59)-1
$1[$2-1]+=1
EndIf
Next
Return StringFormat("%02u:%02u:%02u",$1[0]-($1[0]>23?24:0),$1[1],$1[2])
EndFunc
```
Too long. Test:
```
ConsoleWrite(_("1h20m5s") & @LF)
ConsoleWrite(_("0h100m0s") & @LF)
ConsoleWrite(_("25h0m0s") & @LF)
```
[Answer]
# Pyth, 40 bytes
```
j\:%L"%02d">3j+%ivM:z"\d+"1K60 86400^KTK
```
I'm still learning. [Try it here!](https://pyth.herokuapp.com/)
[Answer]
# Perl 5, 84 (83 Bytes + 1)
Uses the overflow of seconds or minutes.
```
($h,$m,$s)=split/\D/;$h+=($m+=$s/60)/60;printf"%0.2d:%0.2d:%0.2d",$h%24,$m%60,$s%60
```
### Test
```
$ echo 35:124:224s |perl -n 61736-time-after-some-time.pl
13:07:44
```
[Answer]
## VBA (150149 bytes)
```
Function t(s)
x = Split(Replace(Replace(Replace(s, "s", ""), "m", " "), "h", " "))
t = Format(TimeSerial(x(0), x(1), x(2)), "HH:MM:SS")
End Function
```
[Answer]
# JavaScript, 97 bytes
```
x=>([h,m,s]=x.match(/\d+/g),[(+h+m/60|0)%24,(+m+s/60|0)%60,s%=60].map(a=>(a>9?'':'0')+a).join`:`)
```
[Answer]
# PowerShell, 84 Bytes
```
$a=$args-split'[hms]';"{0:HH:mm:ss}"-f(date 0).AddSeconds(3600*$a[0]+60*$a[1]+$a[2])
```
Splits the command-line input into an array of strings based on the `[hms]` regex. Uses the verbose built-in function `.AddSeconds()` to add (hours\*3600, minutes\*60, and seconds) to `(date 0)` a/k/a `Monday, January 1, 0001, 12:00:00 AM`, then feeds that into `-f` with formatting `HH:mm:ss` which will automatically convert it to 24-hour clock format and output it.
### Example:
```
PS C:\Tools\Scripts\golfing> .\time-after-some-time.ps1 25h100m0s
02:40:00
```
[Answer]
# Lua, 104 bytes
```
h,m,s=io.read():match"(%d+)h(%d+)m(%d+)"m=m+s/60;print(("%02d:%02d:%02d"):format((h+m/60)%24,m%60,s%60))
```
[Answer]
## VB.NET (107 bytes)
First submission for code golf so I'm guessing character count => byte count?
```
MsgBox(TimeSpan.Zero.Add(TimeSpan.Parse(Regex.Replace(InputBox("XhYmZs"),"[hm]",":").Trim("s"))).ToString)
```
[Answer]
# Python 3, 158
```
import re
e=input()
b=[];p=0
for s in re.split('\D',e)[:3][::-1]:c,a=divmod(int(s),60);b+=[a+p];p=c
b[2]=(b[2]+p)%24;f=':%02d'*3;print(f[1:]%(b[2],b[1],b[0]))
```
Ungolfed version:
```
import re
def timer(elapsed):
base=[]
previous_carry=0
for section in re.split('\D+',elapsed)[:3][::-1]:
carry,amount=divmod(int(section),60)
base+=[amount+previous_carry]
previous_carry=carry
base[2]=(base[2]+previous_carry)%24
format_str = ':%02d'*3
return format_str[1:]%(base[2],base[1],base[0])
```
[Answer]
# CJam, 50 bytes
```
0[l"hms"Ser~][24 60 60].{md}(;+2/::+{"%02d"e%}%':*
```
[Answer]
# GNU sed+date, 51 bytes
(including +1 byte for `-r` flag)
```
#!/bin/sed -rf
s/(.*h)(.*m)(.*s)/date -d"0:0 \1our\2in\3ec" +%T/e
```
This simply gets `date` to add the specified number of hours, minutes and seconds to `00:00:00` (today) and display the time part. Recommended to set `TZ=UTC` or avoid running the program around a local-time change (e.g. daylight savings).
] |
[Question]
[
Given a number, find an expression in words equaling that number, with a length of that number.
Thus, to an input of `15`, you might output `sixteen minus one`, which has fifteen characters (not counting spaces). If multiple solutions exist, print whichever you want. If none exist, print `impossible`
Use only the operators `plus`, `minus`, `times`, and `divided by`. Operators are evalutated left to right.
Format 1234 as `one thousand two hundred thirty four`. Note the absence of "and", and that there are no dashes or commas.
The input and all numbers used in the output must be positive integers less than 10,000.
The input will be given as a command line argument. Print to standard output.
## Examples
```
1: impossible
4: four
7: impossible
13: eight plus five (you could also output "five plus eight")
18: one plus two times six (note that operators are evaluated from left to right)
25: one thousand divided by forty
```
[Answer]
# JS, 1719/1694
# Theory
Unfortunately, the rule set that you provide may not be a wise decision from a mathematical point of view. In fact, using a smaller subset of rules, you can find a solution for every number in the given interval
>
> ![I = [1; 10000]](https://i.stack.imgur.com/KBiqV.gif)
>
>
>
except for
>
> ![X = [1; 3] ∪ [5; 10] ∪ {12}](https://i.stack.imgur.com/rDCDo.gif)
>
>
>
for which there is no solution.
## Reduced rule set
Consider the following subet of rules:
* Use only the operators `plus`, `minus` and `times`.
* You **don't need to implement** multiple occurrences of `plus` or `minus` in your expressions.
* You **don't need to implement** neither `division` nor `operator associativity` (as their solution set is already covered by the first rule).
The reason why this works is that, as you discussed earlier with @Qwix, you allow **boring answers**, that is, expressions that end in the regular expression
`( times one)+$`. Allowing this, each number in the given interval will have a solution.
When you replied in one of your comments,
>
> @Qwix Yes; boring answers are acceptable, although that one doesn't
> work for 104, 105, 106, 107, 108, 109, 110, or 111. –
>
>
>
you were absolutely right: This does not work when you're trying to build your expression starting with the numbers themselves, i.e. `one hundred four times one times one …` or any other of those numbers.
If however, your expression starts with an expression whose evaluation equals one of the given numbers, you're out of luck. For example, note that `17 + 87` is indeed `104`, so we could write `104` as:
```
104: seventeen plus eighty seven times one times one times one times one times one times one times one times one times one times one
```
To see that this subset works, save this file as **`num.js`** and make sure that SpiderMonkey, a JavaScript engine for command lines, is installed on your system.
## The algorithm
* Let us define the property `K` for positive integers as the state of the number having `N` letters and having a value of `N`.
* Let us further define the property `F` for an expression as the state of its word conversion being `8k`-times shorter than its evaluation with k ∈ ℕ. `F` stands for "fillable" and describes whether or not we can fill the word conversion of the expression with expressions of length 8 (i.e. `" times one"`) such that the resulting expression might get the property `N`.
We then proceed as follows:
* Convert the input number to words.
* Check if the input number has property `K`.
+ If it does, return the words (`4` is the only number with this property, unfortunately).
+ If it doesn't, proceed.
* For all two-operand expressions (additions, subtractions and multiplications in this order) that result in the input number, check if their evaluation has property `K`.
+ If it does, return the words.
+ If it doesn't, check if the two-operand expression has property `N`.
- If it does, fill the expression with `" times one"` and check if the evaluation of the resulting expression has property `K`.
* If it does, return the words
* If it doesn't, proceed
- If it doesn't, proceed
* Go drink a coffee
# Practice
## num.js (for SpiderMonkey / command lines)
```
function X(e,t){return e+": "+t}function P(e){var n,t;for(n=1;.5*e+(e%2===0?1:0)>n;++n){if(t=C.s(n)+" plus "+C.s(e-n),t.replace(/\s/g,"").length===e)return t;if(F(e,t)&&e>t.length)return G(e,t)}return!1}function M(e){var t,n;for(t=L;t>1;--t){if(0>t-e)return!1;if(n=C.s(t)+" minus "+C.s(t-e),n.replace(/\s/g,"").length===e)return n;if(F(e,n)&&e>n.length)return G(e,n)}return!1}function F(e,t){return(e-t.replace(/\s/g,"").length)%8===0}function G(r,t){var e,i=(r-t.replace(/\s/g,"").length)/8,n="";for(e=0;i>e;++e)n+=" times one";return t+n}function T(e){var t,n,r;if(F(e,C.s(e)))return G(e,C.s(e));for(t=1,n=1;t<Math.floor(Math.sqrt(e));++t){for(;e>t*n;)++n;if(t*n===e&&(r=C.s(t)+" times "+C.s(n),r.replace(/\s/g,"").length===e))return r}return!1}function Y(e){var n,r,t;return e===C.s(e).length?X(e,C.s(e)):(n=P(e))?X(e,n):(r=M(e))?X(e,r):(t=T(e),t?X(e,t):X(e,"impossible"))}var L=1e4,C=new function(){return this.o=["","one","two","three","four","five","six","seven","eight","nine"],this.t=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.T=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.s=function(e){return e?this.m(e):"zero"},this.m=function(e){return e>=1e6?this.m(Math.floor(e/1e6))+" million"+(e%1e6!==0?" "+this.Z(e%1e6):""):this.Z(e)},this.Z=function(e){return e>=1e3?this.h(Math.floor(e/1e3))+" thousand"+(e%1e3!==0?" "+this.h(e%1e3):""):this.h(e)},this.h=function(e){return e>99?this.o[Math.floor(e/100)]+" hundred"+(e%100!==0?" "+this.U(e%100):""):this.U(e)},this.U=function(e){return 10>e?this.o[e]:e>=10&&20>e?this.T[e-10]:this.t[Math.floor(e/10)]+(e%10!==0?" "+this.o[e%10]:"")},this};print(Y(0|arguments[0]))
```
## num.js (for browsers)
The given code from above can't work for browsers due to its last command, which grabs the command line arguments in order to make a nice command out of the given script.
In order to run the JavaScript code directly from within your browser, select this piece of the above code:
```
function X(e,t){return e+": "+t}function P(e){var n,t;for(n=1;.5*e+(e%2===0?1:0)>n;++n){if(t=C.s(n)+" plus "+C.s(e-n),t.replace(/\s/g,"").length===e)return t;if(F(e,t)&&e>t.length)return G(e,t)}return!1}function M(e){var t,n;for(t=L;t>1;--t){if(0>t-e)return!1;if(n=C.s(t)+" minus "+C.s(t-e),n.replace(/\s/g,"").length===e)return n;if(F(e,n)&&e>n.length)return G(e,n)}return!1}function F(e,t){return(e-t.replace(/\s/g,"").length)%8===0}function G(r,t){var e,i=(r-t.replace(/\s/g,"").length)/8,n="";for(e=0;i>e;++e)n+=" times one";return t+n}function T(e){var t,n,r;if(F(e,C.s(e)))return G(e,C.s(e));for(t=1,n=1;t<Math.floor(Math.sqrt(e));++t){for(;e>t*n;)++n;if(t*n===e&&(r=C.s(t)+" times "+C.s(n),r.replace(/\s/g,"").length===e))return r}return!1}function Y(e){var n,r,t;return e===C.s(e).length?X(e,C.s(e)):(n=P(e))?X(e,n):(r=M(e))?X(e,r):(t=T(e),t?X(e,t):X(e,"impossible"))}var L=1e4,C=new function(){return this.o=["","one","two","three","four","five","six","seven","eight","nine"],this.t=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.T=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.s=function(e){return e?this.m(e):"zero"},this.m=function(e){return e>=1e6?this.m(Math.floor(e/1e6))+" million"+(e%1e6!==0?" "+this.Z(e%1e6):""):this.Z(e)},this.Z=function(e){return e>=1e3?this.h(Math.floor(e/1e3))+" thousand"+(e%1e3!==0?" "+this.h(e%1e3):""):this.h(e)},this.h=function(e){return e>99?this.o[Math.floor(e/100)]+" hundred"+(e%100!==0?" "+this.U(e%100):""):this.U(e)},this.U=function(e){return 10>e?this.o[e]:e>=10&&20>e?this.T[e-10]:this.t[Math.floor(e/10)]+(e%10!==0?" "+this.o[e%10]:"")},this}
```
Now, paste it into your browser's JavaScript console, so you can produce the same results from within your browser with, for example:
```
Y(1234);
```
## Examples (command line)
```
chiru@chiru ~ $ js num.js 28
28: fourteen plus fourteen times one
chiru@chiru ~ $ js num.js 7
7: impossible
chiru@chiru ~ $ js num.js 42
42: nine thousand sixty minus nine thousand eighteen
```
And in order to see the trick with which you can make each number work, just have a look at the **boring answer** for `js num.js 1337`:
```
1337: ten plus one thousand three hundred twenty seven times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one
```
The provided codes generates valid solutions for the given interval (and probably even above, you'd only have to raise the value of the variable `L`).
## Statistics
I was interested in "how **boring**" the expressions were (or: how much the substring `times one` was used per expression within this algorithm), as this part was responsible for finding a solution for every number within the given interval. See for yourselves:
**x**: n-th expression (min. 0, max. 10,000)
**y**: number of occurences of substring " times one" within expression (min. 0, max. 1245)

**Conclusions:**
* The expressions tend to get more and more boring in a linear manner.
* Over 99% of solutions are boring.
[Answer]
## C, 450 characters
Edit: removed `zero`
Edit: using only `plus` and `minus`
I searched for the shortest expression that adds chars and keeps the condition true.
I found `plus ten plus five` is 15 long and adds 15 to the string.
I need only expressions for the first 15 numbers that are not impossible, to express any possible number.
12 is the biggest impossible number, therefore it suffices to hardcode numbers smaller 28.
```
4 = four
11 = six plus five
13 = eight plus five
14 = twenty minus six
15 = twenty minus five
16 = eighteen minus two
17 = fourteen plus three
18 = twenty two minus four
20 = thirty two minus twelve
21 = twenty plus two minus one
22 = twenty plus four minus two
23 = thirty minus eight plus one
24 = twenty plus eight minus four
25 = twenty plus eight minus three
27 = twenty eight minus six plus five
```
We can write every number >27 as x\*15 + one of the numbers above.
## Golfed
```
#define P" plus "
#define M" minus "
#define U"four"
#define F"five"
#define E"eight"
#define W"twenty"
#define A"ten"P F P
*e[]={0,0,0,0,U,0,0,0,0,0,0,F P"six",0,E P F,W M"six",W M F,E"een"M"two",U"teen"P"three",W" two"M U,A U,"thirty two"M"twelve",W P"two"M"one",W M"two"P U,"thirty"P"one"M E,W P E M U,W M"three"P E,A F P"six",W" "E M"six"P F};main(n){n=atoi(1[(int*)1[&n]]);for(printf("%d: ",n);n>27;n-=15)printf(A);puts(e[n]?e[n]:"impossible");}
```
## Readable Code
```
#include <stdio.h>
#include <stdlib.h>
// add fifteen to string, both as value and as character count (without spaces)
const char *add_fifteen = "plus ten plus five";
// table with hardcoded expressions
// NOTE: we could calculate 19, 26, 28 and 29 from 4, 11, 13 and 14
// but we would need more logic, so we hardcode those 4 numbers too.
const char *expressions[30]={"impossible", "impossible", "impossible", "impossible",
"four", "impossible", "impossible", "impossible", "impossible",
"impossible", "impossible", "five plus six", "impossible",
"eight plus five", "twenty minus six",
"fourteen plus one", "eighteen minus two", "fourteen plus three",
"twenty two minus four", "four plus ten plus five",
"thirty two minus twelve", "nine plus seven plus five",
"twenty plus four minus two", "twelve plus seven plus four",
"twenty plus eight minus four", "twenty plus eight minus three",
"five plus six plus ten plus five", "twenty eight minus six plus five",
"eight plus five plus ten plus five", "seven plus seven plus ten plus five"};
int main(int argc,char *argv[])
{
int n = strtol(argv[1], NULL, 0);
int fifteens = 0;
printf("%d: ", n);
// how many times do we need to add fifteen?
if(n>29){
fifteens=(n/15) - 1;
n -= fifteens*15; // ensure 30 > n >= 15, so we don't get "impossible"
}
// look up the expression for n
printf("%s", expressions[n]);
// add fifteens till we are done
while(fifteens-- > 0) {
printf(" %s", add_fifteen);
}
printf("\n");
return 0;
}
```
[Answer]
# Javascript, 434 characters
```
function f(s){return s.replace(/[A-Z]/g,function(t){return{O:'one',T:'two',H:'three',F:'four',I:'five',S:'six',E:'seven',G:'eight',N:'nine',Z:'ten',P:' plus ',M:' minus ',U:' times ',X:'teen',A:'thir',B:'twenty'}[t]})}A='TPAX|GeenMT|EXUO|B FMS|F|GPSUT|ZPHPG|BPFMT|AXPFPS|BPGMF|EUOPGeen|NPT|B GMSPI|GPI|EPE'.split('|');O=26640;function S(n){return n<15&&!(O>>n&1)?'Invalid':f(A[v=n%15])+(new Array(~~(n/15)+(O>>v&1))).join(f('PSPN'))}
```
Yields a function in the global namespace, `S`, that accepts any non-negative integer and returns the required string, or `"Invalid"` if the integer cannot be represented within the specifications.
I would appear to have used the same approach as @optokopper, having made the same observation that `"plus six plus nine"` is the shortest possible padding string, and that all numbers greater than 27 can be expressed by concatenating one of 15 base strings to repeated copies of the pad.
Having said that, the tables of base strings we use differ, and my solution relies on bit twiddling and the remainder operator (`%`). It also includes `"multiplied by"` as a possible operation. And naturally the mechanics of how the strings are constructed are completely different due to the dissimilarity between C and Javascript.
That's my best attempt, at any rate. ;)
Special thanks to @chiru, whose discussion of which numbers were achievable helped prevent fruitless searching.
] |
[Question]
[
# The Task:
Given a `.txt` file with frames of ASCII art each separated by a `\n` (see this example if you are unclear) output a motion picture with frame with 1 frame per second.
Note that there is a trailing `\n` on the final frame.
Each frames dimensions will be:
* X<80
* Y<20
# The Rules
* The Previous frame must be cleared before the next is displayed, so just printing each frame onto the terminal isn't a valid answer.
* **New** You can grab the file name however you want, either from it being stored in a variable or from sys args.
* **New** The images must Loop indefinitely
* This is code golf: smallest program wins.
# Example
### Input
```
0 0
0 0
00000
0 0
0 0
00000
0
00000
0
00000
0 0
0 0
0
0
0
```
### Output

### Un-golfed
```
import curses, time
stdscr = curses.initscr()
Frames = file.read(file('Frames.txt')).split('\n')
while True:
y = 0
for i in range(len(Frames)):
stdscr.addstr(y,0,Frames[i])
stdscr.refresh()
y += 1
if Frames[i] == '':
y = 0
stdscr.clear()
time.sleep(1)
```
[Answer]
## Mathematica, 41 bytes
```
Import@f~StringSplit~"\n\n"~ListAnimate~1
```
Expects the file name to be stored in variable `f`.
This is the first time Mathematica's precedence rules for `@` and `.~.~.` are exactly the way I need them.
Btw, this snippet could go horribly wrong if the file extension is anything else than `.txt` (because Mathematica will try to guess how to do the import based on that), but luckily that file ending is part of the challenge specification.
[Answer]
## Bash, 82
```
IFS=
clear
for((;;)){
while read a;do
[ "$a" ]&&echo $a||(sleep 1;clear)
done<$1
}
```
Assumes the file name of the .txt file is provided as the first argument to the script.
Note that a trailing empty line must be present at the end of the .txt file for this to work.
Special thanks to @professorfish and @DigitalTrauma.
[Answer]
# Ruby, ~~88~~ ~~86~~ ~~56~~ 55 characters
```
$<.read.split($/*2).cycle{|i|system'cls';$><<i;sleep 1}
```
This program assumes the file name is given as the first argument.
Thanks a lot to Ventero for sharing great improvements!
Un-golfed:
```
$<.read.split($/*2).cycle{ |i| # read file, split by two newlines, and loop
system 'cls' # clear screen
$><<i # print the current array item
sleep 1 # sleep one second
}
```
This program reads the file, splits it into chunks, and prints each chunk separately after clearing the screen. `cls` only works on Windows. A variant with `clear` is 57 characters.
[Answer]
## Dyalog APL (64)
(Can't beat Mathematica this time. It seems to have a built-in for everything.)
```
{⎕ML←3⋄{⎕SM←1 1,⍨⊂⊃⍵⊂⍨~⍵∊⎕TC⋄⎕DL 1}¨M⊂⍨~(4/1)⍷⎕TC∊⍨M←80 ¯1⎕MAP⍵}
```
This is a function that takes the filename as its argument. It assumes the file is in Windows (`\r\n`) format.
Explanation:
* `⎕ML←3`: set migration level to 3 (allowing `⊂` to be used as APL2's split feature)
* `M←80 ¯1⎕MAP⍵`: read the file given by the right argument as an ASCII file, and store the contents in `M`.
* `M⊂⍨~(4/1)⍷⎕TC∊⍨M`: find all occurrences of four consecutive terminal control characters, and split `M` on those. This gives each frame.
* `{`...`}¨`: for each of these...
+ `⊂⊃⍵⊂⍨~⍵∊⎕TC`: split the argument (=one frame) on terminal control characters, and then turn the vector-of-vectors into a matrix (so it will display each line on a separate line, this is necessary because `⎕SM` does not understand control characters.)
+ `⎕SM←1 1,⍨`: then display it in the upper left of the `⎕SM` window.
+ `⎕DL 1`: and then wait for one second.
[Answer]
# ~~Awk, 53~~
```
BEGIN{RS=RS RS}{system("clear")}1;{system("sleep 1")}
```
---
New rules:
# Awk, 74
```
BEGIN{RS=z}{a[NR]=$0}END{while(!system("sleep 1;clear"))print a[i++%NR+1]}
```
[Answer]
## Perl, 40
```
seek ARGV,0,!eof;sleep 1;system clear
```
run as
```
perl -p00 frames.pl < animation.txt
```
(i.e. animation file is read through STDIN). 3 bytes for `p00` were added to count. It's 2 characters shorter i.e. **38** on Windows because of `cls` instead of `clear`. Or, to be portable:
```
seek ARGV,0,!eof;sleep 1;system$^O=~/Win/?cls:clear
```
Or, stretching rules a bit (and then 31+3=**34**):
```
seek ARGV,sleep(1)&`reset`,!eof
```
[Answer]
# Rebol, 74
```
forever[foreach s split to-string read f"^/^/"[call"clear"print s wait 1]]
```
Expects the filename to be stored in variable `f`. Below is an ungolfed example:
```
f: %ascii-art.txt
forever [
foreach s split to-string read f "^/^/" [
call "clear"
print s
wait 1
]
]
```
[Answer]
**Java, 678 characters(when golfed)**
Of course with GUI, since doing stuff in console sucks with Java, especially if you want to clear the screen ...
```
import java.awt.Font;
import java.io.File;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
public class G extends JFrame
{
static JTextArea b = new JTextArea();
G()
{
setSize(170, 370);
add(b);
b.setFont(new Font(Font.MONOSPACED, 0, 50));
}
public static void main(final String[] args)
{
new G().setVisible(true);
new SwingWorker()
{
protected Void doInBackground()
{
for(;;)
{
try(Scanner s = new Scanner(new File(args[0])))
{
String l = null;
while(s.hasNextLine())
{
if(l == null || (l = s.nextLine()).isEmpty())
{
Thread.sleep(1000);
b.setText(l == null ? (l = s.nextLine()) + '\n' : null);
}
else
b.setText(b.getText() + l + '\n');
}
}
catch(Exception i){}
}
}
}.execute();
}
}
```
[Answer]
# Cobra - 163
```
class P
def main
while 1
for i in File.readAllLines("t.txt")
print i
if i=="",.x
.x
def x
Threading.Thread.sleep(1000)
Console.clear
```
[Answer]
# Python 117
Assumes the file name is stored in variable `f`.
```
import time,os
while 1:
for i in file.read(file(f)).split('\n'):
print i
if i=='':time.sleep(1);os.system('cls')
```
Note: replace `'cls'` with `'clear'` if on a unix based system, adding 2 chrs.
`ctl+C` to quit
[Answer]
## Groovy - 121 119 chars
Ported [ProgramFOX's answer](https://codegolf.stackexchange.com/a/28153/21004) to Groovy 2.2.1. The "clear console" is weak.
***edit***: replaced recursive closure with simple while loop, which is shorter and no stack overflow
```
a=new File(args[0]).text.split "\n\n";i=0;p={println it};while(1){p a[i++%a.size()];Thread.sleep(1000);80.times{p ""}}
```
Ungolfed:
```
a = new File(args[0]).text.split "\n\n"
i = 0
p = { println it }
while(1) {
p a[i++%a.size()]
Thread.sleep(1000)
80.times{p ""}
}
```
[Answer]
# GNU sed, 32
```
1eclear
/^$/{
esleep 1;clear
d
}
```
[Answer]
# Groovy, 81
This is a more groovy way:
```
new File(args[0]).text.split("\n\n").each{["cls"].execute();print it;sleep(1000)}
```
ungolfed
```
new File(args[0]).text.split("\n\n").each{
["cls"].execute()
print it
sleep(1000)
}
```
[Answer]
# C# 226
Why bother eh?
```
namespace System{class P{static void Main(){for(;;)foreach(var x in Text.RegularExpressions.Regex.Split(new IO.StreamReader("f.txt").ReadToEnd(),"\n\r\n")){Console.Clear();Console.WriteLine(x);Threading.Thread.Sleep(1000);}}}}
```
**Un-golfed**:
```
namespace System
{
class P
{
static void Main()
{
for(;;)
foreach (var x in Text.RegularExpressions.Regex.Split(new IO.StreamReader("f.txt").ReadToEnd(), "\n\r\n"))
{
Console.Clear();
Console.WriteLine(x);
Threading.Thread.Sleep(1000);
}
}
}
}
```
---
Or in LINQPAD (so C# can stay semi-competitive with uber shorthand langs :D)
**C# LINQPAD - 134**
```
for(;;)foreach(var x in Regex.Split(new StreamReader("f.txt").ReadToEnd(),"\n\r\n")){x.Dump();Thread.Sleep(1000);Util.ClearResults();}
```
I feel a bit dirty, but hey, this is code-golf.
[Answer]
# SmileBASIC, 74 bytes
```
F=LOAD(F)@L
IF" "*!CSRX>F[I]THEN WAIT 60CLS
?F[I];
I=(I+1)MOD LEN(F)GOTO@L
```
F should be the file name
] |
[Question]
[

Imgur is a free image hosting service. Many people use it. Here is an example of an imgur link: <https://i.stack.imgur.com/II8CA.png>. Write a program that continually outputs random (valid) imgur links. For example, here is some sample output of my progam (not shown because it contains some tricks you will have to figure out yourself):
```
http://i.imgur.com/uFmsA.png
http://i.imgur.com/FlpHS.png
http://i.imgur.com/eAbsZ.png
http://i.imgur.com/lEUsq.png
http://i.imgur.com/RuveH.png
http://i.imgur.com/BoEwB.png
http://i.imgur.com/HVFGQ.png
http://i.imgur.com/PZpMg.png
http://i.imgur.com/DezCY.png
```
Helpful hints:
* When imgur was new, 5-letter links were used.
* When imgur was new, numbers weren't used.
* You can use this to your advantage: only find 5-letter link images with only letters. That is what my program does.
* Also, all images are saved as `.png`.
Requirements:
* Continually output random imgur links
* Links considered sufficiently "random" if 50 are outputted with no repeats
* When visited, links must be an image
* Links must start with `http://i.imgur.com/` and end with `.png`
* Score is amount of characters
I did it in Java (TERRIBLE for golfing) in 452 chars. Not shown here because it contains some tricks you will have to figure out for yourself!)
[Answer]
**HTML (152)**
```
<img src=x
onload=console.log(s);g()
onerror=g=function(){s='http://i.imgur.com/'+Math.random().toString(36).substr(2,6)+'.png';event.target.src=s};g()>
```
This logs all found images on the JavaScript console using `console.log()`. Works in all tested browsers (Firefox, Chrome, IE9, Safari and Opera).
The fun part is that all sorts of funny images are flashing up for the blink of an eye :).
[Try it!](http://jsfiddle.net/zR4AS/show/) (jsFiddle wraps this into a more complete HTML page, but browsers also accept the single element.)
Props to the [amazing random string method](https://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript/8084248#8084248) by [doubletap](https://stackoverflow.com/users/1040319/doubletap)!
**Where can I see the JavaScript console and the logged images?**
* *Firefox:* Press Control-Shift-K (Command-Option-K on the Mac). Unselect the Net, CSS and JS buttons there, only select the Logging button.
* *Opera:* Press Control+Shift+i, select the Console tab.
* *Chrome:* Press Control+Shift+i, select the Console tab. On the bottom, select Logs.
* *Safari:* Basically like Chrome, but make sure first that [Safari's developer tools are activated](http://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/Safari_Developer_Guide/1Introduction/Introduction.html#//apple_ref/doc/uid/TP40007874-CH1-SW4). Then press Control+Alt+C (on Windows, not sure on the Mac) instead of Control+Shift+i, select the Console tab. On the bottom, select Logs.
* *IE:* Press F12, select the console tab.
[Answer]
## Perl (93 + 4 = 97)
Using imgur's own [random](https://imgur.com/gallery/random) mechanism to get **their** image URLs, which aren't png URLs most of the time:
```
$ perl -Mojo -E 'say+g("http://imgur.com/gallery/random")->dom->at("[rel=image_src]")->attrs("href")for+1..50'
http://i.imgur.com/7cNoA.jpg
...
```
(You need [Mojolicious](http://mojolicio.us) for this.)
[Answer]
## PHP 5.4, 76 characters
URLs are generated in sequential order using only uppercase letters and never repeat, meeting the letter of the specification.
```
<?for($t=@ZZZZ;$t++;)file($u="http://i.imgur.com/$t.png")[0]>@F&&print"$u
";
```
[Answer]
# Perl (87)
```
perl -pe's/\W//g;$_="http://i.imgur.com/$_.png\n";$_=""if`curl $_`=~/^</'</dev/urandom
```
Finding images with uppercase, lowercase and digits from 0 up to any characters,
some day.
[Answer]
### *Mathematica*, 108
White-space added.
```
While[True,
Import@# /. _Image :> Print@# &[
"http://i.imgur.com/" <> "a" ~CharacterRange~ "z" ~RandomChoice~ 5 <> ".png"
]
]
```
[Answer]
## Python (~~174~~ ~~158~~ 156)
I want shorter module names in Python. Also an easier method of getting random letters. :)
```
import urllib,random
while 1:a='http://i.imgur.com/%s.png'%''.join(chr(random.randint(65,90))for i in'AAAAA');print('File'not in urllib.urlopen(a).read())*a
```
Explanation:
The modulus operator on a string is the formatting command, in this case it replaces '%s' in the string with 5 random uppercase letters
`a` is the website name (type `str`)
`('File'not in urllib.urlopen(a).read())` is True when 'File' (from 'File not found!') is **not** found in the the HTML of the URL. (type `bool`)
`bool` \* `str` = `str` if `bool` = True, so it will only output `a` if 'File' is not found in the HTML code.
[Answer]
# Bash (129, 121) (117, 109)
I've got two versions: an iterative and an endless recursive one (which will slowly eat up all memory).
Both versions check if there actually is a PNG file present (jpg's, gif's and other file types are ignored).
Iterative(old) (129):
```
while true;do u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -s 2>&1|head -c4|grep PNG$ -q&&echo $u;done
```
Recursive(old) (121):
```
:(){ u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -s 2>&1|head -c4|grep PNG$ -q&&echo $u;:;};:
```
**Note**:
There might be a compatability issue with grep. My grep manual states that `-s` silents grep's output but it does nothing. However, using `--quiet`, `--silent` or `-q` instead works.
**EDIT:**
Using content headers now after reading <https://codegolf.stackexchange.com/a/10499/7195> :)
Iterative (117):
```
while true;do u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -sI|grep image -q&&echo $u;done
```
Recursive (109):
```
:(){ u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -sI|grep image -q&&echo $u;:;};:
```
[Answer]
# Python, 361 355 334 332 322 314 characters
A little obfuscated, nothing too difficult. May result in unusually high density of cat pictures, you have been warned.
```
import json as j,urllib as o,time as t;a=0
while 1:
q="i.imgur";y,p=('data','children');r="njj";h="erqqvg.pbz/";u="uggc://"+h+"e/"+r;c=j.loads(o.urlopen(u.decode('rot13')+".json?sorted=new&after=%s"%a).read())[y]
for s in c[p]:
f=s[y];w=f['url'].strip('?1')
if w.find(q)!=-1:print w
a=c['after'];t.sleep(3)
```
Output:
```
http://i.imgur.com/u3vyMCW.jpg
http://i.imgur.com/zF7rPAf.jpg
http://i.imgur.com/aDTl7OM.jpg
http://i.imgur.com/KONVsYw.jpg
http://i.imgur.com/RVM2pYi.png
http://i.imgur.com/tkMhc9T.jpg
http://i.imgur.com/KxUrZkp.gif
http://i.imgur.com/mnDTovy.jpg
http://i.imgur.com/WpuXbHb.jpg
http://i.imgur.com/qZA3mCR.jpg
http://i.imgur.com/AxMS1Fs.png
http://i.imgur.com/TLSd571.jpg
http://i.imgur.com/VfMhLIQ.jpg
http://i.imgur.com/Wu32582.jpg
http://i.imgur.com/hrmQL2F.jpg
http://i.imgur.com/Clg8N.jpg
http://i.imgur.com/7Wsko.jpg
http://i.imgur.com/Rhb0UNx.jpg
http://i.imgur.com/LAXAf45.gif
http://i.imgur.com/jhOLJ9B.jpg
http://i.imgur.com/FQ9NeAl.jpg
http://i.imgur.com/oqzf6tE.jpg
http://i.imgur.com/rnpXs1A.jpg
http://i.imgur.com/DfUIz6k.jpg
http://i.imgur.com/orfGA5I.jpg
http://i.imgur.com/wBT7JNt.jpg
http://i.imgur.com/RycK1m2.jpg
http://i.imgur.com/7j21FIR.jpg
http://i.imgur.com/z2tVnNC.jpg
http://i.imgur.com/mnsAGuF.jpg
http://i.imgur.com/vIZM1NY.jpg
http://i.imgur.com/JT3XRI4.jpg
http://i.imgur.com/SNpwTmp.jpg
http://i.imgur.com/u9ynLb9.jpg
http://i.imgur.com/DrFWsBP.jpg
http://i.imgur.com/rU6oyup.jpg
http://i.imgur.com/XxBD5nl.jpg
http://i.imgur.com/d09qQzP.jpg
http://i.imgur.com/vvPSbqI.jpg
http://i.imgur.com/1hdfobQ.jpg
http://i.imgur.com/4LLC6Vs.jpg
http://i.imgur.com/RfasxO2.jpg
http://i.imgur.com/BBcpOos.jpg
http://i.imgur.com/zMH8mgG.jpg
http://i.imgur.com/7g8k2Ww.jpg
```
[Answer]
## R, 182 characters
```
library(httr);while(0<1){s=paste("http://i.imgur.com/",paste(sample(c(LETTERS,letters),5),collapse=""),".png",sep="");if(HEAD(s)$headers$'content-type'=='text/html')'' else print(s)}
```
[Answer]
# Python, 153 chars
```
import string as s,random as w,requests as r
while 1:
t='http://i.imgur.com/%s.png'%''.join(w.sample(s.letters,5))
if'not'not in r.get(t).text:print t
```
While this works, it is bloody slow and might take many seconds before returning any output.
Inspired by @beary605's solution - he saved me a bunch of characters as I was planning to check for image by content-type header.
[Answer]
# Ruby (103 chars)
```
require"open-uri";loop{u="http://i.imgur.com/#{rand(1e9).to_s(36)[0,5]}.png";open u rescue next;puts u}
```
[Answer]
# Bash/command-line tools, 72 chars
Borrowing @memowe's [clever technique](https://codegolf.stackexchange.com/a/10503/11259):
```
curl -sL http://imgur.com/gallery/random|grep e_sr|cut -d\" -f4;exec $0
```
This achieves a continuous loop by re-execing itself within the same process space.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 41 bytes
```
ØẠẊs5Ḣ
“http://i.imgur.com/”;¢;“.png”ṄƲÐḶ
```
How?
```
ØẠẊs5Ḣ : Helper Link
ØẠ : Upper and Lowercase Alphabet
Ẋ : Shuffle
s5 : Split Into Lengths of 5
Ḣ : Head; pop from front of list
-----------------------------------------------------------------------------------------
“http://i.imgur.com/”;¢;“.png”ṄƲÐḶ : Main Link
“http://i.imgur.com/” : String Literal
¢ : Previous link as a nilad.
“.png” : String Literal
; ; : Concat
Ṅ : Print with a linefeed
Ʋ : Last four links as a monad
ÐḶ : Loop; Repeat until the results are no longer unique.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FjftD894uGvBw11dxaYPdyzietQwJ6OkpMBKXz9TLzM3vbRILzk_V_9Rw1zrQ4usgZJ6BXnpQN7DnS3HNh2e8HDHtiXFScnFUMNghgIA)
] |
[Question]
[
There is a competition with \$n\$ participants in total. Alice is one of the participants. The outcome of the competition is given as a ranking per participant with a possibility of ties; e.g. there can be three participants who won 2nd place, and the next best participant gets the 5th place.
More rigorously, a participant's rank is defined as *the number of other participants who performed strictly better than them plus 1*.
If Alice scored \$k\$th place in the competition, what is the number of possible distinct outcomes of the competition? Two outcomes are distinct if there exists a participant whose ranking is different between the two.
As a worked example, let's say \$n = 3\$ and the participants are Alice, Bob, and Charlie. If Alice is 1st, Bob is 2nd, and Charlie is 3rd, the outcome can be written as `{Alice: 1, Bob: 2, Charlie: 3}`, or `[1, 2, 3]` in short. This outcome is distinct from `[1, 3, 2]` or `[1, 2, 2]`. This notation is used in the test cases below.
Assume that \$n\$ and \$k\$ are integers and \$1 \le k \le n\$.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
n, k -> ans (possible rankings; Alice is the first in the array)
1, 1 -> 1 ([1])
2, 1 -> 2 ([1,1], [1,2])
2, 2 -> 1 ([2,1])
3, 1 -> 6 ([1,1,1], [1,1,3], [1,3,1], [1,2,2], [1,2,3], [1,3,2])
3, 2 -> 4 ([2,1,3], [2,3,1], [2,2,1], [2,1,2])
3, 3 -> 3 ([3,1,1], [3,1,2], [3,2,1])
4, 1 -> 26
4, 2 -> 18
4, 3 -> 18
4, 4 -> 13
```
For a given \$n\$, sum of outputs over \$1 \le k \le n\$ is [A000670](https://oeis.org/A000670). The output for \$k = 1\$ is [A000629](https://oeis.org/A000629).
Imaginary brownie points for answers that solve the challenge without generating all possible rankings.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~93~~ ~~84~~ 77 bytes
-9 bytes thanks to @xnor!
Going for the brownie points, but still exponential runtime ;)
```
f=lambda n,k,d=1:(n<2or~-n*(f(n-1,k,d+1)*(d!=k-1)+f(n-1,k-d)))/(d-(k==1)or 1)
```
[Try it online!](https://tio.run/##Tc2xDsIwDATQna8wU@02FjKIpar5l6AQqAJOFXVh4ddDIzEwnfROulve6yPbqdaoT/@6Bg/mkgsqI9p0zOXD1mNEY2k8CPUY9ppYaPgpByI6YGBMqkK5gFCNWxjMBsXb/YbizjTuABqnf7ZtsRUAS5ltxXbe8aVzbd0lovoF "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~124~~ ~~119~~ 117 bytes
*-5 bytes thanks to [enzo](https://codegolf.stackexchange.com/users/91472).*
```
lambda n,k:sum(all(r==sum(q<r for q in s)for r in s)for s in product([k-1],*[range(n)]*(n-1)))
from itertools import*
```
[Try it online!](https://tio.run/##VYxBDoIwEEX3nGKWHSyLxrghchJgUYUqaTstQ1l4@kqjifGvXvLyfnylZ6BzNt2Qnfa3SQNJ2267F9o5wV1XcL0ymMCwwkKwYUH@4VYwcpj2exK9bdQo6541PWZBONaCGoWIleHgYUkzpxDc0fgYONW5PFB5@BRKwgXbCo4VY/8MwQnU15ZFXigJI0iCRcxv "Python 3 – Try It Online")
This uses the `sum` function two times too many, considering the algorithm doesn't involve any addition at all...
## Explanation
The algorithm is pretty simple. Let's assume there are \$n = 3\$ contestants and Alice's rank \$k = 1\$. The ranks that follow will be 0-indexed because it's more convenient to work with. First, it generates a list of possible rankings where Alice's rank, or the first rank in the list, is \$0\$. This is done by taking the Cartesian product of the singleton list \$[0]\$ with \$n - 1 = 2\$ copies of \$[0, 3)\$.
```
[(0, 0, 0), (0, 0, 1), (0, 0, 2),
(0, 1, 0), (0, 1, 1), (0, 1, 2),
(0, 2, 0), (0, 2, 1), (0, 2, 2)]
```
Then, it knocks out invalid rankings by checking if each rank is equal to "the number of other participants who performed strictly better than them", or in other words, the number of ranks lower than the rank in question.
```
[(0, 0, 0), (0, 0, 2),
(0, 1, 1), (0, 1, 2),
(0, 2, 0), (0, 2, 1)]
```
Finally, it returns the number of rankings remaining, which is \$6\$.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~58~~ 57 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍵÷⍨⍺(⊣{n×⍵÷1⌈(⌽-⍺∘=)⍳n←≢⍵}¯1↓⊢/⍤⊢+⊢×(≠∨=∘⍳)∘≢)⍣⍵⊢0,⍨⍵⍴1}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=HY1BCkBQGISv84R4B3AlF5Ct3pO/lAVLPRZ2FkgpG@8mcxLDYpqama8pIIc/IQvkUqinIvf9H2k0RqG5YxYwQxZAthxVC@vYl8@qUXWoXQKZaSHlewU7wiwZAc6Dz6wjORHhII3@owOy6/IF&f=01DPU1dQzwbixLxidc1HvasetU181NWso1/9qHcrEO8CUhpAnAZkatYeWvGodzOQB2FYAAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
A dynamic programming adaption of my recursive Python answer. Runs in \$ \mathcal{O}(n^2) \$. A brute force approach would 25 bytes:
```
{⊃+⌿⍺=1+↑∪(+/∘.<⍨)¨,⍳⍵⍴⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U1az9qGf/o95dtobaj9omPupYpaGt/6hjhp7No94VmodW6Dzq3fyod@uj3i1AshYA&f=01DPU1dQzwbixLxidc1HvasetU181NWso1/9qHcrEO8CUhpAnAZkatYeWvGodzOQB2GYAAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 11 bytes
```
RJ:ᵐhmj↕ũh=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FhuCvKwebp2QkZv1qG3q0ZUZtkuKk5KLoZILbqobKhhyGYGxEZcxkDYG08ZcJkC2CZBtAmabQNQDAA)
```
RJ:ᵐhmj↕ũh= Take input n, k
R Range from 1 to n
J Split the range into a list of parts
:ᵐhm Replace every element in each part with the head of the part
For example, [[1],[2,3],[4,5]] -> [[1],[2,2],[4,4]]
j Join the list of parts into a single list
↕ Take a permutation
ũ Remove duplicate permutations
h= Check if the head of the list is equal to k
```
`-n` counts the number of solutions.
[Answer]
# JavaScript (ES6), 63 bytes
A port of [ovs' great Python answer](https://codegolf.stackexchange.com/a/269860/58563). Now including the optimization suggested by xnor.
Expects `(n, k)`.
```
f=(n,k,d=1)=>(--n?n*=(~d+k&&f(n,k,d+1))+f(n,k-d):1)/(d-!~-k||1)
```
[Try it online!](https://tio.run/##dZDRCoIwFIbve4p1I1tuydkRicB6kPBCXEYpMzK6El/dlnNGuK72w/efbzu75a@8LR7X@1PoRp2HoUyp5hVXKbD0QIXQR71Jaa/CKghKi0JgLByzUGwPLKJKrHtRdR2woWh029Tnbd1caEmBmy6JIgKEniBjq18sHZYfzCHjxBzS05NfjRlaFNCJEityKuBoA85yo5/CjKTHN10Y2wttVzqNkbgA3mm002im0b0Gx@4YfCvE818kC@K23y0I/iXxRHB4Aw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 114 bytes
Expects `(n)(k)`.
```
n=>k=>eval("for(j=t=n**n;j--;)t-=(a=[...Array(n)].map((_,i)=>x=j/n**i%n|0)).some(r=>a.map(v=>q-=v<r,q=r)|q|~x+k)")
```
[Try it online!](https://tio.run/##dZB9a4MwEIf/36eQQiHXxbgkUgbtCfscRUbodGhtUqNIB7Kv7jLfytBBIAfP755LLleNqs42u9W@Nh9Jl2KnMbpglDSqIJvUWJJjjXq304fc9w9Q@0gUnhhjb9aqL6IhZld1I@SdZoDRHfPAhbOtbl8AWGWuCbEYqT7TYFT62BwtLdFCW7bf9@cLbKA7G12ZImGF@SQp4eAOeEHgcY@ceAxPf7mYufjllMfUc5dYC4qHSNClSs6q/aCaZJzKoZCz3g0YixmJNeE4MhxGDmExeZxlKvh6uxzapWuX03tkH@6LtV@Ej4Xsl2hawesSyf9ROCLZ/QA "JavaScript (Node.js) – Try It Online")
### Commented
This is a version without `eval()` for readability.
```
n => // outer function taking n
k => { // inner function taking k
for( // loop:
j = t = n ** n; // start with j = t = n ** n, where:
// j = iteration counter
// t = success counter
j--; // stop once j = 0 has been processed
) //
t -= // decrement t for each failure
( a = // let a[] be an array of n entries,
[...Array(n)] // which are turned into 0-indexed rankings
.map((_, i) => // for each value at index i in a[]:
x = // save the last value in x
j / n ** i // fill with an integer in [0 .. n-1],
% n | 0 // according to j and i
) // end of map()
).some(r => // for each ranking r in a[]:
a.map(v => // for each ranking v in a[]:
q -= v < r, // decrement q if v < r
q = r // starting with q = r
) // end of map()
| q // some() is triggered if q != 0
| ~x + k // or x != k - 1 (i.e. the last ranking
// is not Alice's ranking)
); // end of some() / end of for()
return t // return the success counter
} //
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L¤ãʒ<Ðδ›OQ}€нQO
```
Port of [*@totallyhuman*'s Python answer](https://codegolf.stackexchange.com/a/269855/52210), so make sure to upvote that answer as well!
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//0zCpMOjypI8w5DOtOKAuk9RfeKCrNC9UU///zMKMQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8X@fQ0sOLz41yebwhHNbHjXs8g@sfdS05sLeQP//Ov@jow11DGN1oo2gpBGQNAazjaFsYyBpAhYxAYuYQEVMYmMB).
**Explanation:**
```
L # Push a list in the range [1, first (implicit) input-integer n]
¤ # Push its last item (without popping): n
ã # Cartesian product to get all n-sized lists using [1,n]-ranged integers
ʒ # Filter it by:
< # Decrease all values in the list by 1
Ð # Triplicate the list
δ # Pop two, and apply double-vectorized:
› # Larger than check
O # Sum each inner list/row together
Q # Check if this list of sums equals the original list we've triplicated
}€н # After the filter: only leave the first item of each remaining list
Q # Check for each whether it equals the second (implicit) input-integer k
O # Sum those checks together
# (which is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly) (fast version)
```
cⱮ`€U;ḋ¥ƒ1H1¦ṖṚ,Ʋ⁹ịⱮPḤ×c×÷⁸
```
A dyadic Link that accepts \$n\$ on the left and \$k\$ on the right and yields the count of weak orderings given a labelled item's rank.
**[Try it online!](https://tio.run/##AUUAuv9qZWxsef//Y@KxrmDigqxVO@G4i8KlxpIxSDHCpuG5luG5mizGsuKBueG7i@KxrlDhuKTDl2PDl8O34oG4////NDD/MjA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/50cZ1CY@a1oRaP9zRfWjpsUmGHoaHlj3cOe3hzlk6xzY9atz5cHc3UE3Awx1LDk9PPjz98PZHjTv@60C1PdzVd2jr0UkPd87QObxcP@tRwxwFWzuFRw1zNSP//zc0AAA "Jelly – Try It Online").
### How?
First calculates the first \$n+1\$ Fubini numbers ([A000670](https://oeis.org/A000670)): \$F(a) \forall a \in [0,n]\$.
This is achieved by expanding the recursive calculation \$F(a) = \sum\_{j=1}^a{F(a-j)\binom{a}{j}}, F(0)=1\$ as a reduction of dot-products over the relevant portion of Pascal's triangle. (I think this can probably be golfed a little by using the recursive calculation itself.)
Then uses that to calculate half of the number of necklaces of partitions of n+1 labelled beads (\$\frac{1}{2}\$[A000629](https://oeis.org/A000629)) which is simply \$F\$ but with the first term halved: \$\frac{N(a)}{2} \forall a \in [0,n]\$
Finally applies the formula suggested by [Nitrodon](https://codegolf.stackexchange.com/users/69059/nitrodon) in the comments:
$$R(n,k)=F(k-1)N(n-k)\binom{n-1}{k-1}$$
```
cⱮ`€U;ḋ¥ƒ1H1¦ṖṚ,Ʋ⁹ịⱮPḤ×c×÷⁸ - Link: n, k
€ - for each {v in [1..n]}:
Ɱ` - map across {w in [1..v]} with:
c - {v} choose {w}
U - reverse each -> [[1C1], [2C2, 2C1], [3C3, 3C2, 3C1], ...]
ƒ1 - starting with 1 reduce by:
¥ - last two links as a dyad f(current, next):
ḋ - {current} dot-product {next}
; - {current} concatenate {that}
-> [F(a) for a in [0..n]] = Fubinis
Ʋ - last four links as a monad - f(Fubinis):
H1¦ - halve the first term
Ṗ - remove the last term
Ṛ - reverse
, - pair {Fubinis} -> [Necklaces/2, Fubinis]
⁹ịⱮ - kth element of each -> [N(n-k)/2, F(k-1)]
P - product
Ḥ - double -> F(k-1)*N(n-k)
c - {n} choose {k}
× - multiply -> F(k-1) * N(n-k) * nCk
× - multiply by {k}
÷⁸ - divide by {n} -> F(k-1) * N(n-k) * (n-1)C(k-1)
```
[Answer]
# Ruby, 212 bytes
## ... but runs in polynomial time!
```
def f(n)=n<1?1: n*f(n-1)
$r={}
def r(n, k)=$r[[n,k]]=k**n-(1...k).sum{|i|f(k)/f(i)/f(k-i)*$r[[n,i]]}
def q(x)=x<1?1:(1..x).sum{|i|r(x,i)}
def s(n, k)=(0..(n-k)).sum{|e|f(n-1)/f(k-1)/f(n-k-e)/f(e)*q(k-1)*q(n-k-e)}
```
The final solution is function `s`, which takes *n* and *k* as arguments.
### How does it work?
Divides *n* - 1 people into three categories: those who were strictly better than Alice, those who were equal, and those strictly worse. We know that exactly *k* - 1 people ranked better than Alice, we just need to iterate over how many were equal: minimum of 0, maximum *n* - *k*.
There are 3 auxiliary functions. Function `f` is just factorial definition. Function `r` calculates how many ways to distribute *n* people into exactly *k* distinct ranks, and must be memoized else the running time goes exponential. Function `q` calculates how many ways do distribute *x* people into any number of ranks (it is just a summation of `r`).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
NθNηILΦEXθ⊖θ⊞O﹪÷ιXθ…⁰⊖θθ⊖η⬤ι⁼λLΦι‹νλ
```
[Try it online!](https://tio.run/##ZY7NCsIwEITvPkWOG4gg4q0nsQoFf4pvENulCWyTNj/18WMqFCzubWZnPqZR0jVWUkqVGWK4x/6FDkZebH61yrp22gQ4SR/giqYLCi6aQn7e5AC1fc81wUpsHPZoAraZwgWro1ePAZ0MNkdtG8lCZUKpJ90i6BxYqk9pOoTdH2OmjHxtq697JJoJ5zFK8kCCrYfp2fAejGDElytSOmz2aTvRBw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on @totallyhuman's Python answer.
```
Nθ Input `n` as a number
Nη Input `k` as a number
θ Input `n`
X Raised to power
θ Input `n`
⊖ Decremented
E Map over implicit range
ι Current value
÷ Vectorised integer divided by
θ Input `n`
X Vectorised raised to power
… Range from
⁰ Literal integer `0` to
θ Input `n`
⊖ Decremented
﹪ Vectorised modulo
θ Input `n`
⊞O Concatenated with
η Input `k`
⊖ Decremented
Φ Filtered where
ι Current list
⬤ All elements satisfy
ι Current list
Φ Filtered where
ν Inner element
‹ Is less than
λ Outer element
L Take the length
⁼ Equals
λ Current element
L Take the length
I Cast to string
Implicitly print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (golf version)
```
ṗ`<Ɱ`§‘ƊƑƇḢ€ċ
```
A dyadic Link that accepts \$n\$ on the left and \$k\$ on the right and yields the count of weak orderings given a labelled item's rank.
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//4bmXYDzisa5gwqfigJjGisaRxofhuKLigqzEi////zX/Mw "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzukJNo82rks4tPxRw4xjXccmHmt/uGPRo6Y1R7r/64AkgMyHu/oObT066eHOGTqHl@tnPWqYo2Brp/CoYa5m5P//pgA "Jelly – Try It Online").
### How?
```
ṗ`<Ɱ`§‘ƊƑƇḢ€ċ - Link: n, k
ṗ` - {n} Cartesian power {n} -> all length n words of alphabet [1..n]
Ƈ - filter keep those for which:
Ƒ - is invariant under?:
Ɗ - last three links as a monad - f(word):
<Ɱ` - {word} less than mapped over {word}
§ - sums -> [count of elements less than i for i in word]
‘ - increment {those}
-> all valid rankings
Ḣ€ - head each -> Alice's rank in each valid ranking
ċ - count occurrences of {k}
```
[Answer]
# Python3, 222 bytes
```
from itertools import*
R=range
def f(n,k):
t=0
q=[(1,{*R(n)},{})]
for a,b,c in q:
if not b:t+=c.get(k,[-1])[0]==0
else:
for i in R(len(b)):
for C in combinations(b,i+1):q+=[(a+i+1,b-{*C},{**c,a:C})]
return t
```
[Try it online!](https://tio.run/##XY4xboQwEEV7n2JKD3ijZaGIkFxxA1pEgYm9sRZsMJMiQnt2YpAiLdvN@3p/9Kdf@vYu/5zCtpngR7CkA3k/LGDHyQdKWC1D5@6afWkDhjvxwJIBySuDWTY8E2tSc4dPsT6xZWB8gE4o0YN1MEcTrAHnCVRJqew/7pr4QzSXrMXm2sr9Dehh0bt5lO1erPmgHVeIR3zk1Z73flTWdWS9W7gSNs2wnNM4o0vjLdRlTaq4JEl60ZXVMSho@gkOaJuCdcRNXJwhsn@6CXjD2wvm7/jqFudqcXYj5mcsELc/)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 120 bytes
```
n=>g=(k,...s)=>(s[n-1]?k==s[0]&[...s].sort((a,b)=>a-b).every(u=(t,i)=>t==u|(u=t)==i+1):g(k,n,...s))+(--s[0]?g(k,...s):0)
```
[Try it online!](https://tio.run/##dZDRjsIgEEXf/Yo@mSECCjRmYzL6IQ0P1a1N1cCmoMkm@@@VSqkx7SYkXObeOQNcykfpTm3z45mx31V3xs7gvka4Us65I7gHVxgm9OGK6IqNXhZ9XXNnWw9Q0mOIlOxIePWo2l@4I3jahJpHvP@FoyeIzUqQXR2QJkLJChjrYYc6zdltSHeyxtlbxW@2hjMIEhbJ1utMZFAITRafvhx92ftUaJqFTc4F5Rsk6RSlRtQ2ohJMUBWFGvFhwCBGS84Bh5F5HBnDMnECJQkx365iuwrtKt1HvcIvMfeK/P0h26mVvuBraqn/rXywVPcE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 102 bytes
```
f(n,k)=∑_{a=0}^{n^n/n-1}0^{[(B[B<i].count-i)^2fori=B].max}
B=mod(floor((na+(k-1)n^n)/n^{[1...n]}),n)
```
[Try It On Desmos!](https://www.desmos.com/calculator/blfnhuzhkv)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/wntdriptde)
Eh, this is so scuffed but it works so whatever lmao.
] |
[Question]
[
Imagine there are \$n\$ people \$\{a\_1, a\_2, \ldots, a\_n\}\$ who enter a room in order and sit down in \$n\$ seats, arranged in a row. Each of these people belong to some gang, indicated by an integer \$\{1, 2, \ldots, k\}\$. These gangs hate the members of the other gangs, so they want to sit as far away from those people as possible; specifically, they sit in the set which maximizes the minimum distance from anyone *in a different gang* who is already seated. They break ties by sitting in the seat furthest to the left.1
For example, suppose \$n=6\$, and there are \$k=3\$ gangs \$\{1, 2, 3\}\$.
Now imagine that the first person that enters is in gang 1, the next two are in gang 2, the next two are in gang 3, and the final person is in gang 1 again -- i.e. the order is `[1, 2, 2, 3, 3, 1]`. Then the people will sit down in the following order:
```
_ _ _ _ _ _
1: 1 _ _ _ _ _
2: 1 _ _ _ _ 2
2: 1 _ _ _ 2 2
3: 1 _ 3 _ 2 2
3: 1 3 3 _ 2 2
1: 1 3 3 1 2 2
```
Your challenge is, given a sequence of numbers \$\{a\_1, a\_2, \ldots, a\_n\}\$, where each \$a\_i \in \{1, 2, \ldots, k\}\$ is some positive integer representing a person in some gang, output the final arrangement of the \$n\$ people in \$n\$ seats as described above. (If useful, you can take \$n\$ and \$k\$ as extra inputs.) You can assume that no gang number will be skipped - e.g. \$\{1, 2, 4\}\$ would not be a valid input.
### Test Cases
```
[1] -> [1]
[1, 2] -> [1, 2]
[1, 1, 1] -> [1, 1, 1]
[1, 2, 1, 2, 1] -> [1, 1, 1, 2, 2]
[1, 2, 2, 3, 3, 1] -> [1, 3, 3, 1, 2, 2]
[1, 2, 4, 3, 2, 1, 4] -> [1, 3, 1, 4, 4, 2, 2]
[4, 4, 4, 3, 3, 2, 1] -> [4, 4, 4, 2, 1, 3, 3]
[1, 2, 3, 4, 5, 6, 7] -> [1, 4, 5, 3, 6, 7, 2]
```
Standard loopholes are forbidden. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program wins.
1 This is a variation of the "urinal protocol".
[Answer]
# [Uiua](https://uiua.org), 32 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
∧⋄∸(⍜⊏+⊢⍏×-1,/↧⌵∺-⇡⊃⧻⊚×⊃±≠,,)≠..
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oin4ouE4oi4KOKNnOKKjyviiqLijY_Dly0xLC_ihqfijLXiiLot4oeh4oqD4qe74oqaw5fiioPCseKJoCwsKeKJoC4uCgpmIFsxIDIgMiAzIDMgMV0gICAjIFsxIDMgMyAxIDEgMl0KZiBbMV0gICAgICAgICAgICAgIyBbMV0KZiBbMSAyXSAgICAgICAgICAgIyBbMSAyXQpmIFsxIDEgMV0gICAgICAgICAjIFsxIDEgMV0KZiBbMSAyIDEgMiAxXSAgICAgIyBbMSAxIDEgMiAyXQpmIFsxIDIgNCAzIDIgMSA0XSAjIFsxIDMgMSA0IDQgMiAyXQpmIFs0IDQgNCAzIDMgMiAxXSAjIFs0IDQgNCAyIDEgMyAzXQpmIFsxIDIgMyA0IDUgNiA3XSAjIFsxIDQgNSAzIDYgNyAyXQo=)
```
∧⋄∸(⍜⊏+⊢⍏×-1,/↧⌵∺-⇡⊃⧻⊚×⊃±≠,,)≠.. input: array of gang ids
∧⋄∸( )≠.. fold over the input, using [0 ... 0] as the initial accumulator
( ) inner function: placed gang ids, next gang id -> placed gang ids
⊃±≠ sign (is occupied?), not equal (is not the current gang?)
√ó multiply (has a person under a different gang?)
⇡⊃⧻⊚ all indices (all positions), indices of ones (positions of enemies)
/↧⌵∺- for each position, minimum distance from enemies
(infinity if no enemies)
√ó-1, multiply (placed gang ids - 1) to make valid distances negative
infinity * 0 is NaN, whose sort order is after infinities
⊢⍏ first index of minimum (the index of maximum distance from enemies)
‚çú‚äè+ ,, add the new gang id at the found index
```
[Answer]
# Python3, 218 bytes
```
def f(g):
R=[0]*len(g)
for i in g:
d=[[],[]]
for j,k in enumerate(R):
if k!=i:d[k==0]+=[j]
if d[0]:R[max([(j,min(abs(j-J)for J in d[0]))for j in d[1]],key=lambda x:x[1])[0]]=i
else:R[min(d[1])]=i
return R
```
[Try it online!](https://tio.run/##dYxBTsMwEEX3OcWws8FIpQkFRfIFuszW8sKV7WIncSM3ldLThxlXCAFFmsXMf3/edJ0/Tql@n/K6WufBsyNvK@ik2ujHwSU8K/CnDAFCgiMisFIpLZTWuBOJoifm0mV02cyOdWQACB76Bxlaq3opN/pJqkgvGFuUt50azcIUi2IMiZnDmcXnPSfhnnTU4eWMt/NFa9G7qxzMeLAGlnbBiGNLy4BaN5wdOdFFXV7S7OZLTtCtUw5pZp4R4dX3JWD7O6D5Uyrx9j7Bqcvcg00ht//mB28KbL6e/5HXpfIqYCfgDfn6CQ)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 bytes
```
¬,an¥T€ạṂNɗÞ/Ḣ
+禃¬
```
[Try it online!](https://tio.run/##y0rNyan8///QGp3EvENLQx41rXm4a@HDnU1@J6cfnqf/cMciLu3Dyw8tOzbp0Jr/D3fus37UMEdB107hUcNc68PtQAEVroe7txyd/HDnYoQMUNfRSWGH249tAhoX@f@/kpJStGEsSBJIcUUb6igYQXkgFlgAhOBiYA5EHZhjhC4JFjKCKwEiYzBCqILy0RSagEUhhpogqzUEy5nAlZvA@MZwHRDlJkgKodbATTcGS5jqKJjpKJjDTYcIGUNEQaYDQwMA "Jelly – Try It Online")
A pair of links which is called with a single argument of a list of integers and returns a list of integers.
## Explanation
```
¬,an¥T€ạṂNɗÞ/Ḣ # ‎⁡Helper link: take a current list of seated people as the left argument and the next person to seat; returns the index of the best available seat
¬ # ‎⁢Not (vectorises)
, ¥ # ‎⁣Pair with:
an # ‎⁤- The result of anding the current seating plan with the result of checking which ones don’t equal the new person
T€ # ‎⁢⁡For each of these, generate a vector of truthy indices
ɗÞ/ # ‎⁢⁢Reduce this list of lists; generate a sorted version of the first list (the indices of empty seats) sorted by the following:
ạ # ‎⁢⁣- Absolute difference between a given index of an empty seat and the indices of all of the seats filled with rival gang members
Ṃ # ‎⁢⁤- Minimum
N # ‎⁣⁡- Negate
Ḣ # ‎⁣⁢Head (I.e. the index of the best available seat)
+禃¬ # ‎⁣⁣Main link: takes a list of people to seat and returns the seating plan
ƒ¬ # ‎⁣⁤Reduce the list of people to seat, using a list of zeros of the same length as the starting left argument and the following:
+ # ‎⁤⁡- Add the new person
ç¦ # ‎⁤⁢ - Specifically just at the index given by using the helper link
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [R](https://www.r-project.org), ~~94~~ 84 bytes
```
\(x,y=!x){for(z in x)y[which.max(sapply(v<-seq(y),\(w)min((w-v[y-z&y])^2))*!y)]=z;y}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVBtSsQwEMW_PYTMFlYykiy0Wz_A7Z7Cf22FUlK30O3GJm6TqifxTxU8lJ7GNKW4IAzJvPdmHjPz_tEOn2X89axKdvt9nxJNTbzQ-FIeWtJD1YBGk3S7qtit9rkmMheiNuS4YZI_EYM0JR3uq4aQjh0Tw_oLk-FDiHi5MJjF_Z15m7x_zs65hg0DqVop6koRP_ACCuH4jOGAS8M_ZGPtYiYih6a6yIscEc1FJ41rR19RuKZw41Pw08bHJAmyDF633skQVkJH1dNmuVxVjeKPvEWvyNW8MNcU7HFQitbKJfGXEtgWltIaiFwqbg8HxaG2LpJDDM53lkrb-F9Fy0kuRjgON51pGKb_Fw)
A function that takes an integer vector and returns an integer vector. Works similarly to [my Jelly answer](https://codegolf.stackexchange.com/a/266427/42248), but golfed differently to reflect the differences in language.
*Thanks to @pajonk for saving three bytes!*
## Ungolfed version
```
find_closest_distance <- function(seat_index, current_seats, next_person) {
distances <- abs(seat_index - seq(current_seats)[current_seats & current_seats != next_person])
min(distances)
}
find_best_seat_and_allocate <- function(current_seats, next_person) {
closest_distances <- sapply(seq(current_seats), find_closest_distance, current_seats = current_seats, next_person = next_person)
best_seat <- which.max(closest_distances * !current_seats)
current_seats[best_seat] <- next_person
current_seats
}
f <- function(people) {
Reduce(find_best_seat_and_allocate, people, init = !people)
}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVNLTsMwEBUsfQg0jVRkIxeppXwWwCGQWJUqctMJWAqOybiiCHoSNmXBpTgNttuUpEUgWVFmPPPmvWf7_aNaLj9nLu9dfO3f5tpM06woCcmlU01OmQzhsgf5zGROl4YTKpf6KpxLyGZVhcalIUcSDM5darGi0gh4ZVD3UwBQE2r0Qg8In3gLQIxaIRy28aFz1ZwwFgweteGbIYItGIv8J4F8nKV8pIqizJRrq_iH-bYDUQEpa4sXvstbwq-2bfkDV3_4BS1tXtpGQ5j8_KCzh-NHNee7xI6g02bD2mNGG6RxgGpM2SqM9rVMsljaAqMhNzidZcj_sFfCqlyCNtp5PZ11O1usb9fegT_34KOryBba8aTP-hIG4RNWDOLv4Cfy6ySuOjGM0apuyIYxMayLGo0nMX0q4UzCeSIhuTOJGI364zG8XbMGCb8lYqpYna-iY20c3mMlmBfG18ce7vsdnwuyld_OedIl6F1DlzyAVeSQhwdRFh6F0MuPuPVW7ht3d4XPEdoQBnIrm-rH-A0)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 102 bytes
```
x=>x.map(c=>s[x.map((_,k)=>x.some((_,i)=>s.some((v,j)=>(i-j)**2<k*k&v!=c|i==j)?0:[A=i])),A]=c,s=[])&&s
```
[Try it online!](https://tio.run/##dYxdC4IwFIbv@xV2I5sco2x9EB3D3zEkZCRsYomT4UX/fc1ZRGXwXpznfc45qjCFFq1sutjsbYm2x7Rf1EVDBKaajyM5Q0WHXt/qy0DSkX6SAeWIyFjRKEqOVVSFZo7iLhEVPS0PPEOZUwpZjgI08pyGobZNK68dKQlfOTd7EwTJdzHkZ8nXybRxWftMSebNeM8@PPOSvY7/PF/7lQ0EWwh2ztsH "JavaScript (V8) – Try It Online")
Seems quite unpolished
pseudo-code:
```
s = []
for c in x:
for k in range(len(x)):
for i in range(len(x)):
if at position i distance k:
A = i
break
s[A] = c
```
[Answer]
# [J](https://www.jsoftware.com), 49 bytes
```
0"0]F..([`(0{&\:~:*[:<./@(I.|@-/i.@#)~:**@])`]})]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZHBToNAEIbjlaeYQgSWwsAulNqFGqJJkybGg1dYrTES9eJFT6W9-RRe6sGHqk_jsgulmtnJ7vz_t_-G8Pn1stufzkacinTEZ45jmOjUMOfggA8RcNkBwuXN1eL7_a0OzvY0MiOxQHTLlRut7YpvuVfyHMPCXWJTBOEzFhaRolcIshIbIvTFn5MPYlxfICjYpFbVwnS8RKW6OTZI7A3ame3SvGhTMqSFL0ijif5dItRILYzmd2xd8jGGgN4tv-dbdq5jrUoxVpXJW-r4-PD0CgxqoPKL2o6AGUqkEPBW7yfWzYNPD0xbxyo7onX3bizrn8-0OBAUEll_mETKTBkaSzpEByos8bsVq8X8ITKBiaRSmB4ilR8rfOJD6sNU_43dTu-_)
* `0"0]F..(fold verb)` A single forward fold that we seed with a list of zeros as long as the input
* To find the new position of each person in line, we...
+ `~:**@]` First create an array which is 1 only in positions of rival gang members, and 0 elsewhere
+ `I.|@-/i.@#` Create a table of absolute differences between the indexes of those ones and all indexes
+ `<./@` And min the resulting rows of that table. This gives us a list showing the distance to the closest rival gang member at each position.
+ `~:*` Zero out any position holding one of our own gang members.
+ `0{&\:` Take the first element of the grade down. This gives us the first of all the "farthest" positions, as needed.
* `[` Update that position with the value we're folding.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
Fθ⊞υ⁰Fθ«≔Eυ∧¬κ⌊Eυ⎇∧μ⁻ιμ↔⁻νλLθη§≔υ⌕η⌈ηι»Iυ
```
[Try it online!](https://tio.run/##NY3LCsIwFETX9ivu8gau4NtFV0UQBBUX7sRFbGsTbFPNQxTx22NSdZYzhzm54Dpvee39udWANwY7ZwQ6ggFLk3/3SnqZMbJSuOHXOGaqwG1r8cIINlLJxjX/aV9qxfUTI9J0qzMoCRoW2Oxk2trZEr@1IqhjvS5VZUUwdSEQwf0zZnalivIRn5cyXIpwyR@dUERUBvSd7LRUFhfcWHSMpd4fDkOCEcGYYEIwJZgRzI9H37/XHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Fθ⊞υ⁰
```
Create an array of empty seats of the same length as the input.
```
Fθ«
```
Loop over the input.
```
≔Eυ∧¬κ⌊Eυ⎇∧μ⁻ιμ↔⁻νλLθη
```
For each seat, if it is empty, calculate the distance to the nearest rival.
```
§≔υ⌕η⌈ηι
```
Place this person in the seat furthest away from any rival.
```
»Iυ
```
Output the resulting seating arrangement.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
_IvÐĀUyÊX*āsƶ0KδαεIgªß}X<*Wkysǝ
```
Port of [*@Bubbler*'s Uiua's answer](https://codegolf.stackexchange.com/a/266432/52210), so make sure to upvote that answer as well!
[Try it online](https://tio.run/##yy9OTMpM/f8/3rPs8IQjDaGVh7sitI40Fh/bZuB9bsu5jee2eqYfWnV4fm2EjVZ4dmXx8bn//0eb6ICgMRAa6RjGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf/jK8sOTzjSEFp5uCtC60hj8bFtBt7ntpzbeG7roXXph1Ydnl8bYaMVnl1ZfHzu/1qd/9HRhrE60YY6RmASCCE8HTCGso10jIEQxjMBskHyJkC@iY4JmG@MpNoYKGKqY6Zjji4PEdWx0LHUMTSIjQUA).
**Explanation:**
```
_ # Convert each value in the (implicit) input-list to 0
Iv # Push the input-list again, and loop over its items `y`:
Ð # Triplicate the current list
Ā # Pop one, and check which positions are occupied
U # Pop and store this list in variable `X`
yÊ # Pop another copy, and check all positions NOT filled with gang `y`
X* # Multiply it to list `X`, so we have a list with 1s at enemy positions
ā # Push a list in the range [1,length] (without popping)
s # Swap so the earlier enemy positions list is at the top again
∆∂ # Multiply each value by its 1-based index
0K # Remove all 0s
δα # Pop both lists, and create an absolute difference table
ε } # Map over this list of lists
Igª # Append the input-length to the list (edge case for empty lists)
ß # Pop and push the minimum
X # Push list `X` again
< # Subtract each value by 1 (0s for enemy positions; -1 otherwise)
* # Multiply it to the values of the mapped list
W # Push the minimum (without popping the list)
k # Pop both, and push the (first) (0-based) index of this minimum
ys # Push the current gang `y`, and swap
«ù # Insert the current gang `y` at this index into the list
# (after the loop, the resulting list is output implicitly)
```
[Answer]
# [Scala](http://www.scala-lang.org/), 207 bytes
207 bytes, it can be golfed much more. Golfed version. [Try it online!](https://tio.run/##dVJRa9swEH7vr7iFUiRwRJqmG6TIsLE9FBoYlK0PpZSrJDfKZNlY8khq9NtTWfY6uixwSHf3ffruTpITaHBfPW2U8LBCbaE7AZCqgDIGBJtnt4TPTYO7@1vfaPv8QJfww2oPPDEBfqMBbevWf0WPMXujnScJgcE/p9m7MIP5Qaa3Q1rKz49A0S6S/RddJGhQWLwnLBK6@HP8mP5F4lxm8DGDTzTh9CRtb9OyomoUijV0UKuqNgp4Pgr1t9Io15r@ogYwso28UYUnfRVWaGPIiDj9oiiZURqViGibRll/q9C7DKza@u@qcZWlf9UB8Dht5IRxr@OreWOJm5x2Y7ny1/CWZJLBhAaY5nDaDd3@i00GuV4s9NP3c@ES0gj319Y/ZHGhPH@Lge@JyGxMdT1XcsG0lVoox0qsO81zXRBBNOV8Rg8oojIm/sROoFOwAV2AIBv6gc/OzgbH8nyFfs3wyRE93dBwFeUk0@5bWfsdjR2wFW5/omkVKBNFJCu1DcmdnocrwdpaolcyHnrR9Z3262sr1TY2t/2yS3WJzB5j@zKwx3kcJOzD/hU)
```
(c,n)=>{val d=c.indices.map{i=>if(c(i)==0){val d=c.indices.collect{case j if c(j)!=0&&c(j)!=n=>Math.abs(i-j)};if(d.isEmpty)Int.MaxValue else d.min}else -1};c.updated(d.zipWithIndex.maxBy{case(d,_)=>d}._2,n)}
```
Ungolfed version. [Try it online!](https://tio.run/##hVNda9swFH3Pr7gLpUjgmDbNNgikkK57KLQwKNseSimKLTfaZNlI8nBq/NuzK9m143xQEP645@ro3HOvTMQk226z1R8eWXhgQkE1Aoh5Ain@EKZfzRyWWrPN06PVQr0@0zn8VMLCwmcC/GMShMoLe8ssw@i9MJZ4BJrvSxoMfgOYHkTcOkzz8ekJCNeVX0fRmYcahtkwYebR2fv2U/xXPudzAF8C@Eo9Tkf@1VUbJpnmLFpDBTnPcslhcd0SOVc0N4V0RjUgZsv4nieWuFPCREhJWsSIN07JBaXIRKJCa67sI2fWBKB4aX9wbTJFe3aARKj4hhuftVTxUsosYpaf3tzurNt3jr20UhEzPqtaEenfpsNkHMCY1jC5hrOqqWEfGzd0jqwetfPiFH2TmUFRt1gfUxEnBmXcqZiXc7hTNoBddXNv9hPGn3eF@kzqn4MRi1tOg9FdmhCPFRgOo0xKN8RVW2HEDAcRlyCSwQaCMQqfFnAB5@fHkV4NWo63wq5DtjJ9NTBxxL0H4M4gncJQmO9pbjfUFRE@sPIXkwUHLlFQn5QKtW/fRw39wLIOHBgXDXty0r@U5Th9zrBuzFxVhwYt0Dp6tN0ID3s8HF9vwORyxzanb9UW7XTtSQ3fRP5b2LU3HQWWNxuU6BvbuR3Ai7sYnbFQhy9TTz6osshjdDMm76ft3416VG@3/wE)
```
object Main {
def main(args: Array[String]): Unit = {
val inputData = List(
List(1),
List(1, 2),
List(1, 1, 1),
List(1, 2, 1, 2, 1),
List(1, 2, 2, 3, 3, 1),
List(1, 2, 4, 3, 2, 1, 4),
List(4, 4, 4, 3, 3, 2, 1),
List(1, 2, 3, 4, 5, 6, 7)
)
inputData.foreach { people =>
val result = people.foldLeft(List.fill(people.size)(0)) { (currentSeats, nextPerson) =>
findBestSeatAndAllocate(currentSeats, nextPerson)
}
println(s"${people.mkString(", ")} -> ${result.mkString(", ")}")
}
}
def findClosestDistance(seatIndex: Int, currentSeats: List[Int], nextPerson: Int): Int = {
val distances = currentSeats.indices.collect {
case idx if currentSeats(idx) != 0 && currentSeats(idx) != nextPerson => Math.abs(seatIndex - idx)
}
if (distances.isEmpty) Int.MaxValue else distances.min
}
def findBestSeatAndAllocate(currentSeats: List[Int], nextPerson: Int): List[Int] = {
val closestDistances = currentSeats.indices.map { idx =>
if (currentSeats(idx) == 0) findClosestDistance(idx, currentSeats, nextPerson) else -1
}
val bestSeat = closestDistances.zipWithIndex.maxBy { case (distance, _) => distance }._2
currentSeats.updated(bestSeat, nextPerson)
}
}
```
] |
[Question]
[
## Introduction
Recently I was trying out one of the more obscure use-cases of a modern smartphone: Calling someone by number. While typing it in, I noticed that some of my phonebook entries were displayed, even though the number I was trying to call was different! After some experiments, I figured out why.
## What it does
Every entry in the phone book is examined like this:
* Split the entry by space into "words".
* Check every word like so:
+ For every digit in the number...
+ Is the character of the word at the current index on the key with the digit at the current number?
* If at least one such word exists, display this entry
## Challenge
Emulate my smartphone's behaviour!
Take the list of names below and a numeric string as input. The format for the phonebook may be chosen freely. Assume the phone number to always match `[0-9]*` and all names to match `[0-9a-zA-Z\s]+`
You can expect entries consisting of ASCII characters with values between 32 and 126 (including both). Your program should handle any length of entry and words within, as well as a list of any size.
Output a filtered list.
Input and output order is not relevant.
Use the following phone keyboard:
```
1 | 2 | 3
| abc | def
-----------------
4 | 5 | 6
ghi | jkl | mno
-----------------
7 | 8 | 9
pqr | tuv | wxy
s | | z
-----------------
| 0 |
| |
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins
* No standard loopholes
## Phone Book, values comma-seperated.
`noodle9, Kevin Cruijssen, Arnauld, RGS, xnor, Bubbler, J42161217, Neil, petStorm, fireflame241, Dennis, Martin Ender, Leaky Nun, Lyxal, HighlyRadioactive, Dingus, math, Beefster, Razetime, my pronoun is monicareinstate, Dom Hastings, Dion`
## Test cases
```
Input: 0815
Output: []
Input: 731
Output: []
Input: 532596
Output: []
Input: 53259
Output: [Leaky Nun]
Input: 542
Output: [J42161217]
Input: 27
Output: [Kevin Cruijssen, Arnauld]
Input: 36
Output: [Martin Ender, Dom Hastings]
Input: 6
Output; [noodle9, Neil, Martin Ender, math, my pronoun is monicareinstate, Leaky Nun]
Input: 3
Output; [Dennis, Martin Ender, fireflame241, Dingus, Dion, Dom Hastings]
```
```
[Answer]
# JavaScript (ES6), 102 bytes
Expects `(book)(digits)`, where `book` is an array of strings and `digits` is an array of integers. Returns an array of strings.
```
b=>a=>b.filter(s=>eval(`/\\b[${a.map(i=>i+"01adgjmptw"[i]+"-"+"01cfilosvz"[i]).join`][`}]/i`).test(s))
```
[Try it online!](https://tio.run/##jZJNb5wwEIbv@ytGqAdQJmwhm6RRxUr9UqM2zWFzJEhrwJDZGBvZhmZT9bdvjai22SZU5YSseZ6xZ94N65kpNLX2WKqS76pklydLlizzsCJhufZNsuQ9E/56fnubp69@sLBhrU/Jko681xEr603T2u9eStmRd@wNZ4Ujlekfh7Mg3CiS6yxd/8zmtA5Cy431TRDscqXuIZkBeFKpUvALhK@8JwkfdEcbY7hEeKcl60SJsPp8g/AglUZ43@W54O7nyyKOzqI4Oke45iQQWm5vrNINQkWaV4I1PF5ECB@5lGQQvjFtnf@TLAf8irP7LVx3rs3V9oE5/pLqO7FdsZIUKyz13KEk686hDbN3rjXnlbEDvGKP3FLjKpottFpJ1UkgA42SVDDNSRrL7CBQDVwy4/rWZtAp6bknh6YVZH0PwQvezmaFkkYJHgpV@5U/DCbw0ze4wCgLAhi/@RzS7OXKUzzBGE/xAs@G@v@pHL1D5X4Mk8gC48Nr7Ac/gcR4/gcYkanNThhOxpc8NRwu7@lYJxwHhtGxD9qYl0PluOJ/rnPqts87vRy5v2L5O1vPI5LtfgE "JavaScript (Node.js) – Try It Online")
### How?
The sequence of digits is turned into a regular expression of the form:
```
/\b[Dx-y][Dx-y]...[Dx-y]/i
```
where `D` is the original digit and `x-y` is the letter range associated to it, or `D-D` for `0` or `1`.
For instance, `[2,7]` becomes `/\b[2a-c][7p-s]/i`.
We walk through the phone book and keep only the names that are matched by this regular expression.
### Commented
```
b => a => // b[] = book, a[] = integer sequence
b.filter(s => // for each string s in b[]:
eval( // evaluate as JS code:
"/\\b" + // regexp delimiter, followed by \b
"[" + // followed by the first '['
a.map(i => // for each integer i in a[]:
i + // append i
"01adgjmptw"[i] // append the first range character
+ "-" + // append a '-'
"01cfilosvz"[i] // append the second range character
).join`][` + // end of map(); join with ']['
"]/i" // append the last ']' and '/i'
) // end of eval()
.test(s) // keep s if it's matching the above regular expression
) // end of filter()
```
[Answer]
# [Python 3](https://docs.python.org/3/), 96 bytes
```
lambda n,p:[s for s in p if' '+n in''.join([i,'%i'%min(ord(i)%32/3.2+2,9)][i>'9']for i in' '+s)]
```
[Try it online!](https://tio.run/##PZFLT8MwDMfvfApfpqyiGjTdGEMCiZdAvA7jOHZIqbsZGqdKUkT58iPJEJf47yT@@dUNfmu43DXnb7tW6apWwHl3tnLQGAsOiKEDagSIQw6OEJMPQzxeUS5GJEY6aGPrMWWjUh6VE3ko80W2XtGFWIh1RFCMCtEuW@@6kAorYz7hHFaCjalbXIgcxCN@hUTXtqcP55Dj1aVl1bd1lMu712i@2dhor/qqajHJh6ksTgpZzKPzgtRG26F/9cbqqBuy2IS@UE6L6N8gM7monpX1Iect13vUE6rPAV76lPxp@FaJdU@bbTssVU1GvXv6wgQh3vQJopXfppIQG@f3oKX6QU86/dQDdNaw6cPsHGjD9K4sEjuv/B5lNNwrFyrZuD3asFgfcK8rtA4gDer4tJjFx3mZepiVcrY4@VdJTGU0Ms2hTG/pKAMrLiGuDv6gZwcQiiL242bMOfzvJMt2vw "Python 3 – Try It Online")
[Also works in Python 2](https://tio.run/##PZFLT8MwDMfvfApfpqyiGjTdGEMCiZdAvA7jOHZIqbsZGqdKUkT58iPJEJf47yT@@dUNfmtY7przt12rdFUr4Lw7WzlojAUHxNABNQLEIQdHiMmHIR6vKBcjEiMdtLH1mLJRKY/KiTyU@SJbr@hCLMQ6IihGhWiXrXddSIWVMZ9wDivBxtQtLkQO4hG/QqJr29OHc8jx6tKy6ts6yuXdazTfbGy0V31VtZjkw1QWJ4Us5tF5QWqj7dC/emN11A1ZbEJfKKdF9G@QmVxUz8r6kPOW6z3qCdXnAC99Sv40fKvEuqfNth2Wqiaj3j19YYIQb/oE0cpvU0mIjfN70FL9oCedfuoBOmvY9GF2DrRhelcWiZ1Xfo8yGu6VC5Vs3B5tWKwPuNcVWgeQBnV8Wszi47xMPcxKOVuc/KskpjIameZQprd0lIEVlxBXB3/QswMIRRH7cTPmHP53kmW7Xw "Python 2 – Try It Online")
`ord(i)%32` converts both upper and lower case characters to the range `(1,2,3,...,24,25,26)`. Division by `3.2` converts this list to `00011122233344455556667778`. Adding `2` to the list and using `min` to convert the last digit into `9`, completes the character mapping `22233344455566677778889999`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ ~~28~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
íl1√∫A9L¬¶3–∏79¬™S{‚İI1√∫√•
```
-8 bytes by porting [*@SurculoseSputum*'s Python 2 answer](https://codegolf.stackexchange.com/a/210374/52210), so make sure to upvote him as well!
First input is the list of contacts, second is the integer.
[Try it online](https://tio.run/##JY49TsNAEIV7TrFyTWMTYbkMPyKASWGXiGISj52B3dlodx3F0HAGbkABBSdAlElHlTNwEeNdV@/N0@h7T1tYEPb975uM9z/TLN99nhy@02z3Vb78vb5fD@H@o@/vI9a6kphFxyK6xQ2xODctPVqL7KOpYWhl5W1xVXrZsjZez9rFQmKwN5MkPo2TOPXHHEl6XaMrnTbK@5oM1hIUJpPY3xfITNa7OzBu6LzkakTlCE@dmLehPO@2EFgzalayK6AiDUtHGwwQ4qYNEAVuFSYh1taNoAKe0ZEKn6oTa6NZtyzICqWZlmCQ2DpwI0orMQM7LGnsiNYcPRwl6T8) or [verify all test cases](https://tio.run/##JY69TgJBFIV7n2Ky9TT7w@JWBH8iUaSAxMQQioG9wOjMHTIzS1iNiZUPwBtYaKKFtbFcOiufgRdZmdnqnHty852jDJtyqG/WZScg@5ctCTpl9XFb/25FuPvpZv3qPf77bmfV5@hx//xafR3S3Vv9ROtxgErlArKAkuAK1hzJqS74nTGALupqZIXInR1ejJxsUGmnJ8V0KsDbyyQK0zAK2@4YABdOV2BHVmnp/JxrmAsmIUpCd58BIjfOXTNtD53nmDeoPrD7kgwKX94vN8yzenyxFOWQ5VyxmeVr8BCOi8JDJLNLPwlgbmwDGrIHsFz6T1mSlVaoCiTcEKmQz5gGjsYy26CUJD1mDksWpkErDCZH4@MkpK04amVpI7SVRDRq0zilKY0n/w).
**Original ~~34~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
íl√∞¬°ŒµUŒµA‚Ä¢√ä_¬¢‚Ä¢6–≤<¬£y√®¬´XN√®√•}P}√†
```
First input is the list of contacts, second is the integer.
[Try it online](https://tio.run/##JY5NSgNBEIX3nqKZtZsZJEFwE38waAySIAgiUslUktLu6tDdEzJCwLVLT6ARIeBGhFxgZucieAYvMqZ7Vu@9ovje0xYGhFX18yLLr@Jts77arFt/T8vy@a5YbrXx@31QvOflqvi87par8mNxuShfq@omYq1TifvRrojOcUYsjkxG99Yi@1PLMGQy9bZ32vcyZ228HmaDgcRgz/aSuBEncdOHLpL0OkXXd9oo70dkcCRBYbIX@3yMzGS9uwDjtp0nnNaoDsJDLrpZKO/kcwisNo0nMu9BShqGjmYYIMTjLEAUuEmYhDiyrgb14BEdqfCpcjE1mnXGgqxQmmkIBomtA1ejtBJtsNslY1ujNUe3O0nzHw) (the test case that results in my own name, I'm honored ^-^) or [verify all test cases](https://tio.run/##JY7fSgJBFIfve4phr@dm13VNCML@kJRJKEUhEqN71KnZGZmZFTcQuuqiS5@gjMAIIgJfYPeuC@kZfJHNmb36fudw@M5PKNKjkF9Nkn0HbZ7myNlP0o@b/HfOsu/0db26TL/Wq9rmcZE936aLLYO/n730LcmW6ed1M1tm77OLWfaSz3DecbgQIYOqg5FzBhPK0aGM6Z1SwM2qJjmJWWhi66RtMOVCGh7EvR4DG099zw1cz62YoQmUGY5Bt7WQkckDKmHASASe75r5CDinyqRzIvX25zEPC1UDyH2CmrF93kimxLrqdDhiSYuEVJC@phOwEsqHsZVERI9sJYCB0oWoRR5A08heRgkaS8FFzBFVKBKc9okEypUmulCJCNWJ2jYZqkItuNPd6ez6Li6XvHI1KIDLvoe9Ci4FOMCl7j8).
**Explanation:**
```
í # Filter the (implicit) input-list of contacts by:
l # Convert the name to lowercase
1√∫ # Pad the string with a single leading space
A # Push the lowercase alphabet
9L # Push a list in the range [1,9]
¦ # Remove the first item to make the range [2,9]
3–∏ # Repeat the list 3 times: [1,2,3,4,5,6,7,8,9,1,2,3,...,9]
79ª # Append 79 to the list: [2,3,4,5,6,7,8,9,2,3,4,...,9,79]
S # Convert the list to a flattened list of digits:
# [2,3,4,5,6,7,8,9,2,3,4,...,9,7,9]
{ # Sort the list: [2,2,2,3,3,3,...,8,8,8,9,9,9,9]
‡ # Transliterate the alphabet to these digits in the contact-string
I # Push the second input-integer
1√∫ # Pad it with a single leading space as well
å # And check if it's a substring of the transliterated contact-string
# (after which the filtered list of contacts is output implicitly)
```
```
í # Filter the (implicit) input-list of contacts by:
l # Convert the name to lowercase
ð¡ # Split it on spaces to a list of words
# (NOTE: `#` can't be used here, because it won't result in a list for
# strings without spaces)
ε # Map each word to:
U # Pop the word and store it in variable `X`
ε # Map the digits of the (implicit) input-integer to:
A # Push the lowercase alphabet
•Ê_¢• # Push compressed integer 13101041
6–≤ # Convert it to base-6 as list: [1,1,4,4,4,4,4,5,4,5]
< # Decrease each by 1: [0,0,3,3,3,3,3,4,3,4]
£ # Split the alphabet into parts of that size:
# ["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
yè # Index the current digit into this list
¬´ # Append the string to the current digit
X # Push the current word `X`
Nè # Index the map-index into it
å # Check if this character is in the string (i.e. "abc2" and "c" → 1)
}P # After the map: check if all digits were truthy
}à # After the map: check if this was truthy for any word
# (after which the filtered list of contacts is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•Ê_¢•` is `13101041` and `•Ê_¢•6в` is `[1,1,4,4,4,4,4,5,4,5]`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~129 111~~ 108 bytes
```
lambda n,S:[s for s in S if" "+n in"".join([`(ord(c)+(c<"S")-(c>"Y"))/3-20`,c][c<"A"]for c in" "+s.upper())]
```
[Try it online!](https://tio.run/##fVLfb9owEH7PX3HKC4lq2BJou6KB1K3Tqq3rAzxNDK0muYC7xLZsh5L98@xMoIvaaQ@R7fP34@5zdOM2Sqb7YvJjX/JqlXOQbD5eWCiUAQtCwhxEEUJ4JukQhoNHJWS0eIiUyaMsPouy9@E8jPtRNg2/h3H8ZthP3z6wbLmgi@tw6WUyzyQFO6i1RhPF8XIveYUWJlBxHVlnBvQJzcDwp59C6tpF8cDqUrgoZKQaPG1EiZCMA3CmGUMpJBK5gw4AdxlqN4aVQf4rAE1zIaOqxsxh/trKa5w8@lNv0gVbZWgT4ZaX0ansIQEYtHXpCFJER4/DLHSnjZDuxGxh8WRyYrMjcy@Vyku8YvAVt5TvR1OLR2tRMrg2ktclIWef5wx2UhkGH@rVqkTafBmlyUWSJpcM7lGUDDS6uVOmYlAIgwU9H6ajhMENSiksg2/cONL/JHNPv6NUGrivyeau2XHi34r1pmxmPBeKZ05saZIbIdc1USvuNmSNWFjnyTP@G52oCFE1NKaSqqbfwUKlpMi4QSGt484LqApuuSXftfVySgbvRgn0p7BYBufD9Pzqons47HvPrfWoPErb4vO4VEwv29qLwHoMesfICDRslXvdsT2i2xLBjqjjI3iAT9OvL4l/26KDT@Sw/m9@30Ur332RQxOHN/mXSxv5q0YPN4oS@QM "Python 2 – Try It Online")
A function that takes in a phone number string and a list of names, and returns the list of matched names.
For each name, converts it to its digit string equivalent, then returns the name if the phone number is found inside that name's digit string.
To make sure that the phone number only matches the start of a word in name, before matching, a space is prepended in front of the phone number and the name.
Example:
```
name : "Kevin Cruijssen" -> " 53846 278457736" (notice the space at the start)
phone: "27" -> " 27"
" 27" in " 53846 278457736" -> True
```
[Answer]
# [R](https://www.r-project.org/), ~~103~~ 102 bytes
*Edit: -1 byte by prepending `0` (zero followed by space) to the contact name, instead of just (space), since the zero without a preceding space can itself never be matched*
```
function(n,l,`~`=toString)l[grepl(paste("",n),chartr(~letters,~c(7:31%/%3.13,9),paste(0,tolower(l))))]
```
[Try it online!](https://tio.run/##fZFNa4NAEIbv/RUiBBSWNmoSm0IO/aKhTXNIjqU0Gx3jNuuMrGsae8hft65CCQW7l5nZd3hm511VJwLjj4hQ80jP6qTESAtCB5lkm9NmpmmtlcCdK992CnLp5LzQ4Ng2Q5dFKVdaOScJWoMq2ClywpvAG1wNgksvYFOXdd1DpknSFyhHus15r/OUELZE@1nk2EgUS5jazLJf4CDQulel@CwKQHN1q5CXMjbp6mltwhFJmXhXbrcS2vR55HsTz/dCUyxBSBNz0GtNKjN5IhQkkmfgjzxTPwCiKEz22qzQzHzEuEMtgO8ra1m2wxfVkbesudilslrxWFDjkzhAC2l8KVtIxnXaPgkgaRZuQSv@DVpkbWdWWbkipBItUVgZoYi4AoGF5rpDUWbNG68aYtGhCW334vxznOG1N2a/zv0Rw8Dr1caBP55O/pf71ZHfq/lhrxT0z@tXgjOl/gE "R – Try It Online")
Same approach as Surculose Sputum's answer: convert phonebook to space-separated numbers & search for match.
**Commented code:**
```
find_contact=
function(n,l # n=number, l=list of contacts
,`~`=toString) # ~=alias to toString function
l[ # return all entries in the list of contacts...
grepl( # ...for which there is a match for...
paste("",n), # ...the number with prepended space...
chartr( # ...in the list made by swapping all...
~letters, # ...lowercase letters for...
~c(7:31%/%3.13,9), # ...digits from 2 to 9 in groups of 3 (or 4 for 7 and 9)...
paste("",tolower(l)) # ...in the lowercase list of contacts with prepended spaces
))]
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 72 bytes
```
~(1G`
.
[$&$&-$&]
T`2-9`a\dgjm\pt\w`.-
T`2-9`cfi\l\os\vz`-.
^
Gi`(?<=\W)
```
[Try it online!](https://tio.run/##LY9BT8JAEIXv8yv2QAgeStKGYEg0RsRAFDkAiQdX04FOy@DuLNndIuXgX689eH3J9773PEUWTNv2d5DOcxjCR6/f6ye9/ids8yyZ5KiL6mj1KeqffJj8h/uStdEu6PM1T4bwBXPOBw939/r9pm3HIM4VhibwSmcW9eRrPoZAAo9esDYFrOcbuIjzMK13O0MeXkZZOk6z9BZWxAZOFDfReQsleyoNWspGKcxIhAO8oe8mq2cpOnBJ@N2oVS2wbC5oYMHVwTRrLNjhPvKZYMZS1QEsxgNMicoQO2yN1@63JbCNOnknrhbFQVknvEdPLCFi7Fhn1QJDp6tCV@TkDw "Retina – Try It Online") Another port of @Arnauld's answer. Takes the first line as the digits and the remaining lines as the phone book. Explanation:
```
~(
```
Execute the rest of the program, then use the output as a program and execute that on the original input.
```
1G`
```
Keep only the line with the digits.
```
.
[$&$&-$&]
```
Turn each digit into a character class.
```
T`2-9`a\dgjm\pt\w`.-
T`2-9`cfi\l\os\vz`-.
```
Adjust the first and last characters of the range to the appropriate letters.
```
^
Gi`(?<=\W)
```
Prefix a Retina instruction to keep only lines matching those characters (case insensitively) when prefixed by a non-letter (therefore excluding the line of digits).
The result of the inner script looks something like this:
```
Gi`(?<=\W)[6m-o]
```
This is a Retina program to keep lines that match any of the characters `6mno` after a non-word character. Note that I can't include the non-word character in the match as that would cause the previous line to be included if the newline is the character in question.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
≈íl>‚±Æ‚Äú¬ÆK¬ø Ç‚ÅπFD¬ªSo‚Å∏V‚Ǩ∆§ƒã
ḲçƇ¥Ƈ
```
A dyadic Link accepting a list of the names on the left and a list of digits on the right which yields a list of names.
**[Try it online!](https://tio.run/##JY4xTwJBFIR7f8V219DchUhsTFRUIkhxJCaGUCzcAxZ335LdPcJZCQ2FnbWlhoaQaIWxMDmUwn/h/ZGT3atm5uXlmxkB50me/zzx4@xtnT08p@t6@vU7z2YfF9X0syWz2eYmm692L9@PB3@b9@1yt0hfd4t8u7zN87aHUkYcjrwS8eowYUjOVMxGWgPa04lCGvPI2vCyZWWKUlk9jbtdDs5elQP/0A/8ig1NYNzqGEzLSCWs7zMFfU4FBGXf5iogMm3dNVVm33mOUYFqAL1LSDN25Y1kSh2rxgZDnoQ0YpL2DJuAgzAcxA4iqBm6SQB9bQpQSO/BMOE@RULGSqKMkTBNhETWowoYakNNgZKC1KjeLxnoAi3R6@TtoEQqnX8 "Jelly – Try It Online")** (Footer formats the list, which when run as a full program gets implicitly smashed)
### How?
```
≈íl>‚±Æ‚Äú¬ÆK¬ø Ç‚ÅπFD¬ªSo‚Å∏V‚Ǩ∆§ƒã - Link 1: list of characters, word; list of integers, key-digits
Œl - lower-case
‚Äú¬ÆK¬ø Ç‚ÅπFD¬ª - compressed string "AAcfilosv" ("AA"+"c"+"filos"+"v")
Ɱ - map with: [ ...mmm filos :D ]
> - greater than?
S - sum
⁸ - chain's left argument, word
o - OR (vectorises) - i.e. replace 0s with word's digit characters
∆§ - for prefixes:
V€ - evaluate each as Jelly - i.e. cast any chars to ints
ċ - count (occurrence of key-digits) -> 1 if a prefix, else 0
ḲçƇ¥Ƈ - Main Link: list of lists of characters, names; list of integers, key-digits
Ƈ - filter keep (names) for which:
¥ - last two links as a dyad - i.e. f(name, key-digits):
·∏≤ - split (name) at spaces
Ƈ - filter keep (words) for which:
ç - call last Link (1) as a dyad - i.e. g(word, key-digits)
```
[Answer]
# Java 8, 172 bytes
```
C->n->C.filter(c->{var s="(?i)";for(int i:n)s+="["+"01adgjmptw".charAt(i)+"-"+"01cfilosvz".charAt(i)+i+"]";var r=0>1;for(var w:c.split(" "))r|=w.matches(s+".*");return r;})
```
Port of [*@Arnauld*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/210263/52210), so make sure to upvote him as well!
[Try it online.](https://tio.run/##fVLBUtswEL3zFRqdrGajwSFASYg7ENoyLXAIx0wOwpYTBXnlkeQEk@bbU9lJCzN0erB25bf7pPe0S7ES3WX2vEu1cI7cC4WbI0KcF16lZBlQXnmleV5h6pVB/u2QXL5hzlspCv7YhssQFM4T@G@zQj@dvS/5J0eSkJyMduNugt1kzHOlvbRR2k02K2GJG9Hoi2J0mBsbBUKiBshcZ0SntEOPY5HNl0Xp15SnC2GvfKRYh3ZbKA1Mxq1e30OqQ2d02PDa0XESt6TNbj1IuSu18hEllDH7a7TmhfDpQrrIdSj/RNnQSl9ZJHa4ZbvhUbCvrJ50sO/g4sqojBTB2WivazojgjUuE/L3x5iMCEVjMi0v4KdcKSRjW6mlcxLhyqKodAaT74/wgsbCdfX0pKWFH/1efBb34nN4kEpDKf2jN7aAXFmZa1HIXj@GG4moHNwL6wPrV8xC450UzzV5qBDu6heh4VbNF7qeiEwZEV5oJeEm3KtyEKQu4FrK3AXrYSJepVeFhKImpTVoKiTKkcKgSoWVChvFodcU5Fa4cNzcBSKD9I@FENxqhR/eLCjHAco1afPpbLP5DH2It7A5hRPowSlcwNn7XZv3oRdiD87DetLizXey3bKWO9hah@sW3FSel8FgrzF6G7Ura0XtuDd78yMMczEgtJNzUZa6/li5n81ozNihAhlPjdYy9dGHCR7vAWMdXxqFzQGNatbq3h5td78B)
**Explanation:**
```
C->n-> // Method with String-Stream & Integer-array parameters and String-Stream return-type
C.filter(c->{ // Filter the input String-Stream by:
var s="(?i)"; // Create a regex-String, starting at "(?i)"
for(int i:n) // Loop over each digit of the input integer-array:
s+= // Append the following to the regex-String:
"[" // An opening square bracket
+"01adgjmptw".charAt(i)
// Appended with the `i`'th character of "01adgjmptw"
+"-" // Appended with a "-"
+"01cfilosvz".charAt(i)
// Appended with the `i`'th character of "01cfilosvz"
+i // Appended with digit `i` itself
+"]"; // Appended with a closing square bracket
var r=0>1; // Boolean `r`, starting at false
for(var w:c.split(" "))
// Split the current String by spaces, and loop over each word:
r|= // Change the boolean to true if the following is true:
w.matches( // Check if the current word regex-matches:
s // The regex-String we created earlier
+".*"); // Appended with ".*"
return r;}) // After the loop, return this boolean `r` to filter on
```
**Regex explanation:**
The [`String#matches`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#matches(java.lang.String)) method in Java implicitly adds a leading `^` and trailing `$` to match the entire String.
```
I.e. input [5,4,2] would result in the following regex:
^(?i)[a-c2][p-s7].*$
^ $ # Match the entire string
(?i) # Match case-insensitive
[a-c # A character in the range a-c (thus in "abc")
2] # or a 2 (thus in "abc2")
[p-s # Followed by a character in the range p-s (thus in "pqrs")
7] # or a 7 (thus in "pqrs7")
.* # Followed by any amount of optional trailing characters
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~242~~ ~~239~~ 237 bytes
```
def f(b,n,k=[]):
x=[[k for k in j]for j in'0 1 abc2 def3 ghi4 jkl5 mno6 pqrs7 tuv8 wxyz9'.split()]
for i in n:k=k and[p+j for p in k for j in x[i]]or x[i]
return[u for u in b if sum(j==r[:len(j)]for j in k for r in u.lower().split())]
```
[Try it online!](https://tio.run/##TZLJbtswEIbveoq5UWrZoFpsxwZUoBsatGkOzlHQgbIom1qGKhdHysu7ItUWPZD/PzPkNwOC42wuEtPbreYNNGFFkXZ5UUaHAKa8KDpopIIOBEJbOtsulryHGFh1SmC5lML5IjJou34DA8otjL@U3oGx13t4mebXPbnTYy9MGJWBhwkHw0OXd8CwLsa3rU@PLr22cz1gKkRZLoHTABQ3VmFhfd26egWiAW2HsM1zVRx6jmEb/RvxD0k5a@96@cJVGP0dJCpvFeRQEJSy7vmeUCA/@HU5@llZ0WrN0aU@KmS2r509fnt2MqFUTj/Zquq5t9@zJN7GSbxzwRMXvdORm2cj1eB8IxRvejbwJItd/IUjCu3cT6bM0vMr1ivqkbNuhifrmz/OE/OsB3G@9POR1UKykxFX7iECz9ZDBmYufiTOG21W0JG9ciMGf3KYYVQSpUUQGgaJ4sQUF6gNMytKDvDA9DLJWa9oiaQMAvd86J6vuKcZjUtabGhKE7qhe7r9P/I@o8miCd0te@rrbqXl8o1GJdCEb5ASePcBCPWfLKKajzkh0e03 "Python 3 – Try It Online")
Explanation: Computes all possible strings that can be formed with the number and checks if any word in a name starts with any of those strings.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~43~~ 42 bytes
```
SθWS⊞υιΦυ№E⪪↥ι ⭆✂λ⁰Lθ¹⎇№ανΣE CFILOSV›νπνθ
```
[Try it online!](https://tio.run/##TU/LbttADLzzKwifVoAKREaQosipsZtH66SB3ebOyLTFdsVV9uFG/XmVSi49cAAOhjOctqPYBvLTdKdDybscRY/upbqEP514Rvc/XVX4WFLnSo1iikcjs7sWnznO3CoU2@9pcLvBS3Y/h4FjS4mdVDUucGH47vSm8dKy8zWe1bhhPebOYmtsbH5wVIqjezekGnW@LP2b9wJxdX23@b57WtR4E5nmdK1xqKpqVs74Yng5TRegIew9f4JvfBLFVSzyKyVW@GwBxe9he7ODVw0Rrsrzs@cIX8@XzUWzbD7CA4uHga17iD0cJPLBU8/L8wbWrCoJ7ilmc/2iezvcMP0e8aEobMZX8nArx86PW9pLoDbLiWFtxUuCnnIHV8yHZI/Dlv5ylp6hH3GIQa0xSsI@qLQUWTRlKwjr0OMtJYs7JjMKCtOHk/8H "Charcoal – Try It Online") Link is to verbose version of code. Takes input as the number and a newline-terminated list of phone book entries. Edit: Saved 1 byte by copying @JonathanAllan's digit conversion algorithm, which means that I get to use the `p` variable again. Explanation:
```
SθWS⊞υι
```
Input the number and the entries. (These bytes could be removed by substituting a more cumbersome input format.)
```
υ List of phonebook entries
Φ Filtered where
ι Current entry
‚Ü• Uppercased
‚™™ Split on spaces
E Map over words
λ Current word
✂ ⁰Lθ¹ Sliced to input digits length
⭆ Map over characters and join
‚éá Ternary
α Uppercase alphabet
‚Ññ Count of (i.e. contains)
ν Current character
CFILOSV Literal string ` CFILOSV`
E Map over characters
ν Word character
› Is greater than
π Inner character
Σ Take the sum
ν Else current character
‚Ññ Count of (i.e. contains)
θ Input digits
Implicitly print
```
[Answer]
# [Rust](https://www.rust-lang.org/), ~~158~~ 154 bytes
```
|a,b|b.filter(move|x|x.split(|&b|b<33).any(|w|(0..).zip(a).all(|(j,&i)|j<w.len()&&(b"@CFILOSVZ".iter().fold(1,|a,&b|a+(b<w[j]&95)as u8)==i||48+i==w[j]))))
```
[Try it online!](https://tio.run/##xZJdT9swFIbv8yvOchFscRatH0AJafcBY7AxJhWJi6EKOakDLo4dxQ5tIfz2zgbGNE27mzpLlqzjc97n@LyuG2NXhYKSCUUo3AfgluQWqmuteKb1DQwhVFpPJd9F@MJvhYL9uhEzY7hCeF8r1sgpwvjTGcJC6RrhQ5NlkrvD5363s93pdnYQTrmQCBW3Z1bXJUIhal5IVvJuv4NwwJUSBuErq63T/6imvvyEs5slnDYOc7JcMFd/JK6u5XLMpkKz3Ipb7kqFumpcacnstUNzXhjri8fsjltRuoxyCVWtlW4UCAOlViJnNRfKWGa9gC7hiBnHvTJeTqswNpUUloQIIY1LVpHWtCZm5jJbWm4IpXGupeS5TZL0nOdptOG1RA4XzWAyGhG6FzzO0SVbsmoZZm0WF0K6xkipb3m7aBfPjDZyd2mvR2OmlqSdt@RNHNP4TlSEuZiUpCUzjARtZ@k8ltyZFEUkC9/tHx6ffDs7/x7GwsvSuNBySjroaE6SbZIsnV/MJtHuFmUGmgEdDkXb9gebYjj0F9StFUL04vNjx77zhyBoDAdjp0lipMh5khw7xF7gvol/UbrB3HgT8EHm3EzdoRxGGwz8fhwBwmECh4r8DKDP9XUvGRRej2A8IoXLw1@fLXnS@G2gEwrB07@saqGsVK9IeJ@8fXD2FCS6GGAfOxN8kXiex7Nxi/bpHbZOkqLW5WVjiwFZ0LhR89ol/OHlpffPjeGvvC3sYRe3cBe3/wd1rcw@dtfI6@LOGmm9tfq3Tlbv37MegtUP "Rust – Try It Online")
The code is a bit of a mess, with a sprinkle of `.iter()`, `&` and `move` here and there. The strings are represented as `&[u8]`s, as are the numbers pressed. Rust doesn't have regexes in its standard library, so I manually find the digit for each letter from the array `b"@CFILOSVZ"`. Case insensitivity is performed by bitmasking with `95` which is `0x5f = 0x7f - 0x20`. This transforms the lowercase chars to uppercase.
Some bytes were saved in the edit by switching from `b==32` to `b<33` and using `(0..).zip()` and indexing instead of `w.iter().zip()`.
[Answer]
# Scala, 118 bytes
```
n=>_.filter(_ split " "exists(_.matches("(?i)"+n.map(i=>s"[$i${"01adgjmptw"(i)}-${"01cfilosvz"(i)}]").mkString+".*")))
```
[Try it online](https://scastie.scala-lang.org/E5gkN9QBRGWfRrbNeZMUIg)
A port of [@Arnauld's JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/210263/52210).
A curried lambda of type `Seq[Int]=>Seq[String]=>Seq[String]`.
] |
[Question]
[
# Definition
[Wolstenholme's theorem](https://en.wikipedia.org/wiki/Wolstenholme%27s_theorem) states that:

where `a` and `b` are positive integers and `p` is prime, and the big parentheses thingy is [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient).
# Task
To verify that, you will be given three inputs: `a`, `b`, `p`, where `a` and `b` are positive integers and `p` is prime.
Compute:

where `a` and `b` are positive integers and `p` is prime, and the parentheses thingy is [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient).
# Specs
Since:

where and the parentheses thingy is [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient).
You can assume that `2b <= a`
# Testcases
```
a b p output
6 2 5 240360
3 1 13 3697053
7 3 13 37403621741662802118325
```
[Answer]
# Haskell, ~~73~~ 71 bytes
Due to the recursion, this implementation is very slow. Unfortunately my definition of the binomial coefficient has the same length as `import Math.Combinatorics.Exact.Binomial`.
```
n#k|k<1||k>=n=1|1>0=(n-1)#(k-1)+(n-1)#k --binomial coefficient
f a b p=div((a*p)#(b*p)-a#b)p^3 --given formula
```
An interesting oddity is that Haskell 98 did allow for *arithmetic patterns* which would have shortened the same code to 64 bytes:
```
g a b p=div((a*p)#(b*p)-a#b)p^3
n+1#k|k<1||k>n=1|1>0=n#(k-1)+n#k
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ż×c/I÷S÷²}
```
Expects `a, b` and `p` as command-line arguments.
[Try it online!](http://jelly.tryitonline.net/#code=xbzDl2MvScO3U8O3wrJ9&input=&args=NiwgMg+NQ) or [verify all test cases](http://jelly.tryitonline.net/#code=xbzDl2MvScO3U8O3wrJ9CsOnIg&input=&args=WzYsIDJdLCBbMywgMV0sIFs3LCAzXQ+NSwgMTMsIDEz).
### How it works
```
ż×c/I÷S÷²} Main link. Left argument: a, b. Right argument: p
× Multiply; yield [pa, pb].
ż Zipwith; yield [[a, pa], [b, pb]].
c/ Reduce columns by combinations, yielding [aCb, (pa)C(pb)].
I Increments; yield [(pa)C(pb) - aCb].
÷ Divide; yield [((pa)C(pb) - aCb) ÷ p].
S Sum; yield ((pa)C(pb) - aCb) ÷ p.
²} Square right; yield p².
÷ Divide; yield ((pa)C(pb) - aCb) ÷ p³.
```
[Answer]
# Python 2, ~~114~~ ~~109~~ ~~85~~ 71 bytes
A simple implementation. Golfing suggestions welcome.
**Edit:** -29 bytes thanks to Leaky Nun and -14 bytes thanks to Dennis.
```
lambda a,b,p,f=lambda n,m:m<1or f(n-1,m-1)*n/m:(f(a*p,b*p)-f(a,b))/p**3
```
A simpler, same-length alternative, with thanks to Dennis, is
```
f=lambda n,m:m<1or f(n-1,m-1)*n/m
lambda a,b,p:(f(a*p,b*p)-f(a,b))/p**3
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes
Takes input as:
```
[a, b]
p
```
Code:
```
*`c¹`c-²3m÷
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=KmBjwrlgYy3CsjNtw7c&input=WzYsIDJdCjU).
[Answer]
# R, ~~50~~ 48 bytes
```
function(a,b,p)(choose(a*p,b*p)-choose(a,b))/p^3
```
As straightforward as can be...
Thanks to @Neil for saving 2 bytes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
y*hZ}Xnd2G3^/
```
[**Try it online!**](http://matl.tryitonline.net/#code=eSpoWn1YbmQyRzNeLw&input=WzY7Ml0KNQ)
The last test case doesn't produce an exact integer due to numerical precision. MATL's default data type (`double`) can only handle exact integers up to `2^53`.
### Explanation
```
y % Implicitly input [a; b] (col vector) and p (number). Push another copy of [a; b]
% Stack: [a; b], p, [a; b]
* % Multiply the top two elements from the stack
% Stack: [a; b], [a*p; b*p]
h % Concatenate horizontally
% Stack: [a, a*p; b, b*p]
Z} % Split along first dimension
% Stack: [a, a*p], [b, b*p]
Xn % Vectorize nchoosek
% Stack: [nchoosek(a,b), nchoosek(a*p,b*p)]
d % Consecutive differences of array
% Stack: nchoosek(a,b)-nchoosek(a*p,b*p)
2G % Push second input again
% Stack: nchoosek(a,b)-nchoosek(a*p,b*p), p
3^ % Raise to third power
% Stack: nchoosek(a,b)-nchoosek(a*p,b*p), p^3
/ % Divide top two elements from the stack
% Stack: (nchoosek(a,b)-nchoosek(a*p,b*p))/p^3
% Implicitly display
```
[Answer]
# J, 17 bytes
```
(!/@:*-!/@[)%]^3:
```
## Usage
```
(b,a) ( (!/@:*-!/@[)%]^3: ) p
```
For example:
```
2 6 ( (!/@:*-!/@[)%]^3: ) 5
240360
```
This is just a direct implementation of the formula so far.
*Note*: for the 3rd testcase input numbers must be defined as *extended* (to handle big arithmetic):
```
3x 7x ( (!/@:*-!/@[)%]^3: ) 13x
37403621741662802118325
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 52 bytes
```
tT;T P&t^₃D&h↰₁S&h;Pz×₎ᵐ↰₁;S-;D/
hḟF&⟨{-ḟ}×{tḟ}⟩;F↻/
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vyTEOkQhQK0k7lFTs4taxqO2DY@aGoPVMqwDqg5Pf9TU93DrBIiYdbCutYs@V8bDHfPd1B7NX1GtC2TVHp5eXQKiH81fae32qG23/v//0dHmOgrGsToKhsax/6MA "Brachylog – Try It Online")
Accepts input `[[a, b], p]`.
```
% Predicate 1 - Given [n, r], return binomial(n, r)
hḟF % Compute n!, set as F
&⟨ % Fork:
{-ḟ} % (n - r)!
× % times
{tḟ} % r!
⟩
;F↻ % Prepend n! to that
/ % Divide n! by the product and return
% Predicate 0 (Main)
tT;T P % Set P to the array [p, p]
&t^₃D % Set D as p^3
&h↰₁S % Call predicate 1 on [a, b],
% set S as the result binomial(a, b)
&h;Pz×₎ᵐ % Form array [ap, bp]
↰₁ % Call predicate 1 on that to get binomial(ap, bp)
;S- % Get binomial(ap, bp) - binomial(a, b)
;D/ % Divide that by the denominator term p^3
% Implicit output
```
[Answer]
# Python 3 with [SciPy](https://www.scipy.org/scipylib/index.html), 72 bytes
```
from scipy.special import*
lambda a,b,p:(binom(a*p,b*p)-binom(a,b))/p**3
```
An anonymous function that takes input via argument and returns the result.
There's not a lot going on here; this is a direct implementation of the desired computation.
[Try it on Ideone](https://ideone.com/50ytXo) (the result is returned in exponential notation for the last test case)
[Answer]
# [Nim](http://nim-lang.org), ~~85~~ ~~82~~ ~~75~~ 59 bytes
```
import math,future
(a,b,p)=>(binom(a*p,b*p)-binom(a,b))/p^3
```
This is an anonymous procedure; to use it, it must be passed as an argument to another procedure, which prints it. A full program that can be used for testing is given below
```
import math,future
proc test(x: (int, int, int) -> float) =
echo x(3, 1, 13) # substitute in your input or read from STDIN
test((a,b,p)=>(binom(a*p,b*p)-binom(a,b))/p^3)
```
Nim's `math` module's `binom` proc computes the binomial coefficient of its two arguments.
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
```
def f(a,b,p):B=2<<a*p;R=(B+1)**a;print(R**p/B**(p*b)-R/B**b)%B/p**3
```
[Try it online!](https://tio.run/##FcZBCoMwEAXQvadwI8z8jkgSWqHRTY6QGyRoaDd2EDc9fSRv9fR/fX6HrXXbS18oSRbld1jtsiSojyuFh2EgeT2/x0UR0CkApMg8xtbMQ5gUcLXQS6w8uSvkxIhxbbO4tnoD "Python 2 – Try It Online")
Expresses the binomial coefficients arithmetically using [this method](https://codegolf.stackexchange.com/a/169115/20260).
[Answer]
## JavaScript (ES6), 70 bytes
```
(a,b,p,c=(a,b)=>a==b|!b||c(--a,b)+c(a,--b))=>(c(a*p,b*p)-c(a,b))/p/p/p
```
Save 1 byte by using ES7 (`/p**3` instead of `/p/p/p`).
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 18 bytes
```
{(-/!/¨⍺1×⊂⍵)÷⍺*3}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqDV19Rf1DKx717jI8PP1RV9Oj3q2ah7cDuVrGtf//myqkKRgpmAEA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 43 bytes
```
(a,b,p)->((c=binomial)(a*p,b*p)-c(a,b))/p^3
```
[Try it online!](https://tio.run/##HcrBCoMwEATQXxk87cqGoqHtSX9ELGwClkBqF@nBfn2aFObwZhjTI7mnlQ1TIZUgxm4milNI@/uVNDNpbxL6usd2YL7Ywxc1y1864WbYkfZPZddKh6g50yY4mQXLchOMguta7QVDjW@@C/zfK5cf "Pari/GP – Try It Online")
] |
[Question]
[
[Related, but not dupe](https://codegolf.stackexchange.com/q/242935/108879).
## Challenge
A list of integers \$a\_1, a\_2, a\_3, \dots, a\_n\$ (\$ n ≥ 1 \$) is Fibonacci-like if \$a\_i = a\_{i-1} + a\_{i-2}\$ for every \$i > 2\$. Note that every list that contains only 1 or 2 integers is Fibonacci-like.
For example, \$[1]\$, \$[6, 9]\$, \$[6, -4, 2, -2, 0, -2, -2, -4, -6, -10]\$, \$[7, -1, 6, 5, 11, 16, 27]\$ are Fibonacci-like lists.
Your task is, given a list, to determine the minimum amount of numbers that you have to remove from the list to make it Fibonacci-like.
For example, in \$[9, 7, -1, 6, 5, 2, 11, 16, 27]\$, you have to remove 2 numbers at minimum (\$9\$ and \$2\$) to transform the list into \$[7, -1, 6, 5, 11, 16, 27]\$, which is a Fibonacci-like list.
## Input/Output
Input/output can be taken in any reasonable format, taking a list of numbers and returning the minimum number to complete the task.
Testcases:
```
[1, 2] -> 0
[5, 4, 9, 2] -> 1
[9, 7, -1, 6, 5, 2, 11, 16, 27] -> 2
[9, 9, 9, 9, 7, 9, 9, 9, 9, -1, 6, 5, 2, 11, 16, 27] -> 9
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) wins!
[Answer]
# JavaScript (ES6), 63 bytes
```
f=([v,...a],x,y)=>1/v?Math.min(v-x-y?1/0:f(a,y,v),1+f(a,x,y)):0
```
[Try it online!](https://tio.run/##fYxBDoIwFET3nqLLNv4WfqM2kCAn8ASERYOgEGyNkIaevpaNMYaYzGJm/ps/aKen5tU/Z27stQ2hK2jlQAiha1jAs@KMiSsver6LR2@o4wv3JSZp3lENHhwD3K92ZVmehsaayY6tGO2NdrRCILJmbPdTH4EcgGTbx1grIDxOT0AiKYFgDBiTVNv8R@rLZ/@ehDc "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
[v, // v = next value from the input array
...a], // a[] = all remaining values
x, // x = penultimate value, initially undefined
y // y = previous value, initially undefined
) => //
1 / v ? // if v is defined:
Math.min( // return the minimum of:
v - x - y ? // 1) if both x and y are defined and v is not
// equal to x + y:
1 / 0 // force this one to fail by using +infinity
: // else:
f(a, y, v), // do a recursive call where v is used
1 + // 2) increment the final result
f(a, x, y) // and do a recursive call where v is removed
) // end of Math.min()
: // else:
0 // stop the recursion
```
[Answer]
# [R](https://www.r-project.org), ~~90~~ 88 bytes
*Edit: -2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).*
```
\(v)max(which(sapply(sum(v|1):1,\(i)all(combn(v,i,\(x)any(diff(x)[-1]-head(x,-2)))))),0)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RYzBCoJAEIbvPcVAl1mYBXepzKDeoVuQHTZtcUFNMk2hN-liQQ_V2zSp0Fxm_m8-_sfz0r3s-l1drVx-diHWIjMN3hIXJViaokhbLKsM67sSK0UhOmHSFKNzdsyxJsekESZvMXbW8rmX6iCTk4mxIalFP-SJsX9rMUJFwI8pyA14kx-YE8wIgj9WPWbgE0jWFwTsaALFQXHS_mjqobjrhv0F)
Checking Fibonacci-likeness borrowed from [@Dominic van Essen's answer to related challenge](https://codegolf.stackexchange.com/a/242953/55372).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 36 bytes
```
#g-MX#*:S H@>_-_=H H_FIFL*CP:GMZgMlg
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLG51bGwsIiNnLU1YIyo6UyBIQD5fLV89SCBIX0ZJRkwqQ1A6R01aZ01sZyIsIiIsIjYgLTQgMiAtMiAwIC0yIC0yIC00IC02IDEwIiwiLXAiXQ==) -6 thanks to DLosc.
```
#g # Length of input
- # Minus
MX # Maximum of
#*: # Map length over
FL* # Flatten each of...
CP: # Cartesian product of...
MZ # Map over zipped
gMl # Input filled with empty lists
g # And input...
G # Get all arguments (i.e. both)
FI # Filter by...
S H # Remove first and last items from
- # Differences of
@>_ _ # Shifted value and value
= # Equal to...
H H_ # Remove last two items from value?
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes
```
ẏṗ'?ẏ⊍?$İ₌ÞS¯Ḣc;ÞgL
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo/huZcnP+G6j+KKjT8kxLDigozDnlPCr+G4omM7w55nTCIsIiIsIlsxXSJd)
Long, clunky, and likely to be outgolfed, but it's 1:01am so whatever lol.
Gets all lists of indices where removing the items at those positions gives a Fibonacci list and then gets the length of the smallest indice list.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~31~~ 30 bytes [SBCS](https://github.com/abrudz/SBCS)
```
≢⌊.-∘∊2(≢⍤⊢×∘⊃↓⍷+/∘,)¨¨(⊢,,¨)\
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9S56FFPl57uo44Zjzq6jDQeAfm9Sx51LTo8HSTU1fyobfKj3u3a@kCejuahFYdWaAAldXQOrdCMAQA&f=HYrBFQAQDMXupsgKvygW6np2MJlyy0sSCCtBp7E@LQZnC09nSMixkUFvpaaeFw&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
`(⊢,,¨)\` gets all non-empty subsequences of the input (taken from [Bubbler's tip](https://codegolf.stackexchange.com/a/211449/64121)).
`2(≢⍤⊢×∘⊃↓⍷+/∘,)x` If x is Fibonacci-like, this returns the length of x, otherwise 0.
`≢⌊.-∘∊x` computes the minimum value of `length of input - some number in x`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒP+⁼ƭ3\Ạ$ƇṪLạL
```
A monadic Link that accepts the list of integers and yields the count of elements to remove.
**[Try it online!](https://tio.run/##ATQAy/9qZWxsef//xZJQK@KBvMatM1zhuqAkxofhuapM4bqhTP///1sxLCAzLCA2LCAxMiwgMjRd "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opADtR417jq01jnm4a4HKsfaHO1f5PNy10Of/4fZHTWv@/4@ONtRRMIrl0ok21VEw0VGwhPKAtLmOgi5Q0kxHAShlpKNgCOQYAnlG5iAFIGwBIkCiYHljsEILINcYIY5PCmwEWBhmkDHYOkOgDiOTWK5YAA "Jelly – Try It Online").
### How?
```
ŒP+⁼ƭ3\Ạ$ƇṪLạL - Link: list of integers, A
ŒP - powerset of A -> all subsequences (Note: shortest to longest)
Ƈ - filter keep those for which:
$ - last two links as a monad:
3\ - three-wise overlapping reduction by:
ƭ - alternate between these two links:
+ - add -> first plus second element of the three-slice
⁼ - equals -> does that result equal the third element?
Ạ - all truthy?
Ṫ - tail -> (one of) the longest one(s)
L - length
L - length of A
ạ - absolute difference
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 51 bytes
```
saJ2.-{jR@f{L[2.>}f{J2CO)++~]j[-[-==}[~L[.-}{0it}IE
```
[Try it online!](https://tio.run/##NYxBC4JAEIXv/orBWzgj7lhZiBJEh0QIunQY9mCgkHhJ87Ssf31bjG7vve/jPedxaKf33DoTUhnmOemxcVNTcUymv586UwvHpe1MxefbJooW3QsJFYWVpZaYrEleH3u9OPsYnCgE1kAlJIHsELYIx/@iAvE5QyAv7RE8ZgTli/KNs1XiYL1ASFfh4GH6@/sC "Burlesque – Try It Online")
```
sa # Non-destructive length
J # Dup
2.- # Longer than 2
{
j # Reorder stack
R@ # All subsequences
f{ # Filter
L[ # Length
2.> # >2
}
f{
J # Dup
2CO # Pairwise 2s
)++ # Map sum
~] # Drop last
j # Reorder stack
[-[- # Drop first twice
== # Are equal
}
[~ # Last
L[ # Length
.- # Difference with original
}
{
0it # Return 0
}IE # If else
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
æʒD¥¦Å?}ζ‚€gÆ
```
-1 byte thanks to *@ovs*
[Try it online](https://tio.run/##ATkAxv9vc2FiaWX//8OmypJEwqXCpsOFP33OtuKAmuKCrGfDhv//WzksNywtMSw2LDUsMiwxMSwxNiwyN10) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8PLTk1yObT00LLDrfa157Y9apj1qGlN@uG2/zr/o6MNdYxidaJNdUx0LMEsSx1zHV1DHTMdUx0jHUNDHUMzHSNzsDgEmuvAWNhUAVlAASMdYyA0BfONdcxiYwE).
**Explanation:**
```
æ # Get the powerset of the (implicit) input-list
ʒ # Filter to check if it's Fibonacci-like:
D # Duplicate the current list
¥ # Pop one and get its forward differences
¦ # Remove the first item
Å? # Check if the original list starts with this as sublist
}ζ # After the filter: zip/transpose; swapping rows/columns, with " "
# as implicit default filler for unequal length lists
‚ # Pair the (implicit) input-list with this matrix
€g # Get the length of both
Æ # Reduce by subtracting
# (which is output implicitly as result)
```
Because we only care about the length, the zip/transpose with filler is used to our advantage to get the length of the longest truthy result of the filter (thanks to *@ovs*).
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü∞♀ÇjäεîVÖ₧"╥←
```
[Run and debug it](https://staxlang.xyz/#p=81ec0c806a84ee8c56999e22d21b&i=%5B1,+2%5D%0A%5B5,+4,+9,+2%5D%0A%5B9,+7,+-1,+6,+5,+2,+11,+16,+27%5D%0A%5B9,+9,+9,+9,+7,+9,+9,+9,+9,+-1,+6,+5,+2,+11,+16,+27%5D&a=1&m=2)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 47 bytes
```
{(#x)-|/{(#x)**/(-2_x)=2_-':x}'(,()){x,x,'y}/x}
```
[Try it online!](https://ngn.codeberg.page/k#eJwdyUEKgCAQRuG9p/ihhY4oMlMpCZ3FnWeYMO+etHrwvV6H25Tim/56n1yUpnRLi7bqtC44oqFBg31m0mlMx4WCyMg4IWAGZ0hZzthxrMf8AcetFBM=)
Wow this is a long one. I tried to emulate APL's `(⊢,,¨)\` with `(,()){x,x,'y}/`. Actually the whole code is almost a port of ovs's answer into ngn/k.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 81 bytes
```
[ dup all-subsets [ dup differences rest head? ] find-last nip [ length ] bi@ - ]
```
[Try it online!](https://tio.run/##bY8xDsIwDEX3nuJfoEipgAoYYEMsLIgJdUhbFyLSEGJ3QIizl0ARYsBevt/zYDe6kkvo97vNdj1Hq@U0qi5taZyO2FSMMwVHdjAsWgzLCzNdO3IV8dvABxK5@WCcYJEk9wSx7lDI8PjkCcaY/cwz5EgVplFkUApqiiz/sUPn3/Rv95H0B9Sdh7Y25a5kEsZAatM0FIYTA7HgRLpeokBjXJ1aHYkzPi5bcsf4QYHSrJCi6FvtMeqf "Factor – Try It Online")
] |
[Question]
[
# Setup
Take the following `4x4x4` cube along with a 2D view of 3 of its faces, with a common `1x1x1` cube highlighted:
[](https://i.stack.imgur.com/7HxCJ.jpg)
The arrows represent the points of view that generated the `V1`, `V2` and `V3` faces drawn underneath the big cube.
Given an arrangement of some `1x1x1` cubes inside the main cube we can try and identify it with only three projections. For example, the arrangement below:
[](https://i.stack.imgur.com/r7DAb.jpg)
could be represented as follows:
```
V1
X...
....
....
XXXX
V2
X...
X...
X...
X..X
V3
X...
X...
X...
XXXX
```
However, if we consider only projections on `V1` and `V2`, most of the time we can't identify uniquely the arrangement being considered.(there are arrangements that can't be uniquely identified, even with the 6 projections)
# Task
Given projections on `V1` and `V2`, output the minimum and maximum number of `1x1x1` cubes that an arrangement could have and still produce the projections `V1` and `V2`.
I'll walk you through 2 examples:
## Explained example 1
```
V1
XXXX
....
....
....
V2
X...
X...
X...
X...
```
These two projections signal some directions along which there must be cubes:
[](https://i.stack.imgur.com/A8KRe.jpg)
and the output would be `4, 16`; This is the case because both `V3` below represent valid projections on `V3`:
```
V3a
X...
.X..
..X.
...X
```
This is a "diagonal" pattern of cubes in the back plane, when viewed from `V3`; ...
```
V3b
XXXX
XXXX
XXXX
XXXX
```
and this is a full face in the back plane.
## Explained example 2
```
V1
XXXX
XXXX
XXXX
XXXX
V2
XXXX
....
....
....
```
These projections represent the top face of the main cube, so in this case we managed to identify the arrangement uniquely. The output in this case would be `16, 16` (or `16`, see output rules below).
# Input
Your code takes the projections on `V1` and `V2` as input. There are a variety of reasonable ways for you to take this input. I suggest the following to represent each projection:
* An array of length 4 with strings of length 4, two different characters to encode "empty" or "filled", like `["X...", ".X..", "..X.", "...X"]` for the `V3a` above.
* An array/string of length 16, representing the 16 squares of the projection, like `"X....X....X....X"` for `V3a` above.
* An integer where its base 2 expansion encodes the string above; 1 *must* represent the `X` above, so `V3a` above would be `33825 = b1000010000100001`.
For any of the alternatives above, or for any other valid alternative we later decide that is helpful for you guys, you can take any face in any orientation you see fit, as long as it is consistent across test cases.
# Output
The two non-negative integers representing the minimum and maximum possible number of `1x1x1` cubes in an arrangement that projects onto `V1` and `V2` like the input specifies. If the minimum and maximum are the same, you can print only one of them, if that helps you in any way.
# Test cases
(I didn't really know how to format these... if needed, I can reformat them! Please let me know.)
```
XXXX
....
....
....,
X...
X...
X...
X... -> 4, 16
XXXX
XXXX
XXXX
XXXX,
XXXX
....
....
.... -> 16, 16
XXXX
XXXX
XXXX
XXXX,
XXXX
....
..X.
.... -> 16, 20
X..X
.XX.
.XX.
X..X,
X.XX
.X..
..X.
XX.X -> 8, 16
XXXX
XXXX
XXXX
XXXX,
XXXX
XXXX
XXXX
XXXX -> 16, 64
X...
....
....
XXXX,
X...
X...
X...
X..X -> 8, 8
X..X
....
....
XXXX,
X...
X...
X...
X..X -> 8, 12
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 bytes
```
+.(⌈,×)/+⌿¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1tP41FPh87h6Zr62o969h9a8T/tUduER719j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv8vMwSpaZuoYahgAIKaeBhcZUYkKE5TKDNUKDPi4kKyAgw18TCQrYBKGcBMBlGGMAZOK8CqYGqQGTApEnxhCLcCAA "APL (Dyalog Unicode) – Try It Online")
Takes V1 and V2 as two binary matrices inside a nested vector, and V1 is rotated so that it vertically lines up with V2. Returns doubly nested vector of `(min, max)`.
### How it works
The first column of V1 and the first column of V2 decide the first vertical layer of 4x4 cells. If `n` cells are shaded in V1's column and `m` cells in V2's, the minimum number of shaded cells in the corresponding 4x4 layer is `max(m,n)`, and the maximum is `m * n`.
```
min | max
| 1 0 1 0 | | 1 0 1 0
----------- | -----------
1 | 1 0 0 0 | 1 | 1 0 1 0
1 | 1 0 0 0 | 1 | 1 0 1 0
0 | 0 0 0 0 | 0 | 0 0 0 0
1 | 0 0 1 0 | 1 | 1 0 1 0
```
Therefore, it suffices to count ones in each column, and evaluate sums of the pairwise max (for minimum) and pairwise product (for maximum) of the column sums.
```
+.(⌈,×)/+⌿¨
+⌿¨ ⍝ In each matrix, evaluate column sums
/ ⍝ Over the two vectors,
+. ⌈ ⍝ Evaluate the sum of pairwise max
, ⍝ and
+. × ⍝ the sum of pairwise product
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~74~~ 71 bytes
*-3 bytes thanks to @Bubbler!*
```
lambda V:(sum(f(*map(sum,p))for p in zip(*V))for f in[max,int.__mul__])
```
[Try it online!](https://tio.run/##nVFLT@MwEL77V4zYi12lVQxVBUg9BIm97g2BslbkNnZJycNyXGip@tu7YwdESNFqWR9G45nv5cTs3GNTXxz1/PexlNUil3B3TdtNRTUdVdL4NjKM6caCgaKG18LQ0V030DhIK7mNitpNsqzalFkm2PEHWCVz0HKpQNumQpTZOJIrHRaZX1B2TQASmEMqsPFqhZe3sl4pOg1bgNbvQwx0iIIMZZPWWQzBmAiYZCKNUXVOW4Z3q9zG1pAQgikaJ50C2SW5iiFXK6sULMtm@fRStKqLFFBdqCT43njXNBajaciV9XP9Jawfr0/HqJcWIl0LVE3Si/Fa4PUj6Q0hL49FqYB7uLO7jiUR3ftYYfb2/tAv/L6XvIftANtohxD1LEv6xhuKqO1SGQe3v37eWtvYzneBQk/Y3UcPSNc0ldFCeLSx@AuoPtvfH2D/cIB0TxHD5nOKTuwgztiR4yExnl4h3NdBmUbAZ2TcOyRwB4V8Jchn/0HmPfJ5PCDjmsTcQ3wJV6yezN/JuODk8jvGw4LGs@mJ8aeHdeSTzxWML7/K/G9Ufv6J@wc "Python 3 – Try It Online")
**Input**: a list of faces `[V1,V2]`, each face is a 4x4 list of binary digit. The orientation of each face is as follow (`V2` is rotated 90 degree clock-wise compare to the challenge's default orientation).
[](https://i.stack.imgur.com/mLCj5.png)
**Output**: A tuple of 2 integers, representing the min and max number of blocks.
### Approach
Consider each of the 4 slices of the cube:
[](https://i.stack.imgur.com/aBgzQ.png)
We can see that for each slice, the min and max number of block in that slice is respectively the max and the product of the top and left strips.
### Code explanation:
`lambda V:(sum(f(*map(sum,p))for p in zip(*V))for f in[max,int.__mul__])`
* `for f in[max,int.__mul__]` assigns `f` first to the function `max`, then to the integer multiply function.
* `p in zip(*V)` pairs each corresponding strips (aka rows) of the 2 faces together.
* `map(sum,p)` applies the `sum` function to each row in the pair. The result is effectively `(top, left)`.
* `f(*map(...))` computes either `max(top,left)` or `top*left`.
* `sum(f(...))` sums over all slices.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
§µ»/,P§
```
A monadic Link accepting a list of the two projections each being a list of lists of 1s and 0s, `[V1, V2]`, with V2 rotated a quarter turn clockwise which yields a list of two integers, `[min, max]`
**[Try it online!](https://tio.run/##y0rNyan8///Q8kNbD@3W1wk4tPz////R0dGGOgZAaBjLpaATbQBmG2CwDXXAMDaWSycazsGvAcKOjf0PAA "Jelly – Try It Online")**
### How?
The same method as Bubbler & Surculose Sputum came up with.
```
§µ»/,P§ - Link: list of two lists of lists of 1s and 0s
§ - sums
µ - start a new monadic chain, call that v
/ - reduce (v) by:
» - maximum (vectorises)
P - product of (v) (vectorises)
, - pair
§ - sums
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~61~~ ~~58~~ 22 bytes
```
≔E⁴EθΣ§λιθI⟦ΣEθ⌈ιΣEθΠι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7FAw0RHAUQV6igEl@ZqOJZ45qWkVmjk6ChkagKBjkKhpjVXQFFmXomGc2JxiUY0SBVUg29iRWYukJsJVogkEVCUn1KaXAKWiNXUtP7/Pzo6WskQCJR0FJQMgACDjtVRIKQiNva/blkOAA "Charcoal – Try It Online") Takes input as a list of lists in a different orientation to the examples. Uses @Bubbler's formula. Explanation:
```
≔E⁴EθΣ§λιθ
```
Transpose the input while taking the count of the number of cubes in each row.
```
I⟦ΣEθ⌈ιΣEθΠι
```
Calculate the minimum and maximum cubes for each row, and then take the totals for all four rows.
] |
[Question]
[
If you remember back to your schooling years, you might remember learning about [Truth Tables](https://en.wikipedia.org/wiki/Truth_table). They seemed boring, but they are basis for logic and (some would argue) all computing...
---
# Problem
Your mission, should you choose to accept it is to write a program, function, or widget of code that can output a truth table given input.
## Input
Input will be a string (like data structure) containing the logic statement to make the Truth Table into. For example:
```
p ∧ q
```
This means `p and q`(logical conjuction) and will output:
```
p q p ∧ q
T T T
T F F
F T F
F F F
```
Notice the spacing: The item of the column is **in the center of the header**
# Characters
**Score via characters, not bytes**
The logic comparison characters are special and not always what they look like. Use these characters:
Logical Conjunction (AND): `∧` U+2227
Logical Disjunction (OR): `∨` U+2228
Logical Negation (NOT) `~` or `¬` U+7e and U+ac respectively
---
# Bonuses
All of these bonuses are optional, but will knock points off your score. Pick any.
## Logical Negation
Logical Negation is a unary operator in truth tables. It is the equivalent of `!` in most C-based languages. It makes `false`=>`true` and vise versa. It is notated with a `¬` **or** `~` (you must support both). **Supporting this will knock off 10% of your score.** You must, however, add an additional column to show its results:
For example:
```
~p ∧ q
```
will output:
```
p ~p q ~p ∧ q
T F T F
T F F F
F T T T
F T F F
```
## Pretty Print
The normal table notation is boring. Let's make it pretty! Pretty print format is as follows for `p ∧ q` is as follows:
```
+---+---+-------+
| p | q | p ∧ q |
+---+---+-------+
| T | T | T |
+---+---+-------+
| T | F | F |
+---+---+-------+
| F | T | F |
+---+---+-------+
| F | F | F |
+---+---+-------+
```
Special details for pretty printing:
* There is a 1 space padding in each cell
* Cell values are still centered
If you pretty print your tables, from your code and then multiply by 0.6. Use this function for this bonus:
```
score = 0.6 * code
```
---
# Examples
`p ∧ q`:
```
p q p ∧ q
T T T
T F F
F T F
F F F
```
`p ∨ q`:
```
p q p ∨ q
T T T
T F T
F T T
F F F
```
`~p ∧ q`:
```
p ~p q ~p ∧ q
T F T F
T F F F
F T T T
F T F F
```
`~p ∨ q`:
```
p ~p q ~p ∧ q
T F T T
T F F F
F T T T
F T F T
```
---
# Rules
* Standard loopholes apply
* No external resources
* If you're going to break the rules, be clever ;)
Shortest Code (in characters) wins. Good Luck!
[Answer]
# JavaScript (ES6), 141
Simple function, no bonus, 141 chars. (140 uft8, 1 unicode wide)
Complex function handling ~ or ¬, 254 chars (253 utf, 1 unicode wide), score 229
Could save 6 bytes using `alert` instead of `console.log`, but `alert` is particularly unfit to display tables.
Test running the snippet below in an EcmaScript 6 compliant browser (tested with Firefox. Won't work in Chrome as Chrome does not support `...`. Also, the bonus version use an extension of `split` that is Firefox specific).
```
/* TEST: redirect console.log into the snippet body */ console.log=x=>O.innerHTML+=x+'\n'
// Simple
F=s=>{[a,o,b]=[...s],z=' ',r=a+z+b+z+a+` ${o} ${b}
`;for(w='FT',n=4;n--;r+=w[c]+z+w[e]+z+z+w[o<'∧'?c|e:c&e]+`
`)c=n&1,e=n>>1;console.log(r)}
// Simple, more readable
f=s=>{
[a,o,b]=[...s]
r=a+' '+b+' '+a+` ${o} ${b}\n`
for(w='FT',n=4; n--; )
{
c = n&1, e = n>>1, x=o<'∧' ? c|e : c&e
r += w[c]+' '+w[e]+' '+w[x]+'\n'
}
console.log(r)
}
// 10% Bonus
B=s=>{[a,o,b]=s.split(/([∧∨])/),t=a>'z',u=b>'z',z=' ',r=(t?a[1]+z:'')+a+z+(u?b[1]+z:'')+b+z+a+` ${o} ${b}
`;for(s=v=>'FT'[v]+z,n=4;n--;r+=s(c)+(t?s(d)+' ':'')+s(e)+(u?s(f)+' ':'')+(t?' ':z)+s(o<'∧'?d|f:d&f)+`
`)c=n&1,d=c^t,e=n>>1,f=e^u;console.log(r)}
Test1 = ['q∨p','q∧p']
Test2 = Test1.concat([
'~q∨p','q∨~p','~q∨~p','~q∧p','q∧~p','~q∧~p',
'¬q∨p','q∨¬p','¬q∨¬p','¬q∧p','q∧¬p','¬q∧¬p'
])
console.log('SIMPLE')
Test1.forEach(t=>F(t));
console.log('BONUS')
Test2.forEach(t=>B(t));
```
```
<pre id=O></pre>
```
[Answer]
# MediaWiki template - 2347 characters
MediaWiki has a built template function called `{{#expr}}` that can handle logical expressions. This must be the perfect challenge for MediaWiki templates! Features such as variables, loops and a readable syntax would have helped a bit, though. Also, the fact that there is no NOT operator for the expr function made it a bit more complex.
```
{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}} {{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}} {{{1}}}<br>T T {{#if:{{#pos:{{#sub:{{#replace:{{{1}}}|~|¬}}|0|1}}|¬}}| |}} {{#replace:{{#replace:{{#expr:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{{1}}}|~|¬}}|{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}}}|0|1}}}}|{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}}}|0|1}}|0|1}}|¬|}}|∧|and}}|∨|or}}}}|1|T}}|0|F}}<br>T F {{#if:{{#pos:{{#sub:{{#replace:{{{1}}}|~|¬}}|0|1}}|¬}}| |}} {{#replace:{{#replace:{{#expr:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{{1}}}|~|¬}}|{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}}}|0|1}}}}|{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}}}|1|0}}|1|0}}|¬|}}|∧|and}}|∨|or}}}}|1|T}}|0|F}}<br>F T {{#if:{{#pos:{{#sub:{{#replace:{{{1}}}|~|¬}}|0|1}}|¬}}| |}} {{#replace:{{#replace:{{#expr:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{{1}}}|~|¬}}|{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}}}|1|0}}}}|{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}}}|0|1}}|0|1}}|¬|}}|∧|and}}|∨|or}}}}|1|T}}|0|F}}<br>F F {{#if:{{#pos:{{#sub:{{#replace:{{{1}}}|~|¬}}|0|1}}|¬}}| |}} {{#replace:{{#replace:{{#expr:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{#replace:{{{1}}}|~|¬}}|{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{#replace:{{#replace:{{{1}}}|~|}}|¬|}}|0|1}}}}|1|0}}}}|{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}|{{#if:{{#pos:{{#replace:{{{1}}}|~|¬}}|¬{{#sub:{{{1}}}|{{#expr:{{#len:{{{1}}}}}-1}}|{{#len:{{{1}}}}}}}}}|1|0}}|1|0}}|¬|}}|∧|and}}|∨|or}}}}|1|T}}|0|F}}
```
**Test:**
```
{{TemplateName|¬X ∧ ~Y}}
{{TemplateName|p ∨ q}}
```
**Result:**
```
X Y ¬X ∧ ~Y
T T F
T F F
F T F
F F T
p q p ∨ q
T T T
T F T
F T T
F F F
```
I'm assuming MediaWiki >= 1.18, where the ParserFunctions extensions comes bundled with the software.
[Answer]
## Python - 288 characters (+10 penalty cause I couldn't get unicode to work :c)
No bonuses. This is my very first codegolf answer.
```
def f(i):
i=i.split(" ")
print i[0],i[2],
for f in i[0:3]: print f,
print ""
for t in["TT","TF","FT","FF"]:
p,q=t[0],t[1]
y = t[0]+" "+t[1]
if i[1]=="^": r=(False,True)[p==q]
if i[1]=="v": r=(False,True)[p!=q]
if r: y+=" T"
else: y+=" F"
print y
```
`i` is the input.
**EDIT:** Removed a few spaces and it now uses function args as input.
[Answer]
# [Dyalog APL](http://dyalog.com/download-zone.htm), ~~58~~ 48 characters
Requires `⎕IO←0`, which is default on many systems. Takes string as argument.
```
{('p q ',⍵)⍪'FT '[p,q,⍪⍎⍵]\⍨324⊤⍨9⍴≢p q←↓2 2⊤⌽⍳4}
```
No bonuses, but on the plus side, any operator works.
`⍳4` first four indices (0 1 2 3)
`⌽` reverse (3 2 1 0)
`2 2⊤` two-bit Boolean table
`↓` split into two-element list of lists (high-bits, low-bits)
`p q←` store as *p* and *q*
`≢` tally them (2)\*
`9⍴` cyclically reshape that to length 9 (2 2 2 2 2 2 2 2 2)
`324⊤⍨` encode 324 thusly, i.e. as 12-bit binary (1 0 1 0 0 0 1 0 0)
`\⍨` use that to expand (insert a space for each 0)...
`'FT '[`...`]` the string "FT ", indexed by
`⍎⍵` the executed argument (valid since *p* and *q* now have values)
`⍪` make that into a column matrix
`q,` prepend a column consisting of *q* (1 1 0 0)
`q,` prepend a column consisting of *p* (1 0 1 0)
`(`...`)⍪` insert a row above, consisting of
`⍵` the argument
`'p q ',` prepended with the string "p q "
---
\* Please star [this issue](https://bugs.chromium.org/p/chromium/issues/detail?id=620629) if you see `≢` as `≢` and not as `̸≡`.
[Answer]
# Julia, 161 bytes
No bonuses.
```
s->(S=split(s);P=println;p=S[1];q=S[3];a=[&,|][(S[2]=="∨")+1];c=" ";P(p,c,q,c,s);for t=["TT","TF","FT","FF"] P(t[1],c,t[2],c^2,"FT"[a(t[1]>'F',t[2]>'F')+1])end)
```
Ungolfed:
```
function f(s::String)
# Split the input on spaces
S = split(s)
# Separate out the pieces of the statement
p = S[1]
q = S[3]
a = [&, |][(S[2] == "∨") + 1]
# Print the header
println(p, " ", q, " ", s)
# Create the table entries in a loop
for t = ["TT", "TF", "FT", "FF"]
println(t[1], " ", t[2], " ", "FT"[a(t[1] > 'F', t[2] > 'F') + 1])
end
end
```
[Answer]
## Python3, 145 139 120 119 Bytes
No bonus (with bonus at the end)
```
def f(s):
a,m,b=s.split(" ");print(a,b,s);F,T,c=0,1,"FT"
for p in c:
for q in c:print(p,q," ",c[eval(p+"+*"[m=="∧"]+q)>0])
```
Needing Python3 for Unicode support out of the box.
Based on DJgamer98 Python code, figuring out his table is not right.
Edit1: Splitting into distinct variables and ommiting the operator string variable
Edit2: (ab)using F and T as both variables and string characters
Edit3: Saving one space thanks to NoOneIsHere
### With Bonus, 215 \* 0.6 = 129
```
def f(s):
r="+---"*3+"----+"
a,m,b=s.split(" ");F,T,c=0,1,"FT"
print("%s\n| %s | %s | %s |\n%s"%(r,a,b,s,r));
for p in c:
for q in c: print("| %s | %s | %s |\n%s"%(p,q,c[eval(p+"+*"[m=="∧"]+q)>0],r));
```
[Answer]
## C/C++ 302 Bytes
335 characters less 10% for handling negation. Formatting incomplete but submitting before I see what the impact of completion is.
Marked as C/C++ because my gcc and g++ accepts it with -fpermissive and it looks far more C like than C++ to me.
```
#include <stdio.h>
void T(char*S) { int (*P)(char*,...)=printf;char*v[2]={"F","T"};for(int m=4;m--;){P("|");char*s=S;int x=m&1;X:P(" %s |",v[x]);if(*++s!=' '){x=x^1;goto X;}char*o=++s;s+=3;int y=(m>>1)&1;Y:P(" %s |",v[y]);if(*++s){y=y^1;goto Y;}int g;for(g=o-S+1;g--;)P(" ");P(*++o==39?v[x&y]:v[x|y]);for(g=s-o;g--;)P(" ");P("|\n");}}
```
I'm sure there's probably a few tweaks that could be applied. In fact handling the nots adds more than the 10% bonus removes.
This does assume the input format is as stated, i.e. 2 input values (p and q), with or without the not prefix and nothing else, and all tokens delimited by a single space.
Ungolfed:
```
void ungolfed(char* S)
{
int (*P)(char*,...) = printf; // useful lookup stuff
char* v[2] = {"F","T"};
for(int m = 4; m--;) { // loop over all 2 bit bit patterns (truth table inputs)
P("|"); // start of line format
char* s=S; // iterator to start of equation for each bit pattern
int x = m&1; // input 1 (aka. p which I called x here to be awkward)
X: P(" %s |",v[x]); // input 1 output and format
if(*++s!=' ') { // if next character is not a space then input must be prefixed with the not character
x=x^1; // so negate the input
goto X; // and redo input 1 output
}
char* o = ++s; // remember where the operator is
s+=3; // and skip it and following space
int y = (m>>1)&1; // input 2 (aka. q which I called y obviously) processing as for input 1
Y: P(" %s |",v[y]);
if(*++s) {
y=y^1;
goto Y;
}
int g;
for(g=o-S+1;g--;) P(" "); // pre-result value padding
P(*++o==39?v[x&y]:v[x|y]); // result
for(g=s-o;g--;) P(" "); // post-result value padding and format
P("|\n");
}
}
```
and the tests:
```
int main()
{
T("p \x22\x27 q"); // p & q
puts("");
T("p \x22\x28 q"); // p | q
puts("");
T("\x7ep \x22\x27 q"); // ~p & q
puts("");
T("\xacp \x22\x28 q"); // ~p | q
puts("");
T("p \x22\x28 \xacq"); // p | ~q
puts("");
return 0;
}
```
[Answer]
## Mathematica, 129 Bytes
**Golfed:**
```
t=InputString[];s=Append[StringCases[t,LetterCharacter],t];Grid[Prepend[Map[If[#,"T","F"]&,BooleanTable[ToExpression[s]],{2}],s]]
```
**Ungolfed:**
```
(*Take input*)
t=InputString[];
(* Find all occurrences of letters and append the final statement.*)
s=Append[StringCases[t,LetterCharacter],t];
(* Evaluate the list as expressions and create a boolean table of True/False values, then display as a table. *)
(* To satisfy the output conditions, we must convert each True/False to T/F *)
Grid[Prepend[Map[If[#,"T","F"]&,BooleanTable[ToExpression[s]],{2}],s]]
```
Not a Mathematica expert, but I found this rather elegant compared to having to do direct character comparison.
I had a solution that worked for negation, but it was longer than the score reduction would take off.
Depending on what qualifies for pretty printing, I might try for that bonus. I feel like outputting in ASCII in Mathematica would be far too expensive for the score reduction to compensate, but if the two main features are a dotted border and specified padding inside the cells, that's only a couple options in Grid.
**With pretty printing, 171 \* 0.6 = 102.6 Bytes**
```
t=InputString[];s=Append[StringCases[t,LetterCharacter],t];Grid[Prepend[Map[If[#,"T","F"]&,BooleanTable[ToExpression[s]],{2}],s],Spacings->1,Frame->All,FrameStyle->Dashed]
```
[Answer]
## Mathematica, 128 characters
```
TraditionalForm@Grid[({#}~Join~BooleanTable[#,Cases[b,_Symbol,{0,∞}]]&/@Cases[b=ToExpression@#,_,{0,∞}]/.{0<1->"T",0>1->"F"})]&
```
`` is the private use character `U+F3C7` representing `\[Transpose]`.
Luckily for us Mathematica golfers, `∧` and `∨` *already* represent `And` and `Or`, so all we have to do is convert the input string into a Mathematica expression and we can do symbolic logical operations on it.
Note that this solution will also handle `Not` ([`¬`](https://unicode-table.com/en/00AC/)), `Implies` ([``](https://unicode-table.com/en/F523/)), `Equivalent` ([`⧦`](https://unicode-table.com/en/29E6/)), `Xor` ([`⊻`](https://unicode-table.com/en/22BB/)), `Nand` ([`⊼`](https://unicode-table.com/en/22BC/)), `Xor` ([`⊻`](https://unicode-table.com/en/22BB/)), and `Nor` ([`⊽`](https://unicode-table.com/en/22BD/)), but it doesn't get the bonus because `~p` is a syntax error in Mathematica. Meh.
[](https://i.stack.imgur.com/4c698.png)
## Explanation
```
b=ToExpression@#
```
Converts the input string into a Mathematica expression and stores it in `b`.
```
Cases[b=ToExpression@#,_,{0,∞}]
```
This is a list every possible subexpression of the input. Each will receive its own column.
```
Cases[b,_Symbol,{0,∞}]
```
This is a list of all of the variables that appear in the input.
```
BooleanTable[#,Cases[b,_Symbol,{0,∞}]]&
```
Pure function which takes an input expression `#` and returns a list of truth values for all possible combinations of truth values for the variables.
```
{#}~Join~BooleanTable[...]
```
Prepends the expression itself to this list.
```
.../@Cases[b=ToExpression@#,_,{0,∞}]
```
Applies this function to each subexpression of the input.
```
.../.{0<1->"T",0>1->"F"}
```
Then replace true (`0<1`) with "T" and false (`0>1`) with "F".
```
(...)
```
Interchange rows and columns.
```
Grid[...]
```
Display the result as a `Grid`.
```
TraditionalForm@Grid[...]
```
Convert the `Grid` to traditional form so that it uses the fancy symbols.
] |
[Question]
[
This challenge is partly an algorithms challenge, partly an optimization challenge and partly simply a fastest code challenge.
A cyclic matrix is fully specified by its first row `r`. The remaining rows are each cyclic permutations of the row `r` with offset equal to the row index. We will allow cyclic matrices which are not square so that they are simply missing some of their last rows. We do however always assume that the number of rows is no more than the number of columns. For example, consider the following 3 by 5 cyclic matrix.
```
10111
11011
11101
```
We say a matrix has property X if it contains two non-empty sets of columns with non-identical indices which have the same (vector) sum. The vector sum of two columns is simply an element-wise summation of the two columns. That is the sum of two columns containing `x` elements each is another column containing `x` elements.
The matrix above trivially has property X as the first and last columns are the same. The identity matrix never has property X.
If we just remove the last column of the matrix above then we get an example which does not have property X and would give a score of 4/3.
```
1011
1101
1110
```
**The task**
The task is to write code to find the highest scoring cyclic matrix whose entries are all 0 or 1 and which *does not* have property X.
**Score**
Your score will be the number columns divided by the number of rows in your best scoring matrix.
**Tie Breaker**
If two answers have the same score, the one submitted first wins.
In the (very) unlikely event that someone finds a method to get unlimited scores, the first valid proof of such a solution will be accepted. In the even more unlikely event that you can find a proof of optimality of a finite matrix I will of course award the win too.
**Hint**
Getting a score of 12/8 is not too hard.
**Languages and libraries**
You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.
**Leading entries**
* 36/19 by Peter Taylor (Java)
* 32/17 by Suboptimus Prime (C#)
* 21/12 by justhalf (Python 2)
[Answer]
## 16/9 20/11 22/12 28/15 30/16 32/17 34/18 36/19 (Java)
This uses a number of ideas to reduce the search space and cost. View the revision history for more details on earlier versions of the code.
* It's clear that wlog we can consider only circulant matrices in which the first row is a [Lyndon word](http://en.wikipedia.org/wiki/Lyndon_word): if the word is non-prime then it must have property X, and otherwise we can rotate without affecting the score or property X.
* Based on heuristics from the observed short winners, I'm now iterating through the Lyndon words starting at the ones with 50% density (i.e. the same number of `0` and `1`) and working out; I use the algorithm described in *A Gray code for fixed-density necklaces and Lyndon words in constant amortized time*, Sawada and Williams, *Theoretical Computer Science* 502 (2013): 46-54.
* An empirical observation is that the values occur in pairs: each optimum Lyndon word that I've found scores the same as its reversal. So I get about a factor of two speedup by only considering one half of each such pair.
* My original code worked with `BigInteger` to give an exact test. I get a significant speed improvement, at the risk of false negatives, by operating modulo a large prime and keeping everything in primitives. The prime I've chosen is the largest one smaller than 257, as that allows multiplying by the base of my notional vector representation without overflowing.
* I've stolen [Suboptimus Prime](https://codegolf.stackexchange.com/users/31760/suboptimus-prime)'s heuristic that it's possible to get quick rejections by considering subsets in increasing order of size. I've now merged that idea with the ternary subset meet-in-the-middle approach to test for colliding subsets. (Credit to [KennyTM](https://codegolf.stackexchange.com/users/32353/kennytm) for suggesting trying to adapt the approach from the integer subset problem; I think that [xnor](https://codegolf.stackexchange.com/users/20260/xnor) and I saw the way to do it pretty much simultaneously). Rather than looking for two subsets which can include each column 0 or 1 times and have the same sum, we look for one subset which can include each column -1, 0, or 1 times and sum to zero. This significantly reduces the memory requirements.
* There's an extra factor of two saving in memory requirements by observing that since each element in `{-1,0,1}^m` has its negation also in `{-1,0,1}^m` it's only necessary to store one of the two.
* I also improve memory requirements and performance by using a custom hashmap implementation. To test 36/19 requires storing 3^18 sums, and 3^18 longs is almost 3GB without any overhead - I gave it 6GB of heap because 4GB wasn't enough; to go any further (i.e. test 38/20) within 8GB of RAM would require further optimisation to store ints rather than longs. With 20 bits required to say which subset produces the sum that would leave 12 bits plus the implicit bits from the bucket; I fear that there would be too many false collisions to get any hits.
* Since the weight of the evidence suggests that we should look at `2n/(n+1)`, I'm speeding things up by just testing that.
* There's some unnecessary but reassuring statistical output.
```
import java.util.*;
// Aiming to find a solution for (2n, n+1).
public class PPCG41021_QRTernary_FixedDensity {
private static final int N = 36;
private static int density;
private static long start;
private static long nextProgressReport;
public static void main(String[] args) {
start = System.nanoTime();
nextProgressReport = start + 5 * 60 * 1000000000L;
// 0, -1, 1, -2, 2, ...
for (int i = 0; i < N - 1; i++) {
int off = i >> 1;
if ((i & 1) == 1) off = ~off;
density = (N >> 1) + off;
// Iterate over Lyndon words of length N and given density.
for (int j = 0; j < N; j++) a[j] = j < N - density ? '0' : '1';
c = 1;
Bs[1] = N - density;
Bt[1] = density;
gen(N - density, density, 1);
System.out.println("----");
}
System.out.println("Finished in " + (System.nanoTime() - start)/1000000 + " ms");
}
private static int c;
private static int[] Bs = new int[N + 1], Bt = new int[N + 1];
private static char[] a = new char[N];
private static void gen(int s, int t, int r) {
if (s > 0 && t > 0) {
int j = oracle(s, t, r);
for (int i = t - 1; i >= j; i--) {
updateBlock(s, t, i);
char tmp = a[s - 1]; a[s - 1] = a[s+t-i - 1]; a[s+t-i - 1] = tmp;
gen(s-1, t-i, testSuffix(r) ? c-1 : r);
tmp = a[s - 1]; a[s - 1] = a[s+t-i - 1]; a[s+t-i - 1] = tmp;
restoreBlock(s, t, i);
}
}
visit();
}
private static int oracle(int s, int t, int r) {
int j = pseudoOracle(s, t, r);
updateBlock(s, t, j);
int p = testNecklace(testSuffix(r) ? c - 1 : r);
restoreBlock(s, t, j);
return p == N ? j : j + 1;
}
private static int pseudoOracle(int s, int t, int r) {
if (s == 1) return t;
if (c == 1) return s == 2 ? N / 2 : 1;
if (s - 1 > Bs[r] + 1) return 0;
if (s - 1 == Bs[r] + 1) return cmpPair(s-1, t, Bs[c-1]+1, Bt[c-1]) <= 0 ? 0 : 1;
if (s - 1 == Bs[r]) {
if (s == 2) return Math.max(t - Bt[r], (t+1) >> 1);
return Math.max(t - Bt[r], (cmpPair(s-1, t, Bs[c-1] + 1, Bt[c-1]) <= 0) ? 0 : 1);
}
if (s == Bs[r]) return t;
throw new UnsupportedOperationException("Hit the case not covered by the paper or its accompanying code");
}
private static int testNecklace(int r) {
if (density == 0 || density == N) return 1;
int p = 0;
for (int i = 0; i < c; i++) {
if (r - i <= 0) r += c;
if (cmpBlocks(c-i, r-i) < 0) return 0;
if (cmpBlocks(c-i, r-1) > 0) return N;
if (r < c) p += Bs[r-i] + Bt[r-i];
}
return p;
}
private static int cmpPair(int a1, int a2, int b1, int b2) {
if (a1 < b1) return -1;
if (a1 > b1) return 1;
if (a2 < b2) return -1;
if (a2 > b2) return 1;
return 0;
}
private static int cmpBlocks(int i, int j) {
return cmpPair(Bs[i], Bt[i], Bs[j], Bt[j]);
}
private static boolean testSuffix(int r) {
for (int i = 0; i < r; i++) {
if (c - 1 - i == r) return true;
if (cmpBlocks(c-1-i, r-i) < 0) return false;
if (cmpBlocks(c-1-i, r-1) > 0) return true;
}
return false;
}
private static void updateBlock(int s, int t, int i) {
if (i == 0 && c > 1) {
Bs[c-1]++;
Bs[c] = s - 1;
}
else {
Bs[c] = 1;
Bt[c] = i;
Bs[c+1] = s-1;
Bt[c+1] = t-i;
c++;
}
}
private static void restoreBlock(int s, int t, int i) {
if (i == 0 && (c > 0 || (Bs[1] != 1 || Bt[1] != 0))) {
Bs[c-1]--;
Bs[c] = s;
}
else {
Bs[c-1] = s;
Bt[c-1] = t;
c--;
}
}
private static long[] stats = new long[N/2+1];
private static long visited = 0;
private static void visit() {
String word = new String(a);
visited++;
if (precedesReversal(word) && testTernary(word)) System.out.println(word + " after " + (System.nanoTime() - start)/1000000 + " ms");
if (System.nanoTime() > nextProgressReport) {
System.out.println("Progress: visited " + visited + "; stats " + Arrays.toString(stats) + " after " + (System.nanoTime() - start)/1000000 + " ms");
nextProgressReport += 5 * 60 * 1000000000L;
}
}
private static boolean precedesReversal(String w) {
int n = w.length();
StringBuilder rev = new StringBuilder(w);
rev.reverse();
rev.append(rev, 0, n);
for (int i = 0; i < n; i++) {
if (rev.substring(i, i + n).compareTo(w) < 0) return false;
}
return true;
}
private static boolean testTernary(String word) {
int n = word.length();
String rep = word + word;
int base = 1;
for (char ch : word.toCharArray()) base += ch & 1;
// Operating base b for b up to 32 implies that we can multiply by b modulo p<2^57 without overflowing a long.
// We're storing 3^(n/2) ~= 2^(0.8*n) sums, so while n < 35.6 we don't get *too* bad a probability of false reject.
// (In fact the birthday paradox assumes independence, and our values aren't independent, so we're better off than that).
long p = (1L << 57) - 13;
long[] basis = new long[n];
basis[0] = 1;
for (int i = 1; i < basis.length; i++) basis[i] = (basis[i-1] * base) % p;
int rows = n / 2 + 1;
long[] colVals = new long[n];
for (int col = 0; col < n; col++) {
for (int row = 0; row < rows; row++) {
colVals[col] = (colVals[col] + basis[row] * (rep.charAt(row + col) & 1)) % p;
}
}
MapInt57Int27 map = new MapInt57Int27();
// Special-case the initial insertion.
int[] oldLens = new int[map.entries.length];
int[] oldSupercounts = new int[1 << 10];
{
// count = 1
for (int k = 0; k < n/2; k++) {
int val = 1 << (25 - k);
if (!map.put(colVals[k], val)) { stats[1]++; return false; }
if (!map.put(colVals[k + n/2], val + (1 << 26))) { stats[1]++; return false; }
}
}
final long keyMask = (1L << 37) - 1;
for (int count = 2; count <= n/2; count++) {
int[] lens = map.counts.clone();
int[] supercounts = map.supercounts.clone();
for (int sup = 0; sup < 1 << 10; sup++) {
int unaccountedFor = supercounts[sup] - oldSupercounts[sup];
for (int supi = 0; supi < 1 << 10 && unaccountedFor > 0; supi++) {
int i = (sup << 10) + supi;
int stop = lens[i];
unaccountedFor -= stop - oldLens[i];
for (int j = oldLens[i]; j < stop; j++) {
long existingKV = map.entries[i][j];
long existingKey = ((existingKV & keyMask) << 20) + i;
int existingVal = (int)(existingKV >>> 37);
// For each possible prepend...
int half = (existingVal >> 26) * n/2;
// We have 27 bits of key, of which the top marks the half, so 26 bits. That means there are 6 bits at the top which we need to not count.
int k = Integer.numberOfLeadingZeros(existingVal << 6) - 1;
while (k >= 0) {
int newVal = existingVal | (1 << (25 - k));
long pos = (existingKey + colVals[k + half]) % p;
if (pos << 1 > p) pos = p - pos;
if (pos == 0 || !map.put(pos, newVal)) { stats[count]++; return false; }
long neg = (p - existingKey + colVals[k + half]) % p;
if (neg << 1 > p) neg = p - neg;
if (neg == 0 || !map.put(neg, newVal)) { stats[count]++; return false; }
k--;
}
}
}
}
oldLens = lens;
oldSupercounts = supercounts;
}
stats[n/2]++;
return true;
}
static class MapInt57Int27 {
private long[][] entries;
private int[] counts;
private int[] supercounts;
public MapInt57Int27() {
entries = new long[1 << 20][];
counts = new int[1 << 20];
supercounts = new int[1 << 10];
}
public boolean put(long key, int val) {
int bucket = (int)(key & (entries.length - 1));
long insert = (key >>> 20) | (((long)val) << 37);
final long mask = (1L << 37) - 1;
long[] chain = entries[bucket];
if (chain == null) {
chain = new long[16];
entries[bucket] = chain;
chain[0] = insert;
counts[bucket]++;
supercounts[bucket >> 10]++;
return true;
}
int stop = counts[bucket];
for (int i = 0; i < stop; i++) {
if ((chain[i] & mask) == (insert & mask)) {
return false;
}
}
if (stop == chain.length) {
long[] newChain = new long[chain.length < 512 ? chain.length << 1 : chain.length + 512];
System.arraycopy(chain, 0, newChain, 0, chain.length);
entries[bucket] = newChain;
chain = newChain;
}
chain[stop] = insert;
counts[bucket]++;
supercounts[bucket >> 10]++;
return true;
}
}
}
```
The first one found is
```
000001001010110001000101001111111111
```
and that's the only hit in 15 hours.
Smaller winners:
```
4/3: 0111 (plus 8 different 8/6)
9/6: 001001011 (and 5 others)
11/7: 00010100111 (and 3 others)
13/8: 0001001101011 (and 5 others)
15/9: 000010110110111 (and 21 others)
16/9: 0000101110111011 (and 1 other)
20/11: 00000101111011110111 (and others)
22/12: 0000001100110011101011 (and others)
24/13: 000000101011101011101011 (and others)
26/14: 00000001101110010011010111 (and others)
28/15: 0000000010000111100111010111 (and others)
30/16: 000000001011001110011010101111 (and probably others)
32/17: 00001100010010100100101011111111 (and others)
34/18: 0000101000100101000110010111111111 (and others)
```
[Answer]
## Python 2 - 21/12
*In the process of proving that a `2-(3/n)` always exists for any `n`*
Inspired by [this question](https://stackoverflow.com/questions/26008406/find-shortest-text-containing-all-combinations-of-a-given-string), I used [De Bruijn Sequence](http://en.wikipedia.org/wiki/De_Bruijn_sequence) to brute force the possible matrices. And after bruteforcing for `n=6,7,8,9,10`, I found a pattern that the highest solution is always in the shape of `(n, 2n-3)`.
So I created another method to bruteforce just that shape of matrix, and use multiprocessing to speed things up, since this task is highly distributable. In 16-core ubuntu, it can find solution for `n=12` in around 4 minutes:
```
Trying (0, 254)
Trying (254, 509)
Trying (509, 764)
Trying (764, 1018)
Trying (1018, 1273)
Trying (1273, 1528)
Trying (1528, 1782)
Trying (1782, 2037)
Trying (2037, 2292)
Trying (2292, 2546)
Trying (2546, 2801)
Trying (2801, 3056)
Trying (3056, 3310)
Trying (3820, 4075)
Trying (3565, 3820)
Trying (3310, 3565)
(1625, 1646)
[[0 0 0 1 0 0 1 0 1 1 1 1 0 0 0 1 0 0 1 1 0]
[0 0 1 0 0 1 0 1 1 1 1 0 0 0 1 0 0 1 1 0 0]
[0 1 0 0 1 0 1 1 1 1 0 0 0 1 0 0 1 1 0 0 0]
[1 0 0 1 0 1 1 1 1 0 0 0 1 0 0 1 1 0 0 0 0]
[0 0 1 0 1 1 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1]
[0 1 0 1 1 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 0]
[1 0 1 1 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 0 0]
[0 1 1 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1]
[1 1 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1 0]
[1 1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1 0 1]
[1 1 0 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1 0 1 1]
[1 0 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1 0 1 1 1]]
(12, 21)
Score: 1.7500
real 4m9.121s
user 42m47.472s
sys 0m5.780s
```
The bulk of computation goes to checking property X, which requires checking all subsets (there are `2^(2n-3)` subsets)
Note that I rotate the first row to the left, not to the right as in the question. But these are equivalent since you can just reverse the whole matrix. =)
The code:
```
import math
import numpy as np
from itertools import combinations
from multiprocessing import Process, Queue, cpu_count
def de_bruijn(k, n):
"""
De Bruijn sequence for alphabet k
and subsequences of length n.
"""
alphabet = list(range(k))
a = [0] * k * n
sequence = []
def db(t, p):
if t > n:
if n % p == 0:
for j in range(1, p + 1):
sequence.append(a[j])
else:
a[t] = a[t - p]
db(t + 1, p)
for j in range(a[t - p] + 1, k):
a[t] = j
db(t + 1, t)
db(1, 1)
return sequence
def generate_cyclic_matrix(seq, n):
result = []
for i in range(n):
result.append(seq[i:]+seq[:i])
return np.array(result)
def generate_cyclic_matrix_without_property_x(n=3, n_jobs=-1):
seq = de_bruijn(2,n)
seq = seq + seq[:n/2]
max_idx = len(seq)
max_score = 1
max_matrix = np.array([[]])
max_ij = (0,0)
workers = []
queue = Queue()
if n_jobs < 0:
n_jobs += cpu_count()+1
for i in range(n_jobs):
worker = Process(target=worker_function, args=(seq,i*(2**n-2*n+3)/n_jobs, (i+1)*(2**n-2*n+3)/n_jobs, n, queue))
workers.append(worker)
worker.start()
(result, max_ij) = queue.get()
for worker in workers:
worker.terminate()
return (result, max_ij)
def worker_function(seq,min_idx,max_idx,n,queue):
print 'Trying (%d, %d)' % (min_idx, max_idx)
for i in range(min_idx, max_idx):
j = i+2*n-3
result = generate_cyclic_matrix(seq[i:j], n)
if has_property_x(result):
continue
else:
queue.put( (result, (i,j)) )
return
def has_property_x(mat):
vecs = zip(*mat)
vector_sums = set()
for i in range(1, len(vecs)+1):
for combination in combinations(vecs, i):
vector_sum = tuple(sum(combination, np.array([0]*len(mat))))
if vector_sum in vector_sums:
return True
else:
vector_sums.add(vector_sum)
return False
def main():
import sys
n = int(sys.argv[1])
if len(sys.argv) > 2:
n_jobs = int(sys.argv[2])
else:
n_jobs = -1
(matrix, ij) = generate_cyclic_matrix_without_property_x(n, n_jobs)
print ij
print matrix
print matrix.shape
print 'Score: %.4f' % (float(matrix.shape[1])/matrix.shape[0])
if __name__ == '__main__':
main()
```
---
### Old answer, for reference
The optimal solution so far (`n=10`):
```
(855, 872)
[[1 1 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0]
[1 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1]
[0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1]
[1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0]
[0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 1]
[1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 1 0]
[0 0 1 1 1 1 0 1 1 1 0 1 1 0 1 0 1]
[0 1 1 1 1 0 1 1 1 0 1 1 0 1 0 1 0]
[1 1 1 1 0 1 1 1 0 1 1 0 1 0 1 0 0]
[1 1 1 0 1 1 1 0 1 1 0 1 0 1 0 0 1]]
(10, 17)
Score: 1.7000
```
For `n=7`:
```
(86, 97)
[[0 1 1 1 0 1 0 0 1 1 1]
[1 1 1 0 1 0 0 1 1 1 0]
[1 1 0 1 0 0 1 1 1 0 1]
[1 0 1 0 0 1 1 1 0 1 1]
[0 1 0 0 1 1 1 0 1 1 1]
[1 0 0 1 1 1 0 1 1 1 0]
[0 0 1 1 1 0 1 1 1 0 1]]
(7, 11)
Score: 1.5714
```
A solution with the shape as described by OP (`n=8`):
```
(227, 239)
[[0 1 0 1 1 1 1 1 0 1 1 0]
[1 0 1 1 1 1 1 0 1 1 0 0]
[0 1 1 1 1 1 0 1 1 0 0 1]
[1 1 1 1 1 0 1 1 0 0 1 0]
[1 1 1 1 0 1 1 0 0 1 0 1]
[1 1 1 0 1 1 0 0 1 0 1 1]
[1 1 0 1 1 0 0 1 0 1 1 1]
[1 0 1 1 0 0 1 0 1 1 1 1]]
(8, 12)
Score: 1.5000
```
But a better one (`n=8`):
```
(95, 108)
[[0 1 1 0 0 1 0 0 0 1 1 0 1]
[1 1 0 0 1 0 0 0 1 1 0 1 0]
[1 0 0 1 0 0 0 1 1 0 1 0 1]
[0 0 1 0 0 0 1 1 0 1 0 1 1]
[0 1 0 0 0 1 1 0 1 0 1 1 0]
[1 0 0 0 1 1 0 1 0 1 1 0 0]
[0 0 0 1 1 0 1 0 1 1 0 0 1]
[0 0 1 1 0 1 0 1 1 0 0 1 0]]
(8, 13)
Score: 1.6250
```
It also found another optimal solution at `n=9`:
```
(103, 118)
[[0 1 0 1 1 1 0 0 0 0 1 1 0 0 1]
[1 0 1 1 1 0 0 0 0 1 1 0 0 1 0]
[0 1 1 1 0 0 0 0 1 1 0 0 1 0 1]
[1 1 1 0 0 0 0 1 1 0 0 1 0 1 0]
[1 1 0 0 0 0 1 1 0 0 1 0 1 0 1]
[1 0 0 0 0 1 1 0 0 1 0 1 0 1 1]
[0 0 0 0 1 1 0 0 1 0 1 0 1 1 1]
[0 0 0 1 1 0 0 1 0 1 0 1 1 1 0]
[0 0 1 1 0 0 1 0 1 0 1 1 1 0 0]]
(9, 15)
Score: 1.6667
```
The code is as follows. It's just brute force, but at least it can find something better than OP's claim =)
```
import numpy as np
from itertools import combinations
def de_bruijn(k, n):
"""
De Bruijn sequence for alphabet k
and subsequences of length n.
"""
alphabet = list(range(k))
a = [0] * k * n
sequence = []
def db(t, p):
if t > n:
if n % p == 0:
for j in range(1, p + 1):
sequence.append(a[j])
else:
a[t] = a[t - p]
db(t + 1, p)
for j in range(a[t - p] + 1, k):
a[t] = j
db(t + 1, t)
db(1, 1)
return sequence
def generate_cyclic_matrix(seq, n):
result = []
for i in range(n):
result.append(seq[i:]+seq[:i])
return np.array(result)
def generate_cyclic_matrix_without_property_x(n=3):
seq = de_bruijn(2,n)
max_score = 0
max_matrix = []
max_ij = (0,0)
for i in range(2**n+1):
for j in range(i+n, 2**n+1):
score = float(j-i)/n
if score <= max_score:
continue
result = generate_cyclic_matrix(seq[i:j], n)
if has_property_x(result):
continue
else:
if score > max_score:
max_score = score
max_matrix = result
max_ij = (i,j)
return (max_matrix, max_ij)
def has_property_x(mat):
vecs = zip(*mat)
vector_sums = set()
for i in range(1, len(vecs)):
for combination in combinations(vecs, i):
vector_sum = tuple(sum(combination, np.array([0]*len(mat))))
if vector_sum in vector_sums:
return True
else:
vector_sums.add(vector_sum)
return False
def main():
import sys
n = int(sys.argv[1])
(matrix, ij) = generate_cyclic_matrix_without_property_x(n)
print ij
print matrix
print matrix.shape
print 'Score: %.4f' % (float(matrix.shape[1])/matrix.shape[0])
if __name__ == '__main__':
main()
```
[Answer]
## 24/13 26/14 28/15 30/16 32/17 (C#)
**Edit:**
Deleted outdated info from my answer. I'm using mostly the same algorithm as Peter Taylor (**Edit:** looks like he is using a better algorithm now), although I've added some of my own optimizations:
* I've implemented "meet in the middle" strategy of searching for
column sets with the same vector sum (suggested by [this KennyTM's
comment](https://codegolf.stackexchange.com/questions/41021/find-highest-scoring-matrix-without-property-x#comment95758_41021)). This strategy improved memory usage a lot, but it's
rather slow, so I've added the `HasPropertyXFast` function, that
quickly checks if there are small set with equal sums before using
"meet in the middle" approach.
* While iterating through column sets in the `HasPropertyXFast`
function, I start from checking column sets with 1 column, then with
2, 3 and so on. The function returns as soon as the first collision
of column sums is found. In practice it means that I usually have to
check just a few hundreds or thousands of column sets rather than
millions.
* I'm using `long` variables to store and compare entire columns and
their vector sums. This approach is at least an order of magnitude
faster than comparing columns as arrays.
* I've added my own implementation of hashset, optimized for `long`
data type and for my usage patterns.
* I'm reusing the same 3 hashsets for the entire lifetime of the
application to reduce the number of memory allocations and improve
performance.
* Multithreading support.
Program output:
```
00000000000111011101010010011111
10000000000011101110101001001111
11000000000001110111010100100111
11100000000000111011101010010011
11110000000000011101110101001001
11111000000000001110111010100100
01111100000000000111011101010010
00111110000000000011101110101001
10011111000000000001110111010100
01001111100000000000111011101010
00100111110000000000011101110101
10010011111000000000001110111010
01001001111100000000000111011101
10100100111110000000000011101110
01010010011111000000000001110111
10101001001111100000000000111011
11010100100111110000000000011101
Score: 32/17 = 1,88235294117647
Time elapsed: 02:11:05.9791250
```
Code:
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
const int MaxWidth = 32;
const int MaxHeight = 17;
static object _lyndonWordLock = new object();
static void Main(string[] args)
{
Stopwatch sw = Stopwatch.StartNew();
double maxScore = 0;
const int minHeight = 17; // 1
for (int height = minHeight; height <= MaxHeight; height++)
{
Console.WriteLine("Row count = " + height);
Console.WriteLine("Time elapsed: " + sw.Elapsed + "\r\n");
int minWidth = Math.Max(height, (int)(height * maxScore) + 1);
for (int width = minWidth; width <= MaxWidth; width++)
{
#if MULTITHREADING
int[,] matrix = FindMatrixParallel(width, height);
#else
int[,] matrix = FindMatrix(width, height);
#endif
if (matrix != null)
{
PrintMatrix(matrix);
Console.WriteLine("Time elapsed: " + sw.Elapsed + "\r\n");
maxScore = (double)width / height;
}
else
break;
}
}
}
#if MULTITHREADING
static int[,] FindMatrixParallel(int width, int height)
{
_lyndonWord = 0;
_stopSearch = false;
int threadCount = Environment.ProcessorCount;
Task<int[,]>[] tasks = new Task<int[,]>[threadCount];
for (int i = 0; i < threadCount; i++)
tasks[i] = Task<int[,]>.Run(() => FindMatrix(width, height));
int index = Task.WaitAny(tasks);
if (tasks[index].Result != null)
_stopSearch = true;
Task.WaitAll(tasks);
foreach (Task<int[,]> task in tasks)
if (task.Result != null)
return task.Result;
return null;
}
static volatile bool _stopSearch;
#endif
static int[,] FindMatrix(int width, int height)
{
#if MULTITHREADING
_columnSums = new LongSet();
_left = new LongSet();
_right = new LongSet();
#endif
foreach (long rowTemplate in GetLyndonWords(width))
{
int[,] matrix = new int[width, height];
for (int x = 0; x < width; x++)
{
int cellValue = (int)(rowTemplate >> (width - 1 - x)) % 2;
for (int y = 0; y < height; y++)
matrix[(x + y) % width, y] = cellValue;
}
if (!HasPropertyX(matrix))
return matrix;
#if MULTITHREADING
if (_stopSearch)
return null;
#endif
}
return null;
}
#if MULTITHREADING
static long _lyndonWord;
#endif
static IEnumerable<long> GetLyndonWords(int length)
{
long lyndonWord = 0;
long max = (1L << (length - 1)) - 1;
while (lyndonWord <= max)
{
if ((lyndonWord % 2 != 0) && PrecedesReversal(lyndonWord, length))
yield return lyndonWord;
#if MULTITHREADING
lock (_lyndonWordLock)
{
if (_lyndonWord <= max)
_lyndonWord = NextLyndonWord(_lyndonWord, length);
else
yield break;
lyndonWord = _lyndonWord;
}
#else
lyndonWord = NextLyndonWord(lyndonWord, length);
#endif
}
}
static readonly int[] _lookup =
{
32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17,
0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18
};
static int NumberOfTrailingZeros(uint i)
{
return _lookup[(i & -i) % 37];
}
static long NextLyndonWord(long w, int length)
{
if (w == 0)
return 1;
int currentLength = length - NumberOfTrailingZeros((uint)w);
while (currentLength < length)
{
w += w >> currentLength;
currentLength *= 2;
}
w++;
return w;
}
private static bool PrecedesReversal(long lyndonWord, int length)
{
int shift = length - 1;
long reverse = 0;
for (int i = 0; i < length; i++)
{
long bit = (lyndonWord >> i) % 2;
reverse |= bit << (shift - i);
}
for (int i = 0; i < length; i++)
{
if (reverse < lyndonWord)
return false;
long bit = reverse % 2;
reverse /= 2;
reverse += bit << shift;
}
return true;
}
#if MULTITHREADING
[ThreadStatic]
#endif
static LongSet _left = new LongSet();
#if MULTITHREADING
[ThreadStatic]
#endif
static LongSet _right = new LongSet();
static bool HasPropertyX(int[,] matrix)
{
long[] matrixColumns = GetMatrixColumns(matrix);
if (matrixColumns.Length == 1)
return false;
return HasPropertyXFast(matrixColumns) || MeetInTheMiddle(matrixColumns);
}
static bool MeetInTheMiddle(long[] matrixColumns)
{
long[] leftColumns = matrixColumns.Take(matrixColumns.Length / 2).ToArray();
long[] rightColumns = matrixColumns.Skip(matrixColumns.Length / 2).ToArray();
if (PrepareHashSet(leftColumns, _left) || PrepareHashSet(rightColumns, _right))
return true;
foreach (long columnSum in _left.GetValues())
if (_right.Contains(columnSum))
return true;
return false;
}
static bool PrepareHashSet(long[] columns, LongSet sums)
{
int setSize = (int)System.Numerics.BigInteger.Pow(3, columns.Length);
sums.Reset(setSize, setSize);
foreach (long column in columns)
{
foreach (long sum in sums.GetValues())
if (!sums.Add(sum + column) || !sums.Add(sum - column))
return true;
if (!sums.Add(column) || !sums.Add(-column))
return true;
}
return false;
}
#if MULTITHREADING
[ThreadStatic]
#endif
static LongSet _columnSums = new LongSet();
static bool HasPropertyXFast(long[] matrixColumns)
{
int width = matrixColumns.Length;
int maxColumnCount = width / 3;
_columnSums.Reset(width, SumOfBinomialCoefficients(width, maxColumnCount));
int resetBit, setBit;
for (int k = 1; k <= maxColumnCount; k++)
{
uint columnMask = (1u << k) - 1;
long sum = 0;
for (int i = 0; i < k; i++)
sum += matrixColumns[i];
while (true)
{
if (!_columnSums.Add(sum))
return true;
if (!NextColumnMask(columnMask, k, width, out resetBit, out setBit))
break;
columnMask ^= (1u << resetBit) ^ (1u << setBit);
sum = sum - matrixColumns[resetBit] + matrixColumns[setBit];
}
}
return false;
}
// stolen from Peter Taylor
static bool NextColumnMask(uint mask, int k, int n, out int resetBit, out int setBit)
{
int gap = NumberOfTrailingZeros(~mask);
int next = 1 + NumberOfTrailingZeros(mask & (mask + 1));
if (((k - gap) & 1) == 0)
{
if (gap == 0)
{
resetBit = next - 1;
setBit = next - 2;
}
else if (gap == 1)
{
resetBit = 0;
setBit = 1;
}
else
{
resetBit = gap - 2;
setBit = gap;
}
}
else
{
if (next == n)
{
resetBit = 0;
setBit = 0;
return false;
}
if ((mask & (1 << next)) == 0)
{
if (gap == 0)
{
resetBit = next - 1;
setBit = next;
}
else
{
resetBit = gap - 1;
setBit = next;
}
}
else
{
resetBit = next;
setBit = gap;
}
}
return true;
}
static long[] GetMatrixColumns(int[,] matrix)
{
int width = matrix.GetLength(0);
int height = matrix.GetLength(1);
long[] result = new long[width];
for (int x = 0; x < width; x++)
{
long column = 0;
for (int y = 0; y < height; y++)
{
column *= 13;
if (matrix[x, y] == 1)
column++;
}
result[x] = column;
}
return result;
}
static int SumOfBinomialCoefficients(int n, int k)
{
int result = 0;
for (int i = 0; i <= k; i++)
result += BinomialCoefficient(n, i);
return result;
}
static int BinomialCoefficient(int n, int k)
{
long result = 1;
for (int i = n - k + 1; i <= n; i++)
result *= i;
for (int i = 2; i <= k; i++)
result /= i;
return (int)result;
}
static void PrintMatrix(int[,] matrix)
{
int width = matrix.GetLength(0);
int height = matrix.GetLength(1);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
Console.Write(matrix[x, y]);
Console.WriteLine();
}
Console.WriteLine("Score: {0}/{1} = {2}", width, height, (double)width / height);
}
}
class LongSet
{
private static readonly int[] primes =
{
17, 37, 67, 89, 113, 149, 191, 239, 307, 389, 487, 613, 769, 967, 1213, 1523, 1907,
2389, 2999, 3761, 4703, 5879, 7349, 9187, 11489, 14369, 17971, 22469, 28087, 35111,
43889, 54869, 68597, 85751, 107197, 133999, 167521, 209431, 261791, 327247, 409063,
511333, 639167, 798961, 998717, 1248407, 1560511, 1950643, 2438309, 3047909,
809891, 4762367, 5952959, 7441219, 9301529, 11626913, 14533661, 18167089, 22708867,
28386089, 35482627, 44353297, 55441637, 69302071, 86627603, 108284507, 135355669,
169194593, 211493263, 264366593, 330458263, 413072843, 516341057, 645426329,
806782913, 1008478649, 1260598321
};
private int[] _buckets;
private int[] _nextItemIndexes;
private long[] _items;
private int _count;
private int _minCapacity;
private int _maxCapacity;
private int _currentCapacity;
public LongSet()
{
Initialize(0, 0);
}
private int GetPrime(int capacity)
{
foreach (int prime in primes)
if (prime >= capacity)
return prime;
return int.MaxValue;
}
public void Reset(int minCapacity, int maxCapacity)
{
if (maxCapacity > _maxCapacity)
Initialize(minCapacity, maxCapacity);
else
ClearBuckets();
}
private void Initialize(int minCapacity, int maxCapacity)
{
_minCapacity = GetPrime(minCapacity);
_maxCapacity = GetPrime(maxCapacity);
_currentCapacity = _minCapacity;
_buckets = new int[_maxCapacity];
_nextItemIndexes = new int[_maxCapacity];
_items = new long[_maxCapacity];
_count = 0;
}
private void ClearBuckets()
{
Array.Clear(_buckets, 0, _currentCapacity);
_count = 0;
_currentCapacity = _minCapacity;
}
public bool Add(long value)
{
int bucket = (int)((ulong)value % (ulong)_currentCapacity);
for (int i = _buckets[bucket] - 1; i >= 0; i = _nextItemIndexes[i])
if (_items[i] == value)
return false;
if (_count == _currentCapacity)
{
Grow();
bucket = (int)((ulong)value % (ulong)_currentCapacity);
}
int index = _count;
_items[index] = value;
_nextItemIndexes[index] = _buckets[bucket] - 1;
_buckets[bucket] = index + 1;
_count++;
return true;
}
private void Grow()
{
Array.Clear(_buckets, 0, _currentCapacity);
const int growthFactor = 8;
int newCapacity = GetPrime(_currentCapacity * growthFactor);
if (newCapacity > _maxCapacity)
newCapacity = _maxCapacity;
_currentCapacity = newCapacity;
for (int i = 0; i < _count; i++)
{
int bucket = (int)((ulong)_items[i] % (ulong)newCapacity);
_nextItemIndexes[i] = _buckets[bucket] - 1;
_buckets[bucket] = i + 1;
}
}
public bool Contains(long value)
{
int bucket = (int)((ulong)value % (ulong)_buckets.Length);
for (int i = _buckets[bucket] - 1; i >= 0; i = _nextItemIndexes[i])
if (_items[i] == value)
return true;
return false;
}
public IReadOnlyList<long> GetValues()
{
return new ArraySegment<long>(_items, 0, _count);
}
}
```
Configuration file:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<gcAllowVeryLargeObjects enabled="true" />
</runtime>
</configuration>
```
] |
[Question]
[
A [boolean circuit](http://en.wikipedia.org/wiki/Boolean_circuit) in TCS is basically a [DAG](http://en.wikipedia.org/wiki/Directed_acyclic_graph) consisting of And, Or, Not gates, and by what is known is "functional completeness" they can compute all possible functions. eg this is the basic principle in an [ALU](http://en.wikipedia.org/wiki/Arithmetic_logic_unit).
>
> Challenge: create a circuit to determine whether an 8-binary-digit number is divisible by 3 and somehow visualize your result (ie in some kind of picture)
>
>
>
The judging criteria for voters is based on whether the code to generate the circuit *generalizes* nicely to arbitrary size numbers, and whether the algorithmically-created visualization is compact/balanced but yet still human-readable (ie visualization by hand arrangement not allowed). ie the visualization is for n=8 only but the code will ideally work for all 'n'. winning entry is just top voted.
Somewhat similar question: [Build a multiplying machine using NAND logic gates](https://codegolf.stackexchange.com/questions/12261/build-a-multiplying-machine-using-nand-logic-gates)
[Answer]
## Depth:7 (logarithmic), 18x AND, 6x OR, 7x XOR, 31 gates (linear)
Let me calculate the digit sum in base four, modulo three:

circuit drawn in [Logisim](http://ozark.hendrix.edu/~burch/logisim/)
Generalisation, formally (hopefully somewhat readable):
```
balance (l, h) = {
is1: l & not h,
is2: h & not l,
}
add (a, b) =
let aa = balance (a.l, a.h)
bb = balance (b.l, b.h)
in { l:(a.is2 & b.is2) | (a.is1 ^ b.is1),
h:(a.is1 & b.is1) | (a.is2 ^ b.is2)}
pairs [] = []
pairs [a] = [{h:0, l:a}]
pairs [rest.., a, b] = [pairs(rest..).., {h:a, l:b}]
mod3 [p] = p
mod3 [rest.., p1, p2] = [add(p1, p2), rest..]
divisible3 number =
let {l: l, h: h} = mod3 $ pairs number
in l == h
```
now in english:
While there are more than two bits in the number, take two lowest pairs of bits and sum them modulo 3, then append the result to the back of the number, then return if the last pair is zero modulo 3. If there is an odd number of bits in the number, add an extra zero bit to the top, then polish with constant value propagation.
Appending to the back instead of to the front ensures the addition tree is a balanced tree rather than a linked list. This, in turn, ensures logarithmic depth in the number of bits: five gates and three levels for pair cancellation, and an extra gate at the end.
Of course, if approximate planarity is desired, pass the top pair unmodified to the next layer instead of wrapping it to the front. This is easier said than implemented (even in pseudocode), however. If the number of bits in a number is a power of two (as is true in any modern computer system as of March 2014), no lone pairs will occur, however.
If the layouter preserves locality / performs route length minimisation, it should keep the circuit readable.
This Ruby code will generate a circuit diagram for any number of bits (even one). To print, open in Logisim and export as image:
```
require "nokogiri"
Port = Struct.new :x, :y, :out
Gate = Struct.new :x, :y, :name, :attrs
Wire = Struct.new :sx, :sy, :tx, :ty
puts "Please choose the number of bits: "
bits = gets.to_i
$ports = (1..bits).map {|x| Port.new 60*x, 40, false};
$wires = [];
$gates = [];
toMerge = $ports.reverse;
def balance a, b
y = [a.y, b.y].max
$wires.push Wire.new(a.x , a.y , a.x , y+20),
Wire.new(a.x , y+20, a.x , y+40),
Wire.new(a.x , y+20, b.x-20, y+20),
Wire.new(b.x-20, y+20, b.x-20, y+30),
Wire.new(b.x , b.y , b.x , y+10),
Wire.new(b.x , y+10, b.x , y+40),
Wire.new(b.x , y+10, a.x+20, y+10),
Wire.new(a.x+20, y+10, a.x+20, y+30)
$gates.push Gate.new(a.x+10, y+70, "AND Gate", negate1: true),
Gate.new(b.x-10, y+70, "AND Gate", negate0: true)
end
def sum (a, b, c, d)
y = [a.y, b.y, c.y, d.y].max
$wires.push Wire.new(a.x , a.y , a.x , y+40),
Wire.new(a.x , y+40, a.x , y+50),
Wire.new(a.x , y+40, c.x-20, y+40),
Wire.new(c.x-20, y+40, c.x-20, y+50),
Wire.new(b.x , b.y , b.x , y+30),
Wire.new(b.x , y+30, b.x , y+50),
Wire.new(b.x , y+30, d.x-20, y+30),
Wire.new(d.x-20, y+30, d.x-20, y+50),
Wire.new(c.x , c.y , c.x , y+20),
Wire.new(c.x , y+20, c.x , y+50),
Wire.new(c.x , y+20, a.x+20, y+20),
Wire.new(a.x+20, y+20, a.x+20, y+50),
Wire.new(d.x , d.y , d.x , y+10),
Wire.new(d.x , y+10, d.x , y+50),
Wire.new(d.x , y+10, b.x+20, y+10),
Wire.new(b.x+20, y+10, b.x+20, y+50)
$gates.push Gate.new(a.x+10, y+90, "XOR Gate"),
Gate.new(b.x+10, y+80, "AND Gate"),
Gate.new(c.x-10, y+80, "AND Gate"),
Gate.new(d.x-10, y+90, "XOR Gate")
$wires.push Wire.new(a.x+10, y+90, a.x+10, y+100),
Wire.new(b.x+10, y+80, b.x+10, y+90 ),
Wire.new(b.x+10, y+90, a.x+30, y+90 ),
Wire.new(a.x+30, y+90, a.x+30, y+100),
Wire.new(d.x-10, y+90, d.x-10, y+100),
Wire.new(c.x-10, y+80, c.x-10, y+90 ),
Wire.new(c.x-10, y+90, d.x-30, y+90 ),
Wire.new(d.x-30, y+90, d.x-30, y+100)
$gates.push Gate.new(d.x-20, y+130, "OR Gate"),
Gate.new(a.x+20, y+130, "OR Gate")
end
def sum3 (b, c, d)
y = [b.y, c.y, d.y].max
$wires.push Wire.new(b.x , b.y , b.x , y+20),
Wire.new(b.x , y+20, b.x , y+30),
Wire.new(b.x , y+20, d.x-20, y+20),
Wire.new(d.x-20, y+20, d.x-20, y+30),
Wire.new(c.x , c.y , c.x , y+60),
Wire.new(c.x , y+60, b.x+30, y+60),
Wire.new(b.x+30, y+60, b.x+30, y+70),
Wire.new(d.x , d.y , d.x , y+10),
Wire.new(d.x , y+10, d.x , y+30),
Wire.new(d.x , y+10, b.x+20, y+10),
Wire.new(b.x+20, y+10, b.x+20, y+30),
Wire.new(b.x+10, y+60, b.x+10, y+70)
$gates.push Gate.new(b.x+10, y+60 , "AND Gate"),
Gate.new(d.x-10, y+70 , "XOR Gate"),
Gate.new(b.x+20, y+100, "OR Gate" )
end
while toMerge.count > 2
puts "#{toMerge.count} left to merge"
nextToMerge = []
while toMerge.count > 3
puts "merging four"
d, c, b, a, *toMerge = toMerge
balance a, b
balance c, d
sum *$gates[-4..-1]
nextToMerge.push *$gates[-2..-1]
end
if toMerge.count == 3
puts "merging three"
c, b, a, *toMerge = toMerge
balance b, c
sum3 a, *$gates[-2..-1]
nextToMerge.push *$gates[-2..-1]
end
nextToMerge.push *toMerge
toMerge = nextToMerge
puts "layer done"
end
if toMerge.count == 2
b, a = toMerge
x = (a.x + b.x)/2
x -= x % 10
y = [a.y, b.y].max
$wires.push Wire.new(a.x , a.y , a.x , y+10),
Wire.new(a.x , y+10, x-10, y+10),
Wire.new(x-10, y+10, x-10, y+20),
Wire.new(b.x , b.y , b.x , y+10),
Wire.new(b.x , y+10, x+10, y+10),
Wire.new(x+10, y+10, x+10, y+20)
$gates.push Gate.new(x, y+70, "XNOR Gate")
toMerge = [$gates[-1]]
end
a = toMerge[0]
$wires.push Wire.new(a.x, a.y, a.x, a.y+10)
$ports.push Port.new(a.x, a.y+10, true)
def xy (x, y)
"(#{x},#{y})"
end
circ = Nokogiri::XML::Builder.new encoding: "UTF-8" do |xml|
xml.project version: "1.0" do
xml.lib name: "0", desc: "#Base"
xml.lib name: "1", desc: "#Wiring"
xml.lib name: "2", desc: "#Gates"
xml.options
xml.mappings
xml.toolbar do
xml.tool lib:'0', name: "Poke Tool"
xml.tool lib:'0', name: "Edit Tool"
end #toolbar
xml.main name: "main"
xml.circuit name: "main" do
$wires.each do |wire|
xml.wire from: xy(wire.sx, wire.sy), to: xy(wire.tx, wire.ty)
end #each
$gates.each do |gate|
xml.comp lib: "2", name: gate.name, loc: xy(gate.x, gate.y) do
xml.a name: "facing", val: "south"
xml.a name: "size", val: "30"
xml.a name: "inputs", val: "2"
if gate.attrs
gate.attrs.each do |name, value|
xml.a name: name, val: value
end #each
end #if
end #comp
end #each
$ports.each.with_index do |port, index|
xml.comp lib: "1", name: "Pin", loc: xy(port.x, port.y) do
xml.a name: "tristate", val: "false"
xml.a name: "output", val: port.out.to_s
xml.a name: "facing", val: port.out ? "north" : "south"
xml.a name: "labelloc", val: port.out ? "south" : "north"
xml.a name: "label", val: port.out ? "out" : "B#{index}"
end #port
end #each
end #circuit
end #project
end #builder
File.open "divisibility3.circ", ?w do |file|
file << circ.to_xml
end
puts "done"
```
finally, when asked to create an output for 32 bits, my layouter generates this. Admittedly, it's not very compact for very wide inputs:

[Answer]

The graph maintains 3 booleans at each level i. They represent the fact that the high-order i bits of the number are equal to 0, 1, or 2 mod 3. At each level we compute the next three bits based on the previous three bits and the next input bit.
Here's the python code that generated the graph. Just change N to get a different number of bits, or K to get a different modulus. Run the output of the python program through [dot](http://www.graphviz.org/) to generate the image.
```
N = 8
K = 3
v = ['0']*(K-1) + ['1']
ops = {}
ops['0'] = ['0']
ops['1'] = ['1']
v = ['0']*(K-1) + ['1']
for i in xrange(N):
ops['bit%d'%i] = ['bit%d'%i]
ops['not%d'%i] = ['not','bit%d'%i]
for j in xrange(K):
ops['a%d_%d'%(i,j)] = ['and','not%d'%i,v[(2*j)%K]]
ops['b%d_%d'%(i,j)] = ['and','bit%d'%i,v[(2*j+1)%K]]
ops['o%d_%d'%(i,j)] = ['or','a%d_%d'%(i,j),'b%d_%d'%(i,j)]
v = ['o%d_%d'%(i,j) for j in xrange(K)]
for i in xrange(4):
for n,op in ops.items():
for j,a in enumerate(op[1:]):
if ops[a][0]=='and' and ops[a][1]=='0': op[j+1]='0'
if ops[a][0]=='and' and ops[a][2]=='0': op[j+1]='0'
if ops[a][0]=='and' and ops[a][1]=='1': op[j+1]=ops[a][2]
if ops[a][0]=='and' and ops[a][2]=='1': op[j+1]=ops[a][1]
if ops[a][0]=='or' and ops[a][1]=='0': op[j+1]=ops[a][2]
if ops[a][0]=='or' and ops[a][2]=='0': op[j+1]=ops[a][1]
for i in xrange(4):
used = set(['o%d_0'%(N-1)])|set(a for n,op in ops.items() for a in op[1:])
for n,op in ops.items():
if n not in used: del ops[n]
print 'digraph {'
for n,op in ops.items():
if op[0]=='and': print '%s [shape=invhouse]' % n
if op[0]=='or': print '%s [shape=circle]' % n
if op[0]=='not': print '%s [shape=invtriangle]' % n
if op[0].startswith('bit'): print '%s [color=red]' % n
print '%s [label=%s]' % (n,op[0])
for a in op[1:]: print '%s -> %s' % (a,n)
print '}'
```
[Answer]
# 2×24 NOT, 2×10+5 AND, 2×2+5 OR, 2×2 NOR
This totally does not scale. Like not at all. Maybe I'll try to improve it.
I did test this for numbers up to 30 and it worked fine.
Those 2 big circuits are counting the number of active inputs:
* The upper right one counts the number of bits with an even power (zero to 4)
* The lower left one counts the number of bits with an odd power (zero to 4)
If the difference of those numbers is `0` or `3` the number is divisible by `3`. The lower right circuit basically maps each valid combination (`4,4`, `4,1`, `3,3`, `3,0`, `2, 2`, `1, 1`, `0, 0`) into an or.
The little circle in the middle is an LED that is on if the number if divisible by 3 and off otherwise.
[](https://i.stack.imgur.com/zLwH0.png)
] |
[Question]
[
The [exponential generating function](https://mathworld.wolfram.com/ExponentialGeneratingFunction.html) (e.g.f.) of a sequence \$a\_n\$ is defined as the [formal power series](https://mathworld.wolfram.com/FormalPowerSeries.html) \$f(x) = \sum\_{n=0}^{\infty} \frac{a\_n}{n!} x^n\$.
When \$a\_0 = 0\$, we can apply the exponential function \$\exp\$ on this formal power series:
\$\begin{align}
\exp(f(x)) &= \sum\_{n=0}^{\infty} \frac{1}{n!} f(x)^n \\
&= \sum\_{n=0}^{\infty} \frac{1}{n!} \left(\sum\_{m=1}^{\infty} \frac{a\_m}{m!} x^m\right)^n \\
&= \sum\_{n=0}^{\infty} \frac{b\_n}{n!} x^n \\
\text{where} \\
b\_0 &= 1 \\
b\_n &= \sum\_{k=1}^n \binom{n-1}{k-1} a\_k b\_{n-k} \text{ when } n>0
\end{align}\$
This is the exponential generating function of the sequence \$b\_n\$. If all \$a\_n\$ are integers, then all \$b\_n\$ are also integers. So this is a tranformation of integer sequences.
It seems that OEIS call this the Exponential transform. But I can't find a reference to its definition.
Here are some examples on OEIS:
* [A001477](https://oeis.org/A001477) (the nonnegative integers, \$0,1,2,3,4,\dots\$) -> [A000248](https://oeis.org/A000248) (\$1,1,3,10,41,\dots\$)
* [A001489](https://oeis.org/A001489) (the nonpositive integers, \$0,-1,-2,-3,-4,\dots\$) -> [A292952](https://oeis.org/A292952) (\$1, -1,-1,2,9,\dots\$)
* [A000045](https://oeis.org/A000045) (Fibonacci numbers, \$0,1,1,2,3,\dots\$) -> [A256180](https://oeis.org/A256180) (\$1,1,2,6,21,\dots\$)
* [A160656](https://oeis.org/A160656) (\$0\$ and the odd primes, \$0,3,5,7,11,\dots\$) -> [A353079](https://oeis.org/A353079) (\$1,3,14,79,521,\dots\$)
* [A057427](https://oeis.org/A057427) (\$0,1,1,1,1,\dots\$) -> [A000110](https://oeis.org/A000110) (Bell numbers, \$1,1,2,5,15,\dots\$)
## Task
Given a finite integer sequence, compute its Exponential transform.
The length of the input sequence is always greater than \$0\$. Its \$0\$th term is always \$0\$. You can omit the leading \$0\$ in the input.
If the input sequence has length \$n\$, you only need to output the first \$n\$ terms of the output sequence.
Input and output can be in any reasonable format, e.g., a list, an array, a polynomial, a function that takes \$i\$ and returns the \$i\$th term (0-indexed or 1-indexed), etc.
You may also take the input sequence and an integer \$i\$, and output the \$i\$th term (0-indexed or 1-indexed) of the output sequence.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Example Python code
This example code uses the above recurrence formula. There are other formulas that might give shorter answers.
```
import math
def exponential_transform(a):
b = [0] * len(a)
b[0] = 1
for i in range(1, len(a)):
b[i] = sum(math.comb(i-1, j-1) * a[j] * b[i - j] for j in range(1, i + 1))
return b
```
## Testcases
```
[0, 0, 0, 0, 0] -> [1, 0, 0, 0, 0]
[0, 1, 0, -1, 0, 1, 0, -1] -> [1, 1, 1, 0, -3, -8, -3, 56]
[0, 1, 2, 3, 4, 5, 6, 7] -> [1, 1, 3, 10, 41, 196, 1057, 6322]
[0, -1, -2, -3, -4, -5, -6, -7] -> [1, -1, -1, 2, 9, 4, -95, -414]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] -> [1, 1, 2, 6, 21, 86, 404, 2121, 12264, 77272, 525941]
[0, 3, 5, 7, 11, 13, 17, 19] -> [1, 3, 14, 79, 521, 3876, 31935, 287225]
[0, 1, 1, 1, 1, 1] -> [1, 1, 2, 5, 15, 52]
[0, 1, 2, 5, 15, 52] -> [1, 1, 3, 12, 60, 358]
[0, 1, 3, 12, 60, 358] -> [1, 1, 4, 22, 154, 1304]
[0, 1, 4, 22, 154, 1304] -> [1, 1, 5, 35, 315, 3455]
[0, 1, 5, 35, 315, 3455] -> [1, 1, 6, 51, 561, 7556]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ ~~20~~ ~~18~~ 16 bytes
```
L©ææʒ˜{®Q}€€gèPO
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f59DKw8sOLzs16fSc6kPrAmsfNa0BovTDKwL8//835oo20FEw1lEw1VEw11EwNARiIM8QxLaMBQA "05AB1E – Try It Online")
Returns the \$ i \$-th term, zero indexed. It runs in complexity \$ \Omega(2^{2^i}) \$, so it can only work in a reasonable time for \$ i \leq 4 \$.
# Explanation
We will define \$ c\_n = \frac{a\_n x^n}{n!} \$.
In the expression
$$ \left(\sum\_{m=1}^{\infty} \frac{a\_m}{m!} x^m\right)^n = \left(\sum\_{m=1}^{\infty} c\_m\right)^n $$
we know from the multinomial theorem that the coefficient of
\$ \prod {c\_m ^ {k\_m}} \$
is
$$ \frac{n!}{\prod{k\_m !}} $$
The \$ n! \$ cancels with the \$ \frac{1}{n!} \$ in \$ \sum\_{n=0}^{\infty} \frac{1}{n!} \left(\sum\_{m=1}^{\infty} \frac{a\_m}{m!} x^m\right)^n \$, so we get
$$ \exp(f(x)) = \sum \frac{\prod{c\_m ^ {k\_m}}}{\prod{k\_m!}} $$
If the exponent of \$ x \$ in the equation is \$ j \$, we get that \$ \sum k\_m m = j \$. If we create a sequence \$ d\_m \$ by repeating \$ m \$ \$ k\_m \$ times, we get that \$ d\_m \$ is a partition of \$ j \$.
Now that we have a mathematical expression for how much time each partition of \$ i \$ occurs, we can think of a combinatorical one.
By playing with equations, we can find out that the coefficient of \$ \prod {a\_{d\_i}} \$ is the number of unique ways to divide a set with \$ j \$ elements to sets of sizes \$ d\_i \$. Therefore, we can generate a set of size \$ j \$, list all of its separations to other sets, take the size of each set in those separations, index that size to \$ a \$, take the product of each, and take the total sum.
```
L push the list 1...input index
© save it in register ® (without popping)
æ take its powerset
æ take the powerset's powerset
ʒ and only keep sets such that
˜ if you flatten them
{ and sort the result
® and then push the original list
Q they compare equal
}
€ for each of those sets
€ map each of its sets
g to its size
è index that size into the input list
P take the product of each list
O and take the sum
```
If the index is 0, `L` returns `[1, 0]`, and no array sorted can be equal to it, so the filter returns an empty list. The map and index then do nothing, then `P` multiplies it to get `1`, which `O` preserves.
[Answer]
# [Haskell](https://www.haskell.org/), 59 bytes
```
f@(a:b)&g@(c:d)=a*c:zipWith(+)(b&g)(f&d)
_&_=[]
e b=1:e b&b
```
[Try it online!](https://tio.run/##bY7NCsJADITvfYo9Lbs6C92ftFoo@BYeRKS1rRZ/UU@@fE31pCuBIeTLTLKv7of2eByGbqGqotZyt1DbotFlNdkWz/667B97NdWqljutOtnoZCM35WqdtKIubcEq6@FU9WdRiuaSCHG99eeHUK1YpXjXWn9NLc/MKJ8mog4eAYQM@Q9jl3EwHibAEEwGk0f2TwBhBuvhLDxn0c/WyHNYO65YbuZ/Ut715zmCJZCLCCc5ZCk8zSIW4BzbAt9LQ0SJPfCc6sP46fAC "Haskell – Try It Online")
`e` accepts the sequence as a list of integers without the leading 0.
If \$f(x)\$ is the e.g.f. of \$a\_n\$, then \$f(0) = a\_0\$ and \$f'(x)\$ is the e.g.f. of \$a\_{n + 1}\$. So this program is a direct encoding of the product rule \$[f(x)g(x)]' = f'(x)g(x) + f(x)g'(x)\$ and the chain rule \$[e^{f(x)}]' = e^{f(x)}f'(x)\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 24 bytes
```
BellY[#,,#2]~Sum~{,0,#}&
```
[Try it online!](https://tio.run/##LU9dasJAEH7PKRYDkugnZnezKoIllD4WWupTCXmYyiYGki2YLW0J8RC9QU/YI6TrKgPDfD/zMdOSPeqWbH2g8aks8/23sfS13U4O7@2kYNGMPdQdvTWaOR/7pJOpTcVmcRCUu/FeN81rHgKhKM77j/bcI0E4TEerO9uxHev7BL4G9BwCEikUVlh7nGBxadfBM1ePwgZcQnBIZ1c3xdctR4ErKOGRBBdYJZBq43EKIZycuogk9YxyGqTbkKlLG4KI/n5@n0@1sTkt7qIyD90dVEyX2QuZSmcRnz9qU9ljRnFcxGyZMf/Q@A8 "Wolfram Language (Mathematica) – Try It Online")
Based on the Mathematica code given by [Vladimir Reshetnikov](https://oeis.org/wiki/User:Vladimir_Reshetnikov) on OEIS [A256180](https://oeis.org/A256180). Takes the 0-indexed item to output and the list.
*-13 bytes thanks to alephalpha*
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `R`, 16 bytes
```
ṗṗ'fs¹ɾ⁼;vvLİvΠ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJSIiwiIiwi4bmX4bmXJ2ZzwrnJvuKBvDt2dkzEsHbOoOKIkSIsIiIsIjNcblswLCAxLCA1LCAzNSwgMzE1LCAzNDU1XSJd)
Port of Command Master's 05AB1E answer, upvote that!
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), ~~103~~ 92 bytes
saved 11 bytes thanks to the comment of @alephalpha
Golfed vesrion, [try it online!](https://tio.run/##dZDdboMwDIXv9xRWdxM6R8KBAF2Vt9gd4iJUtApaWwRsr8@csR8QqRQriXU@H9ud7Z28dNN0FjYytflsTuO9F88WHcbRsS6pMnQ8c8oZhZyuS1eZ4eMqWkPoJGHtbvers@/CSYWtpGhvy/aFqj0rZVtFXGTqencbxe6tGUY42aEBeoUdwlmUMcL/8eKnjVYttPQtlPP1@wljyRpTCAlCiqARMoQ8DKULyLvwSCCZkwxKJiWj8gGr14Z/nowV/OWX4lziW9DhCtmiwgzmDNIMk38fwmC@sf45YXmxWQ1bEYdWYeCwBnw3DGW@TV2EEYrXDI@tlHdJ/Thx@oCiNaW9A4dvLknnvU1f)
```
f(a)=b=vector(#a,i,0);b[1]=1;for(i=2,#a,b[i]=sum(j=1,i-1,binomial(i-2,j-1)*a[j+1]*b[i-j]));b
```
Ungolfde version, modified from the provided Python example code
```
exponential_transform(a) = {
b = vector(#a, i, 0); \\ Initialize b as a zero vector of the same length as a
b[1] = 1; \\ Set the first element of b to 1
for(i=2, #a,
b[i] = sum(j=1, i-1, binomial(i-2, j-1) * a[j+1] * b[i-j])
);
return(b);
}
print("Test case 1: ", exponential_transform([0, 0, 0, 0, 0]));
print("Test case 2: ", exponential_transform([0, 1, 0, -1, 0, 1, 0, -1]));
print("Test case 3: ", exponential_transform([0, 1, 2, 3, 4, 5, 6, 7]));
print("Test case 4: ", exponential_transform([0, -1, -2, -3, -4, -5, -6, -7]));
print("Test case 5: ", exponential_transform([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
print("Test case 6: ", exponential_transform([0, 3, 5, 7, 11, 13, 17, 19]));
print("Test case 7: ", exponential_transform([0, 1, 1, 1, 1, 1]));
print("Test case 8: ", exponential_transform([0, 1, 2, 5, 15, 52]));
print("Test case 9: ", exponential_transform([0, 1, 3, 12, 60, 358]));
print("Test case 10: ", exponential_transform([0, 1, 4, 22, 154, 1304]));
print("Test case 11: ", exponential_transform([0, 1, 5, 35, 315, 3455]));
```
[Answer]
# [Python](https://www.python.org), 85 bytes
```
import math
f=lambda n,l:sum(math.comb(n-1,i)*l[i]*f(n-i-1,l)for i in range(n))+(n<1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZBBboMwEEX3nGKUlZ18KmzjBEWlt-gKsSAtbiyBQeAsepZusmnv1Jt0WWPophrJ8vsz_vb3x9f47q-Du98_b96kxfez7cdh8tQ3_pqYsmv6y2tDDt15vvVsUR9ehv7CXCpg-b6rbL03gWzgjpthIkvW0dS4t5Y5zg_MPQq-mf_4dvYzlVRVGWLVqAQkFHJoHHGKnCFdlnUTlXVGo4BQkAIqjOutE2vz0RAaWkZSEBLHDEoXkXNIGdp5sMjyqOjQgwonVB7d1jtOEMFQ1XWSLHH8Eie--5wQjZN1nnnQrnzagaqFDLMgzzn9S9-1jnl-ELze8v998i8)
Doesn't take the leading zero in the input. If that's not allowed, I will change.
Based on the Maple code given by [Alois P. Heinz](https://oeis.org/wiki/User:Alois_P._Heinz) in [A007446](https://oeis.org/A007446) and [A353079](https://oeis.org/A353079).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
FLθ⊞υ∨¬ιΣEυ××κ§θ⁻ιλ∨¬λ÷Π…⁻ιλιΠ…·¹λIυ
```
[Try it online!](https://tio.run/##TYzLCsIwEEX3fsUsJxDBrl2Jbgo@irorXYQ0toNpYvMo/n1sLUovw3Dnca5shZNW6JQe1gEelWlCiz1jUETfYuRwcXi2AYlxuMUOT@I1be/UKY9zf3LYhdzU6o09hxOZ6JE4aMbYH9ejzU040EC1wsLZOsqAV2EahQuCA03Q754bqaOnQc2P2Rz61XZVODIB98IHjOOcUlluOGTLqqq0HvQH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: A translation of the recurrence formula given in the question, except the subscript of `b` is used as the loop index, and the combination has to be written out as a ratio of products of ranges.
33 bytes using the newer version of Charcoal on ATO:
```
FLθ⊞υ∨¬ιΣEυ××κ§θ⁻ιλ÷Π…⁻ιλιΠ…·¹λIυ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY89CsJAEIV7TzGkmoUNaCdYiTYBf4LahRTrZmMG40b3J3gXGwtFD-BlvI2GKGR4DLw33wzM5SkLYWQlyuv17l0eDt-vvDKAM6V3rsATYxB7W6DnsDS4qBwS47D2B5yLY5Nu6KAstn3PYewinakznjjMSXuLxKFk7LsTaTelmjKFsakyLx2uhN4p7GAcqCH_80jL0luqVQsO2ktNjXqxIe1wIqxD__U3u5X298EjCcK6DNJXkvQ5DLpK0xb5AA "Charcoal – Attempt This Online") Link is to verbose version of code.
] |
[Question]
[
Your task is to make a bidirectional compressor. It takes a list of bytes as input and returns a list of bytes as output. It has the property than whenever it is iterated twice it returns the original input.
In other words, if `f` is your program as a function, then `f(f(x))=x` for all `x`.
Now, since this is a "compressor", it should actually try to compress it's input. Of course, it can't compress every input. It should however be able to compress your program's source code. That is, if `s` is your program's source code, then `len(f(s))<len(s)`.
To recap, your program acts as a function that takes a list of bytes as input and outputs a list of bytes as output. Let's call your program `f` and it's source code `s`. Your program must satisfy both:
* `f(f(x)) = x` for all `x`
* `len(f(s)) < len(s)`
Remember that the empty list is a list, and thus your code should be able to handle it.
Normal quine rules apply, so no introspection is allowed (opening the file that contains your source code, etc.).
Shortest code wins!
[Answer]
# JavaScript (ES6), 26 bytes
*-1 thanks to @thejonymyster*
*-7 thanks to @Arnauld*
*-4 thanks to @l4m2*
```
x=>x.replace(/-2|1/,z=>~z)
```
Swaps the first instance of `-2` and `1`, saving 1 byte when the program compresses itself. Takes the list of bytes as input, as a string.
This is quite the community effort now :p
[Answer]
# [R](https://www.r-project.org/), ~~102~~ 59 bytes
```
function(x)`if`(nchar(x)%%2,sub("#$","",x),sub("$","#",x))#
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjMhMy1BIy85I7EIyFFVNdIpLk3SUFJWUdJRUtKp0IRwQTxlEFdT@X9uZUFRfrqtOgVmqHOlaUCM0QSy4GxNLi5lheSM1OTsYisUcVtbCEtBWSEkKNSVC2IVQt4GIgDlQlX9BwA "R – Try It Online")
`f()` removes any trailing `#` comment character if there are an odd number of characters in the input (as in `myprog`), or adds one if there are an even number.
([Removing the first `f`](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjMhMy1BIy85I7EIyFFVNdIpLk3SUIpT0lFKU9Kp0IRygWwlEFfzf25lQVF@uq06@Uaoc6VpQEzRBLLgbE0uLmWF5IzU5OxiKxRxW1sIS0FZISQo1JULYhNC3gYiAOVCVf0HAA) would also work, and is 1-byte shorter, but it's less satisfying as the 'compressed' function is no longer a runnable compression function itself...)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 49 bytes
```
A;f(char*s){s[-1]=65;A=s[A=*s==65]-59?s:s-1+A*2;}
```
[Try it online!](https://tio.run/##S9ZNT07@/9/ROk0jOSOxSKtYs7o4Wtcw1tbM1NrRtjja0Var2BbIidU1tbQvtirWNdR21DKyrv0PUq1QXFIUbWhgEGvNpZySmpaZlwoSUdAAEtommlyZeSUKuYmZeRqaCtVcCkAAFE8uqARJ6ygoGRoZm5gqaVqDZQpKS4o10kAymlARFLWO1qSoxqe49j8A "C (gcc) – Try It Online")
[Surculose Sputum's idea](https://codegolf.stackexchange.com/a/241354/)
# [C (gcc)](https://gcc.gnu.org/), ~~55~~ ~~54~~ 52 bytes
```
A;f(char*s){A=*s-(s[-1]=65)?s-1:*++s-65?s:f(s+1)-2;}
```
[Try it online!](https://tio.run/##lYuxCoMwFEV3vyLYJc80YKxxMIjkO8RBUtNmMIjPDkX89tSULl0KfcMdzjnP8JsxIWhlqbkPS4aw6SZDTrHjom8qCS1yUWeMIa9ki7WlyATwQu0hPhBcl07kea@S03W0zo@REHoMKyFxfiXT4DwFsiXkuIOb@Rn1maSiuJQyBfU282NFaqOBD/lq9V/xr3oPLw "C (gcc) – Try It Online")
Thank gastropner for -2 bytes
Requires `s[-1]` be writable
[Answer]
# [Zsh](https://www.zsh.org/), 35 bytes
```
printf %s ${1/(#m)(-3|2)/$[~MATCH]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwdaSIgXdFIWYmDwbG_XU_DR1u-T8lNSlpSVpuhY3lQuKMvNK0hRUixVUqg31NZRzNTV0jWuMNPVVout8HUOcPWJroUqvAvVycRWV5mloJufn5ibmpSgAjVfQVdHNV0itKEnNS0lNSc_JT1IAGa-gpGKoxMVlA-ZYK6QmZ-SDtAKFNSBimkqoomiScGmwvDEyxwhJoy6KjC6KFJocmiRMFuK5BQsgNAA)
Previous version [independently discovered to l4m2's golf to Redwolf's answer, goddamn ninjas!](https://chat.stackexchange.com/transcript/message/60184082#60184082) (now just a lazy port :/)
Swaps the first instance of `-3` for `2` and vice versa.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 37 bytes
```
'¯2|1'⎕R{⍕83⎕Dr~11⎕Dr⍎⍵.Match}⍠'ML'1⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE9QPrTeqMVQHcoKqH/VOtTAGslyK6gwNwfSj3r5HvVv1fBNLkjNqH/UuUPf1UTd81LUIKPn/v4K6OlQ30dpB@sEGKKg/6p2rUFKeDzREIS2/SCG1ODmxIDMvXUFdITNPoSQjFUgVlJYoAAA "APL (Dyalog Unicode) – Try It Online")
Same thing as everyone else here has done replaces ¯1 with 1 and vice versa
and it works this time for sure :D
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 18 bytes
```
1`-1|(2)
$#1$*-$.&
```
[Try it online!](https://tio.run/##K0otycxL/P/fMEHXsEbDSJNLRdlQRUtXRU8NmxgA "Retina 0.8.2 – Try It Online") Explanation: Port of @RedwolfPrograms' JavaScript answer.
```
1`
```
Only replace the first match.
```
-1|(2)
```
Match `-1` or `2`.
```
$#1$*-
```
Output `-` only if `2` was matched.
```
$.&
```
Output the length of the match.
[Answer]
# Haskell, 54 bytes
```
f('l':')':l)='!':l;f('!':l)="l)"++l;f(x:l)=x:f l;f_=[]
```
[Try it Online!](https://tio.run/##y0gszk7Nyfn/P01DPUfdSl1T3SpH01ZdEUhZA4UUwVylHE0lbW2QQAWIW2GVpgDkxNtGx/7PTczMsy0oLQkuKVJJU1HCZ0oM0JgYHOYo/QcA)
Switches the first occurrence of `l)` and `!`.
[Answer]
# [Python 3](https://docs.python.org/3/), 48 bytes
*Thanks @AnttiP for pointing out the error in a previous version.*
```
lambda s:['l'+s,s[1:],s][('l'+s[:2]).find('la')]
```
[Try it online!](https://tio.run/##fZC9TsMwFIV3P8WhHRKLqBIgMURkYGFi7IAURcgk142RY0e2Q@nTBydNpFIkJvt@99y/059Ca83DWNuGUGCz2YxadB@NgM/LRCe3PvPlXV5lvirTOS7z@4rvpDJNjEXCqzEW7Xxwqk85Y1vs3QlHFVqEliAHUwdlDeYBwkOZfghMxln0JXQ6Yc5q2/WOvKcmcrnAhv7gNeSsd8qERbj@r7OXDVZ23pB8OK8otMa0ujl4WAlN5hDpEx5xbMkRSNQt6lY4UQdyUB4Uy@LvNcMzrMMbk852UDEbrNXxvq63LqB3thnqwOKA9@CGydt9fJiMNSaaACfMgdJHnjNggpMza1WaCP2dZI56EqEwswZRUSBJdp9WmdTzGV0ZtNB/jZsESsZmN8Uv4XkGsD37tLQCLg54EdrT4uOK@fgD "Python 3 – Try It Online")
Takes in a string and compress/decompress it.
* If the input starts with `a`, prepends `l`
* If the input starts with `la`, then remove the first character `l`.
* Otherwise, returns the input unchanged
`('l'+s[:2]).find('la')` evaluates to 0, 1, -1 for each of the above case respectively. This is because by prepending `l` to the first 2 characters, we get `l??`. If we find `la` at the 0th index (`la?`), then the first character of input must be `a`. If we finds `la` at the 1st index (`lla`), then the input must starts with `la`.
] |
[Question]
[
*From [my CMC](https://chat.stackexchange.com/transcript/message/59600689#59600689).*
Given a regex and a non-empty printable ASCII text, return one bit per character in the text, indicating the positions of beginnings of non-overlapping matches, and also the positions of beginnings of sequences that are not part of any non-overlapping matches.
You can:
* take the regex as a regex object, string or any other way that is reasonable or allowed by default rules
* take the text as a string object, character list, or any other way that is reasonable or allowed by default rules
* return the bits as an array, integer, or any other way that is reasonable or allowed by default rules
You may use any flavour, library, or implementation for regexes, as long as you support:
* any-character wildcards, e.g. `.`
* positive and negative character classes, e.g. `[ab]` and `[^ab]`
* repetitions, e.g. `a?` and `a+` and `a*` and/or the general `a{m,n}` form
* capturing groups, e.g. `(ab)`
* alternatives, e.g. `a|b`
## Examples
`[0123456789]+` or `[0123456789]{1,}`
`Hello4the42`
`10000110010`
`(aa)+` or `(aa){1,}`
`aaaaaaa`
`1000001`
`aaa`
`baaaab`
`110010`
`aaa|b`
`baaaab`
`110011`
`aab?` or `aab{0,1}`
`baaaab`
`110100`
`x.*z` or `x.{0,}z`
`abcdef`
`100000`
(you can take this as `(?:)` if necessary)
`Hello`
`11111`
`[^aeiou]+` or `[^aeiou]{1,}`
`Hello, world!`
`1110110011000`
`aaa`
`aaaaaaa`
`1001001`
`10101`
`101010101`
`100001000`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 [bytes](https://github.com/abrudz/SBCS)
Assumes an index origin of 0.
```
{(⍳≢⍵)∊0,∊+\¨⍺⎕S 0 1⊢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rjUe/mR52LHvVu1XzU0WWgAyS0Yw6teNS761Hf1GAFAwXDR10g2dr/aY/aJjzq7QMKe/o/6mo@tN74UdtEkKIgZyAZ4uEZ/B8spwBUp2DApR5tYGhkbGJqZm5hGautrpCmoO6RmpOTb1KSkWpipM6lrpGYqAkUhwGgfCIEAOVApIICslwSSCYJIlWTpI5DKsleHbuuCj2tKlSpxKTklNQ0oBSyRRApsDuBMtFxiamZ@aWxUFfCZHQUyvOLclIU1QE "APL (Dyalog Unicode) – Try It Online")
`⍺⎕S 0 1⊢⍵`: **S**earch for matches of the regex `⍺` in the string `⍵`. For each each match return the number of characters before the match (0) and the length of the match (1).
`+\¨`: For each match, get the cumulative sums. This gives the 0-based starting index of the match and the first index after the match.
`∊`: Flatten into a single list of indices.
`0,`: Prepend a zero in case there was no match at the beginning.
`(⍳≢⍵)∊`: For each index of the string `⍵`, is it an element of this list?
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 86, 79 bytes
```
lambda r,s:(c:=1<<len(s)-1)|sum({c>>j for i in r.finditer(s)for j in i.span()})
```
[Try it online!](https://tio.run/##VZBRb4IwEMff@yk6ntqtI9S5zRHR1z0b39QlBUqsgUJKzRzIZ2c90Omapr3@7n/Xu6t@7L7UL7PK9Fm07XNRxKnAhtUhScKIz@e51KSmz5ye62NB2mSxOOCsNFhhpbHxM6VTZaVxGqAHoMqvK6EJ7Wi/jjzP2wR88jJ9fXuffeyesFPdg5azDn3KPC@ndi@nE8QDt7g7eYAQEYIOIWAMUjGuURZwBADFgGJ0jXKPc/wPDrp4CZnc3QaMd3d@p0Do5D824D/5zt01SMRJKrPLP66SZUjHOl0Eh4SbLyFVeby0dHnc2mH4uzR5@gDysR8@JIJ675qA7WbkRpYrS7yt3mqPIlVUpbHYSLSONhtz9cJP3jBoA4O2tyiP7gBbwOsdAnvFSM0oI4LRgYYINwxHuM2IkX5SFpXKJTGU1RT/pVx1CFdGaUsa1kQRGIJNKO1/AQ "Python 3.8 (pre-release) – Try It Online")
[Old version](https://tio.run/##VZBRb4IwEMff@ym6PrVbR6hzmyOir3s2vqlLCpRYA4UUzBzIZ2c90Omapr3@7n/Xuyt/6n1hXmal7dNw22cyjxKJLa@ClLQ0DkIxn2fK0Io9C3aujjlt48XigNPCYo21wdZLtUl0razTAD0A1V5VSkNZx4KoI/06JIRsfDF5mb6@vc8@dk/YKe9BK3iHPlWWFdN6r6YTJHy3hDuFjxCVkg0hYAxSOa5R5gsEAEWAInSNco9z9A8OumgJmdzd@lx0d36nQOjkPTbgP3nO3TVIRnGi0ss/rpJlwMY6XYSAhJsvqXRxvLR0edza4fi7sFnyAPKxHzEkgnrvmoDtZuTGlumakq3ZGsKQzsvC1tgqtA43G3v1wk9kGLaFYde3KMJ2gGvA6x0Ce8VpxRmnkrOBBgg3HIe4TalVXlzkpc4UtYxXDP@lXHUIl1abmja8CUPJ@l8 "Python 3.8 (pre-release) – Try It Online")
Takes a re object and a string and returns a string of 1s and 0s an integer that encodes the mask in binary.
Output is created by bitwise arithmetic. As we know the leftmost bit is set there are no worries about leading zeros. Ideally, we would like to `or`-reduce the set bits. As there is no short way to do this (is there?) we instead take the sum after eliminating any duplicates.
[Answer]
# [R](https://www.r-project.org/), 77 bytes
```
function(p,t,m=el(gregexpr(p,t))){T[c(m,m+attr(m,"m"))[m>0]]=1;T[1:nchar(t)]}
```
[Try it online!](https://tio.run/##lc7LDoIwEAXQvV9B6qajjRHFd3DtB7BriGlLERJaSBkT4@Pb0crex6xuJudmxnVGoCqOtrZ9aFE4PJY2K5Vu4y4/W4VlbWnDkJlYV/Tk9ElfGuc3AHBLuKKGmbFAdK9ADAHgZj9N0zjcJTzcWlUIRxHSx8dblPBpOJtHi@VqvUnHhJGDrqo6wkJHMwKDz10qBPiO6Oer94YR6a38Bd/lX/yPTy6T0dVzqTKdEwiGga2Dtxx0Tw "R – Try It Online")
Outputs `1` for starts of matches/non-matches, `NA` otherwise.
---
# [R](https://www.r-project.org/), ~~84~~ ~~86~~ 84 bytes
*Edit: thanks to pajonk for spotting a bug when there is no match*
```
function(p,t,l=0:nchar(t),m=el(gregexpr(p,t)))`[<-`(!l,c(m,m+attr(m,"m"))[m>0],1)[l]
```
[Try it online!](https://tio.run/##lc5NDoIwEAXgvafAuuloNYD4G3HtHQjRUquQtIWUMSHGu6OVPcqsXjLfy4xtNUeRn01pulAjt3guzLUQso7b28MILEpDK4ZMxf7eiJxbisB0LBW9W3mXTWXdGgAuyWF@oWPFBNVMzzii/QSiCUCij37KAkhU2nuSksQPwmW0Wm@2u3RGGDlJpcoIcxmFBEb9Xco5uA7v5qd3hpHM2ewf/MoG8QGfNIvp0/FMXOWNgDfxTOl95ah9Aw "R – Try It Online")
Outputs `1`/`0`.
```
function(p,t, # p = pattern, t = text,
m=el(gregexpr(p,t))) # m = positions of matches,
# with attribute "match.length" = lengths of matches
# (can be abbreviated as "m");
head(...,-1) # Return all except the last element of...
`[<-`( # assigning the elements of...
!0:nchar(t) # ...a vector of 1 followed by nchar(t) zeros...
c(m, # at the positions of the matches,
m+attr(m,"m") # and the positions immediately after the matches,
)[m>0] # (but ignoring the value of -1 assigned to 'no match')...
,1) # ...to 1
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~42~~ 36 bytes
```
~L$`^.*
0A`¶, ,S0`($&)
.
0
m`^.
1
¶
```
[Try it online!](https://tio.run/##K0otycxLNPyvr6d9aJuetn68hoZ7wv86H5WEOD0tLgPHhEPbdBR0gg0SNFTUNLn0uAy4coEyXIZch7Zx/f8fbWBoZGxiamZuYRmrzeWRmpOTb1KSkWpixKWRmKipzZUIASCaKwnESgIxa5IQnCR7GLtCT6uKKzEpOSU1jUtDE2IYV3RcYmpmfinMcB2F8vyinBRFAA "Retina – Try It Online") Link includes test suite which doesn't support empty regex, so `()` is used instead. Explanation:
```
L$`^.*
0A`¶, ,S0`($&)
```
Wrap the regex in a capturing group and prefix it with commands that delete the regex from the input and split the ASCII text on the regex, including only the first capturing group in the output. (This unfortunately still renumbers the other capturing groups. A similar problem applies to the `w` modifier in Retina itself, but at least Retina is able to avoid renumbering numbered capturing groups in that case.)
```
~`
```
Evaluate those commands on the original input.
```
.
0
```
Change all characters to `0`s.
```
m`^.
1
```
Change all characters at the beginning of lines to `1`s.
```
¶
```
Join everything back together.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 81 bytes
```
f=->r,s,a=0{s>''?[(a=((s=~r)!=0?a-1:[a-1,s[r].size].max))>0,*f[r,s[1..-1],a]]:[]}
```
[Try it online!](https://tio.run/##FctBDsIgEEDRq9RuCmagoF2RAAeZzIKqJC5MGogJ2tarY9m8/M1P7/lTa7TCJcgQrFqzGwaPLFjGsv0lfrLKB6ENHkDGRDI/vw@Sr1A4dwrOEY8VtZRCEwQig7TXpYs46st1GqEPc4vbvdm3cVm3spXOa6P2@gc "Ruby – Try It Online")
[Answer]
# [Python](https://www.python.org), 87 bytes
```
def f(s,p):
r=[i:=0]
for m in p.finditer(s):r+=m.span()
for x in s:yield i in r;i+=1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY87DsIwEET7nGJxZZMQQYeMXNBxA4ooSCG2YZF_2hgBZ6GhgTtxGxQB5Uhv3mjur3TLxxgej-c529nyvdXGguVDlYQsgFSDUs3bAmwk8IABUm0xaMyG-CAklcrXQ-oCF1_mOjKDvKFxGnAMtMJSLX56e1Cu83vdTdcyEYbMGatPEQNn8wVr-nZ09GPN8ulaCFGgT5EykCkOnG2Mc7GCSySnJ6wiU_fRJ3SGE2t2ncF4bksmxHftf-oD)
Takes a string and an [`re.Pattern` object](https://docs.python.org/3/library/re.html#re-objects), and returns a generator of booleans.
I'm really not happy with the last line; it seems like there must be a better way of doing it.
---
Explanation:
* `i:=0`: using the observation that the first bit is always set, we can abuse the initial definition of `r` to initialise `i` to `0` at the same time
* `for m in p.finditer(s):`: for every (non-overlapping) match of `p` inside `s`:
+ `r+=m.span()`: append the range of the match object - inclusive start, exclusive end. This is convenient, because we need to include a `1` for the start of every match, and after the end of every match.
If two matches are consecutive, this is not a problem, because it doesn't matter if the same value is added to the list twice (once for the end of the first, and once for the start of the second).
* Finally, output a generator of booleans for each index in the string's range according to whether that index is in the list `r`.
If a match occurs at the end of the string, an out-of-bounds index will be appended to `r`, but this also doesn't matter, because we only check indeces in `s`'s range.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 43 bytes
```
s1{g1~&l_j}{g1~=}w!ClFL`Fz?{L['0j.*'10sa}\m
```
[Try it online!](https://tio.run/##SyotykktLixN/Z@TVxD3v9iwOt2wTi0nPqsWxLCtLVd0znHzSXCrsq/2iVY3yNLTUjc0KE6sjcn9/z/awNDI2MTUzNzCMlabyyM1JyffpCQj1cQIAA "Burlesque – Try It Online")
```
s1 # Set 1 to be the RegEx
{g1 # Get the RegEx
~& # Partition based on the RegEx (PreMatch, Match, PostMatch)
l_j # Get PostMatch out of block and on top of the stack
}
{
g1~= # PostMatch still contains match to RegEx
}w! # While
ClFL # Collect results and flatten
`Fz? # Remove empty string(s)
{
L[ # Length
'0j.* # "0"*Len
'1 0 sa # Set first char to 1
}\m # Map and concatenate
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
s=>r=>[...s].map((_,i)=>s.replace(r,(...p)=>i=(v=p.at(-2)-i)&&v+p[0].length&&i)&&!i)
```
[Try it online!](https://tio.run/##lZLfT9swEMefl7/iKqTWpq2TlO4HdClCvGzT0HjgreomJ3USM9eOHCfQDf72zk6K1ELFqBXZyt35c1/f3S2taZloXpihVAu29o87HhzDtVCrlAsBKoULrenqiBpItVo6Z25MUZ75fsZNXsUkUUvfJCenfqFVoUoqhpoJanjNhlwu2D2X2XDJTK4WR4USDdZRLlWx0jzLDaAEwygYBXBDY7gwv7ks4ZsmLujq6w185wmTJbO/vvcjvmWJIQuWcsmubT6mzQo1ColNb5RZFWwAPWp6A/jrAdRUVOwM0komhisJ1CCJrecdgIQIrqjJidHW68wPDxBMnIungCR8hgDbqH4EJuclEUxmJt/1uysSpjsRGDQzlZZQyVbnormzMbrAmZxPrLbHgd3uNDc0FlajlcGchclqyXRrS6koG2OiZMqzSm@HPuKJ56XRuoymOprOCCHlnCxpgdCvAcfRtCSaFYImDOkBst7C2niE6qggtgzDER5y3O3W/WIWzDfau11n6nC8tglLJRgRKkMp6n1hQqixydl41MPInwXh6GT8/sPHT6fzvp/hJm0N0RT6NSa3ikvU62E8Ad@HMLArtHsYeM@otF2OiCjFr5K21xM1CJ8TY8eLHdCeb8VtiHsl7gAf4jcjn4CvKozP3y6xBVrkiyLGiZ0zB7wnx38OAzZF9Pb1uunJ@Rk@tIbhyxc3vAHcKS0WnWZ6flLGVTX/T79bXjs64R6dW9NzULPbh7tv/Q8 "JavaScript (Node.js) – Try It Online")
* `Array#at` is ES2022.
Could be [73 bytes](https://tio.run/##lZLfT9swEMefl7/iKqTWpqmTFPaDdilCvGzT0HjgDXWTkzqJmWtHjhPoVv72zk6KRKFicIoc@e78ua99d0MbWqWal2Yk1YJtgsOeB4dwKdQq40KAyuBMa7o6oAYyrZYuWBhTVpMgyLkp6oSkahmY9OgkKLUqVUXFSDNBDW/YiMsFu@MyHy2ZKdTioFSixTrKuSpXmueFAZRiGIfjEK5oAmfmN5cVfNPEJV18vYLvPGWyYnYbeD@SG5YasmAZl@zS1mParFCrkNjyRplVyXwYUDPw4a8H0FBRswlktUwNVxKoQRLbyDsACTFcUFMQo23UuddrCKcuxDNAEj5DiG3WMAZT8IoIJnNT7MbdEQmznQwMmplaS6hlp3PRntk6XeK1nE@ttnvfLreaG5oIq9HKYM7DZL1kuvNlVFStM1Uy43mtH6fe46nnZfGmimc6nl0TQqo5WdISoV8@x/GsIpqVgqYMaR9RP7EuHqMmTkYc9/vNkG4F9/tu3@N4Y6tUSjAiVI4yNPjChFDHpmDH4wFGwXUYjY@O33/4@OlkPgxy3NZqIJ7BsMHkRnGJBgOMpxAEEIXWIrtGofeESjtzRHQ6oRS/yHpsD9wwespMHDFxSPt/LW5L3CtyB7hOXo18AL6oMDl9vcQOaJHPnjFJ7Xg54B05/PM2YPuI3r5ub7uC3/qG0fMbtzwfbpUWi147Pz8p46qe/6ffHa8bnmiPzkfz86Zmdxd33@Yf) if regex passed to this function use `(?:aa)` instead of `(aa)`.
---
# [JavaScript (Node.js)](https://nodejs.org) + [core-js](https://www.npmjs.com/package/core-js), 78 bytes
```
s=>r=>[...s].map((_,i)=>s.matchAll(`(${r})|((?!${r}).)+`).some(v=>v.index==i))
```
* `String#matchAll` is ES2020.
* [`Iterator#some`](https://github.com/tc39/proposal-iterator-helpers) is currently Stage 2.
[Answer]
# [Julia 1.3](http://julialang.org/), 73 bytes
```
a\b=(r=[0;b...].==0;findall(a,b).|>m->r[m.start]=r[m.stop+1]=1;pop!(r);r)
```
[Try it online!](https://tio.run/##ZZHRTtswFIbv/RQuSCiBkMS0sC1VYENCGhO7YdtV1kl247Qurh05DoRRnmMPtAdjx04LreaLxOc//znns71opaCke9nHX9wOk3gY4a/X37EUU66mHO3jubV1kyXJTNh5y@KpXibee0PVLFm4XcKkZsk91MYkYbThieEz3sULuX8zHI2Ob4anZwhVrZpaoRW@BEdcCVVSKQObZT8UqE@fWGMNndpv1gg1i25dh@cIN1m2mxljfc@NpHWWXWot84rKhocIw6p0q0qcY2hob4GOP10r@1xMfFJEmEOuEqaxMJt3QRNGWNK3yNse5kJybE3LfeiW8WWqVLyzgQWkCItwO5vnWGk7Bzh8cICZ4fTuNV23zXwQeLIIm7eyBTRdHwSvVlg0fFnbx8CE@KJndNvM8wU7ZedwjP@mfBSKuRENFtDXgQJvAKCLvpSr0v8Nt61R/UUhEF/oT5YHJi/SMYvjeBLneTrePA2NWBivzpfH56ZYxo2lxk7yfqvrIzLJybjW9QDwxiZ8MTkQlVIo3gQhqrQBFKHwHX9swFGQbJTBwP4tKED6Bw5MISY9IgMNIujbE3f1WjjphRoe30oVBCyiYbg@TQMeOMJWtNBCBeQQgnCn7FUQlXcOcjfi7ZnWtr2/f/BVV/Op5WWG9yJn2r3CjTP091ek5GQ4Oj179/7D5Ah95lLqkZ3z0QkiKSwCX5IiFFAaHiHarz6VEuQExJzE0MYJwYrtiN7HLrY0UBHq4sPfiLJpyat1Q4R6ALAQV1X8olzodsMV4QdtZDlw6R6M@CIHsUVGPJkbQvrvepf6VPoP "Julia 1.0 – Try It Online")
* `findall(::Regex,::String)` was added in Julia 1.3 and returns a vector of ranges for each match.
* `pop!(r);r` is one byte shorter than `r[1:end-1]`
* expects `a` as a `Regex` object and `b` a `String`
* output is a vector of `Bool`s
] |
[Question]
[
We'll define the ***N***-exponential potential of a positive integer **M** as the count of prefixes of **MN** that are perfect **N**-powers.
The prefixes of an integer are all the contiguous subsequences of digits that start with the first one, interpreted as numbers in base 10. For example, the prefixes of **2744** are **2**, **27**, **274** and **2744**.
A prefix **P** is a perfect **N**-power if there exists an integer **K** such that **KN = P**. For example, **81** is a perfect **4**-power because **34 = 81**.
---
Given two strictly positive integers **M** and **N**, compute the **N**-exponential potential of **M** according to the definition above.
For instance, the **2**-exponential potential of **13** is **3** because **132** is **169**, and **1**, **16** and **169** are all perfect squares.
## Test cases
Naturally, the outputs will nearly always be pretty small because powers are... well... exponentially growing functions and having multiple perfect-power prefixes is rather rare.
```
M, N -> Output
8499, 2 -> 1
4, 10 -> 2
5, 9 -> 2
6, 9 -> 2
13, 2 -> 3
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
{^a₀.&b~b^}ᶜ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vzou8VFTg55aUl1SXO3DbXP@/482NAACHaPY/1EA "Brachylog – Try It Online")
## Explanation
```
{^a₀.&b~b^}ᶜ
{ }ᶜ Count the number of ways the following can succeed:
a₀ A prefix of
^ the first {input} to the power of the second {input}
.& produces the same output with the same input as
~b any number
^ to the power of
b all inputs but the first (i.e. the second input)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
*DḌƤÆE%Ḅċ0
```
[Try it online!](https://tio.run/##y0rNyan8/1/L5eGOnmNLDre5qj7c0XKk2@C/tdLh5fqPmta4//8fbWFiaamjYBSroxBtoqNgaABimOooWIJoMyhtaAxSAQA "Jelly – Try It Online")
### How it works
```
*DḌƤÆE%Ḅċ0 Main link. Left argument: m. Right argument: n.
* Compute m**n.
D Generate its decimal digits.
ḌƤ Convert prefixes back to integers.
ÆE Get the exponents of each prefix's prime factorization.
% Take all exponents modulo n.
For a perfect n-th power, all moduli will be 0.
Ḅ Convert from binary to integer, mapping (only) arrays of 0's to 0.
ċ0 Count the zeroes.
```
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
0%n=0
x%n=sum[1|t<-[1..x],t^n==x]+div x 10%n
m#n=(m^n)%n
```
[Try it online!](https://tio.run/##JcxNCoMwEAXgfU4xYIWEjuL4UyiYk4QIkQqVmlCatGTh3dPUbubjwXtzN/6xbFtKTelkw2K@/m0V7WGsFNV11BgmJ2XU59v6gQiUi8wWTnI7OVG6FBYfPEhQvEdqBAIf8CoA@SWTE3XYHiL9aLu/hIPQjFmzujx@vlYX4ATKFPPODc5irI7HOn0B "Haskell – Try It Online")
Extracts the prefixes arithmetically by repeated `\x->div x 10`. I tried expressing the last line point-free but didn't find a shorter expression.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
mηÓ¹%O0¢
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/99z2w5MP7VT1Nzi06P9/Iy5DYwA "05AB1E – Try It Online")
Uses Dennis's Jelly 10-byte algorithm. Inputs are in reversed order.
[Answer]
# [Perl 5](https://www.perl.org/), 38 bytes
```
#!/usr/bin/perl -p
/ /;$_=grep/^${\++$n**$'}/,($`**$')x$`
```
[Try it online!](https://tio.run/##K0gtyjH9/19fQd9aJd42vSi1QD9OpTpGW1slT0tLRb1WX0dDJQHE0qxQSfj/39BYwehffkFJZn5e8X/dAgA "Perl 5 – Try It Online")
[Answer]
## Haskell, 73 bytes
```
m#n=sum[1|c<-scanl(\s c->s++[c])"0"$show$m^n,any(==read c)$map(^n)[1..m]]
```
[Try it online!](https://tio.run/##TcdLCsIwEADQvacYmiwS@qFRl6YXiSkMaaHFzLR0FBG8e9z6dm9Becw5l0KKvbwouG@6tZKQs7kLpHaQug4p2qqvtCzbW9PIDfLHeH/MOEGymnA3I9vguo5iLIQrg4dpOwHsx8pP0HBVrv@ru6hz@QE "Haskell – Try It Online")
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 105 bytes
```
m->n->{int c=1,k=m;for(;--k>0;)if((""+(int)Math.pow(m,n)).matches((int)Math.pow(k,n)+".*"))c++;return c;}
```
[Try it online!](https://tio.run/##lY9NS8NAEIbv/RVDTrtNszRaxbAmIIjgoad6Ew/rNmk3yX6QnVRKyW@PS/VgQLCeZphnnuGdWhxEYl1p6m2TjUo72yHUYch6VC2reiNRWcPmfCZb4T2shTJwmgG4/r1VEjwKDOVg1RZ0YGSDnTK71zcQ3c7T8yrAs8Gn71P3jzaY5Yv9MSugykedFCYpTsogyDxdNLnmle0IT5KmWHKqKkKiKCaB07XAPXP2g@iFoZRpgXJfejJlTWBxxOYRpTKOeVdi3xmQfBj5OdPm6LHUzPbIXIiMrSEVE861R3K3yjL61T/4kJNcUfqntJoY6fIC5WaiZBcYt/820uvfPhlmw/gJ "Java (OpenJDK 9) – Try It Online")
## Credits
* -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 40 bytes
```
{1+(^$^m X**$^n).grep({$m**$n~~/^$^p/})}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lBbI04lLlchQktLJS5PUy@9KLVAo1olF8jNq6vTB8oV6Ndq1v635ipOBOnRqFGJ11RIyy/i4tSwMLG01FEw0tQBsk10FAwNwCxTHQVLMMMMxjA0Bqv6DwA "Perl 6 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
*DḌƤ*İ}ær⁵%1¬S
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//KkThuIzGpCrEsH3DpnLigbUlMcKsU////zX/OQ "Jelly – Try It Online") or see the **[test suite](https://tio.run/##y0rNyan8/1/L5eGOnmNLtI5sqD28rOhR41ZVw0Nrgv8f3XNoq7XS4eX6j5rWuP//b2FiaamjYKKjYKqjYKajYGj83whIGugoWIKREQA "Jelly – Try It Online")**
## How it works
```
*DḌƤ*İ}ær⁵%1¬S - Main link. Arguments: n, m (integers) e.g. 13, 2
* - Power. Raise x to the power y 169
D - Convert to a list of digits [1 6 9]
Ƥ - Convert each Ƥrefix
Ḍ - Back to an integer [1 16 169]
İ - Calculate the İnverse of
} - The right argument 0.5
* - Raise each element to that power [1 4 13]
ær⁵ - Round each to 10 ** -10 [1 4 13]
- to remove precision errors
%1 - Take the decimal part of each [0 0 0]
¬ - Logical NOT each [1 1 1]
S - Sum 3
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 31 bytes
```
{+/o=⌊o←(÷⍵)*⍨10⊥¨,\10⊥⍣¯1⊢⍺*⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqbX2NRz1dto@6FmlqHN7@qHerptaj3hWGBo@6lh5aoRMDZjzqXXxovSFQyaPeXUDZrbX//1uYWFoqpCkYcZkASUMDLlMgZcllBiYNjUEyAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 83 bytes
```
import Data.List
m#n=sum[1|x<-read<$>(tail$inits$show(m^n)),x`elem`((^n)<$>[1..m])]
```
[Try it online!](https://tio.run/##dc1NC4JAEAbgc/srxo@DQknbFwnaIboVeaibFC644NLuKu5KBv532@xSRHMYZnjeYQqibpTzvmeiKmsNO6JJcGBKI@HIWDUixV0bTWpK8sjdeJow7jLJtHJVUd49cZW@P24zyqnIPM9sJpXiIBAX/9K3kJlUw/MtzeABHbQQx2YwFUPV6JOuDxLsZG@jEbyrg1IXtL4zRb8yx@QMyd6yLBshQZg0mJfodbFehCE4MIPPZ3igxas5gKefNBto@aYQfmn1n/B8oO9fc9Q/AQ "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 60 bytes
```
->m,n{c=1;s=m**n;c+=(0..m).count{|j|j**n==s}while 0<s/=10;c}
```
a lot of it is to deal with floating point errors
[Try it online!](https://tio.run/##Zc7RDoIgFIDhe5/i3FVGpGktNXoR50Uhpi7BKaya@uyGWnOrGwbff3ZGpa6vPiH95lwg3lBiBzUpTJMHdE2WFsbFClOhuGzavM21E1J3jzS7M7BO9ZbYVkC7PjQAwqPreYBgB/qwIzSQCzC@rMEn2k/kwUyHf7KdkcZdTmREmF1oCrGAVv8SiVbPlFXGJSwyXirpDxsWA0KoB6I538QUvzn56exZMipZ7E9dyRrE52IwHvdv "Ruby – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 89 bytes
```
m,n->1+(1..m-1).count{"${Math.pow(m+0.0,n)}".startsWith("${Math.pow(it+0.0,n).toInt()}")}
```
[Try it online!](https://tio.run/##bY49D4IwEIZ3fsXFOLShNNSvCIlMLg5ODs7VCDTSK4EDB8Jvxw6aGMMlN7zPPXlzT0eVwSnvEKw2yHrd6KYAv20KF2oMFhyGAPzUPlCFLGf7TZIIWMmY87/LRoCKZ/hWQDKDd/NYrb/tYxD0uoI8ZTY9IQlMj667VQ8eZT4ehskKjDIVMiWljRSXd9chDYvlcNZUytq9mA39QwL5uJAt6Ybaq6GS/RqGPook51uZV/k4jdMb "Kotlin – Try It Online")
In the test cases, passed in n as double values (2.0, 10.0, 9.0) so that I don't have to convert to double when calling Math.pow().
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ ~~71~~ 70 bytes
```
n,m=input();s=n**m;k=0
while s:k+=round(s**(1./m))**m==s;s/=10
print k
```
[Try it online!](https://tio.run/##LU1LDoIwFNz3FG9Hiw0/0QikS9y68QIKTWgqbfNaopy@QnQzM5nMx61hsqaKgx2lSJIkGj4LZdwSKOu8MGk6d1oU5D2plwTf6oNAu5iR@jSlZZbPjG0RIXznc1EWxKEyAXTcpjIfUDnK/t07LrIlAAHXnQDkRw6w/5JdD9IF6G/XHtHiL/BE@dAkXuqm4VCRmsN2cOLQkPMO5XFzvw "Python 2 – Try It Online")
Thx for 1 from ovs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
*DḌƤœ&*€L
```
[Try it online!](https://tio.run/##y0rNyan8/1/L5eGOnmNLjk5W03rUtMbn////pv8tAQ "Jelly – Try It Online")
] |
[Question]
[
Last Thursday user [@SpookyGengar](https://codegolf.stackexchange.com/users/72476/spookygengar) delighted us with his/her first challenge about [Making Squared Words](https://codegolf.stackexchange.com/q/133650/70347). What if we double the number of sides?
### The challenge
Take a string as input in any reasonable format you need (`string`, `char` array...) and output an octogonal representation of the input (also in any reasonable format: `string`, list of `string`s, `char` matrix...) as in the next examples:
```
Input: golf
Output:
golf
o l
l o
f g
l o
o l
g f
o l
l o
flog
Input: HelloWorld
Output:
HelloWorld
e l
l r
l o
o W
W o
o l
r l
l e
d H
l e
r l
o l
W o
o W
l o
l r
e l
H d
e l
l r
l o
o W
W o
o l
r l
l e
dlroWolleH
Input: a
Output:
a
Input: ab
Output:
ab
b a
a b
ba
Input: code golf
Output:
code golf
o l
d o
e g
g e
o d
l o
f c
l o
o d
g e
e g
d o
o l
c f
o l
d o
e g
g e
o d
l o
flog edoc
```
### Notes
* Input will consist only of printable ASCII characters.
* Leading and/or trailing whitespaces and newlines allowed as long as the octogonal shape is maintained.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the sortest program/function for each language win!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes (10 bytes noncompeting)
```
F⁸«✂θ⁰±¹↷¹A⮌θθ»θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw0JToZqLM6AoM69EIzgnMzlVo1BHwUBHwS81PbEkVcNQU1PTGiifWZZfEpSZnlECFAHyHYuLM9PzNIJSy1KLioFaNHUUCoHitVwQg4Ds///T83PS/uuW/dctzgEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⁸« Repeat for each side of the octagon
✂θ⁰± ¹ Print the input except the last character
↷¹ Rotate 45° clockwise
A⮌θθ Reverse the input string
»θ Print the input again, to handle the length 1 case
```
Alternative length 1 fix, also 16 bytes: [Verbose version.](https://tio.run/##HYxBCsIwEEXXzSlmOYEUdCe48gBKqScIcZoOhMYmYzbi2cfo8j3e/2H1JWSfVK@vJPwsvAnu9myWXABPFt5mmP7ynjgQ7g4ODm4UvRAere3lMHHLMnNcpZvOl1o5bjhTo1L7xDr4PX5UQ34QxJwWo2PTsaYv "Charcoal – Try It Online")
```
PθF⁸«✂θ⁰±¹↷¹A⮌θθ
```
A Charcoal bugfix means that the following 10-byte code now works: [Verbose version.](https://tio.run/##S85ILErOT8z5/z8tv0hBw0RToZqLM6AoM69Eo1DTmovTN78sVcPKJzWtBMSDSFi55JfnBWWmZ5ToKASllqUWFacCFSNUhxbA1AfllySWpGoAmbX//yfnp6QqpOfnpHH91y37r1ucAwA "Charcoal – Try It Online")
```
F⁴«θ←↘⮌θ↖⟲
```
[Answer]
## JavaScript (ES6), 156 bytes
```
f=
s=>[...Array((l=s.length-1)*3+1)].map((_,i,a)=>a.map((_,j)=>s[i+j-l?l*5-i-j?i+l*2-j?j+l*2-i?i%(l*3)?j%(l*3)?-1:j?i-l:l+l-i:i?l+l-j:j-l:j:l-i:l*3-i:i]||` `))
```
```
<input oninput=o.textContent=this.value?f(this.value).map(function(a){return(a.join``)}).join`\n`:``><pre id=o>
```
Returns a character array.
[Answer]
# Mathematica, 247 bytes
```
(T=Table;k=Length[s=Characters@#];If[k==1,#,Column[Flatten@{#,T[""<>{s[[i]],T[" ",k/2-2+i],s[[-i]]},{i,2,k}],T[""<>{s[[-i]],T[" ",k+k/2-2],s[[i]]},{i,2,k}],T[""<>{s[[i]],T[" ",3k/2-1-i],s[[-i]]},{i,2,k-1}],StringReverse@#},Alignment->Center]])&
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~79~~ ~~69~~ 65 bytes
```
j++K+]+*dJtlzzm+++*;-Jd@zd*;+ytdlz@z_hdSJjL*;t*3tlztC_B_zt__MC.tK
```
[Test suite](http://pyth.herokuapp.com/?code=j%2B%2BK%2B%5D%2B%2adJtlzzm%2B%2B%2B%2a%3B-Jd%40zd%2a%3B%2Bytdlz%40z_hdSJjL%2a%3Bt%2a3tlztC_B_zt__MC.tK&test_suite=1&test_suite_input=golf%0AHelloWorld%0Aa%0Aab%0Acode+golf&debug=0).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~84~~ 79 bytes
*-5 bytes thanks to @ETHproductions.*
```
Ål
VoA{A?(UÅw +Uê)£Y¥V*2+AªY¥V-A?X:SÃ:Vç +U+Vç
Wf cU¬£V?(V*3 ç hUg~Y)+X:XÃcWz2
```
Leading newline is part of program. Takes a string as input and returns an array of strings.
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=CsVsClZvQXtBPyhVxXcgK1XqKaNZpVYqMitBqlmlVi1BP1g6U8M6VucgK1UrVucKV2YgY1Wso1Y/KFYqMyDnIGhVZ35ZKStYOljDY1d6Mg==&inputs=ImdvbGYi,IkhlbGxvV29ybGQi,ImEi,ImFiIg==,ImNvZGUgZ29sZiI=&flags=LVI=) with the `-R` flag to join the resulting array with newlines.
Not my proudest work, but I got it down from ~100 bytes, at least. My idea here was to create the top and middle parts, then append the top portion, rotated 180°.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~220~~ 213 bytes
* Surprisingly longer than I had imagined.
```
a=input()
l=len(a)
r=range(l)
print'\n'.join(p.center(l*3-2)for p in[a]+(l>1)*([a[i]+(2*i-2+l)*' '+a[~i]for i in r[1:-1]]+[a[~i]+(l*3-4)*' '+a[i]for i in r]+[a[i]+(3*l-2*i-4)*' '+a[~i]for i in r[1:-1]]+[a[::-1]]))
```
[Try it online!](https://tio.run/##hcy9CsMgFIbhPVfh5h8GYjIF0huxDpKa1HI4itihS2/dJkKhW7fzHR7e9Cr3iLpWtwRMz8J4Bwt4ZI53eckOd8@AdykHLPSKtH/EgCz1q8fiMwMxKs23mEkiAY2zksFl4IIZZ8IxtAhKS@CCEiqdeQd72nBYks0wq8Faadpfttb0lb@wkVOMAtRZnP715nZxXitd482TPcJGPw "Python 2 – Try It Online")
[Answer]
# PHP 7.1, ~~230 156~~ 155 bytes
```
for($x=$e=strlen($s=$argn)-1;$n<9;$r[$y][$x+=$n+1&3?$n&4?-1:1:0]=$s[$i],$i+=($n+=!$i||$i==$e)&1?:-1)$r[$y+=$n-1&3?$n<6?:-1:0]=$r[$y]?:"";echo join("
",$r);
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/4b957bba1a94e5f7ba4b5799582a12cc626e1458).
**breakdown**
```
for($x=$e=strlen($s=$argn)-1; # import to $s, set $e to length-1, init $x
$n<9; # loop through 8 repetitions of string
$r[$y][
$x+=$n+1&3?$n&4?-1:1:0 # 3. increment/decrement $x depending on $n
]=$s[$i], # 4. copy character to current position
$i+=(
$n+=!$i||$i==$e # 5. if first or last character of string, increment $n
)&1?:-1 # 6. if odd repetition next, else previous character
)
$r[
$y+=$n-1&3?$n<6?:-1:0 # 1. increment/decrement $y depending on $n
]=$r[$y]?:""; # 2. if empty, init row to string
echo join("\n",$r); # output
```
[Answer]
# Mathematica, ~~168~~ ~~166~~ ~~147~~ 127 bytes
```
(n=Length@#;b=Array[" "&,3{n,n}-2];Do[l={{1,n+k-1},{k,n-k+1}};l=Join[l,Cross/@l];b=ReplacePart[b,Join[l,-l]->#[[k]]],{k,n}];b)&
```
This takes a list of one-character strings and outputs a matrix of one-character strings.
I saved 18 bytes by exploiting the symmetry to use `-l` and `Cross/@l` which takes [something like a cross-product](https://en.wikipedia.org/wiki/Cross_product#Multilinear_algebra) of each of the two single 2D vectors to take `{x,y}` to `{-y,x}`. Basically, the two initial directions are East (top edge) and Southwest (top right edge). Then we add in 90-degree counterclockwise rotations of them with `Cross`: North for left edge and Southeast for bottom left edge. Then we add in the other four pieces using `-l` to flip the four we covered.
You can test it out on [the sandbox](https://sandbox.open.wolframcloud.com/) with something like:
```
(n=Length@#;b=Array[" "&,3{n,n}-2];Do[l={{1,n+k-1},{k,n-k+1}};l=Join[l,Cross/@l];b=ReplacePart[b,Join[l,-l]->#[[k]]],{k,n}];b)&[{"H","e","l","l","o"," ","G","o","l","f"}]//MatrixForm
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 14 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
4H┐⁸k⁸±\+⁸L1╋↶
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE0JXVGRjI4JXUyNTEwJXUyMDc4JXVGRjRCJXUyMDc4JUIxJXVGRjNDJXVGRjBCJXUyMDc4JXVGRjJDJXVGRjExJXUyNTRCJXUyMUI2,i=JTIyY29kZSUyMGdvbGYlMjI_,v=8)
] |
[Question]
[
Your task is to calculate the square root of a positive integer without using any mathematical operators to change the number, such as:
* Setting a variable (ex. squareRoot = 5)
* Addition (A+B)
* Subtraction (A-B)
* Multiplication (A\*B)
* Division (A/B)
* Square, cube, fourth, etc. roots
* Exponents
Comparison operators (such as <, >, ==, etc) are not considered "mathematical operators" for the purposes of this question and are allowed as long as they do not change the value of a variable.
The only operator that you are able to use is ++. The following exceptions are in place:
* If you wish, you may initialize a variable by setting it to 0.
* If your language does not include the ++ syntax, you may use an equivalent syntax, such as foo+=1 or foo=foo+1
* The square root should be calculated to at least 6 digits beyond the decimal (the hundred-thousands place) and outputted as a whole number of the decimals (ex. if I input 2 it could come out as 14142135624 or 1414213 depending on the rounding). Rounding up or down is not important.
User-defined functions are not allowed. In addition, simulating functions with goto is not allowed as well.
I'm interested to see what everyone submits! Happy coding!
## CLARIFICATION
Clarify that number is a positive integer. You are welcome to make code that would do any number but it is not necessary.
## CLARIFICATION #2
Clarify that comparison operators are allowed.
## CLARIFICATION #3
Addition, subtraction, multiplication, division, and functions to change numbers are not allowed **at all**, regardless of whether they are saved to a variable or not. I'm sorry that this invalidates a couple existing answers, but I meant to define this group of operators with "change the number" in order to prevent troll answers (ex. I just used the sqrt() function, you only prohibited addition, multiplication, division, and subtraction). Sorry for the confusion.
## CLARIFICATION #4
Clarify that we need at least 5 digits. 10 digits caused code to run for a long time.
[Answer]
## Python 66
```
print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
```
## Output
```
>>> print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
121
110000000000
>>> print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
1000
316227766017
```
>
> This solution uses [Spiral of Theodorus](http://en.wikipedia.org/wiki/Spiral_of_Theodorus) on a complex plane to achieve the result.
>
>
>
[Answer]
# Python, 184 characters
The following Python solution uses only the increment operator and no other arithmetic operators at all. However, with the required precision (10 digits), it takes an impossibly long time to run. You can test it with lower precision (3 digits) by reducing `1e20` to `1e6`.
```
import sys;t=0
for _ in range(int(sys.argv[1])):
for _ in range(int(1e20)):t+=1
q=0
while 1:
z=0
for _ in range(q):
for _ in range(q):z+=1
if z>=t:break
q+=1
print(q)
```
Ungolfed:
```
import sys
# t = N * 100000000000000000000 (magnitude of twice the precision)
t = 0
for _ in range(int(sys.argv[1])):
for _ in range(int(1e20)):
t += 1
q = 0
while True:
# z = q * q
z = 0
for _ in range(q):
for _ in range(q):
z += 1
if z >= t:
break
q += 1
print(q)
```
[Answer]
## Fortran 73
```
read*,t;s=0;do while(abs(s*s/1e10-t)>1e-10);s=s+1;enddo;print*,s/1e5;end
```
Might take a loooong to actually determine an answer for certain values, but it'll work for sure. While I use `*` and `-`, *these are not changing any values*, only the `s=s+1` actually changes anything.
[Answer]
# CJam, 26 bytes
```
q~,1e20,m*,:N!{)_,_m*,N<}g
```
[Try it online.](http://cjam.aditsu.net/ "CJam Interpreter") Paste the **Code**, type the desired integer in **Input** and click **Run**. Before you do, I suggest changing `1e10` to `1e4` though.
The [Java interpreter](http://sourceforge.net/projects/cjam/files/?source=navbar) handles `1e6` with input “2” in about 15 seconds. `1e20` will require a *huge* amount of RAM.
### Examples
```
$ cjam <(echo 'q~,1e2,m*,:N!{)_,_m*,N<}g') <<< 4; echo
20
$ cjam <(echo 'q~,1e2,m*,:N!{)_,_m*,N<}g') <<< 2; echo
15
$ cjam <(echo 'q~,1e4,m*,:N!{)_,_m*,N<}g') <<< 4; echo
200
$ cjam <(echo 'q~,1e4,m*,:N!{)_,_m*,N<}g') <<< 2; echo
142
$ cjam <(echo 'q~,1e6,m*,:N!{)_,_m*,N<}g') <<< 4; echo
2000
$ cjam <(echo 'q~,1e6,m*,:N!{)_,_m*,N<}g') <<< 2; echo
1415
```
### Background
Since we're not allowed mathematical operators to change numbers, we're going to use setwise operators to change arrays.
The code starts by "multiplying" the input (“i”) by 1e20, but without any actual multiplication. Instead, we push an array containing “i” integers, an array containing 1e20 integers, take their cartesian product and compute its length.
Then, we push zero and increment until the product of the integer by itself (calculated as above) is no longer smaller than `i * 1e20`. This causes the square root to be rounded up.
### How it works
```
q~ " Read for STDIN and interpret. ";
, " Push an array containing that many integers. ";
1e20, " Push the array [ 0 … 1e20 - 1]. ";
m*,:N " Get the length of the cartesian product and save it in “N”. ";
! " Logical NOT. Since the input is a positive integer, this pushes 0. " ;
{ " ";
) " Increment the integer on the stack.";
_, " Push an array containing that many integers. ";
_m*, " Get the length of the cartesian product of the array by itself. ";
N< " If the product is smaller than the target value, push 1; otherwise push 0. ";
}g " Repeat the loop if the result was 1. ";
```
[Answer]
# Cobra - 62
**Posted before the third edit, no longer valid.**
Not only is it short, but it should be overflow-free if `n < Decimal.maxValue`
```
def f(n)
r,e=0d,10000000000
while r/e*r/e<n,r+=1
print r
```
[Answer]
## Scala, 117
```
val z=BigInt(readLine+"0000000000")
print(Stream.from(1)find(x=>(BigInt(0)/:Stream.fill(x,x)(1).flatten){_+_}>=z)get)
```
Doesn't finish in a reasonable amount of time, even for 2 as input, but it does work. You may notice that I'm doing `_+_`, but that only ever adds 1, and Scala doesn't have a `++` operator anyway. I could save two characters by replacing the inner Stream with List, but then it would run out of memory. As written, I think it scales only in processing time, not memory usage.
[Answer]
# Haskell, 70 bytes
```
s i|r<-[1..i]=foldl1(.)[(+1)|j<-r,k<-r]
f i=[j-1|j<-[0..],s j 0>=i]!!1
```
`f` gives the integer square root by finding the largest number whose square is less than or equal to the input. The squaring function `s i` increments by one for every element of an `(i,i)` matrix. (Typed on phone so might have typos).
[Answer]
# PHP, 124 bytes
It's an exhaustive algorithm. It just tries numbers until the square of that number is bigger than the "goal" number (which is the input times 1E`number of decimals` squared (10.000 for a 2 decimal result). Then it prints that last number.
```
for(;$a++<$z=$argv[1];)for(;$$a++<1e6;)$g++;for(;$b++<$g;$i=$x=0)for(;$i++<$b;)for($j=0;$j++<$b;)if(++$x>=$g)break 3;echo$b;
```
Run like this (`-d` added for aesthetic reasons only):
```
php -d error_reporting=32757 -r 'for(;$a++<$z=$argv[1];)for(;$$a++<1e6;)$g++;for(;$b++<$g;$i=$x=0)for(;$i++<$b;)for($j=0;$j++<$b;)if(++$x>=$g)break 3;echo"$b\n";' 2
```
Don't recommend trying this out with anything more than 3 decimals or a number above 10.
[Answer]
# x86-64 Assembly Code, 22 bytes
No operators or function calls, as per the rules.
```
// Int from stack -> st0
fild 8(%rsp)
// sqrt(st0) -> st0
fsqrt
ret
```
Expects argument pushed onto the stack, then call this function, like so:
```
push $2
call a
```
The result is saved onto the register stack (`%st0`). Tested on MinGW64.
] |
[Question]
[
A binary matrix represents a shape in the plane. `1` means a unit square at that position. `0` means nothing. The background is `0`.
For example, the matrix `[[0,1,0],[0,0,1],[1,1,1]]` represents the following shape:
```
o----o
|////|
|////|
o----o----o
|////|
|////|
o----o----o----o
|////|////|////|
|////|////|////|
o----o----o----o
```
There are several equivalent ways to define the Euler characteristic.
One way is finding all the vertices and edges of these squares, and defining the Euler characteristic to be \$\chi=V-E+F\$, where \$V\$ is the number of vertices, \$E\$ is the number of edges, and \$F\$ is the number of tiles.
For example, the above shape has \$13\$ vertices, \$17\$ edges, and \$5\$ tiles. So its Euler characteristic is \$13-17+5=1\$.
An equivalent definition is the total number of connected regions in the shape, minus the number of holes that occur inside those regions. Regions that connected diagonally are considered connected, while holes that are connected diagonally are considered disconnected.
For example, the above shape has \$1\$ connected region, and \$0\$ hole. So its Euler characteristic is \$1-0=1\$.
Note that there is an alternative but non-equivalent definition of the Euler characteristic, where regions that connected diagonally are considered disconnected, while holes that are connected diagonally are considered connected. The Euler characteristic of the above shape would be \$2\$ using that definition.
## Task
Given a binary matrix, find its Euler characteristic.
You can use any two consistent values instead of `0` and `1` for the binary matrix.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Testcases
```
[[1]] -> 1
[[1,0,1]] -> 2
[[1,0],[0,1]] -> 1
[[0,1,0],[0,0,1],[1,1,1]] -> 1
[[0,1,1,0],[1,0,1,1],[1,1,0,1],[0,1,1,0]] -> -1
[[0,0,1,1,0],[0,1,1,1,1],[1,1,0,1,1],[0,1,1,0,0]] -> 0
[[1,1,1,0,1,1,1],[1,0,1,0,1,0,1],[1,1,1,0,1,1,1]] -> 0
[[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] -> 1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
FA«Fι«FκUO³@#¶#@→→»⸿⸿»≔⁻№KA@№KA#θ⎚Iθ
```
[Try it online!](https://tio.run/##bYwxC4MwEIVn/RUSlwtYqHSrS8Wpg1S6qkMqqQZDUhN1Kf72NGqlhZaDu@/eu3tVQ1QlCTfmLpUHZ/EYesDYe7rOIrAFV26xd7lxKWo4BB46@YXwTwhH1k7lSOF4ZXXT/9sn18kUEz2gQhVqfpncWGtWC0iZGDQkcrBuRmkbcw54Tke2/8o@wnZ0NiHhlCiwsCYnRPfQYRwZk@d5GLyrDCzvl9o4/OKPvt2XpdmN/AU "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FA«Fι«FκUO³@#¶#@→→»⸿⸿»
```
Draw the shape represented by the matrix, except using a `3×3` square with `@`s at the vertices and faces and `#`s at the edges.
```
≔⁻№KA@№KA#θ
```
Subtract the final number of edges from the number of vertices and faces.
```
⎚Iθ
```
Clear the canvas and output the result.
Example: The last test case `[[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]` results in the following drawing:
```
@#@#@#@#@#@
#@#@#@#@#@#
@#@#@#@#@#@
#@# #@#
@#@ @#@ @#@
#@# #@# #@#
@#@ @#@ @#@
#@# #@#
@#@#@#@#@#@
#@#@#@#@#@#
@#@#@#@#@#@
```
This has 53 `@`s and 52 `#`s so its characteristic is `1`.
[Answer]
# [Python](https://www.python.org) NumPy, 79 bytes
```
lambda A:sum(g(g(pad(A,1)).T))
g=lambda A:r_[-A,A|roll(A,1)]
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZDNSsUwEIVxm6cY7iqRtDSu5EKFPoEbd7VIpO01kD_SVii48TncXBB9J30a06ZN66UEZs75zmTSj2879i9Gnz_b_PFr6Nvk9udecvVccyiO3aDwyX-W17igjJD0gRB0yiPgnsqkoMWbM1LORIVaZxToQdkRhLLG9dfL2PfQBg-h1jiQIDQY22ickdQ1vJZCNx0mRwQgqIEcFLe4eeWSyrSzUvT4AMkdHPwWnvD-PCzlzvERi0m0TugeC9r6Ns8N-FvwVFNDSFjk_HtFy5JV1TSJIV_SjC7tTWgrWkZpInyziJNMPcIu7QDMoyIS4NWd8STwWyJU_zL71JrL5sUisOAZjWfdKvoXsS2yPWIf3etsP4KFv_YH)
## Old [Python](https://www.python.org) NumPy, 85 bytes
```
lambda A:sum([A:=r_[A:=pad(A.T,1),-A[1:]|-A[:-1]]for i in"12"][1])
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVBNaoQwFKZbT_FwlZQoZlZFcMA7tCsbSopKA4kJUQtCNz1HNwOlvVN7mibGv85Cfd-vL_n4NtPworvLZ1s8fo1Dm9z9PEiunmsOZd6PClVlXtgn_za8RmV6TygmSVnRnL25T55QxlptQYDoYnqKWUUZjlqrFXSjMhMIZbQdbpfy9wCDFkU-KV0StGk6lOHUNryWomt6hPMIQBANBShuUPPKJZFpb6QYUAzJGWKMvcPpc1nKreUTEp40VnQDEqR1sCg0uL8gPxONcVjk8ntDKrcq8000ciPJyAJPATJSbZR3OLCQnibOQq_lYJirNkswr-psT4J_T4TpX-aYWnPZvNhmWOwZ2Z51q02_iu2R_RDH6JGnxwoabu0P)
## How?
This is essentially a golfed version of the formula V-E+F given in OP. Our criterion to find edges (vertices) is that at least one of the 2 (4) adjacent squares is marked.
Little trick:
We make a sizeable saving by folding squares and vertical edges into one matrix. It turns out that the expression that computes and appends vertical edges from the squares alone can be reused verbatim to get and append horizontal edges and vertices in just one more step.
[Answer]
# [R](https://www.r-project.org/), ~~74~~ ~~68~~ 67 bytes
*Edit: -1 byte thanks to pajonk*
```
function(m,`^`=cbind)sum(w<--t(m^0|0^m),-(t(m)^0|0^t(m)),w^0|0^w,m)
```
[Try it online!](https://tio.run/##ldDRDoIgFAbg@57CrZtztsMGXWePYhrZYgvbUOdN725KgtBazAu2w/z/D8GMdf@ozVneK1PJrjaq7ZTMx1vfyE49G9BUFmUuL6q5YttrGI6MdaAL/uKFRmIwbdDu5gFpsPNAGn/KYCWQIBAx22fslInd/yBxWsOHZBhJQthI8FPUdeYWzYbYVl8A@6MrsWgu4DyWBAPyM8ZoxAYwT72M7zuOk1/@3j6xiQ3I4BkjO/oivg4R4xs "R – Try It Online")
Gets vertical edges by adding a row of `0`s to the first or last column of the matrix `m`, and summing the non-zero elements when these two matrices are added together:
`sum(cbind(m,0)+cbind(0,m)>0)`, which is golfed (by substituting the `cbind` function) to `sum(m^0+0^m>0)`.
Repeats the same operation with the `t`ranspose of `m` to get horizontal edges:
`sum(cbind(t(m),0)+cbind(0,t(m))>0)`, golfed to `sum(t(m)^0+0^t(m)>0)`.
We then recycle the added-together vertical-edge matrix, transposed (saved inline as `w<-t(...)`), and repeat the operation again to get the vertices:
`sum(cbind(w,0)+cbind(0,w)>0)`, golfed to `sum(w^0+0^w>0)`.
Finally, the sum of `m` gives us the tiles, and we can wrap it all together using only a single call to `sum`.
[Answer]
# [Octave](https://www.gnu.org/software/octave/) with Image Package, 7 bytes
```
bweuler
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKvgoKCnp/c/qTy1NCe16H@aRrRhrCYXiNIx0EEwreEcIAPMBdLWhkA2kjBIAqwNKgVSAhWHKYIpg9BIChFKYYoNdeBSYGUGOnBsjSKHrBymFOY@hAaEmCFM238A "Octave – Try It Online")
A built-in.
---
# [Octave](https://www.gnu.org/software/octave/), 49 bytes
```
@(m)sum(conv2(m,[1,2;4,8])(:)==[1,6,7])*[1;-1;-1]
```
[Try it online!](https://tio.run/##VY7BCsIwEETvfkWPG1lDt4iKS8D/CDmUYm@xB7W/H5PYTVJI2JmdN7DL9BnXZ5g702mtwwO8en89TMtrHcCjJRz4jDen4K6MifaCV6eOlviUngszWHLqkAb2WCUXE0W2cTJF3axTkGtblJBtL5Bg/9mAFRWYsEQZ67F83mUtLqjcVwt1R1ILPw "Octave – Try It Online")
Based on [this blog article](https://sydney4.medium.com/the-euler-number-of-a-binary-image-1d3cc9e57caa). The Euler characteristic is \$M\_1-M\_2-M\_3\$, where \$M\_1\$, \$M\_2\$, \$M\_3\$ are the numbers of \$2\times2\$ submatrices of the form \$\bigl(\begin{smallmatrix}1&0\\0&0\end{smallmatrix}\bigr)\$, \$\bigl(\begin{smallmatrix}1&1\\1&0\end{smallmatrix}\bigr)\$, \$\bigl(\begin{smallmatrix}0&1\\1&0\end{smallmatrix}\bigr)\$ respectively.
Thanks [@Cris Luengo](https://codegolf.stackexchange.com/users/91877/cris-luengo) for pointing out that this is Gray's algorithm.
[Answer]
# [Python](https://www.python.org) with [numpy](https://numpy.org/), ~~79~~ 77 bytes
```
lambda m:sum(sign(diff(diff(pad(kron(m,eye(2)-.5),1)).T)))
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZDPSsQwEMYRb32KHCeSXbaCIAWPu4cF8bK32kO0iRts_jBN1D6LlwXRd9KnsTVtWgcymZnv9w0h71-u80drTh_y5v4zeLm6_r5tuH6oOdFFGzS06slAraSMyfEantEa0Ex0Ai7pan1FWU7p-kApzSRaTUzQriNKO4v-Yly699gVGenj9agaQQ4YROyHcKiMBwnihTegjAse6LBOvD0K58n2brdFtFgQx9s2bjz9nJ2XZV5VWZ_ZhqWqYuXU9ffYDxPWq_lCidqfN6mRm9RIzmys_tFLfnTkLGkjuWHpTK9I-uyY6fm9S9dyPvFV_Ixf)
This is based on [my answer to "Expand a matrix goo-ily"](https://codegolf.stackexchange.com/a/245610/104752).
`kron` expands each 1 into `eye(2)-.5`, which is
\$ \begin{array}{|c|c|} \hline 0.5 & -0.5 \\ \hline -0.5 & 0.5 \\ \hline \end{array} \$. After `pad` adds a border of zeroes, taking `diff` in both directions (with a transpose in between because that's shorter than specifying a different direction for `diff`; the rearrangement doesn't change anything in the end) is equivalent to a sum with multipliers \$ \begin{array}{|c|c|} \hline 1 & -1 \\ \hline -1 & 1 \\ \hline \end{array} \$ on each 2-by-2 square (overlapping). The nonzero terms (before summing) are positive at even positions (by sum of coordinates), which correspond to faces and vertices, and negative at odd positions, which correspond to edges. `sign` produces 1 or -1, correspondingly, for each part that is present, and `sum` gives the Euler characteristic.
[Answer]
# Python3, 606 bytes:
```
E=enumerate
def V(m,x,y):
if x>=0 and y>=0:
try:return m[x][y]
except:return 0
def f(m):
s,R=[],[0,0]
while(O:=[(x,y)for x,b in E(m)for y,_ in E(b)if m[x][y]and(x,y)not in s]):
q=[O[0]]
while q:
x,y=q.pop(0)
M,D=[(0,1),(0,-1),(1,0),(-1,0)],[(-1,-1),(-1,1),(1,-1),(1,1)]
if(x,y)in s:continue
s+=[(x,y)]
for u,v in M:
R[1]+=(p:=(x+u,y+v))not in s
if V(m,*p)and p not in s:q+=[p]
for u,v in D:
R[0]+=(p:=(x+u,y+v))not in s and all((x+u+j,y+v+k)not in s for j,k in[(0,[-1,1][v<1]),([-1,1][u<1],0)])
if V(m,*p)and p not in s:q+=[p]
return R[0]-R[1]+sum(map(sum,m))
```
[Try it online!](https://tio.run/##jVNNb9swDD3Pv4LIpdIsB/J2GYypp/bYFehhF80onFZG3fpDseXM/vUZKX/ECzBgh1gi@fj4SEZ2dG9N/fWbbc/ne2XqvjJt5kzwanL4ySoxiJEnARQ5DLdKQla/wogXdIFrx6Q1rm9rqPSQ6jFFpxlejHWLX3qenFXE0YknpVOhpZCI/P1WlIY9JkozqpE3LQziAEUN9wgncxTPk3ngWH4ugQI8vm4cBbuUmOGo9KOWKQnwvHAkLxKO6ri3jWWSk/0g7rCcFDEX@I3oiIXEb0QHSqOLd@M5RWdQzIkbx@CLU@HkpaldUfeG/F04t@FRJL4XJ9L34HXAk47TUDGbKDaEvRjDE1878IBimvZny2nCFpZgckRme816t7DKf7L6TWVlySgUvlMw/LhEiexdfKBB89DUbqpP3@MUu52tHi2aCv8fgRDAvHISFfl@u75iVWYZnqLi/FxUtmkdZJ0LOrXb7TSCUohuIQ7wKnAtk/llMv0/ZYNAY3aSWyAkvg5PAE@1QibwEvXwaMJfMqbbXznbrCVPemErYIZLsf4WVWv8Ku2Scmlim7r1x1uKGMcV0M4KGnpelM607EdTGwHdvrNl4djNr/qG42P4lOErUkCDx0nvMYQPunw2p6wUUCxgIkU4orvO4FJylnFQCg7nPw)
[Answer]
# JavaScript (ES7), 105 bytes
This is based on the simple yet brilliant method [used by Neil](https://codegolf.stackexchange.com/a/247105/58563). It's probably not the shortest approach in JS, though.
```
m=>[...7**8+'23'].map(n=>m.map((r,y)=>r.map((v,x)=>!v|m[k=[x*2+n%3,y*2+n/3|0]]?0:o-=m[k]=n&1||-1)),o=0)|o
```
[Try it online!](https://tio.run/##hZDfDoIgFIfvewq7KEWPCHpRa8MehHHhylp/hKbN6ca7m6WhLTcvGBx@5/vY4ZqUSXHIL4@nL9UxbU6syVjMMcYb1916dhjZAmfJw5Eszj4HJ4casTjvihKqtliWOuM3xis39OQqgvq9B5EmQuzJTvmsTQWTa6q1TxECxQjSqjkoWah7iu/q7JwczqkQCFlBYNHFXwQETBxOxQL4qOXf0IZ907sNWoTOtXfA52mDdPA37XF/ih8M3enHMbYMHjIxmAF6nIBZ3ylMPqMZFMMnjFXje/qrpM0L "JavaScript (Node.js) – Try It Online")
### Commented
```
m => // m[] = input binary matrix, reused as an object
// to store the cells of the expanded matrix
[...7 ** 8 + '23'] // all digits from 0 to 8 (order doesn't matter):
// [ '5', '7', '6', '4', '8', '0', '1', '2', '3' ]
.map(n => // for each n in the above list:
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each value v at position x in r[]:
!v | // if v = 0
m[ // or the cell at ...
k = [ // ... the key position k defined as ...
x * 2 + n % 3, // [ 2x + (n mod 3),
y * 2 + n / 3 // 2y + floor(n / 3) ]
| 0 //
] //
] ? // ... is already set:
0 // do nothing
: // else:
o -= m[k] = // set m[k] and update o:
n & 1 // -1 if n is odd (edges)
|| -1 // +1 otherwise (vertices and faces)
) // end of map()
), // end of map()
o = 0 // start with o = 0
) | o // end of map(); return o
```
] |
[Question]
[
## Challenge
You have been given a string of digits 0-9.1 Your task is to shuffle this string, but every index must have a different value than it did before the string was shuffled.
For example:
```
In : 287492
Out: 892247
```
If this is not possible, return `false` or something similar. (`null`, `undefined`, etc.)
```
In : 131
Out: false
```
There is no upper bound on the length of the string, but you can assume you have unlimited computation time.
Your function must pass the following tests:
```
shuffle('2') => false
shuffle('88') => false
shuffle('794588888') => false
shuffle('344999') => for example, '999434'
shuffle('172830560542976539') => for example, '271038650425697395'
```
**Shortest code wins, and good luck!**
---
1 More specifically, the string would match `/^[0-9]+$/`.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~37~~ 32 bytes
```
{$[|/x=r:x[,/|2 0N#<x]@<<x;0;r]}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqloluka/wrbIqiJaR7/GSMHAT9mmItbBxqbC2sC6KLb2f5q6ho6SkZK1koUFkDC3NDG1AAEg29jExNLSEsgwNDeyMDYwNTMwNTGyNDczNbZU0vwPAA "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`$[` `;` `;` `]` if-then-else
`<x` "grade" - the sorting permutation for `x`
`<<x` "rankings" - the inverse of the sorting permutation
`2 0N#` split in two halves (or when length is odd - only approximately)
`|` swap the halves
`,/` concatenate
`x[` `]` use as indices in `x`
..`@<<x` use `<<x` as indices in the previous result (`a@b` is alternative syntax for `a[b]`)
`r:` assign to `r` - the potential result
`x=r` boolean list of which elements of `x` are equal to their counterparts in `r`
`|/` or-reduction, i.e. "any?"
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
Like the Pyth answer, outputs all possible shuffled strings or digits.
```
œʒø€Ëà_
```
[Try it online!](https://tio.run/##AR4A4f9vc2FiaWX//8WTypLDuOKCrMOLw6Bf//8yODc0OTI "05AB1E – Try It Online")
## Explanation
```
œ Permutations of the input
ʒ Filter such that:
ø Zipping with the original input
€Ë And comparing at corresponding indices
à_ are all unequal.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
f.AnVQT.p
```
[Try it online!](https://tio.run/##K6gsyfj/P03PMS8sMESv4P9/JWMTE0tLSyUA "Pyth – Try It Online")
Outputs all possible strings that meet the criteria given in the question. This results in an empty list for the `false` cases.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
-VI#Q.p
```
[Try it online!](https://tio.run/##K6gsyfj/XzfMUzlQr@D//2glYyUdBSUTOGGJRMT@yy8oyczPK/6vmwIA "Pyth – Try It Online")
Takes input as a list of digit-characters. For example:
```
['1', '2', '3']
```
Output: all possible derangements, with multiplicity for related characters.
* `.p`: Generate all permutations.
* `#`: Filter on
* `I`: Invariant under
* `-V ... Q`: Removing all characters that are at the same position in the input.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œ!nẠ¥Ƈ
```
**[Try it online!](https://tio.run/##y0rNyan8///oJMW8h7sWHFp6rP3/4fbI//@VjE1MLC0tlQA "Jelly – Try It Online")**
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 125 bytes
```
e=>[...Array(i=2+e|0)].every(_=>(s=[...q=(--i+'').slice(1)]).some((_,j)=>_==e[j])|s.sort()+''!=[...e].sort()||console.log(q))
```
[Try it online!](https://tio.run/##LYtBCoMwEEXPUjfOYBOqXZYJeA4JEtKhRKyJiQhC7p7a0t3jvf8ns5tkowubWPyTS6DCpAYpZR@jOcBR13C@oZa8czxgJAWJvn0lEMI1dY0yzc4ytKhP9G8GGK8TkhqJeJg05nTquAGe48vvy/pvcrZ@SX5mOfsXrIglQNV29wof5QM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ 80 bytes
```
lambda l:[p for p in permutations(l)if all(map(cmp,l,p))]
from itertools import*
```
[Try it online!](https://tio.run/##PY6xbsMwDER3fcXBk10YGVIXtQ3kA/oNSQfFkVAWlERQ6pCvd6QEKBfycId7lHv5SfG4@9NlZxuuNwtezwKfFAKKEKfhr9hCKeaeB/KwzH2w0m9BRh5lGL6N1xRAxWlJiTMoSNLytr828j2b1scUXaus@pDLjeJqwDjhvD1xW/NapppK0tdeaLV9xRpUsK4QpVjQoTv8JorPN7rXPepQU46z@099VXzOdGXX7Uczz@Z9mpZlMZ/L9DG3eQA "Python 2 – Try It Online")
Goes through all permutation of the string, and keeps the ones that are different to the original string at every index.
[Answer]
# [PHP](https://php.net/), ~~152~~ 141 bytes
```
$a=count_chars($s=$argn,1);rsort($a);$a[0]*2<=strlen($s)?:die;for($s=$t=str_split($s);$s!=array_diff_assoc($s,$t);)shuffle($t);echo join($t);
```
[Try it online!](https://tio.run/##HY5NDsIgGET3nKI2LIqxSe2PLWJ15yXUNKQtgmmA8OHCy4vS2b28mWSstOF0sdKieZQmvWvM3VMn@TlJWcC8H81b@2GU3EGGoV/tbk@YA@N8hjlhmN@Kx7Y89eDdMut/i1yOk5qZMG6d@GgGsIvyUTIMm547xz/DpIQYOIAZ/2KHPWEE5FuIZc4ixEfJyyi9Uggl6jrU0rrpYlBV15RStG/LriqaQ9HUJW0PTUW/xnplNIT8@gM "PHP – Try It Online")
A bit lengthy but it's my first approach, will think more about it later
* displays empty string (exits) if impossible (if the most frequent number occurence is more than half of length of the string)
* uses an array approach and shuffles until it finds a proper result
EDIT: fixed an error in string length var attribution (missing brackets) + improved `while` condition for +1 byte
EDIT2: saved 1 byte, since brackets were mandatory for ternary condition, an `if` is now shorter
EDIT3: saved 11 bytes with the help of [this answer by Titus to a closely related question](https://codegolf.stackexchange.com/a/103554/90841)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 187 bytes
```
e=>{for(b=a=e.slice().sort(),a=+a.join(""),b=+b.reverse().join("");a<=b;){if(k=(a+"").split("").map(a=>+a),b==k.slice().sort((a,e)=>e-a).join("")&&e.every((a,e)=>a!=+k[e]))return a;a++}}
```
[Try it online!](https://tio.run/##lc7BbsIwDAbgO0/R9QCxUiKFwqHq3BdBO7idmUK7JkoKEkI8e1lHyzSkSez2y/Zne09HCpU3rlu29p17hz1jcd5ZL0okZBUaU7EAFazvBCSEktTemlbEMSQlylJ5PrIPw8xUz@kVyxzOZidqFCS/Siq4xnRDU32SE4SFpMFj/fuCoIQBC17Sz7r5nNVw4zR16QVlveU3AM/dwbcR5STl5TLrK9sG27Bq7IeItU43cRK5MY0vLBa3FzjCIpIMAPnsgWm9Sif4nZ@md/c/pO9KP83S9TrLshsc89@0vwI "JavaScript (Node.js) – Try It Online")
-8 bytes thanks VFDan
# [JavaScript (Node.js)](https://nodejs.org), 179 bytes
```
e=>{for(b=a=e.slice().sort(),a=+a.join``,b=+b.reverse().join``;a<=b;){if(k=(a+"").split``.map(a=>+a),b==k.slice().sort((a,e)=>e-a).join``&&e.every((a,e)=>a!=+k[e]))return a;a++}}
```
[Try it online!](https://tio.run/##lc5Ra8IwEAfwdz9F1wfNkRrI6h5Kd/0iIvRazxHbNSHphCF@9k6tFSYM3Nufy/3@lz0dKNTeuH7Z2S0PDgfG4rizXlRIyCq0pmYBKljfC0gIJam9NV1ZJhXKSnk@sA@XjXGa0ztWORzNTjQoSMbx2brW9GWpPskJwkISnC02v7sFJQxY8JKmqvmc1aX9e3qjF5TNmjcAnvsv30WUk5Sn02yobRdsy6q1HyLWOn2Lk8jd0nheLBZw/QBHWESSASCfPTCtX9MJXvPT9O7@h/Rd6adZulplWTbCW/6bDj8 "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
For the purposes of the current challenge to "outline" a word means to surround it successively with its own letters, starting with the last one, and finally to replace the original word in the center with spaces:
```
oooooo
onnnno
on -> on no
onnnno
oooooo
```
## Task:
Given a list of words, consisting only of lowercase and/or uppercase English letters, outline each word and display all the resulting blocks next to each other horizontally, separated by a column of single space, vertically aligned at the centers of the blocks.
You can write a full program, or a function.
## Input:
A list of words, or if you prefer - a space- or other symbol- delimited string
## Output:
The ASCII representation of the blocks for the outlined words. Leading/trailing
whitespaces are permitted.
## Test cases:
```
Input 1: ["code", "golf"] (or "code golf")
Output 1:
cccccccccccc gggggggggggg
cooooooooooc goooooooooog
coddddddddoc gollllllllog
codeeeeeedoc golfffffflog
code edoc golf flog
codeeeeeedoc golfffffflog
coddddddddoc gollllllllog
cooooooooooc goooooooooog
cccccccccccc gggggggggggg
Input 2: ["I", "am", "just", "a", "man"] (or "I am just a man")
Output 2:
jjjjjjjjjjjj
juuuuuuuuuuj mmmmmmmmm
aaaaaa jussssssssuj maaaaaaam
III ammmma justtttttsuj aaa mannnnnam
I I am ma just tsuj a a man nam
III ammmma justtttttsuj aaa mannnnnam
aaaaaa jussssssssuj maaaaaaam
juuuuuuuuuuj mmmmmmmmm
jjjjjjjjjjjj
```
## Winning criteria:
The shortest code in bytes in each language wins. I will greatly appreciate if you comment/explain your code and approach.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~22~~ 20 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
l *;±21*{;l└*e⟳} ]r⤢
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjRDJTIwJXVGRjBBJXVGRjFCJUIxJXVGRjEyJXVGRjExJXVGRjBBJXVGRjVCJXVGRjFCJXVGRjRDJXUyNTE0JXVGRjBBJXVGRjQ1JXUyN0YzJXVGRjVEJTIwJXVGRjNEJXVGRjUyJXUyOTIy,i=JTVCJTIySSUyMiUyQyUyMCUyMmFtJTIyJTJDJTIwJTIyanVzdCUyMiUyQyUyMCUyMmElMjIlMkMlMjAlMjJtYW4lMjIlNUQ_,v=8)
Explanation:
```
{ ] map over the inputs
l * array of length spaces - the canvas of the current word
; get the word back on top
± reverse it
21* repeat each character twice
{ } for each character
;l└ push the height of the item below (the canvas)
* repeat the character that many times vertically
e and encase the canvas in that char column
⟳ and rotate it clockwise for encasing the next time
∙ push another space as the separator of words
r center the words
⤢ and transpose the final output (as everything was built vertically)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
FA«≔LιθMθ↑Fθ«B⁻׳θ⊗κ⊕⊗⁻θκ§ικ↘»M⊕⊗θ→
```
[Try it online!](https://tio.run/##bU49D4IwFJzhVzRMrwlObjhhXEhkMToRBoQKVXgFWpDE8NtrC7K5XHL37uPlVdbnIqu1foieQITtoIBS8nGdUEpeIpwZlqoCTn3S0YPrxGJk0PkkuLWWLrFuCThHMUHMcZBw5Q2TsLcRn5zEcK9ZAS9qSIR5zxqGygjbYc2YTuMwllBFWLAJ@CKYjXUzOIk3XnhZKavNv0/@9XW2Jdiss9ZJ4kWeT7yssfgcpFqYhSZDL031bqy/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FA«
```
Loop over the input list.
```
≔Lιθ
```
Get the length of the current word.
```
Mθ↑
```
Move to the top left corner of the resulting outline.
```
Fθ«
```
Loop once for each character.
```
B⁻׳θ⊗κ⊕⊗⁻θκ§ικ
```
Draw a box of the appropriate height, width and character.
```
↘»
```
Move to the top left corner of the next box.
```
M⊕⊗θ→
```
Move to the next outline.
[Answer]
# [Haskell](https://www.haskell.org/), ~~188~~ ~~183~~ ~~174~~ ~~171~~ 167 bytes
~~-9~~ -13 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni).
```
e=[]:e
c#a=k c<$>k(c<$a!!0)a
k c s=c:s++[c]
f w=foldr(#)[p w]w
p=(' '<$)
s w=unlines.map unwords.foldr(zipWith(:))e$until(\a->all((p a>=).p)$f<$>w)(k=<<p.head)<$>f<$>w
```
[Try it online!](https://tio.run/##JY2xDoIwFEX3fsUTm9gXlTgTyu7s4IAML1BCpdSGtmniz2PV5ST33NzcifysjNk2JduuUqzfk5yhr3kzi0za7S5ILBvwsq/88dj2HRshyfFlhlXssXWQusScFAc41ByZz2W0Rlvly4UcRJte6@DL/@Ct3V2HSVSIikcbtBEPOjdkjBAOqJFYOuRj/k8oZlnXrpwUDZjFT24LaStdDLewAgcPbXEtTlDQ8uUz@vBLXyxki277AA "Haskell – Try It Online")
[Answer]
# Pyth, ~~34~~ 33 bytes
```
Jsm+;uCjR*2HG_.iddm\ dQjCm.[lJd;J
```
[Try it online.](https://pyth.herokuapp.com/?code=Jsm%2B%3BuCjR*2HG_.iddm%5C+dQjCm.[lJd%3BJ&input=%5B%22I%22%2C+%22am%22%2C+%22just%22%2C+%22a%22%2C+%22man%22%5D&test_suite_input=%5B%22code%22%2C+%22golf%22%5D%0A%5B%22I%22%2C+%22am%22%2C+%22just%22%2C+%22a%22%2C+%22man%22%5D&debug=0)
Dumps out a whole bunch of extra whitespace, but that's allowed by the challenge.
### Explanation
* `m`…`Q` does the following for each word `d` in the input `Q`:
+ `m\ d` maps the word with `x => " "`, essentially creating the list `[" ", ..., " "]` with as many items as the word has letters.
+ `.idd` interleaves the word with itself, repeating the word's letters twice. `_` reverses this string. `word` becomes `ddrrooww`.
+ `u` starts with `G` = the array of spaces, and applies the following with each letter in the interleaved string in `H`:
- `*2H` repeats the character twice.
- `jR`…`G` puts each string in `G` between the pair of characters.
- `C` swaps rows and columns. When these three steps are done twice with the same character in `H`, this outlines the lines in `G` with that character.
+ We now have the columns for the outlined word `d`. `+;` prepends a space column.
* `s` flattens the array of columns for each word, and `J` saves it in the variable `J`.
* `m`…`J` does the following for each column of the output:
+ `.[lJd;` pads both sides of the column with spaces so that the length of the column is equal to the number of columns. This is always sufficient padding to make the columns align vertically.
* `C` turns the columns to rows and `j` joins the rows with newlines.
### Alternative solution, 33 bytes
```
j.tsm.[L\ l+dsQ+;uCjR*2HG_.iddm\
```
[Try it online.](https://pyth.herokuapp.com/?code=j.tsm.%5BL%5C+l%2BdsQ%2B%3BuCjR%2a2HG_.iddm%5C+&input=%5B%22I%22%2C+%22am%22%2C+%22just%22%2C+%22a%22%2C+%22man%22%5D&test_suite_input=%5B%22code%22%2C+%22golf%22%5D%0A%5B%22I%22%2C+%22am%22%2C+%22just%22%2C+%22a%22%2C+%22man%22%5D&debug=0)
Note that there is a trailing space. Mostly the same algorithm, except only pads columns on the top and then transposes with space fill.
[Answer]
# [R](https://www.r-project.org/), 189 bytes
```
function(x,S=32,`+`=rbind,`*`=cbind)cat(intToUtf8(Reduce(`+`,Map(function(s,K=utf8ToInt(s),o=S-!K){for(i in rev(K))o=i+i*o*i+i
for(j in(0:(max(nchar(x))-nchar(s)))[-1])o=S*o*S
o+S},x))+10))
```
[Try it online!](https://tio.run/##PYxBCsIwEEX3PUVddaZNwepGxBygFDdGVyI0pg2m0ETSVAri2esUwcV8Hrz/x886PuSzHq0KxlmYmODbDauzmvu7sQ2r05qrhVDJAMaGs7sEvYNT24yqBSqyo3zC/8HAKj5S4exKG2BA5rjIVxW@tfNgYmNj376gQnTcZCZ1KWW0uI4crPfQywmsekgPE2L@owERr3lxo5GgiYhcJj6MfFasEWcNCpIyYYnsKbpxCAvT9dIm5L8 "R – Try It Online")
A collaboration between digEmAll and myself [in chat](https://chat.stackexchange.com/transcript/81960?m=47574639#47574639).
```
function(x){
S <- 32 # space
`+` <- rbind # alias for rbind
`*` <- cbind # alias for cbind
outlineWord <- function(s){ # function to construct the outline for each word
chars <- utf8ToInt(s) # convert to code points
output <- S - !chars # replace each char with 32 (space)
for(i in rev(chars))
o <- i + i * o * i + i # o <- rbind(i,cbind(i,o,i),i)
for(j in(0:(max(nchar(x))-nchar(s)))[-1])
o <- S * o * S # pad with spaces
o + S} # return with an additional row of spaces between words
outlines <- Map(outlineWord,x) # apply outlineWord to each element of x
outlines <- Reduce(`+`,outlines)# reduce by rbind
outlines <- outlines+10 # add row of newlines
cat(intToUtf8(outlines)) # convert back to strings and print
}
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~57~~ ~~51~~ 50 bytes
```
{⍉⊃⍪/,/((⊢-⌈/)≢¨⍵)⌽↑{⍪¨↓0 1↓⍕,∘⍉∘⌽⍣4/⍵,⊂⍉⍪¯1/⍵}¨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Bk9aPezkddzY96V@nr6GtoPOpapPuop0Nf81HnokMrHvVu1XzUs/dR20SgslVAfttkAwVDIPmod6rOo44ZIL1AEqiid7GJPlC1zqOuJpAgUPF6Q5BALdiQ2v//03QOrVD3VFdQT8wFElmlxSUgNhDnJuapAwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~26~~ 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¢π‼○MªΘ└ƒ∩┘?◙↕)fY╨nu⌂E┴6X
```
[Run and debug it](https://staxlang.xyz/#p=9be313094da6e9c09fefd93f0a12296659d06e757f45c13658&i=I+am+just+a+man&a=1)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 46 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εg©;ò<Uyη央∍«®>∍}y𫩪®Xиª˜».º.∊}¶«».C.B€SζJ»
```
Not too happy about it, but I'm glad it's working.
[Try it online](https://tio.run/##yy9OTMpM/f//3Nb0QyutD2@yCa08t/3c1kNLDq171NF7aPWhdXZAurby8AYge@WhVYfWRVzYcWjV6TmHdusd2qX3qKOr9tA2oNRuPWc9p0dNa4LPbfM6tPv//2ilkIzMYiUdJTCRVVpcAqQSgbg4M7cgJxXIKEkFi5XkgwRTQSKZaSACJFieX5QN0pcINiGvJDUvJTVFKRYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WqVP5/9zW9EMrrQ9vsgmtPLf93NZDSw6te9TRe2j1oXV2QLq28vAGIHvloVWH1kVc2HFo1ek5h3brHdql96ijq/bQNqDUbj1nPadHTWuCz23zOrT7v86hbfb/o6OVPJV0lBJzgURWaXEJiA3EuYl5SrE60UrJ@SmpSjoKSun5OWlggZCMzGKgPJhAUl@cmVuQA1SpVJIKFivJBwmmgkQy00AESLA8vygbpC8RbEJeSWpeSmqKUmwsAA).
**Explanation:**
```
ε # Map `y` over the (implicit) input-list
g # Take the length of the current item
© # Store it in the register (without popping)
; # Halve it
ò # Ceil and cast to integer at the same time
< # Decrease it by 1
U # Pop and store it in variable `X`
yη # Take the prefixes of the current string `y`
ε } # Map over these prefixes:
¤ # Take the last character of the string
®× # Increase it to a size equal to the length from the register
« # Append it to the current prefix
®> # Take the length from the register, and add 1
∍ # Shorten the string to that size
y # Push the string `y` again
ð« # Append a space
© # Store it in the register (without popping)
ª # Append it at the end of the list of modified prefixes
® # Push the string with space from the register again
Xи # Repeat it `X` amount of times
ª # Append them to the list
˜ # Flatten to remove the empty appended list if `X` was 0
» # Join by newlines
.º.∊ # Intersect mirror both horizontally and vertically
} # Close outer map
¶« # Append a newline after each (for the space delimiters)
» # Join everything by newlines
.C # Centralize it horizontally
# (too bad a centralize vertically isn't available..)
.B # Split on newlines again
€S # Convert each line to a list of characters
ζ # Zip, swapping rows/columns (with space filler by default)
J # Join the loose characters of every line to a string again
» # Join the lines by newlines (and output implicitly)
```
] |
[Question]
[
**421** is a rather popular dice game in France and some other European countries. It is mostly played in bars and pubs to determine who's going to buy the next round of drinks. The full game is usually played in two rounds, with tokens that each player tries to get rid of, but this is irrelevant here. ([Wikipedia page](https://fr.wikipedia.org/wiki/421_(jeu)) in French.)
The game is played with 3 standard cube dice.
## Task
Your task is to sort a non-empty list of distinct 3-dice rolls **[ X,Y,Z ]** from highest to lowest, by applying the scoring rules of this game.
## Basic scoring
* **4,2,1** is the highest possible combination. Depending on the rules, it may score 8, 10 or 11 points. Because we are sorting the rolls rather than counting the points, the exact value doesn't matter.
* Three Aces: **1,1,1** is the second highest combination and scores **7** points.
* Two-Aces: **X,1,1** (where **X** is 2 to 6) scores **X** points.
* Three-of-a-Kind: **X,X,X** (where **X** is 2 to 6) scores **X** points.
* Straights: **X,X+1,X+2** scores **2** points.
* All other rolls score **1** point.
## Settling ties
Whenever two rolls give the same number of points, the following rules apply:
* A Two-Aces is better than a Three-of-a-Kind. Example: **5,1,1** beats **5,5,5**.
* The Three-of-a-Kind **2,2,2** is better than a straight. Example: **2,2,2** beats **4,5,6**.
* Straights are ordered from lowest to highest. Example: **4,5,6** beats **2,3,4**.
* All other rolls are settled by sorting the dice from highest to lowest. Example: **6,5,2** beats **6,4,3**. (Therefore, the lowest possible combination in the game is **2,2,1**.)
Below are the 56 possible distinct rolls ordered from highest to lowest:
```
421 111 611 666 511 555 411 444 311 333 211 222 654 543 432 321
665 664 663 662 661 655 653 652 651 644 643 642 641 633 632 631
622 621 554 553 552 551 544 542 541 533 532 531 522 521 443 442
441 433 431 422 332 331 322 221
```
## Challenge rules
* You may take the rolls in any reasonable format, such as a list of lists `[[3,2,1],[4,2,1]]`, a list of strings `["321","421"]`, a list of integers `[321,421]`, etc. However, each die must be clearly identifiable with a value from **1** to **6**.
* For each roll, you can assume that the dice are sorted either from lowest to highest or from highest to lowest, as long as it is consistent. Please state in your answer which order you're expecting, if any.
* The shortest answer in bytes wins!
## Test cases
Using lists of strings with the dice sorted from highest to lowest:
### Inputs
```
[ "321", "654" ]
[ "222", "321", "211" ]
[ "333", "311", "331", "111" ]
[ "111", "222", "333", "444" ]
[ "321", "421", "521", "621" ]
[ "422", "221", "442", "421", "222" ]
[ "222", "111", "421", "211", "651", "652", "543" ]
```
### Expected outputs
```
[ "654", "321" ]
[ "211", "222", "321" ]
[ "111", "311", "333", "331" ]
[ "111", "444", "333", "222" ]
[ "421", "321", "621", "521" ]
[ "421", "222", "442", "422", "221" ]
[ "421", "111", "211", "222", "543", "652", "651" ]
```
[Answer]
# [Python](https://docs.python.org/), 93 bytes
```
lambda a:sorted(a,key=lambda x:(x!=421,x>111,-(x%100<12)*x-(x%111<1)*x*.9,(x%111==99)*-x,-x))
```
[Try it online!](https://tio.run/##bU/RDoIwDHz3K@aDCSPD0G6YQJg/oj5ggGhUIMjD@PrZjSVG4kvT9q5312Gebn2HttVn@6xe17piVfHux6mpo0o8mlmHrSkis9UKQZgjAIgkMjtI0xKQx8YPACVQH@9zsYxa5zmPEyMSw7kdxns3sTY6MUki7JApduGb7xYRxQIhwC8kpSSITKmjAmvc5Qn3jqnUStqruugs89a4ulfuFD1JYWCS3J983kmFkO4JXwjIlCS6/QA "Python 2 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 67 bytes
```
O$#^`(421|111)|(\d)((11)|\2\2)|(654|543|432|321)|\d{3}
$1$2$#4$#5$&
```
[Try it online!](https://tio.run/##JU4xDgIxDNvzjQbUk7LESfkCIx@o0CEdAwsDYqO8vSTHEMmxHTuv@/vxvM1DPa/zwuW6VocOVV1G7dtSa6KOjthPzUdzG24YhuS3j32JlcHFuTQ@zhmChJEASGKokpmJqYqZSkRTjOx68O5O6YtaaXkLJQ8NyTl2Prx7Xt75PzM6ciDx0A8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The numeric sort key is generated as follows:
```
421 42100421
111 11100111
611-211 610611- 210211
666-222 600666- 600222
654-321 01654- 01321
653-221 00653- 00221
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;Ø1,ẋ3$)Ẏṙ-;‘r’Ɗ€;œċ3$Ṇ63¦
6RṚÇiµÞ
```
A monadic link accepting a list of lists of dice rolls (each sorted descending) which yields the sorted rolls descending.
**[Try it online!](https://tio.run/##y0rNyan8/9/68AxDnYe7uo1VNB/u6nu4c6au9aOGGUWPGmYe63rUtMb66OQjQLmHO9vMjA8t4zILerhz1uH2zENbD8/7//9/dLSRDhDG6ihEG@oAIYhhAhQBM4xgImY6pggGWLGpjomOcWwsAA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8/9/68AxDnYe7uo1VNB/u6nu4c6au9aOGGUWPGmYe63rUtMb66OQjQLmHO9vMjA8t4zILerhz1uH2zENbD8/773K4/eGOnqOTHu6coRn5/390tLGRoY6CmalJrA6XQrSRkZGOAljEyNAQLGJsbAwUMQSKGBsDCUOosCFIBKIapMDEBKIfrNUERJiCjTWCqDYBKTQCy5kYQRUANSOsBBtnArUX5BwwAZQwNTGOjQUA "Jelly – Try It Online") ...or try [all rolls sorted lexicographically](https://tio.run/##VY6hTgNBFEU9X1GBIVlEd967Zv8Cu1mJgFTV1TUISCDBYNoKJAqL2Mou9D9mf2TKqJOXrLiZve@e83i/Wm1K6abdssnHt3R9k4/vedzfdvN2t563@/Pr/PTd/X38/v/L47PS6etKd3k8TC8Pp5/ps5TS98tmUb@hWfRtiG2IbY2JQqKQQiHxmsJrqtFYMBaMBWPBWLCwYBSMgoWC1ejQHJpDc2gOzaE5NIfm0DzQnK7Tdboeul6jkBSSQlJICkkhKSSFpJAUkkJSSApJIakgKc7EmTgTZwpnGoYL "Jelly – Try It Online")
### How?
This method builds a list of all rolls from highest to lowest\*, replacing `[4,2,1]` with `0` (an invalid input roll), in order to rank each roll using Jelly's first-index-of atom, `i`.
\* The list also includes repeats and redundant entries which wont affect the behaviour:
```
[[1,1,1],[6,1,1],[6,6,6],[5,1,1],[5,5,5],[4,1,1],[4,4,4],[3,1,1],[3,3,3],[2,1,1],[2,2,2],[1,1,1],[7,6,5],[6,5,4],[5,4,3],[4,3,2],[3,2,1],[2,1,0],[6,6,6],[6,6,5],[6,6,4],[6,6,3],[6,6,2],[6,6,1],[6,5,5],[6,5,4],[6,5,3],[6,5,2],[6,5,1],[6,4,4],[6,4,3],[6,4,2],[6,4,1],[6,3,3],[6,3,2],[6,3,1],[6,2,2],[6,2,1],[6,1,1],[5,5,5],[5,5,4],[5,5,3],[5,5,2],[5,5,1],[5,4,4],[5,4,3],[5,4,2],[5,4,1],[5,3,3],[5,3,2],[5,3,1],[5,2,2],[5,2,1],[5,1,1],[4,4,4],[4,4,3],[4,4,2],[4,4,1],[4,3,3],[4,3,2],[4,3,1],[4,2,2],0,[4,1,1],[3,3,3],[3,3,2],[3,3,1],[3,2,2],[3,2,1],[3,1,1],[2,2,2],[2,2,1],[2,1,1],[1,1,1]]
```
```
;Ø1,ẋ3$)Ẏṙ-;‘r’Ɗ€;œċ3$Ṇ63¦ - Link 1, build rolls: descending pips, P e.g. [6,5,4,3,2,1]
) - for each: e.g. X=5
Ø1 - literal [1,1]
; - concatenate [5,1,1]
$ - last two links as a monad (f(X)):
3 - literal 3
ẋ - repeat [5,5,5]
, - pair [[5,1,1],[5,5,5]]
Ẏ - tighten (to a list of rolls rather than pairs of rolls)
- - literal -1
ṙ - rotate left by (make rightmost [1,1,1] the leftmost entry)
Ɗ€ - for €ach: last three links as a monad (f(X)):
‘ - increment -> X+1
’ - decrement -> X-1
r - range -> [X+1,X,X-1]
- ...note: [7,6,5] and [2,1,0] are made but are redundant
; - concatenate
$ - last two links as a monad (f(P)):
3 - literal 3
œċ - combinations with replacement -> [[6,6,6],[6,6,5],...,[6,6,1],[6,5,5],...,[1,1,1]]
; - concatenate
¦ - sparse application...
63 - ...to indices: 63
Ṇ - ...what: NOT -> replaces the [4,2,1] entry with a 0
6RṚÇiµÞ - Main Link: list of rolls
µÞ - sort by the monadic link:
6 - six
R - range -> [1,2,3,4,5,6]
Ṛ - reverse -> [6,5,4,3,2,1]
Ç - call the last link as a monad -> [[1,1,1],[6,1,1],[6,6,6],[5,1,1],...]
i - first index of (e.g.: [1,1,1]->1 or [6,1,1]->2 or [4,2,1]->0)
```
[Answer]
# [R](https://www.r-project.org/), 73 bytes
```
(x=scan())[order(x!=421,x>111,-(x%%100<12)*x-(!x%%37)*x*.9,x%%37!=25,-x)]
```
[Try it online!](https://tio.run/##HYzbSsNAFEXf5ysmSGFSEuncjgjGHxEfio62tCQyCTh/H9fxYbEv7HPqvrs2rR/n2fX921I/S3Wtm1LwQ3v13g@ja4eDP51efOiPbXQdMT5hj4/Pw7/vppCHsfXvO3sbIEKCDKJdoAO@2gyiOZIhg6hPeBDVjCqit4HbwG3gNnBLjmTIIOoTHkQ1o4roLrKL7CI7fMKDqGZUEe0TfaJHM6qI@owHUcSYB1vP8@06f9vtUuzvZbkXu5bNLl92q9efe9lWY43Z/wA "R – Try It Online")
* Full program taking a list of integer from stdin and returning them in
descending order (i.e. `421 ... 221`)
* Started as partially inspired by [@Lynn answer](https://codegolf.stackexchange.com/a/169472/41725), now is basically a porting of it... so credits to @Lynn ;)
* Saved 2 bytes getting division remainder `x % 37` instead of `111`
**Explanation :**
For each of the numbers 5 keys are computed and used hierarchically to sort the array :
```
key1 = 0 if equal to 421, 1 otherwise
key2 = 0 if equal to 111, 1 otherwise
key3 = 0
- 1.0*x if number is x11 numbers (2 aces)
- 0.9*x if number is xxx numbers (3 of a kind)
key4 = 0 if number is a straight, 1 otherwise
key5 = -x
Then the array is sorted by key1 first, then by key2 in case of tie and so on...
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~76~~ ~~48~~ 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
421X3∍6LR©vy11«y3∍}®vy>y<ŸJ})D®3ãJsм)˜©IΣ®sk>
```
~~This turned out to be a lot longer than expected, but at least it's easy to implement. Will see if I can find a better solution..~~ Made the list by hand now, but still a bit long.
[Try it online](https://tio.run/##MzBNTDJM/f/fxMgwwvhRR6@ZT9ChlWWVhoaHVleC@LWH1pVV2lXaHN3hVavpcmid8eHFXsUX9miennNopee5xYfWFWfb/f8fraBkZGSkpKOgZGhoCKKAxoEoIwjPzBRKgZWYmhgrKcQCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u9t/EyDDC@FFHr5lP0KGVZZWGhodWV4L4tYfWlVXaVdoc3eFVq@lyaJ3x4cVexRf2aJ6ec2il57nFh9YVZ9v9r9X5H62gZGxkqKSjoGRmaqKkEMsFFDAyMgIJQMWNDA2h4sbGxmBxQ7C4sTGYMoRLG0LEYbohik1MYKZCjTOBUKZQS41guk0g2oygqkyMkBSDjERxGtQqE4QLwR6AUmAlpibGQD0A).
**Explanation:**
```
421 # Push 421 to the stack
X3∍ # ('1' lengthened to size 3) Push 111 to the stack
6LR # Take the range [6, 1]
© # Save this range in the register so we can re-use it
v } # Loop over this range:
y11« # Merge '11' with the current number `y`, and push it to the stack
y3∍ # Lengthen the current number `y` to size 3, and push it to the stack
®v } # Load the range [6, 1] from the register, and loop over it again:
y>y<Ÿ # Take the range [`y+1`, `y-1`]
J # And join them together to single 3-digit numbers
) # Push everything that's now on the stack to a single list
D # Duplicate this list
® # Load the range [6, 1] from the register again
3ã # Take the cartesian repeated three times
R # Reverse this list
J # Join every inner list to a single 3-digit number
s # Swap, so the duplicate list of above is at the top of the stack again
м # And remove all those items from the cartesian list
) # Combine both lists (as list of lists)
˜ # Flatten it
© # Store this full completed list (now equal to the challenge description,
# with some additional values we can ignore) in the register
I # Take the input-list
Σ # Sort it by:
® # The list we generated above
sk # Take the 0-indexed indices
> # And increase it by 1 (because apparently 0 is placed at the back,
# so '421' would always be at the end)
```
Here is the actual list the first part of the code generates:
```
['421','111','611','666','511','555','411','444','311','333','211','222','111','111','765','654','543','432','321','210','','665','664','663','662','661','656','655','','653','652','651','646','645','644','643','642','641','636','635','634','633','632','631','626','625','624','623','622','621','616','615','614','613','612','','566','565','564','563','562','561','556','','554','553','552','551','546','545','544','','542','541','536','535','534','533','532','531','526','525','524','523','522','521','516','515','514','513','512','','466','465','464','463','462','461','456','455','454','453','452','451','446','445','','443','442','441','436','435','434','433','','431','426','425','424','423','422','','416','415','414','413','412','','366','365','364','363','362','361','356','355','354','353','352','351','346','345','344','343','342','341','336','335','334','','332','331','326','325','324','323','322','','316','315','314','313','312','','266','265','264','263','262','261','256','255','254','253','252','251','246','245','244','243','242','241','236','235','234','233','232','231','226','225','224','223','','221','216','215','214','213','212','','166','165','164','163','162','161','156','155','154','153','152','151','146','145','144','143','142','141','136','135','134','133','132','131','126','125','124','123','122','121','116','115','114','113','112','']
```
[Try it online.](https://tio.run/##MzBNTDJM/f/fxMgwwvhRR6@ZT9ChlWWVhoaHVleC@LWH1pVV2lXaHN3hVavpcmid8eHFXsUX9mienvP/f7SCkpGRkZKOgpKhoSGIAhoCoowgPDNTKAVWYmpirKQQCwA)
As you can see it contains empty items; numbers like `765` or `210`; and numbers in the range `[216, 112]`. But we can all ignore these, because the items we want to actually sort are in the correct order.
---
## Original 76 bytes solution:
```
Σ•X˜„Éε´õñ€9Ú ù?ä0₅9úd5àPÎøŒccuĆYÑ,o¾eíË¿¼À8@gID=vÆOΣxjF¨O‡J₃^εR™\èv•667вsk>
```
[Try it online](https://tio.run/##MzBNTDJM/f//3OJHDYsiTs951DDvcOe5rYe2HN56eOOjpjWWh2cpHN5pf3iJwaOmVsvDu1JMDy8IONx3eMfRScnJpUfaIg9P1Mk/tC/18NrD3Yf2H9pzuMHCId3TxbbscJv/ucUVWW6HVvg/aljo9aipOe7c1qBHLYtiDq8oA9plZmZ@YVNxtt3//9EKSkZGRko6CkqGhoYgysQITBlBeGamUAqsxNTEWEkhFgA) ~~or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5vn/3OJHDYsiTs951DDvcOe5rYe2HN56eOOjpjWWh2cpHN5pf3iJwaOmVsvDu1JMDy8IONx3eMfRScnJpUfaIg9P1Mk/tC/18NrD3Yf2H9pzuMHCId3TxbbscJv/ucUVWW6HVvg/aljo9aipOe7c1qBHLYtiDq8oA9plZmZ@YVNxtt3/Wp3/0QpKxkaGSjoKSmamJkoKsVxAASMjI5AAVNzI0BAqbmxsDBY3BIsbG4MpQ7i0IUQcphui2MQEZirUOBMIZQq11Aim2wSizQiqysQISTHISBSnQa0yQbgQ7AEoBVZiamIM1AMA)~~ (no test suite because there is still [a bug with sort-by with compressed numbers not seeing the closing bracket to stop the sort](https://codegolf.stackexchange.com/questions/169125/sort-of-numbers/169126#comment408663_169126)).
**Explanation:**
```
Σ # Sort by:
•...•667в # The correctly sorted list of all possible rolls from the challenge
sk # Take the 0-indexed indices
> # And increase it by 1 (because apparently 0 is placed at the back,
# so '421' would always be at the end)
```
**Explanation** `•X˜„Éε´õñ€9Ú ù?ä0₅9úd5àPÎøŒccuĆYÑ,o¾eíË¿¼À8@gID=vÆOΣxjF¨O‡J₃^εR™\èv•667в`**:**
Everything between the two `•` is a [compressed number](https://codegolf.stackexchange.com/a/166851/52210) that is generated with the following program:
```
Z>β 255B
```
[Try it online.](https://tio.run/##FY6xrQJADENX@QOk@EnslBSMAaIAiQUZhJWOl8JyfLFz/vfzle9zbpfv56/s6zl3VUZmxixmwrDtECwpGu7uKLiqYqywOtQVXZsxEGjAfngjP0Z7/WjuDJkRWmjuDflp5r1Z@yd3yZiMyVj7DzN@4zd@4zd@13ajA3uxV28fmF1vL@ZmrsrHDw)
* `Z>`: Take the max of the list + 1 (`667` in this case)
* `β`: Convert the list from Base-`667` to a single number
* `255B`: And convert that single number to base `255` (using 05AB1E's code page), so we have our [compressed number](https://codegolf.stackexchange.com/a/166851/52210).
By using `667в` it converts this compressed number back to the original list.
[Answer]
# JavaScript (ES7), 96 bytes
```
d=>d.sort((a,b,g=(n,[x,y,z]=n)=>n**=n-421?y*z-1?x-y|y-z?~y%x|~z%y?1:2:3:x-1?3.1:5:5)=>g(b)-g(a))
```
Sorts rolls by adhering closely to the rules of scoring.
Expects an array of strings with individual rolls in descending order of
value, e.g. `["654"]`
[Try it online!](https://tio.run/##bVNNj5swEL3nV4wirRYiw8qfByon90ptDz1GUeUEwlJRiABFAa32r6fmmWrbqBzG1puZ9@bD/HRX15@66jIkTZsX97O953abp33bDVHk2JGVNmrY/sZGNh1sE9tts9nYJlGC78bNlPDdLRnfxmTavY9Pt7f36Wnc8UxkMrt5n0x5pjPts8roGCdl5OL4PpClnOyWTm3Tt3WR1m0Zff7@7WvaD13VlNV5jPKY0bPdPjM6@3u8enmhsroWDQ1FP9DJ9UW/Iv8N0Z7WUvA1o7XRak2H@AMXQsz44hac/@uWUsLN4ZYSB3@M4sH9hyvkKPUgtWiocOilIPHApQKJWIKV@CtnFvhf9Yu@@mgCrS4HQrSSSJ2ndHot3KUeqXNN3v6qpiIn13VupPZMrq7p0vZ9dawL6tq6DjO8ug4uS/sgEzTXJlhjvNW4a629VbjPI2BheGEqobZQNnbBUJiPlDOCCXk2DatgJSziDbzgNxq4DjzAoWXAZhRwBRy6BvxGAgnqIlSLGsCmwabBplWoDQh4NHg0eDR4NHiwR98pukC8QrySoS/cESlDj0AkkHnJh0/LOv14wy/1Y373X9zwmoYFRTFtSFBC3D/y1f03 "JavaScript (Node.js) – Try It Online")
# Explanation
Categories of rolls are raised to the following exponents:
```
421 5
Three Aces 5
Two Aces 3.1
Three-of-a-Kind 3
Straights 2
Other 1
```
**Ungolfed**
Mentally unwrapping the conditional checks gives me a headache, and I'm certain it can somehow be further golfed....
```
var f =
d => d.sort(
(
a, b,
g = (n, [x, y, z] = n) => // destructure rolls, e.g. "321" => ["3","2","1"]
n **= // differentiate scores by raising to the exponent corresponding to its category in the table above
// all conditionals check for a falsy value
n - 421
? y * z - 1 // ends with "11"
? x - y | y - z // three-of-a-kind
? ~y % x | ~z % y // straights, with operators chosen to correctly convert strings to numbers
? 1
: 2
: 3
: x - 1 // three aces
? 3.1
: 5
: 5
) =>
g(b) - g(a)
)
```
[Answer]
### Javascript, 101 chars, 116 bytes (UTF-8)
```
a=>(r=d=>(i="ƥoɣʚǿȫƛƼķōÓÞʎȟưŁ".indexOf(String.fromCharCode(d)),i<0?700-d:i),a.sort((a,b)=>r(a)-r(b)))
```
Takes an array of numbers representing the rolls like `[ 321, 654 ]`.
[Try it online!](https://tio.run/##PZG9TsMwEMdfJcpkS26U2ClILSlCVQcmJBhDBjcfbaCNIydF7cgDwMIGEgyIiYWNBYmhNJS@VDg7gcGnu//97ku@4Fe8CGWal50iT6NYzkV2Ga/qxKu5N0DSi8Cmnlm9iJ/n3f335/a1eqg@vt43N@u79ePudvtUvW2uTSvNonh5kqCzUqbZxEqkmA@nXA5FFKMIY5Ie2If7tt2Jeikm3CqELBHiZIy9gUQcdyQaY4zrvuH7PqMO2eu6AfHBEogCcH1KqfIJdRwIwZJW0VnGGGGgMeYQRxOOirTClKop568KNNd1Wwo8rUCm6QVTXHhdtQdVvVTEmkipmnKhD1WkSzWtqhtSTWhUTfxvr2c1F8B96lHSdVlbpXdr9wNVZ4EKgsBKhBzxcIpKwxsYocgKMYutmZgg8zjLF2XPMAyTGKVvB8Qwz7PTuFjMlApigo6k5Cv9IUgR8BeKGS3zOCzjqKcLnabQxLhf/wI)
**Explanation:**
I took the first 16 of the 56 possible distinct rolls (the ones that don't really follow any order) and I encoded them as a string: `"ƥoɣʚǿȫƛƼķōÓÞʎȟưŁ"`. Each character of this string corresponds the the first 16 possible rolls (`ƥ` is `421`, `o` is `111`, ...). Now for each two elements `a` and `b` of the array we just check their index from the string, if they are included the index is used, otherwise (the index is `-1`) we use the roll number itself (we substract it from `700` to inverse the order of the ones not included, **i.e.** to sort them in a decreasing order).
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~169~~ 102 bytes
All octal escapes are counted as one byte, as the Clean compiler will happily take them that way, but TIO and SE won't because they aren't well-formed UTF-8.
```
import StdEnv
$l=[e\\c<-:"\245\157\143\232\377\53\233\274\67\115\323\336\216\37\260\101\231\230\227\226\225\217\215\214\213\204\203\202\201\171\170\167\156\155\52\51\50\47\40\36\35\25\24\23\n\11\273\272\271\261\257\246\114\113\102\335",e<-l|c==toChar e]
```
[Try it online!](https://tio.run/##HU9NSwQxDL37K8qyxxlokqYF2TmpB8HbHjd7KLOjDsyH7I6C4G@3vgp9SWjyXl76achLmdfL5zS4OY9LGeeP9bq543Z5Wr7u9lN3Gsz6Q3u/Mw5qpMkoiLGwSUqmtQRSsIgOqQmLiURjipgwjt7IE6YqvDHjj9FmxQhqqjkAUPHIvmYGyChVgF@lNQJqyqZk6i0kC96wSCCAB6rYAgswUw1BAnSOADxzAB1rCGsI8iK6a4ZDO/30XbetD@/56oZzOW4Zx3du707M3DgialxgBK5V1P@AhgY5l9/@dcpvt9I@v5TH7yXPY3/7Aw "Clean – Try It Online")
Uses the fact that all the dice rolls, as integers modulo 256, are unique.
Conveniently, `Char` is treated (mostly) as a modulo 256 integer.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 48 bytes
```
oxs[]j421T]j7 2_sm+Ld,,ddjT9tS6_m_+LdS3 4.C_S6 3
```
Expects input as a nested array, each element ordered descending. Try it online [here](https://pyth.herokuapp.com/?code=oxs%5B%5Dj421T%5Dj7%202_sm%2BLd%2C%2CddjT9tS6_m_%2BLdS3%204.C_S6%203&input=%5B%20%5B3%2C2%2C1%5D%2C%20%5B4%2C2%2C1%5D%2C%20%5B5%2C2%2C1%5D%2C%20%5B6%2C2%2C1%5D%20%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=oxs%5B%5Dj421T%5Dj7%202_sm%2BLd%2C%2CddjT9tS6_m_%2BLdS3%204.C_S6%203%29NQ&test_suite=1&test_suite_input=%5B%20%5B3%2C2%2C1%5D%2C%20%5B6%2C5%2C4%5D%20%5D%0A%5B%20%5B2%2C2%2C2%5D%2C%20%5B3%2C2%2C1%5D%2C%20%5B2%2C1%2C1%5D%20%5D%0A%5B%20%5B3%2C3%2C3%5D%2C%20%5B3%2C1%2C1%5D%2C%20%5B3%2C3%2C1%5D%2C%20%5B1%2C1%2C1%5D%20%5D%0A%5B%20%5B1%2C1%2C1%5D%2C%20%5B2%2C2%2C2%5D%2C%20%5B3%2C3%2C3%5D%2C%20%5B4%2C4%2C4%5D%20%5D%0A%5B%20%5B3%2C2%2C1%5D%2C%20%5B4%2C2%2C1%5D%2C%20%5B5%2C2%2C1%5D%2C%20%5B6%2C2%2C1%5D%20%5D%0A%5B%20%5B4%2C2%2C2%5D%2C%20%5B2%2C2%2C1%5D%2C%20%5B4%2C4%2C2%5D%2C%20%5B4%2C2%2C1%5D%2C%20%5B2%2C2%2C2%5D%20%5D%0A%5B%20%5B2%2C2%2C2%5D%2C%20%5B1%2C1%2C1%5D%2C%20%5B4%2C2%2C1%5D%2C%20%5B2%2C1%2C1%5D%2C%20%5B6%2C5%2C1%5D%2C%20%5B6%2C5%2C2%5D%2C%20%5B5%2C4%2C3%5D%20%5D&debug=0).
```
oxs[]j421T]j7 2_sm+Ld,,ddjT9tS6_m_+LdS3 4.C_S6 3)NQ Final 3 tokens inferred from context
Implicit: Q=eval(input()), T=10
]j421T Convert 421 to base 10, wrap in array -> [[4,2,1]]
]j7 2 Convert 7 to base 2, wrap in array -> [[1,1,1]]
m tS6 Map d in [2,3,4,5,6] using:
,dd [d,d]
jT9 Convert 10 to base 9 -> [1,1]
+Ld, Prepend d to each of the above
_s Flatten and reverse -> [[6,1,1],[6,6,6]...[2,2,2]]
m 4 Map d in [0,1,2,3] using:
+LdS3 [d+1,d+2,d+3]
_ Reverse the above
_ Reverse the result -> [[6,5,4]...[3,2,1]]
_S6 [6,5,4,3,2,1]
.C 3 All 3-element combinations of the above, respecting order
s[ ) Wrap the 5 previous sections in an array, concatenate
ox NQ Order Q using each element's index in the above list
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes
```
Σ5βËyθyP‚yнÃ6βyË_y¥PΘy)(
```
[Try it online!](https://tio.run/##XVG7DcIwEF3FJUhu7Dt7jvRRhECioKKgcodEmQUQLWKBVDQ0pLeYgUVCnDh6ZyQXT6d373M@nra7w34Y4t3Frm9DfIbqe76Fz6u/@NiFvt2E96OK17BeDUNdW63M@Bqtaq@Vz9BplV6eslaU4MhNL08pQyqmI5cT5AlaQMpcsUZwo0yYM3hkMFnBIqSAYs0hg4huYLFAAmREZ4jNxoRCBjUNuOJmDsaiBWcxLq4jQhoQCN3EzcR1hNsSUnBFIS6MGYUYYhZTC13xsZOYKXTF2nIHC0j/fyEymKb5AQ "05AB1E – Try It Online")
Overall algorithm:
```
Σ )( # sort by the following, in decreasing priority:
5βË # 1 for 421, 0 otherwise
yθyP‚yнÃ6β # 7 for 111, X for XXX and X11, 0 otherwise
yË_ # 0 for XXX, 1 otherwise
y¥PΘ # 1 for sequences, 0 otherwise
y # the roll itself
```
Details:
```
5β # parse the roll as a base-5 number
Ë # are all digits equal? (base-5 421 is 111)
yθ # last die (equal to the 1st die iff we have XXX)
yP # product of dice (equal to the 1st die iff we have X11)
‚ # wrap the two in an array
yнà # keep only those that are equal to the 1st die
6β # parse as a base-6 number (111 -> [1, 1] -> 7)
yË # are all dice equal?
_ # boolean negation
y¥ # deltas ([a, b, c] -> [b - a, c - b])
P # product
Θ # 1 if it's equal to 1, 0 otherwise
```
] |
[Question]
[
You have come across an old Indian manuscript, one that describes mounds of buried treasure. The manuscript also tells you the location of the treasure, except that some crucial numbers have been encoded indirectly into the text. You figure out that the text uses a 'Kaadi' system, a restricted subset of the more common 'Katapayadi' system.
(The [Katapayadi](https://en.wikipedia.org/wiki/Katapayadi_system) system is an ancient Indian system to encode numerals as letters, often used as mnemonics to remember long numbers.)
Your task here is to decode text encoded in the Kaadi system and print out the numerical value.
### Details
**Input characters**
The Kaadi system is based on the [Katapayadi system's rules](https://en.wikipedia.org/wiki/Katapayadi_system#Rules_and_practices), but uses only the first row of consonants. Your text here has been transliterated to Latin alphabet, and is known to contain only:
* vowels 'a','e','i','o','u'
* consonants 'g','k','c','j', and their capital forms (to represent the [aspirated](https://en.wikipedia.org/wiki/Aspirated_consonant) form of those consonants), and 'ṅ' and 'ñ'.
(You may choose to receive and handle 'ṅ' as 'ng' and 'ñ' as 'ny' if that's more convenient in your language.)
**Value assignment**
In this system,
1. each consonant when followed by a vowel has a digit associated with it. These are:
`'k'=>1, 'K'=>2,`
`'g'=>3, 'G'=>4,`
`'ṅ'=>5,`
`'c'=>6, 'C'=>7,`
`'j'=>8, 'J'=>9,`
`'ñ'=>0`
*Note however, that these values apply only when these consonants are followed by a vowel.* `kacCi` has the same value as `kaCi` (`ka`,`Ci`=(1,7)) since the middle c is unaccompanied by a vowel.
2. Additionally, an initial vowel or sequence of two vowels represents a 0. `aikaCi` would be: `ai`,`ka`,`Ci` = (0,1,7)
3. Extra vowels anywhere else in the middle of the text have no value: `kauCia` is the same as `kaCi`, the extra vowels can be ignored.
**Final numeric value**
Once the digit values of the letters have been figured out, the final numerical value is obtained as the reverse order of those digits i.e. the first digit from the text is the least significant digit in the final value.
Eg.
`GucCi` has `Gu` and `Ci`, so (4, 7), so the final value is 74.
`kakakaGo` is (1,1,1,4), so the the answer is 4111.
`guṅKo` is (3,2), so encodes 23. (`gungKo` if using ASCII-equivalent.)
### Input
* A string containing a Kaadi-encoded text
+ will contain only vowels and the above consonants
+ the vowels are always in lowercase and occur in groups of no more than 2
+ you may choose to accept the letters for 5 and 0 either as their Unicode characters 'ṅ' and 'ñ' or as their ASCII equivalents 'ng' and 'ny' (they're in lowercase in either form)
+ you may assume there are no spaces or punctuations
### Output
* The numerical value of the text, as given by the above rules
+ for empty input, an empty output or any false-y output in your language of choice is acceptable, in addition to 0
+ for invalid input (input with anything other than vowels and the above consonants), the output is undefined - anything goes
### Test cases
```
"GucCi"
=> 74
"kakakaGo"
=> 4111
"aiKaCiigukoJe"
=> 913720
""
=> 0 //OR empty/falsey output
"a"
=> 0
"ukkiKagijeCaGaacoJiiKka"
=> 1964783210
"kegJugjugKeg"
=> 2891
"guṅKo"
=> 23
"Guñaaka"
=> 104
"juñiKoṅe"
=>5208
```
(the last ones can be:
```
"gungKo"
=> 23
"Gunyaaka"
=> 104
"junyiKonge"
=>5208
```
if you prefer that.)
Standard rules for [I/O](https://codegolf.meta.stackexchange.com/q/2447/73884) and [loopholes](https://codegolf.meta.stackexchange.com/q/1061/73884) apply. May the best golfer win!
[Answer]
# JavaScript (ES6), 83 bytes
```
s=>s.replace(s=/(^|[ṅcCjJñkKgG])[aeiou]/g,(_,c)=>o=(s+s).search(c)%10+o,o='')&&o
```
[Try it online!](https://tio.run/##dZGxbsIwEIZ3niJCKtgiJXGIChnCkiFSMlTqimh1co3rOOUiHFdC6toHYuzMk/RJ0qQSQxO4W//vv//uCvgAww@qqu/3@CqaXdyYeG3mB1GVwAUxsUeePzc/3188KbLzSecy3dINCIV260mXvLicxmuMiZkZOjcCDvyNcHrH/Bm6GE@ndDLBhuPeYCnmJUqyI@PU8kSNKXWG5XnOMhz19Bq6TvEK0upDxlifAJVDopS0GjPxH2uJiC2Wgd9nrge6ML7z@OSI96o@ejsojTg6aOvK1oPJt206l77cat1GlaoQCaQAHDOlcv1n0spZ9BAuV4uADTgtZGZlYWUuZG9iywWraHASadsv5njz7MFiNHjT@QSgr27UhfPD5hc "JavaScript (Node.js) – Try It Online")
### How?
We use the following regular expression to match either the beginning of the string or one of the Kaadi consonants, followed by a vowel:
```
/(^|[ṅcCjJñkKgG])[aeiou]/g
```
For each match in the input string, we invoke the following callback function that takes the content **c** of the capturing group as parameter:
```
(_, c) => o = (s + s).search(c) % 10 + o
```
We find the value of the consonant by looking for its position in the regular expression (coerced to a string by adding it to itself).
The consonants are ordered in such a way that their value is equal to their position modulo **10**:
```
string : / ( ^ | [ ṅ c C j J ñ k K g G ] ) [ a e i o u ] / g
position : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...
modulo 10: - - - - - 5 6 7 8 9 0 1 2 3 4 - ...
```
When we match the beginning of the string instead of a consonant, **c** is an empty string whose position in the regular expression is **0** -- which, conveniently, is the expected result in that case.
Finally, we insert this digit at the beginning of the output string **o**.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 41 bytes
```
T`ñkKgGṅcCjJ`d`.[aeiou]
^[aeiou]
0
\D
V`
```
[Try it online!](https://tio.run/##NYw9CgIxEEb77x6ClegZIgwkrdj4Qz7WEGYHDIhzBA@0pfWexJPEtZDXvOa9R3nqnbu@WkvuhzxPlqp83q8hjDHf8ubEos0vuP5li/MeOObexYegMP6QBiYG1erWYgEIN9PEqmMJFHJoUTUZUX3ZpwbxeeKSfgE "Retina – Try It Online") Link includes test cases. Explantion:
```
T`ñkKgGṅcCjJ`d`.[aeiou]
```
Translate the consonants that are followed by vowels.
```
^[aeiou]
0
```
Handle a leading vowel.
```
\D
```
Delete everything else.
```
V`
```
Reverse the result.
[Answer]
# [Python 2](https://docs.python.org/2/), 93 bytes
```
lambda s,h=u'ñkKgGṅcCjJ'.find:''.join(`h(c)`*(0>h(v)<h(c))for c,v in zip(u'ñ'+s,s))[::-1]
```
An unnamed function accepting a Unicode string which returns a string representation of the base ten result.
**[Try it online!](https://tio.run/##RY5BTsMwEEXX5BSWWNgucQSsqoh0k0Wk5AiAVOM4ySTUjmK7qOw5UJesexJOEuykCI000n//68@MJ9tp9Tjfsg2TSugaVJs627CtBxEcRj1Z5LEU5k@Zk0GRX4mxtXYWZVc/aaX9mMDKiWDfsMWU/Kdo1GQv8zs/vNUcmbjLHL6ch6otfr6/RN6XOGlA1SnGSa9BkX1HBN1vyP2uI0f6FBRt9IREfESg0CeMJBTgOxMbSp/TlD28ziFgpbEh4e3CiRxwjBweeJhCL4JXPAdo3aBLuYCVLtsNA1S8hV7mvOBc6BKgGlavdf7Vau0o3OXMfSWmaXQzTqDscjhGmLGdTzQkSDr/Ag "Python 2 – Try It Online")**
[Answer]
# Java 8, ~~136~~ 126 bytes
```
s->{for(int i=s.length,t;i-->0;)if("aeiou".contains(s[i]))System.out.print(i<1?0:(t="ñkKgGṅcCjJ".indexOf(s[i-1]))<0?"":t);}
```
[Try it online.](https://tio.run/##XVG9bsIwEN55CsuTIzURrATKkCESUenAiBiuxkkvDnaEbdQKMfaBGDvzJH2S1AlBLZElS3f@7vs5l3CEsNzJhldgDHkBVKcRIaisOOTABVm1JSFHjTvC2doeUBWbLTFB7Pvnkb@MBYucrIgic9KY8PmU6wPzDATnJqqEKuz7k40xDJ/HcYA5oyBQOxpxrazXM8xscBsE609jxT7Szka1V7EMZ5PFeMrsnF4vMivSn@8vnpRLGqHaiY/XvJ0LJ35yNl5QOrVBfG7i1lHt3irvqDfWWd97oT/3ENxSWWEso6njCdIu0L0loT2pfuxCBgli4aReiseXAW5QSokZFFiKBFIArpeImRyACufjZQPB1F0vAHfo/213oTrQLZT/sdrZPpaKOOvqyNQVdvZ62uGOK8V66nPzCw)
**Explanation:**
```
s->{ // Method with String-array parameter and String return-type
for(int i=s.length,t;i-->0;) // Loop backwards over the input-characters
if("aeiou".contains(s[i])) // If the current character is a vowel:
System.out.print( // Print:
i<1? // If we're at the first character:
0 // Print a 0
: // Else:
(t="ñkKgGṅcCjJ".indexOf(s[i-1]))<0?
// If the character before the vowel is also a vowel:
"" // Print nothing
: // Else:
t);} // Print the correct digit of the consonant
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes
```
ݵe€Øẹœpṫ€0F“kKgGṅcCjJ”iⱮUḌ
```
[Try it online!](https://tio.run/##y0rNyan8///o7kNbUx81rTk84@GunUcnFzzcuRrIM3B71DAn2zvd/eHO1mTnLK9HDXMzH21cF/pwR8//w@1ABZH//0dzKbmXJjtnKulwKWUngqB7PoidmOmd6JyZmV6ane@VChIAC4KI0uxsoFx6Zlaqc6J7YmJyvldmpnc2WCq9FGiTN1i/e@nhjYmJYOFYAA "Jelly – Try It Online")
Jelly has built-in for... 1-byte `ṅ`.
**Explanation**
```
ݵ Prepend 0 to the string.
e€ œp Split at...
Øẹ the vowels. (0 is not a vowel)
ṫ€0 For each sublist `l` takes `l[-1:]`.
If the initial list is empty the result is empty,
otherwise the result is a list contain the last element.
F Flatten. (concatenate the results)
“kKgGṅcCjJ”iⱮ Find the index of each character in the list.
Get 0 if not found (i.e., for `0` or `ñ`)
UḌ Upend (reverse) and then convert from decimal.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 101 bytes
```
lambda s,S=u'ñkKgGṅcCjJ':''.join(`S.find(c)`for c,n in zip(u'ñ'+s,s)if c in(n in'aeiou')*S)[::-1]
```
[Try it online!](https://tio.run/##TZAxbsJAEEV7TjGCYm2CgTVWDJZI48ISLiKFMonEZO11BsOuhb0F6XMgytScJCcxuPGi6f57fzSa6tx8a@W3I/DGHuRK6IxUEYFppLfssoFcf7QHPH5lCPVkuzbseinTIvn/@xXxfsMixqZ7TcrZbaeSVOYIdyf1CcREASn4ocrpKuypntQuSRD31OkQw5y0Ye54675Hkcc/2@pEqnGkM0yMiGnoujCC9QuEwaAnJXaT6B4GnHOLMcWYqDCl3uS9suKL0J9bqQdzmM1e3yA/Vs15JvFQ52fQpqlM87DR2jY0ZUkpFrTPY0wQhd4QpaVV@eo5CJcLn9uOGRbm/rLUXu4vHmBirhfExxXzoL0B "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), ~~104~~ 102 bytes
```
lambda s,S='ñkKgGṅcCjJ':''.join(str(S.find(c))for c,n in zip('ñ'+s,s)if c in(n in'aeiou')*S)[::-1]
```
[Try it online!](https://tio.run/##TZAxboNAEEV7n2LlFLubEMMCCjESaSiQoIgUyiTFZA1kwGYRsAXpcyCXqX2SnATjBtB0//3/NTPN0H@r2hnz4GM8wunrAKQz0oBezlVSRP9/vzIsY@pTuisV1qzrW5bucqwPTHKeq5ZIoyZYkx9s2BSiD53RccyJnER2IxQyVJry@5S/@/6j@BybFuue5WwbaRnilnNyR4IX4rmbmVRwm0jN0BVCLBgSCBELXak4my174Xi2tZhmYBHTfH0j2anpBzOHY5cNROm@0f2qcXEvoq4qTKDAMgshApAqRkyqxSr2T6737NhilSn09LNkWdx2Nqt7L2eAdYHljlc "Python 3 – Try It Online")
---
Saved
* -3 bytes, thanks to Rod
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 126 bytes
```
_=>(l=_.match(/[kgñṅcj][aeiou]/gi))?l.map(a=>"ñkKgGṅcCjJ".indexOf(a[0])).reverse``.join``+(/[ aiueo]/.test(_[0])?0:''):0
```
[Try it online!](https://tio.run/##bdDPboJAEAbwe59iw4XdmPJHTa0m4IEDiRxMejUEJjhsl0WWyK6pD9AH8tizT9InoZgetNXM9TffZL4KDtAVe9Hq50ZtsS@DPgtCWgeZswNdvFN3I/n59P31WVTpBlAok7pcMLasB9BSCELrfJIJjy8kqlaWI5otfqxLChsvZczZ4wH3Hea5UynR5PloiCQgDKrUdTR2mmYXuPQWts0WXl@oplM1OrXitKRWbIpIWIyMiE2CkMymNnv6RyRcJlZXNfV9/95BApEQ3Ei1wqud@5PZ2LvXFvklIfGI667fCO5afXRLqDs8EmV0a/SDG9fgB5lGSpEAFxVGEAMUaiVEIm92/PnLdPY6GfsPlrkZKk5uvhxP7lFszieAP5HeUFn/Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 152 143 bytes
```
func[s][t:"ñkKgGṅcCjJ"c: charset t
d: copy{}parse s[opt[1 2 not c(alter d 0)]any[copy n c not c(insert
d(index? find/case t n)- 1)| skip]]d]
```
[Try it online!](https://tio.run/##TU@7bsMwDNz9FYSmeCjadPTSwYMAe8sqaCAk2WVUSIIeQIO0Yz8oY@d8Sb/ElYGiEDiQdzzegdHo7WS0kN0ybEtxSiQp8sDuNzuv/Of7S43niakB1CvGZDLkTlfgw@X6GXYGkvAhiyM8g/MZ1AHfsomg4amX6C5il4ID9bcll0ysHnXQ5v0FltofFVafDK5/gGP/AclSkFLLLURyGRZgvKiRWPePLe7FfUMhzTgSrcX6yTR8K2nmYm09WOlsRuSIyk9Es20Va6nfz20EL/cb1ly2/QI "Red – Try It Online")
## Readable:
```
f: func[s] [
t: "ñkKgGṅcCjJ"
c: charset t
d: copy {}
parse s [
opt [ 1 2 not c (alter d 0) ]
any [
copy n c not c (insert d (index? find/case t n) - 1)
| skip
]
]
d
]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~48~~ ~~47~~ 45 bytes
```
'ng'98Ztt'y'whw11Y2m)'ykKgGbcCjJ'tfqXEt10<)oP
```
[Try it online!](https://tio.run/##HUy7CgIxEOz9kcXOs1KwixJIGgsLtXI94rpZL0HIctzXx0SGgXkxE5ZPfVRIBPvdvRRYYH7Pw3DbTmtYxJN9jiY6KK/v9VSGzWGdz/V4qWB1NAwrEOywuUlkj4aZVLILzfeoUUVaQRyDQYs4ZsfspTcSyClFJR@oWdJEvh9ZTQvifxKbZJ8TBfgB "MATL – Try It Online")
*('b' instead of 'd' to save a byte)*
*(-2 bytes thanks to Luis Mendo)*
MATLAB (and hence MATL) treating strings as a dumb series of bytes made porting @TFeld's Python solution harder than I imagined (maybe a straight loop solution would have been easier here?). Ended up using the alternate `'ng'`, `'ny'` input method, and replacing `ng` with `b` at the beginning for easier processing.
Explanation:
```
% Implicit input (assume 'junyiKonge')
'ng' % string literal
98 % 'b'
Zt % replace substring with another (stack: 'junyiKobe')
t % duplicate that (stack: 'junyiKobe' 'junyiKobe')
'y' % string literal
w % swap elements in stack so 'y' goes before input (stack: 'junyiKobe' 'y' 'junyiKobe')
h % horizontal concatenation (prepend 'y' to input string) (stack: 'junyiKobe' 'yjunyiKobe')
w % swap stack (stack: 'yjunyiKobe' 'junyiKobe')
11Y2 % place 'aeiou' in stack (stack: 'yjunyiKobe' 'junyiKobe' 'aeiou')
m % set places with a vowel to True i.e. 1 (stack: 'yjunyiKobe' 0 1 0 1 0 1 0 0 1)
) % index into those places (stack: 'jyKd')
'ykKgGdcCjJ' % string literal
tfq % generate numbers 0 to 9 (stack: 'jyKd' 'ykKgGdcCjJ' 0 1 2 3 4 5 6 7 8 9)
XE % replace elements in first array which are found in second,
% with corresponding elements from third
t10<) % keep only elements that are less than 10 (removes extraneous vowels)
o % convert from string to double (numeric) array (stack: 8 0 2 5)
P % flip the order of elements (stack: 5 2 0 8)
% (implicit) convert to string and display
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 27 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
âΔxñW⌡╪c§âaQ&δ▓äHê╠$╞╣;→◄vΓ
```
[Run and debug it](https://staxlang.xyz/#p=83ff78a457f5d8631583615126ebb2844888cc24c6b93b1a1176e2&i=GucCi%0AkakakaGo%0AaiKaCiigukoJe%0A%0Aa%0AukkiKagijeCaGaacoJiiKka%0Agu%E1%B9%85Ko%0AGu%C3%B1aaka%0A%E1%B9%85u%E1%B9%85u&a=1&m=2)
] |
[Question]
[
**Challenge**
Given an integer **n ≥ 4**, output a permutation of the integers **[0, n-1]** with the property that no two consecutive integers are next to each other. The value of a permutation `pi` is the sum of `abs(pi[i] - i)` for all indices `i`.
**Examples**
* `(1, 3, 0, 2)` has value `6`
* `(0, 2, 4, 1, 3)` has value `6`
* `(0, 2, 4, 1, 3, 5)` has value `6`
* `(0, 2, 4, 1, 5, 3, 6)` has value `8`
**Score of your answer**
The score of your answer is the sum of the values of your permutations for `n = 4 .. 14` plus the number of bytes your code takes. The lower the score, the better. Your code must give valid output for all those values of `n`.
You must be able to run your submission to completion on your machine.
In case of ties, time of last edit that resulted in the relevant score will be the decider.
**Isn't this the same question as [this one](https://codegolf.stackexchange.com/q/164700/194)?**
Answers to the linked question will not be competitive for this question as they make no effort to optimize the value of a permutation. For example for `n=10`, the permutation `[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]` given by most of the answers there gives a value of `30`. You can do much better than that.
For the permutation part of the question, the optimal value overall is at most `120`. (Thank you to @Laikoni.) Whereas Dennis's answer to the previous question scores [222](https://tio.run/##JYtNCsIwGAX3OcVDQVuKTSNBIVAI4sqFF3BV6lcbaRJpsuzdY392j5l535SetxJ3cs6EI5rh40cTewvj0HBxkddKwtjfQJZcpPfCH6xDrZBxhfNhyqFhSsZC60da@Euh4JigM5xmo/c5Y5FCDLWShSmFYNT2Hiva5pyvb93tKmwipT8). (Thank you to @user202729.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ ~~34~~ ~~33~~ ~~32~~ ~~31~~ 30 bytes, result: 120
Thanks to Dennis for -1 byte! (implicitly by fixing a Jelly bug, although the feature postdates the challenge)
```
ðRḟISị“Ƥ¿‘Ʋœ?$;@µ2x5~4¦ṁ_4$Ä’
```
New feature: accumulated sum (`Ä`).
[Try it online!](https://tio.run/##AWAAn/9qZWxsef//w7BS4bifSVPhu4vigJzDhsKkwr/igJjGssWTPyQ7QMK1Mng1fjTCpuG5gV80JMOE4oCZ/zRyMTTDh@G5hOG6oUpTxorGiuKCrFPigJxTY29yZTog4oCdO/8 "Jelly – Try It Online")
Use 1-indexing.
Takes linear time, too.
---
This C++ program generates the lexicographically smallest permutation, assuming that **|i - pi| ≤ width** (where **width** is a hardcoded constant) for all **0 ≤ i < n**, with time complexity about ***O(width2 × 22×width × n)*** (which is just ***O(n)*** for fixed **width**): [Try it online!](https://tio.run/##jVVtb5tIEP6Mf8U0lWwwoEB1dx/Ci@RLrV50vaqSXd2Ha2VhWNd7hQXBkviUpH89N7tgdrGtu0ZRArM788zMM/OQVpX7NU1fXl5TluZtRsI0aRpS83gyWGjZ8JokhWa6Jykva82QNjzL6Vaz5LSgvIknE8o4pCVrODlUNfx593b9W/RT0NmLhDLTeoTra0DYtiAN8Idy1qBDUeWkIIxPDHGRBRMDIW5uUsriWLyhC4t@xjidvcsobPGy/8uGx5BVpmky27dgDuabucS1wArD4cUKBK4HN0CLqmwaus0JhnudkR1lBD4ubn83ebnZ0Tx38qTh3ZP4s2l4wokFnyeGgSj9JURSQDaYg49lQRhCfwRPYGoxLETMqr8kmOcA/n43XdMPwz5H60vkiyJ3ZW2KRvRYkRf0TyELbPuYgbo3gEc9bjBYXDf2AkvUTllGDvgX5vP3i9V6Poct5UXSfFNxVKqRr/UuUPYu3CO2YmAa0raOjlX9Zwu/BMJvZ3pRhD4WenPKWoIVX8@NnvGy5WF4tVov1ku4CsNj3eGVLFKYhtDCKP6TDK5E5GMVNFKYzmFoyUHmTuM48i0NK90ntTnzZrZJpz6OyWScCURRJFAx4TCcfWYzwY8o4shNxLRC5td42O2UqREfhv4TzuYUBNfapAQXb/f3ju13MSsL0wDPOmK/0m6LpAUfYkeKtulIBMqhpl/3uEvlgzhEJ9W36I1KWUwGK/EHkuzvJJU7iEm1vJwCIwe@uU/ylpzya/uOpzEbx35HrqG5yC4WlIXISWyqAwdbafeDJVxU9wzjeaLxKF1GUz1YkEo/6KRksMEfn1Zr@HUJq7t3H5Zv@6plFsm2MYd7tu8qCkIchlEvsAuTvpurj8vbu8V7uF2sljeAWaUE@J5gg2tsM2uLLalxRWFLwOtd9LnwptMBM@7q1Sa@y@6M9MHDOkkrR1HO/hHkZj9I0BDKEQ6GhvV0gqTow5S0mJFnua56D4Z2y9eh358@qI7/KP/ntLhHnZZjICfhqO/QBXRRG42x3OlDGI21NLggj5tzfdz8n6IxR/N34IKc4e1Xgm0hETJT67FLGA0KKFJRgr4@TWfk4y5vmz0G7SVBBrF9jG0Fo8vywPWVHmnfig2vcYuj4RPafyoFB1CRumhNJqI97GlOzJGPwHkUg@m6I/uJIjLXd5WWdKzZIwf87M5gJqdll9NK7oyExq7RkkFSly3L@oZXNbnfaCReUs3vY9nUtV66n3/@xmZF8UgRhnNUhLHDWBak3zAb8tLFneuqd8ahnJMC1aL1O6bi2eeZHZdC5m6oOscYMqLRxVPhOqvW2pNMuvMt6so3@fisFk@juxux58nLi@95/wI "C++ (gcc) – Try It Online")
---
### How?
1. Write a C++ program attempting to solve the problem optimally.
2. Observe the pattern. We note that the sequence of all elements except 4 last ones is a prefix of
```
0 2 4 1 3 5 7 9 6 8 10 12 14 11 13 15 17 19 16 18 20 22 24 21 23 25 ...
```
3. Computes the sequence's incremental difference.
```
2 2 -3 2 2 2 2 -3 2 2 2 2 -3 2 2 2 2 -3 2 2 2 2 -3 2 2
```
Note the period 5.
4. The Jelly implementation:
* **n-4** first elements are taken from the sequence above. ***O(n)***.
* For **4** last elements, ~~just brute force all 24 possibilities~~. ***O(1)***.
(note: I no longer brute force all 24 possibilities from the 32-bytes version)
[Answer]
## CJam (60 bytes + 120 = 180 score)
```
{_5/4*8e!961=7_)er<:A\,^e!{A\+}%{2ew::-:z1&!},{_$.-:z1b}$0=}
```
[Online test suite with integrated scoring](http://cjam.aditsu.net/#code=15%2C4%3E%0A%0A%7B_5%2F4*8e!961%3D7_)er%3C%3AA%5C%2C%5Ee!%7BA%5C%2B%7D%25%7B2ew%3A%3A-%3Az1%26!%7D%2C%7B_%24.-%3Az1b%7D%240%3D%7D%0A%0A%25_p%7B_%24.-%3Az1b%7D%251b)
[Extension up to n=24](http://cjam.aditsu.net/#code=25%2C4%3E%0A%0A%7B_5%2F4*8e!961%3D7_)er8e!5076%3D0Wer8f%2B%2B%3C%3AA%5C%2C%5Ee!%7BA%5C%2B%7D%25%7B2ew%3A%3A-%3Az1%26!%7D%2C%7B_%24.-%3Az1b%7D%240%3D%7D%0A%0A%25p)
### Dissection
```
{
_5/4* e# Work out how much of the hard-coded prefix to use
8e!961=7_)er e# Prefix [0 2 4 1 3 5 8 6]
e# I identified this by brute forcing up to n=10 and looking for patterns
e# I then used the identified prefix [0 2 4 1] to brute-force further
<:A e# Take the desired prefix of the hard-coded array, and store a copy in A
\,^e! e# Generate all permutations of the values in [0 .. n-1] which aren't in A
{A\+}% e# Prepend A to each of them
{ e# Filter...
2ew::- e# Take each difference of two consecutive elements
:z e# Find their absolute values
1& e# Test whether 1 is among those absolute values
! e# Reject if it is
},
{ e# Sort by...
_$.- e# Take pairwise differences of permutation with the identity
:z e# Absolute values
1b e# Add them (by interpreting in base 1)
}$
0= e# Take the first
}
```
[Answer]
# [Haskell](https://www.haskell.org/), 146+89 score+bytes
```
f i|k<-mod i 4=scanl(+)1$take(i-2-k)(cycle[2,-3,2,3])++[[2],[2,2],[5,-3,2],[5,-3,2,2]]!!k
```
Repeats pattern [1,3,0,2], last `mod i 4` elements are hand tuned.
### Previous algorithm (132+116):
```
f i=last$filter(\a->all(`elem`a)[0..i-1]).(!!(i-1)).iterate((\l->map((:l).(+head l))[-3,2,-2,3])=<<)$pure<$>[i-3..i]
```
Bruteforces the correct number of jumps of length ±2 or ±3. Selects the last one that has the correct numbers in it, seems to work just fine and is a lot cheaper than implementing the score. Tio just runs out time before the last score, which is 18.
[Try it online!](https://tio.run/##PY0xbsMwDEV3n4IBPJCIJTR2psL2FTp2cASETeRaMJ0YlrLk8FGJDN0@8R/fnzjOXiTnEUInHFM5Bkl@wxObnkXw7MUvZ6bhw9pgDo4s7naoicgGBTl5xJOYfuEV8VO030@eryBEg2mqujJ11Tjq2pbK9bH5tuyHYBq1uRwv981DB/Gx2GdYv0OaEPknWrUYem@6olg43BS63gsA8QlmPXQN8P1uR4LhaO2hcdqvW7gp8Z9Q1TBTfl1G4d@YzVf9Bw "Haskell – Try It Online")
[Answer]
# Japt, 120 + 20 = 140
(Copying one of my solutions from the other challenge would have scored me 227)
```
o á k_äa d¥1ÃñxÈaYÃg
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=byDhIGtf5GEgZKUxw/F4QFhhWcNn&input=OA==) or use [this version](https://ethproductions.github.io/japt/?v=1.4.5&code=byDhIGtf5GEgZKUxw/F4yGFZw2cKeMhhWQ==&input=OA==) to check scores. Both versions may start crapping out on you around 9.
---
## Explanation
```
o :Range [0,input)
á :All permutations
k_ Ã :Remove sub-arrays that return true
äa : Get the consecutive absolute differnces
d¥1 : Do any equal 1?
È Ã :Pass the integers in each remaining sub-array through a function
aY : Get the absolute difference with the integer's index
x :Reduce by addition
ñ :Sort the main array by those values
ñ :Return the first sub-array
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 120 score + ~~112 106 91~~ 82 bytes
```
->n{(0...n).map{|a|a+(a+2)%5-([[],[],[0,4,3],[-1,4,4,4],[1,1,6,1]][n%5][a-n]||2)}}
```
[Try it online!](https://tio.run/##LY3BCoMwEER/JRchqcmSWO2lpD@y7GE9CD0YpCJaTb49TaDMwDzmMPPZxm@efDavcEkLAEHBzMsVOXIrue1UMxiJSLra6l7fSxpXoKig004/tCPC0AyEbALF2KmU8untU8gewPX/zSMuAic8SIvd14TzvUi81d@DFKzbXI8loyXD6ErF45q0OFu/U8o/ "Ruby – Try It Online")
The sequence is basically `(a-2)+(a+2)%5`.
If n mod 5 is not 0 or 1, the last 3 or 4 elements are different.
This is still half-hardcoded, always finds the best solution, maybe it could be golfed a little more, but I have run out of ideas.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 148 score + ~~109~~ 73 bytes
```
n=>[...Array(n)].map(_=>l=!m|l>n%5+2&&l>m+2?[+m,m=l+2][0]:l+2,m=n>4,l=~m)
```
[Try it online!](https://tio.run/##jZHBb8IgGMXv/hWfzWZoqESNXuzossOOO@3YNJNVqjQUDFTN4ty/3n2tNTHZDl548ID3foFSHITPndrVY2PXsil4Y3iSMsZenBNfxIQZq8SOfPBE82H1rRPzuKCz0UgnFZ09p7SKKq7pLEsn2RIVVyaZR5r/VGETe@CwejgV5xXT0mzqbTworAOi0J/HoOAJpgtUSkM4DQAE@gVRYYzz3BpvtWTaboiKQHSmKoCIPguGHFQI9dbZIxh5hFfnrCOBk36vawiAYgFFPTprNnC5FHQxHUSJZZMYSoRQKFeGS8lQMGVyvV9LT8rwnpZKea@wp3XKrgXAA@XwJuotE5@eiLTMYNxvnm8xpv9hrOHvXRQcp1mf35LiMQy4h7B9UZnva3WQnXsNazejq5P1dOfB7QcE77l1ctme82Hc/AI "JavaScript (Node.js) – Try It Online") Explanation: `l` keeps track of the last number generated and `m` keeps track of the next number of the opposite parity to `l`; once `l` exceeds `m+2` the variables are exchanged. An adjustment is made at the start of the sequence so that sequences whose lengths are not multiples of 5 do not miss out any numbers, and another adjustment is made for `n=4`.
] |
[Question]
[
# Definition
The maxima and minima of a given function are the largest and smallest values of the function either within a given range or otherwise within the entire domain of the function.
# Challenge
The challenge is to **find the local maxima and minima** of a given polynomial function **using any method you may like**. Don't worry, I will try my best to explain the challenge and keep it as simple as possible.
The input will contain **all the coefficients of the single variable polynomial** in either decreasing or increasing order of power (up to you). For example,
* `[3,-7,1]` will represent \$3x^2 - 7x + 1\$
* `[4,0,0,-3]` will represent \$4x^3 - 3\$
# How To Solve Using Derivatives
Now, let's say our input is `[1,-12,45,8]`, which is nothing but the function \$x^3 - 12x^2 + 45x + 8\$.
1. The first task is to find the derivative of that function. Since it is a polynomial function, so it is indeed a simple task to do.
The derivative of \$x^n\$ is \$n\times x^{n-1}\$. Any constant terms present with \$x^n\$ are simply multiplied. Also, if there are terms added/subtracted, then their derivatives are also added or subtracted respectively. Remember, the derivative of any constant numerical value is zero. Here are a few examples:
* \$x^3 \to 3x^2\$
* \$9x^4 \to 9\times4\times x^3 = 36x^3\$
* \$-5x^2 \to -5\times2\times x = - 10x\$
* \$2x^3 - 3x^2 + 7x \to 6x^2 - 6x + 7\$
* \$4x^2 - 3 \to 8x - 0 = 8x\$
2. Now solve the equation by equating the new polynomial to zero and get only the integral values of \$x\$.
3. Put those values of \$x\$ in the original function and return the results. **That should be the output**.
# Example
Let us take the example we mentioned earlier, i.e, `[1,-12,45,8]`.
* Input: `[1,-12,45,8]`
* Function: \$x^3 - 12x^2 + 45x + 8\$
* Derivative: \$3x^2 - 24x + 45 + 0 \to [3,-24,45]\$
* Solving equation: \$3x^2 - 24x + 45 = 0\$, we get \$x = 3\$ and \$x = 5\$.
* Now putting \$x = 3\$ and \$x = 5\$ in the function, we get the values \$(62,58)\$.
* Output: `[62,58]`
# Assumptions
1. Assume that **all the input coefficients are integers**. They can be in increasing or decreasing order of power.
2. Assume the **input to be at least a 2-degree polynomial**. If the polynomial has no integer solutions, you can return anything.
3. Assume that the final result will be integers only.
4. You can print the results in any order. The degree of the input polynomial would not be more than 5, so that your code can handle it.
5. The input will be valid so that the solutions of x are not saddle points.
Also, **you are not forced to do it by the derivative method. You can use any method you feel like.**
# Sample Input And Output
```
[2,-8,0] -> (-8)
[2,3,-36,10] -> (91,-34)
[1,-8,22,-24,8] -> (-1,0,-1)
[1,0,0] -> (0)
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
ASŒRḅ@Ðḟ
J’U×µṖÇḅ@€³
```
[Try it online!](https://tio.run/##y0rNyan8/98x@OikoIc7Wh0OT3i4Yz6X16OGmaGHpx/a@nDntMPtIPFHTWsObf7//3@0oY6uoZGOiamORawCAA "Jelly – Try It Online")
# Explanation
```
ASŒRḅ@Ðḟ Helper Function; find all integer solutions to a polynomial
All integer roots are within the symmetric range of the sum of the absolute values of the coefficients
A Absolute Value (Of Each)
S Sum
ŒR Symmetric Range; `n -> [-n, n]`
Ðḟ Filter; keep elements where the result is falsy for:
ḅ@ Base conversion, which acts like the application of the polynomial
J’U×µṖÇḅ@€³ Main Link
J Range of length
’ Lowered
U Reversed
× Multiplied with the original list (last value is 0)
µ Begin new monadic chain
Ṗ Pop; all but the last element
Ç Apply last link (get all integer solutions of the derivative)
ḅ@€³ Base conversion of the polynomial into each of the solutions; apply polynomial to each solution of the derivative.
```
The helper function in this program was taken from Mr. Xcoder's answer
[here](https://codegolf.stackexchange.com/a/154016/68942) which was based off of Luis's answer [here](https://codegolf.stackexchange.com/a/154009/68942)
[Answer]
# JavaScript (ES7), ~~129~~ 120 bytes
Takes the coefficients in increasing order of power.
```
a=>(g=x=>x+k?(A=g(x-1),h=e=>a.reduce((s,n,i)=>s+n*(e||i&&i--)*x**i,0))()?A:[h(1),...A]:[])(k=Math.max(...a.map(n=>n*n)))
```
### Test cases
```
let f =
a=>(g=x=>x+k?(A=g(x-1),h=e=>a.reduce((s,n,i)=>s+n*(e||i&&i--)*x**i,0))()?A:[h(1),...A]:[])(k=Math.max(...a.map(n=>n*n)))
console.log(JSON.stringify(f([0,-8,2]))) // (-8)
console.log(JSON.stringify(f([10,-36,3,2]))) // (91,-34)
console.log(JSON.stringify(f([8,-24,22,-8,1]))) // (-1,0,-1)
```
### Commented
```
a => ( // given the input array a[]
g = x => // g = recursive function checking whether x is a solution
x + k ? ( // if x != -k:
A = g(x - 1), // A[] = result of a recursive call with x - 1
h = e => // h = function evaluating the polynomial:
a.reduce((s, n, i) => // for each coefficient n at position i:
s + // add to s
n // the coefficient multiplied by
* (e || i && i--) // either 1 (if e = 1) or i (if e is undefined)
* x**i, // multiplied by x**i or x**(i-1)
0 // initial value of s
) // end of reduce()
)() ? // if h() is non-zero:
A // just return A[]
: // else:
[h(1), ...A] // prepend h(1) to A[]
: // else:
[] // stop recursion
)(k = Math.max( // initial call to g() with x = k = maximum of
...a.map(n => n * n) // the squared coefficients of the polynomial
)) // (Math.abs would be more efficient, but longer)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
a@x/.#&/@Solve[a=#;#'@x==0,x]&
```
Takes a pure-function polynomial (i.e. a polynomial with `#` as a variable and with a `&` at the end).
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T/RoUJfT1lN3yE4P6csNTrRVtlaWd2hwtbWQKciVu2/pjVXQFFmXomDVpq@QzUXl5FynJGuhbKaDohlrG0M4hqbKWsbGgCFlONMgHJAYSOwMiMTZW0LNS6u2v8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/) (with [`Polynomials`](https://github.com/JuliaMath/Polynomials.jl) package), 57 bytes
```
using Polynomials
x->map(Poly(x),roots(polyder(Poly(x))))
```
[Try it online!](https://tio.run/##yyrNyUw0@/@/tDgzL10hID@nMi8/NzMxp5grXcFWoUJB104hN7FAAyShUaGpo1CUn19SrFEA5KakFsGEgeB/cUZ@uUa6RrSBjoGOYSxQAAA)
Takes coefficients in increasing order, i.e. the first input is the constant term.
Example run:
```
julia> using Polynomials
julia> g = x -> map(Poly(x), roots(polyder(Poly(x))))
(::#1) (generic function with 1 method)
julia> g([8,45,-12,1])
2-element Array{Float64,1}:
58.0
62.0
```
[Answer]
# Java 8, ~~364~~ ~~239~~ ~~227~~ ~~226~~ 218 bytes
```
a->{int l=a.length,A[]=a.clone(),s=0,i,r,f=l,p;for(;f>0;A[--f]*=f);for(int n:A)s+=n<0?-n:n;for(r=~s;r++<s;){for(p=0,i=f=1;i<l;f*=r)p+=A[i++]*f;if(p==0){for(f=i=0;i<l;f+=a[i++]*Math.pow(r,p++));System.out.println(f);}}}
```
[Uses the same functionality from this answer of mine.](https://codegolf.stackexchange.com/a/154136/52210)
-8 bytes thanks to *@OlivierGrégoire* by taking the array in reversed order.
**Explanation:**
[Try it online.](https://tio.run/##dZFdb8IgFIbv9yuIVyAfaatbjIhLf4DeeNn0gtWiuEqbgprFdH@9ox9L3LIRCDkPbw7nvOckr5KWVW5O@/c2K6S1YCO1uT8BoI3LayWzHGy7EIBrqfcgg54zxiTiHjb@@L0FBgjQSrq@@1dQCMmK3BzckcRJ6oOsKE0OEbEiIJrURImCVFyVNeRqHfA4oVSlU6FQz7oUZhkji4VZBa/ULE3Pa/FpeY3xynJ070DVpRNKhFyvCq6mokYVFnGiMU6nimvlFSIYtEpoEQw6LOQg2Uh3ZFV5gzWpMEaI7z6sy8@svDhW1b6MwkBfU9M0LX/ybVaXt0JnwDrp/NXbcfZmwZ3z4kOSSjQY5XLr4ILMnwkNIxL2To00IHRBokcSejR7IbOfdEFoNCdR1Ml/JQhGMHr/WE2v@J7PUIvJb/1EIWKGZVCOuf7odEL/W5Pxv6b9Ag)
```
a->{ // Method with integer-varargs parameter and integer return-type
int l=a.length, // The length of the input-array
A[]=a.clone(), // Copy of the input-array
s=0, // Sum-integer, starting at 0
i, // Index-integer
r, // Range-integer
f=l, // Factor-integer, starting at `l`
p; // Polynomial-integer
for(;f>0; // Loop over the copy-array
A[--f]*=f); // And multiply each value with it's index
// (i.e. [8,45,-12,1] becomes [0,45,-24,3])
for(int n:A) // Loop over this copy-array:
s+=n<0?-n:n; // And sum their absolute values
for(r=~s;r++<s;){ // Loop `r` from `-s` up to `s` (inclusive) (where `s` is the sum)
for(p=0, // Reset `p` to 0
i=f=1; // and `f` to 1
// (`i` is 1 to skip the first item in the copy-array)
i<l; // Inner loop over the input again, this time with index (`i`)
f*=r) // After every iteration: multiply `f` with the current `r`
p+= // Sum the Polynomial-integer `p` with:
A[i++] // The value of the input at index `i`,
*f;} // multiplied with the current factor `f`
if(p==0){ // If `p` is now 0:
for(f=i=0; // Use `f` as sum, and reset it to 0
i<l; // Loop over the input-array
f+=a[i++]*Math.pow(r,p++));
// Fill in `r` in the parts of the input-function
System.out.println(f);}}}
// And print the sum
```
[Answer]
# [Haskell](https://www.haskell.org/), 89 bytes
*-3 bytes thanks to Laikoni.*
```
r#l=foldr1((.(r*)).(+))l
r l|_:d<-zipWith(*)[0..]l,t<-sum$abs<$>d=[i#l|i<-[-t..t],i#d==0]
```
[Try it online!](https://tio.run/##FcPRCsIgFADQ975CmA@6VLYoiNB@oweRWGjssrs1rtZD7N@NDpxxyFNCrJUadM8XRuqFMIJaKY3YS4k7YrjdL9HqL6w3KKNope@MCaiK1fk98@GRLb9G56HBDaz2uhhTgoImOteFOg@wMMdWgqUwzug/fRLlxHyvdH9Qx5M6h/oD "Haskell – Try It Online")
Takes coefficients reversed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
J’×UḊÆrḅ@
```
[Try it online!](https://tio.run/##y0rNyan8/9/rUcPMw9NDH@7oOtxW9HBHq8P/0MPtj5rW/P8fbaGjYGKqo6BraKSjYBiroxBtAOQABY1AbEMQx9hMR8EYKgCU0DUyAXKMIKpgOgxATAA "Jelly – Try It Online")
Takes input as a list of coefficients in decreasing order of powers
## How it works
```
J’×UḊÆrḅ@ - Main link. Takes a list of coefficients C on the left
J - Yield indices; [1, 2, ..., len(C)]
’ - Decrement; [0, 1, ..., len(C)-1]
U - Yield C reversed
× - Multiply each element of C reversed by each element of [0, 1, ..., len(C) - 1]
Ḋ - Remove the leading 0
Ær - Solve the polynomial represented by the new list of coefficients
ḅ@ - Evaluate the roots as inputs to C (base conversion)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
∆Ċ:∆Kv∆Q
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiIbEijriiIZLduKIhlEiLCIiLCJbMiwzLC0zNiwxMF0iXQ==)
The power of **actual symbolic algebra**.
## Explained
```
∆Ċ:∆Kv∆Q
∆Ċ # Convert the list of coefficients into an expression that looks like a*x**n + b*x**(n-1) ... + z
: # Push a second copy of that
∆K # Get the stationary points of that (returns x values)
v∆Q # and sub those x-values into the original equation
```
[Answer]
# [Python 3](https://docs.python.org/3/), 156 bytes
```
def f(p,E=enumerate):a=lambda p,v:sum(e*v**i for i,e in E(p));d=[e*i for i,e in E(p)][1:];r=sum(map(abs,d));return[a(p,x)for x in range(-r,r+1)if a(d,x)==0]
```
[Try it online!](https://tio.run/##Zc3NCsMgEATgV/Go6RZqf6AkeMxTiIcNrq3QGNmYkD69Tc69zszH5G95T@lWq6cggszQG0rLSIyFVIvmg@PgUWRY23kZJTVr00QRJhYRSMQkepmV6ryx9J87q1vXsTnkiFniMIPf10xl4WRxv9vUYbZDMKYXyTMDn7SKQaD0e23MxdXMMRUZpH3C/QFnfQXtlKo/ "Python 3 – Try It Online")
-2 bytes thanks to Mr. Xcoder
-22 bytes thanks to ovs
[Answer]
# Python + numpy, 91
* 1 byte saved thanks to @KevinCruijssen
```
from numpy import*
p=poly1d(input())
print map(lambda x:int(polyval(p,x)),roots(p.deriv()))
```
[Try it online](https://tio.run/##FcvBCsIwDIDh@56ix0Sq0KEggk8yPHRUsdA0IWZjffpuXn@@X5p9uY69f5TJ1YWkuUzCaqdBnsKlhQS5ymKAOIjmao6iQIk0p@i2xxHgz9ZYQPyG6JXZfiCX9Na8Hhf2PgV/DqO/3vz9tQM).
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 28 bytes
```
p->[eval(p)|x<-polroots(p')]
```
Evaluate the polynomial at the roots of its derivative.
[Try it online!](https://tio.run/##HcrBCsIwEATQX1l6MUmzoJsiPWh/pDSQg5VCMEtaZAX/PSbeZuYNh7zhk8sKdyiM0/x4h6hYf@WGnGJO6dgVn/RSAnP8KAacgPP2OmrsWulgrX9tYRZPOBqxQEa8651pg7sa6S9nC@KHphWI/kJDlbEBLbr8AA "Pari/GP – Try It Online")
] |
[Question]
[
The challenge is simple:
**Create a pie-chart based on a number of input values.**
The input will be a list of positive numbers, decimal or integers, and the output will be a pie-chart where each of the input values are represented by separate colors, and a percentage value outside each of the areas.
**Rules:**
* The colors must be visually distinguishable (the exact colors are optional)
* There will be at least two, and maximum 10 input values
* The radius of the circle must be in the range `[100 300]` pixels
+ Vector graphics are OK as long as the default output gives a radius of `[100, 300]` pixels
* The percentage values shall be integers
+ There is no strict rule saying where the percentage value shall be placed, but it must be easily seen which area it belongs to
+ The distance between the closest character and the outer edge of the circle must be in the range `[5, 40]` pixels
+ The font is optional
* The plot may or may not have black lines separating each region
* Functions made for creating pie charts, for instance, MATLAB: `pie`, Python: `matplotlib.pyplot.pie` and Mathematica: `PieChart` are not allowed
* Normal rounding rules (up if it's `(1.00, 0.5]`, down if it's `(0.5, 0.00)`)
* If the percentage value of a slice is smaller than `0.5%`, output `0%`. The slice must still be included in the plot.
* Please provide plots for examination (or a link to an interpreter). It's enough to show only the plot with 10 input values (to avoid very long answers)
**Examples**
Please use the example values below. You can convert the lists to an appropriate format using a [numeric list converter](https://codegolf.stackexchange.com/questions/66345/make-a-numeric-list-converter), for instance this [27 byte one](http://cjam.aditsu.net/#code=l%29l_5ms%60-SerS%25*%5CS-_o_'%28%23%28f-&input=%20%3B%0A%7B16%2C2%2C77%2C29%7D) by [jimmy23013](https://codegolf.stackexchange.com/users/25180/jimmy23013).
```
x = [0.3, 1.2]
```
[](https://i.stack.imgur.com/M1jN6.jpg)
```
x = [3, 6, 2, 10]
```
[](https://i.stack.imgur.com/BsbeJ.jpg)
```
x = [0.4387, 0.3816, 0.7655, 0.7952, 0.1869, 0.4898, 0.4456, 0.6463, 0.7094, 0.7547]
```
[](https://i.stack.imgur.com/bz4Bn.jpg)
[Answer]
# Mathematica, ~~186~~ ~~183~~ 164 bytes
```
Graphics[{Hue@#,Disk[{0,0},{1,1},a=2Pi{##}],Black,Text[ToString@Round[100(#2-#)]<>"%",5Through@{Cos,Sin}@Mean@a/4]}&@@@Partition[Accumulate[#/Tr@#]~Prepend~0,2,1]]&
```
Could be golfed further. Currently generates a `Graphics` object. Test cases:

---

---

[Answer]
# JavaScript (ES6), ~~311~~ ~~310~~ ~~302~~ 298 bytes
```
a=>{with(Math)document.write(`<svg height=300>`+a.map(n=>`<path fill=#${(p*4e3|0).toString(16)} d=M135,150L${c(o=100,v=0)}A${[o,o,0,(v=n/=s)+.5|0,0,c(o)]}Z /><text x=${(z=c(135,v/=2))[0]} y=${z[p+=n,1]}>${n*o+.5|0}%</text>`,c=r=>[sin(d=PI*2*(v+p))*r+135,cos(d)*r+150],p=s=0,a.map(n=>s+=n)).join``)}
```
*Saved a byte with help from @Neil!*
## Explanation
Writes some SVG to the HTML of the current page. Builds the chart with centre point `135 x 150` of radius `100px` and text at a radius of `135px` from the centre.
```
var solution =
a=>{
with(Math)
document.write( // write to HTML body
`<svg height=300>`+ // create 300px x 300px SVG canvas (width defaults to 300px)
a.map(n=> // for each number
// Get the hex colour by multiplying the current position by (roughly) 0xfff
`<path fill=#${(p*4e3|0).toString(16)
// Calculate the path of the pie slice
} d=M135,150L${c(o=100,v=0)}A${[o,o,0,(v=n/=s)+.5|0,0,c(o)]
// Text
}Z /><text x=${(z=c(135,v/=2))[0]} y=${z[p+=n,1]}>${n*o+.5|0}%</text>`,
// Returns [ x, y ] for a certain radius at position v around the pie
c=r=>[sin(d=PI*2*(v+p))*r+135,cos(d)*r+150],
p=s=0, // p = current position around pie (0 - 1)
a.map(n=>s+=n) // s = sum of all numbers
).join``
+`</svg>` // <- this is just here for the test, so multiple charts can be displayed
)
}
// Test
;[
[0.3, 1.2],
[3, 6, 2, 10],
[0.4387, 0.3816, 0.7655, 0.7952, 0.1869, 0.4898, 0.4456, 0.6463, 0.7094, 0.7547]
].map(c=>solution(c));
```
[Answer]
# Python + PIL, ~~365~~ 355
```
from math import*;from random import*
from PIL import Image,ImageDraw
L,a,r=256,0,0.8;l,p,c=L/2,L/6,(L,L,L);I=Image.new('RGB',(L,L),c);D=ImageDraw.Draw(I)
x=input()
for i in x:b=a+ceil(360.0*i/sum(x));D.pieslice((p,p,L-p,L-p),int(a),int(b),tuple(map(randrange,c)));t=(a+b)*0.00872;D.text((l+cos(t)*l*r,l+sin(t)*l*r),str(int((b-a)/3.6))+'%',0);a=b
I.show()
```
[](https://i.stack.imgur.com/b936I.jpg)
Result for the largest example list :
[](https://i.stack.imgur.com/QTVX3.png)
] |
[Question]
[
[Clock](https://en.wikipedia.org/wiki/Clock_Patience) is an interesting card game, as it requires no skill. It is a single player game, and the same card configuration always leads to a win or a loss. In this challenge, **you need to figure out whether a given card configuration wins or loses**. You can [play the game here](http://www.mindjolt.com/clock-patience.html).
The game is played as follows:
1. Thirteen piles of cards are dealt face down. Each pile is numbered from 0 to 12.
2. We set the 0th pile to be the *current pile*
3. We flip the top card of the current pile face up.
4. We move the face up card at the bottom of its respective pile *(A 4 card goes under the 4th pile)*. The card remains face up. This pile becomes the current pile.
5. If the current pile is completely face up, then the game is over. Otherwise, go back to step 3.
*Tip: The game will always end on the 0th pile*
The game is won if all cards end up face up, and is lost if there are remaining face down cards.
# Input/Output
A 2D array containing each of the piles. Cards are represented with numbers from 0 to 12 (suit is irrelevant, and not given). The top card of each pile is the first element of each array.
You can assume that the input will be well formed: it will contain 52 cards from 0 to 12 (inclusive), and contain each number exactly 4 times.
You must return a truthy value if the game can be won, and falsy if it cannot.
# Test cases
Truthy:
```
[[11, 11, 7, 7], [8, 6, 5, 0], [2, 10, 9, 1], [12, 3, 0, 6], [8, 7, 4, 8], [3, 10, 5, 12], [11, 7, 1, 10], [3, 1, 6, 0], [2, 3, 0, 6], [5, 10, 5, 4], [12, 9, 11, 2], [9, 4, 12, 4], [1, 9, 8, 2]]
[[0, 9, 4, 8], [1, 4, 11, 3], [10, 12, 4, 0], [5, 9, 11, 5], [7, 0, 11, 2], [6, 5, 6, 0], [5, 7, 6, 7], [1, 10, 3, 4], [10, 11, 12, 3], [9, 9, 3, 6], [12, 12, 2, 1], [1, 8, 8, 2], [7, 2, 10, 8]]
[[11, 11, 9, 5], [3, 0, 1, 7], [6, 2, 9, 4], [6, 9, 11, 2], [10, 9, 6, 1], [12, 8, 10, 0], [2, 3, 12, 3], [3, 12, 5, 11], [4, 1, 8, 12], [7, 0, 2, 5], [4, 1, 10, 4], [7, 10, 6, 5], [8, 8, 0, 7]]
[[2, 3, 4, 11], [6, 12, 5, 9], [11, 0, 5, 9], [1, 8, 0, 12], [11, 9, 5, 8], [12, 7, 1, 0], [10, 3, 1, 11], [3, 12, 7, 2], [2, 7, 1, 5], [6, 3, 4, 10], [10, 10, 9, 8], [6, 2, 4, 4], [6, 8, 0, 7]]
[[1, 2, 12, 9], [5, 6, 4, 11], [0, 0, 7, 10], [9, 7, 12, 0], [12, 1, 8, 6], [10, 1, 4, 8], [9, 2, 6, 11], [10, 12, 1, 8], [6, 7, 0, 3], [2, 2, 5, 5], [8, 11, 9, 3], [4, 7, 3, 10], [5, 11, 4, 3]]
[[8, 12, 5, 3], [3, 10, 0, 6], [4, 11, 2, 12], [6, 1, 1, 12], [7, 6, 5, 0], [0, 8, 8, 7], [4, 8, 1, 2], [2, 3, 11, 6], [11, 10, 5, 2], [10, 1, 9, 4], [12, 5, 9, 7], [7, 3, 10, 9], [9, 0, 11, 4]]
[[3, 4, 8, 7], [2, 2, 8, 9], [12, 7, 0, 4], [4, 7, 10, 11], [5, 10, 3, 11], [10, 9, 8, 7], [5, 2, 11, 8], [6, 0, 3, 10], [9, 1, 4, 12], [12, 3, 12, 6], [2, 5, 1, 1], [6, 11, 5, 1], [6, 9, 0, 0]]
[[11, 9, 11, 1], [1, 3, 2, 8], [3, 3, 6, 5], [8, 11, 7, 4], [9, 4, 5, 1], [6, 4, 12, 6], [12, 10, 8, 7], [3, 9, 10, 0], [2, 8, 11, 9], [2, 4, 1, 0], [12, 5, 6, 0], [10, 7, 10, 2], [5, 0, 12, 7]]
[[9, 9, 6, 5], [7, 5, 11, 9], [8, 12, 3, 7], [1, 2, 4, 10], [11, 3, 3, 10], [2, 0, 12, 11], [4, 7, 12, 9], [3, 6, 11, 1], [1, 10, 12, 0], [5, 6, 8, 0], [4, 10, 2, 5], [8, 8, 1, 6], [0, 7, 2, 4]]
[[4, 0, 7, 11], [1, 5, 2, 10], [2, 9, 10, 0], [4, 12, 1, 9], [10, 12, 7, 0], [9, 4, 1, 8], [6, 6, 9, 12], [5, 3, 6, 2], [11, 3, 6, 4], [7, 3, 5, 5], [11, 8, 1, 11], [10, 7, 2, 8], [8, 12, 0, 3]]
```
Falsy:
```
[[8, 1, 6, 1], [7, 9, 0, 12], [11, 12, 12, 12], [11, 5, 9, 3], [2, 10, 9, 7], [11, 2, 0, 8], [0, 10, 4, 6], [8, 0, 4, 2], [6, 5, 3, 8], [4, 10, 3, 1], [5, 11, 9, 6], [7, 5, 1, 4], [2, 7, 3, 10]]
[[1, 4, 4, 6], [3, 11, 1, 2], [8, 5, 10, 12], [7, 10, 7, 5], [12, 8, 3, 7], [4, 0, 12, 12], [1, 1, 9, 6], [8, 7, 5, 10], [11, 0, 11, 0], [5, 10, 3, 11], [3, 2, 9, 8], [9, 6, 0, 2], [2, 6, 9, 4]]
[[10, 1, 10, 7], [12, 3, 11, 4], [0, 5, 10, 7], [5, 11, 1, 3], [6, 6, 9, 4], [9, 0, 8, 6], [9, 12, 7, 10], [1, 6, 3, 9], [0, 5, 0, 2], [4, 8, 1, 11], [7, 12, 11, 3], [8, 2, 2, 2], [8, 4, 12, 5]]
[[3, 8, 0, 6], [11, 5, 3, 9], [11, 6, 1, 0], [3, 7, 3, 10], [6, 10, 1, 8], [11, 12, 1, 12], [8, 11, 7, 7], [1, 8, 2, 0], [9, 4, 0, 10], [10, 2, 12, 12], [7, 4, 4, 2], [9, 4, 5, 5], [6, 2, 9, 5]]
[[0, 1, 9, 5], [0, 1, 11, 9], [12, 12, 7, 6], [3, 12, 9, 4], [2, 10, 3, 1], [6, 2, 3, 2], [8, 11, 8, 0], [7, 4, 8, 11], [11, 8, 10, 6], [7, 5, 3, 6], [0, 10, 9, 10], [1, 4, 7, 12], [5, 5, 2, 4]]
[[9, 8, 0, 6], [1, 1, 7, 8], [3, 2, 3, 7], [9, 10, 12, 6], [6, 12, 12, 10], [11, 4, 0, 5], [10, 11, 10, 7], [5, 3, 8, 8], [1, 2, 11, 4], [0, 5, 6, 0], [5, 9, 2, 4], [4, 2, 3, 11], [9, 1, 12, 7]]
[[4, 3, 5, 7], [1, 9, 1, 3], [7, 9, 12, 5], [9, 0, 5, 2], [7, 2, 11, 9], [1, 6, 6, 4], [11, 0, 6, 4], [3, 0, 8, 10], [2, 10, 5, 3], [10, 11, 8, 12], [8, 1, 12, 0], [7, 12, 11, 2], [10, 6, 8, 4]]
[[9, 5, 11, 11], [7, 7, 8, 5], [1, 2, 1, 4], [11, 11, 12, 9], [0, 12, 0, 3], [10, 6, 5, 4], [4, 5, 6, 8], [10, 9, 7, 3], [12, 6, 1, 3], [0, 4, 10, 8], [2, 0, 1, 12], [3, 9, 2, 6], [2, 7, 8, 10]]
[[4, 1, 5, 7], [7, 12, 6, 2], [0, 11, 10, 5], [10, 0, 0, 6], [10, 1, 6, 8], [12, 7, 2, 5], [3, 3, 8, 12], [3, 6, 9, 1], [10, 9, 8, 4], [3, 9, 2, 4], [11, 1, 4, 7], [11, 5, 2, 12], [0, 8, 11, 9]]
[[3, 11, 0, 1], [6, 1, 7, 12], [9, 8, 0, 2], [9, 6, 11, 8], [10, 5, 2, 5], [12, 10, 9, 5], [4, 9, 3, 6], [7, 2, 10, 7], [12, 6, 2, 8], [10, 8, 4, 7], [11, 3, 4, 5], [12, 11, 1, 0], [1, 3, 0, 4]]
```
[Answer]
## ES6, 57 bytes
```
a=>(g=n=>a.map((x,i)=>i&&x[3]==n&&++c&&g(i)),g(c=0),c>11)
```
This works because only the cards on the bottom of piles 1-12 are relevant, and they need to form a directed graph back to pile 0. So, I count the number of piles whose bottom card is 0, then the number of piles whose bottom card was one of the piles I counted earlier, etc. If I reach 12 piles then the configuration is a winning one.
Outline proof:
The game always ends when you turn over the last 0, since that pile effectively has one fewer card than the others.
If the bottom cards on piles 1-12 form a directed graph to pile 0, then in order to clear pile 0, we have to clear all the piles whose last entry is 0, and so on recursively to all the piles we have to clear so that we can clear the piles whose last entry is 0, and so forth. The configuration is therefore a winning one.
If the cards on the bottom of piles 1-12 do not form a directed graph to pile 0, there must exist at least one cycle. No pile in this cycle can be cleared, since it depends on the previous pile in the cycle. (In the case of a cycle of length 2, this is a chicken-and-egg situation.) The configuration is therefore a losing one.
[Answer]
## CJam, ~~23~~ 21 bytes
```
q~({(\a@+1$ff-m<(}h*!
```
[Run all test cases.](http://cjam.tryitonline.net/#code=cU4veycsLTpROwoKUX4oeyhcYUArMSRmZi1tPCh9aCohCgpdb30v&input=W1sxMSwgMTEsIDcsIDddLCBbOCwgNiwgNSwgMF0sIFsyLCAxMCwgOSwgMV0sIFsxMiwgMywgMCwgNl0sIFs4LCA3LCA0LCA4XSwgWzMsIDEwLCA1LCAxMl0sIFsxMSwgNywgMSwgMTBdLCBbMywgMSwgNiwgMF0sIFsyLCAzLCAwLCA2XSwgWzUsIDEwLCA1LCA0XSwgWzEyLCA5LCAxMSwgMl0sIFs5LCA0LCAxMiwgNF0sIFsxLCA5LCA4LCAyXV0KW1swLCA5LCA0LCA4XSwgWzEsIDQsIDExLCAzXSwgWzEwLCAxMiwgNCwgMF0sIFs1LCA5LCAxMSwgNV0sIFs3LCAwLCAxMSwgMl0sIFs2LCA1LCA2LCAwXSwgWzUsIDcsIDYsIDddLCBbMSwgMTAsIDMsIDRdLCBbMTAsIDExLCAxMiwgM10sIFs5LCA5LCAzLCA2XSwgWzEyLCAxMiwgMiwgMV0sIFsxLCA4LCA4LCAyXSwgWzcsIDIsIDEwLCA4XV0KW1sxMSwgMTEsIDksIDVdLCBbMywgMCwgMSwgN10sIFs2LCAyLCA5LCA0XSwgWzYsIDksIDExLCAyXSwgWzEwLCA5LCA2LCAxXSwgWzEyLCA4LCAxMCwgMF0sIFsyLCAzLCAxMiwgM10sIFszLCAxMiwgNSwgMTFdLCBbNCwgMSwgOCwgMTJdLCBbNywgMCwgMiwgNV0sIFs0LCAxLCAxMCwgNF0sIFs3LCAxMCwgNiwgNV0sIFs4LCA4LCAwLCA3XV0KW1syLCAzLCA0LCAxMV0sIFs2LCAxMiwgNSwgOV0sIFsxMSwgMCwgNSwgOV0sIFsxLCA4LCAwLCAxMl0sIFsxMSwgOSwgNSwgOF0sIFsxMiwgNywgMSwgMF0sIFsxMCwgMywgMSwgMTFdLCBbMywgMTIsIDcsIDJdLCBbMiwgNywgMSwgNV0sIFs2LCAzLCA0LCAxMF0sIFsxMCwgMTAsIDksIDhdLCBbNiwgMiwgNCwgNF0sIFs2LCA4LCAwLCA3XV0KW1sxLCAyLCAxMiwgOV0sIFs1LCA2LCA0LCAxMV0sIFswLCAwLCA3LCAxMF0sIFs5LCA3LCAxMiwgMF0sIFsxMiwgMSwgOCwgNl0sIFsxMCwgMSwgNCwgOF0sIFs5LCAyLCA2LCAxMV0sIFsxMCwgMTIsIDEsIDhdLCBbNiwgNywgMCwgM10sIFsyLCAyLCA1LCA1XSwgWzgsIDExLCA5LCAzXSwgWzQsIDcsIDMsIDEwXSwgWzUsIDExLCA0LCAzXV0KW1s4LCAxMiwgNSwgM10sIFszLCAxMCwgMCwgNl0sIFs0LCAxMSwgMiwgMTJdLCBbNiwgMSwgMSwgMTJdLCBbNywgNiwgNSwgMF0sIFswLCA4LCA4LCA3XSwgWzQsIDgsIDEsIDJdLCBbMiwgMywgMTEsIDZdLCBbMTEsIDEwLCA1LCAyXSwgWzEwLCAxLCA5LCA0XSwgWzEyLCA1LCA5LCA3XSwgWzcsIDMsIDEwLCA5XSwgWzksIDAsIDExLCA0XV0KW1szLCA0LCA4LCA3XSwgWzIsIDIsIDgsIDldLCBbMTIsIDcsIDAsIDRdLCBbNCwgNywgMTAsIDExXSwgWzUsIDEwLCAzLCAxMV0sIFsxMCwgOSwgOCwgN10sIFs1LCAyLCAxMSwgOF0sIFs2LCAwLCAzLCAxMF0sIFs5LCAxLCA0LCAxMl0sIFsxMiwgMywgMTIsIDZdLCBbMiwgNSwgMSwgMV0sIFs2LCAxMSwgNSwgMV0sIFs2LCA5LCAwLCAwXV0KW1sxMSwgOSwgMTEsIDFdLCBbMSwgMywgMiwgOF0sIFszLCAzLCA2LCA1XSwgWzgsIDExLCA3LCA0XSwgWzksIDQsIDUsIDFdLCBbNiwgNCwgMTIsIDZdLCBbMTIsIDEwLCA4LCA3XSwgWzMsIDksIDEwLCAwXSwgWzIsIDgsIDExLCA5XSwgWzIsIDQsIDEsIDBdLCBbMTIsIDUsIDYsIDBdLCBbMTAsIDcsIDEwLCAyXSwgWzUsIDAsIDEyLCA3XV0KW1s5LCA5LCA2LCA1XSwgWzcsIDUsIDExLCA5XSwgWzgsIDEyLCAzLCA3XSwgWzEsIDIsIDQsIDEwXSwgWzExLCAzLCAzLCAxMF0sIFsyLCAwLCAxMiwgMTFdLCBbNCwgNywgMTIsIDldLCBbMywgNiwgMTEsIDFdLCBbMSwgMTAsIDEyLCAwXSwgWzUsIDYsIDgsIDBdLCBbNCwgMTAsIDIsIDVdLCBbOCwgOCwgMSwgNl0sIFswLCA3LCAyLCA0XV0KW1s0LCAwLCA3LCAxMV0sIFsxLCA1LCAyLCAxMF0sIFsyLCA5LCAxMCwgMF0sIFs0LCAxMiwgMSwgOV0sIFsxMCwgMTIsIDcsIDBdLCBbOSwgNCwgMSwgOF0sIFs2LCA2LCA5LCAxMl0sIFs1LCAzLCA2LCAyXSwgWzExLCAzLCA2LCA0XSwgWzcsIDMsIDUsIDVdLCBbMTEsIDgsIDEsIDExXSwgWzEwLCA3LCAyLCA4XSwgWzgsIDEyLCAwLCAzXV0KW1s4LCAxLCA2LCAxXSwgWzcsIDksIDAsIDEyXSwgWzExLCAxMiwgMTIsIDEyXSwgWzExLCA1LCA5LCAzXSwgWzIsIDEwLCA5LCA3XSwgWzExLCAyLCAwLCA4XSwgWzAsIDEwLCA0LCA2XSwgWzgsIDAsIDQsIDJdLCBbNiwgNSwgMywgOF0sIFs0LCAxMCwgMywgMV0sIFs1LCAxMSwgOSwgNl0sIFs3LCA1LCAxLCA0XSwgWzIsIDcsIDMsIDEwXV0KW1sxLCA0LCA0LCA2XSwgWzMsIDExLCAxLCAyXSwgWzgsIDUsIDEwLCAxMl0sIFs3LCAxMCwgNywgNV0sIFsxMiwgOCwgMywgN10sIFs0LCAwLCAxMiwgMTJdLCBbMSwgMSwgOSwgNl0sIFs4LCA3LCA1LCAxMF0sIFsxMSwgMCwgMTEsIDBdLCBbNSwgMTAsIDMsIDExXSwgWzMsIDIsIDksIDhdLCBbOSwgNiwgMCwgMl0sIFsyLCA2LCA5LCA0XV0KW1sxMCwgMSwgMTAsIDddLCBbMTIsIDMsIDExLCA0XSwgWzAsIDUsIDEwLCA3XSwgWzUsIDExLCAxLCAzXSwgWzYsIDYsIDksIDRdLCBbOSwgMCwgOCwgNl0sIFs5LCAxMiwgNywgMTBdLCBbMSwgNiwgMywgOV0sIFswLCA1LCAwLCAyXSwgWzQsIDgsIDEsIDExXSwgWzcsIDEyLCAxMSwgM10sIFs4LCAyLCAyLCAyXSwgWzgsIDQsIDEyLCA1XV0KW1szLCA4LCAwLCA2XSwgWzExLCA1LCAzLCA5XSwgWzExLCA2LCAxLCAwXSwgWzMsIDcsIDMsIDEwXSwgWzYsIDEwLCAxLCA4XSwgWzExLCAxMiwgMSwgMTJdLCBbOCwgMTEsIDcsIDddLCBbMSwgOCwgMiwgMF0sIFs5LCA0LCAwLCAxMF0sIFsxMCwgMiwgMTIsIDEyXSwgWzcsIDQsIDQsIDJdLCBbOSwgNCwgNSwgNV0sIFs2LCAyLCA5LCA1XV0KW1swLCAxLCA5LCA1XSwgWzAsIDEsIDExLCA5XSwgWzEyLCAxMiwgNywgNl0sIFszLCAxMiwgOSwgNF0sIFsyLCAxMCwgMywgMV0sIFs2LCAyLCAzLCAyXSwgWzgsIDExLCA4LCAwXSwgWzcsIDQsIDgsIDExXSwgWzExLCA4LCAxMCwgNl0sIFs3LCA1LCAzLCA2XSwgWzAsIDEwLCA5LCAxMF0sIFsxLCA0LCA3LCAxMl0sIFs1LCA1LCAyLCA0XV0KW1s5LCA4LCAwLCA2XSwgWzEsIDEsIDcsIDhdLCBbMywgMiwgMywgN10sIFs5LCAxMCwgMTIsIDZdLCBbNiwgMTIsIDEyLCAxMF0sIFsxMSwgNCwgMCwgNV0sIFsxMCwgMTEsIDEwLCA3XSwgWzUsIDMsIDgsIDhdLCBbMSwgMiwgMTEsIDRdLCBbMCwgNSwgNiwgMF0sIFs1LCA5LCAyLCA0XSwgWzQsIDIsIDMsIDExXSwgWzksIDEsIDEyLCA3XV0KW1s0LCAzLCA1LCA3XSwgWzEsIDksIDEsIDNdLCBbNywgOSwgMTIsIDVdLCBbOSwgMCwgNSwgMl0sIFs3LCAyLCAxMSwgOV0sIFsxLCA2LCA2LCA0XSwgWzExLCAwLCA2LCA0XSwgWzMsIDAsIDgsIDEwXSwgWzIsIDEwLCA1LCAzXSwgWzEwLCAxMSwgOCwgMTJdLCBbOCwgMSwgMTIsIDBdLCBbNywgMTIsIDExLCAyXSwgWzEwLCA2LCA4LCA0XV0KW1s5LCA1LCAxMSwgMTFdLCBbNywgNywgOCwgNV0sIFsxLCAyLCAxLCA0XSwgWzExLCAxMSwgMTIsIDldLCBbMCwgMTIsIDAsIDNdLCBbMTAsIDYsIDUsIDRdLCBbNCwgNSwgNiwgOF0sIFsxMCwgOSwgNywgM10sIFsxMiwgNiwgMSwgM10sIFswLCA0LCAxMCwgOF0sIFsyLCAwLCAxLCAxMl0sIFszLCA5LCAyLCA2XSwgWzIsIDcsIDgsIDEwXV0KW1s0LCAxLCA1LCA3XSwgWzcsIDEyLCA2LCAyXSwgWzAsIDExLCAxMCwgNV0sIFsxMCwgMCwgMCwgNl0sIFsxMCwgMSwgNiwgOF0sIFsxMiwgNywgMiwgNV0sIFszLCAzLCA4LCAxMl0sIFszLCA2LCA5LCAxXSwgWzEwLCA5LCA4LCA0XSwgWzMsIDksIDIsIDRdLCBbMTEsIDEsIDQsIDddLCBbMTEsIDUsIDIsIDEyXSwgWzAsIDgsIDExLCA5XV0KW1szLCAxMSwgMCwgMV0sIFs2LCAxLCA3LCAxMl0sIFs5LCA4LCAwLCAyXSwgWzksIDYsIDExLCA4XSwgWzEwLCA1LCAyLCA1XSwgWzEyLCAxMCwgOSwgNV0sIFs0LCA5LCAzLCA2XSwgWzcsIDIsIDEwLCA3XSwgWzEyLCA2LCAyLCA4XSwgWzEwLCA4LCA0LCA3XSwgWzExLCAzLCA0LCA1XSwgWzEyLCAxMSwgMSwgMF0sIFsxLCAzLCAwLCA0XV0)
If the assignment of truthy and falsy was the opposite I could save 3 bytes:
```
q~{((\a@+1$ff-m<}h
```
### Explanation
>
> Putting the cards face up under another pile is a red herring. We might as well remove them from the game and keep playing until the current pile is empty. So that's what I'm doing: the code simply plays the game until the current pile is empty and then checks if any cards are left.
>
>
>
```
q~ e# Read and evaluate input.
( e# Pull off the first (current) pile.
{ e# While the current pile is non-empty...
(\ e# Pull off the top card and swap with the remaining pile.
a e# Wrap the pile in an array.
@+ e# Prepend it to the list of piles
1$ e# Copy the drawn card.
ff- e# Subtract it from all all remaining cards.
m< e# Rotate the stack to the left by the drawn card
( e# Pull off the top pile as the new current pile.
}h
* e# The top pile is empty. Joining the other piles with it, flattens them.
! e# Logical not, turns an empty array into 1 and a non-empty array into 0.
```
[Answer]
# Haskell, 85 bytes
```
(a:b)?n|n<1=tail a:b|1>0=a:b?(n-1)
l%i|null(l!!i)=all null l|1>0=l?i%(l!!i!!0)
f=(%0)
```
[Answer]
## Pyth, 13 bytes
```
!su@LGGXeMQZZ
```
Relies on @Neil's proof. `!su&VG@LGGeMQ` also works.
```
implicit: Q=input
! s u Sum of (apply lambda G,H on ... until fixed point) equals 0
@L Index G into itself.
G
G
Apply that to:
X set to
eM Q Last elts of input, with the
Z 0th
Z 0
```
Try it [here](http://pyth.herokuapp.com/?code=%21su%40LGGXeMQZZ&input=%5B%5B11%2C+11%2C+7%2C+7%5D%2C+%5B8%2C+6%2C+5%2C+0%5D%2C+%5B2%2C+10%2C+9%2C+1%5D%2C+%5B12%2C+3%2C+0%2C+6%5D%2C+%5B8%2C+7%2C+4%2C+8%5D%2C+%5B3%2C+10%2C+5%2C+12%5D%2C+%5B11%2C+7%2C+1%2C+10%5D%2C+%5B3%2C+1%2C+6%2C+0%5D%2C+%5B2%2C+3%2C+0%2C+6%5D%2C+%5B5%2C+10%2C+5%2C+4%5D%2C+%5B12%2C+9%2C+11%2C+2%5D%2C+%5B9%2C+4%2C+12%2C+4%5D%2C+%5B1%2C+9%2C+8%2C+2%5D%5D&debug=0).
[Answer]
**Python, 55 bytes**
```
x=lambda l,i=0:x(l,l[i].pop(0))if l[i]else[]==sum(l,[])
```
If the sublist is not empty, continue poping items. When it's empty, Return either all the lists are empty (by grouping them into one big list) or not.
[Answer]
## Jelly, 11 bytes
```
‘ịa
Ṫ€ÇL¡S¬
```
Try it [here](http://jelly.tryitonline.net/#code=4oCY4buLYQrhuarigqzDh0zCoVPCrA&input=&args=W1sxMSwgMTEsIDcsIDddLCBbOCwgNiwgNSwgMF0sIFsyLCAxMCwgOSwgMV0sIFsxMiwgMywgMCwgNl0sIFs4LCA3LCA0LCA4XSwgWzMsIDEwLCA1LCAxMl0sIFsxMSwgNywgMSwgMTBdLCBbMywgMSwgNiwgMF0sIFsyLCAzLCAwLCA2XSwgWzUsIDEwLCA1LCA0XSwgWzEyLCA5LCAxMSwgMl0sIFs5LCA0LCAxMiwgNF0sIFsxLCA5LCA4LCAyXV0).
] |
[Question]
[
Consider the process of:
1. Taking a non-negative integer N.
e.g. `27`.
2. Spliting it into integers `N - floor(N/2)` and `floor(N/2)` (a 'bigger' and 'smaller' half) and writing them in that order.
e.g.`27` becomes `14 13`.
3. Removing the space to join the integers into a new, much larger integer.
e.g. `14 13` becomes `1413`.
4. Repeating steps 2 and 3 some desired number of times.
e.g. `1413` → `707 706` → `707706` → `353853 353853` → `353853353853` → ...
This challenge is about doing exactly this, but not always in base 10.
# Challenge
Write a program that takes in three numbers, B, N, and S:
* B is an integer from 2 to 10 that is the base of N (binary to decimal).
* N is the non-negative integer to apply the splitting-rejoining process to. To make user input easier, it is given as a **string** in base B, not an integer.
* S is a non-negative integer that is the number of times to repeat the splitting-rejoining process.
The output of the program is the string representation of N in base B after S split-join procedures.
When S is `0`, no splits are done, so the output is always N.
When N is `0`, all splits have the form `0 0` and reduce to `0` again, so the output is always `0`.
# Examples
* `B = 10, N = 27, S = 1` → `1413`
* `B = 10, N = 27, S = 2` → `707706`
* `B = 9, N = 27, S = 1` → `1413`
* `B = 9, N = 27, S = 2` → `652651`
* `B = anything, N = anything, S = 0` → `N`
* `B = anything, N = 0, S = anything` → `0`
Table for all B with N = `1` for S = `0` to `7`:
```
B S=0 S=1 S=2 S=3 S=4 S=5 S=6 S=7
2 1 10 11 101 1110 111111 10000011111 10000100001000001111
3 1 10 21 1110 202201 101101101100 1201201201212012012011 212100212102121002121212100212102121002120
4 1 10 22 1111 223222 111311111311 2232222232322322222322 11131111131311311111311113111113131131111131
5 1 10 32 1413 432431 213441213440 104220331443104220331442 2433241322130211014044424332413221302110140443
6 1 10 33 1514 535535 245550245545 122553122553122553122552 4125434125434125434125441254341254341254341254
7 1 10 43 2221 11111110 40404044040403 2020202202020220202022020201 10101011010101101010110101011010101101010110101011010100
8 1 10 44 2222 11111111 44444454444444 2222222622222222222226222222 11111113111111111111131111111111111311111111111113111111
9 1 10 54 2726 13581357 62851746285173 3142536758708231425367587081 15212633743485606571782880411521263374348560657178288040
10 1 10 55 2827 14141413 70707077070706 3535353853535335353538535353 17676769267676676767692676771767676926767667676769267676
```
Table for all B with random N for S = `0` to `3`:
```
B S=0 S=1 S=2 S=3
2 11011 11101101 11101111110110 11101111110111110111111011
3 2210 11021101 20102012010200 1001212100121210012121001211
4 1113 230223 112112112111 2302302302323023023022
5 101 2323 11341134 31430423143042
6 120 4040 20202020 1010101010101010
7 134 5252 24612461 1230456412304564
8 22 1111 445444 222622222622
9 4 22 1111 505505
10 92 4646 23232323 1161616211616161
```
# Details
* Take input via stdin or the command line. Output to stdout.
* Instead of a program, you may write a function that takes B, N, and S and prints the result normally or returns it (as a string).
* B, N, and S may be taken in any order.
* All inputs that produce outputs whose decimal values are below 232 should work.
* N is represented in the usual way. i.e. most significant digit first and no leading zeros except in zero itself which is written `0`. (Outputting `00` instead of `0` is invalid.)
* **The shortest code in bytes wins.**
[Iff](http://en.wikipedia.org/wiki/If_and_only_if) you enjoy my challenges, consider giving [Block Building Bot Flocks!](https://codegolf.stackexchange.com/q/50690/26997) some love :)
[Answer]
# Pyth, ~~21~~ 19 bytes
```
vujksmjldQc2UiGQvwz
```
Takes input in the format `N\nB\nS`. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=vujksmjldQc2UiGQvwz&input=27%0A10%0A1&debug=0) or [Test harness](https://pyth.herokuapp.com/?code=z+Q%23w%3Dzw%3DQvw%0AvujksmjldQc2UiGQvwz&input=Test+Cases%3A%0A%22%22%0AB+%3D+10%2C+N+%3D+27%2C+S+%3D+1%0A27%0A10%0A1%0AB+%3D+10%2C+N+%3D+27%2C+S+%3D+2%0A27%0A10%0A2%0AB+%3D+9%2C+N+%3D+27%2C+S+%3D+1%0A27%0A9%0A1%0AB+%3D+9%2C+N+%3D+27%2C+S+%3D+2%0A27%0A9%0A2%0AB+%3D+5%2C+N+%3D+141%2C+S+%3D+0%0A141%0A5%0A0%0AB+%3D+9%2C+N+%3D+0%2C+S+%3D+4%0A0%0A9%0A4&debug=0)
### Explanation
```
implicit: z = 1st input (N)
Q = 2nd input evaluated (B)
u vwz reduce z (evaluated 3rd input) times by:
iGQ convert string from base Q to base 10
U create a range [0, 1, ..., ^-1]
c2 split into 2 lists (lengths are N-[N/2] and [N/2])
m map each list d to:
ld their length
j Q in base Q
s join both lists
jk join the numbers by ""
v convert string to int (getting rid of leading zeros)
```
[Answer]
# Pyth, 29 21 bytes
```
jku+j-JiGQK/J2QjKQvwz
```
Really straightforward implementation.
Takes input on stdin in the following format:
```
N
B
S
```
[Answer]
# Mathematica, 101 bytes
```
Nest[a~Function~(b=FromDigits)[Through@((c=IntegerString)@*Ceiling<>c@*Floor)[a/2],#],#2~b~#,#3]~c~#&
```
Uses some `Through` trickery to apply both the ceiling and floor functions. Just ignore the errors.
[Answer]
# CJam, 24 bytes
```
q~:B;{:~Bb_)\]2f/Bfbs}*i
```
[Test it here.](http://cjam.aditsu.net/#code=q~%3AB%3B%7B%3A~Bb_)%5C%5D2f%2FBfbs%7D*i&input=%221%22%207%202) Takes input as `"N" S B`.
## Explanation
```
q~ e# Read an eval input.
:B; e# Store the base in B and discard it.
{ }* e# Repeat S times.
:~ e# Turn the string N into an array of digits.
Bb e# Interpret as base B.
_)\ e# Duplicate and increment. Swap order.
]2f/ e# Wrap them in an array and (integer-)divide both by 2.
Bfb e# Convert both to base B.
s e# Flatten into a single string.
i e# Convert to an integer to fix the N = 0 case.
```
[Answer]
# JavaScript (*ES6*) 78 ~~79~~
Recursive function. Run snippet to test (Firefox only)
**Edit** 1 byte saved thx @DocMax
```
F=(b,n,s,S=x=>x.toString(b),m=parseInt(n,b))=>m*s?F(b,S(-~m>>1)+S(m>>1),s-1):n
// Ungolfed
U=(b,n,s)=>
{
var S=x=>x.toString(b) // function to convert in base b
var m=parseInt(n,b) // string in base b to integer
if (m==0 || s==0)
return n
else
return F(b,S((m+1)>>1) + S( m>>1 ),s-1)
}
// Test
test=[
{B: 10, N: '0', S:3, K: '0' }, {B: 10, N: '27', S: 1, K: '1413' }, {B: 10, N: '27', S: 2, K: '707706' }, {B: 9, N: '27', S: 1, K: '1413' }, {B: 9, N: '27', S: 2, K: '652651' }
];
test2=[[2, '11011', '11101101', '11101111110110', '11101111110111110111111011'],[3, '2210', '11021101', '20102012010200', '1001212100121210012121001211'],[4, '1113', '230223', '112112112111', '2302302302323023023022'],[5, '101', '2323', '11341134', '31430423143042' ] ,[6, '120', '4040', '20202020', '1010101010101010'],[7, '134', '5252', '24612461', '1230456412304564'],[8, '22', '1111', '445444', '222622222622'],[9, '4', '22', '1111', '505505'],[10, '92', '4646', '23232323', '1161616211616161' ]
]
test2.forEach(r=>test.push(
{B:r[0],N:r[1],S:1,K:r[2]}, {B:r[0],N:r[1],S:2,K:r[3]}, {B:r[0],N:r[1],S:3,K:r[4]}
))
test.forEach(t => (
r=F(t.B, t.N, t.S),
B.innerHTML += '<tr><th>'+(r==t.K?'Ok':'Failed')
+'</th><td>'+t.B +'</td><td>'+t.N
+'</td><td>'+t.S +'</td><td>'+r +'</td><td>'+t.K +'</td></tr>'
))
```
```
th,td { font-size: 12px; padding: 4px; font-family: helvetica }
```
```
<table><thead><tr>
<th>Test<th>B<th>N<th>S<th>Result<th>Check
</tr></thead>
<tbody id=B></tbody>
</table>
```
[Answer]
# ECMAScript 6, 90 bytes
```
var f=(B,N,S)=>((n,s)=>S?f(B,s(n+1>>1)+s(n>>1),S-1):s(n))(parseInt(N,B),x=>x.toString(B))
```
Defining a recursive function using a variable is not really good style, but it is the shortest code I could come up with in ECMAScript 6.
Getting the corner case `"00" => "0"` right wastes three bytes (`s(n)` instead of simply `N`).
To try it out, you can use [Babel's REPL](http://babeljs.io/repl/): copy/paste the code and print example invocation results like so: `console.log(f(9, "27", 2))`.
[Answer]
# Common Lisp - 113 characters
```
(lambda(b n s)(dotimes(i s)(setf n(format ()"~vR~vR"b (- #1=(parse-integer n :radix b)#2=(floor #1# 2))b #2#)))n)
```
# Ungolfed
```
(lambda(b n s)
(dotimes(i s)
(setf n (format () "~vR~vR" b (- #1=(parse-integer n :radix b)
#2=(floor #1# 2))
b #2#)))
n)
```
* The `~vR` format directive outputs integer in base `v`, where `v` is provided as an arguments to `format`.
* `parse-integer` accepts a `:radix` argument for converting from a specified base.
* `#1=` and `#1#` (respectively assign and use) are reader variables which allow to share common sub-expressions. When expanded, they give the following code:
```
(lambda (b n s)
(dotimes (i s)
(setf n
(format nil "~vr~vr" b
(- (parse-integer n :radix b)
(floor (parse-integer n :radix b) 2))
b (floor (parse-integer n :radix b) 2))))
n)
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 27 bytes
```
Lcb:+J[(bFB:a)%2i]+b//2TBab
```
Takes base, integer, and number of repetitions as command-line arguments. The algorithm is straightforward, but uses a couple interesting language features:
```
a, b, c initialized from cmdline args, and i = 0 (implicit)
Lc Do c times:
bFB:a Convert b from base a to decimal and assign back to b
[( )%2i] Construct a list containing b%2 and 0 (using i to avoid
scanning difficulties)
+b//2 Add floor(b/2) to both elements of list; the list now contains
b-b//2 and b//2
TBa Convert elements of list back to base a
J Join list
+ Coerce to number (necessary to turn 00 into plain 0)
b: Assign back to b
b Print b at the end
```
Pip's scalar type, which represents both numbers and strings, is handy here, as are item-wise operations on lists; unfortunately, parentheses and the two-character operators `FB`, `TB`, and `//` negate any advantage.
Alternate solution, without the intermediate assignment but still 27 bytes:
```
Lcb:+J[bFBa%2i]+bFBa//2TBab
```
[Answer]
# C, 245 bytes
```
int b,z,n,f,r;c(char*t,n){return n?((z=c(t,n/b)),z+sprintf(t+z,"%d",n%b)):0;}main(){char t[99],*p;gets(t);b=atoi(t);f=n=strtol(p=strchr(t,32)+1,0,b);if(!(r=atoi(strchr(p,32)+1)))f=0;while(r--)n=strtol(t+c(t+c(t,n-n/2),n/2)*0,0,b);puts(f?t:"0");}
```
This isn't going to win *anything*, but it was fun to make!
[Answer]
# [PHP](https://php.net/), ~~115~~ 112 bytes
```
function($b,$n,$s){while($s--)$n=($c=base_convert)(ceil($n=$c($n,$b,10)/2),10,$b).$c(floor($n),10,$b);return$n;}
```
[Try it online!](https://tio.run/##fZAxa8MwEIXn@FccRoNElDb2EowiCoVCh9IGuhZMLaTaYCQhOe0Q/NvdU3BCW5pMd7r3vnuHfOun7Z1vPegQXKiD9i4Mnf2gayaAGDmZvVVD5ywlDSeWk8gOX23Xa0riasWIlZQo2bxHXStnP3UYGFW66ykqRNFENLxYs9uSYcEHu8Gx6Z0LKJ5mIuhhHyyxYpxEplXrIL8HCajCM9Zyw@E1vd@GnONZFAWcFYzD7nFXP7w8XaPK31T5P1VdiKquJFUXgqo/OT/gzLgAFEiT/CLVbbo4dcslMDhki@N@/DbIcZ/IFjMRQSZbTMAmNSf/DBh6hAqePOxMj/PC8wXj9A0 "PHP – Try It Online")
Ungolfed:
```
function split_join_repeat( $b, $n, $s ) {
// repeat S times
for( $x=0; $x < $s; $x++ ) {
// convert N from base B to base 10 for arithmetic
$n = base_convert( $n, $b, 10 );
// divide and split in base 10, convert back to base B and join
$n = base_convert( ceil( $n / 2 ), 10, $b ) .
base_convert( floor( $n / 2 ), 10, $b );
}
return $n;
}
```
Output
```
B = 10, N = 27, S = 1 1413
B = 10, N = 27, S = 2 707706
B = 9, N = 27, S = 1 1413
B = 9, N = 27, S = 2 652651
2 1 10 11 101 1110 111111 10000011111 10000100001000001111
3 1 10 21 1110 202201 101101101100 1201201201212012012011 212100212102121002121212100212102121002120
4 1 10 22 1111 223222 111311111311 2232222232322322222322 11131111131311311111311113111113131131111131
5 1 10 32 1413 432431 213441213440 104220331443104220331442 12141204110401030043301214120411040103004330
6 1 10 33 1514 535535 245550245545 122553122553122553122552 131022143412311313533131022143412311313533
7 1 10 43 2221 11111110 40404044040403 2020202202020220202022020201 40556522600645213204055652260064521320
8 1 10 44 2222 11111111 44444454444444 2222222622222222222226222222 76650460747555347665046074755534
9 1 10 54 2726 13581357 62851746285173 3142536758708231425367587081 4861155667688600048611556676886000
10 1 10 55 2827 14141413 70707077070706 3535353853535335353538535353 17676769267677271767676926767727
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
```
_nW o ó ®ÊsWÃq}gV
```
[Try it online!](https://tio.run/##y0osKPn/Pz4vXCFf4fBmhUPrDncVhx9uLqxND/v/35ArWsnIXCmWy9AAAA "Japt – Try It Online")
Takes input in the order S, N, B with N as a [singleton list](https://codegolf.meta.stackexchange.com/a/11884/71434). Accepting N without a singleton list costs [2 bytes](https://tio.run/##y0osKPn/Pz4vXCFf4fBmhUPrDncVhx9uLqxNjw6L/f/fkEvJyFyJy9AAAA).
Explanation:
```
_ }g #Get the Sth item generated by this function...
V #...Starting with N as the 0th item:
nW # Evaluate the previous item as a base B number
o # Create a list with that length
ó # Divide it into two lists as evenly as possible
® Ã # For each of those lists:
Ê # Get the length
sW # Convert it to base B
q # Join the two strings together
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 105 bytes
```
: f base ! 0 ?do 0. 2swap >number nip 2drop 2 /mod >r i + r> 0 tuck <# #s 2drop #s #> loop type decimal ;
```
[Try it online!](https://tio.run/##VY5BcsIwDEX3nOLhLIE08YYBipnhAN1wghAnkCnBHicp09MHmYFp2Uj6T9KXahf68@JUxzSOa2qORVcxJWNnHVmK7m6Fx1yH9lgFro1H2@Ak8tE6iwk0zAhGNvqh/OYzIemeM1IkhouTsv/1FbYqm7a4sJFLnlSxZ4uyQ3RLQwRzDhG5H7n1x74i0w/48BHIwqDk3TKwmXQKvVTk5Bn@pfSbyln9b4kY7w "Forth (gforth) – Try It Online")
### Explanation
Changes the base to B, then in a loop that runs S times:
* Converts string to a number
* Splits number in 2 halves (one larger than the other if odd)
* Combines the two numbers back into a string
Prints the string when finished and sets the base back to 10 (so we can run multiple times in a row)
### Code Explanation
```
:f \ start a new word definition
base ! \ set the base to B
0 ?do \ loop from 0 to S-1 (runs S times)
0. 2swap \ places a double-length 0 on the stack behind the string
>number \ converts the string to a number in the current base
nip 2drop \ get rid of string remainder and second part of double
2 /mod \ get the quotient and remainder of dividing by 2
>r \ throw the quotient on the return stack
i \ get a copy of the quotient from the return stack
+ \ add quotient and remainder
r> \ move quotient from return stack to stack
0 tuck \ convert both to double-length numbers
<# \ start a pictured numeric output
#s \ add entire number to output
2drop \ drop empty number
#s \ add second number to output
#> \ convert output to a string and drop number from stack
loop \ end loop
type \ print output string
decimal \ set base back to 10
; \ end word definition
```
] |
[Question]
[
You are given a machine with two 16-bit registers, `x` and `y`. The registers are initialized `x=1` and `y=0`. The only operation the machine can do is addition modulo 65536. That is:
* `x+=y` - `x` is replaced by `(x + y) mod 65536`; `y` is unchanged
* `y+=x` - similarly for `y`
* `x+=x` - `x` is replaced by `2x mod 65536`; legal only if `x` is even
* `y+=y` - similarly for `y`
The goal is to get a predetermined number in one of the registers (either `x` or `y`).
Write a program or a subroutine that receives a number (in `stdin`, `argv`, function parameter, top of stack or any other conventional place), and outputs a program to get this number. The output should go to `stdout`, or (if your language has no `stdout`) to any other conventional output device.
The output program can be up to 100% plus 2 steps far from optimal. That is, if the shortest program to get the target number has `n` steps, your solution cannot be longer than `2n+2`. This restriction is to avoid "too easy" solutions (e.g. counting 1, 2, 3, ...) but not require full optimization; I expect that the shortest program is easiest to find, but cannot be sure...
For example: Input = 25. Output:
```
y+=x
x+=y
x+=y
x+=x
x+=x
x+=x
y+=x
```
Another example: For any fibonacci number, the output has this alternating pattern. For Input = 21, output is
```
y+=x
x+=y
y+=x
x+=y
y+=x
x+=y
y+=x
```
Shortest code (measured in bytes) wins.
(this puzzle was inspired by some code for a 16-bit processor I had to generate recently)
P.S. I wonder - for which number the optimal program is longest?
[Answer]
# Perl 107 97
First post, so here goes.
```
sub h{($i)=@_;return if(($i%=65536)==0);($i%4==0)?do{h($i/2);say"y+=y";}:do{h($i-1);say"y+=x";}}
```
Which fits all of the register addition criteria, but I didn't run an exhaustive check to see if my answer was always within 2n+2 of the optimal number of steps. It is well inside the limit for every Fibonacci number, though.
Here is a more detailed breakdown
```
sub h{ # Declare the subroutine, it should be called referencing an integer value
($i)=@_; # Assign the i variable to the integer used in the call
return if(($i%=65536)==0); # Check for base condition of called by 0, and enforce modulo from the start.
($i%4==0) ? # If the value passed is even, and will result in an even number if we halve it
do{h($i/2);say"y+=y";} # Then do so and recurse
:do{h($i-1);say"y+=x";} # Otherwise "subtract one" and recurse
} # Note that the print statements get called in reverse order as we exit.
```
As I mentioned, this is my first attempt at golfing, so I'm sure this can be improved upon. Also, I'm not sure if the initial subroutine call has to be counted in a recursive call or not, which could drive us up a few chars.
Interestingly we can reduce the code by 11 bytes\* and improve our "efficiency" in terms of the number of register operations, by relaxing the requirement that only even values can be "doubled". I've included that for fun here:
```
sub h{($i)=@_;return if(($i%=65536)==0);($i%2==0)?do{h($i/2);say"y+=y";}:do{h($i-1);say"y+=x";}}
```
Begin addendum:
Really liked this problem, and I've been fiddling with it off and on for the last couple weeks. Thought I would post my results.
Some numbers:
Using a BFS algorithm to find an optimal solution, in the first 2^16 numbers there are only 18 numbers that require 23 steps. They are: 58558, 59894, 60110, 61182, 61278, 62295, 62430, 62910, 63422, 63462, 63979, 64230, 64314, 4486, 64510, 64698, 64854, 65295.
Using the recursive algorithm described above, The "most difficult" number to reach is 65535, at 45 operations. ( 65534 takes 44, and there are 14 numbers that take 43 steps) 65535 is also the largest departure from optimal, 45 vs 22. The 23 step difference is 2n+1. (Only three numbers hit 2n: 65534, 32767, 32751.) Excepting the trivial (zero-step) cases, over the defined range, the recursive method averages approximately 1.4 times the optimal solution.
Bottom line: For the numbers 1-2^16, the recursive algorithm never crosses the defined threshold of 2n+2, so the answer is valid. I suspect that it would begin to depart too far from the optimal solution for larger registers/more bits, however.
The code I used to create the BFS was sloppy, memory intensive, not commented, and quite deliberately not included. So... you don't have to trust my results, but I'm pretty confident in them.
[Answer]
# Python 3, 202 bytes
```
def S(n):
q=[(1,0,"")];k=65536
while q:
x,y,z=q.pop(0)
if n in{x,y}:print(z);return
q+=[((x+y)%k,y,z+"x+=y\n"),(x,(x+y)%k,z+"y+=x\n")]+[(2*x%k,y,z+"x+=x\n")]*(~x&1)+[(x,2*y%k,z+"y+=y\n")]*(~y&1)
```
*(Thanks to @rationalis for a few bytes)*
Here's an extremely basic solution. I wish I could golf the last line better, but I'm currently out of ideas. Call with `S(25)`.
The program just does a simple BFS with no caching, so is very slow. Here is `S(97)`, for some sample output:
```
y+=x
x+=y
x+=x
x+=x
x+=x
x+=x
y+=x
y+=x
x+=y
```
[Answer]
# Dyalog APL, 49 chars / bytes\*
```
{0=N←⍵|⍨2*16:⍬⋄0=4|N:⎕←'y+=y'⊣∇N÷2⋄⎕←'y+=x'⊣∇N-1}
```
Algorithm shamelessly inspired by **@CChak**'s answer.
**Example:**
```
{0=N←⍵|⍨2*16:⍬⋄0=4|N:⎕←'y+=y'⊣∇N÷2⋄⎕←'y+=x'⊣∇N-1} 25
y+=x
y+=x
y+=y
y+=x
y+=x
y+=y
y+=y
y+=x
```
**Ungolfed:**
```
{
N←(2*16)|⍵ # assign the argument modulo 65536 to N
0=N: ⍬ # if N = 0, return an empty value (that's a Zilde, not a 0)
0=4|N: ⎕←'y+=y' ⊣ ∇N÷2 # if N mod 4 = 0, recurse with N÷2 and *then* print 'y+=y'
⎕←'y+=x' ⊣ ∇N-1 # otherwise, recurse with N-1 and *then* print 'y+=x'
}
```
\* Dyalog APL supports a legacy charset which has the APL symbols mapped to the upper 128 byte values. Therefore an APL program that only uses ASCII characters and APL symbols can be considered to be bytes == chars.
[Answer]
# Python, 183
```
def S(n):
b,c,e=16,'x+=x\n','x+=y\n';s=d='y+=x\n';a=i=0
if n<2:return
while~n&1:n>>=1;a+=1
while n:n>>=1;s+=[e,c][i]+d*(n&1);i=1;b-=1
while a:s+=[c,c*b+e*2][i];i=0;a-=1
print(s)
```
I can't guarantee this stays within 2x the optimal program for even numbers, but it is efficient. For all valid inputs `0 <= n < 65536`, it's essentially instantaneous, and generates a program of at most 33 instructions. For an arbitrary register size `n` (after fixing that constant), it would take `O(n)` time with at most `2n+1` instructions.
### Some Binary Logic
Any odd number `n` can be reached within 31 steps: do `y+=x`, getting `x,y = 1,1`, and then keep doubling `x` with `x+=x` (for the first doubling do `x+=y`, since `x` is odd to begin with). `x` will reach every power of 2 this way (it's just a left-shift), and so you can set any bit of `y` to be 1 by adding the corresponding power of 2. Since we're using 16-bit registers, and each bit except for the first takes one doubling to reach and one `y+=x` to set, we get a maximum of 31 ops.
Any even number `n` is just some power of 2, call it `a`, times an odd number, call it `m`; i.e. `n = 2^a * m`, or equivalently, `n = m << a`. Use the above process to get `m`, then reset `x` by left-shifting it until it's 0. Do a `x+=y` to set `x = m`, and then continue to double `x`, the first time using `x+=y` and subsequently using `x+=x`.
Whatever `a` is, it takes `16-a` shifts of `x` to get `y=m` and an additional `a` shifts to reset `x=0`. Another `a` shifts of `x` will occur after `x=m`. So a total of `16+a` shifts is used. There are up to `16-a` bits that need to be set to get `m`, and each of those will take one `y+=x`. Finally we need an extra step when `x=0` to set it to m, `x+=y`. So it takes at most 33 steps to get any even number.
You can, of course, generalize this to any size register, in which case it always takes at most `2n-1` and `2n+1` ops for odd and even `n`-bit integers, respectively.
### Optimality
This algorithm produces a program that is near-optimal (i.e. within `2n+2` if `n` is the minimum number of steps) for odd numbers. For a given odd number `n`, if the `m`th bit is the leading 1, then any program takes at least `m` steps to get to `x=n` or `y=n`, since the operation which increases the registers' values fastest is `x+=x` or `y+=y` (i.e. doublings) and it takes `m` doublings to get to the `m`th bit from 1. Since this algorithm takes at most `2m` steps (at most two per doubling, one for the shift and one `y+=x`), any odd number is represented near-optimally.
Even numbers are not quite so good, since it always uses 16 ops to reset `x` before anything else, and 8, for example, can be reached within 5 steps.
Interestingly, the above algorithm never uses `y+=y` at all, since `y` is always kept odd. In which case, it may actually find the shortest program for the restricted set of only 3 operations.
### Testing
```
# Do an exhaustive breadth-first search to find the shortest program for
# each valid input
def bfs():
d = {(0,1):0}
k = 0xFFFF
s = set(range(k+1))
current = [(0,1)]
nexts = []
def add(pt, dist, n):
if pt in d: return
d[pt] = dist
s.difference_update(pt)
n.append(pt)
i = 0
while len(s) > 0:
i += 1
for p in current:
x,y = p
add((x,x+y&k), i, nexts)
add((y,x+y&k), i, nexts)
if y%2 == 0: add(tuple(sorted((x,y+y&k))), i, nexts)
if x%2 == 0: add(tuple(sorted((x+x&k,y))), i, nexts)
current = nexts
nexts = []
print(len(d),len(s))
# Mine (@rationalis)
def S(n):
b,c,e=16,'x+=x\n','x+=y\n';s=d='y+=x\n';a=i=0
if n<2:return ''
while~n&1:n>>=1;a+=1
while n:n>>=1;s+=[e,c][i]+d*(n&1);i=1;b-=1
while a:s+=[c,c*b+e*2][i];i=0;a-=1
return s
# @CChak's approach
def U(i):
if i<1:return ''
return U(i//2)+'y+=y\n' if i%4==0 else U(i-1)+'y+=x\n'
# Use mine on odd numbers and @CChak's on even numbers
def V(i):
return S(i) if i % 2 == 1 else U(i)
# Simulate a program in the hypothetical machine language
def T(s):
x,y = 1,0
for l in s.split():
if l == 'x+=x':
if x % 2 == 1: return 1,0
x += x
elif l == 'y+=y':
if y % 2 == 1: return 1,0
y += y
elif l == 'x+=y': x += y
elif l == 'y+=x': y += x
x %= 1<<16
y %= 1<<16
return x,y
# Test a solution on all values 0 to 65535 inclusive
# Max op limit only for my own solution
def test(f):
max_ops = 33 if f==S else 1000
for i in range(1<<16):
s = f(i); t = T(s)
if i not in t or len(s)//5 > max_ops:
print(s,i,t)
break
# Compare two solutions
def test2(f,g):
lf = [len(f(i)) for i in range(2,1<<16)]
lg = [len(g(i)) for i in range(2,1<<16)]
l = [lf[i]/lg[i] for i in range(len(lf))]
print(sum(l)/len(l))
print(sum(lf)/sum(lg))
# Test by default if script is executed
def main():
test()
if __name__ == '__main__':
main()
```
I wrote a simple test to check that my solution indeed produces correct results, and never goes over 33 steps, for all valid inputs (`0 <= n < 65536`).
In addition, I attempted to do an empirical analysis to compare my solution's output against the optimal outputs -- however, it turns out that breadth-first search is too inefficient to obtain the minimum output length for every valid input `n`. For example, using BFS to find the output for `n = 65535` does not terminate in a reasonable amount of time. Nonetheless I've left in `bfs()` and am open to suggestions.
I did, however, test my own solution against @CChak's (implemented in Python here as `U`). I expected mine would do worse, since it is drastically inefficient for smaller even numbers, but averaged across the whole range in two ways, mine produced output of length on average 10.8% to 12.3% shorter. I thought maybe this was due to better efficiency from my own solution on odd numbers, so `V` uses mine on odd numbers and @CChak's on even numbers, but `V` is in between (about 10% shorter than `U`, 3% longer than `S`).
[Answer]
# CJam, 31
Like **@Tobia**'s answer, my algorithm is also shamelessly ~~stolen~~ inspired by **@CChak**'s answer. But, wielding the black magic that is CJam, I managed to make an even smaller implementation of the algorithm.
[Try it here.](http://cjam.aditsu.net/)
**Golfed:**
```
qi{_4%!:X)/X!-'xX+"
y+="@}h;]W%`
```
**Ungolfed:**
```
qi "Read input and convert to integer.";
{ "Do...";
_4%!:X "Assign (value mod 4 == 0) to X.";
)/X!- "If X, divide value by 2. If not X, decrement value.";
'xX+ "If X, put 'y' on the stack. If not X, put 'x' on the stack.";
"
y+=" "Put '\ny+=' on the stack.";
@ "Rotate top 3 elements of stack left so the value is on top.";
}h "... while value is not zero.";
; "Discard zero value on stack.";
]W% "Collect stack into array and reverse.";
```
Please correct me if I'm wrong, but I believed that the modulo 65536 operation used in answers with a similar algorithm is unnecessary. I interpreted the question such that we can assume that the input will be a valid unsigned 16-bit integer, and any intermediate values or results of this algorithm will be as well.
] |
[Question]
[
An *Almost Equilateral Heronian Triangle* is a triangle with integer lengths of the form `n-1`, `n`, and `n+1` and also has integer area. The first few are:
```
3, 4, 5 -> 6
13, 14, 15 -> 84
51, 52, 53 -> 1170
```
**Quest**: Generate the shortest program that outputs the `n`th such triple. (Hint: this is a known sequence).
Winner will be selected on May 2, 2014.
[Answer]
# Mathematica, ~~26, 22, 16~~ 18 chars
```
{0,1,2}+⌊(2+√3)^n⌋
```
[Answer]
### APL, 15 14 charaters
```
0 1 2+⌊⎕*⍨2+√3
```
Same approach as [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)'s solution but uses floor instead of the correction term.
Thank you to [algorithmshark](https://codegolf.stackexchange.com/users/5138/algorithmshark) for pointing out that the commute operator saves one char.
[Answer]
## GolfScript (24 21 chars)
```
2 4@~{.4*@-}*;.(\.)]p
```
Takes input on stdin, gives output to stdout in the form
```
[3 4 5]
```
[Online demo](http://golfscript.apphb.com/?c=OyczJwoKMiA0QH57LjQqQC19KjsuKFwuKV1wCg%3D%3D)
Note that I've assumed that the 0th element of the sequence is `[1 2 3]` (with area 0), which I think is consistent with [OEIS A003500](http://oeis.org/A003500).
With thanks to [Howard](https://codegolf.stackexchange.com/users/1490/howard) for a 3-char saving.
[Answer]
# [GNU dc](http://www.gnu.org/software/bc/manual/dc-1.05/), 30 19 bytes
```
9k3v2+?^0k1/p1+p1+p
```
This uses the same trick as [@Howard's APL answer](https://codegolf.stackexchange.com/a/26118/11259) so only one term has to be calculated. Takes input for n from stdin.
Output:
```
$ dc -e '9k3v2+?^0k1/p1+p1+p' <<< 1
3
4
5
$ dc -e '9k3v2+?^0k1/p1+p1+p' <<< 2
13
14
15
$ dc -e '9k3v2+?^0k1/p1+p1+p' <<< 3
51
52
53
$
```
[Answer]
## Python 77
Quite a verbose implementation in Python
```
[(a-1,a,a+1)for a in(int((2+3**.5)**t+(2-3**.5)**t+.1)for t in range(N))][-1]
```
[Answer]
# Python 3, 83 characters
```
f=lambda t:4*f(t-1)-f(t-2)if t>2 else(4,14)[t-1];n=f(int(input()));print(n-1,n,n+1)
```
This uses a recursive solution, taking advantage of the fact that (quote from [Wikipedia](http://en.wikipedia.org/wiki/Heronian_triangle#Almost-equilateral_Heronian_triangles)):
>
> Subsequent values of n can be found by multiplying the previous value by 4, then subtracting the value prior to that one (52 = 4 × 14 − 4, 194 = 4 × 52 − 14, etc.)
>
>
>
[Answer]
# JavaScript (ECMAScript 6) - 52 Characters
```
f=x=>x?--x?4*f(x)-f(x-1):4:2
g=x=>[a=f(x)-1,a+1,a+2]
```
Defines a recursive function `f` which returns the nth term and a function `g` which returns an array containing the corresponding triple.
# JavaScript - 41 Characters
```
for(a=2,b=4;--x;)b=-a+4*(a=b);[a-1,a,a+1]
```
Expects the term to be calculated to be stored in the global variable `x` and outputs the triple to the console.
[Answer]
# CJam, 13 bytes
```
3,3mq))ri#if+p
```
The first version of CJam is 10 days older than this challenge, but I don't know if all of the features I'm using have been present back then. The challenge is officially closed anyway though, so...
[Test it here.](http://cjam.aditsu.net/#code=3%2C3mq))ri%23if%2Bp&input=3)
## Explanation
```
3mq e# Push √3.
)) e# Increment twice.
ri e# Read input and convert to integer.
# e# Raise 2+√3 to that power.
i e# Convert to integer, truncating the result.
3, e# Push [0 1 2]
f+ e# Add the previous number to each of these.
p e# Pretty-print the result.
```
] |
[Question]
[
[Part I](https://codegolf.stackexchange.com/questions/259960/g%C3%B6del-encoding-part-i)
Previous part was considered encoding of non-empty nested lists with a positive integer.
Reminding the coding procedure \$G(x)\$:
1. If \$x\$ is a number, \$G(x) = 2^x\$
2. If \$x\$ is a list \$[n\_0, n\_1, n\_2, n\_3, …]\$, \$G(x) = 3^{G(n\_0)} \cdot 5^{G(n\_1)} \cdot 7^{G(n\_2)} \cdot 11^{G(n\_3)} \cdot...\$
Bases are *consecutive primes*.
The number *will be unique* (it can be proved, but you don’t have to do it).
So always there is *valid reverse procedure*:
determine an array-structure from a given number,
or verify that no structure exists for that number.
This is the task of this challenge.
### Input
Positive integer (possibly very large)
**UPD**
I know that in CG does not approve strict validation of input.
But here *invalid in general* number means: negative, float, with typo etc.
You don’t have to check it out!
But figuring out if a number is *valid encoding* or not is part of the challenge.
### Output **UPD**
*Very sorry I missed the important thing ((*
Single number (if it is suitable for the first part of the procedure, see test cases)
or
non-empty list of non-negative integers (possibly nested, without empty sub-lists) that is encoded with given number;
printed in any appropriate form: as pure array, string, json etc.
*OR*
any appropriate message (`[ ], None, -1` etc), if there is no decoding for this number.
### Test cases
```
1 → 0
2 → 1
3 → [0]
4 → 2
5 → None
6 → None
7 → None
8 → 3
9 → [1]
10 → None
666 → None
729 → None
1024 → 10
1215 → None
3375 → [[0], [0]]
77777 → None
5859375 → [0, [1]]
666777666 → None
2210236875 → [3, 2, 1, 0]
7625597484987 → [[[0]]]
1111111111111111111111111111 → None
```
[Answer]
# JavaScript (ES6), 167 bytes
Expects a Bigint. Returns `-1` if the encoding is invalid.
This is probably longer than it should, but validating the encoding is costly (see below).
```
n=>(e=h=(n,F=n>1&&n%2n?(n,k=3n,i=0n)=>n%k?i?[h(i),...k>n?[]:F(n,-~k)]:(g=d=>k%--d?g(d):e|=d<2)(k)?[]:F(n,-~k):F(n/k,k,-~i):n=>n%2n?e|=n>1:-~F(n/2n))=>o=F(n))(n)&&-e||o
```
[Try it online!](https://tio.run/##fZDNboMwEITvfQouQbZkCLb5Vw23HPsCiEMUSEIdraum6gnl1elagjZ1Sywh2fMtM2O/7j/318P78PYRgOn66agmUBXp1VkRYDsFFfd92Aio8aiVBDaoCKiqYKProW7OZKAsDENdQd205Q6ngpumbUlOqlOV3gRBV59IR8t@VN2zoETT@0G72Wqm8TDQEqwvZuEsBpfBzVIBFPOMwj2l@Pl@0I@jmQ4GrubShxdzIkfCEXrbrRc9/dbFrHNHj2ddOHo@69LReSSWX7ibIWfQRK1DioVwl6RpOrMXA70DM1GsQy54sk6lzBbaYB9mS7nZmV3rFkmeFHcuEbP1/@mPJg9vIQQ@mkzzHyvJPME8zrw/D5WlIkmKLM7jIs@@@9vu7fQF "JavaScript (Node.js) – Try It Online")
### 111 bytes (for information only)
A large part of the code is dedicated to Gödel encoding validation. If we assume that the input is a valid encoding, then several sanity checks can be removed and we don't even have to include a primality test:
```
f=(n,F=n>1&&n%2n?(n,k=3n,i=0n)=>n%k?[...i?[f(i)]:[],...k>n?[]:F(n,-~k)]:F(n/k,k,-~i):n=>n%2n?0:-~F(n/2n))=>F(n)
```
[Try it online!](https://tio.run/##ZY7NboMwEITvfQpfEmHJgH9wMEiGW17C8iFKQ@Q6Wqqm6jGvTtcV9Me97c43s7Mvp4/T/fwWXt9LmJ8vyzLZAtjRwiD2e9hJGHGNVgELlgO1A@zi6KqqCqObikB97zzDNQ4wOt8f0V0@Iv2a6sgiboH2kHJ4i/flIwEJFE/hRJfzDPf5dqlu87WYCoGA1DXhT391ueoi05tVl5luVl1luuByi4i8Q63AcZ@RbiMiJ0q1eoOYYymce7TR3S8bZ@lObpISX1MH8@NTjEhGBCP/3mkPUuuubUzTmfa7PTX75RM "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org), ~~168~~ ~~149~~ ~~132~~ ~~117~~ 116 bytes
*Edits: -9 and -1 bytes thanks to pajonk (re-defining `if` as `[`, now no longer needed, and then function as ``~``), -7 bytes by switching to `\` instead of `function`, and -35 more bytes by re-arranging.*
```
`~`=\(x,p=2,y=0)`if`(!x%%p,`~`(x/p,p,y+1),`if`(p==2&x<2,y,c(if(sum(!p%%1:p)<3&p>2|y)list(~y[!y|p>2]),if(x>1)x~p+1)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVNLTsMwEF2w4xRuUSqPGETsND9Ud0PXXCBUCooSEQlSy3WkRKqy5ABs2QQkDgVLToJDdm2EUnUWtuyZN_Oen_z2rtqPlfgsdXYVfOm4icU9rVAKjrWwIc6zmE4qy5JoUrS6liixvmSAfxkpBJ9VC1OLCc0zui2f6URaFruRsHBmcsl3NTzlW02bOprUO3OxBjSF1ZJB1UjTCKCf_X12rlV9-6CTR7rViq5oCICpUhslsrJIdL4paApS5YWm02JTpFMAckF-Xl5JxNb7YM_zRsPvzGkf7_Px44fwjuO74_lH9hqJWQ5kMM7GtxnU0cVJHdzADY8SY2NnyJAjhsqpvnDObO54wTGEHCQcCUNiH5DyPe66oT8P5mEw_pmizrABs_6J40T3X6Jt-_0X)
Outputs the number or list whose Gödel encoding is the input. Errors if no such number/list exists.
**Ungolfed code:**
```
D=function(x,p=2,y=0){
if(!x%%p)D(x/p,p,y+1) else
if(p==2&x<2)y else
c(if(is_prime(p)&p>2|y)list(D(y*(!y|p>2))),if(x>1)D(x,p+1))
}
is_prime=function(x)sum(!x%%1:x)<3
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes
```
λ1>[∆Ǐḣvx₌∨∧ßu›:A∧]‹
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+UCIsIiIsIs67MT5b4oiGx4/huKN2eOKCjOKIqOKIp8OfdeKAujpB4oinXeKAuSIsIiIsIjkgPT4gWzFdXG42NjYgPT4gLTFcbjcyOSA9PiAtMVxuMzM3NSA9PiBbWzBdLCBbMF1dXG4xMjE1ID0+IC0xXG43Nzc3NyA9PiAtMVxuNTg1OTM3NSA9PiBbMCwgWzFdXVxuNjY2Nzc3NjY2ID0+IC0xXG4yMjEwMjM2ODc1ID0+IFszLCAyLCAxLCAwXVxuNzYyNTU5NzQ4NDk4NyA9PiBbW1swXV1dXG4xMTExMTExMTExMTExMTExMTExMTExMTExMTExID0+IC0xIl0=)
Returns `-1` for invalid inputs. Times out on the last test case.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 101 bytes
```
n->iferr(g(n),e,x)
g(n)=if(n==2^q=logint(n,2),q,primes(1+#t=factor(n)~)[^1]-t[1,],0/0,apply(g,t[2,]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fY5BTsMwEEX3nGJUNraYiHhSO87CvUiUIgvFkaXiuq4rwYYrcAA2kRDiTNwGJ-2av5n5M0_z5_Mn2uSfpjh_OTDfl-wq_TuGaufdmBKbWOA44iu_WzrjHQvG0P5kDsfJh8wCEscTxuRfxjMTD_fZOPucj6nQ77zfi6HKvcAB68cabYyHNzZh7gkHzm9hH9exhWoH5U45amGzmA04ZjlH6DsEpRRC07QSoV2EILXsVl9WZbACRKKmRukVUyRl1271ttMFF_-owFQyBAk53N6a52v9Aw)
Returns `x` for invalid inputs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ȯ6ÆEs߀Ḣ?ḢḊ?0
ÇŒṘ
```
A full-program that accepts a positive integer and either:
* prints the decoded value and exits with a code of `0`; or
* prints nothing to STDOUT and exits with a code of `1` (printing a traceback to STDERR).
**[Try it online!](https://tio.run/##y0rNyan8///EerPDba7Fh@c/alrzcMcieyB@uKPL3oDrcPvRSQ93zvj//7@5mZGpqaW5iYWJpYU5AA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##HU@7qsJAFOz3K4Ygei2EZJN9Iept/BJdMRJ2wSSFr8ZCwdLqdoK1YKt1EPyN@CO5ux44cGbOzMCs83nTFDovfrrYED2ZW/QMgtYvBkMEZKGzbAVdGnTed14dxnl1@exv9eM6cls/TqOQVMfXuX7@deBMdNgOsd3iGxQYi9xmZZFag5ktzTQgOzKzS6RIDSJQJJCIQpoghgLnHIIqxLFgiGjEIPyASaY85f4OehWlzhRz6UjBKWNKJDJRUvQxtfBt0Er9bXTT/AM "Zsh – Try It Online") (in Zsh to catch the exit code).
### How?
```
ȯ6ÆEs߀Ḣ?ḢḊ?0 - Helper Link: positive integer, N
ȯ6 - logical OR with 6 (when N=0 use 6 - this is so that recursive calls
handle zeros in the ÆE result in a way that will
produce the error we want)
ÆE - prime factorisation list (e.g. 56=2*2*2*7 -> [3,0,0,1])
? - if...
Ḋ - ...condition: dequeue (i.e. is of length 2 or more)
? - ...then: if...
Ḣ - ...condition: remove and yield the head (exponent of 2)
s 0 - ...then (i.e. non-zero): split into chunks of length zero
(this will error out)
€ - ...else: for each (of the rest of the exponents):
ß - call this Link with that number
Ḣ - ...else: head (i.e. yield the power of two that N is)
ÇŒṘ - Main Link: positive integer, N
Ç - call the helper Link, above
ŒṘ - print a Python representation of the result
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 100 bytes
```
⊞υ⟦X³N⟧Fυ«≔⊟ιθ¿﹪貫≔²η≔⟦⟧ζW⊖θ¿﹪θη«≦⊕η¿⬤…²η﹪ηλ⊞ζ⁰»«⊞ζ⊕⊟ζ≧÷ηθ»Fζ¿∧κ¬&⊖κκ⊞ι⊖L↨겫≔⟦κ⟧κ⊞ικ⊞υκ»»⊟ι»⭆¹⊟§υ⁰
```
[Try it online!](https://tio.run/##VZFNj4IwEIbP@CvmOE26iavZ7METxouJGuIejQdWKm2orUKrGzb@dnYo4GoCIfP1zPsOB5mWB5vqpkl8JdFz2CX2Jkqcclias3cbf/qmkLE9m42OtgT0DH5HUVxVKjeY2DMqxuFC1UgdAdc289rihcOEhcahc8JBtk1DvNtzqEPiJpUWgAtxKMVJGCcyvNDsK032tGidnnvC0jwGBnaQEGuN29TkotvJoadIDpoRJjitOYzDyB2ErkTHHipP5OCwprHZy/KtyqUjBW6hrioTtKe/QXSnN9yp7izEJsOCw8Y6nCt3U5VoM89mC5JYsIcyxeG5uhImdxLnaSVazoT1Wv5VDwct9i1n9jCiXkM/hKSQnjCflMq4/idS7T7qEl@OPjmZxXcObTV2S5OJn5Yxbvc3zXT6@dG8XfUf "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⟦X³N⟧
```
The main loop only works on lists of odd numbers, so fake it out by starting with a list of `3ⁿ`.
```
Fυ«
```
Loop over the input and any sublists that may be generated while processing it.
```
≔⊟ιθ
```
Get the value to turn into a list.
```
¿﹪貫
```
If it's odd, then:
```
≔²η≔⟦⟧ζ
```
Start finding prime factor multiplicities.
```
W⊖θ
```
Repeat until the all the factors have been found.
```
¿﹪θη«
```
If the current prime is not a factor, then:
```
≦⊕η
```
Try the next integer.
```
¿⬤…²η﹪ηλ
```
If this is a prime, then...
```
⊞ζ⁰
```
... start counting its multiplicity.
```
»«
```
Otherwise:
```
⊞ζ⊕⊟ζ
```
Increment the multiplicity.
```
≧÷ηθ
```
Divide the value by the prime.
```
»Fζ
```
Loop over the multiplicities.
```
¿∧κ¬&⊖κκ
```
If this is a power of `2`, then...
```
⊞ι⊖L↨겫
```
... push its logarithm to the list, otherwise:
```
≔⟦κ⟧κ⊞ικ⊞υκ
```
... push the wrapped value to both the list and also the list of sublists to be processed.
```
»»⊟ι
```
Otherwise, crash the program, because the input is invalid.
```
»⭆¹⊟§υ⁰
```
Output the final value.
Since the above program has to find the logarithm to base `3` of `3ⁿ` the slow way, here's a slightly less slow 112 byte version which special-cases inputs of powers of `2` to avoid this:
```
Nθ¿&θ⊖θ«⊞υ⟦θ⟧Fυ«≔⊟ιθ¿﹪貫≔²η≔⟦⟧ζW⊖θ¿﹪θη«≦⊕η¿⬤…²η﹪ηλ⊞ζ⁰»«⊞ζ⊕⊟ζ≧÷ηθ»Fζ¿∧κ¬&⊖κκ⊞ι⊖L↨겫≔⟦κ⟧κ⊞ικ⊞υκ»»⊟ι»⭆¹§υ⁰»I⊖L↨θ²
```
[Try it online!](https://tio.run/##dZFNa8IwGMfP8VM8xwQycA7ZRk91XoQp4o7iobOxCY2pbRIdHX72LumbVdihKc/bL///kz2Pin0WyapaqJM1K3v8ZgXOSTASB8AzYS5Cs1DFOKcwZ/uCHZkyzIWEEPgdobXVHFsK23znZtAhKwDbuoJCrUWi8Do7YUEoeCZCnrrMYiszT5w0kL53QoHXbV1iu6NQNpkLF5IBfhAB90DeAdEyOrWMheonenytI5QSbyKVsOZeCi2HU5DeXu2tpDBuZq7ApGYtvqsN4LXT0g0G9wI2IuHGqTBzcRYxc1d1y0BXf9Q7KxsnftMphVVmhrsfek6dzpT08sT9s3wylRiOZ5FmnjMhnZyB9G616c6Tgpsd8RDbPvY6/VdT1oVQpn1WX3aFJvVl3C9xvvEzhdAsVMx@PGTs266jwfBHpA3@T3fe6iZBVU3fpu8vr9Pq6Sz/AA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 32 bytes
```
L?sIlbslbCWneJCr8Pb.fP_ZleJ3yMhJ
```
[Try it online!](https://tio.run/##BcG5CgIxFAXQP5K85b6lspjKoDCdYCMERqYIIo5Nvj6e8xm/fc7r@bj0dvS23N9bXb6xttNrfT76VmXc9jrHJI5kmIXA4aTFMgqiuKpLQhFJVpKSWMWNICbMYE8HW0DwBw "Pyth – Try It Online")
Defines a decoding function `y(b)` which returns the decoded list or throws a TypeError if the input is invalid.
### Explanation
```
L # define y(b)
? # if
lb # log base 2 of b
sI # is an integer:
slb # return int(log(b))
# otherwise
J # assign J to
Pb # the list of prime factors of b
r8 # length encoded
C # and transposed
W # if
eJ # the last element of J
n # is not equal to
.fP_ZleJ3 # the first length(eJ) primes (starting at 3):
C # apply transposition (this will result in a TypeError)
# otherwise
yM # apply y to every element of
hJ # the first element of J
```
] |
[Question]
[
*Inspired by [Is this Flow Free puzzle trivial?](https://codegolf.stackexchange.com/questions/235848/is-this-flow-free-puzzle-trivial) by [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler). Lengthy chunks of this challenge are borrowed from there. This may be one step of a solution for the linked challenge, depending on chosen strategy.*
## Background
*Flow Free* is a series of puzzle games whose objective is to connect all the same-colored pairs of dots on the grid. In this challenge, we consider the original game on a rectangular grid (no variations like bridges, warps, or hexagonal grids).
A puzzle in *Flow Free* might look like this:
```
Puzzle Solution
....1 11111
..... 13333
..24. 13243
1.... 13243
23... 23243
...43 22243
```
## Challenge
Given a solved Flow Free puzzle, output the unsolved puzzle.
The input can be taken as a single string/array or a list of lines. You may also take the dimensions of the array as input.
You may assume only the digits 1-9 are used and the numbers used in the solved puzzle will be a strict prefix of these (i.e. no need to handle there being `2`s but no `1`s in the input). Also, each line represented by each digit is a valid [polystrip](https://codegolf.stackexchange.com/q/155983/78410) of length 3 or higher.
Unsolving means identifying the ends of the polystrips and keeping them in place, while replacing other cells with a `0` or any consistent non-digit character.
Output the string/array in any convenient manner.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code per language wins!
## Test cases
| Inputs | Outputs |
| --- | --- |
|
```
11111122211111333333322221111113333132431324323243222431112113121131211311111122131211312133111133331344313343112432124322244111677712266661125555555534488883349998444
```
|
```
.....12.211..13.....32..2....1.......24.1....23......43...21.3......2.13.......2.3..11..2.3....1......4....3....2..21..3....4..167.7.2....6.12...55...34.8....3.9.984..
```
|
[Answer]
# JavaScript (ES6), ~~87 84 83~~ 82 bytes
*Saved 1 byte thanks to @tsh*
Expects a matrix of integers. Returns another matrix where empty cells are set to `0`.
```
m=>m.map((r,y)=>r.map((v,x)=>v*-(g=d=>d+2?((m[y+d--%2]||0)[x+d%2]==v)+g(d):d)(2)))
```
[Try it online!](https://tio.run/##VU7JTsMwEL37K6xIKB7SuI0TuoAcTnDk0mPbQ4idkCobThq1onx7sZ1WwDs8zcxbNPtkSLpUFW3v142Ql4xfKh5XtEpaQtTkBDxW4zJMjnoZ7n2Sc8Fj4bFnQqrNyRO@f8d25/MMNkdP6JHzAbycCHgUQBgAXJT8PBRKEjfrXKBKJuK1KOX6VKdkBrRv1r0q6pwA7dqy6Imzrbe1AzRr1EuSfpAO8xh/IYwrzHH3a9IW85qVN5TSbmf3t0P1LhXAk06kTd01paRlk5OMVGNAmYCi@6aoieMAXCdbqGRbJqkk09k0n2CXuoA9bCX0DZfAAAWMsQAhM4coNEChPrHxpHV7CkIW3ZiNzAwbEzOmfxyMhbrkrxBehWthZAtDw4EtDG61kU3PF4uF@W6uYSwPGsiQTqKlhs6i1Wq1jKLoBw "JavaScript (Node.js) – Try It Online")
Or **79 bytes** with optional chaining:
```
m=>m.map((r,y)=>r.map((v,x)=>v*-(g=d=>d+2?(m[y+d--%2]?.[x+d%2]==v)+g(d):d)(2)))
```
(not supported by TIO)
### Commented
```
m => // m[] = input matrix
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each value v at position x in r[]:
v * -( // set v to 0 if the result of g() is 0
// or leave it unchanged if it's -1
g = // g is a recursive function taking
d => // a direction d in [-1, 0, 1, 2]
d + 2 ? // if d is not equal to -2:
( // we test whether the adjacent cell
( // at (x', y') with:
m[y + d-- % 2] // y' = y + (d % 2)
|| 0 //
) //
[x + d % 2] // x' = x + ((d - 1) % 2)
== v // is equal to v
) // and increment the result if it is
+ g(d) // recursive call
: // else:
d // stop the recursion and subtract 2
)(2) // initial call to g with d = 2
) // end of inner map()
) // end of outer map()
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 106 bytes
```
ArrayFilter[Count[Extract[#,{{1,2},{2,1},{2,3},{3,2}}],#[[2,2]]]/.{1->#[[2,2]],_->0}&,#,{1,1},Padding->0]&
```
[Try it online!](https://tio.run/##RY9Na8MwDIb/iws5Kcss77iFjrLeBoXs5pjhNe5qSJ3garBh8tszucmYDnrR41cfvlg6u4slf7Tz6Wl@jtH@7H1PLurd8BVIv3xTtEfSG0hJAk6QEOQtK86KyWRgozUCGmOquyTL@q@E97K@nwrgXpmbDrbrfPhkaIo5CZmjDRIRpYBbqdqgcrAwxZVm00Klwod/wVWQRUxV9WpHvTvbfK@L121Dkbc1Y@/z@aINwhRmcR34Jf9tHCItNn3asufNfvSOt@6967vGjTyLhngVZS2EeazXGfMv "Wolfram Language (Mathematica) – Try It Online")
```
ArrayFilter[ -apply to each 3x3 block, padded with 0s
Count[ -count the
Extract[#, -occurrences at
{{1,2},{2,1},{2,3},{3,2}} -positions up, down, left, right
],
#[[2,2]] -of the center element
]
/.{1->#[[2,2]],_->0}&, -replace with center element if count is 1, otherwise 0
#,{1,1},Padding->0]&
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 51 bytes
```
WS⊞υιυUMυ⪪ι¹FLυ«J⁰ιFL§υι«F⊖№KVKK§≔§υικ.→»»J⁰¦⁰Eυ⪫ιω
```
[Try it online!](https://tio.run/##VU9BboMwEDzjV1g52ZIbxUBDaE5ReknUVKipekewAStgI7CTSlXeTtdCbdo9WN6dnZmdos77wuTNOF5r1QBlO905e7S90hXjnGZuqJkTVPE1yXBomcPfIe@2pm1zXXrs2DXKMiWo5IidTE/ZC@jKIhEVvkiwd233bthikgn@bmzsTpfwOVlM2xP@DEUPLWgLJdsah8YZwPnD6FdwaKwZF9RP8EikbYZBVfpH7J@ooGdBZ/OZdw4O5gLs6U1VtfX9jdzI/bjFb0bM58l7o7TPdUWL9ThKKZdJkhAZhkssImX4iEX8E8UxWWFFUUzSNF3F2I8Pl@Yb "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of strings of digits. Explanation:
```
WS⊞υιυ
```
Input the strings and print them to the canvas.
```
UMυ⪪ι¹
```
Split the strings into character lists so that they can be replaced.
```
FLυ«
```
Loop over each of the lists.
```
J⁰ι
```
Jump to the start of its line.
```
FL§υι«
```
Loop over the cells of the list.
```
F⊖№KVKK§≔§υικ.
```
Count the number of times the cell appears in its Von Neumann neighbourhood. If it's more than once then replace the state with a `.`.
```
→
```
Move to the next cell.
```
»»J⁰¦⁰Eυ⪫ιω
```
Overwrite the canvas with the new states.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 125 bytes
```
(.)(?<=(\1).)?(?=(?<2>\1))?(?<=(?<!.)(?(3)$)(?<-3>.)*(?<2>\1).*¶(.)*.)?(?=(?<=(.)*.).*¶(?<-4>.)*(?(4)$)(?<2>\1))?(?<-2>){2}
.
```
[Try it online!](https://tio.run/##VU45DsIwEOz3F0gg2VFiaQ9ySDkeQUsBBQUNBaJDfCsPyMfCrp1wTDHe2Z0Z@X55XG/neRohh8Mpz2Hn9Jld8G5oO3dEH/zghk4V9apMtKY25nDst2YsuA8@Wz0hm0YtyD7JLqm4V7Mks5MU/vYW1PsnvSDM/hR/pDSNyzSjAZCIEMBmBjYA64rSSu9xhUyyMiUmYzORmf4YU6GW/B54OSyFEgvZGGMhrrUS02VVVfa7UmGWvQKMNAm1QrPQNE0tIm8 "Retina 0.8.2 – Try It Online") Link includes test suite that splits on double-spaced tests and double-spaces the results. Explanation:
```
(.)
```
Match a character...
```
(?<=(\1).)?
```
... that might be preceded by a copy of that character, ...
```
(?=(?<2>\1))?
```
... that might be followed by a copy of that character, reusing capture group 2 for the count of copies, ...
```
(?<=(?<!.)(?(3)$)(?<-3>.)*(?<2>\1).*¶(.)*.)?
```
... that might be below a copy of that character, using a .NET balancing group to ensure both characters are in the same column, ...
```
(?=(?<=(.)*.).*¶(?<-4>.)*(?(4)$)(?<2>\1))?
```
... or that might be above a copy of that character, ...
```
(?<-2>){2}
```
... where two copies exist.
```
.
```
Replace it with a dot.
[Answer]
# [R](https://www.r-project.org/), 112 bytes
```
function(m)m*(apply(which(m|1,T),1,function(j)sum(m[t((j+rbind(o<-c(1:-1,0),rev(o)))%%(dim(m)+1))]==m[t(j)]))<2)
```
[Try it online!](https://tio.run/##dY/LDoIwEEX3/Q@SGR0SW3zH/gU740JAY4mlpoJI4r9ji2A0xpzNSWdub2vbqria8@2QyfZYFWmpTAEa9Qj2l8u5gfqk0hPoB6cYidN7JcdrpUFvS4B8bBNVZGA2YQp8HXKaINnDDQwiBgFkyi3imCPupPSJHHeIG4GtlnpfWnUHlyPPnBYdjJNwzHuYnwma9bBBIpo62JJeRN0BW5Fn2c2m6OJJY00tY2TDV91zGPsp97imqKdT4e74VvGp4qX/Ston "R – Try It Online")
```
unsolved=function(m) # get unsolved puzzle for matrix m:
m* # m multiplied by...
(apply(which(m|1,T),1,function(j) # function applied to all coordinates of m:
sum(m[ # sum of elements of m...
t((j # at each coordinate...
+rbind(o<-c(1:-1,0),rev(o))) # plus (1,0),(0,-1),(-1,0) & (0,1)...
%%(dim(m)+1)) # modulo dimensions of m +1...
# (prevents offset coordinates becoming too big)
]==m[t(j)])) # that are equal to the value at this coordinate
<2) # is less than 2
# (so, is equal to 1, since there are no 'lonely'
# digits without any equal neighbours as each line
# is guaranteed to be length 3 or longer)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒĠạⱮ§ỊSʋÐṀ⁸$€ẎŒṬ¬a
```
A monadic Link that accepts a list of list of positive integers and yields a list of lists of non-negative integers (`0` representing the unclued cells).
**[Try it online!](https://tio.run/##y0rNyan8///opCMLHu5a@GjjukPLH@7uCj7VfXjCw51Njxp3qDxqWvNwV9/RSQ93rtE@tCbx////0dGGOgoQZKajYA5BsToKIGEjMDKDI6gwRMYUjkDCpkgCxjoKJkAEErbQUYAjY4gMSNhSRwGCLCBKQcKxAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opCMLHu5a@GjjukPLH@7uCj7VfXjCw51Njxp3qDxqWvNwV9/RSQ93rtE@tCbx/9HJD3cuftS479A2INz6cPeWMKAKIDrcnv@oYa5epGYWVPL/f3V19RguQxDgMjQyMjLkAnOMuYxBgMsYKGTEBZMHCxkaG5nASCMIaQQiQYqMQIpQSEOIgUBDkCWMoRJQA03ABhqDSEOwgYYwY03Aus3Mzc1BrjMDApASUyDgAhFAnVwWQADUy2VpaWlhYmIC9A8A "Jelly – Try It Online").
### How?
```
ŒĠạⱮ§ỊSʋÐṀ⁸$€ẎŒṬ¬a - Link: list of lists, A
ŒĠ - group multi-dimensional indices by their values
€ - for each group (a list of coordinates, G, where one of the values are):
$ - last two links as a monad, f(G):
⁸ - using G as the right argument...
ÐṀ - filter G keeping those [a,b] which are maximal under:
ʋ - last four links as a dyad, f([a,b], G)
Ɱ - map across G with:
ạ - absolute difference (vectorises)
§ - sums (-> Manhatten distances)
Ị - insignificant? (0 or 1?)
S - sum
Ẏ - tighten to a list of coordinates (of the blanks in the puzzle)
ŒṬ - multi-dimensional untruth
¬ - logical NOT (vectorises)
a - logical AND with A (vectorises)
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 41 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
4⊸⊑⊸(⊣×1=·+´1‿3‿5‿7⊏=)∘⥊⎉2 3‿3↕⊢↑˝·≍⟜¬2+≢
```
[Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgNOKKuOKKkeKKuCjiiqPDlzE9wrcrwrQx4oC/M+KAvzXigL834oqPPSniiJjipYrijokyIDPigL8z4oaV4oqi4oaRy53Ct+KJjeKfnMKsMiviiaIKCuKAolNob3cgdGVzdGNhc2VzIOKGkCDin6gKICA+4p+oMeKAvzHigL8x4oC/MeKAvzEsCiAgICAx4oC/MuKAvzLigL8y4oC/MeKfqSwKICA+4p+oMeKAvzHigL8x4oC/MeKAvzMsCiAgICAz4oC/M+KAvzPigL8z4oC/MywKICAgIDPigL8y4oC/MuKAvzLigL8y4p+pLAogID7in6gx4oC/MeKAvzHigL8x4oC/MSwKICAgIDHigL8z4oC/M+KAvzPigL8zLAogICAgMeKAvzPigL8y4oC/NOKAvzMsCiAgICAx4oC/M+KAvzLigL804oC/MywKICAgIDLigL8z4oC/MuKAvzTigL8zLAogICAgMuKAvzLigL8y4oC/NOKAvzPin6ksCiAgPuKfqDHigL8x4oC/MeKAvzLigL8xLAogICAgMeKAvzPigL8x4oC/MuKAvzEsCiAgICAx4oC/M+KAvzHigL8y4oC/MSwKICAgIDHigL8z4oC/MeKAvzHigL8x4p+pLAogID7in6gx4oC/MeKAvzHigL8y4oC/MiwKICAgIDHigL8z4oC/MeKAvzLigL8xLAogICAgMeKAvzPigL8x4oC/MuKAvzEsCiAgICAz4oC/M+KAvzHigL8x4oC/MeKfqSwKICA+4p+oMeKAvzPigL8z4oC/M+KAvzMsCiAgICAx4oC/M+KAvzTigL804oC/MywKICAgIDHigL8z4oC/M+KAvzTigL8zLAogICAgMeKAvzHigL8y4oC/NOKAvzMsCiAgICAy4oC/MeKAvzLigL804oC/MywKICAgIDLigL8y4oC/MuKAvzTigL804p+pLAogID7in6gx4oC/MeKAvzHigL824oC/N+KAvzfigL83LAogICAgMeKAvzLigL8y4oC/NuKAvzbigL824oC/NiwKICAgIDHigL8x4oC/MuKAvzXigL814oC/NeKAvzUsCiAgICA14oC/NeKAvzXigL814oC/M+KAvzTigL80LAogICAgOOKAvzjigL844oC/OOKAvzPigL8z4oC/NCwKICAgIDnigL854oC/OeKAvzjigL804oC/NOKAvzTin6kK4p+pCgpGwqh0ZXN0Y2FzZXM=)
It is a tacit function which takes input as an integer array and returns an integer array. The function can be split into three parts:
Pad the input with 0s on all sides.
```
⊢↑˝·≍⟜¬2+≢ #
2+≢ # Add 2 to each dimension of the shape
⊢↑˝·≍⟜¬ # and use that to over-take from the input in each direction
```
Make a rank 4 array of the 3 by 3 windows.
```
3‿3↕
```
Replace each window with it's center element if it is an endpoint, otherwise replace with 0.
```
4⊸⊑⊸(⊣×1=·+´1‿3‿5‿7⊏=)∘⥊⎉2 #
⎉2 # On the rank 2 subarrays:
∘⥊ # flatten
4⊸⊑ # get the center element,
⊸( ) # and pass as the left argument into the train:
= # compare equality of flattened window with center
1‿3‿5‿7⊏ # pick out only the Manhattan neighbors
·+´ # sum the true values
1= # test if equals 1,
⊣× # and multiply bool result by the center element
```
[Answer]
# [Python 3](https://docs.python.org/3/), 111 bytes
```
lambda k:[c*(sum('0'<c==(k+" "*d)[n+q]for d in(1,k.find('\n')+1)for q in(d,-d))<2)or'.'for n,c in enumerate(k)]
```
[Try it online!](https://tio.run/##VU/LcoIwFN3nKzJukoh1mgRFrXRnt/0A6wIhjCkYMOK0fj29N2htzwwH5rzm0l67Q@N0X6YffZ0d90VGq9U2H/Pz5cjZM1vnacqraERH40JsXXTalY2nBbWOy0k1La0rOPtwTERSoHNCp5g8FUKslWg8mzKU3SQHgxp3ORqfdYZXYtdb19KUMka@DrY2VK4IpZ2/4ovS2joDLmQuHRdBsuWgvkJnCFH0aZQGPcI7gmzqs7kHWm9dxxmbfjZwWcmhIIR4edRThiXznZu2o5v3t433jR/ae2@yqpcIIpVSkhD81kQjiAZJDRL4QZJaxXdWAytkDCkM/WM5DMLIX0PfjNtgHAY1sgyD8j4bh/Y8SRK8bg7AyAxAkKBJFgDokuVyuYhDQenfB9s4hL9DSALS7MEgJzAOHD@Y/AA "Python 3 – Try It Online")
Returns a list of characters.
-1 byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
Thanks to [PertinentDetail](https://codegolf.stackexchange.com/users/103228/pertinentdetail) for fixing a bug for only +3 bytes
[Answer]
# [Ruby](https://www.ruby-lang.org/), 170 bytes
```
->m{(0...R=m.size).map{|y|(0...C=m[0].size).map{|x|[[y-1,x],[y,x-1],[y+1,x],[y,x+1]].reject{|a,b|a<0||a>=R||b<0||b>=C}.map{|a,b|m[y][x]==m[a][b]?1:0}.sum<2?m[y][x]:'.'}}}
```
[Try it online!](https://tio.run/##fVHbjoIwEH3vV0yIiRqwoYX1FtEH/8DXpg@gkMVYNYAJLOXb2da6gNnsTtJwzsyZmdOSPaKqHSVBO9uKeuJijA@BwHn6FU@xCO@1rOQzuw8Ec/mwUErGqhlxSu6wyilnRH/tjtuEc5zF5/hY1DJ0IhluXCnDbXCQMtIw2gb7xozSZcEqzkoeqD0hZxHfkbXb4PwhNnT3qq3HeNw0TXuKEyjivJiIKYIsGCX4GF4uT5bcMkghvYL2bO6BAO6PIgfBUg42WADq2JApis@39Iogvp6Q0VgWUgQQQoxZRIflqH6LUEqJxR2EwOQ9k/d0vKCS0KHkp7WXEI/6vyEdQKphP4N2M/6AZGhKrf9H7b2ph6b83pTXQdKbIm/@/MHG@WKx6B5orqJr/lBhiEZqhSFLFWqJIavVaunreRzH4fGzlkK@/mrTfgM "Ruby – Try It Online")
* Straightforward approach : we cross check every element against the 4 adjacent elements and we keep it if there are only 1, we put a dot instead.
* to check adjacent elements we build an array of [y,x] indexes and we reject pairs out of bounds, this costs so many bytes!
[Answer]
# [Matlab](https://au.mathworks.com/products/matlab.html), ~~102~~ 90 bytes
```
function a=f(a)
for i=1:9
b=a==i
a=a-b.*(conv2(b,[0 1 0;1 0 1;0 1 0],'same')~=1)*i
end
end
```
The input is *a* and the output is also *a*. This goes through all the values in the grid (1 to 9). For each value it finds cells that have more than one neighbor of that value. This is done using the 4-directional 2D convolution conv2. It then sets those cells to 0. What is left is the required grid. Note this will also work if there are multiple paths with the same digit. It also works for the case when digit 1 is missing, but digit 2 exists.
-12 bytes by removing unnecessary white space. Thanks to @MarcMush!
] |
[Question]
[
## Background
[Combinatory logic](https://en.wikipedia.org/wiki/Combinatory_logic) is a system where a term is written using a finite set of combinators and function application between terms, and reduction rules are defined for each combinator. The well-known S and K combinators have the following reduction rules:
$$
\begin{aligned}
S\;x\;y\;z & \overset{S}{\implies} x\;z\;(y\;z) \\
K\;x\;y & \overset{K}{\implies} x
\end{aligned}
$$
A term is in *normal form* when no reduction is possible. A term has a normal form if a series of reductions applied to it gives a normal form. The halting problem in combinatory logic is essentially about determining whether a term has a normal form.
In [a previous challenge of mine](https://codegolf.stackexchange.com/q/227904/78410), I mentioned that the halting problem for K is trivial; it always terminates, and we can always find the normal form of a K expression.
## Challenge
Given a K combinatory logic expression, simplify it into its normal form. For this challenge, the expression is to be input/output as a string (list of chars or charcodes is also acceptable), using prefix notation:
```
expr := "K" | "@" expr expr
```
So the expression \$K(KK)(KK)K\$ is given as `@@@K@KK@KKK`. The reduction rule can be also rewritten as
```
@@Kab => a
```
where `a` and `b` are valid expressions. The input is guaranteed to be a valid expression as a whole. You may use `k` instead of `K`, and any non-`kK` non-space printable ASCII character instead of `@`.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Generated using [this Python script](https://tio.run/##ZVFdS8QwEHzvr1jwoYn25HIiQqHiuz8hBKmX9Bpsk5JEwV9f89U24NvuzmRmd7L8ulGrp3WV86KNA9MrrueKiyGWH1@Ii8WNuK0AjHDfRmXK43XU8ioQnfr5k/ct1O81gwc4@rfat6XIieD/Ewb3kCwQru4WI5VDmfKMcVxk6Y0VyMYd5ACWnhl0XTBst50QZY0HSMuwJynNBWnA9XIi0G3vS/SS0MuORi5OBvE5@B1Sle0oO9zSnLCsgo9wEM3m0eUghDuG2RVX7GopqAh6K7zXhBW6/tioYfX0s2WRocDeIgoC1aANSJDxp24CkXNkW39rDvYlCKeobQNC8a6G0yvUxTjb4HX9Aw).
```
K -> K
@KK -> @KK
@K@KK -> @K@KK
@@KK@KK -> K
@@@@KK@KKKK -> K
@K@@@KKK@K@KK -> @K@K@K@KK
@@@KKK@@@KKK@@KKK -> @K@KK
@@@@@@@KK@KKK@@KK@@KK@KK@@@@KKK@@KKK@@K@KK@KKK@@@@K@@KK@KK@K@KK@@@KKK@K@K@KK@@@K@KK@K@K@KK@@@KK@@KK@KK@@KKK -> @K@K@K@K@KK
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~28~~ 27 bytes
```
s/@(.K)(\1*K)\1*K/$2/&&redo
```
[Try it online!](https://tio.run/##K0gtyjH9/79Y30FDz1tTI8ZQy1sTROirGOmrqRWlpuT//@/N5eANwmASSEBoKAsiA@J4w1SA2VDSG6oWrhxMQ9gOSIocwJqhOh3gKqDKoIZDOQ4oPIRpQFX/8gtKMvPziv/rFgAA "Perl 5 – Try It Online")
### How it works
Each term in the \$K\$ calculus normalizes to \$a\_i = (\texttt{@K})^i\texttt K\$ for some \$i \ge 0\$, because \$\texttt K = a\_0\$, \$\texttt @a\_0a\_j = a\_{j + 1}\$, and \$\texttt @a\_{i + 1}a\_j \to a\_i\$. So the innermost redex always looks like \$\texttt @(\texttt{@K})^{i + 1}\texttt K(\texttt{@K})^j\texttt K\$ for some \$i, j \ge 0\$, and reduces to \$(\texttt{@K})^i\texttt K\$.
To avoid the need to escape `@K` (which would otherwise refer to an array) as `\@K`, we relax it to `.K`, using backreferences for further copies. This doesn’t introduce bugs because any invalid redex \$\texttt @(\texttt{KK})^{i + 1}\texttt K(\texttt{KK})^j\texttt K\$ must be preceded by a valid redex \$\texttt @(\texttt{@K})^{i + 1}\texttt K(\texttt{@K})^j\texttt K\$.
[Answer]
# [Haskell](https://www.haskell.org/), 137 bytes
```
p('K':x)=(K,x)
p(_:x)|(s,z)<-p x,(u,v)<-p z=(s:@u,v)
data M=K|M:@M
f(x:@y)|K<-x="@K"++f y|K:@z<-x=f z|(u,_)<-p$f x=f$u:@y
f K="K"
f.fst.p
```
[Try it online!](https://tio.run/##JYxBCsMgFET3nkJEiBKTA0gE95@cIQjtp6FpkWqKEe9uTTqrmcfwHi4879tWqxcddDpJI0AlSbxY2igiqCynwdOkxK6@V81GBG3PRW4uOjobKLO2M0GRtD1kgWlIhllgfY/0KKBtPgnSXJpkOSUcaQN8b3@CFAwDRqLBEUMcfX259W38Z31Hjrwh7pm9Av@w@gM "Haskell – Try It Online")
This one actually parses the strings into a tree. I'm sure this is not the most efficient way to do this but I actually couldn't beat it. `p` is our parser, and `f` performs the actual function.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes
```
+`@@K(((@)|(?<-3>K))*(?(3)$)K){2}(?<-1>)
$1
```
[Try it online!](https://tio.run/##VYw7EoAwCET7nCMF6FjEtE5CzyW0sLCxcOzUs8d8MGrBsgsPtnlf1imEdiRiACA8wQ@ddYzYgAeLGhmP/kpT41BpEwIr4lRZo5QurmxS4IfIXpSFrXjuxdMHonwsl1QJweS5BPql91ukbg "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The `+` simply repeats until the entire expression is normalised. The `@@K` represents a potential normalisation, but we still need to find `a` and `b`. The next portion of the regex achieves this by counting `@`s and `K`s, stopping only after an equal number followed by a `K`. This is matched twice, but the second match `b` is then is dropped using `(?<-1>)`, allowing the first match `a` to be used as the substitution.
Of course this is all blown out of the water when you consider @AndersKaesorg's observation that all you have to do is to normalise depth first for 20 bytes:
```
+`@(@K)(\1*K)\1*K
$2
```
[Try it online!](https://tio.run/##K0otycxL/P9fO8FBw8FbUyPGUMtbE0RwqRj9/@/N5eANwmASSEBoKAsiA@J4w1SA2VDSG6oWrhxMQ9gOSIocwJqhOh3gKqDKoIZDOQ4oPIRpQFUA "Retina 0.8.2 – Try It Online") Link includes test cases.
[Answer]
# JavaScript (ES2019), 70 bytes
```
s=>(i=0,T=(p=s[i++],N=p<s?[p,p=T(),T()]:[p])=>p[1]>s?p[2]:N)().flat(i)
```
[Try it online!](https://tio.run/##fY7NDoIwEITvvgjdUIl6RBd6b8KJW9MDQTA1hG4s8fUrYoM/ST10251vO7PX5t649mZo2o723PkevcOCGdzxGhmhUyZNNa@QTq5UxAlrBnw@OlekAQtSe124ktRB5xUwyPqhmZgB39rR2aHLBnthPUtkAnDc/IhCRuQYmPUoCjBq@eTyj/WCQ5XxkDVnuV9v8fFPLBHBTKwTYSysEBrx1b3dQrx/AA "JavaScript (Node.js) – Try It Online")
This one try to parse the string into a tree, and then convert back.
```
s=> // Input String
(i=0, // cursor for reading the string
T=( // We try to parse the string into a prefix expression tree
// Tree structure would be `<exp> ::= ["K"] | ["@", <exp>, <exp>]`
p=s[i++], // get character under cursor, and move cursor to next character
N= // Node for expression tree
p<s? // s would be a single "K" or start with "@"
// In either cases, `p<s` indicate `p` is "@"
[p, // Expression node, "@" character
p=T(), // We reuse `p` variable to storage left child of current node
T() // And right child here
]:
[p] // `["K"]` as leaf node
)=>
p[1] // If current character is "K", then p === "K", p[1] would be (void 0)
// If current character is "@", then p is left child
// If left child is leaf node ["K"], p[1] is (void 0)
// If left child is non-leaf node ["@", <exp>, <exp>], p[1] is its left child
>s? // p[1]>s whenever p[1] is "K" since s would start with "@"
// For the special case s === "K", p[1] is (void 0) and compare would always be false
p[2]: // Current node is ["@", ["@", "K", <exp = p[2]>], <exp>]
// We keep p[2] and drop the right child expression
N // Otherwise, we keep current expression as is
)().flat( // We flat the expression so we got an array of characters
// which would be acceptable for string I/O
i) // `i` would equals to length of original string
// And the expression nested level would always less than `i`
// So we use `i` here to flatten the array
```
---
# JavaScript (ES6), 51 bytes
```
f=s=>s<(s=s.replace(/@(@K)(\1*K)\1*K/,'$2'))?f(s):s
```
[Try it online!](https://tio.run/##fY7dCgIhEIXve47AMWqXuqysufcVuhHTKGRddqLXN9eG7QcMZHTON3OON/MwZIdrf1918eySV/mQOtAeSFEzuD4Y66BFQC3htF5oOZZ2KeYbIeXRA8ktJRs7isE1IV7Ag9AZ7WY/IuqKXANZryKGVcuR6z/WBXPV9ZApp9yvN37sYYlgM5wmeIy/wA1@dW83jk9P "JavaScript (Node.js) – Try It Online")
The regex used in [this Perl answer](https://codegolf.stackexchange.com/a/229296/44718).
[Answer]
# [Python 3](https://docs.python.org/3/), 82 bytes
```
import re
def f(e,n=1):
while n:e,n=re.subn(r'@(@K)(\1*K)\1*K',r'\2',e)
return e
```
[Try it online!](https://tio.run/##VU5BjsIwDLznFb45QQGJ3RtSUe7@AqcVqbBUksikWu3ru0kIhV7smfF47PSXbzF8LwvfU5QM4tXVjzBqb8NwNCcFvzeePIRTFcQfHvNP0IJOOzL6ctyRqQWt4OULrTeqRORZAvhljAITcADOXjSHNGcLiDWULUQYYDo80sRZI@zPgHW3iKPmgpJwyLr4cH9GC2LrbIBoFqpmUo4aKK3AlTRaShcq6XQVqCm0WXottkGvtM1076TWn9h9uF2z9gi3Orqtn@zEbdg7jbY/1dPqHw "Python 3 – Try It Online")
Obligatory translation of Anders Kaseorg's excellent Perl solution. I will admit to not being sure this works.
Without regex:
# [Python 3](https://docs.python.org/3/), ~~125~~ ~~122~~ ~~97~~ ~~96~~ ~~94~~ 89 bytes
```
def f(e,*s):
for x in e[::-1]:s=[x,*s]*(x>'@')or[s[0][2:]or'@K'+s[1]]+s[2:]
return s[0]
```
[Try it online!](https://tio.run/##VU5BjsMgDLznFb6ZdMlq270hJeLOExC3EhUpggiolH191rA03VzsmfF47PUnP4L/3ve7nWFmll9SLzqYQ4QNnAerhRiuRqRRbzQzF7ZNKLEPUSf9ZfRNmBBRKvxI@moMVVI6iDY/o4di2UvWUrJctpE5vz4zB8RyxnEIMMLymdbFZYYwTIA9rZM4M0dojc5nRj4cJuQQeZmNEPpdFbPqpKqAGsGDVEqlCYU0egiqKuq09Fqsg1bVOVO@k2r/w/KfW1Zri5CHo9nayUbkib3T1Pmncrr7BQ "Python 3 – Try It Online")
*-3 bytes because naming `o` was entirely pointless*
*-23 bytes thanks to tsh, and then I also shaved another 2 off since not needing list mutability opens the door to some splat abuse*
*-1 byte because it's not like `s` has to not be a list either*
*-2 bytes thanks to ovs replacing the ternary with another `or`*
*-5 porting Wheat Wizard's second golf to my Haskell solution*
(Note: there are old explanations in the edit history)
```
def f(e ): # Define a function f taking an argument e
,*s # and collecting any extra arguments into a tuple s.
# (There are no extra arguments, so s is empty.)
for x in e[::-1]: # For each element x of e, in reverse order:
s=[ ]*(x>'@') # if x is 'K', set s to a list
x,*s # containing x followed by the elements of s,
s= or # else set s to:
[ ... ]+s[2:] # s without its first two elements, appended to:
# (note: this would error if s was not a list,
# but a valid input must end in K)
s[0] # the first element of s
[2:] # without its first two characters
or # unless that's empty, otherwise
'@K'+s[1] # the second element of s appended to 'K@'.
return s[0] # Return the sole remaining element of s.
```
I'd attempted to remove the final reversal before, but it came out longer because I tried using `insert` instead of removing `pop`.
Since Python 2 doesn't require you to import `reduce` (why would they change that? :/ also thanks again to tsh), porting to it saves two more bytes:
# [Python 2](https://docs.python.org/2/), ~~93~~ ~~92~~ 86 bytes
```
lambda e:reduce(lambda s,x:([x]+s)*(x>'@')or[s[0][2:]or'@K'+s[1]]+s[2:],e[::-1],[])[0]
```
[Try it online!](https://tio.run/##VU7RbsMgDHzPV1iVImCl09pHpFS88wkUTdmaaEhpiAzV0q/PgLF0ebHvzuezp0f4cuNp6ZvLMrS3j2sLncDuev/saOGez4Lq2ew9e6HzmUjCHGqv34w@CeOQSEX2Xh9NdCSFd1qIw9FwbVg0Lb1DGMCOYEOHFNvvdztO98CBECYqsBwcNDC8@mmwgRI4nIGwCjCKPbURTWjHALvap1GstEa2gxpoXEWejA04tqg0VpVUGcQW4UoyjaUIiRS6CiorarP0t5gHpaptpnwm5f6L5T@3zNYSIVdHsZWThcgNe6ap7U/pdPUD "Python 2 – Try It Online")
*-1 porting ovs's golf*
*-5 porting Wheat Wizard's second golf to my Haskell solution*
[Answer]
# [Python 3](https://docs.python.org/3/), 190 bytes
```
lambda x:h(c(g(x)))
g=lambda x:x.pop(0)>"@"and"K"or[g(x),g(x)]
c=lambda x:x=="K"and"K"or(lambda x:x[0][0]=="K"!=x[0]and x[0][1]or x)([*map(c,x)])
h=lambda x:x=="K"and x or"@"+h(x[0])+h(x[1])
```
[Try it online!](https://tio.run/##bY/LDoMgEEX3fgVlNdOaRtNdExr3fIJ1QTWKiQKhNqFfb8Fnm5RM5nHncAPmPUitLmPN7mMn@kcliLtKKKEBh4hRwzbVnY02kOCNZlSoinKqbR6wOKQiKr9Qxvx6hWDX86TwMW0PLEyeIZOaFtoSh5Afe2GgjL0jRvKPJXFEW/@Ek4RwEaeaFjga26oBauja5wCtMq8B/A9wzObDuQ8@1bmfRb6mDQj9QiwYn9tlyH6m3c1THw "Python 3 – Try It Online")
Horribly long answer. But, it's the most direct way I could think of at first.
And a horribly scuffed one-liner using weird something-combinators just because this challenge is about combinators:
# [Python 3](https://docs.python.org/3/), 227 bytes
```
lambda x:(lambda h,c,g:h(h,c(c,g(g,x))))(lambda f,x:x=="K"and"K"or"@"+f(f,x[0])+f(f,x[1]),lambda f,x:x=="K"and"K"or(lambda x:x[0][0]=="K"!=x[0]and x[0][1]or x)([f(f,y)for y in x]),lambda f,x:x.pop(0)>"@"and"K"or[f(f,x),f(f,x)])
```
[Try it online!](https://tio.run/##dU/RCsMgDPwV51NkMlr2Vujou5/Q9aFbsRU6K50D@/UuVtuxwUIwd8nlVLPYYdJnL8urH9vHrWuJKyChgd95XwyAFRBBzx3D2MaSu8KVJRW01R2e00wrepSA/TprWEJ5w/jfBdjvDCuY6/RQBoYasnbzZpqJY1AHw4VJZAtRmrgf55OZDGTsgq/Y/NcVx3gsDfNmVtqChFE9LShtXhbCl3wVQwhMsdaIY1Nsxy4IOCmSTESYSPXFPm6oegM "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 21 bytes
```
Ṫṫ3ȯṪ⁾0K;Ɗṭ
ṚṭÇ}V?@/Ṛ
```
[Try it online!](https://tio.run/##y0rNyan8///hzlUPd642PrEeyHjUuM/A2/pY18Oda7ke7pwFpA6314bZO@gDOf@tHzXMUdC1U3jUMNf6cDsXUK2DQSWQ8XD3loc7Nj3csehw@7GuR01rIv//9wap8@Zy8AYzgBSQCeeAuUACKgDiQLlwAW@wiDeKJphGsASU9EY10wFhEpiGsB2QVDuAlUKNcICrgCqDWgnlOKDwEKZ5o7oJyAcA "Jelly – Try It Online")
A full program that takes a single argument consisting of `K`s and `0`s and prints the output to STDOUT using the same symbols.
Based on @UnrelatedString’s Python answer so be sure to upvote that one too!
Thanks also to @UnrelatedString for saving a byte!
## Explanation
### Helper link
Takes the current draft output list and processes it where there was a zero in the next position
```
Ṫ | Tail (pop last element from list)
ṫ3 | Third character onwards
ȯ Ɗ | Or the following as a monad:
Ṫ | - Tail (pop last element from list)
⁾0K; | - Concatenate "0K" to this
ṭ | Tag onto end of draft output list (this will have lost its last two members via the action of Ṫ twice)
```
### Main link
```
Ṛ | Reverse
@/ | Reduce using the following, swapping left and right arguments:
V? | - If the next value in the reversed list evaluates to non-zero (i.e. is a K)
ṭ | - Then wrap it in a list and add to the end of the draft output list
Ç | - Otherwise call helper link on draft output list
Ṛ | Finally reverse, and implicitly smash together and print
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~68~~ 64 bytes
```
head.foldr(#)[]
'K'#s="K":s
a#(t:n:s)|_:_:v<-t=v:s|u<-a:t++n=u:s
```
[Try it online!](https://tio.run/##VYxBDoMgEEX3noLUhRqjByCQsKc9QdsYoqCmikTQbjx7qSK17WL@/J95fxqmH7zrrMA323BW5WLoqjEOk@s9iGgUanyiJ6gDFsYGSqiTpYAFnFFm8Az1MqGMQZOmEk9Q2561EmDQM3UpQKzGVhqQA5Gs8hzGSgOMEKi5ObeSWwoI3cbpKvv2br9sgX4I571Szx6427snPxBxZd8kB@Ex/9wH8pe@31bqVYqO1dpmpVJv "Haskell – Try It Online")
*-4 thanks to Wheat Wizard actually using the destructured arguments and realizing that the input only consists of one expression (so at the end there should only be one on the stack)*
Another translation of my Python answer.
```
. -- The relevant function is the composition of
foldr(#) -- right-associative folding #
[] -- starting from an empty list
head -- and taking the first element from the result.
'K'#s= -- If the item encountered is the character 'K', # yields
"K":s -- the string "K" prepended to the accumulator.
a# -- If it's something else (that is, '@', which we bind to a),
(t:n: ) -- let t and n be the first two elements of the accumulator
s -- and s the remaining elements;
|_:_:v<-t -- if t has at least two elements to ignore let v be the rest
=v:s -- and yield v prepended to s,
|u<- -- else t must be "K", let u be
a:t -- "@K"
++n -- concatenated with n
=u:s -- and yield u prepended to s.
```
] |
[Question]
[
A Belphegor number is a number of the form \$(10^{n+3}+666)\*10^{n+1}+1\$ (`1{n zeroes}666{n zeroes}1`) where \$n\$ is an non-negative integer. A Belphegor prime is a Belphegor number that is also prime.
The \$n\$ values of the first few Belphegor primes are `0`, `13`, `42`, `506` ([A232448](https://oeis.org/A232448))
# Task
Write a program that either:
* takes no input and outputs all Belphegor primes.
* takes a input \$k\$ and outputs the first \$k\$ Belphegor primes.
A reference python implementation can be found [here](https://tio.run/##VY5BCsMgEEX3nmKgG01LaAhkUcgtcoKWsQpxRtQsPL21MaR0FrP4//3543MyTGMp1nkOCWzCkJjXKHRgBzE7n3tKBjnk3gfrMGGs2EHHXRJCcwACS798/@KNklQPAXWeuHqD70rNIId710mCK4yqrmmaFHRwisNXHMQe26/XyNEjzzOq@VY3pJUcidp6cjfQ6xbNvIQNFcAF6gcNoT@rlA8).
# Rules
* You may output the \$n\$ value for the Belphegor prime instead of the prime itself
* You may use probabilistic primality tests as long as there is no known counter case.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins.
---
*Inspired by [The Most Evil Number - Numberphile](https://www.youtube.com/watch?v=zk_Q9y_LNzg)*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞°66+€ûʒp
```
Outputs the infinite sequence.
Extremely slow due to the prime-check on large numbers, so times out before it even reaches the `n=13` Belphegor prime on TIO..
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8QxvMzLQfNa05vPvUpIL//wE) or [verify the numbers without the prime-check filter](https://tio.run/##yy9OTMpM/f//Uce8QxvMzLQfNa05vPv/fwA).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,4,5,...]
° # Take 10 to the power each: [10,100,1000,10000,100000,...]
66+ # Add 66 to each: [76,166,1066,10066,100066,...]
€û # Palindromize each: [767,16661,1066601,100666001,10006660001,...]
ʒ # Filter the list by:
p # Check whether it's a prime number
# (minor note: 767 is NOT a prime)
# (after which the resulting list is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 51 bytes
outputs the n value
"...program that does not stop and will eventually output all..."
```
PrimeQ[10^c*666+1+100^++c]~If~Print[c-2]~Do~{c,∞}
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDM3NTDa0CAuWcvMzEzbUNvQwCBOWzs5ts4zrQ4om1cSnaxrFFvnkl9XnazzqGNe7f///wE "Wolfram Language (Mathematica) – Try It Online")
thanks to @DanTheMan for saving 4 bytes
and also to @mypronoun -7 bytes
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
.fP_sj666_B`^TZQ0
```
[Try it online!](https://tio.run/##K6gsyfj/Xy8tIL44y8zMLN4pIS4kKtDg/3@jf/kFJZn5ecX/dVMA "Pyth – Try It Online")
Takes `k` as input and outputs the `n` corresponding to the first `k` Belphegor primes.
Explanation:
```
.fP_sj666_B`^TZQ0
.f Q0 Find the first k values of Z where the following is true,
starting at 0 and counting upwards.
^TZ Raise 10 to the power of Z
` Convert to a string
_B Pair with reversal
j666 Join with 666 in the middle
s Convert to number
P_ Check for primality.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) -rprime, 45 bytes
```
Prime.map{|p|p p if"#{p}"=~/^1(0*)666(\1)1$/}
```
[Try it online!](https://tio.run/##KypNqvz/P6AoMzdVLzexoLqmoKZAoUAhM01JubqgVsm2Tj/OUMNAS9PMzEwjxlDTUEW/9v//f/kFJZn5ecX/dYsKQDoB "Ruby – Try It Online")
Stutters, then checks all primes against a Belphegor prime regex. Very slow.
(Edit: Kudos to @Abigail, whose earlier [Perl answer](https://codegolf.stackexchange.com/a/205314/92901) used a similar regex. I didn't notice it until after I posted my answer.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+ؽṬ6×1;ŒḄḌṄẒ¡×0µ1#
```
A full program which prints the Belphegor primes.
**[Try it online!](https://tio.run/##AS0A0v9qZWxsef//K8OYwr3huaw2w5cxO8WS4biE4biM4bmE4bqSwqHDlzDCtTEj//8 "Jelly – Try It Online")**
### How?
```
+ؽṬ6×1;ŒḄḌṄẒ¡×0µ1# - Main Link: no arguments (implicit input = 0)
µ1# - count up, from n = 0, finding the first n for which
this yields a truthy value:
ؽ - [1,2]
+ - add to n -> [n+1, n+2]
Ṭ - un-truth -> [0]*n+[1,1] (e.g. n = 3: [0,0,0,1,1])
6× - multiply by six -> [0]*n+[6,6]
1; - prefix with a one -> [1]+[0]*n+[6,6]
ŒḄ - bounce -> [1]+[0]*n+[6,6,6]+[0*n]+[1]
Ḍ - from base 10 -> 100...0066600...001
¡ - repeat...
Ẓ - ...number of times?: is prime?
Ṅ - ...action?: print it and a newline character
×0 - multiply the result by 0 (forcing an infinite loop)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
```
b=2
while 1:n=100**b+10**~-b*666+1;all(n%m for m in range(2,n))and print(n);b+=1
```
[Try it online!](https://tio.run/##DcRLCoAgFAXQeat4k8BPQa/AQeFilH6C3UKEaNLWrTM415P3E0Mp3vbVvYe4EI@w3HVKec3/b@uVMUbz5GIUqA9az0QHBVBy2BbRN5DSYaYrBWQBOXltuZQP "Python 3 – Try It Online")
[Answer]
# perl -M5.010 -Mbigint -Mexperimental=signatures, 62 70 bytes
```
sub p($m=3){$m>=$_||($_%$m&&p($m+2))}$_=16661;{p&&say;s/6+/0$&0/;redo}
```
[Try it online!](https://tio.run/##FcrdCsIgGIDhW@ngSyaj1GKeiN1B1yCOPoYwf1AHxbZbz9rRCw9vwjwPrZVlPKUOvL7TFfxDg9m2DswZPCGH9zdKdzBaSCmFWhMhxX5UYbJnHAhnKuMr7q19Y6ouhtIuz@HKBf8X3wmz8xiqnXVxU7B1yXgco5tcqD8 "Perl 5 – Try It Online")
@ikegami pointed out the original solution doesn't work, because `..` doesn't work well with bigints. So we replaced it with recursive function which checks whether a number is a prime (by checking whether it isn't evenly divisible by any odd digit less than the tested number (excecpt 1)). We also no longer iterating over all numbers, instead, we're just checking all the Belphegor numbers; we can easily make the next one from the previous by replacing `666` by `06660`.
It's still slow, because of the rather dumb primeness checking. Running it on TIO doesn't actually produce any output (it seems to run at most one minute). Running it from the command line quickly produces 16661, but I couldn't bother waiting for it to reach 1000000000000066600000000000001, the next Belphegor prime. It is likely to die from memory exhaustion when trying to determine one of the Belphegor numbers is prime, before finding 1000000000000066600000000000001 anyway.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 22 bytes
```
.V0IP_h*+^T+3b666^Thbb
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/MwDMgPkNLOy5E2zjJzMwsLiQjKen/fwA "Pyth – Try It Online")
Implements the formula provided in the question. Prints the *n* values rather than the primes themselves.
Since this version (not surprisingly) times out on TIO, here is a version that prints all *n* values lower than the input: [Try it online!](https://tio.run/##K6gsyfj/PyzQMyA@Q0s7LkTb2M/MzCwuJMPP7/9/QxMA "Pyth – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 71 bytes
A full program that prints Belphegor primes forever ... and takes forever to print them.
```
for(k=10n;;)for(d=n=666n*k+(k*=10n)*k+1n;n%--d||d<2n&&console.log(n););
```
[Try it online!](https://tio.run/##FclBCoAgEAXQ0xRaGNXCzeRhJC1K@RMWrby75e7BO@1r7zUd16PAzpeycRLBTCOIZLUzMFprdKEXoashf04gNEq5nN0yo21Xxs3RD5F3AUmSSvkA "JavaScript (Node.js) – Try It Online")
### Commented
```
for(k = 10n;;) // outer loop: start with k = 10 and loop forever
for( // inner loop:
d = n = // start with d = n =
666n * k + // 666 * k +
(k *= 10n) * k + // (10 * k)² +
1n; // 1
// and update k to 10 * k
n % --d || // decrement d until it divides n
d < 2n && // if d is less than 2:
console.log(n); // n is prime --> print it
); //
```
---
### [JavaScript (Node.js)](https://nodejs.org), 176 bytes (non-competing)
A *much* faster version that uses a single iteration of the Miller-Rabin primality test.
```
for(k=10n;;)(n=666n*k+(k*=10n)*k+1n,~-(x=(g=(d,r,a)=>d?g(d/2n,d&1n?r*a%n:r,a*a%n):r)(d=n/(~-n&1n-n),1n,2n))&&~x+n?(g=d=>~d+n?~-(x=x*x%n)?~x+n&&g(d+d):1:1)(d):0)||console.log(n)
```
[Try it online!](https://tio.run/##HYzBCoMwEES/pmFXYzUePERiviW4VlplU2IpHsRfT9eeZpjHvFf4hm1Mz/en4khTzo@YYHGm4b5HYNd1HRdLCUtxbSjVsD4r2B3MDkgnHdAN5GegumVNyrBPRbixFXIl2oRAjms4KxZaMWpRtIyo1LmX7EVEbjhJ6l@8F7vc/MWUEm9JaI01YkHb4HGMkbe4Tvc1zsCY8w8 "JavaScript (Node.js) – Try It Online")
I guess it doesn't comply with the challenge rules since the test is likely to produce false-positives. It does however find the same 5 first terms as other answers.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 108 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 13.5 bytes
```
Þ:'3+↵666+n›↵*›æ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJUPSIsIiIsIsOeOiczK+KGtTY2Nitu4oC64oa1KuKAusOmIiwiIiwiIl0=)
Using the `T` flag sets the interpreter to time out after 1 minute :P
[Answer]
# Python, ~~220~~ 164 bytes
```
def a(k,s=set()):
for i in range(k):
p=1;n=(10**(i+3)+666)*10**-~i+1
for d in range(1,int(n**.5//1/2)):
p*=n%-~(d*2)>0
if~-p:break
s.add(p*n)
return s
```
Simple prime search by checking modulus below the square root; fastened by skipping every even divisor.
Likely there's room for improvement, as it becomes incredibly slow for k > 10.
---
Edit: thanks to @JonathanAllan and @mathjunkie for ideas and sources. This update has heavy use of tweaks and bit-operations.
] |
[Question]
[
## Definitions
### Quadratic residues
An integer \$r\$ is called a [quadratic residue](https://en.wikipedia.org/wiki/Quadratic_residue) modulo \$n\$ if there exists an integer \$x\$ such that:
$$x^2\equiv r \pmod n$$
The set of quadratic residues modulo \$n\$ can be simply computed by looking at the results of \$x^2 \bmod n\$ for \$0 \le x \le \lfloor n/2\rfloor\$.
### The challenge sequence
We define \$a\_n\$ as the minimum number of occurrences of the same value \$(r\_0-r\_1+n) \bmod n\$ for all pairs \$(r\_0,r\_1)\$ of quadratic residues modulo \$n\$.
The first 30 terms are:
$$1, 2, 1, 1, 1, 2, 2, 1, 1, 2, 3, 1, 3, 4, 1, 1, 4, 2, 5, 1, 2, 6, 6, 1, 2, 6, 2, 2, 7, 2$$
This is [A316975](http://oeis.org/A316975) (submitted by myself).
## Example: \$n=10\$
The quadratic residues modulo \$10\$ are \$0\$, \$1\$, \$4\$, \$5\$, \$6\$ and \$9\$.
For each pair \$(r\_0,r\_1)\$ of these quadratic residues, we compute \$(r\_0-r\_1+10) \bmod 10\$, which leads to the following table (where \$r\_0\$ is on the left and \$r\_1\$ is on the top):
$$\begin{array}{c|cccccc}
& 0 & 1 & 4 & 5 & 6 & 9\\
\hline
0 & 0 & 9 & 6 & 5 & 4 & 1\\
1 & 1 & 0 & \color{blue}7 & 6 & 5 & \color{green}2\\
4 & 4 & \color{magenta}3 & 0 & 9 & \color{red}8 & 5\\
5 & 5 & 4 & 1 & 0 & 9 & 6\\
6 & 6 & 5 & \color{green}2 & 1 & 0 & \color{blue}7\\
9 & 9 & \color{red}8 & 5 & 4 & \color{magenta}3 & 0
\end{array}$$
The minimum number of occurrences of the same value in the above table is \$2\$ (for \$\color{green}2\$, \$\color{magenta}3\$, \$\color{blue}7\$ and \$\color{red}8\$). Therefore \$a\_{10}=2\$.
## Your task
* You may either:
+ take an integer \$n\$ and print or return \$a\_n\$ (either 0-indexed or 1-indexed)
+ take an integer \$n\$ and print or return the \$n\$ first terms of the sequence
+ take no input and print the sequence forever
* Your code must be able to process any of the 50 first values of the
sequence in less than 1 minute.
* Given enough time and memory, your code must theoretically work for any positive integer supported by your language.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
:UG\u&-G\8#uX<
```
[Try it online!](https://tio.run/##y00syfn/3yrUPaZUTdc9xkK5NMLm/39jAwA) Or [verify the first 30 values](https://tio.run/##Dcs7CsJAAEXR/m4jYCfMe/MXSyEbUJCQIum1M@DuR09/3vvnNbZxeczrcTrPa5uO53Xclu99CBNJZAqVRkcBCRlFlFBGBVXUUMcB/49xxAlnXHDFDXdi@AE).
### Explanation
```
: % Implicit input. Range
U % Square, element-wise
G % Push input again
\ % Modulo, element-wise
u % Unique elements
&- % Table of pair-wise differences
G % Push input
\ % Modulo, element-wise
8#u % Number of occurrences of each element
X< % Minimum. Implicit display
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-g`, ~~22~~ 20 bytes
Spent too long figuring out what the challenge was actually about, ran out of time for further golfing :\
Outputs the `n`th term in the sequence. Starts struggling when input `>900`.
```
õ_²uUÃâ ïÍmuU
£è¥XÃn
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9V+ydVXD4iDvzW11VQqj6KVYw24=&input=NTAKLWc=) or [check results for 0-50](https://ethproductions.github.io/japt/?v=1.4.6&code=9V+ydVXD4iDvzW11VQqj6KVYw24gZw==&input=NTEKLW0=)
---
## Explanation
```
:Implicit input of integer U
õ :Range [1,U]
_ :Map
² : Square
uU : Modulo U
à :End map
â :Deduplicate
ï :Cartesian product of the resulting array with itself
Í :Reduce each pair by subtraction
m :Map
uU : Absolute value of modulo U
\n :Reassign to U
£ :Map each X
è : Count the elements in U that are
¥X : Equal to X
à :End map
n :Sort
:Implicitly output the first element in the array
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Dennis (forcing dyadic interpretation with a leading `ð`)
-2 more also thanks to Dennis (since the pairs may be de-duplicated we can avoid an `R` and a `2`)
```
ðp²%QI%ĠẈṂ
```
A monadic link accepting a positive integer which yields a non-negative integer.
**[Try it online!](https://tio.run/##AR0A4v9qZWxsef//w7BwwrIlUUklxKDhuojhuYL///8xMA "Jelly – Try It Online")** Or see [the first 50 terms](https://tio.run/##ASEA3v9qZWxsef//w7BwwrIlUUklxKDhuojhuYL/NTDDh@KCrP8 "Jelly – Try It Online").
### How?
```
ðp²%QI%ĠẈṂ - Link: integer, n e.g. 6
ð - start a new dyadic chain - i.e. f(Left=n, Right=n)
p - Cartesian product of (implicit ranges) [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6],[4,1],[4,2],[4,3],[4,4],[4,5],[4,6],[5,1],[5,2],[5,3],[5,4],[5,5],[5,6],[6,1],[6,2],[6,3],[6,4],[6,5],[6,6]]
² - square (vectorises) [[1,1],[1,4],[1,9],[1,16],[1,25],[1,36],[4,1],[4,4],[4,9],[4,16],[4,25],[4,36],[9,1],[9,4],[9,9],[9,16],[9,25],[9,36],[16,1],[16,4],[16,9],[16,16],[16,25],[16,36],[25,1],[25,4],[25,9],[25,16],[25,25],[25,36],[36,1],[36,4],[36,9],[36,16],[36,25],[36,36]]
% - modulo (by Right) (vectorises) [[1,1],[1,4],[1,3],[1,4],[1,1],[1,0],[4,1],[4,4],[4,3],[4,4],[4,1],[4,0],[3,1],[3,4],[3,3],[3,4],[3,1],[3,0],[4,1],[4,4],[4,3],[4,4],[4,1],[4,0],[1,1],[1,4],[1,3],[1,4],[1,1],[1,0],[0,1],[0,4],[0,3],[0,4],[0,1],[0,0]]
Q - de-duplicate [[1,1],[1,4],[1,3],[1,0],[4,1],[4,4],[4,3],[4,0],[3,1],[3,4],[3,3],[3,0],[0,1],[0,4],[0,3],[0,0]]
I - incremental differences (vectorises) [0,3,2,-1,-3,0,-1,-4,-2,1,0,-3,1,4,3,0]
% - modulo (by Right) (vectorises) [0,3,2,5,3,0,5,2,4,1,0,3,1,4,3,0]
Ġ - group indices by value [[1,6,11,16],[10,13],[3,8],[2,5,12,15],[9,14],[4,7]]
Ẉ - length of each [3,2,2,4,2,2]
Ṃ - minimum 2
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ ~~20~~ ~~15~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LnI%êãÆI%D.m¢
```
-2 bytes thanks to *@Mr. Xcoder*.
[Try it online](https://tio.run/##MzBNTDJM/f/fJ89T9fCqw4sPt3mquujlHlr0/9Ca/0aWAA) or [verify the first 99 test cases (in about 3 seconds)](https://tio.run/##ATAAz/8wNWFiMWX/0YJHTj8iIOKGkiAiP05VTsOQ/0xuWCXDqsOjw4ZYJUQubcKi/8KsLP8). (NOTE: The Python legacy version is used on TIO instead of the new Elixir rewrite. It's about 10x faster, but requires a trailing `¬` (head) because `.m` returns a list instead of a single item, which I've added to the footer.)
**Explanation:**
```
L # Create a list in the range [1, (implicit) input]
n # Square each
I% # And then modulo each with the input
ê # Sort and uniquify the result (faster than just uniquify apparently)
ã # Create pairs (cartesian product with itself)
Æ # Get the differences between each pair
I% # And then modulo each with the input
D.m # Take the least frequent number (numbers in the legacy version)
¢ # Take the count it (or all the numbers in the legacy version, which are all the same)
# (and output it implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~202~~ ~~200~~ ~~190~~ ~~188~~ ~~187~~ 186 bytes
* Saved ~~two~~ ~~twelve~~ ~~fourteen~~ fifteen bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
* Saved a byte.
```
Q(u,a){int*d,*r,A[u],t,i[a=u],*c=i,k;for(;a--;k||(*c++=a*a%u))for(k=a[A]=0,r=i;r<c;)k+=a*a%u==*r++;for(r=c;i-r--;)for(d=i;d<c;++A[(u+*r-*d++)%u]);for(t=*A;++a<u;t=k&&k<t?k:t)k=A[a];u=t;}
```
[Try it online!](https://tio.run/##LY/BagMxDER/pQQ22JIMOdcrij8hZ7MHYSetcbstwqaHpN@@dZbcBt6bgUnuPaVtO5tOYm9lbZAJlELsCzUqUXgESFyo@uu3Gi/O@Xq/G0iILCBTt/YBKksMC59IuXidk7f1yZlBEfe2cvLF6ZjYO3moeaiIIZqOoA4yop36Yne9MYQBZe6@cT0e69ze6muzlUOUxXdu/m/7krKa1d5@P8rnZYQfHS@u5jBlejnQ2axj0Q7vHw "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 97 bytes
```
def f(n):r={i*i%n for i in range(n)};r=[(s-t)%n for s in r for t in r];return min(map(r.count,r))
```
[Try it online!](https://tio.run/##XcwxCsJAEEbhq0wjzEgU1tKQk4QUQXd1ivy7TCZFEM@@ymJl9@CDV3Z/ZlxqvcdEiSFXG1561AMoZSMlBdmMR/zSu7dh5PXk8tO1aUtvOfUWfTPQouBlLmznW97gnYnUYgqnMbHK/zt0IchUPw "Python 2 – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 29 bytes
```
{&/#:'=,/x!r-\:r:?x!i*i:!x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/dqlpNX9lK3VZHv0KxSDfGqsjKvkIxUyvTSrGi9n@JVbVKdGVdkVWaQoV1Qn62tUZCWmJmjnWFdaV1kWZsLVeaVXW6uqE2UC1XSbSxgbWhgpGCIRgaQVlGCsZA0ljBBMwzAfJNwaJmQAihQSrNFYxi/wMA "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`!x` integers from `0` to `x-1`
`i:` assign to `i`
`x!` mod `x`
`?` unique
`r:` assign to `r`
`-\:` subtract from each left
`r-\:r` matrix of all differences
`x!` mod `x`
`,/` concatenate the rows of the matrix
`=` group, returns a dictionary from unique values to lists of occurrence indices
`#:'` length of each value in the dictionary
`&/` minimum
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 64 bytes
```
Min[Last/@Tally@Mod[Tuples[Union@Mod[Range@#^2,#],2].{1,-1},#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983My/aJ7G4RN8hJDEnp9LBNz8lOqS0ICe1ODo0LzM/DywQlJiXnuqgHGekoxyrYxSrV22oo2tYC@TEqv13yY8OKMrMK4nOU9C1U0iLzouN1VGoztNRMNRRMDaojf0PAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 88 bytes
```
->n{(z=(w=(0..n).map{|x|x*x%n}|[]).product(w).map{|a,b|(a-b)%n}).map{|c|z.count(c)}.min}
```
[Try it online!](https://tio.run/##PYxBDkAwEAA/Q7IVNnVveYg4tBWJgyWiUWzfXg7iOjOZzdszjTpVDd1waTg0SEQSOJv15sChCDlF7nqB67YM3u1wfNKUlsFUVrzBhxxf6BZPOzgRcZ4oJqgRayn/YdYoNXahV6otY3oA "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ 24 bytes
```
{⌊/⊢∘≢⌸∊⍵|∘.-⍨∪⍵|×⍨⍳⍵+1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9XTpP@pa9KhjxqPORY96djzq6HrUu7UGyNfTfdS74lHHKhD38HQQu3czkK1tWPs/Daj3UW8fxJiu5kPrjR@1TQTygoOcgWSIh2fw/7RDKwy1gTqMDQA "APL (Dyalog Unicode) – Try It Online")
Prefix direct function. Uses `⎕IO←0`.
Thanks to Cows quack for 4 bytes!
### How:
```
{⌊/⊢∘≢⌸∊⍵|∘.-⍨∪⍵|×⍨⍳⍵+1} ⍝ Dfn, argument ⍵
⍳⍵+1 ⍝ Range [0..⍵]
×⍨ ⍝ Squared
⍵| ⍝ Modulo ⍵
∪ ⍝ Unique
∘.-⍨ ⍝ Pairwise subtraction table
∊⍵| ⍝ Modulo ⍵, flattened
⌸ ⍝ Key; groups indices (in its ⍵) of values (in its ⍺).
⊢∘≢ ⍝ Tally (≢) the indices. This returns the number of occurrences of each element.
⌊/ ⍝ Floor reduction; returns the smallest number.
```
] |
[Question]
[
Background: the Ramsey number \$R(r,s)\$ gives the minimum number of vertices \$v\$ in the complete graph \$K\_v\$ such that a red/blue edge coloring of \$K\_v\$ has at least one red \$K\_r\$ or one blue \$K\_s\$. Bounds for larger \$r, s\$ are very difficult to establish.
Your task is to output the number \$R(r,s)\$ for \$1 \le r,s \le 5\$.
## Input
Two integers \$r, s\$ with \$1 \le r \le 5\$ and \$1 \le s \le 5 \$.
## Output
\$R(r,s)\$ as given in this table:
```
s 1 2 3 4 5
r +--------------------------
1 | 1 1 1 1 1
2 | 1 2 3 4 5
3 | 1 3 6 9 14
4 | 1 4 9 18 25
5 | 1 5 14 25 43-48
```
Note that \$r\$ and \$s\$ are interchangeable: \$R(r,s) = R(s,r)\$.
For \$R(5,5)\$ you may output any integer between \$43\$ and \$48\$, inclusive. At the time of this question being posted these are the best known bounds.
[Answer]
# JavaScript (ES6), ~~51~~ 49 bytes
Takes input in currying syntax `(r)(s)`.
```
r=>s=>--r*--s+[9,1,,13,2,,3,27,6][r<2|s<2||r*s%9]
```
[Try it online!](https://tio.run/##HYjdCoIwHEfvfYr/TbDZb8K0D6S2FxkjhmkY5mSLUPDdl3VxDofzdB8Xm9BPbzH6e5s6lYLSUWkhQi5E3JsaEpAVSmDTGSdrwrVc48Ya8rirbWr8GP3QFoN/sIzISFAJqkAH0NEWLzcxNoNuIMdJaXL/tfyyYzNnC@c845f0BQ "JavaScript (Node.js) – Try It Online")
### How?
As a first approximation, we use the formula:
$$(r-1)(s-1)$$
```
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16
```
If we have \$\min(r,s)<3\$, we simply add \$1\$:
```
1 1 1 1 1
1 2 3 4 5
1 3 - - -
1 4 - - -
1 5 - - -
```
Otherwise, we add a value picked from a lookup table whose key \$k\$ is defined by:
$$k=(r-1)(s-1)\bmod9$$
```
k: table[k]: (r-1)(s-1): output:
- - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - -
- - 4 6 8 --> - - 2 3 6 + - - 4 6 8 = - - 6 9 14
- - 6 0 3 - - 3 9 13 - - 6 9 12 - - 9 18 25
- - 8 3 7 - - 6 13 27 - - 8 12 16 - - 14 25 43
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~56~~ 55 bytes
```
f=(x,y)=>x<2|y<2||f(x,y-1)+f(x-1,y)-(x*y==12)-7*(x+y>8)
```
[Try it online!](https://tio.run/##NY3hCsIwDIRfJ1mbQAdDQTvwOUQkzE2UuY5OpIW9e5f98OAgd4Hv3vKTpYuv@UtTePSlDB6SzejbdK7XrF6HvSCHRg9y@iNIVfbe1UiHCpLJ7RFLF6YljD2P4QlXZr7EKBkavPFHZoC7TVaUKv@4TyjQKNA4VJ3KBg "JavaScript (Node.js) – Try It Online") I noticed that the table resembles Pascal's triangle but with correction factors. Edit: Saved 1 byte thanks to @sundar.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
’ScḢƊ_:¥9“ ı?0‘y
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw8zg5Ic7Fh3rirc6tNTyUcMchSMb7Q0eNcwASv6PNtUxiQUA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8//9Rw8zg5Ic7Fh3rirc6tNTyUcMchSMb7Q0eNcyo/G8aZH24/dDSw/sSwh41rQEi9/8A "Jelly – Try It Online").
Replace the `0` with `+`, `,`, `-`, `.`, or `/` to set \$R(5,5)\$ equal to \$43\$, \$44\$, \$45\$, \$46\$, or \$47\$ respectively (rather than the \$48\$ here).
### How?
Since \$R(r,s)\leq R(r-1,s)+R(r,s-1)\$ we may find that:
$$R(r,s)\leq \binom{r+s-2}{r-1}$$
This is `’ScḢƊ` and would produce:
```
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
```
If we subtract one for each time nine goes into the result we align three more with our goal (this is achieved with `_:¥9`):
```
1 1 1 1 1
1 2 3 4 5
1 3 6 9 14
1 4 9 18 32
1 5 14 32 63
```
The remaining two incorrect values, \$32\$ and \$63\$ may then be translated using Jelly's `y` atom and code-page indices with `“ ı?0‘y`.
```
’ScḢƊ_:¥9“ ı?0‘y - Link: list of integers [r, s]
’ - decrement [r-1, s-1]
Ɗ - last 3 links as a monad i.e. f([r-1, s-1]):
S - sum r-1+s-1 = r+s-2
Ḣ - head r-1
c - binomial r+s-2 choose r-1
9 - literal nine
¥ - last 2 links as a dyad i.e. f(r+s-2 choose r-1, 9):
: - integer division (r+s-2 choose r-1)//9
_ - subtract (r+s-2 choose r-1)-((r+s-2 choose r-1)//9)
“ ı?0‘ - code-page index list [32,25,63,48]
y - translate change 32->25 and 63->48
```
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
def f(c):M=max(c);u=M<5;print[48,25-u*7,3*M+~u-u,M,1][-min(c)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1nTytc2N7ECyLAutfW1MbUuKMrMK4k2sdAxMtUt1TLXMdby1a4r1S3V8dUxjI3Wzc3MA6qN/Z@WX6RQpJCZp1CUmJeeqmGoo2CmacXFCRIuRggXQYU5waYqALnFOgpKtnZKOgrWQNuji3SKYzX/AwA "Python 2 – Try It Online")
---
### [Python 2](https://docs.python.org/2/), 63 bytes
```
def f(c):M=max(c);print[48,M%2*7+18,3*~-M+2*(M>4),M,1][-min(c)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1nTytc2N7ECyLAuKMrMK4k2sdDxVTXSMtc2tNAx1qrT9dU20tLwtTPR1PHVMYyN1s3NzAMqjv2fll@kUKSQmadQlJiXnqphqKNgpmnFxQkSLkYIF0GFOcGGKwC5xToKSrZ2SjoK1kDro4t0imM1/wMA "Python 2 – Try It Online")
This is ridiculous, I will soon regret having posted this... But eh, ¯\\_(ツ)\_/¯. Shaved off 1 byte thanks to our kind [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) :). Will probably be outgolfed by about 20 bytes shortly though...
[Answer]
# [Julia 0.6](http://julialang.org/), ~~71~~ ~~61~~ ~~59~~ 57 bytes
```
A->((r,s)=sort(A);r<3?s^~-r:3r+(s^2-4s+3)*((r==s)+r-2)-3)
```
[Try it online!](https://tio.run/##LcoxDoMwDEbhq3i0CR5KSgcgIM6BQOoSKagC9JuuvXpg6Pb06a3fT3q/cqRAedSeGaVJsB0nj9Ki84MtP0Xj4diWSp/mvBT3FoKJg1aiXvKBtJ08RZ5Qks1CcQeB0kaPpr7lX7PkCw "Julia 0.6 – Try It Online")
### Ungolfed (well, a bit more readable):
```
function f_(A)
(r, s) = sort(A)
if r < 3
result = s^(r-1)
else
result = 3*r +
(s^2 - 4*s + 3) * ((r == s) + r - 2) -
3
end
return result
end
```
### What does it do?
Takes input as array `A` containing r and s. Unpacks the array into r and s with the smaller number as r, using `(r,s)=sort(A)`.
If r is 1, output should be 1. If r is 2, output should be whatever s is.
\$ s^{r - 1} \$ will be \$ s^0 = 1 \$ for r=1, and \$ s^1 = s \$ for r = 2.
So, `r<3?s^(r-1)` or shorter, `r<3?s^~-r`
For the others, I started with noticing that the output is:
* for r = 3, \$ 2\times3 + [0, 3, 8] \$ (for s = 3, 4, 5 respectively).
* for r = 4, \$ 2\times4 + \ \ [10, 17] \$ (for s = 4, 5 respectively)
* for r = 5, \$ 2\times5 + \ \ \ \ \ [35] \$ (for s = 5)
(I initially worked with f(5,5)=45 for convenience.)
This looked like a potentially usable pattern - they all have `2r` in common, 17 is 8\*2+1, 35 is 17\*2+1, 10 is 3\*3+1. I started with extracting the base value from [0, 3, 8], as `[0 3 8][s-2]` (this later became the shorter `(s^2-4s+3)`).
Attempting to get correct values for r = 3, 4, and 5 with this went through many stages, including
```
2r+[0 3 8][s-2]*(r>3?3-s+r:1)+(r-3)^3+(r>4?1:0)
```
and
```
2r+(v=[0 3 8][s-2])+(r-3)*(v+1)+(r==s)v
```
Expanding the latter and simplifying it led to the posted code.
[Answer]
# x86, ~~49~~ 37 bytes
Not very optimized, just exploiting the properties of the first three rows of the table. While I was writing this I realized the code is basically a jump table so a jump table could save many bytes. Input in `eax` and `ebx`, output in `eax`.
-12 by combining cases of `r >= 3` into a lookup table (originally just `r >= 4`) and using Peter Cordes's suggestion of `cmp`/`jae`/`jne` with the flags still set so that `r1,r2,r3` are distinguished by only one `cmp`! Also indexing into the table smartly using a constant offset.
```
start:
cmp %ebx, %eax
jbe r1
xchg %eax, %ebx # ensure r <= s
r1:
cmp $2, %al
jae r2 # if r == 1: ret r
ret
r2:
jne r3 # if r == 2: ret s
mov %ebx, %eax
ret
r3:
mov table-6(%ebx,%eax),%al # use r+s-6 as index
sub %al, %bl # temp = s - table_val
cmp $-10, %bl # equal if s == 4, table_val == 14
jne exit
add $4, %al # ret 18 instead of 14
exit:
ret
table:
.byte 6, 9, 14, 25, 43
```
Hexdump
```
00000507 39 d8 76 01 93 3c 02 73 01 c3 75 03 89 d8 c3 8a |9.v..<.s..u.....|
00000517 84 03 21 05 00 00 28 c3 80 fb f6 75 02 04 04 c3 |..!...(....u....|
00000527 06 09 0e 19 2b |....+|
```
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
f=lambda R,S:R<=S and[1,S,[6,9,14][S-3],[18,25][S&1],45][R-1]or f(S,R)
```
[Try it online!](https://tio.run/##VcuxDsIgFEDRWb/iTRaS1ya0tdHG/gSMhKSYitIoNICDX484up073O2THt61OZvpqV/XRQNHMfLLJEC7RTIUKAc8I@uVFHWnULITtscSB6awL@A1Uz6AIQI5zaYwgHUQtLvfCMOBjvvdFqxLUFXN6q0jsyEBI52bsL5jIh2F3xX/L5q/ "Python 2 – Try It Online")
[Answer]
# MATL, ~~25~~ 21 bytes
```
+2-lGqXnt8/k-t20/k6*-
```
[Try it on MATL Online](https://matl.io/?code=%2B2-lGqXnt8%2Fk-t20%2Fk6%2a-&inputs=4%0A3&version=20.9.1)
Attempt to port Jonathan Allan's [Jelly answer](https://codegolf.stackexchange.com/a/168624/8774) to MATL.
`+2-lGqXn` - same as that answer: compute \$ \binom{r+s-2}{r-1} \$
`t8/k` - duplicate that, divide by 8 and floor
`-` - subtract that from previous result (We subtract how many times 8 goes in the number, instead of 9 in the Jelly answer. The result is the same for all but the 35 and 70, which here give 31 and 62.)
`t20/k` - duplicate that result too, divide that by 20 and floor (gives 0 for already correct results, 1 for 31, 3 for 62)
`6*` - multiply that by 6
`-` - subtract that from the result (31 - 6 = 25, 62 - 18 = 44)
---
Older:
```
+t2-lGqXntb9<Q3w^/k-t20>+
```
[Try it on MATL Online](https://matl.io/?code=%2Bt2-lGqXntb9%3CQ3w%5E%2Fk-t20%3E%2B&inputs=5%0A5&version=20.9.1)
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
lambda *a:[[1]*5,[2,3,4,5],[6,9,14],[18,25],[43]][min(a)-1][max(a)-min(a)]
```
[Try it online!](https://tio.run/##bVDRbsIgFH3nK258Ku5uEVsXZ9af8JURwzrcmrXUAMYZ47d3UK20RgjJveeee84Ju6P7aXTarvOPtpL155eEqVxxzsR0gXyOKWa4EMhf8Q1Z5gu2xHkAslQIXpc6kfSZ@Ur@heoCiFZqe1Bm86uOkAMn4A9neL0Ce@Cm3wMp9kY9koX@4tlDC0/wQMiA2VIIIggpGmNU4bzbjJR62G0bAxbBNAcoNSi9r5WRTiUxIgKjq048cA1CoapqTPbbkdUx97rYGGX3VXBZJxYNvQ1Lu4kJOrE8H25E4hbccaeSwKGBVJXWRZOHWnwm4H0kF9puwsRQOW6OFXu5pxzYbaAqq@6M9UNiODtTapdMDqbR3yswpzNY/0KE/HTGLpovJi/@O2vpEoMWwxAHmSklF5WrCUY/OvIi7T8 "Python 3 – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 52 bytes
Near-port of my [Python answer](https://codegolf.stackexchange.com/a/168620/59487).
```
c=>[48,(M=max(c))%2*7+18,3*M-(M>4?1:3),M,1][-min(c)]
```
[Try it online!](https://tio.run/##PcoxCoMwFADQOTnFRygk9iukSitC0hPkBCFDEQIOJvLjIIhnT@3S9fFWSluKJYAukzauH1BYvXx2MUl5e9Svuxqwq20jrOnfauwkWlTeNcscr@JLSAQEIyhoW3jCwdlP8iX0F7bSHDdBCBmh0qZCCMIRZi8lZyc/yxc "Proton – Try It Online")
[Answer]
# Java 8, 62 bytes
```
(r,s)->--r*--s+new int[]{9,1,0,13,2,0,3,27,6}[r<2|s<2?1:r*s%9]
```
Lambda function, port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168633/79343). Try it online [here](https://tio.run/##RVLbToNAEH2Gr5iQmEBZGulNW1obEzUxakzsI@FhS7cNlVt2F7VBvh1nuxQJzMyeOTkzO8ORflGvKFl@3H22ZbVNkxjilAoBbzTJoTaNJJeM72nM4INmgp0UpkDIq2zLuK1CTkA54QSm0ZhGpyMklei@imQHGarZG8mT/BBGQPlBOGehTpNrt4LW5kQ43p3n8YHnCTdn30o6jOo58ck18cdkhA7tDZk1IV@OfsVytPYXfCCu5lFrGIFuL4ywjm5RoG6vg2hd@wT@34aAAkYExgQmBKYdgKcZgTkyJh0y0cdbJF9IU5VWZ8yOm0YV3xfdULCsH6BbrmAagOtyfeWeIDRB9IRuJnq87KdksWQ71by@Rsg9PwoFmqBn0VhWNEWOnuCwWwou5LwMfDYnIVk2LCo5LHH8Ms1tDi5YxEIrVLQAFXZKLtj2RXTVN@HAGiz7/cWxANn20/3z6@MD6dNaoe8YNR3L0fXxd1BfYzbtHw).
# Java, 83 bytes
```
int f(int x,int y){return x<2|y<2?1:f(x,y-1)+f(x-1,y)-(x*y==12?1:0)-7*(x+y>8?1:0);}
```
Recursive function, port of [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168619/79343). Try it online [here](https://tio.run/##RVJNb8IwDD2XX2H1lKwpWhlsjNJ9SNukaZuQxhFxCBBQGRSUpKwV629nThNK1Tq239Oza2fNDzzc7UW2Xvyc9vlsk85hvuFKwRdPMzi2PD5TWvK5BqW5btBvvlWiNPiFkGYalsRYyepA0bjlVS3P6TqBwy5dwBbVyVjLNFtNpsDlStFazOlKeySQiV9XiyDhaXQQUqYLcbrUKpixJT1KoXOZQTHs/JXDzmM0WJKClWFEA3TCiJU0JMVVmSSRAa9peHdFiqB86NdRXJ08r8J@PZSbTLGpLN/OhFSuiXP2eIwYXN6KgUl0GNww6DLouQRGtwzukdF1ma4N@0g@k3oGNjGiN1VdfLmTdoJYNorxGCbQiyEIpJ1PQ1CWoBqCG2DdP4hiL@ZaLEzz9jcmMoymE4Umbli4tJxvkGPH3V4SXFy9NHzGpdJi297lur3HNelNRiQE4DMfrTLeAIzrRAIg5KyXNPUpPIJPRh/UB2STt@f3z9cX1sBWoWkWNalPbX28NuarWtXpHw).
[Answer]
# C (gcc), 57 bytes
```
f(x,y){x=x<2|y<2?:f(x,y-1)+f(x-1,y)-(x*y==12)-7*(x+y>8);}
```
Recursive function, port of [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168619/79343). Try it online [here](https://tio.run/##RY5va4MwEMZf109xCEJST2hs3bpaVwbboGywD9D1hbOxK6yuJBYU52d3F/8VjiT3/J7LPYl3TJKmSVmBJa@KqFj7f@Xa36xaxRPcpYcnCHqsmJZRJHzu3U9Z4ZaPSx7WzSnL4RyfMsahsiamy67nL6n0LthTQQRVJRBuVSMYwUeYIywQgl6g7g7hgRyLXll07ZLMgykw2PRE53UdWpP0VzGzVdEmEdK1jiAIwXVVG2jkuuN65LrjbWRZXGSSywN5hvTKE/udpiMcTHGSX@MfsqRMIWjeguQ7VnCWWsdHuROzWWfXF0UTKesBAmPDdDQu47ABm328cRtW9Hh92r6/POOIV@AcuM1vQrew/9l2Dui0HnD0Z2YjmEzYh8QhUjtTW6aUzK8qg1lo1c0/).
# C (gcc), 63 bytes
```
f(r,s){r=--r*--s+(int[]){9,1,0,13,2,0,3,27,6}[r<2|s<2?:r*s%9];}
```
Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168633/79343). Try it online [here](https://tio.run/##RZBva4NADMZf108RBOGujaBWu7VWymAbjA32AZwvnLVdYXUlZ2Hg7rO7nP8KIXfJ78nl4Qr3WBRtexCESjaUuC7NXVctxKmq00w2a/TRQ3@JAR@c73ClU9oGf2ob7DY0V846i3XLajjnp0pIaKyZqarr@bMklUYZByTQND7CLTSCaQQIS4QQIRoaXK0Q1qwIh07Yl/csHkWRwaZmutQ6tmaHHzKOgXiTH/OxTSCKYbGgztDEVc/VxFXPO8vl76Us6nLPmtE9uX6WKk7xKMqL@pp/s8R8GSjZgeIrJziXSuXHMvU9r5erC/HEQQwAQYhxOpmWSdiBLd5fpQ0bvjw/vLw9PeKEN@DspS1vjX7h8LLt7NHpNOCoj8pGMJ5wMImjpW5GWyaorK9UgRdbuv0H).
] |
[Question]
[
## Introduction
Suppose I have a list of integers, say **L = [-1,2,2,1,2,7,1,4]**.
I like having balance in my life, so I'm happy to see it has as many odd elements as even elements.
What's more, it also has an equal number of elements in all modulo classes of 3 that it has elements in:
```
[-1,2,2,1,2,7,1,4]
0 mod 3:
1 mod 3: 1 7 1 4
2 mod 3: -1 2 2 2
```
Sadly, for the modulo classes of 4 this no longer holds.
In general, we say a non-empty list is *balanced modulo **N*** if it has an equal number of elements in all modulo classes of **N** for which this number is not 0.
The above list **L** is balanced modulo 2 and 3, but unbalanced modulo 4.
## The task
Your input is a non-empty list **L** of integers taken in any reasonable format.
Your output is the list of those integers **N ≥ 2** such that **L** is balanced modulo **N**, again in any reasonable format.
The order of the output does not matter, but it should not contain duplicates.
It is guaranteed that there are only finitely many numbers in the output, which means precisely that not all elements of **L** occur an equal number of times in it.
Examples of invalid inputs are **[3]**, **[1,2]** and **[0,4,4,0,3,3]**.
Notice that the largest number in the output is at most **max(L) - min(L)**.
The lowest byte count in each language wins, and standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test cases
```
[1,1,2] -> []
[1,1,5] -> [2,4]
[1,1,24] -> [23]
[1,2,3,2] -> [2]
[12,12,-4,20] -> [2,3,4,6,8,12,24]
[1,1,12,12,-3,7] -> [3,10]
[-1,2,2,1,2,7,1,4] -> [2,3]
[4,-17,-14,-18,-18,3,5,8] -> []
[-18,0,-6,20,-13,-13,-19,13] -> [2,4,19]
[-11,-19,-19,3,10,-17,13,7,-5,16,-20,20] -> []
[3,0,1,5,3,-6,-16,-20,10,-6,-11,11] -> [2,4]
[-18,-20,14,13,12,-3,14,6,7,-19,17,19] -> [2,3]
[-16,-9,6,13,0,-17,-5,1,-12,-4,-16,-4] -> [3,9]
[-97,-144,3,53,73,23,37,81,-104,41,-125,70,0,111,-88,-2,25,-112,54,-76,136,-39,-138,22,56,-137,-40,41,-141,-126] -> [2,3,6]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
ÄOL¦ʒ%{γ€gË
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cIu/z6FlpyapVp/b/KhpTfrh7v//ow2NdIBI10THyCAWAA "05AB1E – Try It Online")
```
ÄOL¦ʒ%{γ€gË | Full program.
Ä | Absolute value (element-wise).
O | Sum.
L | 1-based inclusive range.
¦ | Remove the first element (generates the range [2 ... ^^]).
ʒ | Filter / Select.
% | Modulo of the input with the current integer (element-wise).
{ | Sort.
γ | Group into runs of adjacent elements.
€g | Get the length of each.
Ë | Are all equal?
```
[Answer]
# [Perl 6](https://perl6.org), ~~52~~ 48 bytes
```
{grep {[==] .classify(*X%$^a).values},2.. .max-.min}
```
[Test it](https://tio.run/##TZHbTsJAEIbv@xR7oVJ0du0eeiAE5QGMV16YICa1rKZJCw1bjITwZN75YjizbdGkW9g5fPP/08Zuq@S0c5Z9JqKYBvWeXRWblWWz0@Fjaxt2WMxmSyaKKneufN@H18@XF6/5WHzm1c66IyghmKjzLy7qcn08Yf@8ta5lM1aVa@vC8c@3cE1VtuGI8Ts2onuxqd/C2xEf3b@sbm4p8rir7bbE@aTkCfunQVPla3bjYdPgfbPtucgI5@W62bUwt1@NLVq7GrNDwFjp@MraptozMtAXjcVD6Vpg59rh7rOiQfvT4HhaSJCglkRfLAN/i7ubAtMHlOkj2gcU6KFDUUABPtyAioZGDQYSyCiuBkhfpiHtqjTICFOceIqGQIpvc0ZgzgCXKR76zfzREEN2FkuRCHiCkzGr@zMBqc8OQE58ofQJOjTXc7EY4THIBDgCBvVYrpGKa8BSZPM@L6Puhk7k/wV5aZQ3ROwsSrKfdlpSkvDPlOdNMC9pjDeIGvCP36HPmmFDXvvEr8CQd1SMq9egU8ioJTJgfGsMaUSiyWdGegBDqFVBjMyUhiFX0wZ0BgrDZAUx3EQdouMkf18wWf4C "Perl 6 – Try It Online")
```
{grep {[==] bag($_ X%$^a).values},2.. .max-.min}
```
[Test it](https://tio.run/##TZHdTvJAEIbPexVzoFLi7Nr96Q8hKBdgviMPTBBNhdU0aaGhxWgIV@bZd2M4s23RpFvY@Xnmfae125XJad84@EjkahpUX3C12q4dzE6H952r4bCYzZbwmr@HFy/weHnxnI/lR17uXXNELSXIKv8Usio2xxP1zlvXtDCDsti4Jhz//5ZNXRZtOAJxCyO@r7bVa3gzEqO7p/X1DUf@7Su3K2g2q3ig/mlQl/kGrj1sGrxtdz2XGOG82NT7Fufus3ar1q3HcAgAikasnavLL2DxfdFY3hdNi3CuHe4@K2uyPg2Op4VChXrJ9MUy8Le4u2m0fUDbPmJ8QKMZOjQHNNIjLOpoaDRoMcGM43qA9GUG067KoIooJZineQim9LZnBOUsCpXS4d/MH4MxZmexHIlQJDSZsqY/E1Tm7ADVxBcqn@DDcz2Xigkeo0pQEGBQT@WGqLQGKiW26PMq6m7kRP1dkJfGecvEzqJi@2mnJWUJf0x53oTyisd4g6SB/vgd@qwdNuS1T/wKLHsnxbR6gybFjFsii9a3xphGLJp9ZqwHKURaNcbETHkYcQ1vwGSoKcxWCCNs1CE6TvL7BZPlDw "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
grep
{ # bare block lambda with placeholder parameter 「$a」
[==] # reduce with &infix:«==» (are the counts equal to each other)
bag( # group moduluses together
$_ X% $^a # find all the moduluses using the current divisor 「$a」
).values # the count of each of the moduluses
},
2 .. .max - .min # all possible divisors
}
```
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~56~~ 52 bytes
*Thanks to Not a tree for saving 4 bytes.*
```
Cases[Range[2,#.#],n_/;Equal@@Last/@Tally[#~Mod~n]]&
```
[Try it online!](https://tio.run/##TVBNS8QwEL3vrwgUFpXEJk36hZeCeFMQ8VaKBC3uQreirQdZun@9zkfaXWiHzLw3783MwY@79uDH/bufn3/2/SiqG3E13/uhHeoX33@2dSKj26iR/Vt89/D967uqevTDGFevvuv@6uj09PVx6ptmO1@LuBLHjTgaKeBLJinWJJ3kGXBLkkhhiYgpJPgrBxV9QV8BoOZUV9yasBpU6cGq0K1MjoFeRQjQm0pRhHYoaAAydEKCXUMJUjawTChQANTooI1UtABFAxoKRcLIlpQNuVm2UCvH6KWCa5nzMIw6Vl52xTxjIxoLjcvQgyIlwYYdeeeUrNVyRubxXVTJR3F8C9wATw@/BaCgNg2gYwFQyjXvQncoaEpoSGl8eKVokNME6GLpUBZoCYK0JSorpxfRIJ1Nm2n@Bw "Wolfram Language (Mathematica) – Try It Online")
The main golfing trick is to use the ~~sum of absolute values (or the 1-norm)~~ sum of squared values, computed as a dot product with itself, as the upper bound instead of `Max@#-Min@#`. Otherwise, it just implements the spec very literally.
[Answer]
# [Haskell](https://www.haskell.org/), ~~85~~ 84 bytes
```
f l=[n|n<-[2..sum$abs<$>l],all.(==)=<<head$[r|m<-[0..n],_:r<-[[0|x<-l,mod x n==m]]]]
```
[Try it online!](https://tio.run/##PVDLboMwELznK3zIIZHGyC9eFfQP@gUIVVRJlahAo6SVcsi/01njBrGw3p2dnfFpuH0dx3FZPtXYdvNjbnTnsuz2O22Hj1uzfR17DOOY7dp23zbN6Tgctt31MRFmsmzu8f5yZd6Zx73RI6bvg7qruW2nns8yDedZtWoaLm9qd7me55/sc6@6jeosLFyPlOXPzIWUOvh/gANfHeDME5ZqHmUsacE7GUfJ78oRoG3JkH8VwyNHlQYqGOiCnOz4FDWsT20bjxIe1kQmQkiXwxbQHEtqPHlogDCy6dSzZj1RqH3ui40gNKt05oUwylqy1wnIuZoNK8TRADcyiTcQu6s7XUdvQUxRGC/Lw5eoBGsCQpzJURrRJ3YqUQCWKMshJ1kpW0joxaiv4FgW1aTRwawUK0/Rb1S//AE "Haskell – Try It Online") Uses the sum of absolute values as maximum from [Martin Ender's answer](https://codegolf.stackexchange.com/a/149797/56433).
*Edit: -1 byte thanks to Ørjan Johansen.*
**Explanation:**
```
f l= -- Given a list of numbers l,
[n|n<- ] -- return a list of all numbers n of the range
[2..sum$abs<$>l], -- from 2 to the sum of the absolute values of l
all.(==)=<<head$ -- for which all elements of the following list are equal:
[r|m<-[0..n], ] -- A list r for each number m from 0 to n, where
_:r<-[ ] -- r is the tail of a list (to filter out empty lists)
[0|x<-l,mod x n==m] -- of as many zeros as elements of l mod n equal m.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
f₅⁰…2ṁa⁰
Λ≈k%
```
[Try it online!](https://tio.run/##yygtzv7/P@1RU@ujxg2PGpYZPdzZmAhkcp2b/aizI1v1////0YZGOkCka6JjZBALAA "Husk – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~75~~ 72 bytes
```
function(L){for(x in 2:(max(L)-min(L)))F=c(F,!sd(table(L%%x)))
which(F)}
```
[Try it online!](https://tio.run/##HclBCsIwEEbhvaeIi8IM/AOm1opit1n1EjUaGrAp1IqB4tlj2t3je1Ny6ibJfYKd/Rio5cWNE0XlgyqvNHQxkwx@PcymsWSwfz9o7u6vJ7VFETPvvr23PRn@JUeWRNeQC2roIw4QfYacoHOUkArbrZjTHw "R – Try It Online")
Uses `table` to compute the counts of each integer modulo `x`. The standard deviation `sd` of a set of numbers is zero iff they are all equal, and positive otherwise. Hence `!sd(table(L%%x))` is `TRUE` wherever `L` is mod-balanced mod `x` and false otherwise. These values are then concatenated into `F`.
`which` then returns the indices of true values from the function. Since R uses 1-based indexing and `F` is initially a length-one vector with value `FALSE`, this will correctly return values beginning with `2`.
One might expect the builtin function `range` to compute the [range of a dataset](https://en.wikipedia.org/wiki/Range_(statistics)), i.e., `max(D)-min(D)`, but sadly it computes and returns the vector `c(min(D), max(D))`.
[Answer]
# [Clean](http://clean.cs.ru.nl/Clean), 121 bytes
Uses the sum-of-absolutes trick from Martin Ender's answer.
**Golfed:**
```
import StdEnv
f l=[n\\n<-[2..sum(map abs l)]|length(removeDup[length[m\\m<-[(e rem n+n)rem n\\e<-l]|m==c]\\c<-[0..n]])<3]
```
**Readable:**
```
import StdEnv
maximum_modulus l = sum (map abs l)
// mod, then add the base, then mod again (to fix issues with negative numbers)
list_modulus l n = [((el rem n) + n) rem n \\ el <- l]
// count the number of elements with each mod equivalency
equiv_class_count l n = [length [m \\ m <- list_modulus l n | m == c] \\ c <- [0..n]]
// for every modulus, take where there are only two quantities of mod class members
f l=[n \\ n <- [2..maximum_modulus l] | length (removeDup (equiv_class_count l n)) < 3]
```
[Try it online!](https://tio.run/##JY09koMwDEbr5RQuYVZm/AcmM9BtTpDSduElTjYztmESSJW7E2WpPulJehpj8Hnb0nReYyDJ33JxS/N0X8hpOR/z86u4kDiYbG3uqRF1/VhTmfxM/O@DxMq9YsjX5a@8hzQ9w886mx2YZG3CizIQHJH8nav/tDb0NLpXGobRWTviCqvr7FzVS1ecFo@fB3Ihhh40UK4USGgkaAlCgtTQcaRMgfqkaEAzYMA5dl0HVAAiyrmARgHVLXDZApUHZLIDgbj9lGhWbFfsntZt2xs "Clean – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
⁹%LƙE
ASḊçÐf
```
[Try it online!](https://tio.run/##y0rNyan8//9R405Vn2MzXbkcgx/u6Dq8/PCEtP///0cbGukAka6JjpFBLAA "Jelly – Try It Online")
Thanks to [user202729](https://codegolf.stackexchange.com/users/69850/user202729) for saving a byte and to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) (indirectly) for saving a byte.
# How it works
```
⁹%LƙE ~ Helper link. Let's call the argument N.
⁹% ~ Modulo the input by N (element-wise).
Lƙ ~ Map with length over groups formed by consecutive elements.
E ~ All equal?
ASḊçÐf ~ Main link.
AS ~ Absolute value of each, sum.
Ḋ ~ Dequeue (create the range [2 ... ^]).
çÐf ~ Filter by the last link called dyadically.
```
A one-liner alternative 12-byter can be [tried online!](https://tio.run/##y0rNyan8/98x@OGOrsMbHjXuVPU5NtP18IbDE9L@//8fbWikA0S6JjpGBrEA "Jelly – Try It Online")
[Answer]
# Python 3, ~~120~~ 102 bytes
Not pretty golfy.
*-18 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).*
```
f=lambda a,i=2:[]if i>max(a)-min(a)else(len({*map([k%i for k in a].count,range(i)),0})<3)*[i]+f(a,i+1)
```
[Try it online!](https://tio.run/##TVFNb5tAFDzHv2IvVSB5WOyHDbZKbumlh1x6Q6haO@tmFQwIcJuo6m935y3GicSC38zbeTPP3fv40jb6fD4UtT3unq2w5Au1LSt/EP7haN8iGydH3@Dj6sFFtWuiv3dH20Xl6xcvDm0vXoVvhK2W@/bUjNTb5peLfBxT@i/@quO70lf3hwiy9zI@@2PX9qOww7gY@/ft4ubPi6@d@NGfHIqbvSgg1p3GKEZVo9ovh672Y3Qrkgdxy6glsQPBFiCzBOl6W/90v21NouYOWB8wxT1HmBvHoijmehdvRdf7BnpP34Mah7pij33f9oDd2951o3h8@hYQ8HYYzqUkSapiI2W1CNVqqhSZC6DMBdEBUKTnG4oBRXgSQyqdL2oytKaccTWLXNo0ZVOXJpmCSlhP8RDK8DZXCXCGEpnh8DcPR9OK8qtZRlJK1pgMVl/OhqS@JiC5CY0yEHx4btBFM8RXJNeUQGB2j3YNVawBrdBOLrxMpwpJ5OcFBWvMG1acIkqOn01eMrbwKVTQ24CXPCYEhAf8CDsMrJk3FLxvwgoMZ4djrF6TzijnK6khE66uKEvZNOfM2Q8BgldFK2hmPAy6mjegc1KAOQpkEpNOEpPO@uMfXFf/AQ "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
*-4 bytes thanks to [Luis Mendo!](https://codegolf.stackexchange.com/users/36398/luis-mendo)*
```
S5L)d:Q"G@\8#uZs~?@
```
[Try it online!](https://tio.run/##JcyrDgJBDIXhdwFFcppMLzPtYli3Zg3BcREkSFCA5dWHblb19BP/6/559n6q8@6xP26m8Rrb7/n9O4y9X2hwEJtBURWuEIU6glOLwZYrFV5QwJxfBEiQRMyCaiBvYG0gHdI0IMltmVm2sibWTrv9AQ "MATL – Try It Online")
Port of my [answer in R](https://codegolf.stackexchange.com/a/149831/67312).
```
Suppose we have input [12,12,-4,20]
# (implicit input), stack: [12,12,-4,20]
S # sort the list, stack: [-4, 12, 12, 20]
5L # push [1 0], stack: [[-4, 12, 12, 20]; [1 0]]
) # 1-based modular index, stack: [-4, 20]
d # successive differences, stack: [24]
: # generate 1:(max(data)-min(data)), stack: [[1...24]]
Q # increment to start at 2, stack: [[2...25]]
" # for each element in [2...25]
G # push input, stack: [[12,12,-4,20]]
@ # push loop index, stack: [[12,12,-4,20], 2]
\ # compute modulo, stack: [[0,0,0,0]]
8# # use alternate output spec, unique has 4 outputs, so 8 keeps only the 4th
u # unique. 4th output is the counts of each unique value, stack: [4]
Zs # compute standard deviation, stack: [0]
~ # logical negate, stack: [T]
? # if true,
@ # push loop index
# (implicit end of if)
# (implicit end of for loop)
# (implicit output of stack as column vector
```
[Answer]
# JavaScript (ES6), 117 bytes
Outputs a space-separated list of values.
```
a=>(g=m=>a.map(n=>x[k=(z|=m/2<n|m/2<-n,n%m+m)%m]=-~x[k],y=z=0,x=[])|z?(x.some(x=>x-(y?y:y=x))?'':m+' ')+g(m+1):'')(2)
```
### Test cases
```
let f =
a=>(g=m=>a.map(n=>x[k=(z|=m/2<n|m/2<-n,n%m+m)%m]=-~x[k],y=z=0,x=[])|z?(x.some(x=>x-(y?y:y=x))?'':m+' ')+g(m+1):'')(2)
console.log(f([1,1,2])) // []
console.log(f([1,1,5])) // [2,4]
console.log(f([1,1,24])) // [23]
console.log(f([1,2,3,2])) // [2]
console.log(f([12,12,-4,20])) // [2,3,4,6,8,12,24]
console.log(f([1,1,12,12,-3,7])) // [3,10]
console.log(f([-1,2,2,1,2,7,1,4])) // [2,3]
console.log(f([4,-17,-14,-18,-18,3,5,8])) // []
console.log(f([-18,0,-6,20,-13,-13,-19,13])) // [2,4,19]
console.log(f([-11,-19,-19,3,10,-17,13,7,-5,16,-20,20])) // []
console.log(f([3,0,1,5,3,-6,-16,-20,10,-6,-11,11])) // [2,4]
console.log(f([-18,-20,14,13,12,-3,14,6,7,-19,17,19])) // [2,3]
console.log(f([-16,-9,6,13,0,-17,-5,1,-12,-4,-16,-4])) // [3,9]
console.log(f([-97,-144,3,53,73,23,37,81,-104,41,-125,70,0,111,-88,-2,25,-112,54,-76,136,-39,-138,22,56,-137,-40,41,-141,-126])) // [2,3,6]
```
[Answer]
## Clojure, 91 bytes
```
#(for[i(range 2(apply +(map * % %))):when(apply =(vals(frequencies(for[j %](mod j i)))))]i)
```
Using `frequencies` isn't ideal in code golf.
[Answer]
# J, 38 bytes
```
[:}.@I.([:i.1#.|)(1=1#.[:~:|#/.])"0 1]
```
Credit goes to Mr. Xcoder for the sum of absolute values trick.
Edit in a TIO link if you want -- I've golfed this in a bit of a hurry.
Explanation and TIO link coming soon(ish).
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~43~~ ~~41~~ ~~38~~ 30 bytes
The ⍨s in the code tells the whole story.
*8 bytes saved thanks to @Adám*
```
∊x⊆⍨1=⊂(≢∘∪1⊥|∘.=|)¨⍨x←1+∘⍳1⊥|
```
[Try it online!](https://tio.run/##LY09CsJAEIV7TzGlIsrO/qfIYQKiTUDLCKksJC4ELK0FIdik8AY5ylwkzixhlrffznu8rS717nCt6vNpno90f1KXGkp36gcsKd3W9HhT96Lui5Q@LeO@bDfTwH7DadyK2f@yyQWAPHq13JZhGhl4RAOr7FDLmUYLWuVIESRnLRhwBoIBbcAEiChrZcFm0A6CAgWI8oyRhZudWFznLEPwgMYzmELWJoJmx2eWP6xaupZG/wc "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
Lets take a set of integers greater than 1 and call it **X**. We will define **S(i)** to be the set of all members of **X** divisible by **i** where **i > 1**. Would like to choose from these subsets a group of sets such that
* Their union is the set **X**
* No element of **X** is in two of the sets.
For example we can regroup `{3..11}` as
```
{3,4,5,6,7,8,9,10,11}
S(3): {3, 6, 9, }
S(4): { 4, 8, }
S(5): { 5, 10, }
S(7): { 7, }
S(11):{ 11}
```
Some sets cannot be expressed in this way. For example if we take `{3..12}`, `12` is a multiple of both 3 and 4 preventing our sets from being mutually exclusive.
Some sets can be expressed in multiple ways, for example `{4..8}` can be represented as
```
{4,5,6,7,8}
S(4): {4, 8}
S(5): { 5, }
S(6): { 6, }
S(7): { 7, }
```
but it can also be represented as
```
{4,5,6,7,8}
S(2): {4, 6, 8}
S(5): { 5, }
S(7): { 7, }
```
## Task
Our goal is to write a program that will take a set as input and output the smallest number of subsets that cover it in this fashion. If there are none you should output some value other than a positive integer (for example `0`).
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with less bytes being better.
## Tests
```
{3..11} -> 5
{4..8} -> 3
{22,24,26,30} -> 1
{5} -> 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 167 bytes
```
lambda a:([q for q in range(a[-1])if a in[sorted(sum(j,[]))for j in combinations([[p for p in a if p%i<1]for i in range(2,1+a[-1])],q)]]+[0])[0]
from itertools import*
```
[Try it online!](https://tio.run/##RY05DsIwEEV7TjENkg2DFIcdwUmMC4fEMFG8xHYKTh8SKCh@85f3wzu/vCtHc7uPnbZVrUFfmOzB@Ag9kIOo3bNhWm6E4mRAT55MPuamZmmwrEWpOJ/b7dx@eFuR05m8S0zK8OWEOZmGBsKSrkLNHv3ZJYr1j6@w50qtZaH4pIWJ3gLlJmbvuwRkw/S7GkMkl8EwcmHIjPNRbnGHezzgEU94RlGgEOoD "Python 2 – Try It Online\"ry It Online")
-9 bytes thanks to Zacharý
-4 bytes thanks to Mr. Xcoder
-2 bytes by using lists instead of sets
-5 bytes by using `a in [...]` rather than `any([a == ...])`.
-2 bytes thanks to Mr. Xcoder
-8 bytes by merging statements
-5 bytes thanks to Mr. Xcoder
-7 bytes thanks to Mr. Xcoder / Zacharý
+7 bytes to fix bug
-1 byte thanks to ovs
### note
This is extremely slow for larger maximum numbers because it is in no way optimized; it did not within 2 minutes on Mr. Xcoder's device for `[22, 24, 26, 30]`.
[Answer]
# [Clingo](https://potassco.org/), 51 bytes
```
{s(2..X)}:-x(X).:-x(X),{s(I):X\I=0}!=1.:~s(I).[1,I]
```
### Demo
```
$ echo 'x(3..11).' | clingo cover.lp -
clingo version 5.1.0
Reading from cover.lp ...
Solving...
Answer: 1
x(3) x(4) x(5) x(6) x(7) x(8) x(9) x(10) x(11) s(3) s(4) s(5) s(7) s(11)
Optimization: 5
OPTIMUM FOUND
Models : 1
Optimum : yes
Optimization : 5
Calls : 1
Time : 0.003s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.010s
$ echo 'x(4..8).' | clingo cover.lp -
clingo version 5.1.0
Reading from cover.lp ...
Solving...
Answer: 1
x(4) x(5) x(6) x(7) x(8) s(3) s(4) s(5) s(7)
Optimization: 4
Answer: 2
x(4) x(5) x(6) x(7) x(8) s(2) s(5) s(7)
Optimization: 3
OPTIMUM FOUND
Models : 2
Optimum : yes
Optimization : 3
Calls : 1
Time : 0.001s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.000s
$ echo 'x(22;24;26;30).' | clingo cover.lp -
clingo version 5.1.0
Reading from cover.lp ...
Solving...
Answer: 1
x(22) x(24) x(26) x(30) s(5) s(8) s(22) s(26)
Optimization: 4
Answer: 2
x(22) x(24) x(26) x(30) s(3) s(22) s(26)
Optimization: 3
Answer: 3
x(22) x(24) x(26) x(30) s(2)
Optimization: 1
OPTIMUM FOUND
Models : 3
Optimum : yes
Optimization : 1
Calls : 1
Time : 0.004s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.000s
$ echo 'x(5).' | clingo cover.lp -
clingo version 5.1.0
Reading from cover.lp ...
Solving...
Answer: 1
x(5) s(5)
Optimization: 1
OPTIMUM FOUND
Models : 1
Optimum : yes
Optimization : 1
Calls : 1
Time : 0.001s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.000s
```
[Answer]
# Mathematica, 105 bytes
```
Length@Select[Subsets@Table[Select[s,Mod[#,i]==0&],{i,2,Max[s=#]}],Sort@Flatten@#==Sort@s&][[1]]~Check~0&
```
***[Try it online](https://sandbox.open.wolframcloud.com/app/objects/)***
copy and paste the code with ctrl+v,
paste the input at the end of the code,
hit shift+enter to run
**input**
>
> [{3,4,5,6,7,8,9,10,11}]
>
>
>
takes a list as input
outputs 0 if there are none
[Answer]
## Haskell, 136 bytes
```
import Data.List
f l|m<-maximum l=(sort[n|(n,c)<-[(length s,[i|j<-s,i<-[j,2*j..m],elem i l])|s<-subsequences[2..m]],c\\l==l\\c]++[0])!!0
```
[Try it online!](https://tio.run/##bcqxDoIwFIXhnae4JA4gpUHUxIFujr5B26FikeJtQVoSB94dcdQ4nu/8rfIPjbgsxg79GOCsgqIX40PUAM62yq16GTtZQJb4NeBuThyp0yrnCWp3Dy14ws3cVbknZtWOlNuOUiuJRm3BAMp09us7Xb1@TtrV2vPyE0hSC4GMoRC1zDJeyDSOi8Uq44DBrY8AhtG4ABtogB/l9z5QevqhPaW73R8r5fIG "Haskell – Try It Online")
How it works
```
f l = -- input set is l
|m<-maximum l -- bind m to maximum of l
[ |s<-subsequences[2..m]] -- for all subsequences s of [2..m]
(length s, ) -- make a pair where the first element is the length of s
[i|j<-s,i<-[j,2*j..m],elem i l]
-- and the second element all multiples of the numbers of s that are also in l
[n|(n,c)<- ,c\\l==l\\c] -- for all such pairs (n,c), keep the n when c has the same elements as l, i.e. each element exactly once
sort[ ]++[0] -- sort those n and append a 0 (if there's no match, the list of n is empty)
( )!!0 -- pick the first element
```
Take a lot of time for `{22,24,26,30}`.
[Answer]
# Jelly, ~~38~~ ~~35~~ ~~34~~ ~~33~~ ~~31~~ ~~28~~ ~~25~~ ~~24~~ ~~23~~ ~~20~~ 19 bytes
```
ṀḊŒPð%þ@⁹¬Sḟ1ðÐḟL€Ḣ
```
-5 bytes thanks to Leaky Nun
[Try it online!](https://tio.run/##AUYAuf9qZWxsef//4bmA4biKxZJQw7Alw75A4oG5wqxT4bifMcOww5DhuJ9M4oKs4bii////WzMsNCw1LDYsNyw4LDksMTAsMTFd)
I **think** the third test case works, but it is very slow. `0` is outputted when there are no solutions.
Explanation (might have gotten this explanation wrong):
```
ṀḊŒPð%þ@⁹¬Sḟ1ðÐḟL€Ḣ (input z)
ṀḊ - 2 .. max(z)
ŒP - powerset
ð - new dyadic chain
%þ@⁹ - modulo table of z and that
¬ - logical not
S - sum
ḟ1 - filter out 1's
ðÐḟ - filter out elements that satisfy that condition
L€ - length of each element
Ḣ - first element
```
[Answer]
# Julia, 91 bytes
```
x->(t=[];for i in x z=findfirst(x->x==0,i%(2:maximum(x)));z∈t?1:push!(t,z) end;length(t))
```
] |
[Question]
[
Given an unordered collection of positive integers by any reasonable input method, return all of the sub-collections that have an odd number of odd elements (i.e. have an odd total).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so you should aim to minimize the byte count of your program.
Since some languages only have ordered collections (lists, arrays, vectors, etc.) or don't have an unordered collection that allows duplicates, you may use ordered collections (regardless of your language choice), however you should not output any duplicate collections with different orders (e.g. `[2,3]` and `[3,2]`). You may output in whatever order you see fit.
## Test cases
```
[2,3,7,2] -> [[3],[7],[2,3],[2,7],[2,2,3],[2,2,7]]
[2,4,6,8] -> []
[4,9] -> [[9],[4,9]]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
{æÙʒOÉ
```
[Try it online!](https://tio.run/nexus/05ab1e#@199eNnhmacm@R/u/P8/2khHwVhHwVxHwSgWAA "05AB1E – TIO Nexus")
```
{æÙʒOÉ
{ Sort
æ Powerset
Ù Uniqufy
ʒ Keep elements where
O the sum
É is uneven
```
-2 bytes thanks to @EriktheOutgolfer
[Answer]
# [Python 3](https://docs.python.org/3/), 93 bytes
```
f=lambda x,r=[[]]:x and f(x[1:],r+[y+x[:1]for y in r])or{(*sorted(y),)for y in r if sum(y)&1}
```
Returns a set of tuples. Most likely way too long.
[Try it online!](https://tio.run/nexus/python3#VcnNCgIhFAbQfU/xrUKbu3GKfoR5EnFhmCA0GncmUKJnN3fV9pwWprubr96hEE/GWKsLXPIIohilLfFg6lCMVjZkRkVMYCszv8RuybzevKiS5PcQA5bn3HWr3u3BMa0iCDMS9oQTYbRSbn75QDgSzn/c7dKhfQA "Python 3 – TIO Nexus")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~10~~ ~~9~~ 8 bytes
```
{f%sT2yS
```
[Try it online!](https://tio.run/nexus/pyth#@1@dplocYlQZ/P9/tJGOgrGOgrmOglEsAA "Pyth – TIO Nexus")
```
# implicit input
S # sort input, this way the subsets will already be sorted
y # all subsets
f # filter elements when ..
sT # the sum ..
% 2 # is odd
{ # remove all duplicated elements
# implicit output
```
[Answer]
# [Python 2](https://docs.python.org/2/), 91 bytes
```
r=[[]]
for n in input():r+=map([n].__add__,r)
print{tuple(sorted(y))for y in r if sum(y)&1}
```
Prints a set of tuples. If a set of strings is allowed, `tuple(sorted(y))` can be replaced with ``sorted(y)`` for **86 bytes**.
[Try it online!](https://tio.run/nexus/python2#FctBCoAgEEDRfaeYVShJkC2CwJOIiKCCUCaTLiQ6uyX81YfXUEip1OAvhAihl0omdMdJnCYRGdWstbFWa4Z0SBhifnJJhyP3hdlZUintuHaMEDzc5fznuLytSc5gZbAx4OoD "Python 2 – TIO Nexus")
[Answer]
# [Perl 6](http://perl6.org/), 50 bytes
```
{.combinations.grep(*.sum!%%2).unique(:as(*.Bag))}
```
To filter out the same-up-to-ordering combinations I filter out duplicates by converting each to a `Bag` (unordered collection) before comparing. Unfortunately I couldn't find a way to accept a `Bag` as input that was as concise.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
o⊇ᵘ{+ḃt1&}ˢ
```
[Try it online!](https://tio.run/nexus/brachylog2#@5//qKv94dYZ1doPdzSXGKrVnl70/3@0kY6xjrmOUez/KAA "Brachylog – TIO Nexus")
I hoped to find a shorter solution, but here's the best I could do.
### Explanation
```
o⊇ᵘ{+ḃt1&}ˢ
o the input, sorted
⊇ᵘ Find all unique subsets of
{ &}ˢ Then select only those results where
+ the sum
ḃ the base 2 of
t The last digit of
1 is 1.
```
Yeah, I could've used modulo 2 to check for oddness, but that's not an odd approach ;)
[Answer]
# Mathematica ~~31 44~~ 38 bytes
Among all subsets of the input set, it returns those for which the sum, `Tr`, is odd.
6 bytes saved thanks to alephalpha.
```
Select[Union@Subsets@Sort@#,OddQ@*Tr]&
```
---
```
Select[Union@Subsets@Sort@#,OddQ@*Tr]&[{2,3,7,2}]
```
{{3}, {7}, {2, 3}, {2, 7}, {2, 2, 3}, {2, 2, 7}}
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ṢŒPSḂ$ƇQ
```
[Try it online!](https://tio.run/##y0rNyan8///hzkVHJwUEP9zRpHKsPfD////RRjrGOuY6RrEA "Jelly – Try It Online")
Bug-fix thanks to Jonathan Allan.
-1 byte by using the alias for filter thanks to Riolku.
[Answer]
# PHP, 126 bytes
```
for(;++$i>>$argc<1;sort($t),$s&1?$r[join(_,$t)]=$t:0)for ($t=[],$j=$s=0;++$j<$argc;)$i>>$j&1?$s+=$t[]=$argv[$j]:0;print_r($r);
```
takes input from command line arguments; run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/c77762140e438f362172c46b1a5cf828c2406d18).
**breakdown**
```
for(;++$i>>$argc<1; # loop through subsets
sort($t), # 2. sort subset
$s&1?$r[join(_,$t)]=$t:0 # 3. if sum is odd, add subset to results
) # 1. create subset:
for ($t=[],$j=$s=0;++$j<$argc;) # loop through elements
$i>>$j&1? # if bit $j is set in $i
$s+=$t[]=$argv[$j]:0; # then add element to subset
print_r($r); # print results
```
] |
[Question]
[
# The Task
In this challenge, your task is to write some code which outputs one of its anagrams chosen randomly with uniform distribution but it should never output itself.
---
## Elaboration
Given no input, your program should output any one of the anagrams of its source code. Your program should never output its own source as it is, i.e. it should never be a quine.
---
## Input
Your program must not take any input. However, if your language requires input as a necessity, you may assume that it will be given lowercase `a`. You must not use the input in any way, though.
---
## Output
Your program can output in any way except writing it to a variable. Writing to file, console, screen, etc. is allowed. Function `return` is allowed as well.
---
## Additional Rules
* Your program's source code must have at least 3 **chars** (not 3 bytes).
* Your program's source code must have at least 3 possible anagrams (excluding itself). For example, `aab` does not count as a valid submission as `aab` only has two anagrams other than `aab` (`baa` and `aba`).
* Your program must not produce any error.
* Your program should output its anagrams *exactly*.
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) and [Standard quine rules](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) apply.
---
## Example
Suppose your program's source code is `abc`. It should randomly output any one of the following (with uniform distribution):
1. `acb`
2. `bca`
3. `bac`
4. `cba`
5. `cab`
And, it should never output `abc`.
---
## Winning Criterion
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! In case of a tie, the solution which was posted earlier wins!
[Answer]
## Python 2, 117 bytes
Surprisingly this solution is shorter than I expected. Shuffles source code, until it differs from the original.
-2 bytes, thanks to @mbomb007
-3 bytes, thanks to @Wondercricket
[Try it online](https://tio.run/nexus/python2#LYw9DgIhEEb7PQWhGXDVA0jmBlTUNgTHLIa/DJusF7dGEq3el7x8b3RkKeWTaxbsy2Mi5lZ5PxmHMOV9Wlj7Cr8Bht4URAdj0S3HFhMJi@huFgGurxqL6j63RMqdExXltNZL41h2YWfg/x7jU@ol@LDRFw)
```
s=r"""from random import*;R='s=r\"""'+s+'\"""'+';exec s';L=R
while L==R:L=''.join(sample(R,len(R)))
print L""";exec s
```
This is one of the basic quines in python, that I've modified
```
s = r"print 's = r\"' + s + '\"' + '\nexec(s)'"
exec(s)
```
Generating anagram is done by random module
```
L=R
while L==R:L=''.join(sample(L,len(L)))
```
Where R contains sourcecode
```
s=...
R='s=r\"""'+s+'\"""'+'\nexec s'
```
Triple quotes were needed as I was forced to keep actual lineseparators in code. Anagrams will have 3 lines anyway.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
“v0¡µṾ;ḢŒ!QḊX”v
```
Just to get things started; this is almost certainly beatable. This is basically just a combination of a universal quine constructor and a "pick a random permutation other than the input" function; the latter may be improvable, the former almost certainly is.
## Explanation
**Universal quine constructor**
```
“v0¡µṾ;Ḣ”v
“ ”v Evaluate the following, given {itself} as argument:
v0¡µ No-op (which starts with "v")
Ṿ Escape string
;Ḣ Append first character of {the argument}
```
This can be seen to be a quine if run by itself. It's also a proper quine by most definitions I know of; it doesn't read its own source (rather, it contains a literal that's "eval"ed, and is given a copy of itself as an argument), it can carry a payload (as seen here!), and the `v` outside the string literal is encoded by the `v` inside.
**Pick a random anagram**
```
Œ!QḊX
Œ! All permutations
Q Discard duplicates
Ḋ Discard the first (i.e. the string itself)
X Choose random element
```
This is really inefficient on a string this long, so I haven't been able to test the program as a whole, but I've tested it on shorter strings and it appears to function correctly.
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 17 bytes
```
{`"_~"+m!(a-mR}_~
```
This isn't going to finish any time soon, so no TIO link this time.
As a consolation, here is a 20 byte solution that does terminate very quickly:
```
{`"_~"+:S{mr_S=}h}_~
```
[Try it online!](https://tio.run/nexus/cjam#@1@doBRfp6RtFVydWxQfbFubURtf9/8/AA "CJam – TIO Nexus")
### Explanation
```
{`"_~"+ e# Standard quine framework, leaves a string equal to the source
e# code on the stack.
m! e# Get all permutations. The first one will always be the original order.
(a e# Remove that copy of the source code and wrap it in a new list.
- e# Remove all copies of the source code from the list of permutations.
mR e# Pick a random permutation.
}_~
```
The 20 byte solution instead shuffles the source code until its different from the original.
[Answer]
# Java 7, ~~376~~ ~~428~~ ~~426~~ 428 bytes
```
import java.util.*;class M{public static void main(String[]a){String s="import java.util.*;class M{public static void main(String[]a){String s=%c%s%1$c,x=s=s.format(s,34,s);for(List l=Arrays.asList(x.split(%1$c%1$c));x.equals(s);s=s.join(%1$c%1$c,l))Collections.shuffle(l);System.out.print(s);}}",x=s=s.format(s,34,s);for(List l=Arrays.asList(x.split(""));x.equals(s);s=s.join("",l))Collections.shuffle(l);System.out.print(s);}}
```
+52 and +2 bytes for two bug-fixes.. I wasn't checking (correctly) if the randomly generating String was equal to the original source-code. The chances of this are astronomical small considering the amount of characters involved, but I have to validate it regardless to comply to the challenge rules.
My first [quine](/questions/tagged/quine "show questions tagged 'quine'") answer in Java..
[Try it here.](https://tio.run/nexus/java-openjdk#rY4xSwQxEIX/SgguJLI3INotW4itV10pFmPMejlmN2tmcuxx3M@2XhPE0kKxGGYew3vvW8M4xyTqgEeELIHgunOEzGp7nvMLBadYUMo6xvCqRgyT2UkK09vTM9rz16m41/@U07iGm5sr1y499wxDTCOK4fb2rmXbFWkeA4ui/j4lPDEgV20W4JmCmGqtY223gH/PSGyKr0YdYqn8/rdk7UMk8k5CnBh4n4eBvCHb7U4sfoSYBeYCJdV/ueg/Amn9E4rWv4ZY148pbhy6vf8E)
You can remove both `Collections.shuffle(l)` and add `!` in front of both the `x.equals(s)` to verify that the output indeed equals the program:
[Try it here.](https://tio.run/nexus/java-openjdk#rY0xC8IwEIX/SgwWEikB0a10cNepozicsUokbWruWlpKf3tNEEcdxOF49@C9982mapwndocOVEvGqlWmLSCyw9i0Z2s0QwIK0jlzYRWYWhTkTX07nkCOr5dhzv@0k@gEk/VSp32OOaqr8xWQwHSzTVFmwYq9QWI233kPAyrA6EWvsLGGRKzGkzJb9Kp8tGBRhGLcurvAfAdSGyLFgFRWyrWkmsCnmJwm/iOb849Uzr/w5vkJ)
**Explanation:**
* The `String s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together
And this part of the code is responsible for outputting a random anagram:
```
// Strings `s` and `x` now both contain the source-code:
x=s=s.format(s,34,s);
// Create a list with the characters of this source-code-String and loop
for(List l=Arrays.asList(x.split(""));
// as long as String `x` equals String `s`
x.equals(s);
// Shuffle the list, and set it to `s` in every iteration of the loop:
s=s.join("",l))Collections.shuffle(l);
// End of loop (implicit / single-line body)
// And then print the random anagram to STDOUT:
System.out.print(x);
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `D`, 14 bytes
```
`q‛:Ė+:Ṗ$o℅`:Ė
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJEIiwiIiwiYHHigJs6xJYrOuG5liRv4oSFYDrEliIsIiIsIiJd)
For a version that doesn't require ~1.2TB of RAM:
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `D`, 16 bytes
```
`q‛:Ė+D{|Þ℅~=`:Ė
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJEIiwiIiwiYHHigJs6xJYrRHt8w57ihIV+PWA6xJYiLCIiLCIiXQ==)
Both of these use a fairly generic quine structure combined with some "generate some permutation other than the input" code.
### Generic quine structure
```
` `:Ė # Evaluate the previous code on itself
q. # Uneval
+ # Append
‛:Ė # ":Ė"
... # Apply some transformation
```
```
Ṗ # Get all permutations of the input
: $o # Remove the original string
℅ # Choose a random element
```
```
{ # While
D | ~= # The current string equals the input
Þ℅ # Shuffle it
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
"34çìDJœ¦.R"34çìDJœ¦.R
```
This creates a list that is too big for TIO, so the link uses a smaller string, but the idea is the same.
[Try it online!](https://tio.run/nexus/05ab1e#@6@UmJSsZGxyePnhNS5eRycfWqYX9P//17x83eTE5IxUAA "05AB1E – TIO Nexus")
```
"34çìDJœ¦.R" # Push this string
34ç # Push "
ì # Prepend
DJ # Duplicate and join
œ¦ # Push all permutations except the original
.R # Pick a random element
```
[Answer]
# Javascript (ES6), 128 bytes
```
!function a(){b="!"+a+"()",c=b.split(""),c.sort(()=>Math.round(Math.random())-.5),c!=b.split("")?console.log(c.join("")):a()}();
```
Uses sort() returning random -1,0, or 1 to shuffle the output.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 72 bytes
```
&($f={for(;$r-eq$o){$r=-join(($o="&(`$f={$f})")|% t*y|Random -c 72)}$r})
```
[Try it online!](https://tio.run/##FcpBDkAwEADArzTNanYlvbg4SD/hBYQ2CJYlEaFvr5jzbHx5OQY/z7Zj8SkZhOCewIIViPU7MD0gzk48rojAThts/gIhkqY3U2d@v3W79rwo26myoAgSKaUP "PowerShell Core – Try It Online")
This is a variation of the quine `&($f={"&(`$f={$f})"})`
```
&($f={for(;$r-eq$o){$r=-join(($o="&(`$f={$f})")|% t*y|Random -c 72)}$r})
($o="&(`$f={$f})") # Stores the original quine in $o
$r=-join( |% t*y|Random -c 72) # Shuffles the characters and store it in $r
for(;$r-eq$o){ }$r # Exit the while loop and print when the shuffled quine is not the same as the origin quine
&($f={ }) # Quine structure, to create a function and run it automatically
```
[A 74 bytes recursive approach](https://tio.run/##FcrRCkAwFADQX1m61r2yR3naT3iVotlCuIyS2LdPzvPZ@LL@GOw8K8PexigRnH4kPuBDDo5qYGV3BK/VxOOKCKwTie2/wAVK6E3Fmd1v1a09L0IZURZETaAYPw "PowerShell Core – Try It Online")
[Answer]
# Bash, ~~27~~ 96 bytes
```
i=`cat $0`&&e=`fold -w1 $0|shuf|tr -d '\n'`&&while [ "$e" = "$i" ]; do `$0`; exit; done&&echo $e
```
`fold` divides the code in lines, `shuf` shuffles the lines, and `tr` put the code back together
fixed the issue of it outputing itself, now it will never output itself
[Try it Online!](https://tio.run/##FYxBCoAgFAWv8hDJVVDr8CQVaPlDIRTKsIV3t99qeMNjNnv71oI2u82Qg@k60uZIp0NfRhb19s9R84XeQS1R8aH4cBJmCEkCmhEE1gkuwXBgAr0h/zMSx3afIKm1Dw)
] |
[Question]
[
You are to create a program that creates exact clones of itself infinitely until stopped. Whatever is in the original program must be in the clones. In other words, the clones and original program are the same in every way except for that the clones don't have to be in the same type of file as the source code (they can be text files).
**Example:**
If my original program is:
```
for i in range(0, 10):
print i
```
the clone must also be:
```
for i in range(0, 10):
print i
```
**Rules and Clarifications:**
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/5337#5337) are forbidden
* The clones must be the exact copy of the original
* The clones must be readable files that can be run if put inside the correct interpreter
* The program can read its own source code
* All clones must be separate files
* Printing your program out is not allowed
* File names count into the number of bytes
* The clones don't have to be in the same directory as the source file nor share the same file name
* At least 1000 clones should be able to be created
**Winning:**
Least bytes wins!
[Answer]
# [Zsh](https://www.zsh.org/), ~~19~~ ~~17~~ 9 bytes
```
#!/bin/zsh
<$0>$$;$0
```
Per [consensus on meta](http://meta.codegolf.stackexchange.com/a/5637/12012), the shebang is excluded from the byte count.
[Try it online!](https://tio.run/nexus/zsh#S03OyFdQV1bUT8rM068qzvhvo2Jgp6JirWLwX12hRiEjNTFFQTdZQddIQcFOITknPy@VKzkjNz9FQbsCytXTh9Bp@UUKaQqZeQpa1gop@VycBUWZeSVpCkpunj6ufo6@rlYxearFMXm6IBCT5@zvF@LqFxKMKqqkoKSSBiI0bFTSNJW4UoAG/wcA "Zsh – TIO Nexus")
Note that TIO's forkbomb protection will kill the process after 113 files have been generated. It can easily generate 1000 files on a system without such conservative resource limits.
[Answer]
## Batch, 32 bytes
```
set/an=%1+1
copy %0 %n%
%0 %n%
```
Not using `@` because there's no restriction on STDOUT. `%1` defaults to the empty string, so `n` becomes `1` the first time and increments on every pass. Alternatively, this might work for 28 bytes, but I have no idea how random `%random%` actually is when used like this:
```
copy %0 %random%%random%
%0
```
[Answer]
# Bash, ~~25~~, ~~16~~, ~~12~~, 11 bytes
EDITS:
* Removed the newline (-1 byte), Added "Try It Online". Thanks @Dennis !
* Use background job PID `$!` as the filename (will be reused every ~32k files, but that is now allowed), -4 bytes
**Golfed**
```
#!/bin/bash
$0&cp $0 $!
```
**Explained**
Re-spawns itself as a background job with &, before doing a copy, so each iteration will run under its own PID.
Uses the last job PID as the filename.
This can run infinitely (or until stopped) but will be reusing clone filenames approx. every ~32k iterations.
Could be a bit nasty to kill, but AFAIK is not against the rules.
[Try It Online!](https://tio.run/nexus/bash#VY5BS8NAEIXP7q943W5tq6QpelMRRCIIGg/2mEuyO@kG42zY3agH/3tMaBWcw8A83nx8pK3Dcj5Lq4bTqgx2UNtT3UFtoWbDEt@wVBokGskFbqFbxySEtu/O4PzreG/SYx5aog6XmCNo33QR2nFsuKeA6OB7RsOIllCV@m3vXc9GiM43HGvIRTjgAmz5MVaIGHti8mUksyk4maZgCbVqwyj2OTq1ayFq51FP4LNrGCdOfnkPj09ZfvecXRW8CH/v9y/5Lst3r/9TCanqaa1uVL2Wwoweww8)
[Answer]
## Ruby, ~~78 bytes~~, ~~77~~ 43 + 4 (filename: a.rb) = 47 bytes
* Version 1.2
43 bytes + name / Thanks to @Alexis
So much shorter!!!
```
loop{File.write "#{$.+=1}",open("a.rb",?r)}
```
that's about as golfed as I think it's going to get
* Version 1.1
73 bytes + name / Thanks to @Alexis Anderson
```
i=0
loop do
File.open("#{i}",?w){|b|b.puts File.read("a.rb",?r)}
i+=1
end
```
* Version 1.0
74 bytes + name
```
i=0
loop do
File.open("#{i}","w") do{|b|b.puts File.read("a.rb")}
i+=1
end
```
This is my first Ruby answer so all inprovements are welcome.
[Answer]
# sh, 24 bytes
```
yes cp $0 '`uuid`'|sh -s
```
[Answer]
# C#, ~~104~~ 102 bytes
-2 bytes thanks to berkeleybross
```
namespace System.IO{class a{static void Main(){int i=0;while(1>0){i++;File.Copy("c{i}.cs");}}}}
```
No, it's not the shortest. But it's C#. What did you expect?
[Answer]
# Processing, 55 + 5 (name of file) = 60 bytes
I don't know if the filename counts as extra bytes
```
for(int i=0;;)saveStrings(i+++"",loadStrings("a.pde"));
```
Pretty much a series of builtins all chained together
### Explanation
```
for(int i=0;;) //A complex piece of code that cannot be explained in words alone
saveStrings( //Save param2 (String[]) into file param1 (String)
i+++"", // filename: the int i (and then is incremented)
loadStrings("a.pde") // content: load the content of file a.pde as a String[]
);
```
[Answer]
# ForceLang + [the ForceLang-JS module](https://github.com/SuperJedi224/ForceLang-JS), 162 bytes
```
set j require njs
j var a=function(){for(;;){var p=new java.io.PrintStream(Math.random()+".txt");p.println("set j require njs");p.print("j var a="+a+";a()")}};a()
```
[Answer]
## Python 2, 54 bytes
```
from shutil import*
a=__file__
while`copy(a,a*2)`:a*=2
```
[Answer]
# Mathematica, 41 bytes
```
For[a=0,1>0,$Input~CopyFile~ToString@a++]
```
Full program. Copies its own source file into `0`, `1`, `2`, etc. in the current directory.
[Answer]
***Python 2, 61 bytes (unix) 65 (cross-platform)***
**Unix** - *61 bytes*
```
import os;i=1
while os.popen('cp %s %i.py'%(__file__,i)):i+=1
```
On unix cp is the systems copy-file - command. Using the console via **popen** allows me to copy the file by cp. new files will spawn in old-files directory.
**CrossPlatform** - *65 bytes*
```
i=0
while 1:i+=1;open('%i.py'%i,'w').write(open(__file__).read())
```
This works, as **open** on default allows reading.
**Funfact:** replace `1:i+=1` with `i:i-=1` and it will stop at i copies.
Other than that, I see no way of making it shorter than @muddyfish did it.
[Answer]
# PHP, ~~91~~ 60 bytes
Saved 31 bytes thanks to manatwork
```
<?for(;;)file_put_contents(++$i,file_get_contents("f.php"));
```
Usage: `$ php f.php` clones `f.php` and its code reproducing infinitely itself in filenames like `1`, `2`, `3`... until timeout.
**Previous version:**
```
<?for($i=0;;$i++)$p=fwrite(fopen("$i.php","w"),fread(fopen($f="f.php","r"),filesize($f)));
```
Usage: `$ php f.php` clones `f.php` and its code reproducing infinitely itself like `f1.php`, `f2.php`, `f3.php` ... `f(n).php` until timeout.
[Answer]
## awk, 29 (21) bytes,
```
{while(close(i++)||1)print>i}
```
awk is not really the tool for this as it requires `close()` when running indefinitely. Otherwise all it produces are empty files.
If the clone count had a limit, for example 5:
```
{while(++i<5)print>i}
```
the program would be 21 bytes.
Paste the program to a file `a` and run:
```
$ awk -f a a
```
[Answer]
# Python, 69 bytes
```
a=open(__file__).read()
i=0
while 1:i+=1;open(`i`+'.py','w').write(a)
```
I tried using `a` for the file name, but (unsurprisingly) Windows does not like files named `a=open(__file__).read()\ni=0\nwhile 1:i+=1;open(`i`+'.py','w').write(a)`. I also tried this:
```
a=open(__file__).read()
i=''
while 1:i+='.py';open(i,'w').write(a)
```
However it gives me this error:
```
Traceback (most recent call last):
File "C:/Python27/codeGolfCopy.py", line 3, in <module>
while 1:i+='.py';open(i,'w').write(a)
IOError: [Errno 2] No such file or directory: '.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py.py'
```
It creates 83 files, but that is not even close to the needed 1000.
If you would like to remove these files, you can use this:
```
import os;i = 1
while 1:os.remove(`i`+'.py');i+=1
```
] |
[Question]
[
For a fixed n, consider the n by n [Toeplitz matrices](https://en.wikipedia.org/wiki/Toeplitz_matrix) with entries which are either 0 or 1. The aim is to find maximum determinant over all such Toeplitz matrices.
**Task**
For each `n` from 1 upwards, output the maximum determinant over all n by n Toeplitz matrices with entries which are either 0 or 1. There should be one output per `n` which should have the maximum determinant and also an example matrix that reaches it.
**Score**
Your score is the largest `n` your code gets to in 2 minutes on my computer. To clarify a little, your code can run for 2 minutes in total, this is not 2 minutes per `n`.
**Tie breaker**
If two entries get the same `n` score then the winning entry will be the one that gets to the highest `n` in the shortest time on my machine. If the two best entries are equal on this criterion too then the winner will be the answer submitted first.
**Languages and libraries**
You can use any freely available language and libraries you like. I must be able to run your code so please include a full explanation for how to run/compile your code in linux if at all possible.
**My Machine** The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code.
**Small answers**
For n = 1..10 the outputs should be 1,1,2,3,5,9,32,56,125,315
This sequence is not in [OEIS](https://oeis.org/) and so the winning entry also gets to propose a new entry there.
**Entries so far**
* `n=10` `n=11` by Vioz in **Python**
* `n=9` by Tyilo in **C**
* `n=12` by Legendre in **J**
* `n=10` by Tensibai in **R**
* `n=14` by SteelRaven in **C++**
* `n=14` by RetoKoradi in **C++**
[Answer]
# J
**Update: Improved code to search over half the values. Now calculates `n=12` comfortably within 120 seconds (down from 217s to 60s).**
You will need the latest version of [J](http://www.jsoftware.com/ "J") installed.
```
#!/usr/bin/jconsole
dim =: -:@>:@#
take =: i.@dim
rotstack =: |."0 1~ take
toep =: (dim (|."1 @: {."1) rotstack)"1
det =: -/ . * @: toep
ps =: 3 : ',/(0 1 ,"0 1/ ,.y)'
canonical =: #. >: [: #. |. " 1
lss =: 3 : 0
shape =. (2^y), y
shape $ ,>{;/(y,2)$0 1
)
ls =: (canonical@:lss) # lss
ans =: >./ @: det @: ls @: <: @: +:
display =: 3 : 0
echo 'n = ';y;'the answer is';ans y
)
display"0 (1 + i.13)
exit''
```
---
Run this and kill when two minutes are up. My results (MBP 2014 - 16GB of RAM):
```
┌────┬─┬─────────────┬─┐
│n = │1│the answer is│1│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │2│the answer is│1│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │3│the answer is│2│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │4│the answer is│3│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │5│the answer is│5│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬─┐
│n = │6│the answer is│9│
└────┴─┴─────────────┴─┘
┌────┬─┬─────────────┬──┐
│n = │7│the answer is│32│
└────┴─┴─────────────┴──┘
┌────┬─┬─────────────┬──┐
│n = │8│the answer is│56│
└────┴─┴─────────────┴──┘
┌────┬─┬─────────────┬───┐
│n = │9│the answer is│125│
└────┴─┴─────────────┴───┘
┌────┬──┬─────────────┬───┐
│n = │10│the answer is│315│
└────┴──┴─────────────┴───┘
┌────┬──┬─────────────┬────┐
│n = │11│the answer is│1458│
└────┴──┴─────────────┴────┘
┌────┬──┬─────────────┬────┐
│n = │12│the answer is│2673│
└────┴──┴─────────────┴────┘
```
Total run time = 61.83s.
---
Just for fun
```
┌────┬──┬─────────────┬────┐
│n = │13│the answer is│8118│
└────┴──┴─────────────┴────┘
```
This took approximately 210 seconds on its own.
[Answer]
# Python 2
This is a very straightforward solution, and probably won't win the contest. But hey, it works!
I'll give a quick overview of what exactly is happening.
1. I first generate every possible starting row for `n`. For example, when `n=2`, this will generate an array length 2n+1, where each row is length 2n-1. It would look like this: `[[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]`.
2. Then, for each of those possible starting rows, I rotate it `n` times and slice off the first `n` items to generate the appropriate matrix, and use `scipy` to calculate the determinant, all while keeping track of the maximum value. At the end of this, I simply print out the maximum, increment `n` by 1, and keep going until 10 minutes has passed.
To run this, you will need [scipy](http://www.scipy.org/scipylib/download.html) installed.
*Edit 1: Changed how initial rows were built by using itertools.product instead, thanks Sp3000!*
*Edit 2: Removed storage of possible starting rows for a minimal improvement in speed.*
*Edit 3: Changed to `scipy` to have more control over how `det` worked.*
```
from scipy import linalg
from collections import deque
from time import time
from itertools import product
c=1
t=time()
while 1:
m=0
for d in product(range(2),repeat=2*c-1):
a=deque(d)
l=[d[0:c]]
for x in xrange(c-1):
a.rotate(1)
l+=[list(a)[0:c]]
m=max(m,linalg.det(l,overwrite_a=True,check_finite=False))
print m,'in',time()-t,'s'
c+=1
```
Here's some sample output on my home machine (i7-4510U, 8GB RAM):
```
1.0 in 0.0460000038147 s
1.0 in 0.0520000457764 s
2.0 in 0.0579998493195 s
3.0 in 0.0659999847412 s
5.0 in 0.0829999446869 s
9.0 in 0.134999990463 s
32.0 in 0.362999916077 s
56.0 in 1.28399991989 s
125.0 in 5.34999990463 s
315.0 in 27.6089999676 s
1458.0 in 117.513000011 s
```
[Answer]
# C++
Bruteforce with use of OpenMP for parallelization and simple optimization to avoid evaluation of determinant for transposed matrices.
```
$ lscpu
...
Model name: Intel(R) Core(TM) i5-2410M CPU @ 2.30GHz
...
$ g++ -O2 toepl.cpp -fopenmp
$ timeout 2m ./a.out
1 1
2 1
3 2
4 3
5 5
6 9
7 32
8 56
9 125
10 315
11 1458
12 2673
13 8118
14 22386
```
```
#include <cmath>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void updateReverses(vector < int > & reverses) {
int reversesCnt = reverses.size();
for(int i = 0; i < reversesCnt; ++i){
reverses[i] <<= 1;
reverses.push_back(reverses[i] | 1);
}
}
const double eps = 1e-9;
double determinant(vector < vector < double > > & matrix) {
int n = matrix.size();
double det = 1;
if(n == 1) return matrix[0][0];
for(int i = 0; i < n; ++i){
int p = i;
for(int j = i + 1; j < n; ++j)
if(fabs(matrix[j][i]) > fabs(matrix[p][i]))
p = j;
if(fabs(matrix[p][i]) < eps)
return 0;
matrix[i].swap(matrix[p]);
if(i != p) det *= -1;
det *= matrix[i][i];
matrix[i][i] = 1. / matrix[i][i];
for(int j = i + 1; j < n; ++j)
matrix[i][j] *= matrix[i][i];
for(int j = i + 1; j < n; ++j){
if(fabs(matrix[j][i]) < eps) continue;
for(int k = i + 1; k < n; ++k)
matrix[j][k] -= matrix[i][k] * matrix[j][i];
}
}
return det;
}
int main() {
vector < int > reverses(1, 0);
reverses.reserve(1 << 30);
updateReverses(reverses);
for(int n = 1;; ++n){
double res = 0;
int topMask = 1 << (2 * n - 1);
vector < vector < double > > matrix(n, vector < double > (n));
#pragma omp parallel for reduction(max:res) firstprivate(matrix) schedule(dynamic,1<<10)
for(int mask = 0; mask < topMask; ++mask){
if(mask < reverses[mask]) continue;
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
matrix[i][j] = (mask >> (i - j + n - 1)) & 1;
res = max(res, determinant(matrix));
}
cout << n << ' ' << res << endl;
updateReverses(reverses);
updateReverses(reverses);
}
}
```
[Answer]
# C++ with pthreads
This gets to n=14 in just under 1 minute on my machine. But since that's just a 2-core laptop, I hope that the 8-core test machine can finish n=15 in under 2 minutes. It takes about 4:20 minutes on my machine.
I was really hoping to come up with something more efficient. There has **got** to be a way to calculate the determinate of a binary matrix more efficiently. I wanted to come up with some kind of dynamic programming approach that counts the +1 and -1 terms in the determinant calculation. But it just hasn't quite come together so far.
Since the bounty is about to expire, I implemented the standard brute force approach:
* Loop over all possible Toeplitz matrices.
* Skip one of the two in each transposed matrix pair. Since the matrix is described by bitmask values, this is simple to do by skipping all values where the reverse of the bitmask is smaller than the bitmask itself.
* The determinate is calculated with a text book LR decomposition. Except for some minor performance tuning, the main improvement I made to the algorithm from my college numerical methods book is that I use a simpler pivot strategy.
* Parallelization is done with pthreads. Just using regular spacing for the values processed by each thread caused very bad load balancing, so I introduced some swizzling.
I tested this on Mac OS, but I used similar code on Ubuntu before, so I hope this will compile and run without a hitch:
1. Save the code in a file with a `.cpp` extension, e.g. `optim.cpp`.
2. Compile with `gcc -Ofast optim.cpp -lpthread -lstdc++`.
3. Run with `time ./a.out 14 8`. The first argument is the maximum `n`. 14 should finish in under 2 minutes for sure, but it would be great if you could try 15 as well. The second argument is the number of threads. Using the same value as the number of cores of the machine is normally a good start, but trying some variations could potentially improve the times.
Let me know if you have any problems building or running the code.
```
#include <stdint.h>
#include <pthread.h>
#include <cstdlib>
#include <iostream>
static int NMax = 14;
static int ThreadCount = 4;
static pthread_mutex_t ThreadMutex;
static pthread_cond_t ThreadCond;
static int BarrierCount = 0;
static float* MaxDetA;
static uint32_t* MaxDescrA;
static inline float absVal(float val)
{
return val < 0.0f ? -val : val;
}
static uint32_t reverse(int n, uint32_t descr)
{
uint32_t descrRev = 0;
for (int iBit = 0; iBit < 2 * n - 1; ++iBit)
{
descrRev <<= 1;
descrRev |= descr & 1;
descr >>= 1;
}
return descrRev;
}
static void buildMat(int n, float mat[], uint32_t descr)
{
int iDiag;
for (iDiag = 1 - n; iDiag < 0; ++iDiag)
{
float val = static_cast<float>(descr & 1);
descr >>= 1;
for (int iRow = 0; iRow < n + iDiag; ++iRow)
{
mat[iRow * (n + 1) - iDiag] = val;
}
}
for ( ; iDiag < n; ++iDiag)
{
float val = static_cast<float>(descr & 1);
descr >>= 1;
for (int iCol = 0; iCol < n - iDiag; ++iCol)
{
mat[iCol * (n + 1) + iDiag * n] = val;
}
}
}
static float determinant(int n, float mat[])
{
float det = 1.0f;
for (int k = 0; k < n - 1; ++k)
{
float maxVal = 0.0f;
int pk = 0;
for (int i = k; i < n; ++i)
{
float q = absVal(mat[i * n + k]);
if (q > maxVal)
{
maxVal = q;
pk = i;
}
}
if (pk != k)
{
det = -det;
for (int j = 0; j < n; ++j)
{
float t = mat[k * n + j];
mat[k * n + j] = mat[pk * n + j];
mat[pk * n + j] = t;
}
}
float s = mat[k * n + k];
det *= s;
s = 1.0f / s;
for (int i = k + 1; i < n; ++i)
{
mat[i * n + k] *= s;
for (int j = k + 1; j < n; ++j)
{
mat[i * n + j] -= mat[i * n + k] * mat[k * n + j];
}
}
}
det *= mat[n * n - 1];
return det;
}
static void threadBarrier()
{
pthread_mutex_lock(&ThreadMutex);
++BarrierCount;
if (BarrierCount <= ThreadCount)
{
pthread_cond_wait(&ThreadCond, &ThreadMutex);
}
else
{
pthread_cond_broadcast(&ThreadCond);
BarrierCount = 0;
}
pthread_mutex_unlock(&ThreadMutex);
}
static void* threadFunc(void* pData)
{
int* pThreadIdx = static_cast<int*>(pData);
int threadIdx = *pThreadIdx;
float* mat = new float[NMax * NMax];
for (int n = 1; n <= NMax; ++n)
{
uint32_t descrRange(1u << (2 * n - 1));
float maxDet = 0.0f;
uint32_t maxDescr = 0;
uint32_t descrInc = threadIdx;
for (uint32_t descrBase = 0;
descrBase + descrInc < descrRange;
descrBase += ThreadCount)
{
uint32_t descr = descrBase + descrInc;
descrInc = (descrInc + 1) % ThreadCount;
if (reverse(n, descr) > descr)
{
continue;
}
buildMat(n, mat, descr);
float det = determinant(n, mat);
if (det > maxDet)
{
maxDet = det;
maxDescr = descr;
}
}
MaxDetA[threadIdx] = maxDet;
MaxDescrA[threadIdx] = maxDescr;
threadBarrier();
// Let main thread output results.
threadBarrier();
}
delete[] mat;
return 0;
}
static void printMat(int n, float mat[])
{
for (int iRow = 0; iRow < n; ++iRow)
{
for (int iCol = 0; iCol < n; ++iCol)
{
std::cout << " " << mat[iRow * n + iCol];
}
std::cout << std::endl;
}
std::cout << std::endl;
}
int main(int argc, char* argv[])
{
if (argc > 1)
{
NMax = atoi(argv[1]);
if (NMax > 16)
{
NMax = 16;
}
}
if (argc > 2)
{
ThreadCount = atoi(argv[2]);
}
MaxDetA = new float[ThreadCount];
MaxDescrA = new uint32_t[ThreadCount];
pthread_mutex_init(&ThreadMutex, 0);
pthread_cond_init(&ThreadCond, 0);
int* threadIdxA = new int[ThreadCount];
pthread_t* threadA = new pthread_t[ThreadCount];
for (int iThread = 0; iThread < ThreadCount; ++iThread)
{
threadIdxA[iThread] = iThread;
pthread_create(threadA + iThread, 0, threadFunc, threadIdxA + iThread);
}
float* mat = new float[NMax * NMax];
for (int n = 1; n <= NMax; ++n)
{
threadBarrier();
float maxDet = 0.0f;
uint32_t maxDescr = 0;
for (int iThread = 0; iThread < ThreadCount; ++iThread)
{
if (MaxDetA[iThread] > maxDet)
{
maxDet = MaxDetA[iThread];
maxDescr = MaxDescrA[iThread];
}
}
std::cout << "n = " << n << " det = " << maxDet << std::endl;
buildMat(n, mat, maxDescr);
printMat(n, mat);
threadBarrier();
}
delete[] mat;
delete[] MaxDetA;
delete[] MaxDescrA;
delete[] threadIdxA;
delete[] threadA;
return 0;
}
```
[Answer]
# R
You'll have to install R and the packages listed with `install.packages("package_name")`
Didn't get under 2 mins on my machine with this version (I've to try with a parallel modification)
```
library(pracma)
library(stringr)
library(R.utils)
library(microbenchmark)
f <- function(n) {
#If n is 1, return 1 to avoid code complexity on this special case
if(n==1) { return(1) }
# Generate matrices and get their determinants
dets <- sapply(strsplit(intToBin( 0:(2^n - 1)), ""), function(x) {
sapply( strsplit( intToBin( 0:(2^(n-1) - 1) ), ""),
function(y) {
det(Toeplitz(x,c(x[1],y)))
})
})
#Get the maximum determinant and return it
res <- max(abs(dets))
return(res)
}
```
Call and output:
```
> sapply(1:10,f)
[1] 1 1 2 3 5 9 32 56 125 315
```
Benchmark on my machine:
```
> microbenchmark(sapply(1:10,f),times=1L)
Unit: seconds
expr min lq mean median uq max neval
sapply(1:10, f) 66.35315 66.35315 66.35315 66.35315 66.35315 66.35315 1
```
For information, for a 1:11 range, it takes 285 seconds.
[Answer]
# C
Compile with:
```
$ clang -Ofast 52851.c -o 52851
```
Run with:
```
$ ./52851
```
Can output the maximum determinant for `n = 1..10` in ~115 seconds on my computer.
The program is just getting the determinant every possible binary Toeplitz matrix of size `n`, however every determinant of matrices of size `5x5` or smaller will be cached using memoization.
At first I wrongly assumed that every submatrix of a Toeplitz matrix will also be a Toeplitz matrix, so I only needed to memoize `2^(2n-1)` values instead of `2^(n^2)` for each `n`. I made the program before realizing my mistake, so this submission is just a fix of that program.
---
```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <string.h>
#define ELEMENTS(x) (sizeof(x) / sizeof(*x))
int *dets[6];
void print_matrix(int n, int c) {
for(int row = 0; row < n; row++) {
for(int col = 0; col < n; col++) {
int j = n - 1 - row + col;
int val = !!(c & (1 << j));
printf("%d ", val);
}
puts("");
}
}
int det(int n, uint8_t *m) {
if(n == 1) {
return m[0];
}
int i = 0;
if(n < ELEMENTS(dets)) {
for(int j = 0; j < n * n; j++) {
i *= 2;
i += m[j];
}
int v = dets[n][i];
if(v != INT_MIN) {
return v;
}
}
int v = 0;
uint8_t *sub = malloc((n - 1) * (n - 1));
for(int removed = 0; removed < n; removed++) {
if(m[removed]) {
uint8_t *p = sub;
for(int row = 1; row < n; row++) {
for(int col = 0; col < n; col++) {
if(col == removed) {
continue;
}
*p = m[col + row * n];
p++;
}
}
v += (removed % 2 == 0? 1: -1) * det(n - 1, sub);
}
}
free(sub);
if(n < ELEMENTS(dets)) {
dets[n][i] = v;
}
return v;
}
int main(void) {
for(int i = 2; i < ELEMENTS(dets); i++) {
int combinations = 1 << (i * i);
dets[i] = malloc(combinations * sizeof(**dets));
for(int j = 0; j < combinations; j++) {
dets[i][j] = INT_MIN;
}
}
puts("1: 1");
for(int n = 2; n < 65; n++) {
int vars = 2 * n - 1;
size_t combinations = 1 << vars;
int best = -1;
int max = -1;
uint8_t *sub = malloc((n - 1) * (n - 1));
for(int c = 0; c < combinations; c++) {
int d = 0;
for(int i = 0; i < n; i++) {
if(c & (1 << (n - 1 + i))) {
uint8_t *p = sub;
for(int row = 1; row < n; row++) {
for(int col = 0; col < n; col++) {
if(col == i) {
continue;
}
int j = n - 1 - row + col;
*p = !!(c & (1 << j));
p++;
}
}
d += (i % 2 == 0? 1: -1) * det(n - 1, sub);
}
}
if(d > max) {
max = d;
best = c;
}
}
free(sub);
printf("%d: %d\n", n, max);
//print_matrix(n, best);
}
return 0;
}
```
[Answer]
# PARI/GP, n=11
This is brute force but taking advantage of `det(A^T) = det(A)`. I'm only posting it to demonstrate how easy it is to skip transposes. The lowest bit of `b1` holds the top left cell, and the other bits hold the rest of the top row. `b2` holds the rest of the left column. We simply enforce `b2 <= (b1>>1)`.
```
{ for(n=1,11,
res=0;
for(b1=0,2^n-1,
for(b2=0,b1>>1,
res=max(res,matdet(matrix(n,n,i,j,bittest(if(i>j,b2>>(i-j-1),b1>>(j-i)),0))));
)
);
print(n" "res);
)
}
```
Regarding computing Toeplitz determinants in `O(n^2)` time: In my limited research, I've kept running into a requirement that all leading principal minors must be nonzero in order for the algorithms to work, which is a major obstacle for this task. Feel free to give me pointers if you know more about this than I do.
[Answer]
# Rust, \$n \leq 14 \$ in 2 min on my laptop
### `src/main.rs`
```
use std::time::{Instant, Duration};
use rulinalg::matrix::Matrix;
fn bit_get(n: u32, i: u32) -> f64 {
((n >> i) & 1) as f64
}
fn main() {
let start = Instant::now();
let max_duration = Duration::from_secs(120); // 2 minutes
let mut n = 1;
while start.elapsed() < max_duration {
let mut res = 0f64;
for b1 in 0..(1 << n) {
for b2 in 0..=(b1 / 2) {
let values: Vec<f64> = (0..n)
.flat_map(|r| (0..n)
.map(move |c| if r > c {
bit_get(b2, r as u32 - c as u32 - 1)
} else {
bit_get(b1 as u32, c as u32 - r as u32)
}))
.collect();
let matrix = Matrix::new(n as usize, n as usize, values);
let det = matrix.det();
res = res.max(det);
}
}
println!("{} {}", n, res);
n += 1;
}
}
```
### `Cargo.toml`
```
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
ndarray = "0.15"
ndarray-linalg = "0.13"
rulinalg = "0.4"
```
### Build and running
```
# win10 environment
$ set Copt-level=3
$ set Clto=fat
$ set Ctarget-cpu=native
$ cargo build --release
$ target\release\rust_hello.exe
1 1
2 1
3 2
4 3
5 5
6 9
7 32
8 56
9 125
10 315
11 1458
12 2673
13 8117.999999999997 # roughly 8118
14 22386.000000000007 # roughly 22386
```
[Answer]
# Mathematica
So slow. It can be optimized more.
[Try it online!](https://tio.run/##NY9BawIxEIXv@yseu@ChjtTkulWwLUoPhR56C1OalYgLcRfSHCzib9/OGJtLmJfvvZc5@XwMJ5/7vZ@mlxh8cvUujp2P3w81t9Wn72JwKfxghWVbYTsm1xkdCHI/rWC/BixgdJzPCRUKY@@MVWYbx5vv0bJKdw7Sm/qzgDpgk5L/dW8H1xis0VjCc593IUsWQbSFaNrExaznH5D221tjmDEjXAbCcCUsZQPByvff/VkXIbyKpVQzt6zIR@qH7MRUoybFuWRIrjFXnqY/)
```
Clear["Global`*"];
Table[res = 0;
For[b1 = 0, b1 <= 2^n - 1, b1++,
For[b2 = 0, b2 <= Floor[b1/2], b2++,
matrix =
Array[If[#1 > #2, BitGet[b2, #1 - #2 - 1],
BitGet[b1, #2 - #1]] &, {n, n}, 0];
res = Max[res, Det[matrix]];]];
Print[n, " ", res], {n, 1, 11}]
```
```
1,1,2,3,5,9,32,56,125,315,1458
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.