text
stringlengths 180
608k
|
---|
[Question]
[
Smallfuck is a brainfuck-like language with 1-bit cells. It has the following instructions:
```
> Increment the pointer
< Decrement the pointer
* Flip the current bit
[ If the current bit is not set, jump to the instruction after the matching ]
] If the current bit is set, jump to the instruction after the matching [
( or just jump unconditionally to matching [ )
```
Whatfuck adds one more instruction:
```
? Nondeterministically set the current bit to 0 or 1.
```
A whatfuck program does not take any input. It can result in one of 3 possibilities: `1` (accept), `0` (reject) or it may never halt.
The program will result in `1` if there exists a sequence of bits chosen for `?`s which results in the program terminating with `1` as the current bit.
The program terminates with `0` if all possible choices terminate with current bit `0`,
If some choices don't terminate, and all choices which terminate do so with `0`, then the program will never terminate.
Your interpreter should run all possibilities simultaneously. You can't try `0` first and then try `1`, because some programs will not terminate when they should. For example, `*[?*]*` will accept with the choice `1`, but never terminate if you always choose `0`.
[As an example, here is a python 2 interpreter I wrote, not golfed](http://pastebin.com/Hp85cg1R)
## Rules
* Your interpreter must accept a whatfuck program from stdin and print its result.
* You may assume the whatfuck program only contains characters `[]<>*?`
* The array of bits is unbounded on both ends.
* Shortest code wins.
## Some Test Cases
This will fail if your code always tries `0` first
```
*[?*]*
1
```
Is there a subset of `{-7,-3, 5, 8}` whose sum is 3?
```
*<<<<<?[<<<<<<<<<<<<<<]?[<<<<<<]?[>>>>>>>>>>]?[>>>>>>>>>>>>>>>>]<
1
```
Is there a subset of `{-7,-3, 5, 8}` whose sum is 4?
```
*<<<<<<<?[<<<<<<<<<<<<<<]?[<<<<<<]?[>>>>>>>>>>]?[>>>>>>>>>>>>>>>>]<
0
```
Is there a way to assign boolean values to `a`,`b` and `c` such that
`(a XOR b) AND (a XOR c) AND (b XOR c)` is true?
```
?[*>*>*<<]?[*>*>>*<<<]?[*>>*>*<<<]>[*>[*>[*>*<]<]<]>>>
0
```
[Answer]
## Python, 305 chars
```
P=raw_input()+'$'
S=[(0,0,[])]
F={}
R={}
i=r=0
for c in P:
if'['==c:S+=i,
if']'==c:j=S.pop();F[j]=R[i]=i-j
i+=1
while S*(1-r):p,t,B=S.pop(0);c=P[p];b=B.count(t)%2;p+=1+F.get(p,0)*(1-b)-R.get(p,0)*b;t+=(c=='>')-(c=='<');B=B+[t]*(c=='*');r|=(c=='$')&b;S+=[(p,t,B)]*(c!='$')+[(p,t,B+[t])]*(c=='?')
print r
```
Keeps track of the nondeterministic set of states in `S`, each with a code position `p`, a tape position `t`, and a list of tape indexes `B`. A tape index can appear multiple times in the list `B`, the tape at that index is 1 if the index appears an odd number of times in `B`.
[Answer]
Infinite tape ahoy!
## Haskell, 516
```
i((p:l,r),(π,'<':φ))=[((l,p:r),('<':π,φ))]
i((l,p:r),(π,'>':φ))=[((p:l,r),('>':π,φ))]
i((l,p:r),(π,'*':φ))=[((l,1-p:r),('*':π,φ))]
i((l,_:r),(π,'?':φ))=[((l,b:r),('?':π,φ))|b<-[0,1]]
i(s@(l,0:r),(π,'[':φ))=[(s,m(']':π,φ)0)]
i(s,(π,'[':φ))=[(s,(']':π,φ))]
i(s,(π,']':φ))=[(s,ξ$m(']':φ,π)0)]
i _=[]
m(l,']':r)0=('[':l,r)
m(l,']':r)n=m('[':l,r)$n-1
m(l,'[':r)n=m(']':l,r)$n+1
m(l,c:r)n=m(c:l,r)n
ν=null;ο=0:ο
μ[]="0"
μ ω|ν[ψ|ψ@((_,b:_),_)<-ω,b>0,ν$i ψ]=μ$ω>>=i
μ _="1"
ξ(a,b)=(b,a)
main=interact$ \ζ->μ[((ο,ο),("",ζ))]
```
[Answer]
## Python (~~405~~ ~~399~~ 379)
It takes the input on one line, but I "may assume the whatfuck program only contains characters `[]<>*?`" and newline isn't on that list :P
```
w,i,p,a={},0,raw_input(),[(0,0,[],[])]
for c in p:
if c=='[':a+=i,
if c==']':g=a.pop();w[i],w[g]=g,i
i+=1
i,z=0,lambda l:l and l.pop()or 0
while a:
n,c,l,r=a.pop(0)
try:o=p[n]
except:
if c:i=1;break
continue
if o=='*':c=not c
if o=='>':l+=c,;c=z(r)
if o=='<':r+=c,;c=z(l)
if o in'[]'and(']'==o)==c:n=w[n]
if o=='?':a+=(n+1,not c,l[:],r[:]),
a+=(n+1,c,l,r),
print i
```
] |
[Question]
[
Thinking about various quine puzzles here, I got an idea for another one:
**Compose a program that outputs its own *compiled* code to a file** (or multiple files, if the compiled code is). (This means that only compiled languages are eligible.)
# Rules
Standard quine rules - no cheating allowed. In particular:
1. The program cannot read the compiled code from disk, cannot store it somewhere etc. It must compute it somehow without external help.
2. If the program is compiled to several files (i.e. several Java `.class` files), it must output them all.
3. You can use any existing libraries available for your language. However:
* The libraries you use cannot be something created just for this task. (For example in order to keep some information away from what's considered to be the program.)
* Any libraries you use must be older than your program. You cannot just create a program that loads a piece of data from an external library, compile the program, and copy the compiled code into the library - that'd be cheating.
* You cannot embed a compiler of your language in any form. In particular, you cannot just take a standard quine and hook it up with a compiler to produce the compiled output.
4. As mentioned, only compiled languages are eligible. You can use a scripting language as long as it can be compiled to a bytecode that's reasonably different from the source form (if you're not sure, better ask).
# Notes
Most likely, this puzzle can be solved reasonably only in languages that compile to some sort of bytecode that can be manipulated. For example, Java and compiled bytecode seems good for the task. (But if you find a genuine solution in some other compiled language, that's fine too, as long as it isn't some sort of cheating.)
# Submission
Don't submit the compiled program (as this could be potentially dangerous). Instead post your sources and a description what to do to create the final program.
# Evaluation
Let voters decide the best solution. Personally I'd appreciate solution that are elegant, short (in their source form) and didactic - that explain what's going on.
# Bonuses
Bonus points for
* Let the program output a *compressed* file containing its compiled code. This has the additional benefit that if the program is compiled into more files, the output will be a single packed file. For example, in Java try to create an executable JAR file that outputs the JAR itself.
* Outputting the MD5 sum of the compiled file(s) - so the program would write its compiled code *and* its MD5 sum.
[Answer]
# Assembly (DOS .com file)
```
start:
%rep 2
call $+3
mov ah, 9
mov dx, 100h + (end - start) / 2
int 21h
mov ah, 2
mov dl, "$" - 1
inc dx
int 21h
ret
db "$"
%endrep
end:
```
Assemble with `nasm quine.asm -o quine.com`. Try with `dosbox quine.com`.
Proof of correctness (you can also verify by the smilies [here](http://de.wikipedia.org/wiki/Codepage_437)):

[Answer]
# Python 2.7.3
```
#!/usr/bin/env python
import sys
import time
import struct
import compiledquine
_ = '\x63\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x40\x00\x00\x00\x73\x6e\x00\x00\x00\x64\x00\x00\x64\x01\x00\x6c\x00\x00\x5a\x00\x00\x64\x00\x00\x64\x01\x00\x6c\x01\x00\x5a\x01\x00\x64\x00\x00\x64\x01\x00\x6c\x02\x00\x5a\x02\x00\x64\x00\x00\x64\x01\x00\x6c\x03\x00\x5a\x03\x00\x64\x02\x00\x5a\x04\x00\x65\x00\x00\x6a\x05\x00\x6a\x06\x00\x64\x03\x00\x65\x02\x00\x6a\x07\x00\x64\x04\x00\x65\x08\x00\x65\x01\x00\x6a\x01\x00\x83\x00\x00\x83\x01\x00\x83\x02\x00\x17\x65\x04\x00\x65\x04\x00\x16\x17\x83\x01\x00\x01\x64\x01\x00\x53\x28\x05\x00\x00\x00\x69\xff\xff\xff\xff\x4e\x73\x08\x00\x00\x00%s\x73\x04\x00\x00\x00\x03\xf3\x0d\x0a\x74\x01\x00\x00\x00\x49\x28\x09\x00\x00\x00\x74\x03\x00\x00\x00\x73\x79\x73\x74\x04\x00\x00\x00\x74\x69\x6d\x65\x74\x06\x00\x00\x00\x73\x74\x72\x75\x63\x74\x74\x0d\x00\x00\x00\x63\x6f\x6d\x70\x69\x6c\x65\x64\x71\x75\x69\x6e\x65\x74\x01\x00\x00\x00\x5f\x74\x06\x00\x00\x00\x73\x74\x64\x6f\x75\x74\x74\x05\x00\x00\x00\x77\x72\x69\x74\x65\x74\x04\x00\x00\x00\x70\x61\x63\x6b\x74\x03\x00\x00\x00\x69\x6e\x74\x28\x00\x00\x00\x00\x28\x00\x00\x00\x00\x28\x00\x00\x00\x00\x73\x1c\x00\x00\x00\x2f\x68\x6f\x6d\x65\x2f\x67\x72\x61\x6e\x74\x2f\x63\x6f\x6d\x70\x69\x6c\x65\x64\x71\x75\x69\x6e\x65\x2e\x70\x79\x74\x08\x00\x00\x00\x3c\x6d\x6f\x64\x75\x6c\x65\x3e\x02\x00\x00\x00\x73\x0a\x00\x00\x00\x0c\x01\x0c\x01\x0c\x01\x0c\x02\x06\x01'
sys.stdout.write('\x03\xf3\x0d\x0a' + struct.pack('I', int(time.time())) + _ % _)
```
Note that this **must** be saved as `compiledquine.py`. These are the results I get:
```
$ ./compiledquine.py > compiledquine.py.out
$ md5sum compiledquine.pyc compiledquine.py.out
4b82e7d94d0d59e3d647d775fffc1948 compiledquine.pyc
4b82e7d94d0d59e3d647d775fffc1948 compiledquine.py.out
```
I won't guarantee that it'll work for you, but it does consistently work for me. Here's what happens:
* At the bottom of the import statements, the script itself is imported. This compiles it to a .pyc file.
* The variable `_` is filled with the program's bytecode starting at byte 0x08, except `%s` is put in place of the variable itself.
* The script fills in the first 4 'magic' bytes, which are specific to Python 2.7.3, followed by the timestamp in the next 4 bytes, which is generated by `struct.pack` and `time.time`, and then adds `_ % _` to complete the output. (That last bit is borrowed from some other Python quines.)
* Because of the timestamp at the beginning, this script technically isn't always accurate. If the self-import and the last line execute in different seconds, the output will be a byte off.
[Answer]
# Lua
```
s="s=%qf=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))"f=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))
```
Now, one's first concern may be that Lua is '*An Interpreted Language, not a compiled one*' However, Lua actually interprets by compiling at runtime. `string.dump` returns the compiled byte code of the function supplied, and `load` returns the function defined by the string supplied.
Very simply, makes a function out of itself through the usual Lua quine method, then writes its compiled output.
## Output
```
LuaS “
xV (w@‰s="s=%qf=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))"f=io.open('dump.txt','w')f:write(string.dump(load(s:format(s)))) @@€À@ A A@ € $€€ €@ ÀA † B ‡@BÆ€B @ ÁB†@ $€ä ¤ $@ & € sEs=%qf=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))fioopen dump.txtwwritestringdumploadformat _ENV
```
Contains mostly unprintable characters, so here's a Hex Dump
```
00000000: 1b4c 7561 5300 1993 0d0d 0a1a 0d0a 0408 0408 0878 5600 0000 :.LuaS..............xV...
00000018: 0000 0000 0000 0000 2877 4001 8973 3d22 733d 2571 663d 696f :........([[email protected]](/cdn-cgi/l/email-protection)="s=%qf=io
00000030: 2e6f 7065 6e28 2764 756d 702e 7478 7427 2c27 7727 2966 3a77 :.open('dump.txt','w')f:w
00000048: 7269 7465 2873 7472 696e 672e 6475 6d70 286c 6f61 6428 733a :rite(string.dump(load(s:
00000060: 666f 726d 6174 2873 2929 2929 2266 3d69 6f2e 6f70 656e 2827 :format(s))))"f=io.open('
00000078: 6475 6d70 2e74 7874 272c 2777 2729 663a 7772 6974 6528 7374 :dump.txt','w')f:write(st
00000090: 7269 6e67 2e64 756d 7028 6c6f 6164 2873 3a66 6f72 6d61 7428 :ring.dump(load(s:format(
000000a8: 7329 2929 2900 0000 0000 0000 0000 0207 1400 0000 0840 4080 :s))))................@@.
000000c0: 06c0 4000 0700 4100 4140 0100 8180 0100 2480 8001 0800 0081 :[[email protected]](/cdn-cgi/l/email-protection)@......$.......
000000d8: 0680 4000 0cc0 4100 8600 4200 8740 4201 c680 4200 0601 4000 :[[email protected]](/cdn-cgi/l/email-protection)[[email protected]](/cdn-cgi/l/email-protection)...@.
000000f0: 0cc1 4202 8601 4000 2401 8001 e400 0000 a400 0000 2440 0000 :..B...@.$...........$@..
00000108: 2600 8000 0c00 0000 0402 7314 4573 3d25 7166 3d69 6f2e 6f70 :&.........s.Es=%qf=io.op
00000120: 656e 2827 6475 6d70 2e74 7874 272c 2777 2729 663a 7772 6974 :en('dump.txt','w')f:writ
00000138: 6528 7374 7269 6e67 2e64 756d 7028 6c6f 6164 2873 3a66 6f72 :e(string.dump(load(s:for
00000150: 6d61 7428 7329 2929 2904 0266 0403 696f 0405 6f70 656e 0409 :mat(s))))..f..io..open..
00000168: 6475 6d70 2e74 7874 0402 7704 0677 7269 7465 0407 7374 7269 :dump.txt..w..write..stri
00000180: 6e67 0405 6475 6d70 0405 6c6f 6164 0407 666f 726d 6174 0100 :ng..dump..load..format..
00000198: 0000 0100 0000 0000 1400 0000 0100 0000 0100 0000 0100 0000 :........................
000001b0: 0100 0000 0100 0000 0100 0000 0100 0000 0100 0000 0100 0000 :........................
000001c8: 0100 0000 0100 0000 0100 0000 0100 0000 0100 0000 0100 0000 :........................
000001e0: 0100 0000 0100 0000 0100 0000 0100 0000 0100 0000 0000 0000 :........................
000001f8: 0100 0000 055f 454e 56 :....._ENV
```
[Answer]
# [Python 3](https://docs.python.org/3/), 161 bytes
```
s = 's = %s; print(compile(s %% repr(s), \'file\', \'exec\').co_code.decode(\'utf-16\'))'; print(compile(s % repr(s), '<file>', 'exec').co_code.decode('utf-16'))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v1jBVkEdRKgWWysUFGXmlWgk5@cWZOakahQrqKoqFKUWFGkUa@ooxKinAQVj1EGs1IrU5Bh1Tb3k/Pjk/JRUvZRUEKURo15akqZraAaU0lTHYhrCMHUbkGF2QMPAZmEaBTUJaND//wA "Python 3 – Try It Online")
This one outputs its EXACT bytecode (that is, the bytecode that is stored in the Python interpreter when you run the program.)
# [Python 3](https://docs.python.org/3/), 328 bytes (Extension)
```
import zipfile
with zipfile.ZipFile("output.zip", "w") as f:s = 'import zipfile\n\nwith open(\"output.zip\", \"w\") as f:\ns = %s\nf.writestr(\n\'output\',\ndata=(compile(s %% repr(s), \'file\', \'exec\').co_code.decode(\'utf-16\')))\n';f.writestr('output',data=(compile(s % repr(s), '<file>', 'exec')).co_code.decode('utf-16'))
```
[Try it online!](https://tio.run/##ZY7bisIwEIbv9ylCoEwCNSALXuyue@lDyICUNsXAmoRkStWXr5OqrIerOfH938QT7YP/nCZ3iCGROLvYuz/7MTra3wezdXHDVckwUBzI8F7WQo5SiyaL/iuLtYDnAPTo54wQrVf4QCKjKEe8w@gLXmX0vRmTI5spKcbhiiDU6LuGmrVqwyGWN7KoKpFsTCprzoLZB6WzR9siaNOGXRs6azpbikIYqF8sV3zSGj18P5huGqjfHP8K@CmKX1bMBk55NdwEfJmmCw)
This one prints its EXACT bytecode (that is, the bytecode that is stored in the Python interpreter when you run the program. It also outputs it being compressed.)
] |
[Question]
[
A [Friedman number](http://en.wikipedia.org/wiki/Friedman_number) is a number that can be expressed by applying basic mathematical operations(^,/,\*,+,-) to all it's digits. The operations need not be applied to each individual digit, but all the digits must be involved. That is, 121= 11^2 --> all digits are involved, but 1 & 1 have been clubbed together to make 11.
Use of parenthesis is allowed, but the trivial solution `x= (x)` is not a valid solution. Also not valid, `x= +x`.
[Examples](https://erich-friedman.github.io/mathmagic/0800.html)
* 25= 5^2
* 121= 11^2
* 343= (3+4)^3
* 2048 = (8^4)/2+0
Write a program that will take positive two integers and print the number of Friedman numbers in that range(inclusive), and the numbers with the expressions in subsequent lines.
Input -
```
n m | n, m integers, n>=0, m>n
```
Output -
```
count | number of Friedman numbers in the given range
fn1 exp1 | Friedman number, expression
fn2 exp2
fn3 exp3
.
.
.
```
Shortest code posted by Sunday 29th July 00:00 Hrs GMT will be the winner.
[Answer]
### Python 2.7 - 380 378 372 371 367 363 357 354 352 348 336 chars
Just a simple brute force search.
```
from itertools import*
s=lambda x:[x]['1'>x>'0':]+['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]
def E(e):
try:return eval(e.replace("^","**"))
except:0
A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}
print len(A)
for v in A:print v,A[v]
```
### Example run:
```
1
300
9
128 (2^(8-1))
289 ((9+8)^2)
216 (6^(1+2))
121 (11^2)
153 (3*51)
25 (5^2)
125 (5^(2+1))
126 (6*21)
127 ((2^7)-1)
```
### Explanation:
`s(x)`
is a function that takes a string containing a sequence of digits and returns all expressions using those digits in that order.
`[x]['1'>x>'0':]`
evaluates to a list containing x if x is '0' or a sequence of digits not starting with '0'; otherwise, it evaluates to an empty list. Basically this handles the case where I join all the digits together.
`['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]`
basically partitions x into two parts (both being of non-zero length), calls s() on each part and joins all the results together with some operator between them, by using product().
`E(e)`
is basically a safe eval. It returns the value of e if e is valid and None otherwise.
```
A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}
```
Basically this code tries all the numbers in the range, permutes their digits and tests each expression s() generates for that permutation, ignoring the first expression if x doesn't start with '0', because if x doesn't start with '0' then the first expression will just be x.
### Alternate version - 397 chars
Here is my code if you are required to use fractions:
```
from fractions import*
from itertools import*
s=lambda x:["Fraction(%s)"%x]['1'>x>'0':]+['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]
def E(e):
try:return eval(e.replace("^","**"))
except:0
A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}
print len(A)
for v in A:print v,A[v].replace("Fraction","")
```
[Answer]
# Ruby, ~~456 438 408 390 370 349 344~~ 334 bytes
```
g={}
f=->a,b{a.permutation(b).to_a.uniq.flatten.each_slice b}
F,T=$*
([F.to_i,10].max..T.to_i).map{|c|f[a="#{c}".split(''),v=a.size].map{|m|f[[?+,?-,?*,?/,'','**'],v-1].map{|w|(d=(s=m.zip(w)*'').size)==v&&next
0.upto(d){|y|y.upto(d+1){|u|begin(r=eval t="#{s}".insert(y,?().insert(u,?)))==c&&g[r]=t
rescue Exception
end}}}}}
p g.size,g
```
Output:
```
% ruby ./friedman-numbers.rb 1 300
9
{25=>"(5)**2", 121=>"(11)**2", 125=>"5**(2+1)", 126=>"(6)*21", 127=>"(2)**7-1", 128=>"2**(8-1)", 153=>"(3)*51", 216=>"6**(1+2)", 289=>"(9+8)**2"}
```
Also it works relatively fast for larger numbers:
```
% time ruby friedman-numbers.rb 3863 3864
1
{3864=>"(6**4-8)*3"}
ruby friedman-numbers.rb 3863 3864 14.05s user 0.17s system 99% cpu 14.224 total
```
[Answer]
### Python3 ~~(436)~~ ~~(434)~~ (443)
It was hard. I can spare some characters if I make output more native.
```
from itertools import*
r={};k=product;m=map
q=lambda n,h=1:["("+i+c+j+")"for(i,j),c in k(chain(*[k(*m(q,f))for f in sum(([(x[:q],x[q:])for q in range(1,len(x))]for x in m("".join,permutations(n))),[])]),list("+-*/^")+[""]*h)]if 1<len(n)else[n]*h
a,b=m(int,m(input,"nm"))
for i,j in chain(*[k(q(str(n),0),[n])for n in range(a,b+1)]):
try:exec("if eval(%r)==j:r[j]=i"%i.replace("^","**"))
except:0
print(len(r))
for j,i in r.items():print(i,j)
```
Output
```
n100
m200
6
(2^(8-1)) 128
(3*(51)) 153
((11)^2) 121
(5^(1+2)) 125
(6*(21)) 126
((2^7)-1) 127
```
[Answer]
# Mathematica 456 416 402 404 400 396 chars
```
<< Combinatorica`; l = Length; p = Permutations; f = Flatten; c = Cases;
u[d_, o_, s_] :=
Fold[#2[[1]] @@ If[s == 1, {#1, #2[[-1]]}, {#2[[-1]], #1}] &,
d[[1]], Thread@{o, Rest@d}];
q[t_, r_] := {u[t, #, r], u[HoldForm /@ t, #, r]} & /@
p[{Plus, Subtract, Times, Divide, Power}, {l@t - 1}];
v[m_, n_] := (t = Table[Union@
c[f[{#~q~1, #~q~0} & /@
f[p /@ c[
FromDigits /@ # & /@
f[SetPartitions /@ p@IntegerDigits@j, 1], x_ /; l@x > 1],
1], 2], {j, _}], {j, m, n}]~f~1; {l@t}~Join~t)
```
**Example**:
```
v[1,300]//TableForm
```
**Output**:

] |
[Question]
[
The idea is based on [this interactive game](https://hyperjumps.quantamagazine.org). Given a set of eight decimal digits which are not necessarily distinct, your task is to find a hyperjump trip with the specified length.
### But what is a hyperjump? I ain't got time to click on HOW TO PLAY
Ok, you have a set of eight digits where none is `0` or `9`. Let's say `[1, 3, 6, 7, 8, 7, 7, 4]`. The hyperjump is basically a sub-list of this list. A valid sequence can start at the left with any two numbers, e.g. `7, 7`.
The next number must be the rightmost digit of a simple arithmetic operation (`+ - * /`) between the previous numbers of that sequence. For example:
```
7 + 7 = 14
7 / 7 = 1
7 - 7 = 0
7 * 7 = 49
```
So the next number can either be `4` or `1` because `0, 9` are not on the list. Let's choose `1`:
```
7 - 1 = 6
7 + 1 = 8
7 / 1 = 7
```
By choosing `8` as the next number (`7, 7, 1, 8`) we have:
```
1 * 8 = 8
1 + 8 = 9
71 - 8 = 63
```
As you see, one can also combine the previous digits in the specified order to form a new number. Since there was just one `8` on the list, we can't choose it again. So the only option is `3`. The resulting sequence can be expanded again by adding `4` (because `8 * 3 = 24`) to get `[7, 7, 1, 8, 3, 4]`. The ultimate goal is to reach a `9` after n-steps, where `n ‚àà {5, 6, 7, 8}`. Thus if `n = 6` we have reached the desired *hyperjumps trip* since `83 - 4 = 79`.
## Challenge
You are given a list of eight digits in the range of `1..8` along with the number of steps `n`. Find a sub-list with length `n` that can form a hyperjump to `9`.
* The given set can have repeating elements.
* The number of steps is either of `5, 6, 7, 8`.
* The sub-list can only use the elements of the main list (obviously!) and the number of repeating elements cannot exceed those in the main list. For example if the given list has three `7`s, the hyperjump can have at most three `7`s.
* The inputs and output can be in any format that you are comfortable with. But the ordering of the output must be preserved.
* Math operations must apply from left to right and negative results are not accepted. Hence a sequence cannot start with `6, 7, 1`.
* If no hyperjump exists, any kind of error message or an empty output is acceptable.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Bonus point
You are a God if your program can find all possible hyperjumps with the specified length.
## Examples:
```
list = [1, 3, 6, 7, 2, 7, 7, 4]; n = 5:
hyperjump = [7, 4, 3, 1, 2]
list = [1, 1, 8, 2, 2, 3, 4, 6]; n = 6:
hyperjump = [6, 2, 2, 1, 3, 4]
list = [5, 5, 5, 5, 5, 5, 5, 5]; n = 7:
hyperjump = []
```
[Answer]
# JavaScript (ES6), 159 bytes
A version always using a single digit for the right operand, which apparently is the correct rule of the game.
```
a=>g=(n,o='',p,m)=>(n?a:[9]).some((v,i)=>m>>i&v<9|o>9&!a.some((_,i)=>[...'+-*/'].some(c=>(s=o.slice(i,-1))&&eval(s+c+p)%10==v))?0:n?g(n-1,o+v,v,m|1<<i):O=o)&&O
```
[Try it online!](https://tio.run/##bY1BboMwEEX3PYW7CHjCYAJNSEEYjpADICuyKEGuwEZ15VXuTl1CV6n0NdLM/@/Pp3TSdl9q/o61@eiXG18krwdONRoehjjjBLymupFlWwhg1kw9pQ6Vv051rQJXFXdTF8Gr3Lzr6rWMsTCK90koHvfOt1humB1V11OFcQoQBL2TI7VRF82wSw@cO4DmUOpmoDpO0UQOHU73tKoUlBduPHFZOqOtGXs2moHeaJsieUOSIzkjydbpdRRATwAkSUj7u64Zn8zEyzPu9b6y2Rrz4dzj@Ybnf9bj0fGp4YTkH/mG89Yglh8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 175 bytes
Expects `(list)(n)`. Returns either a string of digits, or *false* if there's no solution.
```
a=>g=(n,o='',m)=>(n?a:[9]).some((v,i)=>m>>i&v<9|o>9&!a.some((_,i)=>(h=j=>(s=o.slice(j))&&eval(o.slice(i,j)+'+-*/'[j*4&3]+s)%10==v|h(j+1/4))(i+1))?0:n?g(n-1,o+v,m|1<<i):O=o)&&O
```
[Try it online!](https://tio.run/##bU1LboMwEN33FO6iMBMbiAkhBWE4Qg6AUGRRQmwBrkrlFXenLk1WqfT0pHm/0dLKuf1Sn9/BZD669SpWKcpewMSM8H02oihhqmReZw2Gsxk7AMuUU8eyVJ4tssWUmfcq795l8@AmtONZmHAeVNuBRvS8zsoBHopiGqlPg13k13qXeIeGzvjG90LY5Qaa8ihBBEU5YrXPp6qHKeDMUMvGhReFwvwsjBs9r62ZZjN04WB6uELNGTkwkjJyYiTe2CFpEI6IJIpI/XtuGZeMm5fnusP71o23mAunrp7e6@nD@nuUPC0cGfkHbuF0X2jWHw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input list of digits
g = ( // g is a recursive function taking:
n, // n = counter
o = '', // o = output string
m // m = bit mask of already used digits
) => //
(n ? a : [9]) // using [9] for the last iteration or a[] otherwise,
.some((v, i) => // for each value v at index i:
m >> i & v < 9 | // is the i-th bit of m set with v not equal to 9?
o > 9 & // does o have at least 2 digits?
!a.some((_, i) => // for each entry in a[] at index i:
( h = j => // h is a recursive function taking a pointer j
(s = o.slice(j)) // using j, extract the right operand s from o
&& eval( // unless s is empty, evaluate as JS code:
o.slice(i, j) // the left operand (from i to j-1)
+ '+-*/' // followed by an operator
[j * 4 & 3] // chosen according to the decimal part of j
+ s // followed by the right operand
) % 10 == v | // and test whether the result modulo 10 is v
h(j + 1 / 4) // do a recursive call with j + 1/4
)(i + 1) // initial call to h with j = i + 1
) ? // end of some(); if the test fails:
0 // do nothing
: // else:
n ? // if there are more digits to add:
g( // do a recursive call:
n - 1, // decrement n
o + v, // append v to o
m | 1 << i // set the i-th bit of m
) // end of recursive call
: // else:
O = o // success: save o in O
) && O // end of some(); return either false or O
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.√Ü íV"+-*/"¬π<√£ŒµUYƒásvyXN√®.VD√ØŒ∏}9√ä;)√êd*√ØQ}√†
```
Slow brute-force. Inputs in the order \$n,list\$, and will output a list of all possible results (including duplicates); not because it's mentioned as *Bonus point* in the challenge description, but simply because it's 1 byte shorter. üòâ
[Try it online](https://tio.run/##AVIArf9vc2FiaWX//y7DhsqSViIrLSovIsK5PMOjzrVVWcSHc3Z5WE7DqC5WRMOvzrh9OcOKOynDkGQqw69RfcOg//81ClsxLDMsNiw3LDIsNyw3LDRd) or [verify all test cases with only the first valid result instead of all](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVQwqGV//UOtx2eqXduSpiStq6WvtKhdTaHF5/bGhp5pL24rDLC7/AKvTCXw@vP7ai1PNxlrXl4QorW4fWBtYcX/K/V@R8dbaoTbahjrGOmY65jBMTmOiaxsToK0WYgYUMdC6CgEVDaRMcMLGyuA9SAAmNjYwE).
**Explanation:**
```
.Æ # Get all n-sized lists using items of the list, where `n` and
# the list are the first/second (implicit) inputs respectively
í # Filter this list of lists by:
V # Pop and store the current list in variable `Y`
# (since we're gonna use it within an inner iterator)
"+-*/" # Push the string of the four operands
¬π< # Push the first input - 1
√£ # Get all input-1 sized combinations of operands
ε # Map over each list of operands:
U # Pop and store the current list of operands in variable `X`
Y # Push digit-list `Y`
ć # Extract head; push remainder-list and first item separately
s # Swap so the remainder-list is at the top
v # Loop over each digit of the remainder-list:
y # Push the current digit
XNè # Push the loop-index'th operand of list `X`
.V # Evaluate and execute this operand as 05AB1E code
D # Duplicate the result
ï # Cast the copy to an integer to remove decimal values
θ # Pop and leave just its last digit
} # After the loop:
9Ê # Check that the final digit is NOT 9 (0 if 9; 1 if [0-8])
; # Halve this 0 or 1 to 0 or 0.5 respectively
) # Wrap all values on the stack into a list
Ð # Triplicate this list
d # Check for each value whether it's non-negative (>=0)
* # Multiply so all negative values in the list become 0s
ï # Cast all values to integers to remove decimal values
Q # Equals-check to verify the list is still the same
}à # After the map: check whether any is truthy by taking the max
# (after which the filtered list is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṖṪṭḌƊÐƤṖjþ“+_×÷”ẎVDṪ€
œ!;9e"ÇƤ$ṫ3ẠƲƇ
```
A dyadic Link that accepts the list of positive digits as integers on the left and the proposed length on the right and yields a list of all possible hyperjump solutions, including the duplicates available when there are repeated digits that may be used.
**[Try it online!](https://tio.run/##y0rNyan8///hzmkPd656uHPtwx09x7oOTzi2BCiSdXjfo4Y52vGHpx/e/qhh7sNdfWEuQFWPmtZwHZ2saG2ZqnS4/dgSlYc7Vxs/3LXg2KZj7f///4821FEwASMzGDLXUbCI/W8KAA "Jelly – Try It Online")**
### How?
Brute force checking.
```
ṖṪṭḌƊÐƤṖjþ“+_×÷”ẎVDṪ€ - Helper Link, get possibles for last digit: list, X
·πñ - pop off the last digit (since it's the one we're aiming for)
ÐƤ - for each suffix:
Ɗ - last three links as a monad - f(S=suffix=[..., r]):
·π™ - tail (S) and yield -> right operand = r (and S=[...])
Ḍ - convert (S) from base ten -> left operand = int([...])
(or 0 when nothing remains)
·π≠ - tack -> [left operand, right operand]
·πñ - pop off the last result (removing the [0, r] which would
become e.g. "0+r", allowing any
repeated digit)
“+_×÷” - list of characters = "+_×÷"
þ - (operands list) table (characters) applying:
j - (operands) join with (character)
Ẏ - tighten to a list of equations
V - evaluate as jelly code -> list of results of the equations
D - convert the results to decimal
Ṫ€ - tail each - note that this will be a negative digit if
the equation result was negative
(hence `DṪ€` rather than `%⁵`)
œ!;9e"ÇƤ$ṫ3ẠƲƇ - Main Link: list, L; integer N
œ! - all permutations choosing N elements
Ƈ - filter keep those of these "potentials" for which:
∆≤ - last four links as a monad - f(potential):
;9 - concatenate a nine
$ - last two links as a monad - f(potential):
∆§ - for each prefix:
Ç - call the helper Link, above
" - (potential) zip (that) applying:
e - exists in?
·π´3 - tail from index 3 on (remove the first two exists in checks)
Ạ - all truthy?
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~125~~ ~~114~~ 113 bytes
```
⊞υ⟦⟦⟧θ⟧F⊕η«≔υθ≔⟦⟧υFθ«≔⊟κε≔⌊κδ≔↨δ⁰ζF⎇⁼ηι⟦⁹⟧Φχ№ελ¿∨‹ι²⊙Eδ↨✂δν⊖ι¹χ№﹪⟦∧μ⁺μζ∧›μζ⁻μζ×μζ∧¬﹪μζ÷μζ⟧χλ¿⁼ηιIκ⊞υ⟦⁺δ⟦λ⟧Φε⁻⌕ελν
```
[Try it online!](https://tio.run/##TVHLasMwEDw3X7HHFaiQ9EEpOaVJUwJNa2hvxgdhb2pRWY4lO5CUfLu7EnVq4wfamd2ZWeelcnmtTN8nnS@xk5CmmYQmE/PJrnaAG5s7qsi2VGApBPxMrhbe6y8buA2zhmNo68I5tjWROWBJvcdvIYECPhS32uqqqyJQjIEn5QkLCVMGThGIIz/JWeWO@Nx0yngsJWgmpI@su9amJYezqYRl3dkWSYIRfIHeAb47fCXvUUu44Y6FPeJW7YNCVPowOo96VsKK/tOG6bPwTIUY5m7rojM1pgtbYCUhMZ0P35OIcwt8caSCk1iTwBFHhE9dkR@gwH6rLxMHzsa2K33QBf1Vsqg/TjOOLyBxmm0tlW95j2IOZDzB5VdGf5wsNZm4bIkGX2vNHuKmODtLhVWfJ@e@T9OZhFsJD7yw@Ob7jp3cZ/31wfwC "Charcoal – Try It Online") Link is to verbose version of code. Outputs all solutions. Explanation:
```
⊞υ⟦⟦⟧θ⟧
```
Start a breadth-first search with a position of no digits in the list yet and the starting set.
```
F⊕η«
```
Loop over each step in the trip plus one for the last hyperjump to `9`.
```
≔υθ
```
Save the list of previously found positions.
```
≔⟦⟧υ
```
Start recording a list of new positions.
```
Fθ«
```
Loop over the previous list of positions.
```
≔⊟κε
```
Get the set of remaining digits.
```
≔⌊κδ
```
Get the list of jumps so far.
```
≔↨δ⁰ζ
```
Get the last jump made, if any.
```
F⎇⁼ηι⟦⁹⟧Φχ№ελ
```
Loop over the remaining digits, or just `9` if this is the final hyperjump.
```
¿∨‹ι²
```
If this is one of the first two steps, or...
```
⊙Eδ↨✂δν⊖ι¹χ
```
... for any suffix of the previous jumps ...
```
№﹪⟦∧μ⁺μζ∧›μζ⁻μζ×μζ∧¬﹪μζ÷μζ⟧χλ
```
... any of the arithmetic operations results in a positive integer that ends with the desired digit, then:
```
¿⁼ηι
```
If this is the final hyperjump, then...
```
Iκ
```
... output the list, otherwise...
```
⊞υ⟦⁺δ⟦λ⟧Φε⁻⌕ελν
```
... save the position of the extended list and reduced set.
] |
[Question]
[
Consider all arrays of \$\ell\$ non-negative integers in the range \$0,\dots,m\$. Consider all such arrays whose sum is exactly \$s\$. We can list those in lexicographic order and assign an integer to each one which is simply its rank in the list.
For example, take \$\ell=7, s=5, m=4\$, the list could look like:
```
(0, 0, 0, 0, 0, 1, 4) rank 1
(0, 0, 0, 0, 0, 2, 3) rank 2
(0, 0, 0, 0, 0, 3, 2) rank 3
(0, 0, 0, 0, 0, 4, 1) rank 4
(0, 0, 0, 0, 1, 0, 4) rank 5
(0, 0, 0, 0, 1, 1, 3) rank 6
(0, 0, 0, 0, 1, 2, 2) rank 7
(0, 0, 0, 0, 1, 3, 1) rank 8
(0, 0, 0, 0, 1, 4, 0) rank 9
[...]
(3, 2, 0, 0, 0, 0, 0) rank 449
(4, 0, 0, 0, 0, 0, 1) rank 450
(4, 0, 0, 0, 0, 1, 0) rank 451
(4, 0, 0, 0, 1, 0, 0) rank 452
(4, 0, 0, 1, 0, 0, 0) rank 453
(4, 0, 1, 0, 0, 0, 0) rank 454
(4, 1, 0, 0, 0, 0, 0) rank 455
```
This challenge requires you to produce two pieces of code/functions.
* Given a rank, compute the corresponding array directly. Call this function `unrank()`
* Given an array, compute its rank. Call this function `rank()`
Your code should run in polynomial time. That is it shouldn't be brute force and more specifically it should take \$O(\ell^a s^b m^c)\$ time for fixed non-negative integers \$a, b, c\$. Any non-brute force method is likely to satisfy this requirement.
# Examples
```
unrank((7, 5, 4), 9) = (0, 0, 0, 0, 1, 4, 0)
rank((7, 5, 4), (4, 0, 0, 0, 0, 1, 0)) = 451
unrank((14,10, 8), 100001) = (0, 0, 0, 1, 0, 0, 1, 3, 1, 2, 0, 0, 2, 0)
rank((14, 10, 8), (2, 0, 1, 1, 2, 0, 0, 0, 2, 1, 1, 0, 0, 0)) = 1000001
```
Your score will be the total size for your code
# Bounty notes
The bounty will be awarded to the answer with the best time complexity. Current best is \$O(\ell s)\$ time first by @loopywait (with help from Bubbler).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~116~~ 105 bytes
~~32~~ 26 bytes of code are shared between the two programs, although I'm currently counting this separately for each program:
```
⊞υE⊕η¬ιF⊖θ⊞υE⊕ηΣ✂…§υι⊕κ±⊕ζ
```
Explanation:
```
⊞υE⊕η¬ι
```
Start with a list of a `1` followed by `s` `0`s. This represents the count of arrays of length `0` with sums of `0` to `s`.
```
F⊖θ
```
Extend the list of lists up to arrays of length `l-1`.
```
⊞υE⊕ηΣ✂…§υι⊕κ±⊕ζ
```
For each sum of `0` to `s` calculate the number of arrays with that sum.
~~63~~ 57 bytes for `unrank`:
```
⊞υE⊕η¬ιF⊖θ⊞υE⊕ηΣ✂…§υι⊕κ±⊕ζF⮌υ«≔⁰δW¬›§ιηε«≧⁻§ιηε≦⊖η≦⊕δ»⟦Iδ
```
[Try it online!](https://tio.run/##fY9PawIxEMXPu58ixxlIQaEHwZNsQTxYRI/iIWSnm2DM2vyxrcXPniZV2pVC5zIw896830glnOyFSWkVvYLI2VIcYWGlowPZQC0o5Oy5D6ARcVq/9I7BE/2uXxHZf9ZNPMDGaEnQfEhDjeqPMAsL29J7segsGVr2WOKoE4HuTp3xu24AazqR8wQxh3/W1cx73VkYcdZmRfWmtCEGBXruKF9yP4maswJFeDVWmfhqXutOBVhqGz1nf9TToXT4fhHcLwfQN5xLXa2ctgG2jfABWtzl6SWl7fiRs3GGnpRWapceTuYL "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⮌υ«
```
Loop over each element.
```
≔⁰δ
```
Start with a current element of zero.
```
W¬›§ιηε«
```
Repeat while there are still sufficient counts of shorter arrays:
```
≧⁻§ιηε
```
Subtract the count from the rank.
```
≦⊖η
```
Decrement the remaining sum.
```
≦⊕δ
```
Increment the current element.
```
»⟦Iδ
```
Output the current element.
~~53~~ 48 bytes for `rank`:
```
⊞υE⊕η¬ιF⊖θ⊞υE⊕ηΣ✂…§υι⊕κ±⊕ζPIΣEε↨¹Eι§§⮌υκ⁻Σ✂εκθ¹λ
```
[Try it online!](https://tio.run/##fU49b8IwEN35FTeepavUIIZKmWhYGIIQjIjBMtfGinGCY6O2f97YhIh26emsOz3f@1CNdKqTJsZtGBoMBLXscW2V4zNbzydsBMGm86iFEOXso3OAK35@X4SA/6j7cMa90Yqx@laGq6brcenX9sRfmaLTyW9KK7Idf0rPf6R@xL3KWR2M173T1mMlB49ZP/sywbscGIsxhiaYXKa54yu7dBGSQ5terW0Y8JkvKbQEF4IiZzDiUWWMh2KR0FeCN4LDnCBtxb3Hfez5BD6Q4zG@XM0N "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
PIΣEε↨¹Eι§§⮌υκ⁻Σ✂εκθ¹λ
```
For each element in the array to rank, get the count of arrays of the remaining length with sums of between the remaining sum including and excluding the current element.
It's possible to replace the shared code with a 51 byte version that reduces the time complexity by using a sliding window to calculate the counts of arrays with specific lengths and sums.
```
≔E⊕η¬ιτFθ«⊞υτ≔⟦⟧σ≔⁰δF⊕η«≧⁺§τκδ⊞σ먪‹κζ≧⁻§τ⁻κζδ»≔στ»F⮌υ«≔⁰δW¬›§ιηε«≧⁻§ιηε≦⊖η≦⊕δ»⟦Iδ
```
[Try it online!](https://tio.run/##bVDBasMwDD2nX6GjDB6ssMOgp7JBKawj9BpyCIlam2bOZjnd2Oi3e3GcZmmYL/aTn57eU6kKWzZF7f2aWR8N7op33JrS0hsZRxUqIeG1cahF93BitTg0FvBDwM8iSVtW2MZyMvRnuQSe4HsJVYB9261wr5F0AyN1r4/KYVq3LGHttqaiL3QSTmJQiOP4ivQBMBh7IWY8SfgWneBMbKfNTK2vDPRB6TJ65RjlEjPu6UyWCdtodJbnU@maooONpcKRxesYLSFsjcT/CWemRvZqSsVnGlcVCLefkz3@hUitNg6zp4IdViIPQbzPlg8Slp3px3CFk/u7c/0L "Charcoal – Try It Online") Link is to verbose version of code.
```
≔E⊕η¬ιτFθ«⊞υτ≔⟦⟧σ≔⁰δF⊕η«≧⁺§τκδ⊞σ먪‹κζ≧⁻§τ⁻κζδ»≔στ»PIΣEε↨¹Eι§§⮌υκ⁻Σ✂εκθ¹λ
```
[Try it online!](https://tio.run/##XZBNa8MwDIbPya/QUQYPlrLDoKdup8IySnsMOYTEbUxdp43sMjb62z07dvZRI7D0Ij2v7LZvxnZolHMrInnQWDZnXOt2FCehjeiwZxzeB4OS@cSwZb4fRsALg68821jq0UY5S/NVzYH@1I8culBOY//BEyPzhrF1Kw@9wY2yxGFl1roTH2g4HFkiRDuaK7kHDIu9CSI8cvhkHngHK6W@o01Kak@k28@uFJ9yy0urjDyPUht8bcjgzp6mjxEcXhoSWPDghPIXPd9bcRWj77Asbh79wvxOyVYEgje/cCiCv2LpLJ2riiev@u965lAtOPismCLmMRazmJS6dg9X9Q0 "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Python 3](https://docs.python.org/3/), 326,334 bytes (+8 to fix complexity @Bubbler)
```
def P(l,m,s,o):
*r,o=0,o+m*o[-1:]
for y,z in zip(o[:s+1],-~m*[0]+o):r[len(r):]=r[-1]+y-z,
return l*o and P(l-1,m,s,r[1:])+[o]
def R(p,L):
l,m,s=p;T=P(*p,[1,1]);r=0
for t,l in zip(T,L):r+=t[s]-t[s-l];s-=l
return r
def U(p,r):
l,m,s,*L=p;T=P(*p,[1,0])
for t in T:
j=m
while(t[s]<=r)*j:r-=t[s];s-=1;j-=1
L+=[m-j]
return L
```
[Try it online!](https://tio.run/##dY5NbsMgEEbX9SlYAh4kaGO1sssNvIiiZIVYRIrT2MJgjV1VyaJXd8Ft3XZRJH7EN/PeDNfpEvzDPJ@aM9lSBz2MEFiZEY4QtISQ9zwYoUqbkXNAcoUbaT25tQMNphxzZUG899xIm8c2NK7xFFlpNcYmm1/FDTKCzfSKnjgeyNGfkkeoxYQmgllugs3SADs6QJ3kyxx6qPZ6S/kARoGyrEItP4eYwH0PsU8NmOvJjFbEQzhbjUK7VYoL@RDJuJKB13/g0rIvcMLuYxnpdH8Xr7dL6xqa4M8aGe9KFIsqOVTVxSMW1bk2vejs6qznBGsTDI/@paGbokjy4zg2ONFW6x2lj7CBgsFhfbWMsSwbsPUTjb9qA0@gJIs7rZj9RFLCvYRCLinn6le8@xv/V83mDw "Python 3 – Try It Online")
[Old version](https://tio.run/##dY6xbsMgEIbn@ikYAR8StLFa2eUNPFRRMiGGSHESLGyss6sqGfrqLiSt2wxF4kD8d9/HcJ5OoX@a531zIG/UQweBlRnhCEFLCHnHgxGqtBk5BCRnuBDXk4sbaADx2XEjbR4H0Pimp8hKqzG22/wsLpARbKZ37Inngez6feILFQ1oIpDlJtgsadd0gDpJk33UQ7XRt58YBcqyCrW82SfwP/ZNmsBcT2a0IhbhbTUK7RcnXtHbiMYFDby@p0vLvsmJu4l9pNXdQzw@Ts43NNFfNTLeliiuriRRVRtLbKpzbTrR2kVazwnmEgx3/bGhq6JI9t04NjhRp/Wa0mdYQcFgu9wcYyzLBnT9ROOrWsELKMniTitmv5GU8CihkNeUc/UnXt/H/3Wz@Qs "Python 3 – Try It Online")
Doesn't feel very short, but maybe a byte count of "only" 3x the golfy languages is acceptable.
If I'm not mistaken, both R and U are O(lm).\*\*Nonsense!\*\*O(ls) using @Bubbler's suggestion.
The function P creates generalised Pascal's triangles where new rows are generated by taking sums of m+1 elements of the current (m=1 in the original Pascal's triangle). Generalising binomial coefficients which count sums made out a total of of *l*-*s* 0s and *s* 1s, the entries of the generalised triangles count sums of 0s,1s,...,*m*s with *l* terms and sum *s*.
Implementation notes: The output contains a few padding elements on the right end for convenience. By passing [1,0] or [1,1] for *o* we can choose between the plain triangle (used by U) or the partial row sums (used by R). To limit complexity we calculate only the first s+1 terms in every row.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 142 bytes
```
r(l,s,m,a)=y=x^m++\(x-1);sum(i=1,l,t=a[i];polcoef(y%x^t*y^(l-i),t+s-=t))
u(l,s,m,q)=a=vector(l);for(i=1,l,until(r(l,s,m,a)>q,a[i]++);a[i]--);a
```
[Try it online!](https://tio.run/##TY3dCoMwDEbv9xTeDNI1hVU2Jkj3Ik5BREeh/rdDn97FqdOS5oOT9qRJOy3ezTR1YLDHElOmRjUkJecvGIRkYe9K0EqiQavSSMdhU5uszgsYz0NiL2MCRmiGlvdCWcZObhW1TKXqk2e2JjULC4pF4yqrDez7ni3OXs5ZOKcQlFPT6cqCgwd6d/Ru6AWkXmC3w4ju9VCSevx/6EDSXBIP5vidg@UwjPztO5V/EPobXAnJpy8 "Pari/GP – Try It Online")
The rank is 0-indexed.
] |
[Question]
[
Al wanted to use my computer to do some simple calculations, so I lent him the use of my R terminal for a bit. He complained though, saying it wasn't set up how he liked it. I said "No problem Al, set it up how you like and I'll just revert it later." This suited Al, and I left him to it. Al isn't a big fan of online R implementations like TIO, they don't seem to support his preferred way of coding.
After a few minutes, I came back and asked how it went. "everything fine", he said. I glanced at his session and it didn't look fine to me — only one of the four results looked correct! But Al knows R inside out, he must have been telling the truth.
Here is a transcript of Al's R session, as it appeared on the screen (Al uses RStudio 1.1.463 and R 3.6.3 if it matters, but I don't think it does here). The question is, how did Al "set up" his session to produce this output?
```
## what did Al type here?
32+55
[1] 87
14*21
[1] 294
91/7
[1] 13
12-21
[1] -9
```
rules:
* Al only typed one function call which is somewhere in the standard R libraries.
* the function didn't import any code or refer to any external files (no `source`, `install.packages`, `library` etc..).
* Al didn't type `cat("55+23\n[1]......-9")`, it is something that could reasonably be interpreted as "setting up an R session"
scoring:
* the primary scoring criterion is the number of bytes in the answer. Ties will be broken in ASCII-order, that is, if two valid answers are the same length the winner is the one which is first "alphabetically" (according to ASCII ordering).
[Answer]
```
options(prompt="\U202E")
```
Uses [RTL Override](https://unicode-explorer.com/c/202E) at the end to make all following input appear reversed. I tried entering the raw character in a string but it turns into a period for some reason. Tested with RStudio 1.2.1335 and R 3.6.3 on Ubuntu 20.04, but does not work in my terminal GNOME Terminal 3.36.2 which appears to do some kind of character stripping unless the character is printable. Note that default R prompt is "> " which works in GNOME Terminal and can be replicated to make it less suspicious.
Also Al and R sound like "L" and "R".
[Answer]
# [R](https://www.r-project.org/), 28 bytes
```
Sys.setlocale("LC_ALL","ja")
```
[Try it online! (doesn't work)](https://tio.run/##K/r/P7iyWK84tSQnPzkxJ1VDycc53tHHR0lHKStRSfP/fwA "R – Try It Online")
I give it a try even if I don't know R and cannot test it on my computer.. If this doesn't work, please tell me and I will delete the answer, because it spoils the trick Al used
] |
[Question]
[
The challenge: compute the day of the week from a `MM-DD` representation of a day in this year (2021).
However, you have to write your program in the following subset of Python: (*I chose Python because it's popular and easy to understand even to the people who doesn't know the language. Obviously you can use another program in another language to generate the program, and you're encouraged to post the source code of that program*)
```
# This is the input. For example this represents the date 2021-01-28.
m1 = "0"
m2 = "1"
d1 = "2"
d2 = "8"
T = {
# `T` is a dict
# * each key must be a string of digits [0-9]
# * each value must be a single digit.
"1234": "1",
"5678": "2",
}
# The main program code.
# Each line must have the format:
# <variable_name> = T[<string formed by concatenating string literals or other variables>]
# Example:
variable_1 = T["12" + m1 + "3" + "4"]
output = T[variable_1]
# This must be exactly one `print` statement like this at the end of the program
print(output)
```
*Background: This is basically the only way [Preproc](https://tio.run/#preproc) (the C/C++ preprocessor) can parse tokens. [See how Boost's `BOOST_PP_INC_I` macro is implemented](https://github.com/boostorg/preprocessor/blob/aa8f347df2b189b14c4079c6fb7fa2819ac4a6f1/include/boost/preprocessor/arithmetic/inc.hpp#L31).*
More info:
* You can (and should!) submit multiple programs in one answer if the method that you use to generate these programs are similar.
* You can reassign variables, but doing that will not make your score better (than labeling each usage of the variables `a_1, a_2, a_3, ...`.
* To be clear (this is implied by the rules), you're not allowed to do `x = "0"` or `x = y + z`; only `x = T[...]` is allowed.
* The output should be `0` if the day is Monday, `1` if the day is Tuesday, ..., `6` if the day is Sunday.
* The program must not raise an error given valid input data.
### Winning criteria
Let `A` about the number of entries in the dict `T`, and `B` be the number of assignment instructions (excluding the input assignment instructions to `m1, m2, d1, d2` but including the final assignment to `output`).
You should minimize both `A` and `B`.
Note that you can make the length of the keys of the dict `T` arbitrarily long and it doesn't make the score worse; however it doesn't make the score better either.
Because there isn't a consensus on whether it's allowed to have 2 separate winning criteria, the method to calculate the score is described in [this meta answer ("**Solution 2**")](https://codegolf.meta.stackexchange.com/a/20720/69850), with the board size `10000 10000`. -- For example, if you have a program with `A=100` and `B=100`, enter into the input of the [score calculation program](https://tio.run/##hVFNb4MwDD2XX@FxCm2KQLuhpj9iV5ZDEGmJBgElVJRfz@zQL2nTxoE49vN7z84wj01v35fFdEPvRnCag589BzNqN/Z966PWWO1FucV06sfaWBk1HCbRqYEZO3LsSU/G1qptmYs/613MIfSUmUySaHAIYtRxj/Hs8UROGZ16F8Bg7K0pL2QRbRSH6l8FZN@slATHi/IeXYM6ZqBsDdUxQ0DQStUwaFuzkpDy7iD1ODP70rNoVVfVCq4FXMl28GXIlFP2rFmOgtqytStJClij0sgyl6Iz99Ka4I/yPqf7c2DS4kB43G@HJQhCGJPW2fWXIUlCLgBDgiqP10hDqppvehx@MQ/mROmDaORTOGwoMFNEnGuJwNVBTDKKnPaXdhTNdvp7/F2e4Aut6L1gL6NnkujMm3hBg269hgab9q9bQZ9bNu3y/Y9VhQeNPwJ9EdPjU5QsS57hB@Ef5Wv0DQ)
```
10000 10000
100 100
```
and the calculated result is 1970199.
### Recommended header format
```
## Score: (5, 1), (4, 2), (3, 3) -> 999, Combined score: 999, Combined score improvement: 99
```
* Score: The (A, B) parameters of your generated program(s), and (optionally) the computed score of all your generated programs.
* Combined score: the computed score of all the generated programs of the whole community (all answers posted so far) (you can easily calculate the "combined score" by taking the most recent/best combined score answer, then modify the score-list to add your program's scores. Also you should add a link to the score calculation program with your generated programs' scores as input)
* Combined score improvement: the difference between the most-recent computed score and the current combined score.
This is not a requirement, but just in case someone want to write a visualization/leaderboard script. (I intend to have it like [this](https://chat.stackexchange.com/transcript/message/57038635#57038635))
### [Table of all values](https://tio.run/##VY1BDoIwEEX3nGLCqo1IoK5g4c4ruG9kkEZpm2GMEsLZa4sxxr@Zv3j/jZ95cPYQghm9I4ZOM7IZMesdwegsD2AskLZXFHUBtdrVss0ghmn@lJREd3r@Y5tG/oAUT8ay6PNl87aVWpe4SRf2R1i@r8tUhKpUdGxkkdSyfCLeYhFyzeXmxdcFPcNZ3x94InLUgtfTlIXwBg "Python 3 – Try It Online")
### [Program to verify submissions](https://tio.run/##ZVHLboMwEDzjr3B8slVEgnsKkk9V@wVVL1UVIbwkVgJGxmmDEN9OvTwUNb0wq92Z2WXcdP5k6@dxLKyGVjHGyLvqyUDs1TdXr3RKtg8dSZBFTNVY56nOPXhTAdFQ0m9wpuy4qQPxgJOYoq/ISAS3BgoP@rDYtN7xVZtgweVOpjGtbO1PcbDtRPIDcA4FF4JEFc5kGATUUt1XkGh2PGhTeGPr3HUKS16lahapWacWqZYCz4GC420x/ScXq6X6N/pkc4t9kciUi3SjHn4uo40ztecle8vNBXRGp3NVf796WPeqfsbQeIyof2gMTBBSWjdlGiwnbJO2uRjP2ZZhzOvilxMUZ1MfZ26P340bkiQJHhF6TDmjicvrI/AQTSqfUrSIvOsQJlqI/w9pvxfZ@swl6yeXbCeHPhAR2fLiQQ@3AhpPP/LLFV6dsy7EkrctGcdf)
Note that this program does not verify that the provided program is inside the subset, only if the output is valid.
[Answer]
# Score: 679685 (`A=64`, `B=6`)
```
T = {
# three digits: first day of the month, 0-based (12 entries)
"001": "4", "002": "0", "003": "0", "004": "3", "005": "5", "006": "1", "007": "3", "008": "6", "009": "2", "010": "4", "011": "0", "012": "2",
# two digits ab: lookup table for (a + b) % 7 (52 entries)
"00": "0", "01": "1", "02": "2", "03": "3", "04": "4", "05": "5", "06": "6",
"10": "1", "11": "2", "12": "3", "13": "4", "14": "5", "15": "6", "16": "0",
"20": "2", "21": "3", "22": "4", "23": "5", "24": "6", "25": "0", "26": "1",
"30": "3", "31": "4", "32": "5", "33": "6", "34": "0", "35": "1", "36": "2",
"40": "4", "41": "5", "42": "6", "43": "0", "44": "1", "45": "2", "46": "3",
"50": "5", "51": "6", "52": "0", "53": "1", "54": "2", "55": "3", "56": "4",
"60": "6", "61": "0", "62": "1", "63": "2", "64": "3", "65": "4", "66": "5", "67": "6", "68": "0", "69": "1",
}
# (d2 + 6) % 7 = (d2 - 1) % 7
d2_0d1 = T["6" + d2]
# (d2 - 1 + 1*d1) % 7
d2_1d1 = T[d1 + d2_0d1]
# (d2 - 1 + 2*d1) % 7
d2_2d1 = T[d1 + d2_1d1]
# (d2 - 1 + 3*d1) % 7 = (d2 - 1 + 10*d1) % 7 = (d1d2 - 1) % 7
day_of_month = T[d1 + d2_2d1]
month_start = T["0" + m1 + m2]
output = T[month_start + day_of_month]
```
[Try it online!](https://tio.run/##ZZTdbqMwEIXv8xQjqkpkQyTP@CdtpL5F71YVIoI0aAtE4KiKVvvsWf@UMWlzdTCHj3PsCeerPQ29vHVYQEcFlAXUTtYEL9D254vN17dXp/@uwP0ewJ7GpoG6fW/ttIdjO04W6uoKw9HdaqAbensqQGwP1dTUkCNB09uxbaZ1AGRCYLaHTGWF1@S1iFoutPJaRq291lEbrzHq3cLz5LWJ@tlrChpFehdi4iPNnrnV5/DVCarDHj6G4c/lDLY6fDRwHEbIK9jAYQ2PsINc/@y0QKeElILIlFWlSItmZi4QiTF4wMTcARNjBwxKxqBiDGreBzRzpkgkwRhCxhAxhiRjSDGGNFcj3vxIlIIxMp2pJMZIyRipGCM1V5Pm7hgylY5LIWMUMUalGVGKMUpzNWXmTJGoBWM0MkansdOSMVoxRmuups2cKRKNYIxJE2WIMUYyxqQxNpqrGcOZzC7BnhLsmTf632r1ALn7M27AxOl7CZdbwHC5qqkUNbrV19@O42w1vc3POJNbwF918uKXt8Zg9c9@s9PSTt/s@MMuZ3sK5t8p7pbxLnF1LYdjGT4Ud3AK8LBeTrYabWwlfKvOezpfbbhY91EKt5bWDSy5b7fz2PY2j@b1TeBW4H8 "Python 3 – Try It Online") and try the [Generator / Testing program!](https://tio.run/##jVRNj9owEL3nV0yzqpIsASWhZSWkHLrnPXLbriKDHTCbL9mmLYry2@nY@SBhOcAJv3nv2fM0k@qsDmWxvFx4XpVCwY5krKBEWN1ZnqVlvb1CDM7vwoEZOOA8/7A2CNSNZVWi3AuS67KBNOPt9YrPsPAE6iAYA8r3XMk1pFxIBZScoUyxxCAvC3XwIZhviWQU3DACVijBmfQ6v7QULQt4AYIUe@aGPoRLb20B/oxjgo4@JPiKvoeFkbT0KIhQYQDPaD7ZGampE9QGXAdR45jCH5KdGJakEu5g3Go276j6wJrhGGjUaOrYNdYbew12bRiN7YMzCeNONn/LLhkg2zVkZfl5qkCRbcZAt@0SjGDrwXd4Affn3WT4NZWXPhGEj6OwAuAp8DheAcskg542DqLmTX3sMrjNweWzo3mCN5TvZPFgHje0cSRxX1hg7oJXLk6bp4eumcboOHh@ApdGWFy14cTmOIfQHC0aJQENEd282ysbaTT66DVIQiB8pldu2HFpaKhae0OPxvTohh5@oS97@vVh@s5gAoeTF5NzUqZJO@dj88iYGzyRiuBWmq4C3VWuOblurTyp6tSWxtQZjH0/THKPr1NxyrdMaDke5aO7pf31fg/uU5vR8OET90z1UzZcPNMrN523XF8R4YL7QPEvBmeGdljeea11YbvHg4r9Yzu3GxzvChMpGWbTRxZ37/C1Yws28A0/Zy3cmIZuruouqgQvlOv8yjJQTOISV9qbOmjFMxbj53MhFWVCeB0V43M3Hu4B5TvFy4KIc7/T90Sdqm/hcvkP)
[Answer]
# Combined score: [440654](https://tio.run/##hVFNb4MwDD0vv8LrKbQpgrXrJNTsR@zKcggiHdEgoISq7a/v7LB@SJs2DsSxn997dobT2PRudT7bbuj9CN4ICKcgwI7Gj33fBtZaZ4Is55hOw1hbp1gj4CA7PXDrRoE96c66Wrct97P3ejETEHvKTCUJGzyCOHVcYjx7PJFTsV3vIxis@27KC1WwBy2g@lcB2R8mSoLjRYeArkG/ZqBdDdVrhoColephMK7mJSHVxUEacGb@aU6y1V1VazgWcCTb0ZclU167D8NzFDSOT11JUsAUlVaVuZKdvZSmhLiWlzndbwOTlgDC4347LEEUwpi0Pny/H5Ik5iIwJqhyfY00pqrTt56AX8yD3VF6Kxt1E44biswUEedUInC1lQfFmDdh346ymR/@Hn@RJ/hCE3op@d3omSI6@yjv0GDaYKDBpuX9VtDnnB8W@fLHquKDzt4ifTGjx6coOZ/zDD@If7ZZwZo9Z7B6YesNrFds/QTPT18 "Python 3 – Try It Online") (63, 4), (50, 37), (46, 43), (42, 52)
## First program: A=~~64~~ 63, B=4
```
T = {
# 0mm: lookup table for a such that a1 % 7 is the first day of the month
"001": "1", "002": "2", "003": "2", "004": "3", "005": "6", "006": "0", "007": "3", "008": "4", "009": "5", "010": "1", "011": "2", "012": "5",
# ab0: lookup table for ab % 7, "010" already happens to be the correct answer "1"
"000": "0", "020": "2", "030": "3", "040": "4", "050": "5", "060": "6", "070": "0", "080": "1", "090": "2",
"100": "3", "110": "4", "120": "5", "130": "6", "140": "0", "150": "1", "160": "2",
"200": "6", "210": "0", "220": "1", "230": "2", "240": "3", "250": "4", "260": "5",
"300": "2", "310": "3", "320": "4", "330": "5", "340": "6", "350": "0", "360": "1",
"400": "5", "410": "6", "420": "0", "430": "1", "440": "2", "450": "3", "460": "4",
"500": "1", "510": "2", "520": "3", "530": "4", "540": "5", "550": "6", "560": "0",
"600": "4", "610": "5", "620": "6", "630": "0", "640": "1", "650": "2", "660": "3",
}
m = T["0" + m1 + m2]
d3 = T["0" + d2 + "0"]
d = T[d1 + d3 + "0"]
output = T[m + d + "0"]
```
[Try it online!](https://tio.run/##bZTdattAEIXv9RSDSiEhLszM/jgJ5C1yV0pZWwoysX6QZYIpfXZ3V@voqKW6EEeze85@RyANl6npO3NtZUOtbujnhqooK6UXOnTDebq7v75G/augeH0hbttnOvb9@3mgKeyONb31IwU6nfcNTU2YKAh9pS0dTvExrh7G00RVuFD/Ng/avpuaOaxklvKZSik3SWvSmrVZaZu0ydol7bP2SXPW29Wex6Rt1k9Ju1kL4ywR5It@7rk1DDv@X8NdanULonAc61BdqAnDUHexaU@7eq6378ex3se30J0@6jEd@NmVwauM8w2D3TLYHYPdM3pvVzmPq05PS2Y@UBjBIggWRbAYBItFsDgEi/8nWBkmFZhUYVKDhmoBog4g6vmvN18ahskITEZhMgb0xgLEOIAYv4DkYMswWYHJKkzWgN5agFgHEOsXkBzsGCYnMDmFyRnQOwsQ5wDi/AKSgz3D5AUmrzB5A3pvAeIdQLxfQIrfRdHGD/n1e7TQA7WSbvqjqMxqGr/7h5QZx/O0SrvijtuwP0/xlzCvtGnhNr8O46Gb7vLq/ZXlG8sf "Python 3 – Try It Online") Verification: [Try it online!](https://tio.run/##bVTbbtpAEH3GX7HZqpKtILr3BCQ/Ve0XRH2JqsjYS7CCL1ovTRDi2@mOFxhKyoP3MDPnzJmxvP3Or7tWHsuuskNOKT0@kZzsExJ@XwhrmgXZdN3btie@WG4sWXWOFGTYlmvi14UnBSdfyQOph/A3ZGs3eFIVO9KtxkDTtX49ilHGOF0QyukUsAAsIpZXWAGWEWvAJmIDmEX8cFXzCFhFPAesR8wZ9uIc9bk415wmLJbsfxMuYaqTECk2zhbVjqyLvrdtmLQjSzuOV3bO2TJsoR3erYOG51kZ@hUM@0uG3hVD75qhd8Nw7ocrncermeYXzdiQMxTmHIW5QGEuUZgrFOYahbm5ERYMSYIjSQgkCYkTCoVGhEYjwrB/Nk8lQ5LkSJICSVKie6nQiNRoRJqLkSisGJIUR5ISSFIS3SuFRpRGI8pcjERhzZCkOZK0QJKW6F4rNKI1GtHmYiQKG4Ykw5FkBJKMRPdGoRGj0YgxFyPJIUma8CE/PQcKuScNh4f4nVTyKlqJ8AgwhMdoBVWh4hTstr7f@jHTQOIUP4ZbIknqpu8cfOve@rqxSWVX5I919WqX1m2gvUBmSuBeyRbJxH704UOx1UsUzQfv0jN3BiAVTPBpvDCmcIVks3dr3wJIsyyZNJATIRHOSuTYIplExZeqLn3dtYXb5QDThueRlEdefqJWIgM7tkzB25R8omdnyfxT6pnGUFjOpF6dqHf5zXAL0ru69emK/izqja0WZLSb79H14dw338czBG5XtL8JHGiWJHA7ge8gOZ7DbOg3tU/pNwprPjf@vrblW92@xto9PO/cYTabBY0JaIx7BhFXtK82Davh4p6DxMS7HRxjGVzl10XzebY4v@YV3Y8qCyYO@1AIJz298cC3H6XtPflVbLb2h3OdC2sphuH4Fw "Python 3 – Try It Online") Edit: Reduced A by 1 thanks to a hint from @user202729.
## Second program: A=~~56~~ ~~52~~ 50, B=37
```
T = {
# 0th day of the month (12 entries)
"01": "3", "02": "6", "03": "6", "04": "2", "05": "4", "06": "0", "07": "2", "08": "5", "09": "1", "10": "3", "11": "6", "12": "1",
# abcde: (a%7%2^b^c)+d+e%7>>1 (30 entries) e.g. a0001: a%7%2 abc01: a^b^c 00cde: c+d+e>>1 0000e: e%7>>1
"01001": "1", "01101": "0", "10001": "1", "10101": "0", "11001": "0", "11101": "1",
"20001": "0", "30001": "1", "40001": "0", "50001": "1", "60001": "0", "70001": "0", "80001": "1", "90001": "0",
"00000": "0", "00001": "0", "00010": "0", "00011": "1", "00100": "0", "00101": "1", "00110": "1", "00111": "1",
"00002": "1", "00003": "1", "00004": "2", "00005": "2", "00006": "3", "00007": "0", "00008": "0", "00009": "1",
# Convert from binary (modulo 7) (8 entries)
"000": "0", "001": "1", "010": "2", "011": "3", "100": "4", "101": "5", "110": "6", "111": "0",
}
# Get the day of the month and convert it to binary.
m = T[m1 + m2]
mh = T["0000" + m]
m0 = T[m + "0001"]
m1 = T[mh + "0001"]
m2 = T["0000" + mh]
# Convert the ones day digit (modulo 7) to binary.
d2h = T["0000" + d2]
d20 = T[d2 + "0001"]
d21 = T[d2h + "0001"]
d22 = T["0000" + d2h]
# Convert the tens day digit to binary.
d10 = T[d1 + "0001"]
d11 = T["0000" + d1]
# Multiply by three (modulo 7)
o = T["000" + d10 + d11]
o1 = T[d10 + d11 + "001"]
o0 = T[o + d10 + "001"]
o1 = T[o + o1 + "001"]
o2 = T[o + d11 + "001"]
# Add the ones.
c0 = T["000" + o0 + d20]
o0 = T[o0 + d20 + "001"]
c1 = T["00" + c0 + o1 + d21]
o1 = T[c0 + o1 + d21 + "01"]
o3 = T["00" + c1 + o2 + d22]
o2 = T[c1 + o2 + d22 + "01"]
# Add the month offset.
c0 = T["000" + o0 + m0]
o0 = T[o0 + m0 + "001"]
c1 = T["00" + c0 + o1 + m1]
o1 = T[c0 + o1 + m1 + "01"]
c2 = T["00" + c1 + o2 + m2]
o2 = T[c1 + o2 + m2 + "01"]
o4 = T["000" + o3 + c2]
o3 = T[o3 + c2 + "001"]
# Reduce modulo 7.
c0 = T["000" + o0 + o3]
c1 = T["00" + c0 + o1 + o4]
o1 = T[c0 + o1 + o4 + "01"]
c2 = T["000" + c1 + o2]
o2 = T[c1 + o2 + "001"]
o0 = T[o0 + o3 + c2 + "01"]
# Convert from binary.
output = T[o2 + o1 + o0]
```
Verification: [Try it online!](https://tio.run/##jVbdi9s4EH@O/wrVZcFmg09Ssskm4MJRevfUl1LupWwXryVvTGMr2Mq1IeRv385I/pCcHJwf4vn6zfxmRjI5nPRO1Yu3XAnZpmEYvn0lKTkHBJ73hOodEdmJqILonSSVqsEQMU5krZtStrGJCykLtyRchHMQOYorIy5GcYkiN@IDiksjrlCkRlyPAY8oPhhxgyJDkdGhBGNDXsb7gI5w9pILuSVRdre@499fvufxvbiXd@sPHxiJFnTgTWTympCMUsq2xAQj1CiIIpSaPDmiEQuBFHSbqWsan7EBTOVqzPNZzsxqzMMx6vksbtCY12CIWCecMacoo66PUc/HqKc5RcduuFOZ2u0NmrNAeB48bTVuH561N5NHT9v4Rbk3tIXHf@n5HjzfyvOtPe3Ri9y4vu6MfFT1v7LRpGhURV7KOmtOJKqUOO4VWcckepyebn9dzvTpOAY2XoFuvctuC8Np7la76jYwsLoEwXvyt9Tmil3dtqwWJO8YlxCjOspJUMFF/fqtYuSeVPwpqHZGN3MO0QYmakNAM4cwBBOzpp1r4xPk7gkp9XNCLqqWreEmyldg4YzLIST4hIIAWoJbEoI7FQVnnXHnWfkUf81Ey9pl4pZnXSXm5mRskpOZlJ@Pe10e9ifycoK0jZROT4EaIBZBzS8AVUe7t9hCWEfZ2mqI7@1ssCs3nDvhjh2Y/SnEMPIkyKnHRZnCnI4FO8OYIh8aRkBO@8ow84GOZzVQQ2rhIdGhuInhA2PPOiAd2vbUqqJopb5Nv5qwr/4H@eoW92qknvPb1KtbzKuRuFr6/BaI5sMoOt3bzxcpjjn2aU/L7R7V4r97UcsbvQCR617cZm70MTl6dGzAXcyNz10SqKM@HLXF8YEDfXqDfwBBUFYHBQiRaanLSgZCFgRylMUpKmvAPaNnTvA/Q7wNZvLXQeZaimebNW11E/XYBIWIU87m9mjM8fLGyU8pf4AQxXEwq9DHwQFvwdOxRDCzGZ9FmetSIfUUxahiqQWlFpd2UMFjpCPzCLnNyRU87lOmV65voTXB1GZl0UHfpZPmtuTQlLWOivCvrNxLsSWGbnoeWV/6uunZvsEwHdF5YriEcRAUqjEzhZTm3SbtYV/qKPwjxDH3hT/uZP6jrF9t7Bl/3zWXJEkgxwxz2CsISZqsfpURjIbxe4YpZro54cuE4UfUDdps4m2/5iI8myxbyi9nCMR32G0c8PJXLg@a/JPtj/JT06gGxpK17dtv "Python 3 – Try It Online") Edit: Reduced A by ~~4~~ 6 thanks to a hint from @user202729.
Note that for the next two variants I used letters to code the lookup type for my sanity but obviously distinct digits work just as well.
## Third program: A=~~52~~ ~~48~~ 46, B=43
Simply performs the XORs two bits at a time instead of three. Verification: [Try it online!](https://tio.run/##jVZNb9s4ED1bv4JlEEBCDC1JO3ZsQAWKorunvRRFL0UaSCIVCzVFQ6a3NQz/9uzwQxItp0hzkGYe5@O9Ial4d9Qb1cxeSsXFPsMYv3xBGTpFCP5ukFwjojeI50ekKqQ3AknVABBThkSj21rsExuKJaF4jfAMT43NjL1w9iyw58Zmzr439tzZC2MTZy@DmAdj3zt7ZWxqbUqGXpQO9SnrYjz/vCj5GsX57fKWfS@Su/KO3y7fv6coZoteABLpc4pyQuga2UhIs/b3AhFboDCJJo0QAq6r4XQDQnryYNPAoeGK42n5w0KwQkm44nI6Z1ihJAijdOjT02BDInFD75xh6uDch86inyM4y1DHQ@isLsaKWShzFhKbhyv34coiXFmGzkMYtiIjZTeoWKOPqvlPtBpVrZKoqJu8PaJYKn7YKrRMUPwwOoxFuClFWL/wm8K8Mxzawm/K3Du0P3qF35SFdwaC5yi6Qf8IbW/G1SXJG45Kz7yGGOWpp5GEK/blG5YY3SFJzYM9RnLjUMPdQIAQi0jwzAHCgFCHbAKIXaZtHg2pbmKGjWrE3rLj9TPwCAYXUOLssj0HRpw5ApwN7TijHtuEIBslX7PQoglZhK2pb0ODipReVqS24L@Hra532yMqjlC0FSJQE6kuwyUQ@4Q85Rl3iO1imijXV/XhHqY9rIJgFgQPMJD6wHk/5zQqSUhD2Z6MDM080BcoO6EmvCRdU5jzwMQDY4ZDtIdnYSmDK2Yz2UDfA2NZQ/SVLHeYVVXthX5Vnhypk2@KkyNt8k1pJXtVmhwpk28KU/ML/jNTjvWj8344hs@CH0ozBXfMXp2Amv1WqppfSoX@fyo11Pp7PY6N5azI1dEmnUivRx307qBdgwJ3pRwz8vgC//@jqJY7BZeW51roWoqIiwrBNa6rY1w3kP1kVqbI/GJI1tFE/NqJUgv@5Gpne93GXW5qjJgRRqfuHE3NJyBJfwrxA4w4SaKJNGsMFuDNWTa0iCau4hOvS10r87HIjBlLmrmkzOVlPpWzxNARZWy4TdFVetKVzK6WvmEHwZAmdeVT32UjcWu0a@tGxxX@O6@3An4LWLrZaWB97vpmJ/cGYDyi0wg44ySKKtXamUJJ@96n@9221jH@C5sxd40/bkT5o26eXezJPN@15zRNocbE1HD3FYq0efMsYhgNZXfUlJjo9mheNsx8isOg1SpZd9tc4ZOtsibsfIJA88Z@xyFf/CrFTqOv@fYgPrWtamEs@X7/8j8 "Python 3 – Try It Online")
## Fourth program: A=~~48~~ ~~44~~ 42, B=52
Also performs the additions two bits at a time instead of three. Verification: [Try it online!](https://tio.run/##rVbLbts4FF1bX8EqCCAhhoakHTsWoAKDojOrbopiNkUaSCQVCzVFQ6KnNQx/e8qXRFrxtF1MFuLh0X2ce0Qp3h/lVrSLFyIo64s4jl8@gQKcIqD@bgDPAZRbQMsjEDWQWwa4aBWRIAxYK7uG9akJjTlEcQ7iRTzXGGu8sngR4KXG2OJ7jZcWrzSGFq@DmAeN7y3eaIwMRtD3QsjXR3iIcfrLiuQgKW/Xt/hLld6R2/Xbtwgk2KsHLHvOQAlRDkyYStHwSwWgzq3uiM6AUGGbbceFEI6SoR3dYhTwVpqRjGCA0Rg/FBt1K7wIsPcLWr8cXo3zQ@uXE/IQ4M2FFzEOVC4CNcuAvw/4VcCvA/wQxGzg5SQ3oMrBO9H@yzoJ6k5wUDVt2R1BwgU97ARYpyB5mJycKvSygkH5yrmJ3cafsArZnKXboPGcVMjmrNzGCzxH0Q34m0lzjF@d6LKlgDjljYoRTnoWcfU@fPoc8xjcAY70BT9GfGtZJUMzioCG4GqnHnysCGSJrWfwRc72UQsa3NJKRMt6o4w2z0pDYFogh@KL1lSJodg2p3jsRTFy1Dbg8GXmawWStaGCsC1yPZCvh9BFPWTKfTjsZLPfHUF1VCU7xoI5IuESbDw0V5UmnNiB0S10B2F7ijHasmhkhQ/FQejIKj1/Ujqam0UEBgqEaYehb@SIIZ2gMBqZm17uQAzRZRBMoMkYSxAdVU4mcEEjuwi7YVMc@8kccbUbMhljCbWE3bCXIPAVa@wbIOq6Z/KaRXziEP@JQXziD//f7CF4ag@fuMN/bo4rQPCvzRHLsJd2k0zcJaGRHxk9EO2jPefXPBQLP6zZL//bQzLx0Mf@hjP@LFyfDHoTBJy@aHAY104mDnJ/kLZ4NdpuNcHHF/VrIYoavhfq60FLyWTDWURZDdT3pKmPSdOq7Cd9Zw7074s0j2bs@54RyeiTrV30skuG3EyDBEOM5vZMzvW3KM2@MfZVgSRNoxnX97C6oVaKC98imtmKT7QhshH6q1VomHBU2KTC5hUuleJUy2Ek0drm4FV6OpQsXt36HFtKmTRrapf6ppgMl4N917QyqeO/ymbHaA6M3OLkVZ@HvsXJroqYWnSaEOc4jaJadMZTVdKsfdbvd41M4j9ibfPQ@N2Wka9N@2xjT/r6pjtnWaZqzHQN@@6rIl3ZPrNEWYPwHdIlZrI76sWE6f8JYdBmk@bDY67jk6mSQ3w@qUC9xu6Jq3z2nbC9BP@UuwN733WiU7aUff/yAw "Python 3 – Try It Online")
## "Fifth" program: A=20, B=360
I noticed that @thedefault.'s answer, while having an impressively low A, had a very high B. I looked to see what I could do to remedy that. My first step was to invert the sense of the first half of the lookup table, so that `not` could be calculated directly rather than by adding `9` and taking the sign. The next step was to swap the two halves of the table, so that `and` only took two operations, and the decimal output function could also be simplified. However this meant that `or` was too inefficient, particularly when used to add modulo 7, so I rewrote that to reduce the inefficiency. This is the generator program that I ended up with:
```
import functools
print("""
T = {
"00": "1", "01":"2", "02":"3", "03":"4", "04":"5", "05":"6", "06":"7", "07":"8", "08":"9", "09":"0"
,
"10": "1", "11":"0", "12":"0", "13":"0", "14":"0", "15":"0", "16":"0", "17":"0", "18":"0", "19":"0"
}
""".strip())
varn = 0
def getvar():
global varn
ret = 'v' + str(varn)
varn += 1
return ret
def enot(bi):
ni = getvar()
print('%s = T["1"+%s]' % (ni, bi))
return ni
def enand(b1, b2): #result may be greater than 1, use enot(eand()) to avoid this
ni = getvar()
print('%s = T[%s+%s]' % (ni, b1, b2))
return ni
def eand(b1, b2):
return enot(enand(b1, b2))
def eor(b1, b2):
return enot(eand(enot(b1), enot(b2)))
def eeqt(vi):
#return array of 10 bits for all 10 possible values of vi.
res = []
vi2 = getvar()
for i in range(10):
ni = getvar()
print('%s = T["1"+%s]' % (ni, vi if i == 0 else vi2))
print('%s = T["0"+%s]' % (vi2, vi if i == 0 else vi2))
res.append(ni)
#e.g. res[0] = !(x == 0)
return res[:1] + res[:0:-1]
def edmon(m1, m2):
#decode m2 using eeqt. create 2 more variables for november and december
#m1 is already boolean
m2p = eeqt(m2)
v11 = eand(m2p[1], m1)
m2p[1] = eand(m2p[1], enot(m1))
v12 = eand(m2p[2], m1)
m2p[2] = eand(m2p[2], enot(m1))
return m2p[1:] + m2p[:1] + [v11, v12]
def elmon(dmon):
#given output of edmon, find first day modulo 7.
#table = [4, 0, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2]
d0 = enot(eand(eand(enot(dmon[1]), enot(dmon[2])), enot(dmon[10])))
d1 = dmon[5]
d2 = eor(dmon[8], dmon[11])
d3 = eor(dmon[3], dmon[6])
d4 = eor(dmon[0], dmon[9])
d5 = dmon[4]
d6 = dmon[7]
return [d0,d1,d2,d3,d4,d5,d6]
def eadd7(v1, v2):
vals = [['"1"'] for _ in range(7)]
for a in range(7):
for b in range(7):
if v2[b] != '"0"':
vals[(a+b)%7].append(enand(v1[a], v2[b]))
return [enot(functools.reduce(eand, a)) for a in vals]
def emod7(d2):
et = eeqt(d2)
et[0] = eor(et[0], et[7])
et[1] = eor(et[1], et[8])
et[2] = eor(et[2], et[9])
return et[:7]
def e3mod7(d1):
et = eeqt(d1) # can't optimize because entries are obtained like 0, 9, 8, ... and 1 must be reached
#d1 < 4. multiply by 3
#0*3 = 0, 1*3 = 3, 2*3 = 6, 3*3 = 2
return [et[0], '"0"', et[3], et[1], '"0"', '"0"', et[2]]
def eout(m7):
val = '"1"'
ni = getvar()
for x in m7:
print('%s = T[%s+%s]' % (ni, x, val))
val = ni
return ni
def solve(m1, m2, d1, d2):
mmod7 = elmon(edmon(m1, m2))
dmod7 = eadd7(emod7(d2), e3mod7(d1))
res = eadd7(mmod7, dmod7)
res = res[1:] + res[:1]
return eout(res[::-1])
print('output =', solve('m1', 'm2', 'd1', 'd2'))
```
[Answer]
# Score: 26310277, A=20, B=2618, combined score 332345
The `A` is fairly likely to be optimal. (of course, the `B` is terrible)
```
T = {
"00": "0", "01":"1", "02":"1", "03":"1", "04":"1", "05":"1", "06":"1", "07":"1", "08":"1", "09":"1",
"10": "1", "11":"2", "12":"3", "13":"4", "14":"5", "15":"6", "16":"7", "17":"8", "18":"9", "19":"0"
}
v1 = T["0"+m2]
v0 = T["1"+m2]
v2 = T["0"+v0]
v0 = T["1"+v0]
v3 = T["0"+v0]
v0 = T["1"+v0]
v4 = T["0"+v0]
v0 = T["1"+v0]
v5 = T["0"+v0]
v0 = T["1"+v0]
v6 = T["0"+v0]
v0 = T["1"+v0]
v7 = T["0"+v0]
v0 = T["1"+v0]
v8 = T["0"+v0]
v0 = T["1"+v0]
v9 = T["0"+v0]
v0 = T["1"+v0]
v10 = T["0"+v0]
v0 = T["1"+v0]
v11 = T["1"+m1]
v11 = T["1"+v11]
v11 = T["1"+v11]
v11 = T["1"+v11]
v11 = T["1"+v11]
v11 = T["1"+v11]
v11 = T["1"+v11]
v11 = T["1"+v11]
v11 = T["1"+v11]
v12 = T["0"+v11]
v13 = T[v10+v12]
v13 = T["0"+v13]
v14 = T[v10+m1]
v14 = T["0"+v14]
v15 = T["1"+m1]
v15 = T["1"+v15]
v15 = T["1"+v15]
v15 = T["1"+v15]
v15 = T["1"+v15]
v15 = T["1"+v15]
v15 = T["1"+v15]
v15 = T["1"+v15]
v15 = T["1"+v15]
v16 = T["0"+v15]
v17 = T[v9+v16]
v17 = T["0"+v17]
v18 = T[v9+m1]
v18 = T["0"+v18]
v19 = T[v18+v8]
v20 = T["1"+v19]
v20 = T["1"+v20]
v20 = T["1"+v20]
v20 = T["1"+v20]
v20 = T["1"+v20]
v20 = T["1"+v20]
v20 = T["1"+v20]
v20 = T["1"+v20]
v20 = T["0"+v20]
v21 = T["1"+v20]
v21 = T["1"+v21]
v21 = T["1"+v21]
v21 = T["1"+v21]
v21 = T["1"+v21]
v21 = T["1"+v21]
v21 = T["1"+v21]
v21 = T["1"+v21]
v21 = T["1"+v21]
v22 = T["0"+v21]
v23 = T[v22+v13]
v24 = T["1"+v23]
v24 = T["1"+v24]
v24 = T["1"+v24]
v24 = T["1"+v24]
v24 = T["1"+v24]
v24 = T["1"+v24]
v24 = T["1"+v24]
v24 = T["1"+v24]
v24 = T["0"+v24]
v25 = T["1"+v24]
v25 = T["1"+v25]
v25 = T["1"+v25]
v25 = T["1"+v25]
v25 = T["1"+v25]
v25 = T["1"+v25]
v25 = T["1"+v25]
v25 = T["1"+v25]
v25 = T["1"+v25]
v26 = T["0"+v25]
v27 = T[v2+v17]
v28 = T["1"+v27]
v28 = T["1"+v28]
v28 = T["1"+v28]
v28 = T["1"+v28]
v28 = T["1"+v28]
v28 = T["1"+v28]
v28 = T["1"+v28]
v28 = T["1"+v28]
v28 = T["0"+v28]
v29 = T["1"+v28]
v29 = T["1"+v29]
v29 = T["1"+v29]
v29 = T["1"+v29]
v29 = T["1"+v29]
v29 = T["1"+v29]
v29 = T["1"+v29]
v29 = T["1"+v29]
v29 = T["1"+v29]
v30 = T["0"+v29]
v31 = T[v7+v4]
v32 = T["1"+v31]
v32 = T["1"+v32]
v32 = T["1"+v32]
v32 = T["1"+v32]
v32 = T["1"+v32]
v32 = T["1"+v32]
v32 = T["1"+v32]
v32 = T["1"+v32]
v32 = T["0"+v32]
v33 = T["1"+v32]
v33 = T["1"+v33]
v33 = T["1"+v33]
v33 = T["1"+v33]
v33 = T["1"+v33]
v33 = T["1"+v33]
v33 = T["1"+v33]
v33 = T["1"+v33]
v33 = T["1"+v33]
v34 = T["0"+v33]
v35 = T[v14+v1]
v36 = T["1"+v35]
v36 = T["1"+v36]
v36 = T["1"+v36]
v36 = T["1"+v36]
v36 = T["1"+v36]
v36 = T["1"+v36]
v36 = T["1"+v36]
v36 = T["1"+v36]
v36 = T["0"+v36]
v37 = T["1"+v36]
v37 = T["1"+v37]
v37 = T["1"+v37]
v37 = T["1"+v37]
v37 = T["1"+v37]
v37 = T["1"+v37]
v37 = T["1"+v37]
v37 = T["1"+v37]
v37 = T["1"+v37]
v38 = T["0"+v37]
v40 = T["0"+d2]
v39 = T["1"+d2]
v41 = T["0"+v39]
v39 = T["1"+v39]
v42 = T["0"+v39]
v39 = T["1"+v39]
v43 = T["0"+v39]
v39 = T["1"+v39]
v44 = T["0"+v39]
v39 = T["1"+v39]
v45 = T["0"+v39]
v39 = T["1"+v39]
v46 = T["0"+v39]
v39 = T["1"+v39]
v47 = T["0"+v39]
v39 = T["1"+v39]
v48 = T["0"+v39]
v39 = T["1"+v39]
v49 = T["0"+v39]
v39 = T["1"+v39]
v50 = T["1"+v40]
v50 = T["1"+v50]
v50 = T["1"+v50]
v50 = T["1"+v50]
v50 = T["1"+v50]
v50 = T["1"+v50]
v50 = T["1"+v50]
v50 = T["1"+v50]
v50 = T["1"+v50]
v51 = T["0"+v50]
v52 = T["1"+v49]
v52 = T["1"+v52]
v52 = T["1"+v52]
v52 = T["1"+v52]
v52 = T["1"+v52]
v52 = T["1"+v52]
v52 = T["1"+v52]
v52 = T["1"+v52]
v52 = T["1"+v52]
v53 = T["0"+v52]
v54 = T["1"+v48]
v54 = T["1"+v54]
v54 = T["1"+v54]
v54 = T["1"+v54]
v54 = T["1"+v54]
v54 = T["1"+v54]
v54 = T["1"+v54]
v54 = T["1"+v54]
v54 = T["1"+v54]
v55 = T["0"+v54]
v56 = T["1"+v47]
v56 = T["1"+v56]
v56 = T["1"+v56]
v56 = T["1"+v56]
v56 = T["1"+v56]
v56 = T["1"+v56]
v56 = T["1"+v56]
v56 = T["1"+v56]
v56 = T["1"+v56]
v57 = T["0"+v56]
v58 = T["1"+v46]
v58 = T["1"+v58]
v58 = T["1"+v58]
v58 = T["1"+v58]
v58 = T["1"+v58]
v58 = T["1"+v58]
v58 = T["1"+v58]
v58 = T["1"+v58]
v58 = T["1"+v58]
v59 = T["0"+v58]
v60 = T["1"+v45]
v60 = T["1"+v60]
v60 = T["1"+v60]
v60 = T["1"+v60]
v60 = T["1"+v60]
v60 = T["1"+v60]
v60 = T["1"+v60]
v60 = T["1"+v60]
v60 = T["1"+v60]
v61 = T["0"+v60]
v62 = T["1"+v44]
v62 = T["1"+v62]
v62 = T["1"+v62]
v62 = T["1"+v62]
v62 = T["1"+v62]
v62 = T["1"+v62]
v62 = T["1"+v62]
v62 = T["1"+v62]
v62 = T["1"+v62]
v63 = T["0"+v62]
v64 = T["1"+v43]
v64 = T["1"+v64]
v64 = T["1"+v64]
v64 = T["1"+v64]
v64 = T["1"+v64]
v64 = T["1"+v64]
v64 = T["1"+v64]
v64 = T["1"+v64]
v64 = T["1"+v64]
v65 = T["0"+v64]
v66 = T["1"+v42]
v66 = T["1"+v66]
v66 = T["1"+v66]
v66 = T["1"+v66]
v66 = T["1"+v66]
v66 = T["1"+v66]
v66 = T["1"+v66]
v66 = T["1"+v66]
v66 = T["1"+v66]
v67 = T["0"+v66]
v68 = T["1"+v41]
v68 = T["1"+v68]
v68 = T["1"+v68]
v68 = T["1"+v68]
v68 = T["1"+v68]
v68 = T["1"+v68]
v68 = T["1"+v68]
v68 = T["1"+v68]
v68 = T["1"+v68]
v69 = T["0"+v68]
v70 = T[v51+v65]
v70 = T["0"+v70]
v71 = T[v53+v67]
v71 = T["0"+v71]
v72 = T[v55+v69]
v72 = T["0"+v72]
v74 = T["0"+d1]
v73 = T["1"+d1]
v75 = T["0"+v73]
v73 = T["1"+v73]
v76 = T["0"+v73]
v73 = T["1"+v73]
v77 = T["0"+v73]
v73 = T["1"+v73]
v78 = T["0"+v73]
v73 = T["1"+v73]
v79 = T["0"+v73]
v73 = T["1"+v73]
v80 = T["0"+v73]
v73 = T["1"+v73]
v81 = T["0"+v73]
v73 = T["1"+v73]
v82 = T["0"+v73]
v73 = T["1"+v73]
v83 = T["0"+v73]
v73 = T["1"+v73]
v84 = T["1"+v74]
v84 = T["1"+v84]
v84 = T["1"+v84]
v84 = T["1"+v84]
v84 = T["1"+v84]
v84 = T["1"+v84]
v84 = T["1"+v84]
v84 = T["1"+v84]
v84 = T["1"+v84]
v85 = T["0"+v84]
v86 = T["1"+v81]
v86 = T["1"+v86]
v86 = T["1"+v86]
v86 = T["1"+v86]
v86 = T["1"+v86]
v86 = T["1"+v86]
v86 = T["1"+v86]
v86 = T["1"+v86]
v86 = T["1"+v86]
v87 = T["0"+v86]
v88 = T["1"+v83]
v88 = T["1"+v88]
v88 = T["1"+v88]
v88 = T["1"+v88]
v88 = T["1"+v88]
v88 = T["1"+v88]
v88 = T["1"+v88]
v88 = T["1"+v88]
v88 = T["1"+v88]
v89 = T["0"+v88]
v90 = T["1"+v82]
v90 = T["1"+v90]
v90 = T["1"+v90]
v90 = T["1"+v90]
v90 = T["1"+v90]
v90 = T["1"+v90]
v90 = T["1"+v90]
v90 = T["1"+v90]
v90 = T["1"+v90]
v91 = T["0"+v90]
v92 = T[v70+v85]
v93 = T["1"+v92]
v93 = T["1"+v93]
v93 = T["1"+v93]
v93 = T["1"+v93]
v93 = T["1"+v93]
v93 = T["1"+v93]
v93 = T["1"+v93]
v93 = T["1"+v93]
v93 = T["0"+v93]
v94 = T["1"+v93]
v94 = T["1"+v94]
v94 = T["1"+v94]
v94 = T["1"+v94]
v94 = T["1"+v94]
v94 = T["1"+v94]
v94 = T["1"+v94]
v94 = T["1"+v94]
v94 = T["1"+v94]
v95 = T["0"+v94]
v96 = T[v70+"0"]
v97 = T["1"+v96]
v97 = T["1"+v97]
v97 = T["1"+v97]
v97 = T["1"+v97]
v97 = T["1"+v97]
v97 = T["1"+v97]
v97 = T["1"+v97]
v97 = T["1"+v97]
v97 = T["0"+v97]
v98 = T["1"+v97]
v98 = T["1"+v98]
v98 = T["1"+v98]
v98 = T["1"+v98]
v98 = T["1"+v98]
v98 = T["1"+v98]
v98 = T["1"+v98]
v98 = T["1"+v98]
v98 = T["1"+v98]
v99 = T["0"+v98]
v100 = T[v70+v87]
v101 = T["1"+v100]
v101 = T["1"+v101]
v101 = T["1"+v101]
v101 = T["1"+v101]
v101 = T["1"+v101]
v101 = T["1"+v101]
v101 = T["1"+v101]
v101 = T["1"+v101]
v101 = T["0"+v101]
v102 = T["1"+v101]
v102 = T["1"+v102]
v102 = T["1"+v102]
v102 = T["1"+v102]
v102 = T["1"+v102]
v102 = T["1"+v102]
v102 = T["1"+v102]
v102 = T["1"+v102]
v102 = T["1"+v102]
v103 = T["0"+v102]
v104 = T[v70+v89]
v105 = T["1"+v104]
v105 = T["1"+v105]
v105 = T["1"+v105]
v105 = T["1"+v105]
v105 = T["1"+v105]
v105 = T["1"+v105]
v105 = T["1"+v105]
v105 = T["1"+v105]
v105 = T["0"+v105]
v106 = T["1"+v105]
v106 = T["1"+v106]
v106 = T["1"+v106]
v106 = T["1"+v106]
v106 = T["1"+v106]
v106 = T["1"+v106]
v106 = T["1"+v106]
v106 = T["1"+v106]
v106 = T["1"+v106]
v107 = T["0"+v106]
v108 = T[v70+"0"]
v109 = T["1"+v108]
v109 = T["1"+v109]
v109 = T["1"+v109]
v109 = T["1"+v109]
v109 = T["1"+v109]
v109 = T["1"+v109]
v109 = T["1"+v109]
v109 = T["1"+v109]
v109 = T["0"+v109]
v110 = T["1"+v109]
v110 = T["1"+v110]
v110 = T["1"+v110]
v110 = T["1"+v110]
v110 = T["1"+v110]
v110 = T["1"+v110]
v110 = T["1"+v110]
v110 = T["1"+v110]
v110 = T["1"+v110]
v111 = T["0"+v110]
v112 = T[v70+"0"]
v113 = T["1"+v112]
v113 = T["1"+v113]
v113 = T["1"+v113]
v113 = T["1"+v113]
v113 = T["1"+v113]
v113 = T["1"+v113]
v113 = T["1"+v113]
v113 = T["1"+v113]
v113 = T["0"+v113]
v114 = T["1"+v113]
v114 = T["1"+v114]
v114 = T["1"+v114]
v114 = T["1"+v114]
v114 = T["1"+v114]
v114 = T["1"+v114]
v114 = T["1"+v114]
v114 = T["1"+v114]
v114 = T["1"+v114]
v115 = T["0"+v114]
v116 = T[v70+v91]
v117 = T["1"+v116]
v117 = T["1"+v117]
v117 = T["1"+v117]
v117 = T["1"+v117]
v117 = T["1"+v117]
v117 = T["1"+v117]
v117 = T["1"+v117]
v117 = T["1"+v117]
v117 = T["0"+v117]
v118 = T["1"+v117]
v118 = T["1"+v118]
v118 = T["1"+v118]
v118 = T["1"+v118]
v118 = T["1"+v118]
v118 = T["1"+v118]
v118 = T["1"+v118]
v118 = T["1"+v118]
v118 = T["1"+v118]
v119 = T["0"+v118]
v120 = T[v71+v85]
v121 = T["1"+v120]
v121 = T["1"+v121]
v121 = T["1"+v121]
v121 = T["1"+v121]
v121 = T["1"+v121]
v121 = T["1"+v121]
v121 = T["1"+v121]
v121 = T["1"+v121]
v121 = T["0"+v121]
v122 = T["1"+v121]
v122 = T["1"+v122]
v122 = T["1"+v122]
v122 = T["1"+v122]
v122 = T["1"+v122]
v122 = T["1"+v122]
v122 = T["1"+v122]
v122 = T["1"+v122]
v122 = T["1"+v122]
v123 = T["0"+v122]
v124 = T[v71+"0"]
v125 = T["1"+v124]
v125 = T["1"+v125]
v125 = T["1"+v125]
v125 = T["1"+v125]
v125 = T["1"+v125]
v125 = T["1"+v125]
v125 = T["1"+v125]
v125 = T["1"+v125]
v125 = T["0"+v125]
v126 = T["1"+v125]
v126 = T["1"+v126]
v126 = T["1"+v126]
v126 = T["1"+v126]
v126 = T["1"+v126]
v126 = T["1"+v126]
v126 = T["1"+v126]
v126 = T["1"+v126]
v126 = T["1"+v126]
v127 = T["0"+v126]
v128 = T[v71+v87]
v129 = T["1"+v128]
v129 = T["1"+v129]
v129 = T["1"+v129]
v129 = T["1"+v129]
v129 = T["1"+v129]
v129 = T["1"+v129]
v129 = T["1"+v129]
v129 = T["1"+v129]
v129 = T["0"+v129]
v130 = T["1"+v129]
v130 = T["1"+v130]
v130 = T["1"+v130]
v130 = T["1"+v130]
v130 = T["1"+v130]
v130 = T["1"+v130]
v130 = T["1"+v130]
v130 = T["1"+v130]
v130 = T["1"+v130]
v131 = T["0"+v130]
v132 = T[v71+v89]
v133 = T["1"+v132]
v133 = T["1"+v133]
v133 = T["1"+v133]
v133 = T["1"+v133]
v133 = T["1"+v133]
v133 = T["1"+v133]
v133 = T["1"+v133]
v133 = T["1"+v133]
v133 = T["0"+v133]
v134 = T["1"+v133]
v134 = T["1"+v134]
v134 = T["1"+v134]
v134 = T["1"+v134]
v134 = T["1"+v134]
v134 = T["1"+v134]
v134 = T["1"+v134]
v134 = T["1"+v134]
v134 = T["1"+v134]
v135 = T["0"+v134]
v136 = T[v71+"0"]
v137 = T["1"+v136]
v137 = T["1"+v137]
v137 = T["1"+v137]
v137 = T["1"+v137]
v137 = T["1"+v137]
v137 = T["1"+v137]
v137 = T["1"+v137]
v137 = T["1"+v137]
v137 = T["0"+v137]
v138 = T["1"+v137]
v138 = T["1"+v138]
v138 = T["1"+v138]
v138 = T["1"+v138]
v138 = T["1"+v138]
v138 = T["1"+v138]
v138 = T["1"+v138]
v138 = T["1"+v138]
v138 = T["1"+v138]
v139 = T["0"+v138]
v140 = T[v71+"0"]
v141 = T["1"+v140]
v141 = T["1"+v141]
v141 = T["1"+v141]
v141 = T["1"+v141]
v141 = T["1"+v141]
v141 = T["1"+v141]
v141 = T["1"+v141]
v141 = T["1"+v141]
v141 = T["0"+v141]
v142 = T["1"+v141]
v142 = T["1"+v142]
v142 = T["1"+v142]
v142 = T["1"+v142]
v142 = T["1"+v142]
v142 = T["1"+v142]
v142 = T["1"+v142]
v142 = T["1"+v142]
v142 = T["1"+v142]
v143 = T["0"+v142]
v144 = T[v71+v91]
v145 = T["1"+v144]
v145 = T["1"+v145]
v145 = T["1"+v145]
v145 = T["1"+v145]
v145 = T["1"+v145]
v145 = T["1"+v145]
v145 = T["1"+v145]
v145 = T["1"+v145]
v145 = T["0"+v145]
v146 = T["1"+v145]
v146 = T["1"+v146]
v146 = T["1"+v146]
v146 = T["1"+v146]
v146 = T["1"+v146]
v146 = T["1"+v146]
v146 = T["1"+v146]
v146 = T["1"+v146]
v146 = T["1"+v146]
v147 = T["0"+v146]
v148 = T[v72+v85]
v149 = T["1"+v148]
v149 = T["1"+v149]
v149 = T["1"+v149]
v149 = T["1"+v149]
v149 = T["1"+v149]
v149 = T["1"+v149]
v149 = T["1"+v149]
v149 = T["1"+v149]
v149 = T["0"+v149]
v150 = T["1"+v149]
v150 = T["1"+v150]
v150 = T["1"+v150]
v150 = T["1"+v150]
v150 = T["1"+v150]
v150 = T["1"+v150]
v150 = T["1"+v150]
v150 = T["1"+v150]
v150 = T["1"+v150]
v151 = T["0"+v150]
v152 = T[v72+"0"]
v153 = T["1"+v152]
v153 = T["1"+v153]
v153 = T["1"+v153]
v153 = T["1"+v153]
v153 = T["1"+v153]
v153 = T["1"+v153]
v153 = T["1"+v153]
v153 = T["1"+v153]
v153 = T["0"+v153]
v154 = T["1"+v153]
v154 = T["1"+v154]
v154 = T["1"+v154]
v154 = T["1"+v154]
v154 = T["1"+v154]
v154 = T["1"+v154]
v154 = T["1"+v154]
v154 = T["1"+v154]
v154 = T["1"+v154]
v155 = T["0"+v154]
v156 = T[v72+v87]
v157 = T["1"+v156]
v157 = T["1"+v157]
v157 = T["1"+v157]
v157 = T["1"+v157]
v157 = T["1"+v157]
v157 = T["1"+v157]
v157 = T["1"+v157]
v157 = T["1"+v157]
v157 = T["0"+v157]
v158 = T["1"+v157]
v158 = T["1"+v158]
v158 = T["1"+v158]
v158 = T["1"+v158]
v158 = T["1"+v158]
v158 = T["1"+v158]
v158 = T["1"+v158]
v158 = T["1"+v158]
v158 = T["1"+v158]
v159 = T["0"+v158]
v160 = T[v72+v89]
v161 = T["1"+v160]
v161 = T["1"+v161]
v161 = T["1"+v161]
v161 = T["1"+v161]
v161 = T["1"+v161]
v161 = T["1"+v161]
v161 = T["1"+v161]
v161 = T["1"+v161]
v161 = T["0"+v161]
v162 = T["1"+v161]
v162 = T["1"+v162]
v162 = T["1"+v162]
v162 = T["1"+v162]
v162 = T["1"+v162]
v162 = T["1"+v162]
v162 = T["1"+v162]
v162 = T["1"+v162]
v162 = T["1"+v162]
v163 = T["0"+v162]
v164 = T[v72+"0"]
v165 = T["1"+v164]
v165 = T["1"+v165]
v165 = T["1"+v165]
v165 = T["1"+v165]
v165 = T["1"+v165]
v165 = T["1"+v165]
v165 = T["1"+v165]
v165 = T["1"+v165]
v165 = T["0"+v165]
v166 = T["1"+v165]
v166 = T["1"+v166]
v166 = T["1"+v166]
v166 = T["1"+v166]
v166 = T["1"+v166]
v166 = T["1"+v166]
v166 = T["1"+v166]
v166 = T["1"+v166]
v166 = T["1"+v166]
v167 = T["0"+v166]
v168 = T[v72+"0"]
v169 = T["1"+v168]
v169 = T["1"+v169]
v169 = T["1"+v169]
v169 = T["1"+v169]
v169 = T["1"+v169]
v169 = T["1"+v169]
v169 = T["1"+v169]
v169 = T["1"+v169]
v169 = T["0"+v169]
v170 = T["1"+v169]
v170 = T["1"+v170]
v170 = T["1"+v170]
v170 = T["1"+v170]
v170 = T["1"+v170]
v170 = T["1"+v170]
v170 = T["1"+v170]
v170 = T["1"+v170]
v170 = T["1"+v170]
v171 = T["0"+v170]
v172 = T[v72+v91]
v173 = T["1"+v172]
v173 = T["1"+v173]
v173 = T["1"+v173]
v173 = T["1"+v173]
v173 = T["1"+v173]
v173 = T["1"+v173]
v173 = T["1"+v173]
v173 = T["1"+v173]
v173 = T["0"+v173]
v174 = T["1"+v173]
v174 = T["1"+v174]
v174 = T["1"+v174]
v174 = T["1"+v174]
v174 = T["1"+v174]
v174 = T["1"+v174]
v174 = T["1"+v174]
v174 = T["1"+v174]
v174 = T["1"+v174]
v175 = T["0"+v174]
v176 = T[v57+v85]
v177 = T["1"+v176]
v177 = T["1"+v177]
v177 = T["1"+v177]
v177 = T["1"+v177]
v177 = T["1"+v177]
v177 = T["1"+v177]
v177 = T["1"+v177]
v177 = T["1"+v177]
v177 = T["0"+v177]
v178 = T["1"+v177]
v178 = T["1"+v178]
v178 = T["1"+v178]
v178 = T["1"+v178]
v178 = T["1"+v178]
v178 = T["1"+v178]
v178 = T["1"+v178]
v178 = T["1"+v178]
v178 = T["1"+v178]
v179 = T["0"+v178]
v180 = T[v57+"0"]
v181 = T["1"+v180]
v181 = T["1"+v181]
v181 = T["1"+v181]
v181 = T["1"+v181]
v181 = T["1"+v181]
v181 = T["1"+v181]
v181 = T["1"+v181]
v181 = T["1"+v181]
v181 = T["0"+v181]
v182 = T["1"+v181]
v182 = T["1"+v182]
v182 = T["1"+v182]
v182 = T["1"+v182]
v182 = T["1"+v182]
v182 = T["1"+v182]
v182 = T["1"+v182]
v182 = T["1"+v182]
v182 = T["1"+v182]
v183 = T["0"+v182]
v184 = T[v57+v87]
v185 = T["1"+v184]
v185 = T["1"+v185]
v185 = T["1"+v185]
v185 = T["1"+v185]
v185 = T["1"+v185]
v185 = T["1"+v185]
v185 = T["1"+v185]
v185 = T["1"+v185]
v185 = T["0"+v185]
v186 = T["1"+v185]
v186 = T["1"+v186]
v186 = T["1"+v186]
v186 = T["1"+v186]
v186 = T["1"+v186]
v186 = T["1"+v186]
v186 = T["1"+v186]
v186 = T["1"+v186]
v186 = T["1"+v186]
v187 = T["0"+v186]
v188 = T[v57+v89]
v189 = T["1"+v188]
v189 = T["1"+v189]
v189 = T["1"+v189]
v189 = T["1"+v189]
v189 = T["1"+v189]
v189 = T["1"+v189]
v189 = T["1"+v189]
v189 = T["1"+v189]
v189 = T["0"+v189]
v190 = T["1"+v189]
v190 = T["1"+v190]
v190 = T["1"+v190]
v190 = T["1"+v190]
v190 = T["1"+v190]
v190 = T["1"+v190]
v190 = T["1"+v190]
v190 = T["1"+v190]
v190 = T["1"+v190]
v191 = T["0"+v190]
v192 = T[v57+"0"]
v193 = T["1"+v192]
v193 = T["1"+v193]
v193 = T["1"+v193]
v193 = T["1"+v193]
v193 = T["1"+v193]
v193 = T["1"+v193]
v193 = T["1"+v193]
v193 = T["1"+v193]
v193 = T["0"+v193]
v194 = T["1"+v193]
v194 = T["1"+v194]
v194 = T["1"+v194]
v194 = T["1"+v194]
v194 = T["1"+v194]
v194 = T["1"+v194]
v194 = T["1"+v194]
v194 = T["1"+v194]
v194 = T["1"+v194]
v195 = T["0"+v194]
v196 = T[v57+"0"]
v197 = T["1"+v196]
v197 = T["1"+v197]
v197 = T["1"+v197]
v197 = T["1"+v197]
v197 = T["1"+v197]
v197 = T["1"+v197]
v197 = T["1"+v197]
v197 = T["1"+v197]
v197 = T["0"+v197]
v198 = T["1"+v197]
v198 = T["1"+v198]
v198 = T["1"+v198]
v198 = T["1"+v198]
v198 = T["1"+v198]
v198 = T["1"+v198]
v198 = T["1"+v198]
v198 = T["1"+v198]
v198 = T["1"+v198]
v199 = T["0"+v198]
v200 = T[v57+v91]
v201 = T["1"+v200]
v201 = T["1"+v201]
v201 = T["1"+v201]
v201 = T["1"+v201]
v201 = T["1"+v201]
v201 = T["1"+v201]
v201 = T["1"+v201]
v201 = T["1"+v201]
v201 = T["0"+v201]
v202 = T["1"+v201]
v202 = T["1"+v202]
v202 = T["1"+v202]
v202 = T["1"+v202]
v202 = T["1"+v202]
v202 = T["1"+v202]
v202 = T["1"+v202]
v202 = T["1"+v202]
v202 = T["1"+v202]
v203 = T["0"+v202]
v204 = T[v59+v85]
v205 = T["1"+v204]
v205 = T["1"+v205]
v205 = T["1"+v205]
v205 = T["1"+v205]
v205 = T["1"+v205]
v205 = T["1"+v205]
v205 = T["1"+v205]
v205 = T["1"+v205]
v205 = T["0"+v205]
v206 = T["1"+v205]
v206 = T["1"+v206]
v206 = T["1"+v206]
v206 = T["1"+v206]
v206 = T["1"+v206]
v206 = T["1"+v206]
v206 = T["1"+v206]
v206 = T["1"+v206]
v206 = T["1"+v206]
v207 = T["0"+v206]
v208 = T[v59+"0"]
v209 = T["1"+v208]
v209 = T["1"+v209]
v209 = T["1"+v209]
v209 = T["1"+v209]
v209 = T["1"+v209]
v209 = T["1"+v209]
v209 = T["1"+v209]
v209 = T["1"+v209]
v209 = T["0"+v209]
v210 = T["1"+v209]
v210 = T["1"+v210]
v210 = T["1"+v210]
v210 = T["1"+v210]
v210 = T["1"+v210]
v210 = T["1"+v210]
v210 = T["1"+v210]
v210 = T["1"+v210]
v210 = T["1"+v210]
v211 = T["0"+v210]
v212 = T[v59+v87]
v213 = T["1"+v212]
v213 = T["1"+v213]
v213 = T["1"+v213]
v213 = T["1"+v213]
v213 = T["1"+v213]
v213 = T["1"+v213]
v213 = T["1"+v213]
v213 = T["1"+v213]
v213 = T["0"+v213]
v214 = T["1"+v213]
v214 = T["1"+v214]
v214 = T["1"+v214]
v214 = T["1"+v214]
v214 = T["1"+v214]
v214 = T["1"+v214]
v214 = T["1"+v214]
v214 = T["1"+v214]
v214 = T["1"+v214]
v215 = T["0"+v214]
v216 = T[v59+v89]
v217 = T["1"+v216]
v217 = T["1"+v217]
v217 = T["1"+v217]
v217 = T["1"+v217]
v217 = T["1"+v217]
v217 = T["1"+v217]
v217 = T["1"+v217]
v217 = T["1"+v217]
v217 = T["0"+v217]
v218 = T["1"+v217]
v218 = T["1"+v218]
v218 = T["1"+v218]
v218 = T["1"+v218]
v218 = T["1"+v218]
v218 = T["1"+v218]
v218 = T["1"+v218]
v218 = T["1"+v218]
v218 = T["1"+v218]
v219 = T["0"+v218]
v220 = T[v59+"0"]
v221 = T["1"+v220]
v221 = T["1"+v221]
v221 = T["1"+v221]
v221 = T["1"+v221]
v221 = T["1"+v221]
v221 = T["1"+v221]
v221 = T["1"+v221]
v221 = T["1"+v221]
v221 = T["0"+v221]
v222 = T["1"+v221]
v222 = T["1"+v222]
v222 = T["1"+v222]
v222 = T["1"+v222]
v222 = T["1"+v222]
v222 = T["1"+v222]
v222 = T["1"+v222]
v222 = T["1"+v222]
v222 = T["1"+v222]
v223 = T["0"+v222]
v224 = T[v59+"0"]
v225 = T["1"+v224]
v225 = T["1"+v225]
v225 = T["1"+v225]
v225 = T["1"+v225]
v225 = T["1"+v225]
v225 = T["1"+v225]
v225 = T["1"+v225]
v225 = T["1"+v225]
v225 = T["0"+v225]
v226 = T["1"+v225]
v226 = T["1"+v226]
v226 = T["1"+v226]
v226 = T["1"+v226]
v226 = T["1"+v226]
v226 = T["1"+v226]
v226 = T["1"+v226]
v226 = T["1"+v226]
v226 = T["1"+v226]
v227 = T["0"+v226]
v228 = T[v59+v91]
v229 = T["1"+v228]
v229 = T["1"+v229]
v229 = T["1"+v229]
v229 = T["1"+v229]
v229 = T["1"+v229]
v229 = T["1"+v229]
v229 = T["1"+v229]
v229 = T["1"+v229]
v229 = T["0"+v229]
v230 = T["1"+v229]
v230 = T["1"+v230]
v230 = T["1"+v230]
v230 = T["1"+v230]
v230 = T["1"+v230]
v230 = T["1"+v230]
v230 = T["1"+v230]
v230 = T["1"+v230]
v230 = T["1"+v230]
v231 = T["0"+v230]
v232 = T[v61+v85]
v233 = T["1"+v232]
v233 = T["1"+v233]
v233 = T["1"+v233]
v233 = T["1"+v233]
v233 = T["1"+v233]
v233 = T["1"+v233]
v233 = T["1"+v233]
v233 = T["1"+v233]
v233 = T["0"+v233]
v234 = T["1"+v233]
v234 = T["1"+v234]
v234 = T["1"+v234]
v234 = T["1"+v234]
v234 = T["1"+v234]
v234 = T["1"+v234]
v234 = T["1"+v234]
v234 = T["1"+v234]
v234 = T["1"+v234]
v235 = T["0"+v234]
v236 = T[v61+"0"]
v237 = T["1"+v236]
v237 = T["1"+v237]
v237 = T["1"+v237]
v237 = T["1"+v237]
v237 = T["1"+v237]
v237 = T["1"+v237]
v237 = T["1"+v237]
v237 = T["1"+v237]
v237 = T["0"+v237]
v238 = T["1"+v237]
v238 = T["1"+v238]
v238 = T["1"+v238]
v238 = T["1"+v238]
v238 = T["1"+v238]
v238 = T["1"+v238]
v238 = T["1"+v238]
v238 = T["1"+v238]
v238 = T["1"+v238]
v239 = T["0"+v238]
v240 = T[v61+v87]
v241 = T["1"+v240]
v241 = T["1"+v241]
v241 = T["1"+v241]
v241 = T["1"+v241]
v241 = T["1"+v241]
v241 = T["1"+v241]
v241 = T["1"+v241]
v241 = T["1"+v241]
v241 = T["0"+v241]
v242 = T["1"+v241]
v242 = T["1"+v242]
v242 = T["1"+v242]
v242 = T["1"+v242]
v242 = T["1"+v242]
v242 = T["1"+v242]
v242 = T["1"+v242]
v242 = T["1"+v242]
v242 = T["1"+v242]
v243 = T["0"+v242]
v244 = T[v61+v89]
v245 = T["1"+v244]
v245 = T["1"+v245]
v245 = T["1"+v245]
v245 = T["1"+v245]
v245 = T["1"+v245]
v245 = T["1"+v245]
v245 = T["1"+v245]
v245 = T["1"+v245]
v245 = T["0"+v245]
v246 = T["1"+v245]
v246 = T["1"+v246]
v246 = T["1"+v246]
v246 = T["1"+v246]
v246 = T["1"+v246]
v246 = T["1"+v246]
v246 = T["1"+v246]
v246 = T["1"+v246]
v246 = T["1"+v246]
v247 = T["0"+v246]
v248 = T[v61+"0"]
v249 = T["1"+v248]
v249 = T["1"+v249]
v249 = T["1"+v249]
v249 = T["1"+v249]
v249 = T["1"+v249]
v249 = T["1"+v249]
v249 = T["1"+v249]
v249 = T["1"+v249]
v249 = T["0"+v249]
v250 = T["1"+v249]
v250 = T["1"+v250]
v250 = T["1"+v250]
v250 = T["1"+v250]
v250 = T["1"+v250]
v250 = T["1"+v250]
v250 = T["1"+v250]
v250 = T["1"+v250]
v250 = T["1"+v250]
v251 = T["0"+v250]
v252 = T[v61+"0"]
v253 = T["1"+v252]
v253 = T["1"+v253]
v253 = T["1"+v253]
v253 = T["1"+v253]
v253 = T["1"+v253]
v253 = T["1"+v253]
v253 = T["1"+v253]
v253 = T["1"+v253]
v253 = T["0"+v253]
v254 = T["1"+v253]
v254 = T["1"+v254]
v254 = T["1"+v254]
v254 = T["1"+v254]
v254 = T["1"+v254]
v254 = T["1"+v254]
v254 = T["1"+v254]
v254 = T["1"+v254]
v254 = T["1"+v254]
v255 = T["0"+v254]
v256 = T[v61+v91]
v257 = T["1"+v256]
v257 = T["1"+v257]
v257 = T["1"+v257]
v257 = T["1"+v257]
v257 = T["1"+v257]
v257 = T["1"+v257]
v257 = T["1"+v257]
v257 = T["1"+v257]
v257 = T["0"+v257]
v258 = T["1"+v257]
v258 = T["1"+v258]
v258 = T["1"+v258]
v258 = T["1"+v258]
v258 = T["1"+v258]
v258 = T["1"+v258]
v258 = T["1"+v258]
v258 = T["1"+v258]
v258 = T["1"+v258]
v259 = T["0"+v258]
v260 = T[v63+v85]
v261 = T["1"+v260]
v261 = T["1"+v261]
v261 = T["1"+v261]
v261 = T["1"+v261]
v261 = T["1"+v261]
v261 = T["1"+v261]
v261 = T["1"+v261]
v261 = T["1"+v261]
v261 = T["0"+v261]
v262 = T["1"+v261]
v262 = T["1"+v262]
v262 = T["1"+v262]
v262 = T["1"+v262]
v262 = T["1"+v262]
v262 = T["1"+v262]
v262 = T["1"+v262]
v262 = T["1"+v262]
v262 = T["1"+v262]
v263 = T["0"+v262]
v264 = T[v63+"0"]
v265 = T["1"+v264]
v265 = T["1"+v265]
v265 = T["1"+v265]
v265 = T["1"+v265]
v265 = T["1"+v265]
v265 = T["1"+v265]
v265 = T["1"+v265]
v265 = T["1"+v265]
v265 = T["0"+v265]
v266 = T["1"+v265]
v266 = T["1"+v266]
v266 = T["1"+v266]
v266 = T["1"+v266]
v266 = T["1"+v266]
v266 = T["1"+v266]
v266 = T["1"+v266]
v266 = T["1"+v266]
v266 = T["1"+v266]
v267 = T["0"+v266]
v268 = T[v63+v87]
v269 = T["1"+v268]
v269 = T["1"+v269]
v269 = T["1"+v269]
v269 = T["1"+v269]
v269 = T["1"+v269]
v269 = T["1"+v269]
v269 = T["1"+v269]
v269 = T["1"+v269]
v269 = T["0"+v269]
v270 = T["1"+v269]
v270 = T["1"+v270]
v270 = T["1"+v270]
v270 = T["1"+v270]
v270 = T["1"+v270]
v270 = T["1"+v270]
v270 = T["1"+v270]
v270 = T["1"+v270]
v270 = T["1"+v270]
v271 = T["0"+v270]
v272 = T[v63+v89]
v273 = T["1"+v272]
v273 = T["1"+v273]
v273 = T["1"+v273]
v273 = T["1"+v273]
v273 = T["1"+v273]
v273 = T["1"+v273]
v273 = T["1"+v273]
v273 = T["1"+v273]
v273 = T["0"+v273]
v274 = T["1"+v273]
v274 = T["1"+v274]
v274 = T["1"+v274]
v274 = T["1"+v274]
v274 = T["1"+v274]
v274 = T["1"+v274]
v274 = T["1"+v274]
v274 = T["1"+v274]
v274 = T["1"+v274]
v275 = T["0"+v274]
v276 = T[v63+"0"]
v277 = T["1"+v276]
v277 = T["1"+v277]
v277 = T["1"+v277]
v277 = T["1"+v277]
v277 = T["1"+v277]
v277 = T["1"+v277]
v277 = T["1"+v277]
v277 = T["1"+v277]
v277 = T["0"+v277]
v278 = T["1"+v277]
v278 = T["1"+v278]
v278 = T["1"+v278]
v278 = T["1"+v278]
v278 = T["1"+v278]
v278 = T["1"+v278]
v278 = T["1"+v278]
v278 = T["1"+v278]
v278 = T["1"+v278]
v279 = T["0"+v278]
v280 = T[v63+"0"]
v281 = T["1"+v280]
v281 = T["1"+v281]
v281 = T["1"+v281]
v281 = T["1"+v281]
v281 = T["1"+v281]
v281 = T["1"+v281]
v281 = T["1"+v281]
v281 = T["1"+v281]
v281 = T["0"+v281]
v282 = T["1"+v281]
v282 = T["1"+v282]
v282 = T["1"+v282]
v282 = T["1"+v282]
v282 = T["1"+v282]
v282 = T["1"+v282]
v282 = T["1"+v282]
v282 = T["1"+v282]
v282 = T["1"+v282]
v283 = T["0"+v282]
v284 = T[v63+v91]
v285 = T["1"+v284]
v285 = T["1"+v285]
v285 = T["1"+v285]
v285 = T["1"+v285]
v285 = T["1"+v285]
v285 = T["1"+v285]
v285 = T["1"+v285]
v285 = T["1"+v285]
v285 = T["0"+v285]
v286 = T["1"+v285]
v286 = T["1"+v286]
v286 = T["1"+v286]
v286 = T["1"+v286]
v286 = T["1"+v286]
v286 = T["1"+v286]
v286 = T["1"+v286]
v286 = T["1"+v286]
v286 = T["1"+v286]
v287 = T["0"+v286]
v288 = T[v95+v147]
v288 = T["0"+v288]
v289 = T[v288+v171]
v289 = T["0"+v289]
v290 = T[v289+v195]
v290 = T["0"+v290]
v291 = T[v290+v219]
v291 = T["0"+v291]
v292 = T[v291+v243]
v292 = T["0"+v292]
v293 = T[v292+v267]
v293 = T["0"+v293]
v294 = T[v99+v123]
v294 = T["0"+v294]
v295 = T[v294+v175]
v295 = T["0"+v295]
v296 = T[v295+v199]
v296 = T["0"+v296]
v297 = T[v296+v223]
v297 = T["0"+v297]
v298 = T[v297+v247]
v298 = T["0"+v298]
v299 = T[v298+v271]
v299 = T["0"+v299]
v300 = T[v103+v127]
v300 = T["0"+v300]
v301 = T[v300+v151]
v301 = T["0"+v301]
v302 = T[v301+v203]
v302 = T["0"+v302]
v303 = T[v302+v227]
v303 = T["0"+v303]
v304 = T[v303+v251]
v304 = T["0"+v304]
v305 = T[v304+v275]
v305 = T["0"+v305]
v306 = T[v107+v131]
v306 = T["0"+v306]
v307 = T[v306+v155]
v307 = T["0"+v307]
v308 = T[v307+v179]
v308 = T["0"+v308]
v309 = T[v308+v231]
v309 = T["0"+v309]
v310 = T[v309+v255]
v310 = T["0"+v310]
v311 = T[v310+v279]
v311 = T["0"+v311]
v312 = T[v111+v135]
v312 = T["0"+v312]
v313 = T[v312+v159]
v313 = T["0"+v313]
v314 = T[v313+v183]
v314 = T["0"+v314]
v315 = T[v314+v207]
v315 = T["0"+v315]
v316 = T[v315+v259]
v316 = T["0"+v316]
v317 = T[v316+v283]
v317 = T["0"+v317]
v318 = T[v115+v139]
v318 = T["0"+v318]
v319 = T[v318+v163]
v319 = T["0"+v319]
v320 = T[v319+v187]
v320 = T["0"+v320]
v321 = T[v320+v211]
v321 = T["0"+v321]
v322 = T[v321+v235]
v322 = T["0"+v322]
v323 = T[v322+v287]
v323 = T["0"+v323]
v324 = T[v119+v143]
v324 = T["0"+v324]
v325 = T[v324+v167]
v325 = T["0"+v325]
v326 = T[v325+v191]
v326 = T["0"+v326]
v327 = T[v326+v215]
v327 = T["0"+v327]
v328 = T[v327+v239]
v328 = T["0"+v328]
v329 = T[v328+v263]
v329 = T["0"+v329]
v330 = T["1"+v26]
v330 = T["1"+v330]
v330 = T["1"+v330]
v330 = T["1"+v330]
v330 = T["1"+v330]
v330 = T["1"+v330]
v330 = T["1"+v330]
v330 = T["1"+v330]
v330 = T["1"+v330]
v331 = T["0"+v330]
v332 = T["1"+v5]
v332 = T["1"+v332]
v332 = T["1"+v332]
v332 = T["1"+v332]
v332 = T["1"+v332]
v332 = T["1"+v332]
v332 = T["1"+v332]
v332 = T["1"+v332]
v332 = T["1"+v332]
v333 = T["0"+v332]
v334 = T["1"+v30]
v334 = T["1"+v334]
v334 = T["1"+v334]
v334 = T["1"+v334]
v334 = T["1"+v334]
v334 = T["1"+v334]
v334 = T["1"+v334]
v334 = T["1"+v334]
v334 = T["1"+v334]
v335 = T["0"+v334]
v336 = T["1"+v34]
v336 = T["1"+v336]
v336 = T["1"+v336]
v336 = T["1"+v336]
v336 = T["1"+v336]
v336 = T["1"+v336]
v336 = T["1"+v336]
v336 = T["1"+v336]
v336 = T["1"+v336]
v337 = T["0"+v336]
v338 = T["1"+v38]
v338 = T["1"+v338]
v338 = T["1"+v338]
v338 = T["1"+v338]
v338 = T["1"+v338]
v338 = T["1"+v338]
v338 = T["1"+v338]
v338 = T["1"+v338]
v338 = T["1"+v338]
v339 = T["0"+v338]
v340 = T["1"+v6]
v340 = T["1"+v340]
v340 = T["1"+v340]
v340 = T["1"+v340]
v340 = T["1"+v340]
v340 = T["1"+v340]
v340 = T["1"+v340]
v340 = T["1"+v340]
v340 = T["1"+v340]
v341 = T["0"+v340]
v342 = T["1"+v3]
v342 = T["1"+v342]
v342 = T["1"+v342]
v342 = T["1"+v342]
v342 = T["1"+v342]
v342 = T["1"+v342]
v342 = T["1"+v342]
v342 = T["1"+v342]
v342 = T["1"+v342]
v343 = T["0"+v342]
v344 = T[v331+v293]
v345 = T["1"+v344]
v345 = T["1"+v345]
v345 = T["1"+v345]
v345 = T["1"+v345]
v345 = T["1"+v345]
v345 = T["1"+v345]
v345 = T["1"+v345]
v345 = T["1"+v345]
v345 = T["0"+v345]
v346 = T["1"+v345]
v346 = T["1"+v346]
v346 = T["1"+v346]
v346 = T["1"+v346]
v346 = T["1"+v346]
v346 = T["1"+v346]
v346 = T["1"+v346]
v346 = T["1"+v346]
v346 = T["1"+v346]
v347 = T["0"+v346]
v348 = T[v331+v299]
v349 = T["1"+v348]
v349 = T["1"+v349]
v349 = T["1"+v349]
v349 = T["1"+v349]
v349 = T["1"+v349]
v349 = T["1"+v349]
v349 = T["1"+v349]
v349 = T["1"+v349]
v349 = T["0"+v349]
v350 = T["1"+v349]
v350 = T["1"+v350]
v350 = T["1"+v350]
v350 = T["1"+v350]
v350 = T["1"+v350]
v350 = T["1"+v350]
v350 = T["1"+v350]
v350 = T["1"+v350]
v350 = T["1"+v350]
v351 = T["0"+v350]
v352 = T[v331+v305]
v353 = T["1"+v352]
v353 = T["1"+v353]
v353 = T["1"+v353]
v353 = T["1"+v353]
v353 = T["1"+v353]
v353 = T["1"+v353]
v353 = T["1"+v353]
v353 = T["1"+v353]
v353 = T["0"+v353]
v354 = T["1"+v353]
v354 = T["1"+v354]
v354 = T["1"+v354]
v354 = T["1"+v354]
v354 = T["1"+v354]
v354 = T["1"+v354]
v354 = T["1"+v354]
v354 = T["1"+v354]
v354 = T["1"+v354]
v355 = T["0"+v354]
v356 = T[v331+v311]
v357 = T["1"+v356]
v357 = T["1"+v357]
v357 = T["1"+v357]
v357 = T["1"+v357]
v357 = T["1"+v357]
v357 = T["1"+v357]
v357 = T["1"+v357]
v357 = T["1"+v357]
v357 = T["0"+v357]
v358 = T["1"+v357]
v358 = T["1"+v358]
v358 = T["1"+v358]
v358 = T["1"+v358]
v358 = T["1"+v358]
v358 = T["1"+v358]
v358 = T["1"+v358]
v358 = T["1"+v358]
v358 = T["1"+v358]
v359 = T["0"+v358]
v360 = T[v331+v317]
v361 = T["1"+v360]
v361 = T["1"+v361]
v361 = T["1"+v361]
v361 = T["1"+v361]
v361 = T["1"+v361]
v361 = T["1"+v361]
v361 = T["1"+v361]
v361 = T["1"+v361]
v361 = T["0"+v361]
v362 = T["1"+v361]
v362 = T["1"+v362]
v362 = T["1"+v362]
v362 = T["1"+v362]
v362 = T["1"+v362]
v362 = T["1"+v362]
v362 = T["1"+v362]
v362 = T["1"+v362]
v362 = T["1"+v362]
v363 = T["0"+v362]
v364 = T[v331+v323]
v365 = T["1"+v364]
v365 = T["1"+v365]
v365 = T["1"+v365]
v365 = T["1"+v365]
v365 = T["1"+v365]
v365 = T["1"+v365]
v365 = T["1"+v365]
v365 = T["1"+v365]
v365 = T["0"+v365]
v366 = T["1"+v365]
v366 = T["1"+v366]
v366 = T["1"+v366]
v366 = T["1"+v366]
v366 = T["1"+v366]
v366 = T["1"+v366]
v366 = T["1"+v366]
v366 = T["1"+v366]
v366 = T["1"+v366]
v367 = T["0"+v366]
v368 = T[v331+v329]
v369 = T["1"+v368]
v369 = T["1"+v369]
v369 = T["1"+v369]
v369 = T["1"+v369]
v369 = T["1"+v369]
v369 = T["1"+v369]
v369 = T["1"+v369]
v369 = T["1"+v369]
v369 = T["0"+v369]
v370 = T["1"+v369]
v370 = T["1"+v370]
v370 = T["1"+v370]
v370 = T["1"+v370]
v370 = T["1"+v370]
v370 = T["1"+v370]
v370 = T["1"+v370]
v370 = T["1"+v370]
v370 = T["1"+v370]
v371 = T["0"+v370]
v372 = T[v333+v293]
v373 = T["1"+v372]
v373 = T["1"+v373]
v373 = T["1"+v373]
v373 = T["1"+v373]
v373 = T["1"+v373]
v373 = T["1"+v373]
v373 = T["1"+v373]
v373 = T["1"+v373]
v373 = T["0"+v373]
v374 = T["1"+v373]
v374 = T["1"+v374]
v374 = T["1"+v374]
v374 = T["1"+v374]
v374 = T["1"+v374]
v374 = T["1"+v374]
v374 = T["1"+v374]
v374 = T["1"+v374]
v374 = T["1"+v374]
v375 = T["0"+v374]
v376 = T[v333+v299]
v377 = T["1"+v376]
v377 = T["1"+v377]
v377 = T["1"+v377]
v377 = T["1"+v377]
v377 = T["1"+v377]
v377 = T["1"+v377]
v377 = T["1"+v377]
v377 = T["1"+v377]
v377 = T["0"+v377]
v378 = T["1"+v377]
v378 = T["1"+v378]
v378 = T["1"+v378]
v378 = T["1"+v378]
v378 = T["1"+v378]
v378 = T["1"+v378]
v378 = T["1"+v378]
v378 = T["1"+v378]
v378 = T["1"+v378]
v379 = T["0"+v378]
v380 = T[v333+v305]
v381 = T["1"+v380]
v381 = T["1"+v381]
v381 = T["1"+v381]
v381 = T["1"+v381]
v381 = T["1"+v381]
v381 = T["1"+v381]
v381 = T["1"+v381]
v381 = T["1"+v381]
v381 = T["0"+v381]
v382 = T["1"+v381]
v382 = T["1"+v382]
v382 = T["1"+v382]
v382 = T["1"+v382]
v382 = T["1"+v382]
v382 = T["1"+v382]
v382 = T["1"+v382]
v382 = T["1"+v382]
v382 = T["1"+v382]
v383 = T["0"+v382]
v384 = T[v333+v311]
v385 = T["1"+v384]
v385 = T["1"+v385]
v385 = T["1"+v385]
v385 = T["1"+v385]
v385 = T["1"+v385]
v385 = T["1"+v385]
v385 = T["1"+v385]
v385 = T["1"+v385]
v385 = T["0"+v385]
v386 = T["1"+v385]
v386 = T["1"+v386]
v386 = T["1"+v386]
v386 = T["1"+v386]
v386 = T["1"+v386]
v386 = T["1"+v386]
v386 = T["1"+v386]
v386 = T["1"+v386]
v386 = T["1"+v386]
v387 = T["0"+v386]
v388 = T[v333+v317]
v389 = T["1"+v388]
v389 = T["1"+v389]
v389 = T["1"+v389]
v389 = T["1"+v389]
v389 = T["1"+v389]
v389 = T["1"+v389]
v389 = T["1"+v389]
v389 = T["1"+v389]
v389 = T["0"+v389]
v390 = T["1"+v389]
v390 = T["1"+v390]
v390 = T["1"+v390]
v390 = T["1"+v390]
v390 = T["1"+v390]
v390 = T["1"+v390]
v390 = T["1"+v390]
v390 = T["1"+v390]
v390 = T["1"+v390]
v391 = T["0"+v390]
v392 = T[v333+v323]
v393 = T["1"+v392]
v393 = T["1"+v393]
v393 = T["1"+v393]
v393 = T["1"+v393]
v393 = T["1"+v393]
v393 = T["1"+v393]
v393 = T["1"+v393]
v393 = T["1"+v393]
v393 = T["0"+v393]
v394 = T["1"+v393]
v394 = T["1"+v394]
v394 = T["1"+v394]
v394 = T["1"+v394]
v394 = T["1"+v394]
v394 = T["1"+v394]
v394 = T["1"+v394]
v394 = T["1"+v394]
v394 = T["1"+v394]
v395 = T["0"+v394]
v396 = T[v333+v329]
v397 = T["1"+v396]
v397 = T["1"+v397]
v397 = T["1"+v397]
v397 = T["1"+v397]
v397 = T["1"+v397]
v397 = T["1"+v397]
v397 = T["1"+v397]
v397 = T["1"+v397]
v397 = T["0"+v397]
v398 = T["1"+v397]
v398 = T["1"+v398]
v398 = T["1"+v398]
v398 = T["1"+v398]
v398 = T["1"+v398]
v398 = T["1"+v398]
v398 = T["1"+v398]
v398 = T["1"+v398]
v398 = T["1"+v398]
v399 = T["0"+v398]
v400 = T[v335+v293]
v401 = T["1"+v400]
v401 = T["1"+v401]
v401 = T["1"+v401]
v401 = T["1"+v401]
v401 = T["1"+v401]
v401 = T["1"+v401]
v401 = T["1"+v401]
v401 = T["1"+v401]
v401 = T["0"+v401]
v402 = T["1"+v401]
v402 = T["1"+v402]
v402 = T["1"+v402]
v402 = T["1"+v402]
v402 = T["1"+v402]
v402 = T["1"+v402]
v402 = T["1"+v402]
v402 = T["1"+v402]
v402 = T["1"+v402]
v403 = T["0"+v402]
v404 = T[v335+v299]
v405 = T["1"+v404]
v405 = T["1"+v405]
v405 = T["1"+v405]
v405 = T["1"+v405]
v405 = T["1"+v405]
v405 = T["1"+v405]
v405 = T["1"+v405]
v405 = T["1"+v405]
v405 = T["0"+v405]
v406 = T["1"+v405]
v406 = T["1"+v406]
v406 = T["1"+v406]
v406 = T["1"+v406]
v406 = T["1"+v406]
v406 = T["1"+v406]
v406 = T["1"+v406]
v406 = T["1"+v406]
v406 = T["1"+v406]
v407 = T["0"+v406]
v408 = T[v335+v305]
v409 = T["1"+v408]
v409 = T["1"+v409]
v409 = T["1"+v409]
v409 = T["1"+v409]
v409 = T["1"+v409]
v409 = T["1"+v409]
v409 = T["1"+v409]
v409 = T["1"+v409]
v409 = T["0"+v409]
v410 = T["1"+v409]
v410 = T["1"+v410]
v410 = T["1"+v410]
v410 = T["1"+v410]
v410 = T["1"+v410]
v410 = T["1"+v410]
v410 = T["1"+v410]
v410 = T["1"+v410]
v410 = T["1"+v410]
v411 = T["0"+v410]
v412 = T[v335+v311]
v413 = T["1"+v412]
v413 = T["1"+v413]
v413 = T["1"+v413]
v413 = T["1"+v413]
v413 = T["1"+v413]
v413 = T["1"+v413]
v413 = T["1"+v413]
v413 = T["1"+v413]
v413 = T["0"+v413]
v414 = T["1"+v413]
v414 = T["1"+v414]
v414 = T["1"+v414]
v414 = T["1"+v414]
v414 = T["1"+v414]
v414 = T["1"+v414]
v414 = T["1"+v414]
v414 = T["1"+v414]
v414 = T["1"+v414]
v415 = T["0"+v414]
v416 = T[v335+v317]
v417 = T["1"+v416]
v417 = T["1"+v417]
v417 = T["1"+v417]
v417 = T["1"+v417]
v417 = T["1"+v417]
v417 = T["1"+v417]
v417 = T["1"+v417]
v417 = T["1"+v417]
v417 = T["0"+v417]
v418 = T["1"+v417]
v418 = T["1"+v418]
v418 = T["1"+v418]
v418 = T["1"+v418]
v418 = T["1"+v418]
v418 = T["1"+v418]
v418 = T["1"+v418]
v418 = T["1"+v418]
v418 = T["1"+v418]
v419 = T["0"+v418]
v420 = T[v335+v323]
v421 = T["1"+v420]
v421 = T["1"+v421]
v421 = T["1"+v421]
v421 = T["1"+v421]
v421 = T["1"+v421]
v421 = T["1"+v421]
v421 = T["1"+v421]
v421 = T["1"+v421]
v421 = T["0"+v421]
v422 = T["1"+v421]
v422 = T["1"+v422]
v422 = T["1"+v422]
v422 = T["1"+v422]
v422 = T["1"+v422]
v422 = T["1"+v422]
v422 = T["1"+v422]
v422 = T["1"+v422]
v422 = T["1"+v422]
v423 = T["0"+v422]
v424 = T[v335+v329]
v425 = T["1"+v424]
v425 = T["1"+v425]
v425 = T["1"+v425]
v425 = T["1"+v425]
v425 = T["1"+v425]
v425 = T["1"+v425]
v425 = T["1"+v425]
v425 = T["1"+v425]
v425 = T["0"+v425]
v426 = T["1"+v425]
v426 = T["1"+v426]
v426 = T["1"+v426]
v426 = T["1"+v426]
v426 = T["1"+v426]
v426 = T["1"+v426]
v426 = T["1"+v426]
v426 = T["1"+v426]
v426 = T["1"+v426]
v427 = T["0"+v426]
v428 = T[v337+v293]
v429 = T["1"+v428]
v429 = T["1"+v429]
v429 = T["1"+v429]
v429 = T["1"+v429]
v429 = T["1"+v429]
v429 = T["1"+v429]
v429 = T["1"+v429]
v429 = T["1"+v429]
v429 = T["0"+v429]
v430 = T["1"+v429]
v430 = T["1"+v430]
v430 = T["1"+v430]
v430 = T["1"+v430]
v430 = T["1"+v430]
v430 = T["1"+v430]
v430 = T["1"+v430]
v430 = T["1"+v430]
v430 = T["1"+v430]
v431 = T["0"+v430]
v432 = T[v337+v299]
v433 = T["1"+v432]
v433 = T["1"+v433]
v433 = T["1"+v433]
v433 = T["1"+v433]
v433 = T["1"+v433]
v433 = T["1"+v433]
v433 = T["1"+v433]
v433 = T["1"+v433]
v433 = T["0"+v433]
v434 = T["1"+v433]
v434 = T["1"+v434]
v434 = T["1"+v434]
v434 = T["1"+v434]
v434 = T["1"+v434]
v434 = T["1"+v434]
v434 = T["1"+v434]
v434 = T["1"+v434]
v434 = T["1"+v434]
v435 = T["0"+v434]
v436 = T[v337+v305]
v437 = T["1"+v436]
v437 = T["1"+v437]
v437 = T["1"+v437]
v437 = T["1"+v437]
v437 = T["1"+v437]
v437 = T["1"+v437]
v437 = T["1"+v437]
v437 = T["1"+v437]
v437 = T["0"+v437]
v438 = T["1"+v437]
v438 = T["1"+v438]
v438 = T["1"+v438]
v438 = T["1"+v438]
v438 = T["1"+v438]
v438 = T["1"+v438]
v438 = T["1"+v438]
v438 = T["1"+v438]
v438 = T["1"+v438]
v439 = T["0"+v438]
v440 = T[v337+v311]
v441 = T["1"+v440]
v441 = T["1"+v441]
v441 = T["1"+v441]
v441 = T["1"+v441]
v441 = T["1"+v441]
v441 = T["1"+v441]
v441 = T["1"+v441]
v441 = T["1"+v441]
v441 = T["0"+v441]
v442 = T["1"+v441]
v442 = T["1"+v442]
v442 = T["1"+v442]
v442 = T["1"+v442]
v442 = T["1"+v442]
v442 = T["1"+v442]
v442 = T["1"+v442]
v442 = T["1"+v442]
v442 = T["1"+v442]
v443 = T["0"+v442]
v444 = T[v337+v317]
v445 = T["1"+v444]
v445 = T["1"+v445]
v445 = T["1"+v445]
v445 = T["1"+v445]
v445 = T["1"+v445]
v445 = T["1"+v445]
v445 = T["1"+v445]
v445 = T["1"+v445]
v445 = T["0"+v445]
v446 = T["1"+v445]
v446 = T["1"+v446]
v446 = T["1"+v446]
v446 = T["1"+v446]
v446 = T["1"+v446]
v446 = T["1"+v446]
v446 = T["1"+v446]
v446 = T["1"+v446]
v446 = T["1"+v446]
v447 = T["0"+v446]
v448 = T[v337+v323]
v449 = T["1"+v448]
v449 = T["1"+v449]
v449 = T["1"+v449]
v449 = T["1"+v449]
v449 = T["1"+v449]
v449 = T["1"+v449]
v449 = T["1"+v449]
v449 = T["1"+v449]
v449 = T["0"+v449]
v450 = T["1"+v449]
v450 = T["1"+v450]
v450 = T["1"+v450]
v450 = T["1"+v450]
v450 = T["1"+v450]
v450 = T["1"+v450]
v450 = T["1"+v450]
v450 = T["1"+v450]
v450 = T["1"+v450]
v451 = T["0"+v450]
v452 = T[v337+v329]
v453 = T["1"+v452]
v453 = T["1"+v453]
v453 = T["1"+v453]
v453 = T["1"+v453]
v453 = T["1"+v453]
v453 = T["1"+v453]
v453 = T["1"+v453]
v453 = T["1"+v453]
v453 = T["0"+v453]
v454 = T["1"+v453]
v454 = T["1"+v454]
v454 = T["1"+v454]
v454 = T["1"+v454]
v454 = T["1"+v454]
v454 = T["1"+v454]
v454 = T["1"+v454]
v454 = T["1"+v454]
v454 = T["1"+v454]
v455 = T["0"+v454]
v456 = T[v339+v293]
v457 = T["1"+v456]
v457 = T["1"+v457]
v457 = T["1"+v457]
v457 = T["1"+v457]
v457 = T["1"+v457]
v457 = T["1"+v457]
v457 = T["1"+v457]
v457 = T["1"+v457]
v457 = T["0"+v457]
v458 = T["1"+v457]
v458 = T["1"+v458]
v458 = T["1"+v458]
v458 = T["1"+v458]
v458 = T["1"+v458]
v458 = T["1"+v458]
v458 = T["1"+v458]
v458 = T["1"+v458]
v458 = T["1"+v458]
v459 = T["0"+v458]
v460 = T[v339+v299]
v461 = T["1"+v460]
v461 = T["1"+v461]
v461 = T["1"+v461]
v461 = T["1"+v461]
v461 = T["1"+v461]
v461 = T["1"+v461]
v461 = T["1"+v461]
v461 = T["1"+v461]
v461 = T["0"+v461]
v462 = T["1"+v461]
v462 = T["1"+v462]
v462 = T["1"+v462]
v462 = T["1"+v462]
v462 = T["1"+v462]
v462 = T["1"+v462]
v462 = T["1"+v462]
v462 = T["1"+v462]
v462 = T["1"+v462]
v463 = T["0"+v462]
v464 = T[v339+v305]
v465 = T["1"+v464]
v465 = T["1"+v465]
v465 = T["1"+v465]
v465 = T["1"+v465]
v465 = T["1"+v465]
v465 = T["1"+v465]
v465 = T["1"+v465]
v465 = T["1"+v465]
v465 = T["0"+v465]
v466 = T["1"+v465]
v466 = T["1"+v466]
v466 = T["1"+v466]
v466 = T["1"+v466]
v466 = T["1"+v466]
v466 = T["1"+v466]
v466 = T["1"+v466]
v466 = T["1"+v466]
v466 = T["1"+v466]
v467 = T["0"+v466]
v468 = T[v339+v311]
v469 = T["1"+v468]
v469 = T["1"+v469]
v469 = T["1"+v469]
v469 = T["1"+v469]
v469 = T["1"+v469]
v469 = T["1"+v469]
v469 = T["1"+v469]
v469 = T["1"+v469]
v469 = T["0"+v469]
v470 = T["1"+v469]
v470 = T["1"+v470]
v470 = T["1"+v470]
v470 = T["1"+v470]
v470 = T["1"+v470]
v470 = T["1"+v470]
v470 = T["1"+v470]
v470 = T["1"+v470]
v470 = T["1"+v470]
v471 = T["0"+v470]
v472 = T[v339+v317]
v473 = T["1"+v472]
v473 = T["1"+v473]
v473 = T["1"+v473]
v473 = T["1"+v473]
v473 = T["1"+v473]
v473 = T["1"+v473]
v473 = T["1"+v473]
v473 = T["1"+v473]
v473 = T["0"+v473]
v474 = T["1"+v473]
v474 = T["1"+v474]
v474 = T["1"+v474]
v474 = T["1"+v474]
v474 = T["1"+v474]
v474 = T["1"+v474]
v474 = T["1"+v474]
v474 = T["1"+v474]
v474 = T["1"+v474]
v475 = T["0"+v474]
v476 = T[v339+v323]
v477 = T["1"+v476]
v477 = T["1"+v477]
v477 = T["1"+v477]
v477 = T["1"+v477]
v477 = T["1"+v477]
v477 = T["1"+v477]
v477 = T["1"+v477]
v477 = T["1"+v477]
v477 = T["0"+v477]
v478 = T["1"+v477]
v478 = T["1"+v478]
v478 = T["1"+v478]
v478 = T["1"+v478]
v478 = T["1"+v478]
v478 = T["1"+v478]
v478 = T["1"+v478]
v478 = T["1"+v478]
v478 = T["1"+v478]
v479 = T["0"+v478]
v480 = T[v339+v329]
v481 = T["1"+v480]
v481 = T["1"+v481]
v481 = T["1"+v481]
v481 = T["1"+v481]
v481 = T["1"+v481]
v481 = T["1"+v481]
v481 = T["1"+v481]
v481 = T["1"+v481]
v481 = T["0"+v481]
v482 = T["1"+v481]
v482 = T["1"+v482]
v482 = T["1"+v482]
v482 = T["1"+v482]
v482 = T["1"+v482]
v482 = T["1"+v482]
v482 = T["1"+v482]
v482 = T["1"+v482]
v482 = T["1"+v482]
v483 = T["0"+v482]
v484 = T[v341+v293]
v485 = T["1"+v484]
v485 = T["1"+v485]
v485 = T["1"+v485]
v485 = T["1"+v485]
v485 = T["1"+v485]
v485 = T["1"+v485]
v485 = T["1"+v485]
v485 = T["1"+v485]
v485 = T["0"+v485]
v486 = T["1"+v485]
v486 = T["1"+v486]
v486 = T["1"+v486]
v486 = T["1"+v486]
v486 = T["1"+v486]
v486 = T["1"+v486]
v486 = T["1"+v486]
v486 = T["1"+v486]
v486 = T["1"+v486]
v487 = T["0"+v486]
v488 = T[v341+v299]
v489 = T["1"+v488]
v489 = T["1"+v489]
v489 = T["1"+v489]
v489 = T["1"+v489]
v489 = T["1"+v489]
v489 = T["1"+v489]
v489 = T["1"+v489]
v489 = T["1"+v489]
v489 = T["0"+v489]
v490 = T["1"+v489]
v490 = T["1"+v490]
v490 = T["1"+v490]
v490 = T["1"+v490]
v490 = T["1"+v490]
v490 = T["1"+v490]
v490 = T["1"+v490]
v490 = T["1"+v490]
v490 = T["1"+v490]
v491 = T["0"+v490]
v492 = T[v341+v305]
v493 = T["1"+v492]
v493 = T["1"+v493]
v493 = T["1"+v493]
v493 = T["1"+v493]
v493 = T["1"+v493]
v493 = T["1"+v493]
v493 = T["1"+v493]
v493 = T["1"+v493]
v493 = T["0"+v493]
v494 = T["1"+v493]
v494 = T["1"+v494]
v494 = T["1"+v494]
v494 = T["1"+v494]
v494 = T["1"+v494]
v494 = T["1"+v494]
v494 = T["1"+v494]
v494 = T["1"+v494]
v494 = T["1"+v494]
v495 = T["0"+v494]
v496 = T[v341+v311]
v497 = T["1"+v496]
v497 = T["1"+v497]
v497 = T["1"+v497]
v497 = T["1"+v497]
v497 = T["1"+v497]
v497 = T["1"+v497]
v497 = T["1"+v497]
v497 = T["1"+v497]
v497 = T["0"+v497]
v498 = T["1"+v497]
v498 = T["1"+v498]
v498 = T["1"+v498]
v498 = T["1"+v498]
v498 = T["1"+v498]
v498 = T["1"+v498]
v498 = T["1"+v498]
v498 = T["1"+v498]
v498 = T["1"+v498]
v499 = T["0"+v498]
v500 = T[v341+v317]
v501 = T["1"+v500]
v501 = T["1"+v501]
v501 = T["1"+v501]
v501 = T["1"+v501]
v501 = T["1"+v501]
v501 = T["1"+v501]
v501 = T["1"+v501]
v501 = T["1"+v501]
v501 = T["0"+v501]
v502 = T["1"+v501]
v502 = T["1"+v502]
v502 = T["1"+v502]
v502 = T["1"+v502]
v502 = T["1"+v502]
v502 = T["1"+v502]
v502 = T["1"+v502]
v502 = T["1"+v502]
v502 = T["1"+v502]
v503 = T["0"+v502]
v504 = T[v341+v323]
v505 = T["1"+v504]
v505 = T["1"+v505]
v505 = T["1"+v505]
v505 = T["1"+v505]
v505 = T["1"+v505]
v505 = T["1"+v505]
v505 = T["1"+v505]
v505 = T["1"+v505]
v505 = T["0"+v505]
v506 = T["1"+v505]
v506 = T["1"+v506]
v506 = T["1"+v506]
v506 = T["1"+v506]
v506 = T["1"+v506]
v506 = T["1"+v506]
v506 = T["1"+v506]
v506 = T["1"+v506]
v506 = T["1"+v506]
v507 = T["0"+v506]
v508 = T[v341+v329]
v509 = T["1"+v508]
v509 = T["1"+v509]
v509 = T["1"+v509]
v509 = T["1"+v509]
v509 = T["1"+v509]
v509 = T["1"+v509]
v509 = T["1"+v509]
v509 = T["1"+v509]
v509 = T["0"+v509]
v510 = T["1"+v509]
v510 = T["1"+v510]
v510 = T["1"+v510]
v510 = T["1"+v510]
v510 = T["1"+v510]
v510 = T["1"+v510]
v510 = T["1"+v510]
v510 = T["1"+v510]
v510 = T["1"+v510]
v511 = T["0"+v510]
v512 = T[v343+v293]
v513 = T["1"+v512]
v513 = T["1"+v513]
v513 = T["1"+v513]
v513 = T["1"+v513]
v513 = T["1"+v513]
v513 = T["1"+v513]
v513 = T["1"+v513]
v513 = T["1"+v513]
v513 = T["0"+v513]
v514 = T["1"+v513]
v514 = T["1"+v514]
v514 = T["1"+v514]
v514 = T["1"+v514]
v514 = T["1"+v514]
v514 = T["1"+v514]
v514 = T["1"+v514]
v514 = T["1"+v514]
v514 = T["1"+v514]
v515 = T["0"+v514]
v516 = T[v343+v299]
v517 = T["1"+v516]
v517 = T["1"+v517]
v517 = T["1"+v517]
v517 = T["1"+v517]
v517 = T["1"+v517]
v517 = T["1"+v517]
v517 = T["1"+v517]
v517 = T["1"+v517]
v517 = T["0"+v517]
v518 = T["1"+v517]
v518 = T["1"+v518]
v518 = T["1"+v518]
v518 = T["1"+v518]
v518 = T["1"+v518]
v518 = T["1"+v518]
v518 = T["1"+v518]
v518 = T["1"+v518]
v518 = T["1"+v518]
v519 = T["0"+v518]
v520 = T[v343+v305]
v521 = T["1"+v520]
v521 = T["1"+v521]
v521 = T["1"+v521]
v521 = T["1"+v521]
v521 = T["1"+v521]
v521 = T["1"+v521]
v521 = T["1"+v521]
v521 = T["1"+v521]
v521 = T["0"+v521]
v522 = T["1"+v521]
v522 = T["1"+v522]
v522 = T["1"+v522]
v522 = T["1"+v522]
v522 = T["1"+v522]
v522 = T["1"+v522]
v522 = T["1"+v522]
v522 = T["1"+v522]
v522 = T["1"+v522]
v523 = T["0"+v522]
v524 = T[v343+v311]
v525 = T["1"+v524]
v525 = T["1"+v525]
v525 = T["1"+v525]
v525 = T["1"+v525]
v525 = T["1"+v525]
v525 = T["1"+v525]
v525 = T["1"+v525]
v525 = T["1"+v525]
v525 = T["0"+v525]
v526 = T["1"+v525]
v526 = T["1"+v526]
v526 = T["1"+v526]
v526 = T["1"+v526]
v526 = T["1"+v526]
v526 = T["1"+v526]
v526 = T["1"+v526]
v526 = T["1"+v526]
v526 = T["1"+v526]
v527 = T["0"+v526]
v528 = T[v343+v317]
v529 = T["1"+v528]
v529 = T["1"+v529]
v529 = T["1"+v529]
v529 = T["1"+v529]
v529 = T["1"+v529]
v529 = T["1"+v529]
v529 = T["1"+v529]
v529 = T["1"+v529]
v529 = T["0"+v529]
v530 = T["1"+v529]
v530 = T["1"+v530]
v530 = T["1"+v530]
v530 = T["1"+v530]
v530 = T["1"+v530]
v530 = T["1"+v530]
v530 = T["1"+v530]
v530 = T["1"+v530]
v530 = T["1"+v530]
v531 = T["0"+v530]
v532 = T[v343+v323]
v533 = T["1"+v532]
v533 = T["1"+v533]
v533 = T["1"+v533]
v533 = T["1"+v533]
v533 = T["1"+v533]
v533 = T["1"+v533]
v533 = T["1"+v533]
v533 = T["1"+v533]
v533 = T["0"+v533]
v534 = T["1"+v533]
v534 = T["1"+v534]
v534 = T["1"+v534]
v534 = T["1"+v534]
v534 = T["1"+v534]
v534 = T["1"+v534]
v534 = T["1"+v534]
v534 = T["1"+v534]
v534 = T["1"+v534]
v535 = T["0"+v534]
v536 = T[v343+v329]
v537 = T["1"+v536]
v537 = T["1"+v537]
v537 = T["1"+v537]
v537 = T["1"+v537]
v537 = T["1"+v537]
v537 = T["1"+v537]
v537 = T["1"+v537]
v537 = T["1"+v537]
v537 = T["0"+v537]
v538 = T["1"+v537]
v538 = T["1"+v538]
v538 = T["1"+v538]
v538 = T["1"+v538]
v538 = T["1"+v538]
v538 = T["1"+v538]
v538 = T["1"+v538]
v538 = T["1"+v538]
v538 = T["1"+v538]
v539 = T["0"+v538]
v540 = T[v347+v399]
v540 = T["0"+v540]
v541 = T[v540+v423]
v541 = T["0"+v541]
v542 = T[v541+v447]
v542 = T["0"+v542]
v543 = T[v542+v471]
v543 = T["0"+v543]
v544 = T[v543+v495]
v544 = T["0"+v544]
v545 = T[v544+v519]
v545 = T["0"+v545]
v546 = T[v351+v375]
v546 = T["0"+v546]
v547 = T[v546+v427]
v547 = T["0"+v547]
v548 = T[v547+v451]
v548 = T["0"+v548]
v549 = T[v548+v475]
v549 = T["0"+v549]
v550 = T[v549+v499]
v550 = T["0"+v550]
v551 = T[v550+v523]
v551 = T["0"+v551]
v552 = T[v355+v379]
v552 = T["0"+v552]
v553 = T[v552+v403]
v553 = T["0"+v553]
v554 = T[v553+v455]
v554 = T["0"+v554]
v555 = T[v554+v479]
v555 = T["0"+v555]
v556 = T[v555+v503]
v556 = T["0"+v556]
v557 = T[v556+v527]
v557 = T["0"+v557]
v558 = T[v359+v383]
v558 = T["0"+v558]
v559 = T[v558+v407]
v559 = T["0"+v559]
v560 = T[v559+v431]
v560 = T["0"+v560]
v561 = T[v560+v483]
v561 = T["0"+v561]
v562 = T[v561+v507]
v562 = T["0"+v562]
v563 = T[v562+v531]
v563 = T["0"+v563]
v564 = T[v363+v387]
v564 = T["0"+v564]
v565 = T[v564+v411]
v565 = T["0"+v565]
v566 = T[v565+v435]
v566 = T["0"+v566]
v567 = T[v566+v459]
v567 = T["0"+v567]
v568 = T[v567+v511]
v568 = T["0"+v568]
v569 = T[v568+v535]
v569 = T["0"+v569]
v570 = T[v367+v391]
v570 = T["0"+v570]
v571 = T[v570+v415]
v571 = T["0"+v571]
v572 = T[v571+v439]
v572 = T["0"+v572]
v573 = T[v572+v463]
v573 = T["0"+v573]
v574 = T[v573+v487]
v574 = T["0"+v574]
v575 = T[v574+v539]
v575 = T["0"+v575]
v576 = T[v371+v395]
v576 = T["0"+v576]
v577 = T[v576+v419]
v577 = T["0"+v577]
v578 = T[v577+v443]
v578 = T["0"+v578]
v579 = T[v578+v467]
v579 = T["0"+v579]
v580 = T[v579+v491]
v580 = T["0"+v580]
v581 = T[v580+v515]
v581 = T["0"+v581]
v582 = T["1"+v545]
v582 = T["1"+v582]
v582 = T["1"+v582]
v582 = T["1"+v582]
v582 = T["1"+v582]
v582 = T["1"+v582]
v582 = T["1"+v582]
v582 = T["1"+v582]
v582 = T["1"+v582]
v583 = T["0"+v582]
v584 = T["1"+v581]
v584 = T["1"+v584]
v584 = T["1"+v584]
v584 = T["1"+v584]
v584 = T["1"+v584]
v584 = T["1"+v584]
v584 = T["1"+v584]
v584 = T["1"+v584]
v584 = T["1"+v584]
v585 = T["0"+v584]
v586 = T["1"+v575]
v586 = T["1"+v586]
v586 = T["1"+v586]
v586 = T["1"+v586]
v586 = T["1"+v586]
v586 = T["1"+v586]
v586 = T["1"+v586]
v586 = T["1"+v586]
v586 = T["1"+v586]
v587 = T["0"+v586]
v588 = T["1"+v569]
v588 = T["1"+v588]
v588 = T["1"+v588]
v588 = T["1"+v588]
v588 = T["1"+v588]
v588 = T["1"+v588]
v588 = T["1"+v588]
v588 = T["1"+v588]
v588 = T["1"+v588]
v589 = T["0"+v588]
v590 = T["1"+v563]
v590 = T["1"+v590]
v590 = T["1"+v590]
v590 = T["1"+v590]
v590 = T["1"+v590]
v590 = T["1"+v590]
v590 = T["1"+v590]
v590 = T["1"+v590]
v590 = T["1"+v590]
v591 = T["0"+v590]
v592 = T["1"+v557]
v592 = T["1"+v592]
v592 = T["1"+v592]
v592 = T["1"+v592]
v592 = T["1"+v592]
v592 = T["1"+v592]
v592 = T["1"+v592]
v592 = T["1"+v592]
v592 = T["1"+v592]
v593 = T["0"+v592]
v594 = T["1"+v551]
v594 = T["1"+v594]
v594 = T["1"+v594]
v594 = T["1"+v594]
v594 = T["1"+v594]
v594 = T["1"+v594]
v594 = T["1"+v594]
v594 = T["1"+v594]
v594 = T["1"+v594]
v595 = T["0"+v594]
v596 = T[v583+"1"]
v596 = T[v585+v596]
v596 = T[v587+v596]
v596 = T[v589+v596]
v596 = T[v591+v596]
v596 = T[v593+v596]
v596 = T[v595+v596]
v597 = T["1"+v596]
v597 = T["1"+v597]
v597 = T["1"+v597]
v597 = T["1"+v597]
v597 = T["1"+v597]
v597 = T["1"+v597]
v597 = T["1"+v597]
v597 = T["1"+v597]
v597 = T["1"+v597]
output = v597
```
Generator code:
```
import functools
print("""
T = {
"00": "0", "01":"1", "02":"1", "03":"1", "04":"1", "05":"1", "06":"1", "07":"1", "08":"1", "09":"1",
"10": "1", "11":"2", "12":"3", "13":"4", "14":"5", "15":"6", "16":"7", "17":"8", "18":"9", "19":"0"
}
""".strip())
varn = 0
def getvar():
global varn
ret = 'v' + str(varn)
varn += 1
return ret
def eaddi(vi, imm):
if imm == 0: return vi
ni = getvar()
for i in range(imm):
print('%s = T["1"+%s]' % (ni, vi if i == 0 else ni))
return ni
def enot(bi):
bi2 = eaddi(bi, 9)
ni = getvar()
print('%s = T["0"+%s]' % (ni, bi2))
return ni
def eor(b1, b2):
ni = getvar()
print('%s = T[%s+%s]' % (ni, b1, b2))
print('%s = T["0"+%s]' % (ni, ni))
return ni
def enor(b1, b2):
return enot(eor(b1, b2))
#def eand(b1, b2):
# return enor(enot(b1), enot(b2))
def eand(b1, b2):
ni = getvar()
print('%s = T[%s+%s]' % (ni, b1, b2))
#return enot(eaddi(ni, 8))
ni = eaddi(ni, 8)
print('%s = T["0"+%s]' % (ni, ni))
return enot(ni)
def exor(b1, b2):
return enor(enor(enot(b1), enot(b2)), enor(b1, b2))
def eeqt(vi):
#return array of 10 bits for all 10 possible values of vi. inverted
res = []
vi2 = getvar()
for i in range(10):
ni = getvar()
print('%s = T["0"+%s]' % (ni, vi if i == 0 else vi2))
print('%s = T["1"+%s]' % (vi2, vi if i == 0 else vi2))
res.append(ni)
#e.g. res[0] = !(x == 0)
return res[0:1] + res[1:][::-1]
def edmon(m1, m2):
#decode m2 using eeqt. create 2 more variables for november and december
#m1 is already boolean
m2p = eeqt(m2)
v11 = eor(m2p[1], enot(m1))
m2p[1] = eor(m2p[1], m1)
v12 = eor(m2p[2], enot(m1))
m2p[2] = eor(m2p[2], m1)
ret = m2p + [v11, v12]
#return ret
return ret[1:10] + ret[0:1] + ret[10:]
def elmon(dmon):
#given output of edmon, find first day modulo 7. also output inverted!
#table = [4, 0, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2]
d0 = eand(eand(dmon[1], dmon[2]), dmon[10])
d1 = dmon[5]
d2 = eand(dmon[8], dmon[11])
d3 = eand(dmon[3], dmon[6])
d4 = eand(dmon[0], dmon[9])
d5 = dmon[4]
d6 = dmon[7]
return [d0,d1,d2,d3,d4,d5,d6]
def enotarr(a):
return [enot(x) for x in a]
def eadd7(v1, v2):
vals = [[] for _ in range(7)]
for a in range(7):
for b in range(7):
vals[(a+b)%7].append(eand(v1[a], v2[b]))
return [functools.reduce(eor, a) for a in vals]
def emod7(d2):
et = eeqt(d2)
et = enotarr(et)
et[0] = eor(et[0], et[7])
et[1] = eor(et[1], et[8])
et[2] = eor(et[2], et[9])
return et[0:7]
def e3mod7(d1):
et = eeqt(d1) # can't optimize because entries are obtained like 0, 9, 8, ... and 1 must be reached
#d1 < 4. multiply by 3
#0*3 = 0, 1*3 = 3, 2*3 = 6, 3*3 = 2
return [enot(et[0]), '"0"', enot(et[3]), enot(et[1]), '"0"', '"0"', enot(et[2])]
def eout(m7):
m7 = enotarr(m7)
val = '"1"'
ni = getvar()
for x in m7:
print('%s = T[%s+%s]' % (ni, x, val))
val = ni
return eaddi(ni, 9)
def solve(m1, m2, d1, d2):
mmod7 = elmon(edmon(m1, m2))
dmod7 = eadd7(emod7(d2), e3mod7(d1))
res = eadd7(enotarr(mmod7), dmod7)
res = res[1:] + res[:1]
return eout(res[::-1])
#print(eaddinv(['A'+str(i) for i in range(7)], ['B'+str(i) for i in range(7)]))
#print('print(' + ', '.join(elmon(edmon('M1', 'M2'))) + ')')
#print('print(' + ', '.join(edmon('M1', 'M2')) + ')')
#print('output =', '['+','.join(e3mod7('d1'))+']')
#print('output =', '['+','.join(eadd7(e3mod7('d1'), emod7('d2')))+']')
#print('output =', '['+','.join(emod7('d2'))+']')
#print('output =', '['+','.join(solve('m1','m2','d1','d2'))+']')
print('output =', solve('m1', 'm2', 'd1', 'd2'))
```
No TIO links because of the code size. The generator can be run as `python3 x.py > solution.py`.
# Explanation
In the table T, `T[0x]` is `0` when x is `0` and `1` otherwise, and `T[1x]` is `(x+1) % 10`.
Then logic can be performed on values in (0, 1):
```
!bit = T['0' + (bit+9)]
b1 | b2 = T['0' + T[b1 + b2]]
```
OR and NOT are functionally complete (and can be used to evaluate any boolean function).
To perform any boolean calculations on the input, it should be converted to bits. In my code, it's done like this:
```
!(x == 0) = T['0' + x]
!(x == 9) = T['0' + (x+1)%10]
!(x == 8) = T['0' + (x+2)%10]
...
!(x == 1) = T['0' + (x+9)%10]
```
(and a 10-bit representation is obtained from this).
To convert a sequence of bits to a number, the following is used in my code:
```
x = 1
x = T[bit1 + x]
x = T[bit2 + x]
x = T[bit3 + x]
...
x = T[bitn + x]
x = x + 9
```
After this, `x` is the number of zeroes after the last `1` in the sequence of bits (modulo 10 and assuming the sequence of bits is short).
In my code, integers modulo 7 are represented as sequences of 7 bits (when the bit at index `i` is set, the integer is equal to `i`). Some calculations are performed with inverted values. Addition is implemented by checking for all 49 possible cases and selecting the correct output.
] |
[Question]
[
# Objective
Given a nonempty multiset of `Rock`, `Paper`, and `Scissors`, output the winning figure according to the special rule.
# Background
For a multiplayer RPS, if all three figures come out, usually it's considered a draw. But by that rule, the probability to draw would dramatically increase when there are many and many players.
Let's resolve that by a special rule.
# Input
Though defined as a multiset, the input type and format doesn't matter. Valid formats of the input include:
* A multiset
* A sequential container with or without guarantee of order
* An size-3 array of integers representing the count of each of RPS
Also, `Rock`, `Paper`, and `Scissors` may be encoded by an arbitrary type.
# The Special Rule and Output
Let's say \$r\$ `Rock`s, \$p\$ `Paper`s, and \$s\$ `Scissors`-es(?) are given.
* If one of them is zero, output the winning figure of the other two.
* If none of them is zero, allot them a score by multiplicating the number of themselves and the number of the figure they win to. That is, `Rock` gets score \$r×s\$, `Paper` gets score \$p×r\$, and `Scissors` get score \$s×p\$.
+ If the scores don't tie, output the figure with the maximum score.
+ If the scores tie by two figures, output the winning figure amongst the two figures.
+ Otherwise, output a fourth value indicating draw.
* Otherwise, output either the only figure or the fourth value.
The output type and format doesn't matter.
# Rule about code golf
Invalid inputs (Empty container, contains a fourth value, etc) fall into *don't care* situation.
# Example
Given the following input:
```
[Rock, Rock, Rock, Paper, Paper, Scissors, Scissors]
```
`Rock` gets score 3×2=6, `Paper` gets score 2×3=6, and `Scissors` get score 2×2=4. Since `Paper` wins to `Rock`, the output is `Paper`.
[Answer]
# [Python](https://docs.python.org/2/), 41 bytes
```
lambda r,s,p:[s>p<=r>0,p>r<=s>0,r>s<=p>0]
```
[Try it online!](https://tio.run/##PYwxDsIwEAT7vGLLWHIRQWfl/Ii0kMJADJbAOd2ZgtcbHAHSFjvS7PKr3Na8q5GO9R4ep0uAWLXsDup5JPGDZS8j6aeI15HYD3OdQJCQr0u/N10XV4EgZUyuQwP9wUb8J6SIfrs3IEI/WLQYd15zSfm5NIcl5dI0qAUbi/id1Dc "Python 2 – Try It Online")
Takes counts as `(r,s,p)`. Outputs a three-element list with `True` at the position of the winner, or all `False`'s if there's a tie or only a single figure appearing.
```
Rock: [True, False, False]
Scissors: [False, True, False]
Paper: [False, False, True]
Tie: [False, False, False]
```
We use an alternate characterization without multiplication (except when only one figure is present). Below is the condition for Rock winning, with Scissors and Paper having similar conditions.
>
> Rock wins if: Paper has the fewest, strictly fewer than Scissors but possibly the same as Rock.
>
>
>
We can write this in Python as `s>p<=r` using inequality chaining.
Unfortunately, this doesn't correctly handle the special case when `r=p=0`, saying that Rock wins even though only Scissors is present. To fix this, we strengthen the condition for Rock to win to include `r>0` via `s>p<=r>0`, which makes the only-Scissors case give all `False` for every condition, matching a tie.
---
**44 bytes**
```
lambda r,s,p:r*s==s*p==p*r or[s>p<=r,p>r<=s]
```
[Try it online!](https://tio.run/##Pc2xDsIwEAPQvV/hsYkyINiiXj@iK2UI0EAkSE53ZeDrg1IBkpcn2TK/13vJ@xppro/wPF8DxKljL1aJ1DIRW0GRo448kDgeZSA91QkECfm29AfTdbEIBClj8h0a9IdN/BdSRL89GBCh3zm0GH8peU35tbQOS8prq0Ed2DjE76R@AA "Python 2 – Try It Online")
Takes counts as `(r,s,p)`. Outputs as:
```
Rock: [True, False]
Scissors: [False, True]
Paper: [False, False]
Tie: True
```
The "Tie" case also includes where there's only a single figure present.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ćü*ZÊ2βD3*7%M
```
Input as a list of integers in the order \$[r,s,p]\$.
Output as one of the following four:
```
Rock wins: 3
Scissors wins: 5
Paper wins: 6
Tie: 0
```
-1 byte thanks to *@xnor*.
[Try it online](https://tio.run/##yy9OTMpM/f//SNvhPVpRh7uMzm1yMdYyV/X9/z/aWMdIxygWAA) or [verify some more test cases](https://tio.run/##AVkApv9vc2FiaWX/MsOdM8Ojdnk/IiDihpIgIj95/8SGw7wqWsOKMs6yRDMqNyVN/0Q/IlRpZSAgIFJvY2sgIFNjaXNzb3JzIFBhcGVyIiNzw6giICjDvykiLClc/w).
**Explanation:**
```
Ć # Enclose the (implicit) input-list, appending its own head
# i.e. input=[3,2,2] → STACK: [[3,2,2,3]
ü # For each overlapping pair: [a,b,c,d] → [[a,b],[b,c],[c,d]]
* # Multiply them together
# STACK: [[6,4,6]]
Z # Get the maximum (without popping)
# STACK: [[6,4,6],6]
Ê # Check which of the values in the list are NOT equals to this maximum
# STACK: [[0,1,0]]
2β # Convert this list of 0s and 1s from a binary list to integer
# STACK: [2]
D # Duplicate it
# STACK: [2,2]
3* # Multiply it by 3
# STACK: [2,6]
7% # Take modulo-7:
# STACK: [2,6]
M # Push the largest value on the stack
# STACK: [2,6,6]
# (after which the top of the stack is output implicitly as result)
```
After the `Ćü*ZÊ` we can have the following values:
```
One of:
Rock wins: [[0,1,1], [0,0,1]]
Scissors wins: [[1,0,1], [1,0,0]]
Paper wins: [[1,1,0], [0,1,0]]
Ties: [[0,0,0]]
```
Converting those from binary-lists to integers:
```
One of:
Rock wins: [3, 1]
Scissors wins: [5, 4]
Paper wins: [6, 2]
Ties: [0]
```
The `3*7%` (thanks to *@xnor*!) will map the lower values to the higher values in the pair, and will also unsure the lower values won't increase.
>
> This works because the pairs `[1,3], [2,6], [4,5]` are constructed from bits where the second number has two bits set: that of the first number, and the bit position to its right, wrapping around in 3 bits. This comes from the binary-list of the RPS game. We can do the set-next-bit with `*3` and enforce 3-bit wrapping with `%7`.
>
>
>
```
One of:
Rock wins: [3→2, 1→3]
Scissors wins: [5→1, 4→5]
Paper wins: [6→4, 2→6]
Ties: [0]
```
After which we can use `M` to only keep the largest value on the stack for our result:
```
One of:
Rock wins: [3, 3]
Scissors wins: [5, 5]
Paper wins: [6, 6]
Ties: [0]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ \$\cdots\$ ~~53~~ 52 bytes
Saved 3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!!
Saved 3 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [formula](https://codegolf.stackexchange.com/a/202941/9481) converted to \$3\$ for Rock, \$2\$ for Scissors, \$1\$ for Paper, and \$0\$ for a tie or only a single figure appearing.
```
f(r,s,p){r=s>p&p<=r&&r?3:p>r&r<=s&&s?2:r>s&s<=p&&p;}
```
[Try it online!](https://tio.run/##RZFBbsIwEEX3OcVvJKy4BInCjsThCK3aLruJjANWizOaCXSBOHvqhEIWljzvydb8GbvYW9v3Tca55KQvbKQiRaVhpXi73lDFiksjSsl2teFKlJSGlKLi2ttDzc@wbTg77jIfOgSNSwL59Z09ILtVsLU4rDdg1504IH1v7Xda3MVqEh/Wi7Qsk3yZ5FtNjieznMyndyPfuaY@/XSTeG1JngZ1Ta7JsfYh05dkaPMIg3WRNC1jbJvNsuDyWMznrBM8sEQsI5aIJ06R08jplhC@QcaYQ@IhGIOljmPpfDi5oTMQx3dNls52GNLjLIjXe97/ckyIRYWZfIU0B@eQHJQ/JnxfktbDpzFU/wc "C (gcc) – Try It Online")
] |
[Question]
[
[Sandbox post](https://codegolf.meta.stackexchange.com/a/18310/42248)
In this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, you are provided with a series of y values at even x-values as well as a console width and height. The desired output is an ASCII-art representation of a ribbon plot of the y-values scaled to the desired size. If all values are positive or negative, the x-axis should be displayed at the bottom or top respectively. Otherwise, the x-axis should be displayed at the appropriate position with the graph extending to the top and bottom.
The data should be scaled horizontally by splitting the data into sublists
of equal (+/- 1) size and taking the arithmetic mean of each sublist. There will never be fewer values than columns, but can be more.
Inspired by [this question](https://codegolf.stackexchange.com/q/196333/42248) which was posed as a tips in C question. Most similar question is [here](https://codegolf.stackexchange.com/q/3989/42248) but there are some important differences in terms of input (floats versus equation) and output style.
[Default loopholes apply.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
## Input/output
* [Default I/O rules apply.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* [Default loopholes forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* The y-values will be a list, array or equivalent of floating point numbers at least as long as the width of the console. These may be positive or negative. Choice of float type is at the discretion of the answerer. Y values should be rounded to the nearest integer after scaling to the relevant size; the default rounding method for 0.5s supported by the language is fine (rounding to even, rounding away from zero, etc.) (See [Wikipedia](https://en.wikipedia.org/wiki/Rounding#Rounding_to_the_nearest_integer) for a discussion of different rounding methods if this is an unfamiliar topic.) However, truncation/floor/ceiling are not permitted approaches.
* The range of y values will always be non-zero (i.e. there will be more than 1 y value, and there will be at least 2 different values).
* The console width and height will be two integers, with the height always at least 2.
* The output can be a return value or be output to STDOUT. If opting for a return value, this can be a single newline-separated string, a list of strings, a list of lists of characters or a matrix of characters.
* Any distinct character can be chosen for the filled area, but the blank area should be a space character.
* A separate non-space character should be used to indicate the x-axis.
* Trailing space on each line is optional.
## Worked example of how the data is scaled to width
```
Floats: 1.0,2.0,3.0,4.0,5.0
Width: 3
Split into three pieces: [1,2],[3,4],[5]
Take arithmetic mean of each: [1.5,3.5,5]
```
## Examples of full input/output
Input
```
Floats: [1.4330127018922192, 1.4740546219716173, 1.46726631732171, 1.4118917879852302, 1.3095749615197134, 1.1642846441770978, 0.98209964435211, 0.770867389064186, 0.5397574401179837, 0.29873801741462563, 0.05800851721072442, -0.17257624372014382, -0.38405389828888165, -0.5688402657187754, -0.7211228325469043, -0.8371379250265838, -0.915315134687127, -0.9562812209887335, -0.9627248583907679, -0.939132622452629, -0.8914149315594007, -0.8264477348143321, -0.7515611018951998, -0.6740091786833334, -0.6004570095761375, -0.5365184287338843, -0.48637567624364625, -0.45250583664959154, -0.4355319935803172, -0.43420862005149424, -0.445541730745404, -0.46503530191616943, -0.4870470099638535, -0.5052290073886498, -0.5130237273726901, -0.5041809629881258, -0.47326095136808916, -0.41608900827923856, -0.330130352731954, -0.21475893339455088, -0.07140098112303239, 0.09645778693148394, 0.28340343297327375, 0.4823565362517651, 0.6849507176587676, 0.8820035800170399, 1.0640505126834876, 1.2219075413197402, 1.3472273300168627, 1.433012701892219]
Width: 24
Height: 24
```
Output:
```
#
# #
## #
## ##
## ##
## ##
### ##
### ###
### ###
### ###
#### ####
#### ####
#### ####
#### ####
------------------------
###############
##############
##############
#############
####### ##
#####
#####
###
##
```
Input
```
Floats: [0.5, 3, 7.5, 14, 22.5, 33, 45.5, 60, 76.5, 95, 115.5, 138, 162.5, 189, 217.5, 248, 280.5, 315, 351.5, 390, 430.5, 473, 517.5, 564, 612.5, 663, 715.5, 770, 826.5, 885, 945.5, 1008, 1072.5, 1139, 1207.5, 1278, 1350.5, 1425, 1501.5, 1580, 1660.5, 1743, 1827.5, 1914, 2002.5, 2093, 2185.5, 2280, 2376.5, 2475]
Width: 24
Height: 24
```
Output
```
#
#
##
##
###
####
####
#####
######
######
#######
########
#########
#########
##########
###########
############
#############
##############
################
#################
###################
######################
------------------------
```
Input
```
Floats: [-4.0,0.0,0.0,4.0,2.0]
Width: 5
Height: 5
```
Output
```
#
##
-----
#
#
```
Input
```
Floats: [0.0,1.0,2.0,3.0]
Width: 4
Height: 4
```
Output
```
#
##
###
----
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~40~~ 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-7 thanks to NickKennedy!
```
œsÆm÷_ṂṀƊ$×⁵’¤ær0r0FṀ‘,_¥ƲṬSz0o⁶Y
```
A full program printing the result to STDOUT with `1`s for bars and `2`s for the x-axis.
**[Try it online!](https://tio.run/##VVO7apRBGH2VFJYxfPfLC/gCViKSykYiQqy0SlJY2FqovVpZCSrbZjHvkX2R9czMj@CSLMzZuZzb9@L5xcWb4/HPh9f7dy/3v8/vdzf3u6u79w/2Hw/XPw9Xn2@/7L9d0iU9Any4@nR6fvv17sf97vvjt/TqcP3ryfF4fMpnpkosSVwtwi2nJ8DSyC2wTA5OnVikRChWwskTYZzhrOxyUZonldrTOtjHWbWBcZiUhRlnUmedntBZl1A3MHVhHgh@q0itpjCuGJBrJ24zYsYbmgOTLmwiTmMQ9NABkhdROacwpZiBykM6w9IzxDSF2LQWqgVteKak8OHwiXoUcAlPrky3CeI6FikVeNFkOkHwYM0WH7tLa4LNrpCsFpUwc2EeUjhPXaCs650OAcHCwaaM7AVqs0qImON7YXAWChu3ehvRurIEjmWqFfQgh8XS2YN5BAjTexEKJEgjnCjFZ@kJIvOkEVFAw6Zcw7mQEDjCgyXSKvB7TPdi@LxQh2pQj7B2SF63IkKI71aEgHrIBpogTyFyqDDZtpo7WqCU5kYbFk7q6GCjatH/CCTZoNqh5Zt5eFykYQaIgsJSCtdJEHHiHynxthMdIpgN71l87TRUNyCeNYrgbyyUAwvURxAq3lroGAoFL1zLvQkVtvRq2NnQQbVupeRhdaEqOCDas5CotifcR4CGrG1Wt9RITaVBJKf/Q6ioB0IQ1BdJDCwK/uJerAslmbNQGBgaFqP6pN1jsDApBE9YEDIMi4GNGSYUmMEbHVhDaSl4UHE2kEnO4f1/7J8dxfD3Fw "Jelly – Try It Online")**
### How?
```
œsÆm÷_ṂṀƊ$×⁵’¤ær0r0FṀ‘,_¥ƲṬSz0o⁶Y - Main Link: values, width
œs - split (values) into (width) chunks
Æm - arithmetic mean (vectorises)
$ - last two links as a monad:
Ɗ - last three links as a monad:
Ṃ - minimum
_ - (left) subtract (minimum) (vectorises)
Ṁ - maximum
÷ - divide (vectorises)
¤ - nilad followed by link(s) as a nilad:
⁵ - third program argument (height)
’ - decrement
× - mutiply (vectorises)
ær0 - round to 0 decimal places (vectorises)
r0 - inclusive range to zero (vectorises)
Ʋ - last four links as a monad:
F - flatten
Ṁ - maximum
‘ - increment
¥ - last two links as a monad:
_ - subtract (vectorises)
, - pair
Ṭ - untruth (vectorises) (e.g. 3 -> [0,0,1])
S - sum (vectorises)
z0 - transpose with filler zero
o⁶ - logical OR with a space character (i.e. replace zeros)
Y - join with newline characters
- implicit, smashing print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
äÅAWUZX-I/I<LR*X+©δ@øD®dÏs®d_Ï_¹Å8s)J˜0ð:
```
Inputs in the order `width, [floats], height`.
Outputs as a list of lines with `1` for the bars and `8` for the x-axis.
Also doesn't round at all for more accurate scaling (similar output as the Jelly answer, which differs from the test cases for some bars).
[Try it online](https://tio.run/##VVO7alRRFO3zFWnVZNzvh1go2ESsBDFEJChaWFnMN6TOD1ja2IiFhWI3txT8pXGdey6CAzNw1pzHeu2P@zdvP7w/HpfPy83jly@uLs8v7l88fPb87uW9w5c/3x8tP54cvr5bbvf4vV5urw8/l5va33n6@xMt3x4cD7@OYieveGeqxJLE1SLccnYKLI3cAsvk4NQVi5QIxUo4eUUYZzgru1yU1pNK7Wkd7OOs2sA4TMrCjDOps85Oadcl1A1MXZgHgv8qUqspjCsG5NqJ24yY8YbmwKQLm4jTGAQ9dIDkRVTOKUwpZqByTjssPUNMU4hNa6Ja0IZnSgofDl9RjwIu4cmV6baCuI5FSgVeNJmuIHiwZouP3aW1gs2ukKwWlTBzYh5SOE9doKzznQ4BwcLBpozsCWqzSoiY43dicBYKG7d6G9G8sgSOZaoV9CCHydLZg3kECNN7EgokSCOcKMVn6gki86QRUUDDplzDuZAQOMKDKdIq8H@s7sXweaIO1aAeYe2QPG9FhBDfrQgB9ZANNEGeQuRQYbJtNXe0QCnNjTYsnNTRwUbVov8RSLJBtUPLN/PwuEjDDBAFhakUrpMg4sQXKfG2Ex0imA3vWXzuNFQ3IJ41iuBvTJQDC9RHECremugYCgUvXMu9CRW29GrY2dBBNW@l5GF1oSo4INprIVFtT7iPAA1Z21rdUiM1lQaRXP0fQkU9EIKgvkhiYFHwF/diXSjJOguFgaFhMapP2j0GC5NC8IQFIcOwGNiYYUKBGbzRgTmUloIHFWcDmeQ6vP@P/esTsb8) or [verify all test cases](https://tio.run/##VZS9jh1FEIXzfYpNgVtL/Vc3QgIkiwARIQE2lmWBICAi2GcwqV@AkIQECCyEhEjuDS0h3mg51T3XErve8cyZ7vr5TvX8cP/1N99/95Aff/Ho9Y8Pl58vLz768vOvHtOTd5@8/@lnbz9@5/zLP68@vPz56Pzrt5eX97g@v7x8fv7t378vL8b9W5@8/okvv7/3cP7rdP7jg/OrB/Ub/Hsqd27GosUypqpMPd1CK@fwxGNJStnSsjTT8KRSshTBHqlRc4Qar53GM8pnSvRe89YkXYenu1TxrHG65bs5lOeEZqEireDdyLIxOV1GthQ2C9GcRZDDqjWdA4tYygUFRlqLHIN5hJQKl7qjFOI7PEalupWyuI2t2kBvSDN04Ecylho5oGtGyagKXyLCieowBYvJbktEHWI1NXr1sLHEKWFo2TxHAebWInVgP8@Bkm3nmakocGDj5MqaW7QppqnqgevWQBYdTkSN6cw75FAQqzIf6Ac@7CpDIkXaQECfu6CEg9zm5DD87H6S2aO4LUr0cHRuGTLgEGoEg92kj8T7XPSyOW810DVKz/QZaHlHhYVofk6DCRgPPURX@KnMgS5cj6UegSkwLg/nQ8tgC8zgxKjlfFNAsXepM23EAQ/JVSdgoFCUsDsFdVZYXPiDS3KsxAwxYIO9aOyVjtFNNC@Wg8E3tyqJB4yPwlTk2mofCkNdCCvzaFTFK8YEzok@eOyoXNKoB0YFG9TmGkiMdhTow0CH175Gd5izuelEIbX4d6NqkTBBMb5worUc4Iu4eB4YknUWBg4MN2KMPtucfbBwUhhMRGEygGVrfYYZAyyoGzOwD6WXIqFhb8KTWof3/8f@2c3xQQC70y08qP5fULfqUiB59F0yXmbfzV4hS5Q@B5JrKSJil6wAGHVcxg4qfQlZ9xNR3Jbu/X2JvT4SGVNWnOyzXTs@Pg6nW0x/34/RuXcxAt/6WjuzNH1R3sVrf2rEgncrPcQSvPILQHbBud9VT51gAtbTXG0zr5g4vtbtjJUPXwPsw7jl7q7i2U3g9yn5HZ/4@Ot7veM3TGlloZ7slYE6AW2w1GRpd0PNlnZsmmvhbp8WXzoA0yJMB2JajOmATIsyHZhpcaYDNC3SdKCmxZoO2LRo04GbFm86gNMiTgdy2szpCp02dbpip82druBpk6cretrs6QqfNn264qfNn64G0HaArhbQ9oCuJtB2wW/W8PJJNvyTtQFvVGqZWqd@8R8). (Uses `»` in the footer to join the resulting list of lines by newlines to pretty-print it. The test suite will have the input-order as `height, width, [floats]` instead.)
**Explanation:**
```
ä # Split the second (implicit) input-list `floats` into the first (implicit)
# input-integer `width` amount of equal-sized parts
ÅA # Take the arithmetic mean of every inner sublist
W # Push the minimum of this list (without popping the list itself)
U # Pop and store it in variable `X`
Z # Push the maximum of this list (again without popping the list itself)
X- # Subtract the minimum `X` from it
I/ # Divide it by the third input `height`
I<L # Push a list in the range [1, `height`-1]
R # Reverse it to [`height`-1, 1]
* # Multiply each value by the (max-min)/height we calculated
X+ # And add the minimum `X`
© # Store this list of y-axis steps in variable `®` (without popping)
δ # Apply double-vectorized on the arithmetic mean and y-step lists:
@ # Check >= among the two
ø # Zip/transpose this matrix (swapping rows/columns)
D # Duplicate it
® # Push the y-steps again from variable `®`
d # Check for each whether its non-negative (>= 0)
Ï # And only leave those inner sublists of the matrix (top part)
s # Swap to get the duplicated list again
®d_Ï # Do the same, but this time for all negative values (bottom part)
_ # Invert each (0 becomes 1; everything else becomes 0)
¹Å8 # Push a list with the first input `width` amount of 8s
s # Swap so the stack order is: top-part, x-axis, bottom-part
) # Wrap these three into a list
J # Join each inner(-most) list of digits to a single string
˜ # Flatten it to a single list of string lines
0ð: # And replace all 0s with spaces
# (after which the resulting list of lines is output implicitly as result)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~324~~ ~~312~~ 298 bytes
```
import Data.List
l=genericLength
(!)=replicate
0#_=[]
w#x=take n x:(w-1)#(drop n x)where n=ceiling(l x/w)
d x=transpose$(++).(!'#')<*>(!' ').(maximum x-).max 0<$>x
w?h=((++).reverse.d<*>((round w)!'-':).d.map(*(-1))).(\x->round.(*(((h-1)/).((-).maximum<*>minimum).(0:))x)<$>x).map((/).sum<*>l).(w#)
```
[Try it online!](https://tio.run/##VVVNbxs3EL3rV6xhA95NVpuZITkkjci59Ohbjq5RKPLWFiLJwkqu1Ev/uvuGVAp0Ia3Ix/l8M0O9Lg8/x83m42O93b9Nx@a35XE5PKwPx9lm8TLuxmm9ehh3L8fXWXvVLaZxv1mvlsdxRtd/LB6fZqfr8@K4/Dk2u@Z8157m3F23z9Pb3vbd6XWccLJYjevNevfSbprzl1M3e26gMy13h/3bYbxpP3/uhvbq9vq2@/rpHovmFvvt8rzevm@b87wbsG7o6839eXb69rpoi8I0/jVOh3F4Np12envfPTen7up2fnvXDc9Q2befWkTTwdbv5/l9kRiAte0r4C@A22ra3MDIdr2zFXC667pzZ/66YqeF8KHIbHB6uu4@juPheFg8tuJ7fB558M4RSyROWYSz9A2w6Cl4xTaycnQF0yiqDjvhyAVh6HBMMacgjoqmoxyiz8rBdJ03jNVL8uo9x0g5pr6hISehnIG5IMyG4CxpdCmTek5qUHA5wponZvhw0TDJCULE0TMCDOoMpJCIUuAoTFG8RyhzGrANUcW7KMTepYq6hNzgJknCwxoKGjQBFw2RU4zBFxDmWCQ5AReZvCsg4mAXswSTTi4VMHNwSNl5TRFkViyoJOhTTgjZVT9ZBQEmKGaKGnMFXWYnKuID3hUDs8gww2rInqiaTALGYnQ@IR/UoUYZOCizFRCk5xqQooJkxdHk8NR8lMiHSFYiRQ6XzJ0GTqgQYgQHNUmfFOda2FPjuaIBWSN0VZ8DUq5WUUIkn7NDEdAecgG9oJ5CFJCFl4uoDwFd4Cj64OmCaSAX0IMZrab5vwAieQs1q0vhQh6ci2SQgUARQs0UrJOgxBFfVIkvkughAtngniVUSY/WVSTPThOBX60oKzZoH0FR4auiNhQOccEs50uiwj6GlEFnRh6UqlWKbFQntAoUxOXSkGjtEME@CuhRa19aNzlPzjvJCCQW/i1RcUFRBEH7ohKGaQK/sIt9QpOUWUgYGDKK0frkcrbBwqQQOGFBkUGYGmYzTGhgRtzogTqUPgocOugqahLL8P5/7J@6/teVAPb6BlWI9suIXKQggHywlRIO1VbZJLiAbJPAWkRhE1pcDKDZ8UrVKNsrcFlnWPGu4N5umFDlg8KjcrGjNt2x2sf10Dfof1unZL5rMIzK2TtWz2z8s1ANXuyyYReopmJtzIGKfwaVFrDWs2h9x@iBssslbaJiEwPsLJ1U/OE@gB4aTmt2MRh1oQ/949wP1NPla2sZyA59X1ilnivWO8OfZu@71fs0/e2aP5t/2mX/o191zQKbZfOjWc22y/VusX8/fj9OD7ub9x3@hcbDjV3ql/XwS7/91nXlWv/4Fw "Haskell – Try It Online")
A lot longer than the other answers, ~~but I would already be happy to get it under 300 bytes.~~ It also gives a slightly different result for test-case 2 (the 16th column is 11 high instead of 10), but I'm not sure how to fix that. I guess it's the difference in rounding methods? Haskell rounds 0.5 to even as far as I know.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ 26 bytes
```
äÅAÐδ-àI<//òÝMαεðIиāΘyǝ}øJ
```
[Try it online!](https://tio.run/##VVO7apRBGO3zFHmAZPPdL2CTMoJPIBYKFlYWVhYWKewtbQIpfAAVhYCdv2C3@EbrmZkfwYVdmLNzObfv9ZvnL169PJ22T9v76@3D8dvldn/z6Opq@7rdPTl@OX7fPt/8efh1e/z49vfdu@3h8ennj5PY2VM@mCqxJHG1CLdcnANLI7fAMjk4dWKREqFYCSdPhHGGs7LLRWmeVGpP62AfZ9UGxmFSFmacSZ11cU6HLqFuYOrCPBD8V5FaTWFcMSDXTtxmxIw3NAcmXdhEnMYg6KEDJC@ick5hSjEDlUs6YOkZYppCbFoL1YI2PFNS@HD4RD0KuIQnV6bbBHEdi5QKvGgynSB4sGaLj92lNcFmV0hWi0qYuTAPKZynLlDW9U6HgGDhYFNG9gK1WSVEzPG7MDgLhY1bvY1oXVkCxzLVCnqQw2Lp7ME8AoTpvQgFEqQRTpTis/QEkXnSiCigYVeu4VxICBzhwRJpFfg/pnsxfF6oQzWoR1g7JK9bESHEdytCQD1kB02QpxA5VJjsW80dLVBKc6MdCyd1dLBRteh/BJJsUO3Q8t08PC7SMANEQWEpheskiDjxRUq870SHCGbDexZfOw3VDYhnjSL4GwvlwAL1EYSKtxY6hkLBC9dy70KFLb0adjZ0UK1bKXlYXagKDoj2LCSq7Qn3EaAha5vVLTVSU2kQyen/ECrqgRAE9UUSA4uCv7gX60JJ5iwUBoaGxag@afcYLEwKwRMWhAzDYmBjhgkFZvBGB9ZQWgoeVJwNZJJzeP8f@2dnYn8B "05AB1E – Try It Online") or [validate all test cases](https://tio.run/##VZS/il1VFMb7eYp5gLtu1v@1NwgSCBaCrRBCCgULqxRWFhYpYp0yTcDCB1CJErCbK1gIg280fmvvcwecmXvnnO/svf78vrXPq@@@@vrbbx7ysy@f/fPjw@Xny5unl7f3H@jy0/NPnjy5/HZ5/8X9r/e/X355/u/Hv17fv/v@7/c/XD5@/nD35@nuj0/vPjyo3@DvhZzdjEWLZUxVmXq6hVbO4YnbkpSypWVppuFOpWQpgj1So@YINV47jWeUz5ToveatSboOT3ep4lnjdMvnOZTnhGahIq3g2ciyMTldRrYUNgvRnEWQw6o1nQOLWMoFBUZaixyDeYSUCpe6oxTiM26jUt1KWdzGVm2gN6QZOvAjGUuNHNA1o2RUhS8R4UR1mILFZLclog6xmhq9ethY4pQwtGyeowBza5E6sJ/nQMm288xUFDiwcXJlzS3aFNNU9cD31kAWHU5EjenMO@RQEKsyH@gHPuwqQyJF2kBAn7ughIPc5uQw/Ox@ktmjuC1K9HB0bhky4BBqBIPdpI/E81z0sjlvNdA1Ss/0GWh5R4WFaH5OgwkYDz1EV/ipzIEuXI@lHoEpMC4P50PLYAvM4MSo5XwsoNi71Jk24oCH5KoTMFAoStidgjorLC584JIcKzFDDNhgLxp7pWN0E82L5WDwza1K4gbjozAVubbah8JQF8LKPBpV8YoxgXOiDx47Kpc06oFRwQa1uQYSox0F@jDQ4bWv0R3mbG46UUgt/t2oWiRMUIwvnGgtB/giLu4HhmSdhYEDw40Yo882Zx8snBQGE1GYDGDZWp9hxgAL6sYM7EPppUho2JvwpNbh/f@xf3lzvBDA7nQLD6r/C@pWXQokj75KxsPsq9krZInS50ByLUVE7JIVAKOOr7GDSn@FrOuJKG5L936/xF4fiYwpK0722a4dHy@H0y2mv6/H6Ny7GIFv/V07szR9Ud7Fa79qxIJ3Kz3EErzyC0B2wbmfVU@dYALW3VxtM6@YOL7W7YyVD28D7MO45e6u4uVN4PcF@ZlPfHz6Ws/8yJRWFurJXhmoE9AGS02WdjfUbGnHprkW7vZp8aUDMC3CdCCmxZgOyLQo04GZFmc6QNMiTQdqWqzpgE2LNh24afGmAzgt4nQgp82crtBpU6crdtrc6QqeNnm6oqfNnq7wadOnK37a/OlqAG0H6GoBbQ/oagJtF/xmDS@fZMM/WRvwqFLL1Dr1g/8A).
```
# scale and round the values
ä # split the list of values in width sublists
ÅA # arithmetic mean of each sublist
Ð # triplicate
δ- # double-vectorized subtraction
à # maximum
I</ # divide by (height - 1)
/ # divide the list by the result
ò # round to nearest integer
# draw the plot
M # maximum of the stack
α # absolute difference of each value with this max
ε } # for each difference y:
ðIи # a space character, repeated width times
āΘ # list [1, 0, 0, 0, ...] (width elements)
yǝ # replace characters at the indices in y
ø # transpose
J # join
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
⊞θ⁰≧×∕⊖ζ⁻⌈θ⌊θθ⊟θFη«≔÷Lθ⁻ηιι≦∕ΣEι⊟θιP↑⁺⊘³ιP↓⁻⊘³ι←¹
```
[Try it online!](https://tio.run/##ZVPLbhtHEDxbX7HHFUAL/ZruHvsUQIcEsADBSU6GD4RMiwtQ1IOUEtjwtzM1O2sBSQiQ4NT0o7qq52a7frq5X@9Op@vnw3Z8XA10/v7sav3wy@Ew3e4/Trfb4/jHdLc5rIbL6WX6shkvNzdPm7vN/rj5Mn47Xw1X0/75MF6t/57unu/Gx44s/89xekTB66dpfxyv7x8a9v7s6/3TMG7Ph@9nb3qf8bf9cSn/YbO/PW5/1kHl7WqYWp0JiW9emX3YfD2OPWU1/I5muBmn1bD0eI1/3h2nh7n7uz8fcL1DxV/XuxeQ1znov1GX93/tf7b@X2Cf411rvhoYyI/T6dMnvjBVYgnirCJcBZcXFkbFHMdg59AZ8xB3xUk4eEYYORwZNYsozZlKtYRV59Jy1RrGbpLmZhxBNRJGXdQUqhWYFmFuCO7SQ7OSG6c3qGgNVDNiRg@NhklNBBGHMQgW1wZSSaIsHMIUYgYqb@kCxxIupiHEptlRTcyGNimJD3uZ0eIJXLwEZ0SxGUQ5FkkVaFHJdAbBgzWqlBadmjNYuShGVvMMiNmx4pLIp5qgrL1PdQHBRGKl8Kgd1MoqLmIFvx2DspiwomqpRtRLpkCxCLXEPPChsyxcnLkZCNFrJ@RwkJo5nopPn8eJrAQ1ixwzLJOrF044BI7QoA9p6bj3WT1vOne0YGpQd7daMHKvCgsxfK0KE7AesoAm8FOICqYwWUKtFGyBUlgxWjAvpAU7WLFqXl8JBFmjWl2zLOKhuUiFGCAKCn1SqE4CiwNfuMRLJHaIIDa0Zyk90rC6juFZPQn6ekfZccD6CExFr462R6HghbJcl0GFLUpWyFkxB2WvSsFN6sSqIEG0zguJ1S4B9WGgwWubVzfVSE2lgkjM@rdBRYvDBMH6womGeUJf1MU5sSTzW0g8GGoSY/VJa20PCy@FoAkLTIZg3rD2hgkLzOCNHeiP0kLQUJHr8CTmx/vvZ/95NTSPxD6f3r7s/gE "Charcoal – Try It Online") Link is to verbose version of code. Uses `|` as the drawing character. I'm not sure I've got all of the desired calculations, but I am now using the latest array splitting, which allowed me to save 9 bytes. Explanation:
```
⊞θ⁰≧×∕⊖ζ⁻⌈θ⌊θθ⊟θ
```
Temporarily add a `0` to the array so that the values can be scaled to the desired height.
```
Fη«
```
Loop over the width. Although this loop counts up, the array is actually processed from right-to-left.
```
≔÷Lθ⁻ηιι
```
Calculate how many array elements to pop.
```
≦∕ΣEι⊟θι
```
Pop that many elements and calculate the mean.
```
P↑⁺⊘³ιP↓⁻⊘³ι←¹
```
Print the desired amount upwards or downwards as applicable, then print the X-axis in a leftward direction.
] |
[Question]
[
You’re given two \$r×c\$ grids. Each cell contains either 0 or 1. What are the minimum number of swaps (between horizontally and vertically adjacent cell elements, no wrapping i.e no swapping between last and first element of a row) are required in the first grid for it to match the second. If the matched arrangement can never be achieved, output -1.
**Constraints**
\$1 \leq r \leq 100\$
\$1 \leq c \leq 100 \$
**Examples**
```
input:
00
11
01
10
output:
1
input:
00
11
01
00
output:
-1
input:
0011011
0101101
output:
2
```
[Answer]
# [Python 3](https://docs.python.org/3/), 383 334 bytes
*-6 bytes thanks to @Kevin Cruijssen*
*-43 bytes thanks to @Jitse*
```
import numpy
z=len
d=lambda a,b,c,d:abs(a-c)+abs(b-d)
def g(l,m):
if z(l)==1:yield d(*l[0],*m[0])
for i in range(z(l)):
for s in g(l[1:],m[:i]+m[i+1:]):yield d(*l[0],*m[i])+s
def c(a,b):
e=a-b;k=z(a);f,*h=[],
for x in range(k*z(a[0])):w=[(x%k,x//k)];v=e[x%k][x//k];f+=w*(v>0);h+=w*(v<0)
return-1 if numpy.sum(e)else min(g(f,h))
```
[Try it online!](https://tio.run/##nZBLboQwDIb3nCKbSjaEDqg7aHqRKIsAYYhIMigwD@byNIFFpbZSpW4s27/9@TGty3Bxb9um7XTxC3FXO63Jkxnlko4ZaZtOEkkb2tKuks0MMm8xi06Td5h0qidnMNRilRDdkycYZKysVq1MRzpIDS8ETW2wmJD@4okm2hEv3VlBLI59e36O@YDiZSWo5ZUWmeU6CxH@pGmB2bwPbyEsFyGKybypR/YEiXVP04FxQY@Rj6@RYxr0uAxWd8bh8TLSx@k0oqhvTPEQCh5jUfcZu6dw@yiwHg73vQgXeLVcvcvLeOv@qtf5akGhMrMiVjs4Q08HxG3y2i3QwlEkvZcrcF7QsD8vaSkEUvJdK3etCBpi8l9A8SeAhvbD/g75qthB2yc "Python 3 – Try It Online")
Takes input as two numpy arrays.
### Explanation:
First, `e=a-b` determines which positions change from one grid to the other.
The next line finds all of the differences and sorts them into the lists `f`
and `h`. If the sum of differences is not zero, meaning there are more 1s in
one grid than the other, this returns `-1`, or the minimum of all possible
paths found by `g`.
This is the fun part. Essentially, in order to make this work, a 1 must move from one position to another by swapping. Therefore, the minimum number of swaps for each pair is the manhattan distance between them, found in `d`. `g`
finds every possible pairing between start and end points and returns a list
of the total distances between them. If there is only one start point, it returns the distance between that and the end point. Beyond that, it pairs the first start point with each end point iteratively and adds their distance to the total distance of the rest of the points, calculated recursively.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 35 bytes
```
{⍺≠⍥≢⍵:¯1⋄⌊/⍺[⌂pmat≢⍺]+.(1⊥∘|-)⍵}⍥⍸
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR765HnQse9S591LnoUe9Wq0PrDR91tzzq6dIHykQ/6mkqyE0sAcvtitXW0zB81LX0UceMGl1NoOJakLbeHf/THrVNeNTb96ir@dB640dtEx/1TQ0OcgaSIR6ewf@BtHOkenFiTom6AtBohdS8xKSc1GBHnxCu2KT8isy8dIX8PC6NRKAhRgpGj3q3GCgYKBgqGGpqlCMJAQUUDDS5EhXSFMqJUGyApthQwRyhGFkLTMIQIQXVCAA "APL (Dyalog Extended) – Try It Online")
A function that takes two Boolean matrices as left and right arguments.
Uses [Hiatsu's algorithm](https://codegolf.stackexchange.com/a/190381/78410). One additional thing to point out is that, while moving a 1 from some position to another, it may freely step over some ones and still take the same steps. Therefore, the pairwise Manhattan distances can be summed without interfering each other. (This doesn't invalidate the previous answers; rather, it covers a hole in the proof that the algorithm is indeed correct.)
```
Moving the one at the start to the end:
1 0 0 0 0 1 1 1 0 0 0
^-------> Move the 1 four steps forward
0 0 0 0 1 1 1 1 0 0 0
<-------^ Move the 0 four steps backwards
0 0 0 0 0 1 1 1 1 0 0 (See that the target 1 has moved 4 steps forward as net effect)
^---> Finally move the 1 to the destination
0 0 0 0 0 1 1 1 0 0 1
So the 1 has travelled the distance of 10 in 10 steps, stepping over ones
```
### How it works: the code
```
{⍺≠⍥≢⍵:¯1⋄⌊/⍺[⌂pmat≢⍺]+.(1⊥∘|-)⍵}⍥⍸ ⍝ Main function
{ }⍥⍸ ⍝ Extract coordinates of ones from both args
⍺≠⍥≢⍵: ⍝ If the lengths (count of ones) do not match,
¯1 ⍝ Return minus 1
⋄ ⍝ Otherwise,
⍺[⌂pmat≢⍺] ⍝ All permutations of coordinates of left arg
+.(1⊥∘|-)⍵ ⍝ Inner product with ⍵ to get Manhattan distance sum:
(1⊥∘|-) ⍝ sum the absolute differences of coords point-wise
+. ⍝ and sum all the distances
⌊/ ⍝ Pick the minimum value
```
[Answer]
>
> Based on [@Hiatsu's answer](https://codegolf.stackexchange.com/a/190381/80244).
>
>
>
# [Python 3](https://docs.python.org/3/), 262 bytes
```
e=enumerate
def f(r,s):
if not r:yield 0
for i,t in e(r):yield abs(t[0]-s[0][0])+abs(t[1]-s[0][1])+min(f(r[:i]+r[i+1:],s[1:]))
def g(x,y):
z=x-y;n=len(x.T);v,*w=[],
for i,p in e(z.flat):t=[(i%n,i//n)];v+=t*(p>0);w+=t*(p<0)
return-1if z.sum()else min(f(v,w))
```
[Try it online!](https://tio.run/##nVBNa4QwEL37K@ZSyKyjm9Cbrv0VvYUcLBu3AY0hxq/98zbVLYVSKBTCI3lv5r3MuDW89/Z523Sl7dhpXwedXHUDDfM0YJGAacD2AXyxGt1egSfQ9B4MBTAWNPP4EOq3gQXJVTZEiAfTgxEPRkSmM5ZFY1kYlXppUlEoGmRExD30xhZaP0Pv1ZKtpa1abdmSv2I50WmupKKvdHek3/OmrQMWoZLMPFky57NFVU5pFU7MvXAs5@N64ZiA12H0NhNxpHs@jB1D3Q4ajl9NNCNupnO9DxBX4dbEeWMDu7H9ldfe1yuTkhNXJAUJpZDgpyZ2jUctzvRfA/6nAcX2A383@a7YjbYP "Python 3 – Try It Online")
] |
[Question]
[
Your task is to take a 24 BPP sRGB image and output the same image upscaled 3x into red, green, and blue subpixels. The resulting image will be made entirely of pure black, red, green, and blue pixels.
Each pixel from the source image, when zoomed, produces an arrangement of 9 sub-pixels that can be either on or off (i.e. their respective color or black). The specific arrangement uses three columns of red, green, and blue, in that order, like so:
[](https://i.stack.imgur.com/EqbgU.png)
*(Note that the borders on these "pixels" are for demonstration only.)*
Since each of the nine subpixels can only be on or off, you will have to quantize the input image and use different subpixel patterns to achieve 3 levels of brightness.
For each subpixel in the image:
* For color levels 0-74, all subpixels should be black.
* For color levels 75-134, the middle subpixel should be the respective color and the other two should be black.
* For color levels 135-179, the middle subpixel should be black and the other two should be the respective color
* For color levels 180-255, all three subpixels should be their respective color
*I chose these level ranges because those are what happened to look good*
Apply this transformation to every pixel in the image and output the subpixel-upscaled image.
## Single-pixel examples
rgb(40, 130, 175) will produce this pattern:
[](https://i.stack.imgur.com/du09P.png)
rgb(160, 240, 100) will produce this pattern:
[](https://i.stack.imgur.com/4pBCK.png)
# Full Image Examples
[](https://i.stack.imgur.com/1BCtA.png) [](https://i.stack.imgur.com/2A2Sp.png)
[](https://i.stack.imgur.com/LZb1S.png) [](https://i.stack.imgur.com/J251d.png)
[](https://i.stack.imgur.com/AO0Nj.png) [](https://i.stack.imgur.com/Phmnb.png)
*Images sourced from Wikipedia*
# Rules and notes
* Input and output may be in any convenient format, whether that's actual image files or (possibly nested) lists of RGB values.
* You may assume the pixels are in the sRGB colorspace with 24BPP.
Happy golfing!
[Answer]
# JavaScript (Node, Chrome, Firefox), 111 bytes
I/O format: matrix of `[R,G,B]` values.
```
a=>[...a,...a,...a].map((r,y)=>r.flat().map((_,x)=>a[y/3|0][x/3|0].map(v=>x--%3|511+y%3%2*3104>>v/15&1?0:255)))
```
[Try it online!](https://tio.run/##PYpBCoMwFAX3nsKNJWljzDfNppD0ICGUj9ViSY2oiIJ3t8FCN/Ng3rxxxrEa2n7Ku/Cs90bvqI3lnCP7w/EP9oQMbKXaDLzxOBH6cw@2RId2LeQmnF2OOa5ZmyXPM7kpgMuayaw8SxBXY@YC1Anu4lYqRSndq9CNwdfchxdpiE3S1FooBUtBRcTIucTF7gs "JavaScript (Node.js) – Try It Online") (just a single pixel)
### How?
All threshold values are multiples of 15. Instead of doing explicit comparison tests, it's a bit shorter to test a bitmask where each bit represents an interval of 15 values (except the most significant bit which is mapped to a single value).
```
bit | range | top/bottom | middle
-----+---------+------------+--------
0 | 0- 14 | off | off
1 | 15- 29 | off | off
2 | 30- 44 | off | off
3 | 45- 59 | off | off
4 | 60- 74 | off | off
5 | 75- 89 | off | on
6 | 90-104 | off | on
7 | 105-119 | off | on
8 | 120-134 | off | on
9 | 135-149 | on | off
10 | 150-164 | on | off
11 | 165-179 | on | off
12 | 180-194 | on | on
13 | 195-209 | on | on
14 | 210-224 | on | on
15 | 225-239 | on | on
16 | 240-254 | on | on
17 | 255 | on | on
```
We encode **off** as \$1\$ and **on** as \$0\$ in order to maximize the number of leading zeros.
We get:
* `000000000111111111` for top and bottom pixels (\$511\$ in decimal)
* `000000111000011111` for the middle pixel (\$3615\$ in decimal)
### Commented
```
a => // a[] = input matrix
[...a, ...a, ...a] // create a new matrix with 3 times more rows
.map((r, y) => // for each row r[] at position y:
r.flat() // turn [[R,G,B],[R,G,B],...] into [R,G,B,R,G,B,...]
// i.e. create a new list with 3 times more columns
.map((_, x) => // for each value at position x:
a[y / 3 | 0] // get [R,G,B] from the original matrix
[x / 3 | 0] // for the pixel at position (floor(x/3), floor(y/3))
.map(v => // for each component v:
x-- % 3 | // 1) yield a non-zero value if this is not the component
// that we're interested in at this position
511 + // 2) use either 511 for top and bottom pixels
y % 3 % 2 * 3104 // or 3615 for the middle pixel (y mod 3 = 1)
>> v / 15 // divide v by 15
& 1 // and test the corresponding bit
? // if either of the above tests is truthy:
0 // yield 0
: // else:
255 // yield 255
) // end of map() over RGB components
) // end of map() over columns
) // end of map() over rows
```
### Example
The following code snippet processes the head of Mona Lisa (64x64). Doesn't work on Edge.
```
f=
a=>[...a,...a,...a].map((r,y)=>r.flat().map((_,x)=>a[y/3|0][x/3|0].map(v=>x--%3|511+y%3%2*3104>>v/15&1?0:255)))
var img;
(img = new Image).onload = function(){
var ctx = document.getElementById('c').getContext('2d');
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, 192, 192), x, y, ptr, a = [];
for(ptr = y = 0; y < 64; y++) {
for(a[y] = [], x = 0; x < 64; x++) {
a[y][x] = [data.data[ptr++], data.data[ptr++], data.data[ptr++]];
ptr++;
}
ptr += 512;
}
a = f(a);
for(ptr = y = 0; y < 192; y++) {
for(x = 0; x < 192; x++) {
data.data[ptr++] = a[y][x][0];
data.data[ptr++] = a[y][x][1];
data.data[ptr++] = a[y][x][2];
data.data[ptr++] = 255;
}
}
ctx.putImageData(data, 0, 0);
};
document.getElementById('img').src = img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAgAElEQVR4nD2713fcx5W2i4tzzowlJoROv9S5G42c0QiNnFMDDXQjg0gEM0iAQUwAkUMjZwIEcxZzEEUry5Y1I2ssWcGSLFmyZjxJ33z/w3Mu6DUXe9XNvnr2u6veqlo7oG+0grPjbs6OV9E3WkXfqIfTo1WcGfNwasRN/3g1/eNVDE97GZj0MOj30D9ewcCEm6GxCvqGijh1Np+B0TLODJZwZqCcoTEfI+N1DIz4ODNcy5nRBvommugfb6BvxMvgUA2DA9WMTzQzMt7M8GQLQ/6dDPqbGZxoZmiimYHxOvrGPPRPeDg17ObMSDWnR3ycHPFxeqyOU2N1nJ5ooH+qmbPTLQzMtdE/18YpfzOnJus5OV7L4FQDZ8ZqODlUSd9kHadHPJwccnNqyM3ZcS/9Ez4CBscr6B8pYWC8gmF/NcP+GgbGK+kbLad/rIKzY24GJ6oYnalhZLqasZkaBifcDPvdjE1UMDRSTN9gAcMT5QyMlnN22M3QuJfRcR8j4z6GJ+sZnm5iYKqBoblG+qe8DI1VMjHhYXy8htHJ2pf5Mw0M+b2MzzQyMlHLwKiHoXEPfSNu+kc9nBz0cGrIy5lRH0NTTZz1NzA408zZqUbO+OsZmGlkcLaewZl6zk7VMjRdz9B0Hf0TNfSNVzMwWc3p4Qr6RyoYGK1iYLyaMyMeAiZna5icq2ZixsOov5LJWS+j/iqGxssZHC9j1F/F5KyX4YlKxqY8jPqrGJl0MzXvwz9dxcRkOaNjpYxOVDA64WZy2sv4VA3Dk17GpusYmfIxMuFjYrqe8cnalzHhY3i4mrHxBkbHGxn3tzDqb2Z0uonRyVpGx6sYHa9ieMzN4FglfaOVnB6t5syol9MjXvrGfPSP1/4dQhODM00MzzYyNFXN2FwtQ1M1jMzUMuj3cnq0ilMjlfSPVdA3XELfYDEDI+UMjlRxetBNwOScj6kFH+Mz1QyOlXN2pBT/nJeJGQ/Dk2WM+iuZmKn5OxQ349M1jPqrGZ+uYWrGw/hEBROTlYyNv1xnZmuYnKxkdLKacb+XiYka5qfqWZxsYKrPw8DhQo50pNDdksSeulh2+WLY15TM4Q4Xpw4VMHymkpEBN2NDlUyMVTM65qF/xM2JoXLOjFfTN1pD30gN/WNe+sa9DPjrGJx6We0hfyWjM9UMTlYy/HcIZ0Yr/95CpfQNFTE4UsrAcCmDwxUMjlYTMDZbh3+xnpnlJkb8NQyOuRn1VzHqdzM4WsrQhJsRv4fxGS+jU9WMTXsZm/Ix6vcyMeNjaq6OiclqxscqmZmuYWWxloXpSlZm6lmfaWaoJ5c9nlAasgQ8SSpKowKpjFHjjZdxRwpURcuUhWkpClWTqd9CVtgOCpI11BXZOdKZzcCxCkYHqhkaqWFgrIa+4SqGJus4O1bD2XEvwzMNDPrrGJj0MT5fz9hcHZMLjYzPNzDo93J2vJqBiRoGxqsYnqikf6iE/sFihserGJ30EjCz2o5/sYmppRbGZuoZmfQyPv2yDUb8lYzN1jA6U8PkfD3++UYm5xtf5k3VMrnQzMRMAzOzTfgnvSzP17E272VpsozjLdH4krdTn7SNhqQg6hJVlIcHUpOgUBSmoSxKpihMpCRCT0mEnqJwiQKHQK5NIMcskGfWkqlsJ8u6DV+ulZOHShgbqaN/xMPAeDUD49UM+2sZm21keLqOkel6JhaamVhoYXSugeGZOkam6xjy1zI44eXsmIfBcQ+jk9UMDJdxdriMgbEqAmaXW5hZrGd2uYmF1VZmF5sZn6phbqmBqXkvU8s+ZpbrGfN7mJzxMbvUyORsLeOztfgXm5ldbGJmxsv8VDXnZmoZOpTBzlwNnsh/pDHuVfZlqugp1LMnW48vXoc7RkdxpEh+uExOqEi2QybdKpJiEUk260izyBSFmSkJVSi1asgUt5AmbyNe2k5pWhhnjpQzOlzC+Hg5k1ONDPsbGfR7GZ2vZ3KphfGFJoZn6l9CmapjcLyavuEKBsaqGZzwMjzpZWi8mhG/l8GJGgIWVppZWmtmYaWR2YUGVs61MbfYwMJyPSvrTcyvepld8jG3VM/CchOLqy1ML9QxvVjP7GoD84u1bCzXMTdSymu74qhOfpXGhG3sTA5kb1YQx8t09NWY2Jero80l0pAqU50oURkvUxotURQpk2UTyLQrJMpqYiQVMXIIqUYVhXYd5eEKBVaJZG0QYTu2EKHdwp6GWCaGi5gY9zDub2PI38D4Qi0TCw2MzTUwMtvA0JSPkalaRiZrmJj2MuKvZWC85iWUCe9LGP5aAhZXW5hbqmd+qYG5xXoWlhuZXfCxfK6Btc0mltd8LK81ML9Uz/xKM4trbSytdzC70sz0chWrSzWsjlXQ2xiGN20r7bkqdudq6CkROFwURL9PYKhBz4F8FbtzRVozRZrTBeqStdQmS3jiJMoiZXLtElkWmXhFJEIRCBdCCAvZRpIUQrpBRa5JQ6oQjGNHIMZt/4g7z4J/vIrp6XomZ1oYn2lgZqWZ6eUWplZaGZtrZGK+ifHZeqbmGpicb2JwwsvQpI+hSR/D/lpGp+sJmF9uxD9Ty+JKE/NLDSysNLC01sj6xRaWz/lYXatl9Vwjy+daWN7oYG61jYVznSyudzC/VMXieBm9dQ46cwT2FxvZXyzTUy7RU6LiNbeaud0OBusUjpRI9JRa2FdooivHyK4sM53ZNuqSDZRHSxSGS+TYdKRbJBJNCmGCFptGjSU4iHB1IAnCDpLEYCJVaqzb1ChbtpESo2ZyvIjJyQqmplqYXqhncqGeqeUWZlbb8S/txL/YwuR8ExNzTQxN+hidrmdkqu5/1RCwvN7G7EITc4uNLCw3sHyuiZX1JpbXG1lYrWVjo4W19RbmlptZXO9kbrWdlfXdLK22szpXx4HaUFozdOzLMdJdZOaI28jJagMn3CJnfTJTHTaGGoycqDDQW2LiQJ6BvXkW2lxGGpwSvmSFijiR4igd+RE6sqwa0gwaYmUt4bKMXVQwqTQYtm/HoQoiTBWEI0SHaasG8dUt5KbKzE3VMDfrYXahlpnlRhbWO5lb72RqpQ3/Uiv+pVaG/bUMTfoYn21kZKqO8dnGly2wstHB4kobC8stzC81sLqxk7WNVlbO7WRtvZWVtZ0srrawtN7JwrlOzl3Yy/r5PVw4v48TXen4UkLoylbYn6ent9zAkXINpz0ahupElvdHcP5INJNtBvq8Eq+5RY6UajmQr6UzU0Nzqpq6ZC2eBIHSGIGiKJFsq5p0QwgJUghhGjWhgoxJJaIPFjAGarAFqYgSRBxqDYatOsRfqfCWRDE3U8Hich0rG20snu9keqWN6bVOplY7mVhsZWym4X+rPzH3UhHjs40ErGx0srzawfJaG7ML9axvdrC20c7axi7WNrpYWe9k9cIezl05wNL53Zzb3MvFC3uZG6+lIVOmNUOmK0dkX5GWU/V65vY5uPpaHM/8WTybcfH2ShZvreTyeDqLG/1JXD0dz9rhSGZ2hXK6Rk+7KxhvXAjlkQLFDplcu540i0SioiVW1BCv6AnTyhi2azEFipgDtdhVGkLVIvqtIvKrEsrW7XQ1Z7OwUMfqRhsT8w1MLDbjX+nAv9rJ9NouJuaamFrcycxyG1OLO5ldace/0ELAyrkO1ta7WF5rY3GlmbWNNtY22jm30cna+i42Luxl/fJB1i4dZen8Yc5f3MvmWiv76mNpzTTSkaliuMXMlb5U3lgo4TebHn5/pZI/3q7ms9sVfHanjD/cLue3Fwt4by2bt5bSeTbl5PG4k1t9KSzsjuJ4hZnWFAlftEKBXSLLoeCyGogXBWJFCVuQGluwhHGHgFUlYtihQr9Fg2GbiClQRHxViylEzUhfFQuLDcwstTO93M70Wgsz67uZ2+xmfr2LuXOdzK52MLfWyfRyK1OLzQSsnmtjba2D9Y1OVtZaWDnXwubFXWxe6OTS5d1cuLSPzWuHWb34GisbJ9hY38X4qXxqUkWanRrm98fxYDKNt5ez+HjTzafXavjsjoev7nn49pGX7x77+Px2OX+8U8EnVwv56EIOL+YSeTIRz92BOC4di2KsWU9viUiXS6E2QaI4UsBlEkjSK3+Xuw5bsIQpUMCmUzAGajHtEJBeUWMMVFB26FH9w3bSogQW55tYWO5iZrmd+fVmZs51snChl9mN3UyvdbBwfg8LG7tZ3NjFzFILAWvrraxvtLO52cGli51cutzJhYsdXL6ym6vX93Px2mE2r/e8VMByN6vz7bRVmPEli5z2hnL1dCoP/cm8s5rFV/ea+MsbXfz1rV385/ud/Pyiib+9vZN/e6uFf33RzJ8fe/n2YTWf3Szh44v5vL+Sw/2RJNYOhTLWYuZouYG2DBlPnEieTSDdqJCoV4jQaLEHarEGiRiDBCzBEjaVHnOgjGG7gLhVh7Rdg/ZX/w8dLcksLDWzsLaL1Uv7mF1vZ3b9ANPre5k+t4f5jX0sbOxlYb2LpY0uAjYvdLK52cHVq7u5eLH179HO5Su7uXL9IBeuH+P8tcNcuNrD8sJu+g4VU+eSaXbKzO+J4s35PP7pailfPfDxH+8f4K+/3sO/f7CfXz7cxS8fdvCf7+3kf37byX+8u5OfX9Tz/ZMavrpXzmc3i/ndZh4v5lK40RfO0gErQ41GesqM7EzTUxqmI88qkyzriNVqCN0egmmLCv02LaYdIqZACcN2AUOghG6rGt1WNZpfbSXKso2ZaS8Lq7uYW9vH0sUuZs/tZm7zAPOb3Uyf28fUahfLFw6wcmEfAZev7uPylT1cvryL8+ebuHy5jYuXOrl4ZR+Xbxzh3OUjnLt0iIsXD7A42Yovy0q+ZRuHShzcPpvKB+fy+eJeNX95s5n//u1+fnqxi7+9u4dfPtzF//y2g//+oI1fPmzjv97fyX+828y//rqebx+5+exmIZ9czuO91TQe+2PZPG7D32ngZJXMnmwZX6yOYodAlllHoqghWqXBtk2F8koIxm0CyjYBaasOabuAsE2DZosKYauAIWgbB3alsbTaxeL5Qyxf2sPkQgszG3uZWd/L1OoeZlb3sHR+H0sbuwm4fqeX6ze7uXp1L5vnd3LpUgeXru7jwrUeLt8+xaUbp9i81MvGShcHm1NJU3ZQbA2hvy6S+yPJfLiez58e1fPD8xb+9t4u/v2dTv7rvd3817tt/N8PO/jlvVb++92d/Pe7O/nlvVb+7c16fnzu46t75fzpXiUfX8jmxVwiV087mOpUOFur0FMs05Yu4YkRybVrSdVriNVoiNbI2IN0GLfpkLbokLfJCNsElCCRkF8FIQXKSK+EEG0MZnl5HzPndrN6aT8LK+3MnutiaqWd2bUuVi7sY3F9FxuX9hJw9c5xLl07xM3bPVy4sItLl3Zz+dphLtw4wcVb/Vy8eoIrl44zM1JPTYaJbL1AdaSeqd3xPJhI5sPzRXz9qInvn7fwr2+38p/vtvF/3u3kl3fb+K93WvjlvVZ+ea+NX95r5T/fbuanZz5+eFrDl3cr+MP1Uj46n80b0wlcPxPB0j4rI416Tlbp2Z0j40uUKHBoSDeqiRe0pBotxIoGzIE69Nsl5B0Kuq0iwjYBOUhAtTUE8R8ElFcCOX6sgqm1VtavHmVuqQX/UjPj841MzDeyurmH1Y1ONi50EnDl9hE2r+zn2o2DnN9o4+KFLq5eP8zVWye4fPs0l68eZ3PlAP3d2Rz0JJEhCngiBSY6w3jsT+XDjWI+u+3lxzdb+fnNZv791838+5vN/O15M//6RgP/+VYbv7zbzt9eNPHz83r+9c0GvnlYyee3y/hoM5e3FlN56o/nZl8k53sdzOwyMVBv4HCpkTaXgfIoHdk2DSl6gRitQGiIDnOQDmOwghKoIO2Q0W7Rod2mJfjVIKRfSYj/oKKuxsnUaisTS7vpH6tjfK6Oibk6ZpabWd3sYmF1J9MLdQRcu93Dlet7uXFjH1cudXLpQge3bnZz+04vN+8c5dbNwwz15uHvzqY+RcYlCNQlaJneFcGv57L5zXoBX97x8uOTZr696+Pnp8388LCWHx76+OlxHT8/refnNxr48Vkd3z2q5rtH1Xx+u4SPL+Xw7koGL+bTeDqVyN3hKC4es7F80Iy/08TJKoVDBSaaUxXKoySS5BDCVVosOwSUrWoMQRJKoIiwTYf6Vxq0rwoE/r/BqH8VgvpXQUSHKoz4W+kdrGbPa9X0D1cwOeNjxF/N9FIzw34vfSNuAm69foxLl7u4dn0vFy+0cfvmAe7cOsS9u0e5c6eHmbEK/EeKaUpT4w5Xk2c0sTvXxMrBKJ5NZ/C7zTK+uO3jx6etfHXHy49PmvjhUT1/fV7H94+q+OGJlx+f1vHTG01896iObx/U8dmtcn53sYB3l3N4ZymbN6ZTeDiWwO2zcVw6EclKdyhTHXZGm8I5Vumg2WUh3aAlPEhFaLCENVjCEChgCJIQt2gwBCpofqVB/YoW1T8Go31Vi1Grpr0rl0N9FbQeKmJoxMPklI/+oXJODZQzOv3yVSng+q0jXL22j5s393Pr5j7u3NrPw/tHeHD/CHdvH2TkSCrHvPHURKmpcMhkinqOuMO4eiqB57PZfHypis9v1fLV3Qa+fdDIT2+08cOTJn5+0cRPz+v55oGHH57W85dnTfz5cQN/ftzIV3er+fRaGb89X8x7K/m8s5TJi7l0nk6mc2/YybUzsWz0RrK4P5L+ehttWQbyrAIRO0KI1hmI1BmxBEuYgmSMgRLyVh26V9RoXlUT8g/BSNuMqF4NxlOTSteRPDp7CzhyNJfjx/I4cbKIvkE3x06XcvhkMQG37xzn5o2DPH50nEcPe3nyuJf7dw/w4F43F9YamOhJpd1lxhuup9isJ10nc9IXyYMxF89nc/lwo4JPrtbw6fUavnq9ju+fNPPD02Z+et7KD09b+PGNnfz4RjM/PW/m+yd1fH3fwx/vVPCHG+V8cqWcj84X8dFmAe8sZ/DrhUyez2byaDKdWwPJnD8SzWirnc4siSK7QJxKiyNYh0OlYNwuoN8mIm3RYVMbEV9Ro92iRv0rFcKregL/vxAKChLYf6yU6p3x7N2fxeGePLq7s9l7IIOuA5l0nygj4NHjPu7fO8rTpyd4/PgIjx/38PRxD88eHGbZX8HYgTQqwzTUhNvJVGScWpGTvkjunE3hg7Vyfn+1li9vN/LNgxa+ud/AN/dq+cvTZr5/3MJfnrbxw9Od/PC0iR+e1PP941q+eeDhy7uVfHbLzec3q/nkchmfXCnm/bUs3lrM5M35HB5OZHLrbBobvQmMtYbTkSVTGibjFCXCVCLmHQKG7RL6bQriKzrMwQaU7SLiNh3CNg3CFgXVKyIpzkg69hbQvDuT2mYnHbuz2Hcgh50dSXQdzKKjO4eAx4/P8ODeMZ4+PcHTp0d56+2TPH/Wy+O7+xg7lcHogRxK7CLlDgdZJiOpsp7T9bE8Gs3hg9Uy/nizgS9u1fHplSr+eNPDn+/X8sPDOr576OMvTxv58WkTPz1t5ru7tXxx3cMHSzm8OZPKm7Mu3l8t4p2lAj5cL+SDtQKeT2fxaDKLG2fT2TyawuLeJAYaotmZrlAUKpAkCERqjViD9eh36BG36tG9KiFuFTEEGVB2KMg7NGi36Ah5RSAq3MLOzkJ8zRkUexJo6sim60A+e7pzOHisiN1HCgl48PAED+4f440nJ3jj6TFevDjBkye9PLnXzYn9cZxqy8AdZSXbYCTLasFlNNFTGcqziRLeWyrjdxuVvL9UyFtz2bw95+Kfzhfyzes1fHOviu8eVPHjs3q+u1/HewsF3D2TwubBSDYPh3H9ZCyvn03n9YF0Xh9M5fbZFK6dTGbjaAKL3fFMdEQzWB/JcbeDVpeRolCBOK2GCI2RULUZY6AJZYcJabsBcbuMTReKPsiAPlhA2KZDClSw6CVa28spcifiKonE05RO29589vUUc6y/hp5+DwG3Hxzn3oPXeONeLy8e9HLv3mFu3O1ldbGVY51OutwJ+JxhZOp15IWGkm40caDcyp3+Yp75S7g7mM2lo8ms7I1kodPC5aPRfHTOzZ9u1vL51RI+v1nK+2uFnO9NZMBn50yVlWGfkbF6hckWM0MNek7XyPTX2hlsiOZ0TTjHquwcLrdw1G3nSJmNriwz5RESCToN0ToDocEKlkA9piAz+iAzuh16lBALhmAThiAF/TYJm9qMRdJTXVNITkk0hd5kvG25VLe48LVmUNuewYETnpdO8MbtY7x43MfTe8e4ebuHc5cPMONvYX9TEp3uGJpcYXiirFRERlEYGk1nro2z3ij6PTbGGx1c6Mngzmk3l3sK8Tc52DwczR8ul/CHK3n8bjOHB6MuBmutdOfKHM6TmWuN4slICR8s+Xg8UcpKt5Oj5WYa4kJoipepjxdoThHoLrbQW2xiT5aJqiiZNFkkRiMRrTNjDdRjDjQhbtUjbjchBZqQtuvR71CQt4iYg43odqhwV+bhyo+kyJtCsdeJu9FFWV0qlc0uWrrLCbj7eJgbt4/z+GE/d24d4+K1wyxv7GNqopWGsggaC8KoT7HhCTPgi4mmyBJJZ3Y4ezPN9OY7WOhyMlxvoidfy6EsPYvtqSx02nlrNpEvbxXz8WYRG4diOVVhoTtHYrI5mqtHEllsN9Gbs43WuFfodKrpKQrjYEE4zQkydTFa2jNFBpuiGW+O4nhZKI2JZrKNClHBWiJCFGJ0duwhNoyBFnSvGl9C2G7AsMOAYZseww4DUohISWkO5TUZFHvTKfG5KKhOobAmjfKmbKo6igi4db+f85cPcufuaW7cPsHqxX0sntvFjL+NXfWpVKXYKbMruM0KlaF2Ck02uksjGKyL43CumfHmKO4PVbDPpaEzXuJInsLm4UgejUTx4+N6Pt6sZK4zkrOeUMabIlk/FM2vp1P4+oaPuRYLh7M0HCu001topadUz3G3AX9HHBdPZXJ3LI+Nnnj6a+y0pVrJtxmJUQnEao1Eaa04VHYMO6woO+zothgwqawYA40YthkwBpoQgwSyslMoKHeSWZpArttJVnkS2W4nxQ25uDtKCVg7t5tjJwqYmGnDv7ib6eV2ltY6WFnsZG9TBu4YG5U2K97QUHJliTyjnsGdsbzh93D5aA7vLnv49KqPB8OZ3O0v5NYJF8/9mby74OJvL3bxyWUvS3tjGG8MY+1ALC9mM/n8eiFf3ijm04slPBxJ4d5QJrcHstg4msCjiWzeWSngvfUi3pjL4OKxKIbqQ2lzWcmzGogM1hKpUogR7DjUoei3m9C+akDaYcIQbMKqtmAOMqLfrkcOkcjJSaPInUqO20lhjYucyhSKfFnkVbvIqk4j4NRrRfT2FuJrSOHomQYGxhtZWelgbbGLuqJw3A4Zr8NOoaSQIYlk6XXM7U/krekCnk9n8mwqg6cTmdw4kcRCu5nXTyfy9lw6n1wo4MdnTfzzJTdr3ZHMtIexdiCCZ9MpvJhO4+3pbJ6Np/JkLIVrJ6NZOxDKrTMufj2Tze/O5/DRZiHPZ1xceS2Bvho7TSkm0vUCEUE6wkMUQkNMWEOsKIEmpB0mNFskDMEK+kAJu9qMsk1CDNKRmhpHfnkyrtJE8qpd5LhTyPekUlqfRWVrAQF7WpM4uC+f1o4i6lrzOXiknNmZnRzoTGdfXTo14QIVRpl8WSZFEEkVVaz1pvLZBTdf3a7ki9tV/P5yGe/OZ/D+UgafXizhi+tuPrmQw9d3y/nnK6VcPB7FuUNxXD/p5P3VAn5/tZB/upjLh+ey+e1GPp9cLuWPNyv46o6bL6+X8i8Xinh/KZ+Hwy7WuxM4Xm6jMkpHsqzFESRiD5KxBOmxqW1I2/RotkpotooogRLKDgFzkB6r2owQqMVu15NREEt0loOE3AiyK5LIr3JSVp9BTUc+AV2N0ZzoyWfv7nyqfak07szkWG8F3W0uuqpi8SRayBJkcvUSyWqRNJ3I2iEXX1wu5KvbNXz3sIk/P27i2we1/PlRPX+65+Vfrpbx+fUSvnvo5aPzRTwYSef1s+k8GUvjnzbz+OkNH//263r+462d/M97u/jvt9r56YmXHx64+fJaAb9ZcvHcn871k0nMd8ZwuMBCRaRCjFaLXaXHGqzHpjJhCTFhCTYjbJExhljQbBUxBBsxBRsIl8MQAwUsBj2FJS7SS+PIr06lyJtGYY2TyuZMfJ35BDTVRNC7N4uWxlTKKuLx1qXR2pROV10yuyvjaHRFkKHVkSWoSQrRkByiYao9gQ/nU/lks+glhPt1/PC4kT8/bOCbe3X8y9UKvrnv46c3Wnh/rZDHEzncHcrkmT+Ljzfz+fGJl5+f1fJvzxv55e0Ofn7SwM9Pavn+XiX/ciGbd+fSuD+UzIXeeEYbHHRl6Mm36ojSaLGFyFiCZSzBCpYQA5ZgIzaVBZPKgmarjByoxxRixKqxYFDLyFo17qo8qhuKKKvOoqzKRXGFE7c3A3ddJgENnnj2d2ZSW5NMSWk8dXWZeN3xtHmS2FPpxBNjwm21UGJUyBAkkkPUnKoM471ZF78/X8jXNz38+LCBHx69vAn+8baPf7lRw5+fNPHTm2387qKb+2PZ3B/J483ZIn63Wcqf7lTxl4defnpUx9+eNfPXR/V8/3oN392p4rfLGTyfdHLtRCwLuyM5XWWlJVkmx6wjWivg0CiECybCdCbCBSt2jRmrykSoEPrSEAUbMIYYsAtWrKIJQbWDnTsraGovoLE1l50dBdQ3Z9DUmkVjWwYBXncS7c3p1FQ5KSpKwF2eQkGmg+rcKKqcdqqjzFSYFIpkgSKLBadKQ7tT4q3JbL644ub7u7X89XET39718eUdH1/cqeOPd+r55kETf37SxgfrZTydKebW2Sye+Av5aNPN17eq+e62hx/u1fLz4ya+u1PDV9fdfHapjPfnM3m9P4GVA5GMNTl4rSyU2liZTKNEtE7CoZYIVUvYVBLhgoVwwYpNbfEZrrgAABO9SURBVMSmtaKoLCjBBuQgGYvWhBIiogvazq4OD13dZezpKaV1dzZ7Dxdx9Ew1x/prCKgojsNdGkVpcQJlJWkU5SVQkB5JiTOcwnATFTY95QYdlRYTuQY9qToRb6TIjeNOPrvg5uvr1Xx1w8N39+r4+vVaPrnk5pPLlXz3cCff3G/mN+fdPBjN5eqpdG6cSeO95TI+vVjOH69U8NWNSr573ccfr1Xyh0sV/G61iDfGM7j2WhIzuyLpqwnjQK6FygiBVEUgSpAI1yrYQ0TCtUZC1QZC1UZsKiNWtRntdgUxUEEKlFGCDRjUCnq1mszUaJw54eRVJJJbFk9ZdQoN7QV0dFcSUFYYTVlRDIX5CWS74shKjSYtxkJ2lI3iyDDcNhPFkpoiWSZZrSZBpaPYLLJ+IJn35vP4/IqHP92u5Zs7Pr6+7eWjtQJ+f9HNX5/t4vtHbbyzXMjd4QzuDuZx7XgKv1mp5IvrPr687uGrmx6+ulXDp5fL+e25Yt6ay+V2Xwqr++MYbozguNtBp8tEqUNLoqQmQisQrlZwqBXC1AbCtWaiZQd2lQmryox2h4KiMqLZJqCEmDBqzNhEAzEOG9GJ4SS54nDlJJOZm0h6TjzZxU4CqspicZclkpcTR2FeCrmueLITwsmKsJNtMVNs1FMTaqFINpIQHEKCWiJT0DLWFMX9ASf/vFHB51er+fxqJZ9uFvPWdCr/vFHKT487+PpOE88mM9k4HMPFXiereyK5fSqZ715v4ssb1Xxx08Mfrrn56HwJb85k8XA0nYtHE5jrjOW0x0FPsYOuLDtFNjVOg44oQcIRIhOlMxOuMWEPMWBTmQjT2dHvkNGrLShqIwatFd12PWatnTDFTqheT0paLEmpkaS5YkhzRZGRE0tmXiwB1ZWJVFYkU1SYQGZmDGkpESRHmUkLM5MfYSVH0lEk28jWGkkIVpEuWUgMCuZwQTiXuhN54S/mg9VSPj6Xx2fn8/l4tYDVA2Y+Wq3mbl8mZyoN7EqR2ZNuZ1+GjpW9Dr69W8+3r3v54rqbf9oo5sPlIp5N5HDzpJPlvXGMNUdzojyUA9kmdjoViu1q0vRaotU6orQK9iABS5BEqMaEQ7Bj0VgxqkzIwQqyyogQYkK1TcGosRAqmYnUG0lMjCAqPpT03GTSMxPIyUsmMy+RgMqyOEqK4sjPjyU7J45MVyzJkRayoh0UxYWTa9aTqpJJ1SikihJJWoXE4BB2pphZbI3k7plMnk1m8/5CJn+6VsZf7vv4450aVnc7OFEosD9dT0usgfYkC/syBa6cSOPTSzX84XIVv10r4p2FHN6cyubu2TQu9sazuCeWwfowTrkdHMq30ZggUByqwWUUiVRpiFBL2INFbCEyDq0Zh2jHEGxEH2JArzYghhgR1VZU2xWMWgt20USMyUJcXCiRCXZiUiOISXSQkZVAdoGTAHdZPIUF0RQUxJGbF09BvhNntJ30cDtOo56CiFCS1AJOjUSSRodTpydFJ1AZLuBvCONKbzK3TyXxZCSZT88X8c2dSr57VMNXN+uZbrJxKEvmcJ6dMzVhrB1K4sFYLm/NlfKmv4BnE1k8Gkvn4Wg6t/tT2eiJY7rTwdjOcPqqw+kpctDs1FNoU5Mm64hWC0RoFMJUCmFaI2E6EzaNEbPKiEllRK9SkFRGxBAzukATJq0Vi1ZPtNFMsjOC5IxoMoqcpOcmkFPgJLPASUBlRRIVZUkUFMRSUJhAfl4yroQIEsxG0sxWXGYTGbJMliDi0sm4RCMuQSZfVjPdEsfVoyncOeXkQX8Kb03l8IdLlfzpdS/f3a3m4UAql3vzWNqdzrlDKVw+mcbN/myuHk/jfHcc5w9Hcn80g/ujmdwZzOD80QTmdocz2uzgTE04h4vDaEjSU2TXkSJpiVYJOEJEwlQyDpWCLUQhUrZjCdFj01owhCgY1GbEYDOqLTIGtRm7aCLaZCYlNZL03DgyipJISA8jqyCRvDIXAUUFMRTmx5CbF01WThT5eQkUuOJIC7OSbrGQbbJSYJRxm0xUmMPIFU3kSAZSg0I4Ue7gxvFsHp3N5OFZFxe6o1jusnCvL563ppL4zUIBt45nstgez2xbFJMt4Qz6QunJVzPZZOLOWRdP/Hk8nszl3kgO548ksbA3hqF6O6+5HezNtVOb8NIFpog6YjUStkAtkVo94Wo99hAZh9aETWXAHKxgCtEj7VAQA01otxvQq0xYtHoiDSaiI024cuLIKIgnpziBSl8OOaWpBBTkRVOQF0tubhT5hbEUFyWQkxpGbnwYOWGh5NvCKbXqcZsMFEtW0jUimYqJ5BCZlgQDF7qzeWM4h19P5XFvyMXds2k8H03j7msR3DhsZ7HFgN9nZNBt4nSpmbOeUFb2xPF4NJ+nEzm8s1TC06k8Xh/MZrM3lbldcfR77RyriKQjw4YnRiHHoiNVFojTSjhCREKDBUJDJKJFCxE6E9ZgiVC1AVOwgrxDjxRkQg6xYJMchEpmok0WokKN5Bekkl+aTE5RHCXuFPLLkwkoLoilMD+OwsI4CopiKSyMJs/loDglgvwoB1kmO6V2BbfVSMoODak6kTSDiTiViTxJzYg3jof9GbyYyuC9lUK+vtvEt7e8fH2piu+uVvKH9ULem87j9RMZnD+QwJVjiTwazubRSBbP/dk8n87m4XgmV0+ksrwvgbGmcI6VmTlUGEaz00J5pEymSfO/AMLVMo4QkUitkSjBTLRoIVxrxB6sYAyUEbZKaLYqSMFmLKIdu2gm0mAiJtRMZkYc+cWJ5BbGkJUbTlF5EgEVpYlUutOo8qRRVZNKbZ2LwqwwKjKjKE0IoyjUSpHFQKHBQGqQjjStglOrEB+iJzZYoDJSx0xnPK/3pfH2dD6fXqrh4wtlvJgq4EpPDPMdRmbb7My0RrG0O471Q7FcOp7I1RPJvD7g4vZAOldPp7LanchkWzQnq+wcKrSxK8NOfaKZ0jCJLLOAU9QRrRKI0CqEqRUiBQuhGiOhGiM2jQlziBF9kBFhux4xyISitmKTHdgEE/EWG+lRNjLTw8gvjqGoIon84gTyShIIqKxyUulOpao6lTJ3HNXVyeS7rJSlOiiNt5Nvt5AqCLhEAykhMsnBMqlaIyk6E7FqIwmqEBoS9My2J3L7VCrvLRbw23Ml/G6jnMdjaVw7Ec2lo3Gc70nk6ok0rpxI5OLROC4cSeDya8lcOuFk9VAik+3RnK4J5UCenvY0mdZUK7UJFgpDRTJMOuI0GqLUIpE6PQ6VTJRkxapSsKmN6IMk9IEyhmAj2q0KIVtkdEEGDBoTVq2eZLuD3LgwSgviqK5zUVKZTG5hPPklCQSUVcVTVZ1GdW0aFZ54drZkUV0UTUGcHl9aDEVRUaQbzCSqRJLVMikaPU61TLbBhlNrJFVjI00lUhenMLMrhmeTWXy8VsJ3d1/+EH//sJYvb/r4eMPDG5P5PBrL4PKxOK6ccHLpuJO1QwlM7AznTHUoB/ON7MnS05SkoyHRSHWcmUKHQpKkIlqjJTxExP73/rcEidjVBkxBEhaVAX2ghH6HhLBNRLdDwaS1YRetWDUysQYTrggLBVmRlFYmkl8aR35xPDn50QS0dOTT2JJLW1chnXsK2d1VSGd9BvW5UdRnxFKeEEO21UqqTiRDJ5EnG3FptGSJIpminlSNgWSNgRRdCN7YEJb3J/LhQjnfvl7HT4/q+bc3GvnLg0Z+f97Ds7E87vSlc/VEChePOlnaF8dkWySnqqzsz9HTmWag1SnTkChRG2+iIsqEy6ghRhtMjCARLegJV4sv9wG1gkNrxBwsY1O/PAUswQpKoIS4Q8KoNmMTLYTq9KSEOkhzmCnKiaXK68LblIvbk06520lAtS+Dmto0qnzJeBtSaG/PprU2jbIUM/UZMZRG2SkKtZIp6CgxGikzmSiQdBQoAvkGPcmaEBJ1apIlCZekoS5Ow4WeDD65WM2Xtyv59nU3n18t5b35XB4OZXC7L5217iRmOuM4U2PlcJGB/bkm2lIVGhMUmlNMNKfZqIoxUxCqJ0VRE6UJIlonEqVViNTK2IO0OFQSlkAdEaIVc5CEKUjCGiJjCJKQgyQsghWTRo9FLRFvtpJit5CWaCe7OJbK+mzKPS48NS4CSsqSKSmPp7w6gaKKSGp8ibQ1ZpCXoFCVEk6+TU+x3UKeopArShTKCjlaNWUmIzmKniStmnidhiTZgFMykC4F0+iU2Diazq/ni/hgJZ8XU6ncG0jm8vFklg/G0e+z011oYE+2TGeGnp0pCo1JepqSzdQmWSiJNJBlFsm2GkhWtMTpVCSIElFqkdBADeZtIThCREzbNNhVMmE6M+GCGZtKQd6hQ68yYNBZsMk2DCqBMMlAss1OYqydkppM8j2pFFelU1ObRUB7l5uOrnJ2H6xk14FSDhx2c/yIj4rscMpTwihwWClyhFJsc5ChlUgJ1pApvHwdSggSiA1SiFWZidUYiNJoSRC1uIwyDQkGznpjme+MZ7Y1jJFaO6cqHRwstLA/305rqkJzip4mp5Gd6TYaUizUxCsUOLS4LALpRpl0s57sUDMui54kSSJKpSNSLRCuEojU6rEFCYSqFSzBMhGiFWOwiLhdQAxSEIL1GAULBo2MQzIRY7QSFWEhqyyVXI+LMl8OpZVpBDS1FtG2q5RDx2rpPeXjyAkPx3qqqC6MJy/GRn6oiRyzmUJbBCkahTSdnogtQSSEiCSqDYS+qsOxRSFWYyRSrSZBkUg2msgw6ikOM9DgtNGYpKfNaaIt1c7OdDvN6TYanRbqnTaqE6yURZspjjSRYdGSYRXJtOrJthsojrJTHGUlJ1QhzagjUVKTIGmI0QpEamQcKgmHRiZcNGNW6ZGDJZQQI0KQASlYj02yoA8RcMgWbIqR6LhIcitzSClKpsCdQUZ2HAFNrbm0dRWxu9vN3p5yDh0t53B3GfvbSsiMMFIUaSFNlsmQrSSFSKTq9KToFNJEI3EqkahgmdAtWsK2a4lWa4nWaYmRZJx6E8kGPZkWhfIoA1URAtVRIpUxCmWRAp44E2VRRgrC9GTb9OQ4zLisCrkOEyWRNgrC9JTGmCgIF8kPE8iyasgJ1ZFpE4kXdESoBBzBOmzBGuxqBWOwjKKSEAMVxB0G9MF6zFoFfYgOq2BE0egxWi3EuuJIK0omqySJ7MJEAvYeruBgr4fe1xrY31NN91EPvUerOXrYS57TjtsZg1OSceoMpOkMpKh1pOtkklUC8WoNiRqF2BCFyCAdcYJMlFZHlFYiTmcgQdGTZtTRkhlOW5qRhkQZX6KJ8miZ8mg9xREKRRFGCsONFIQZKIwwUhiux5NopyLWQHWSiYo4iepkI9VJRjyJJvLDZJyyQESwlmitgi1Yg00lo9+uQwnSoQ/WIwcaMKkN2CUTerWIWWvCrLWiV0yEJ4aTnBeLqyCavLJ4ArqPedjf42Z/TzUdeyvY3e1m175iOnYVUFIQRW68A6fRQKpsIVMykarWkiGIOEM0JGvVpAgKSToj0WqROFEiTpKJl03ECwaSDAYybQK9NYkMNMfTW27nQHE0HQXRNGSEUpVgoCrBjCfBSlW8GW+SlTqnhboUI75kmbYcK205VjrybLTmWGhymSmNFElXNCRodESGaIlQidgCBUw7dJiCtZiCZQxBCkaVjF0yYtIqGFQGQgULEaEOMvJTyXenkV0cR5k3nYDe0w3sOVTOvsM1tHaVsafbTdeBEnZ25NCyM4/C9GhSbWbS9RbSBQP5eiP5igGXTiRDFnDqROLVItFqgRhBIEGvJ1lvwmkwkmSUyQ0TONGYwNLhFCa7ojndGMPxugT2l0fSmW+nIc1AbbJMU5qRplQD7ZkmuvIs7Ck001Pp4HClnZ6qULryJVozRWridOSa1Dh1ahJ0OhIlBXugDuNWDaGal57AGChiVok4ZD0mjYRFa8Ss1hIZaiE7L5mMvFgKypLJKUkkoOuwl10HKth7qIau/RXs7S5j78ESdu0pobk5H19pOokmmRTJQJZswu2IIEcx4BJkCowGnGodkTtUJEgKCXqJeFnEqTeSbJJxmhVyHRJ7SixcOpPJhZNO5rqdTHQlcaYhgt5KK91/nyPaV2jiYLGVvfkK+wsVjlRaOFlrp78pnL7GMI55TBws1dOUoqPIEkiGoiJeHUSCKBAerMOyQ4spUIc5WMIYqMOuFQmXZSxqAavagEklYJIFsnKScKaFUVKRQkllKgFdPU3sOexj/2Ef7V0F7OsuYtfubDo6Cmiuy6OhMpMks0iWyUq6RiJDJ5GlGEkX9bg0mpduUDISL8qkWk0kKgLJej1JRhGn2UC2zUhLpombw8Xcm8jjUn8O546lM707krG2MIaawumrC+U1j4XjHgsnvTZOea301dsYaQ1nvDOSic5IzjZaOValpzVVRW28QJ4phBQxmBhVIBEhaiK1egyBAuZgGatKxq7RESXL2NUvJ03ErTKq7WoiIx0kO0Op8qTia8wkoOtwI+17PbR3uWndVcjeA8Xs3ltAfV0GzfUFVBcmk2wSybM5yDFYSRf0FNnDcYl6sgWZNI1IolYiWqMjXpFwmvQk62VcNiO54aHkO0zUORUunirmyUwZ98ZzuTmUwdX+dM6/5mRmdwQT7eH4OyOY7AhnrM3BaGsoE51hzO2LZuFgNMs9CUztCWOi3cGxMokmp5Z8SxB5Ji0pumDCAwMJDRYwbldjDRGwqgzE6g2km2TidCI2rQlDkBXddhm9qJCSHE1ebhwFhbH8/yAZ7ktBxllRAAAAAElFTkSuQmCC";
```
```
<img id="img" />
<canvas id="c" width=192 height=192></canvas>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
<“⁷KṆ‘‘Ḅœ?Ɗo⁹’)×€"3⁼þ¤)ẎZ)Ẏ
```
A monadic Link accepting a list (picture) of lists (rows) of lists (pixels). Each pixel being three integers in \$[0,255]\$, `[r, g, b]`, which yields the result in the same format.
**[Try it online!](https://tio.run/##y0rNyan8/9/mUcOcR43bvR/ubHvUMAOIHu5oOTrZ/lhX/qPGnY8aZmoenv6oaY2S8aPGPYf3HVqi@XBXXxSI@P//f3R0tImBjqExEJubxupEG5oZ6BiBRAwMYoHcaAMdIAQyjExNdaA4NjYWAA "Jelly – Try It Online")** This example is taking a two by two image where the top-left pixel is the first example pixel, the top-right pixel is the second example pixel, the bottom-left pixel is a black pixel and the bottom-right pixel is a white pixel.
### How?
```
<“⁷KṆ‘‘Ḅœ?Ɗo⁹’)×€"3⁼þ¤)ẎZ)Ẏ - Link: list of lists of lists of integers, I
) - for each row, R, in I:
) - for each pixel, P, in R:
) - for each integer, C, in P:
“⁷KṆ‘ - list of code-page indices = [135,75,180]
< - less than -> [C<135,C<75,C<180]
Ɗ - last three links as a monad:
‘ - increment -> [1+(C<135),1+(C<75),1+(C<180)]
Ḅ - from binary -> 4*(1+(C<135))+2*(1+(C<75))+1+(C<180)
œ? - permutation at that index of [C<135,C<75,C<180]
- when all permutations sorted lexicographically
- ... a no-op for all but [0,0,1]->[0,1,0]
⁹ - 256
o - logical OR e.g. [0,1,0]->[256,1,256]
’ - decrement ->[255,0,255]
¤ - nilad followed by link(s) as a nilad:
3 - three
þ - table with: (i.e. [1,2,3] . [1,2,3])
⁼ - equal? -> [[1,0,0],[0,1,0],[0,0,1]]
" - zip with:
€ - for each:
× - multiply
Ẏ - tighten (reduce with concatenation)
Z - transpose
Ẏ - tighten
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 186 bytes
Input and Output are lists of RGB values
```
(g=#;Flatten[(T=Transpose)@Flatten[T/@{{#,v={0,0,0},v},{v,#2,v},{v,v,#3}}&@@(If[(l=Max@#)<75,v,If[74<l<135,{0,l,0},If[134<l<179,{l,0,l},{l,l,l}]]]&/@#)&/@g[[#]],1]&/@Range[Length@g],1])&
```
[Try it online!](https://tio.run/##NY1Ra8MwDIT/SsAQEhA0TuqFshj8VBhsMEbejB/McNyC65XWhIHRb8/k0nHidHzi0MWmk7vYdP622yK3xkv2egw2JRd1M8v5ZuP9@nN3rfqn807lzGCVuQMSwoqQV2D9M1AcEGulmrdFN0F@2F/F2mkUdCEy7qcw8UEA1UOpE@PDA44HyIQgYNkkNMbUO2qTea2ZMcAL@LLRO/3uok8n5Qts6@3zdo6pUovOOe87qPhQbBQIVeYvlPsH7ToshL5XZUruhaDr0xDRbNsf "Wolfram Language (Mathematica) – Try It Online")
# Wolfram Language (Mathematica), 243 bytes
this second code is a **function** that takes as input an **image** and outputs an **image**
(I don't know why people were confused in the comments)
So, if you feed this img
[](https://i.stack.imgur.com/zL7No.jpg?s=128&g=1)
into this function
```
(i=#;Image[Flatten[(T=Transpose)@Flatten[T/@{{#,v={0,0,0},v},{v,#2,v},{v,v,#3}}&@@(If[(l=Max@#)<75,v,If[74<l<135,{0,l,0},If[134<l<179,{l,0,l},{l,l,l}]]]&/@#)&/@ImageData[i,"Byte"][[#]],1]&/@Range[Last@ImageDimensions@i],1],ColorSpace->"RGB"])&
```
you will get this output
[](https://i.stack.imgur.com/06LLi.png)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 157 bytes
```
n=>{int i=0,j=n[0].Length;for(;;Write(z(0)+",0,0|0,"+z(1)+",0|0,0,"+z(2)+"\n|"[++i%j&1]));int z(int k)=>(((511^i/j%3%2*4064)>>n[i/j/3][i%j][k]/15)&1^1)*255;}
```
Prints the RGB of the output. The output is newline separated and not aligned. Originally, I used a bit-mask with `1` being on and `0` being off, but then I saw Arnauld's answer, and I realized using `0` as on and `1` as off could save bytes in the number. The TIO link contains a 4 by 2 pixel sample "image".
[Try it online!](https://tio.run/##bZBRb4IwFIXf/RWNiaaVu3HbguAYJHtcsvc9MEyMQy1ONEj24NxvZ22lmVsMgXDP@XrugeXxbnlU3dOyVfv6UdVtXpgrW6VdnWZfWiAqRajSOsfi/qWs1@0mWe0bmiSvjWpLeqLIvCEg4Blh6J0ot6MeLqPQ41t9Huaep0bVmBeMJSb1RM1zy9KMUhpyPld@NZIjMQlwGrAsq3Mt@LLI9aki3xY@D9mYzzmbiDBMvrtkYMtuyo9D2XB6WDSL3ZFYjVQ6teoBh4g/SF70zOdevZMLIf8RfdCKViwZOMSFub3RVH@nbsTAKVxI4EJAEDEn/uIiCEAfia54AVEAcXwD5jMBXEYg5FU6CJA32HgKZvFM/KK2l@2mf/nA98nzbrEuH8wbmtpoAeL6YhAZyzS0dhQSRC3rdhjHxnJ9UEhtcbA2ShvY78eZIH2wubsf "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# APL+WIN, 102 bytes
Prompts for a 2d matrix of pixels as 24 bit integers as they would appear in the image
```
((⍴a)⍴,3 3⍴255*⍳3)×a←(3 1×⍴m)⍴∊⍉((1↓⍴m)/⍳↑⍴m)⊂n←(-+⌿n)⊖n←1 0↓0 75 135 180∘.≤,m←(1 3×⍴m)⍴,⍉(3⍴256)⊤,m←⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##RY4xDoJAEEV7TrHloqC7LAt4Bz3EBoMxATShsrVAIGI0RvEA3kB7C24yF1lnpbCYmczM@z9fbVN3uVPpZuXGqSqKdazhdFvMoTwLC6pDoimF9q1sbI4gAocn5Qjal7D7TiFGBeF9h/fMMFA10NaUciivv9sUUSgvw7/Z50bhjuH4yXG9m5UThjAjoSRcYEUMqscE6qeTGZgT8bd3jPkQIkD9gGBgjVF1YnnEM79A@tEMnZj0Q8HYFw "APL (Dyalog Classic) – Try It Online")
Outputs a 2d matrix of 24 bit integers of the transformed image.
Most of the code is handling the formatting of the input and output.
Example: Take a 2 x 2 image made up of the sample pixels
Input:
```
2654895 10547300
2654895 10547300
```
Output:.
```
0 0 16581375 255 65025 0
0 65025 0 0 65025 16581375
0 0 16581375 255 65025 0
0 0 16581375 255 65025 0
0 65025 0 0 65025 16581375
0 0 16581375 255 65025 0
```
[Answer]
# Rust - 281 bytes
```
fn z(p:Vec<u8>,wh:[usize;2])->Vec<u8>{let mut o=vec![0;wh[0]*wh[1]*27];for m in 0..wh[0]{for n in 0..wh[1]{for i in 1..=3{for j in 0..3{o[m*9+n*wh[0]*27+j*wh[0]*9+i*2]=match p[18+m*3+n*wh[0]*3+3-i]{75..=134=>[0,1,0],135..=179=>[1,0,1],180..=255=>[1,1,1],_=>[0,0,0],}[j]*255;}}}}o}
```
This line is a function that meets the challenge, however it's input is actually data in the TGA file format as described at [paulbourke.net](http://paulbourke.net/dataformats/tga/), along with pre-parsed width and height, in pixels, of the image. It returns pixel data for the output, as bytes, in a vector 9 times the size of the input pixel data.
```
use std::fs::File;use std::io::{Read,Write};fn main(){let mut p=vec![];let mut o=vec![0u8;18];File::open("i.tga").unwrap().read_to_end(&mut p).unwrap();let mut wh=[0;2];let h=|x|p[x] as usize;let g=|x|(3*x/256) as u8;for i in 0..2{wh[i]=h(12+i*2)+256*h(13+i*2);o[12+i*2]=g(wh[i]*256);o[13+i*2]=g(wh[i]);}let mut f=File::create("o.tga").unwrap();o[2]=2;o[16]=24;o.extend(z(p,wh));f.write(&o).unwrap();}
```
This second line is a main() function that can transform an input file named i.tga into an output file named o.tga, by calling the function z from the first line, without using any external libraries. It handles parsing of width/height, creating a header for the output file, and file reading + writing. It would add 402 bytes if the challenge required File I/O, for a total of 683. It is useful for testing.
] |
[Question]
[
Notwen wants to study the kinematics of bodies thrown from big heights in a uniform gravitational field but unfortunately he doesn't have the technical possibility to go to sufficiently high places and observe the objects while falling. But who doesn't want to see advances in science so... Let's help Notwen build a gravity simulator!
## Physical Background
An object dropped from a height \$h\$ (**without initial velocity**) in a uniform gravitational field, neglecting atmospheric effects such as drag or wind gains velocity and speeds up towards the ground with time. This "rate of change" of velocity in a unit of time is called [gravitational acceleration](https://en.wikipedia.org/wiki/Gravitational_acceleration). Near the surface of Earth, it is approximately equal to \$g\approx9.8\frac{m}{s^2}\$, but for the purposes of this challenge we will use the value \$10\frac{m}{s^2}\$, meaning that in a single second, an object increases its velocity by about \$10 \frac{m}{s}\$. Consider having a height \$h\$, which is a multiple of \$100m\$ and imagine dividing that height into equal intervals, each \$100\$ meters long. Notwen wants to measure how long it takes for the object to fall through each of those intervals, so that's what we aim to compute as well. Modern [kinematics](https://en.wikipedia.org/wiki/Kinematics) – skipping technicalities – tells us that:
$$\Delta h\_k=v\_kt\_k+\dfrac{1}{2}gt\_k^2$$
where \$\Delta h\_k\equiv\Delta h=100m\$ for all values of \$k\$ in our case, \$v\_k\$ is the initial velocity at the beginning of our \$k^\text{th}\$ interval and \$t\_k\$ is the duration of the \$k^\text{th}\$ time interval (for reference, indexing starts at \$0\$ with \$v\_0=0\$). We also know that \$v\_k\$ has the following expression:
$$v\_k=\sqrt{2g(\Delta h\_0+\Delta h\_1+\cdots+\Delta h\_{k-1})}=\sqrt{2gk\Delta h}$$
Numerically, we get \$v\_k=\sqrt{2000k}\frac{m}{s}\$ and plugging into the first equation and solving for \$t\_k\$ gives $$\color{red}{\boxed{t\_k=2\sqrt{5}\left(\sqrt{k+1}-\sqrt{k}\right)s}}\tag{\*}$$
So the object travels the first interval (\$k=0\$) in \$4.4721s\$, the second interval (\$k=1\$) in \$1.8524s\$ and so on ([pastebin](https://pastebin.com/EEEhPeLy) with more values).
## The challenge
**Input:** The height \$h\$ from which the object is thrown as either: a positive integer multiple of \$100\$, \$h\$ **or** the number of intervals \$N=\frac{h}{100}\$ (so either \$700\$ or \$7\$ would mean that \$h=700m\$) – which one is up to you.
**Output:** An ASCII art animation of a falling object, dropped from a height \$h\$ (details below).
The structure of an output frame must be as follows:
* \$N\$ newlines preceding the "ground", represented by at least one non-whitespace character (e.g. `@`). At least one of the characters of the ground must lie on the vertical that the object falls on.
* Another non-whitespace character representing the object (e.g. `X`), other than the one you chose for the ground.
* **Optionally**, a character at the beginning of each line representing the vertical axis or the wall made on \$N\$ lines. Any amount of leading and trailing spaces are fine as long as they are consistent between frames, as well as any amount of spaces between the wall and the object. Examples of valid frames include1 (for \$h=700m\$ or \$N=7\$):
```
| X >
| @ > A
| >
| or or or >
| O >
| >
| >
@@@ ^ ----- &&&
```
The object must start on the first line of the first frame, then after \$t\_0\approx 4.47s\$ the output should be flushed and your program should display the object on the same vertical but on the next line in the second frame; then after \$t\_1\approx 1.85s\$ the output should be flushed again and your program should display the object on the same vertical but on the next line in the third frame and so on, until the object reaches the line right above the ground. Example:
[](https://i.stack.imgur.com/uY9PV.gif)
### Rules
* The output should be some text written to an interactive (flushable) console, a GIF, a separate file for each frame or some other reasonable technique of output.
* Each frame should completely overwrite the last frame and be in the same location.
* You can assume that the time required for the compiler / interpreter to output the text is negligible and the minimum precision permitted for computing the square roots is to 2 decimal places.
* You can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to complete the task in the least bytes you can manage in your [language](https://codegolf.meta.stackexchange.com/a/2073/59487) of choice.
---
1: I'm lenient about what constitutes a valid frame because I want to allow whatever suits your solution best and I'm not trying to add superfluous stuff to the challenge. If anything is unclear, ask in the comments.
[Answer]
## JavaScript (ES7) + CSS + HTML, 340 bytes
```
f=n=>{o.style.height=n+'em';x.style.animationDuration=(n*20)**.5+'s';o.appendChild(x,x.remove())}
```
```
pre{position:relative;border:1px solid;height:5em;overflow:hidden}span{position:absolute;top:0;animation:x 10s cubic-bezier(0.33,0,0.67,0.33)both}@keyframes x{to{top:100%}}
```
```
<input type=number value=5 oninput=f(this.value)><pre id=o><span id=x>X
```
If I've got my sums right then the animation duration is \$ \sqrt { 20 N } \$ and then the CSS cubic-bezier does the rest.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
Nθ↓θ⁴Fθ«J²ιPXR⌊×φ×₂²⁰⁻₂⊕ι₂ι
```
[Try it online!](https://tio.run/##VY4xC8IwFITn9leETilEiEUQdBWhQkVqB9daUxpI8trXRAfxt8fUDuqb7t19cNd0NTZQK@9z0zt7dPoqkA7pNj6hNJZudvAwjHyNVVAtIAkMecbRwem@ApoxIkMQFU5Z2X/A5JJMTilaFGNH9woAaSW1GOmSc87IrM@Dq1GUAJZmPGWkkMb9ublpUGhhrLhRmQbiJwv/dKFmHpeQqfPl/dov7uoN "Charcoal – Try It Online") Link is to verbose version of code. Note: trailing space. You can observe the delay on TIO but you can't watch the animation so you'll have to imagine that from the output. Takes `N` as input. Explanation:
```
Nθ
```
Input `N`.
```
↓θ⁴
```
Print the wall and the ground, so that the output's shape is consistent.
```
Fθ«
```
Loop over each interval.
```
J²ιPX
```
Place an `X` at the appropriate height.
```
R⌊×φ×₂²⁰⁻₂⊕ι₂ι
```
Output the current canvas contents and wait for the appropriate amount of time (truncated to the nearest millisecond).
```
```
Overwrite the `X` with a space.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 81 bytes
```
{say "\e[s{"\n"x$_}-";map {say "\e[u{" \n"x 4.9e-6*$_²}o";sleep .01},^452*.sqrt}
```
["Try it online!", but TIO cannot handle the animation.](https://tio.run/##K0gtyjH7n1upoJKmYPu/ujixUkEpJjW6uFopJk@pQiW@VlfJOjexQAEuU1qtpACSUjDRs0zVNdNSiT@0qTZfybo4JzW1QEHPwLBWJ87E1EhLr7iwqKT2vzXXfwA "Perl 6 – Try It Online")
## Explanation
I chose a bit different approach (and I think it's for the better, though I don't know for sure). Instead of sleeping for times given by the formula in the OP, I just draw the appropriate situation "every 10 ms" (± errors induced by `sleep`).
That means that there are 100 frames a second, so if we denote the frame number by \$k\$, it must be \$t=k/100\$. And since we divide the vertical distance into 100 meter blocks, we can write the height as \$h = 100n\$, where \$n\$ is the number of blocks (given as an input). The height traveled in time \$t\$ is given by \$h = gt^2/2\$, so the number of blocks traveled is
$$ n = \frac{1}{100} \tfrac 1 2 g t^2 = \tfrac 1 2 g \times 10^{-6} k^2 \approx 4.905\times 10^{-6} k^2. $$
We can invert it to get the total number of frames we need to render:
$$ k = \frac{\sqrt n}{\sqrt{4.905\times 10^{-6}}} \approx 452 \times \sqrt n.$$
This suffices to write the function. It takes one argument, the number of blocks to render, i. e. \$n\$. First, we do `say "\e[s{"\n"x$_}-"`. That prints an ANSI escape sequence called *Save Cursor*, then it prints \$n\$ newlines, and after that, it prints a dash (the ground) and a newline. (This uses the cool feature of double quotes in Perl 6: you can inline result of any code right into the string by writing that code inside curly braces.)
After that, we make a sequence from 0 to \$452\sqrt n\$ (automatically truncated to integer) with `^452*.sqrt`, and we map over it. In each iteration, we print an *Unsave Cursor* ANSI sequence (which puts the cursor at the position where it was last saved), write \$4.9\times 10^{-6} k^2\$ strings "space+newline" (automatically truncated once again) and finally an `o` that denotes the object. Then we sleep for 10 ms, rinse and repeat.
Due to the automatic truncation, it just Does The Right Thing™ and moves the "o" only after each full 100 m of the fall.
[](https://i.stack.imgur.com/DuyTl.gif)
[Answer]
## Haskell, 145 bytes
```
import Control.Concurrent
a!b=[a..b]>>"\n"
f h=mapM(\k->putStr("\27[2J"++1!k++'O':k!h++"-")>>threadDelay(round$4472135*(sqrt(k+1)-sqrt k)))[1..h]
```
Needs to be run in an ANSI terminal. The input is the number of intervals.
`threadDelay`'s parameter is in nanoseconds, so a literal `4472135` is shorter than `2*sqrt 5*10^6`. Unfortunately `46**4 = 4477456` is not within the limit of the required precision.
[Answer]
# [Python 2](https://docs.python.org/2/), 117 ~~120~~ ~~123~~ bytes
-3 bytes Thanks to "Don't be a x-triple dot" and "Jonathan Frech"
```
import time
h=input()
for k in range(h):print'\33[2J'+'\n'*k+'O'+'\n'*(h-k)+'^';time.sleep(2*5**.5*((k+1)**.5-k**.5))
```
[Try it online!](https://tio.run/##Lcw9CgIxEEDhfk@Rbn7CLphlERQvYOMBXASLaELcSYhj4ekjAZvHV73y1ZDFtRa3kqsajZsfwilK@SjS8MjVJBPF1Ls8PQY6lBpFYZ3nqzuDhVWAk4XLnxjGRBZucOyj6f3yvqDjhXlaGDHZHXWOqZeotf0P "Python 2 – Try It Online")
[](https://i.stack.imgur.com/LaA04.gif)
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~201~~, 180+13 = 193 bytes
Needs using System; for 13 additional bytes.
Strangely, Console.Clear() does not seem to be working for me on TIO. However, this runs perfectly in a console app under VS2017.
EDIT: Thanks to Embodiment of Ignorance for shortening up the loop, pointing out my unnecessary variable assign and unnecessary using System.Threading; statement (leftover from VS copying), and pointing out that the ground was required! Total of 8 bytes golfed thus far with the addition of the ground. Ty Ty!
```
x=>{for(var j=x;j>0;System.Threading.Thread.Sleep((int)(4470*(Math.Sqrt(x-j+1)-Math.Sqrt(x-j--))))){Console.Clear();Console.Write("X".PadLeft(x-j+1,'\n').PadRight(x+1,'\n')+"-");}}
```
[Try it online!](https://tio.run/##VY0xa8MwEIV3/4rDS6SmEg4EOqg2hKwJhLrQDl0USbFlFCmVlOBi/NtdmSZD7w139x3vnQhEOK@ma9C2gfonRHVmmTA8BDh413h@HjKAy/VotIAQeUzt5rSEPdcW4fkIsBFRO/uqbaxAQjn1ZTWcnEc37qEre9ZVBfvLpu@tV1ymZ/eJ1kapC0LJi9F6/VI8oT2PLa2/fUQ96ZYrTP4BQvBcw9bZ4IyiW6O4R5g99g@vo0L5Z04PXO7U6Z7yvPiyCzyzN920CT7QMic5ZuM4sUyiVYFZNiZNvw "C# (.NET Core) – Try It Online")
] |
[Question]
[
[September 1993 is known on Usenet as the September that never ended.](http://www.catb.org/jargon/html/S/September-that-never-ended.html) Thus, for example, the day this question is being posted is Saturday, September 8740, 1993.
Your program or function should take any Gregorian date (with positive year) as input and return the same date as output if it's prior to September 1993 or the date on the September 1993 calendar if thereafter.
You may accept YYYY-MM-DD, YYYY/MM/DD, MM/DD/YYYY, DD/MM/YYYY, D-Monthnameabbr-YYYY, or any other popular format that uses the entirety of the year (as opposed to the year modulo 100). You need only accept one such format, of your choosing. Output format must match the input format.
Sample input → output:
* Sunday, 6 August 2017 → Sunday, 8741 September 1993
* Tuesday, 28 January 1986 → Tuesday, 28 January 1986
Or:
* 2017-08-06 → 1993-09-8741
* 1986-01-28 → 1986-01-28
In the interest of more interesting answers, the use of a built-in function designed for this purpose (such as the UN\*X [`sdate`](http://manpages.ubuntu.com/manpages/yakkety/en/man1/sdate.1.html) command) is disallowed. Aside from that and [the standard exceptions](//codegolf.meta.stackexchange.com/q/1061), this is golf, so the shortest answer wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 109 bytes
```
from datetime import*
i=input()
z=date(*map(int,i.split())).toordinal()-727806
print([i,'1993 09 %d'%z][z>9])
```
[Try it online!](https://tio.run/##FcqxDoMgEADQ3a@4xQjGGtREZLA/YhxIsOklAhe8DuXnqZ3foy@/Y5hKeaXowVk@GP0B6CkmbitcMdCHhazy@kfReksCA3fYX3TiLVL2HGNyGOwp5EOPelFzRelOYsOuGYyZQBmoXVPnfctPs8tSRjVoUAuo@Qc "Python 3 – Try It Online")
-59 bytes thanks to notjagan
-3 bytes thanks to Mr. Xcoder
-2 bytes thanks to officialaimm
-12 bytes thanks to Jonathan Allan
[Answer]
## JavaScript (ES6), 48 bytes
```
f=
s=>(d=new Date(s)/864e5-8643|0)>9?'1993-09-'+d:s
```
```
<input size=10 oninput=o.textContent=/\d{4}(-\d\d){2}/.test(this.value)?f(this.value):``><pre id=o>
```
Based on @Mr.Xcoder's algorithm.
[Answer]
# Mathematica, 55 bytes
```
If[(s=#&@@{1993,9}~DateDifference~#)>0,{1993,9,s+1},#]&
```
**I/O**
>
> {2017, 8, 6} ->{1993, 9, 8741}
>
> {1986, 1, 28}->{1986, 1, 28}
>
>
>
*-6 bytes thanx to user202729*
[Answer]
# [Perl 5](https://www.perl.org/), 102 + 16 (-MTime::Local -F-) = 118 bytes
```
$,='-';say @F=($t=timelocal(0,0,0,$F[2],$F[1]-1,$F[0]-1900)-749433599)>0?(1993,'09',31+int$t/86400):@F
```
[Try it online!](https://tio.run/##FY2xCsIwFEV/xSGQFPP0PdOorxLtlEk3N@lQSodCbYvN4s8bEy7cM9wLZ@k/o41RaCdBXtb2u6m9UyK4MLz7ce7aUaHOEf51aHJTA5SJiYxYwKnk0hjLXFzxpojZaIkstaHtMAUR9udjmX5V7WPMKxAB0m9ewjBPa4SH3SFh4jMpq@qepRE8/AE "Perl 5 – Try It Online")
Takes the date as "YYYY-MM-DD"
I think I did the count right on the command line options. I'm sure someone will correct me if I didn't.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 107 bytes
```
s=>{var d=(System.DateTime.Parse(s)-new System.DateTime(1993,8,31)).TotalDays;return d<1?s:"9/"+d+"/1993";}
```
[Try it online!](https://tio.run/##fc4xa8MwEAXgOf4VQpNEHKtOILXrOB0aOrUQaKBD6XDIFyOwJbhTUkLwb3fTpl06dHrD@3g8yzMbCMfEdsAsthRagl6ckwlHiM6KY3CNeAbnFUdyvn17F0At6wt5OXHEPns8eLu6luk11mJfj1yvz0cg0dTqB24g4s71mG2BGBXrmccP8adUeVku0iJd5FpnuxCh28CJK8J4IC@aVX7Pd7I0ctpMpfmyshrGKvk98xA8hw6zV3IRn5xHtVeyMEszv8lvpdbVvzA38@IyWiy/5WRIhvET "C# (.NET Core) – Try It Online")
Takes dates as M/D/YYYY (numbers below 10 written with only 1 digit). Written from my mobile phone using the API by heart.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 78 bytes
```
ℍZ¤∨4Ė
:'//d¦[1993₉31];>\{\‡:(…1993>↑¦365+¦¤ṇ↑∂K∂k,=;((<¤)-243]_ḥΣ“1993/09/”¤+}?
```
[Try it online!](https://tio.run/##S0/MTPz//1FLb9ShJY86VpgcmcZlpa6vn3JoWbShpaXxo6ZOY8NYa7uYaiuNRw3LQEJ2j9omHlpmbGaqfWjZoSUPd7YD@Y86mryBOFvH1lpDw@bQEk1dIxPj2PiHO5aeW/yoYQ5Im76Bpf6jhrmHlmjX2v//b2RgaK5vYKFvYAYA "Gaia – Try It Online")
### Explanation
First, we have a helper function that determines if a year is a leap year.
```
ℍ 100
Z Divmod year by 100, pushing the first 2 digits, then the second 2 digits
¤ Swap
∨ Logical OR, gives the left-most non-zero number
4Ė Check for divisibility by 4
```
The main function does the rest of the work:
```
: Push two copies of the input.
'// Split the top on on slashes.
d¦ Parse each section as a number.
[1993₉31] Push the list [1993 9 31].
;> Copy the date and check if its less than that.
\ If it is, delete the list and leave the input string on top.
{ Else:
:( Copy the date and get the year.
…1993> Get the range from 1993 to year-1.
↑¦365+¦ Map each to 365+(whether it's a leap year).
¤ Swap, bring the date back to the top.
ṇ↑ Pull out the year and check if it's a leap year.
∂K∂k, Push the pair of lists [[days in months in a leap year] [days in months]]
= Index the result of checking if the year is a leap year into the pair.
;((< Get the first (month number - 1) elements.
¤ Swap, bring date back to the top.
) Get the day.
-243 Push -243 (243 is the number of days between Jan 1 1993 and Sept 1 1993).
] Wrap everything in a list.
_ Flatten the list.
ḥ Remove the first element (the input string).
Σ Sum it.
“1993/09/”¤+ Append the resulting number to "1993/09/".
}? (end if)
Implicitly display whatever is on top of the stack.
```
] |
[Question]
[
Write a program that adds or removes whitespace to format code nicely. Rules for what the code should look like when you're done:
* No line should contain more than one of `{` and `}`.
* A `{` should always be the last thing on a line.
* A `}` should always be the *only* thing on a line (besides whitespace that comes before it).
* The amount of whitespace in front of each line should be a fixed multiple of the current nesting count. (You can use any amount of indentation you want, as long as it doesn't change.)
* No whitespace should be inserted or removed that doesn't contribute to satisfying one of these rules.
The nesting count for the first line is 0. The nesting count of any other line is the nesting count of the previous line, plus one if the previous line contains a `{`, minus one if the current line contains a `}`.
`{` and `}` inside string literals and comments don't count in the above rules. A string literal is text enclosed in single or double quotes, where single or double quotes with an odd number of backslashes immediately before them aren't interpreted as the end of the string literal. A comment is text enclosed in `/*` and `*/`, or text going from `//` to the end of the line. In a line multiple comment start markers, only the first one counts. Comments are not parsed inside string literals.
# Examples
```
main() {printf("Hello!"); // I don't care about the world...
}
becomes:
main() {
printf("Hello!"); // I don't care about the world...
}
int main(){
puts("a");
puts("b");
}
becomes:
int main(){
puts("a");
puts("b");
}
main()
{ printf("{"); /* }
} */
printf("}//}"); ///*
}
becomes:
main()
{
printf("{"); /* }
} */
printf("}//}"); ///*
}
int test[] = {1, 2, 3};
becomes:
int test[] = {
1, 2, 3
}
;
```
[Answer]
## JavaScript (ES6), ~~376~~ ~~373~~ ~~378~~ 393 bytes
This was... quite the challenge...
```
let f =
s=>{F=(i,l=1)=>[a=a.map(([q,y])=>[q,y<i+e?y:y+l]),e+=l]
for(a=b=[];b;s=s[r='replace'](/\/\*(?:(?!\/\*|\*\/)[^])*\*\/|\/\/.+|("|')(?:\\.|(?!\1).)*\1/,(q,_,y)=>a.unshift(b=[q,y])&0))b=l=0
s=s[e=1,r](/[{}](?=.)|.(?=})/g,(c,i)=>F(i)&&c+`
`)[e=0,r](/.+/g,(x,i)=>x[r](/^\s*/,y=>" ".repeat(q=/{/.test(x)?l++:/}/.test(x)?--l:l,F(i,q-y.length))))
a.map(([q,y])=>s=s.slice(0,y)+q+s.slice(-~y))
return s}
```
```
<textarea rows=7 cols=50 oninput=O.innerText=f(value)> main() {printf("Hello!"); // I don't care about the world...
}</textarea>
<pre id=O></pre>
```
Let me know if there's anything wrong with the output, though I ~~couldn't find anything~~ can't find anything more.
### Ungolfed version
I golfed the code as I wrote it, so let's see how this goes...
```
function prettify(code) {
let excerpts = [], extras, level;
// Extract comments and strings for easy parsing
// This has to be done recursively because of the nested comments
for (let done = false; !done; ) {
done = true;
code = code.replace(/\/\*(?:(?!\/\*|\*\/)[^])*\*\/|\/\/.+|("|')(?:\\.|(?!\1).)*\1/, (excerpt, _, index) => {
excerpts.unshift([excerpt, index]);
done = false;
return "0";
});
}
// Update the indices of the excerpts when the code is changed
let adjustIndices = (index, length) => {
index += extras;
excerpts = excerpts.map(([string, oldIndex]) => {
var newIndex = oldIndex;
if (oldIndex >= index) newIndex += length;
return [string, newIndex];
});
extras += length;
}
// Add extra newlines where necessary:
// - After a { or a } if there isn't one already
// - Before a } if there isn't one already (note: already-indented '}'s will get an extra newline)
extras = 0;
code = code.replace(/[{}](?=.)|.(?=})/g, (char, index) => {
adjustIndices(index + 1, 1);
return char + "\n";
});
// Remove extra whitespace at the beginning of each line,
// and the same time apply the necessary number of tabs
extras = 0;
level = 0;
code = code.replace(/.+/g, (line, index) =>
line.replace(/^\s*/, spaces => {
let tabs;
if (line.indexOf('{') > -1)
tabs = level, level += 1;
else if (line.indexOf('}') > -1)
level -= 1, tabs = level;
else
tabs = level;
adjustIndices(index, tabs - spaces.length);
return "\t".repeat(tabs);
})
);
// Add back in the excerpts
for ([excerpt, index] of excerpts)
code = code.slice(0, index) + excerpt + code.slice(index + 1);
return code;
}
```
```
<textarea rows = 7 cols = 50 oninput = "O.innerText = prettify(this.value)"> main() {printf("Hello!"); // I don't care about the world...
}</textarea>
<pre id=O></pre>
```
[Answer]
## JavaScript (ES6), ~~260~~ 259 bytes
Parses the input character by character. Uses 4-space indentation.
```
s=>s.replace(/[^]/g,(x,n)=>(p=s[n-1],a=!l&!c&!e,l|x!='/'?a&x=='*'&p=='/'?c=x:!c&!e&x=='"'?(l^=1,x):x==`
`?(i=e=0,x):a&x=='}'?d--&&i?`
`+x:i=x:a&x=='{'?s[i=!++d,n+1]==`
`?x:x+`
`:i?x:x==' '?'':' '.repeat(!c*d*4,i=1)+x:p==x?e=x:!e&p=='*'?(c=0,x):x),d=i=l=c=e=0)
```
This is still a WIP and was basically tested only against the provided examples. If you find any bug, please let me know in the comments.
The state of the parser is fully described by the following variables:
* `d` → current nesting depth
* `i` → flag telling that we're located 'inside' the code (i.e. after the leading spaces of the line)
* `l` → string literal flag
* `c` → block comment flag
* `e` → line comment flag
### Obligatory indented version
```
s => s.replace(
/[^]/g,
(x, n) => (
p = s[n - 1],
a = !l & !c & !e,
l | x != '/' ?
a & x == '*' & p == '/' ?
c = x
:
!c & !e & x == '"' ?
(l ^= 1, x)
:
x == `\n` ?
(i = e = 0, x)
:
a & x == '}' ?
d-- && i ? `\n` + x : i = x
:
a & x == '{' ?
s[i = !++d, n + 1] == `\n` ? x : x + `\n`
:
i ?
x
:
x == ' ' ? '' : ' '.repeat(!c * d * 4, i = 1) + x
:
p == x ?
e = x
:
!e & p == '*' ? (c = 0, x) : x
),
d = i = l = c = e = 0
)
```
### Test cases
```
let f =
s=>s.replace(/[^]/g,(x,n)=>(p=s[n-1],a=!l&!c&!e,l|x!='/'?a&x=='*'&p=='/'?c=x:!c&!e&x=='"'?(l^=1,x):x==`
`?(i=e=0,x):a&x=='}'?d--&&i?`
`+x:i=x:a&x=='{'?s[i=!++d,n+1]==`
`?x:x+`
`:i?x:x==' '?'':' '.repeat(!c*d*4,i=1)+x:p==x?e=x:!e&p=='*'?(c=0,x):x),d=i=l=c=e=0)
console.log(f(
` main() {printf("Hello!"); // I don't care about the world...\n` +
` }`
))
console.log(f(
`int main(){\n` +
` puts("a");\n` +
` puts("b");\n` +
`}`
))
console.log(f(
`main()\n` +
`{ printf("{"); /* }\n` +
`} */\n` +
` printf("}//}"); ///*\n` +
` }`
))
console.log(f(
`int test[] = {1, 2, 3};`
))
```
] |
[Question]
[
Write a program that outputs all possible Tic Tac Toe positions including the corresponding game outcome. Avoid duplicate output of equal positions.
The program takes no input.
### Rules:
* A position output must consist of 9 characters, using `X` and `O` for the taken squares, and an arbitrary non-whitespace character for the blank squares
* Each position must be printed in 3 lines/columns, with a blank line as a separator between two positions.
* Additional whitespace / blank lines / box drawing characters are welcome
* Player X goes first
* The *outcome* can be either of:
+ X has won
+ O has won
+ Draw
+ Game in progressYou are free to choose a suitable visualization of the position's outcome, e.g. as colored text, or as textual annotation, as long as it is placed near the corresponding position
* Positions are considered equal if one can be obtained from the other by rotation or mirroring. Duplicate positions must not be printed. (In other words, print the equality classes only.)
For example, print **only one** of the following:
```
X•• ••X ••• •••
••• ••• ••• •••
••• ••• X•• ••X
```
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
---
### Sample output:
```
•••
•••
••• -
X••
•••
••• -
•X•
•••
••• -
•••
•X•
••• -
[…]
XXO
OOX
XXO /
OXO
XXX
OXO X
```
**Hint:** There are 765 positions, with 91 wins for X, 44 wins for O, and 3 draws.
---
A [similar question](https://codegolf.stackexchange.com/questions/1065/the-tic-tac-toe-dictionary) has been asked before, but this one is different.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~192~~ ~~179~~ 168 bytes
```
5ĿḢṠµFf0L¬ị⁾-/µ5ĿḢṠµ?
U,µṚ,µ€µ“æɗþƑ’DịFs3,µ€€Fs9s3$€Ṣ
FSµ×’¬
ÑPµA_µọ9n1
,UŒDḢ$€;;ZS€f3,-3
Ç,SS€µṪµṪCµSṠ‘µ?÷Ḣ
Ça3Ŀa4Ŀ
3ṗ9_2s3$€ÇÐf2Ŀ€QḢ€µ;ÑFµ€µ3Ḷ’,“O¤X”yµ€Fs10µs3Gµ€j⁾¶¶
```
[Try it online!](https://tio.run/nexus/jelly#TVCxSgQxFOzzHZY5vLtosWwh4hEbQSUciM1xzRYWNqnsVpsrRHBtVkVBDrGQbbNeOLiFl1XwM5IfWcechRAm7zHz3kzSbbeNX8y9fSEjs/4BVX55HS5XvU0y/6gdNuZkvH0EhqsKkD@5t@/Srb6KkD@MMCS1WJM4UidabKDwds6kIuNKqKhirjgiszvBquVNcj5gfPx5N4LJrzZNTxWuTPCeYG7GlYpO3r5H2COjkCXk94jjPjAE0VS0zXSrbZjwtkwmw7Wrm7nbbNg2KI@hi2tSV8i/7MIvasTheMMhvZ6E/PkiMlIP@mS02I/dGX6Baqq77gc "Jelly – TIO Nexus") (Takes about 30 seconds, so be patient).
### How it Works
*High level overview:*
In intermediate steps, this stores X as `1`, unplaced as `0`, and O as `-1`.
The program generates all 3^9 possibilities, then keeps only the valid positions based on meeting the three criteria:
* There is 1 or 0 more X than O.
* Not both X and O have won.
* If X has won, there is 1 more X than O. If O has won, there are an equal number of Os and Xs.
Then, the program replaces each game state with all of its rotations and reflections to get a list of all equivalence classes. This is the operation which takes most of the time.
The first game state is taken from each of the equivalence classes, then who won is calculated.
*Where this happens*
The lines are numbered for readability
```
1: 5ĿḢṠµFf0L¬ị⁾-/µ5ĿḢṠµ? ••calculates who wins (output as -1 or 1) or draw ("-") or in game ("/")
µ5ĿḢṠµ? - if(someone won based on line 5):
5ĿḢṠ - return 1 if X won and -1 if O won
µ - else:
Ff0L¬ị⁾-/ - return "/" if the game is in progress and "-" if the game is at a tied end-state
2: U,µṚ,µ€µ“æɗþƑ’DịFs3,µ€€Fs9s3$€Ṣ••outputs the equivalence class to a game state
U, - list of game state [reflected horizontally, unaltered]
µṚ,µ€ - for each, replace with the list [reflected vertically,unaltered]
µ“æɗþƑ’DịFs3,µ€€ - for each, replace with the list [rotated 90 degrees counter-clockwise,unaltered]
Fs9s3$€ - reformat into list of game states
Ṣ- Sort
3: FSµ×’¬ ••outputs truthy iff there is the right number of `X`s to `O`s (condition 1)
FS - d = number of `X`s minus number of `O`s
µ×’ - d*(d-1): falsey iff d is 0 or 1
¬ - logical not, to return truthy iff d is 0 or 1
4: ÑPµA_µọ9n1 ••outputs truthy iff there is the right number of winners (condition 2)
Ñ - the winners. [-3,3] is what we want to return falsy on
PµA_µ - 18 on [-3,3] and 0 otherwise
ọ9n1 - not divisible by 9 exactly once: 0 on [-3,3] and 1 otherwise
5: ,UŒDḢ$€;;ZS€f3,-3 ••outputs the number of times each player won.
,UŒDḢ$€;;Z - the diagonals, rows, and columns of a board
S€ - sum of each. Returns -3 or 3 iff the line is only 1s or -1s
f3,-3 - filter out, keeping only 3s and -3s
6: Ç,SS€µṪµṪCµSṠ‘µ?÷Ḣ ••return truthy iff the winner corresponds to the respective numbers of X and O (condition 3)
Ç,SS€ - list of winners and how many more Xs than Os there are
µSṠ‘µ? - if O won, then
µṪ - how many more Xs than Os there are
- else:
µṪC - the complement of how many more Xs than Os there are
÷Ḣ - deal with no one winning
7: Ça3Ŀa4Ŀ ••return truthy iff the game state meets all three conditions
Ç 3Ŀ 4Ŀ - the three conditions: on line 3,4, and 6
a a - joined by logical ANDs
8: 3ṗ9_2s3$€ÇÐf2Ŀ€QḢ€µ;ÑFµ€µ3Ḷ’,“O¤X”yµ€Fs10µs3Gµ€j⁾¶¶ ••do everything
3ṗ9_2 - all possible game states, with -1 for O and 1 for X
s3$€ - turn into two-dimensional game boards
ÇÐf - filter based on line 6: if the board meets all three ocnditions
2Ŀ€Q - generate the equivalence classes for each and remove repeats based on line 1
Ḣ€ - get the first board from each class
µ;ÑFµ€ - append the winner to each board based on line 1
µ3Ḷ’,“O¤X”yµ€ - map each -1, 0, and 1 to the proper `O`, `¤`, and `X`.
Fs10µs3Gµ€ - format each board- winner combos
j⁾¶¶ - join the combos by double-newlines
```
[Answer]
# Ruby, 305 bytes
```
19683.times{|i|c=(i%3).to_s
s=(9**8+i/3*6562).to_s(3)
w=0
t=(0..3).map{|j|r=s[1+j*2,9]
w|=1<<r[0..2].sum%8|1<<(c+r[j/2]+r[4+j/2]).sum%8
[r,r.reverse].min}.min
v=t[0..2]+$/+t[7]+c+t[3]+$/+t[6]+t[5]+t[4]
w&=65
b=v.sum%51
w<65&&b>w/64&&b<3-w%2&&t==s[1,9]&&puts(v.tr("012","X.O"),w<1?v.include?(?1):w%31,"")}
```
This works similiarly to the other answers in that it generates all `3**9` boards then filters out the valid ones. Internally, we use ternary numbers where `0=X 1=. 2=O` in the output. Iterate `c` through the 3 possible values for the centre, and `s` through the `3**8 = 6561` values for the perimeter. Before converting `i/3` to a string representation of a ternary number, we multiply by `6562` to duplicate all digits, and add `3**16` to start the number with a 1, in order to ensure there are leading zeros where applicable. `w` is the win condition - set this to zero.
For each board **Iterate through 4 rotations** of the digits in `s` to find the lexically lowest version of the current 8 digit ternary number representing the perimeter. At the same time, add the ascii values of the first 3 digits (top row of current rotation) and use this to check for a win. Also, add the ascii values of `c` and a pair of diametrically opposite digits to check if there is a win through the centre.
**Check if the output is valid** - If both 1's bit and 64's bit of `w` are both set, both sides win - this is not valid. Check the balance of X's and O's (if there is no winner yet it can be either equal X and O or one more X - but if the game is won, there is only one possible value, as the winner must have gone last.) To avoid showing different rotations of the same board, only output if the lexically lowest version of the perimeter corresponds to the current value of `s[2,9]`.
**Output the board**, sustituting the symbols `tr("012","X.O")`. The game status is shown below the board. If w=0, this is `true` if there are still empty squares (game still in progress) and `false` if the board is full. If `w` is nonzero we output `1` if player 1 (X) has won or `64%31==2` if player 2 (O) has won.
**Ungolfed**
```
19683.times{|i| #check 3**9 possibilities
c=(i%3).to_s #centre square: 0=X, 1=. 2=O
s=(9**8+i/3*6562).to_s(3) #perimeter:multiply i/3 by 3**8+1 to duplicate digits, add 3**16 to give a 1 at left side to ensure leading zeros
w=0 #set w=0 to clear wins (1´s bit holds win for X, 64´s bit holds win for O)
t=(0..3).map{|j| #build an array of 4 different rotations of the perimeter
r=s[1+j*2,9] #by taking different 9-character slices of s
w|=1<<r[0..2].sum%8| #add ascii codes mod 8 for top row of current rotation, take sum modulo 8 to give sum of digits. set a bit in w (we only care about bits 0 and 6)
1<<(c+r[j/2]+r[4+j/2]).sum%8 #do the same for one of the 4 lines through the centre. if j/2=0 check diagonal, if j/2=1 check horizontal/vertical.
[r,r.reverse].min}.min #add to the array the lexically lowest version(forward or reverse) of the current rotation. When the loop ends, find the lexically lowest version overall and assign to t.
v=t[0..2]+$/+t[7]+c+t[3]+$/+t[6]+t[5]+t[4]#format the output into a square 012\n 7c3\n 654
w&=65 #clear bits 1 through 5 of w, leave only bits 0 and 6 which are the ones of interest.
b=v.sum%51 #valid values of sum of ascii codes in output are 461 (equal 0's and 2's) and 460 (one more 0 than 2). Take modulo 51 to reduce these values to 1 and 2
w<65&& #if a maximum of one player has a winning line (not both) and
b>w/64&& #b must be 1 or 2 (only 2 permitted if O's won)
b<3-w%2&& #b must be 1 or 2 (only 1 permitted if X's won)
t==s[1,9]&& #s[2,9] is the lexically lowest version of the current board (to avoid duplicates) then
puts(v.tr("012","X.O"), #output the board, subsituting internal "012" characters for external "X.O"
w<1?v.include?(?1):w%31,"") #if nobody won, output true if game in still in play (1's present on board) else false
} #if there is a winner, output (player) 1 for X, (player) w%31=2 for O. Also output a blank line.
```
**Checking scheme**
The diagrams below show the scheme for rotation (and win checking, in capitals). The diagrams are shown unrotated. The four different rotations are taken as substrings from the double copy of `i/3`, with the 3 consecutive capital letters on the perimeter of each diagram (the "top" per current rotation) being the first 3 characters in the 9-character substring. For each rotation, 9-character reversal (diagonal flip about A-E or C-G axis) is also tried. The board is only output if the current value of `i/3` is the lexically lowest of all rotations and mirrors.
```
ABC abC aBc Abc
hZd hZD hZd HZD
gfE GfE GFE Gfe
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~648~~ 620 bytes
```
import re
M=re.match
x='X';o='O'
R=lambda b,z=[6,3,0,7,4,1,8,5,2]:''.join(b[z[i]]for i in range(9))
p='XXX......|...XXX...|......XXX|X...X...X';q=p.replace(x,o)
def e(b):c=b.count;d=c(x)-c(o);w=M(p,b)or M(p,R(b));v=M(q,b)or M(q,R(b));return 0 if d not in[0,1]else 0 if w and v else(x if d==1 else 0)if w else(o if d==0 else 0)if v else'.'if'.'in b else'/'
h=set()
for n in range(3**9):
b=reduce(lambda a,v:('.XO'[a[1]%3]+a[0],a[1]/3),range(9),('',n))[0]
if b not in h:
u=e(b)
if u:print'%s\n%s\n%s %s\n'%(b[:3],b[3:6],b[6:],u)
h.update(reduce(lambda a,v:a+[R(a[-2]),R(a[-1])],range(3),[b,R(b,[2,1,0,5,4,3,8,7,6])]))
```
[Try it online!](https://tio.run/##ZVLBbuMgED2Xr@ASAe3UteNutnXEJ1SVcorEcgCbrL1KwHHsNFvl37OD7WpXWktjmDcPeDym/d3XwS9vt@bQhq6nnSNvsnPJwfRlTS6Sbdk6SPbOyEbuzcFWhlr4lGoFOaTwHZ4hgxf4BktdMJb8Co3nVn2qRutd6GhDG0874386/ioEaXG77TYZvyvGlFwnAJNrTMdg66Nsk861e1M6foEgSOV21HErilLapAyD79eVLPlFPJY8iPWHfOMtWIGnxskGmWJ9RvD4BR5nsHP90Hma0mZHK@pDjyJVCpl2@5Ob4A9qfEXPNCL8MhKlzOhEECNhLIW5lP5TmlaxhDW7@PPUTsATI7U8uZ4LEq3xf63J7@9fRUGoReOrAe87G23gXHCWbN@ZMirTi1w/GJVqiMlTLuDLWOCMgRcCayQKsvOlaF2Qu0FG08gd4kPRdo3v2eL0w09B48AW@GRFrsGqvFjFYVVoGHBNnQxtZXrH/9dlHtSGG/W41ALGSaaFnhWhNGWj2aCW2B4ptscztssLtssKWULcbn8A "Python 2 – Try It Online")
Probably a bit of minor golfing possible here with this approach; but not a lot.
Edit: Thx to ovs, who noted a tweak gaining 28 bytes; and 3 from [Artemis Fowl](https://codegolf.stackexchange.com/users/80756/artemis-fowl)
**Un-golfed code**
The basic idea here is: brute force each of the 3^9=19683 possible board encodings. Keep track of the conjugates (rotations and reflections) of boards that have already been examined so you don't duplicate entries. At a minimum, valid boards must have either an equal number of X's and O's or else one more X than O. Not possible to have both a win for X and a win for O; plus some additional finicky constraints.
```
import re
from collections import Counter
FLIP_XFRM = [2,1,0,5,4,3,8,7,6]
ROT_XFRM = [6,3,0,7,4,1,8,5,2]
def xfrm(b, xf):
return ''.join(b[xf[i]] for i in range(9))
def flipIt(b):
return xfrm(b,FLIP_XFRM)
def rotIt(b):
return xfrm(b,ROT_XFRM)
def conjugates(b):
conj = [b, flipIt(b)]
for i in range(3):
conj += [rotIt(conj[-2]), rotIt(conj[-1])]
return conj
def tttToB(n):
b = ''
for i in range(9):
b = '.XO'[n %3]+b
n /= 3
return b
def printBoard(b,outcome='.'):
print '%s\n%s\n%s %s\n' % (b[:3],b[3:6],b[6:],outcome)
def evalBoard(b):
c = Counter(b)
if c['X']-c['O'] not in [0,1]:
return False
p1 = 'XXX......|...XXX...|......XXX|X...X...X'
p2 = p1.replace('X','O')
br = rotIt(b)
w1 = re.match(p1,b) or re.match(p1,br)
w2 = re.match(p2,b) or re.match(p2,br)
if w1 and w2:
return False
if w1:
return 'X' if c['X']==c['O']+1 else False
if w2:
return 'O' if c['X']==c['O'] else False
if '.' in b:
return '.'
else:
return '/'
def main():
history = set()
for m in range(3**9):
b = tttToB(m)
if b not in history:
outcome = evalBoard(b)
if outcome:
printBoard(b,outcome)
history.update(conjugates(b))
main()
```
] |
[Question]
[
In the wake of the many (two?) FizzBuzz-related challenges posted recently on PPCG, I've been tempted to come up with my own. Behold...
# Fizz Buzz Lightyear
Write a program or function that takes an integer `n` and prints out `FizzBuzz` for any number divisible by 15, `Fizz` for any number divisible by 3, and `Buzz` for any number divisible by 5, up to (and including) `n`. Output for all `i` must be followed by a newline. But there's a twist!
For every third time you print `Buzz`, Buzz Lightyear finally heeds your call and crash lands in your program. He then introduces himself - but since he crash landed, some of what he said gets mixed up with your program's output:
```
Buzz Lightyear, Space Ranger, Universe Protection Unit.
FizzBuzz Lightyear, Space Ranger, Universe Protection Unit.
```
*(that is, only append `Lightyear, Space Ranger, Universe Protection Unit.` to `Buzz` or `FizzBuzz` - whatever it is you'd have displayed otherwise. Note the leading space)*
However, Buzz Lightyear, being the Space Ranger he is, has very acute hearing, and so *printing `FizzBuzz` will count towards your `Buzz` count*.
Then, Buzz hangs around to defend your computer from all of that evil output, until you hit another number that's divisible by 5 (or 15, since those are divisible by 5, too). What that means is until you have to print `Buzz` (or `FizzBuzz`) again, you don't print anything at all.
When you finally reach that condition, Buzz departs:
```
To infinity and beyond!
```
# Example Output
This is the expected output for `n = 25`: *(notice how it skips 16 through 19)*
```
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz Lightyear, Space Ranger, Universe Protection Unit.
To infinity and beyond!
Fizz
22
23
Fizz
Buzz
```
# Rules
Optional trailing newline is acceptable.
This is code golf; as such, shortest code, in bytes, wins.
Assume given `n` is valid *and greater than or equal to 15* (which is when the challenge first deviates from standard fizzbuzz)
Buzz greets you when the "Buzz counter" (which counts both `Buzz` and `FizzBuzz`) hits 3; he departs when the next `Buzz` (including, again, both `Buzz` and `FizzBuzz`) is printed.
The number in which he departs does not count towards the next "Buzz counter"; you should instead start counting the `Buzz`es again from 0. For instance, a program running with `n = 25` (example output) should end with a "Buzz counter" of 1, since that's how many times `Buzz` was printed since the last time he departed.
In case `n` falls between one of Buzz's arrivals and one of his departures (i.e., he's still there - you're not printing anything), graceful termination is expected. Therefore, the last line of output would be his introduction
Standard loopholes are forbidden.
[Answer]
# Javascript (ES6), 182 175 bytes
* **-7 bytes**: Moved Buzz Lightyear logic into Buzz ternary expression.
```
f=(n,s=i=b=_='')=>i++<n?f(n,s+`${(i%3?_:'Fizz')+(i%5?_:`Buzz${++b%3?_:` Lightyear, Space Ranger, Universe Protection Unit.${(i+=5)>n?_:`
To infinity and beyond!`}`}`)||i}
`):s
```
```
<!-- snippet demo: -->
<input oninput=o.innerHTML=f(this.value)>
<pre id=o>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~185~~ ~~178~~ 172 bytes
```
for i in range(input()):
if-~i%20<16:print i%20/19*"To infinity and beyond!"or i%3/2*"Fizz"+i%5/4*"Buzz"+i%20/14*" Lightyear, Space Ranger, Universe Protection Unit."or-~i
```
[Try it online!](https://tio.run/nexus/python2#JY67DoJAEEV7v2LchATwgeAjQqwsrCyMjw9YYcBpZsk6mEDhr@NuLM9N7rl3rI0FAmKwmhsMidtOwigqJkD14ktBtjqku6K1xAKekjSP1d24Rk1M0oPmCp7YG66myruCdZLF6kTDoGYUbJNNrI7dH3zbIZypeUmP2s7h1uoS4eq3HT2YPmjfCBdrBEshwz6TpTO7M@OY738 "Python 2 – TIO Nexus")
### Explanation
Observe: Buzz Lightyear arrives on the third "buzz number" and departs on the fourth. "Buzz numbers" are the multiples of five. Thus, Buzz's movements happen on a cycle of length 20.
We loop over each `i` from 0 through input-1. (This means that `i` is always one less than the actual number we're considering.)
Using `-~i` as a shortcut for `i+1`, `if-~i%20<16:` checks if `i+1`, mod 20, is 15 or under. (If it's 16 to 19, Buzz Lightyear is present and we don't want to output anything.)
Inside the if statement, we want to print `To infinity and beyond!` on every multiple of 20--that is, every time `i%20` is 19. (Remember that `i` is one less than the actual number.) Since `i%20` will never be greater than 19, `i%20/19` will be 1 in the desired case, <1 otherwise. Python 2, conveniently, truncates floats when multiplying by strings, so `i%20/19*"..."` gives the full string if `i%20` is 19, otherwise `""`.
If the above case applies, we don't print anything else. But if the first expression is `""` (which is falsy), we use `or` to keep going. The expressions for `Fizz`, `Buzz`, and the introduction are computed similarly to the above and added together.
Finally, if none of these cases applies, we print the number itself with `-~i`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~97~~ ~~93~~ 90 bytes
```
>GN"FizzBuzz"2äN35SÖÏJ)˜1(è“To infinity€ƒ—°!“)N20%©_è®15Q” Lightyear,‡²ìÓ,ªÜŠí‰¿.”×J®16‹i,
```
[Try it online!](https://tio.run/nexus/05ab1e#AYUAev//PkdOIkZpenpCdXp6IjLDpE4zNVPDlsOPSinLnDEow6jigJxUbyBpbmZpbml0eeKCrMaS4oCUwrAh4oCcKU4yMCXCqV/DqMKuMTVR4oCdIExpZ2h0eWVhcizigKHCssOsw5MswqrDnMWgw63igLDCvy7igJ3Dl0rCrjE24oC5aSz//zQx "05AB1E – TIO Nexus")
Explanation to come after further golfing.
**Alternative 97 byte version**
```
>G"FizzBuzz"2ä” Lightyear,‡²ìÓ,ªÜŠí‰¿.”)˜N•9¨•3äR%15%_ÏJ“To infinity€ƒ—°!“)N20ÖèN)˜é®èN20%15›i\},
```
] |
[Question]
[
# Task
Your task is to convert a text into medieval orthography.
# Details
1. `j` is converted to `i` and `J` to `I`.
2. `u` and `U` at the beginning of words are converted to `v` and `V` respectively.
3. `v` and `V` at anywhere except the beginning of words are converted to `u` and `U` respectively.
4. `s` is converted to `≈ø` (U+017F) unless at the end of the word or preceded by another `s`.
# Specs
* A word is defined as a sequence of letters in `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`.
* All words will have at least two letters.
* The input will only consist of **printable ASCII characters** (U+0020 - U+007E).
* There will be no occurrences of more than two consecutive `s`. That is, `sss` will not be a substring of the input.
# Testcases
Individual words:
```
Input Output
------------------------
Joy Ioy
joy ioy
Universe Vniuer≈øe
universe vniuer≈øe
Success Succe≈øs
successfull ≈øucce≈øsfull
Supervise Superui≈øe
supervise ≈øuperui≈øe
Super-vise Super-vi≈øe
I've I've
majors maiors
UNIVERSE VNIUERSE
0universe 0vniuer≈øe
0verify 0verify
I0ve I0ve
_UU_ _VU_
_VV_ _VU_
ss_ ≈øs_
```
Whole paragraph:
```
Input: Christian Reader, I have for thy use collected this small Concordance, with no small labour. For being to comprise much in little roome, I was to make choyse of the most principall and usefull places, and to rank them under such words as I thought most essentiall and materiall in the sentence, because the scant roome allotted unto me, would not permit that I should expresse them under every word in the verse, as it is the manner in large Concordances.
Output: Chri≈øtian Reader, I haue for thy v≈øe collected this ≈ømall Concordance, with no ≈ømall labour. For being to compri≈øe much in little roome, I was to make choy≈øe of the mo≈øt principall and v≈øefull places, and to rank them vnder ≈øuch words as I thought mo≈øt e≈øsentiall and materiall in the ≈øentence, becau≈øe the ≈øcant roome allotted vnto me, would not permit that I ≈øhould expre≈øse them vnder euery word in the ver≈øe, as it is the manner in large Concordances.
```
The [SHA-256](http://www.xorbin.com/tools/sha256-hash-calculator) hash of the output of the last testcase is:
```
5641899e7d55e6d1fc6e9aa4804f2710e883146bac0e757308afc58521621644
```
# Disclaimer
Medievall orthographie is not that con≈øtante. Plea≈øe do not complayne if you ≈øhall ≈øee olde bookes with a different orthographie.
[Answer]
# SED, 144 140 111 Bytes
saved 29 bytes thanks to NoOneIsHere
```
-r -e'y/j/i/g;y/J/I/g;s/ u/ v/g;s/ U/ V/g;s/^u/v/g;s/^U/V/g;s/([^s])s(\w)/\1≈ø\2/g;s/(\w)v/\1u/g;s/(\w)V/\1U/g'
```
[Answer]
## Python 3 (128 126 bytes)
```
import re;lambda k:re.sub("(?<!s)s(?=[a-zA-Z])",'≈ø',re.sub("(?i)j|(?<![a-z])u|(?<=[a-z])v",lambda c:chr(ord(c.group())^3),k))
```
`chr(ord(c.group())^3)` feels excessive to xor a single-character string, but maybe a real Pythonista can suggest a golf. However, it's very convenient that `^3` suffices to interchange `i <-> j` and `u <-> v`.
NB The only thing here which requires Python 3 is the Unicode character: Python 2 complains `Non-ASCII character '\xc5' <snip> but no encoding declared`.
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~55~~ ~~54~~ 50 bytes
```
T`jJvV`iIuU
Ti01`uUp`vVp`[a-z]+
s(s*[a-zA-Z])
≈ø$1
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYApUYGpKdlZgaUl1VQpUaTAxYHVVcGB2VnBgW2Etel0rCnMocypbYS16QS1aXSkKxb8kMQ&input=Sm95CmpveQpVbml2ZXJzZQp1bml2ZXJzZQpTdWNjZXNzCnN1Y2Nlc3NmdWxsClN1cGVydmlzZQpzdXBlcnZpc2UKU3VwZXItdmlzZQpJJ3ZlCm1ham9ycwpVTklWRVJTRQowdW5pdmVyc2UKMHZlcmlmeQpJMHZlCl9VVV8KX1ZWXwpzc18KQ2hyaXN0aWFuIFJlYWRlciwgSSBoYXZlIGZvciB0aHkgdXNlIGNvbGxlY3RlZCB0aGlzIHNtYWxsIENvbmNvcmRhbmNlLCB3aXRoIG5vIHNtYWxsIGxhYm91ci4gRm9yIGJlaW5nIHRvIGNvbXByaXNlIG11Y2ggaW4gbGl0dGxlIHJvb21lLCBJIHdhcyB0byBtYWtlIGNob3lzZSBvZiB0aGUgbW9zdCBwcmluY2lwYWxsIGFuZCB1c2VmdWxsIHBsYWNlcywgYW5kIHRvIHJhbmsgdGhlbSB1bmRlciBzdWNoIHdvcmRzIGFzIEkgdGhvdWdodCBtb3N0IGVzc2VudGlhbGwgYW5kIG1hdGVyaWFsbCBpbiB0aGUgc2VudGVuY2UsIGJlY2F1c2UgdGhlIHNjYW50IHJvb21lIGFsbG90dGVkIHVudG8gbWUsIHdvdWxkIG5vdCBwZXJtaXQgdGhhdCBJIHNob3VsZCBleHByZXNzZSB0aGVtIHVuZGVyIGV2ZXJ5IHdvcmQgaW4gdGhlIHZlcnNlLCBhcyBpdCBpcyB0aGUgbWFubmVyIGluIGxhcmdlIENvbmNvcmRhbmNlcy4) (The first line enables a linefeed-separate test suite.)
[Answer]
# Python 3.5, ~~124~~ ~~116~~ ~~111~~ ~~118~~ ~~125~~ ~~144~~ 142 bytes:
```
import re;lambda k:re.sub("J|j|(?<![a-zA-Z])[uU]|(?<=[a-zA-Z])[Vv]|(?<!s)s(?=[a-zA-Z])",lambda g:dict(zip('jJuUvVs','iIvVuU≈ø'))[g.group()],k)
```
Well, this seems like the perfect job for *regular expressions*!
[Answer]
# JavaScript (ES6), 154
Using parseInt to identify alphabetic characters. Note: casually but luckily `parseInt('undefined',36)|0` is < 0
```
s=>[...s].map((c,i)=>((n=v(c))-19?n==31&p>9?'uU':n!=30|p>9?c=='s'&s[i-1]!=c&v(s[i+1])>9?'?':c+c:'vV':'iI')[p=n,c<'a'|0],p=0,v=c=>parseInt(c,36)|0).join``
```
**Less golfed**
```
s=>
[...s].map(
(c,i)=>
((n=v(c))-19
?n==31&p>9
?'uU'
:n!=30|p>9
?c=='s'&s[i-1]!=c&v(s[i+1])>9
?'≈ø'
:c+c
:'vV'
:'iI')[p=n,c<'a'|0],
p=0,
v=c=>parseInt(c,36)|0
).join``
```
**Test**
```
F=
s=>[...s].map((c,i)=>((n=v(c))-19?n==31&p>9?'uU':n!=30|p>9?c=='s'&s[i-1]!=c&v(s[i+1])>9?'≈ø':c+c:'vV':'iI')[p=n,c<'a'|0],p=0,v=c=>parseInt(c,36)|0).join``
out=(a,b,c)=>O.textContent+=a+'\n'+b+'\n'+c+'\n\n'
ti='Christian Reader, I have for thy use collected this small Concordance, with no small labour. For being to comprise much in little roome, I was to make choyse of the most principall and usefull places, and to rank them under such words as I thought most essentiall and materiall in the sentence, because the scant roome allotted unto me, would not permit that I should expresse them under every word in the verse, as it is the manner in large Concordances.'
to='Chri≈øtian Reader, I haue for thy v≈øe collected this ≈ømall Concordance, with no ≈ømall labour. For being to compri≈øe much in little roome, I was to make choy≈øe of the mo≈øt principall and v≈øefull places, and to rank them vnder ≈øuch words as I thought mo≈øt e≈øsentiall and materiall in the ≈øentence, becau≈øe the ≈øcant roome allotted vnto me, would not permit that I ≈øhould expre≈øse them vnder euery word in the ver≈øe, as it is the manner in large Concordances.'
r=F(ti)
out(to==r?'OK':'KO',ti,r)
test=`Joy Ioy
joy ioy
Universe Vniuer≈øe
universe vniuer≈øe
Success Succe≈øs
successfull ≈øucce≈øsfull
Supervise Superui≈øe
supervise ≈øuperui≈øe
Super-vise Super-vi≈øe
I've I've
majors maiors
UNIVERSE VNIUERSE
0universe 0vniuer≈øe
0verify 0verify
I0ve I0ve
_UU_ _VU_
_VV_ _VU_
ss_ ≈øs_`
.split('\n').map(t=>{
var [i,o]=t.split(/\s+/),r=F(i)
out(o==r?'OK':'KO',i,r)
})
```
```
#O {width:90%; overflow:auto; white-space: pre-wrap}
```
```
<pre id=O></pre>
```
[Answer]
## JavaScript (ES6), 111 bytes
```
s=>s.replace(/[a-z]+/gi,w=>w.replace(/j|J|^u|^U|\Bv|\BV|ss|s(?!$)/g,c=>"iIvVuU≈ø"["jJuUvVs".search(c)]||"≈øs"))
```
Explanation: Because JavaScript regexp has no lookbehind, I instead break up the string into words, which then allows me to use `^` and `\B` as negative and positive letter lookbehinds. `ss` is dealt with by matching separately, with the slightly awkward replacement expression which takes fewer bytes than either replacing only the first character of `c` or adding an extra `s` to both strings and using the matching substring.
[Answer]
## CJam (89 88 bytes)
```
{32|_'`>\'{<*}:A;SqS++3ew{_1="jJuUvVs"#[-4_{_0=A!3*}_{_0=A3*}_{_)A\0='s=>268*}W]=~f^1=}%
```
[Online demo](http://cjam.aditsu.net/#code=%7B32%7C_'%60%3E%5C'%7B%3C*%7D%3AA%3BSqS%2B%2B3ew%7B_1%3D%22jJuUvVs%22%23%5B-4_%7B_0%3DA!3*%7D_%7B_0%3DA3*%7D_%7B_)A%5C0%3D's%3D%3E268*%7DW%5D%3D~f%5E1%3D%7D%25&input=Joy%0Ajoy%0AUniverse%0Auniverse%0ASuccess%0Asuccessful%0ASupervise%0Asupervise%0ASuper-vise%0AI've%0Amajors%0AUNIVERSE%0A0universe%0A0verify%0AI0ve%0A_U%0A_V%0Ass_)
I never understood why CJam doesn't have regexes, but since it doesn't here's a solution which doesn't use them.
[Answer]
# Ruby, 85 + 1 = 86 bytes
Run with `ruby -p` (+1 byte for `p` flag). Takes input on stdin.
```
gsub(/j|(?<=^|[^a-z])u|(?<=[a-z])v|(?<=^|[^s])s(?=[a-z])/i){$&.tr"jJsUuVv","iIfVvUu"}
```
Run the tests on ideone (wrapped in a lambda there because you can't give flags to ideone): <http://ideone.com/AaZ8ya>
] |
[Question]
[
## Challenge
Given the roots of a polynomial separated by spaces as input, output the expanded form of the polynomial.
For example, the input
```
1 2
```
represents this equation:
```
(x-1)(x-2)
```
And should output:
```
x^2-3x+2
```
The exact format of output is not important, it can be:
```
1x^2+-3x^1+2x^0
```
or:
```
0 0 0
1x^3+0x^2+0x^1+0
```
or:
```
3 14 15 92
1x^4+-124x^3+3241x^2+-27954x^1+57960
```
## Scoring/Rules
* `eval` and likes are disallowed.
* You may use any version of Python *or any other language*.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 29 bytes
```
ljU"1@_hX+]tn:Pqv'+%gx^%g'wYD
```
Input is an array with the roots.
*EDITS:*
* *(May 20, 2016): the `X+` function has been removed, as `Y+` includes its functionality. So in the above code replace `X+` by `Y+`.*
* *(September 29, 2017): due to changes in the `YD` function, `w` in the above code should be removed.*
*The following link includes those changes.*
[**Try it online!**](https://tio.run/##y00syfn/PycrVMnQIT4jUju2JM8qoLBMXVs1vSJONV090uX/f2MFQxMFQ1MFSyMA)
### Explanation
This applies repeated convolution with terms of the form `[1, -r]` where `r` is a root.
```
l % push number 1
jU % take input string. Convert to number array
" % for each root r
1 % push number 1
@_ % push -r
h % concatenate horizontally
X+ % convolve. This gradually builds array of coefficients
] % end for each
tn:Pq % produce array [n-1,n-2,...,0], where n is the number of roots
v % concatenate vertically with array of coefficients
'+%gx^%g' % format string, sprintf-style
w % swap
YD % sprintf. Implicitly display
```
[Answer]
# Jelly, 15 bytes
```
Æṛ‘Ė’Uj€“x^”j”+
```
This uses `Æṛ` to construct the coefficients of a monic polynomial with given roots. [Try it online!](http://jelly.tryitonline.net/#code=w4bhuZvigJjEluKAmVVq4oKs4oCceF7igJ1q4oCdKw&input=&args=MywgMTQsIDE1LCA5Mg)
### How it works
```
Æṛ‘Ė’Uj€“x^”j”+ Main link. Argument: A (list of roots)
Æṛ Yield the coefficients of a monic polynomial with roots A.
‘ Increment each root by 1.
Ė Enumerate the roots, yielding
[[1, coeff. of x^0 + 1], ... [n + 1, coeff. of x^n + 1]].
’ Decrement all involved integers, yielding
[[0, coeff. of x^0], ... [n, coeff. of x^n]].
U Upend to yield [[coeff. of x^0, 0], ... [coeff. of x^n, n]].
j€“x^” Join each pair, separating by 'x^'.
j”+ Join the pairs, separating by '+'.
```
## Alternate version, 24 bytes
```
1WW;ð0;_×µ/‘Ė’Uj€“x^”j”+
```
This uses no polynomial-related built-ins. [Try it online!](http://jelly.tryitonline.net/#code=MVdXO8OwMDtfw5fCtS_igJjEluKAmVVq4oKs4oCceF7igJ1q4oCdKw&input=&args=MywgMTQsIDE1LCA5Mg)
### How it works
```
1WW;ð0;_×µ/‘Ė’Uj€“x^”j”+ Main link. Argument: A (list of roots)
1WW Yield [[1]].
; Concatenate with A.
ð µ/ Reduce [[1]] + A by the following, dyadic chain:
0; Prepend a zero to the left argument (initially [1]).
This multiplies the left argument by "x".
× Take the product of both, unaltered arguments.
This multiplies the left argument by "r", where r is
the root specified in the right argument.
_ Subtract.
This computes the left argument multiplied by "x-r".
‘Ė’Uj€“x^”j”+ As before.
```
[Answer]
# Ruby, 155 bytes
Anonymous function, input is an array of the roots.
Prints from lowest power first, so calling `f[[1,2]]` (assuming you assigned the function to `f`) returns the string `"2x^0+-3x^1+1x^2"`.
```
->x{j=-1
x.map{|r|[-r,1]}.reduce{|a,b|q=a.map{|c|b=[0]+b
b.map{|e|e*c}[1..-1]}
q.pop.zip(*q).map{|e|(e-[p]).reduce(:+)}}.map{|e|"#{e}x^#{j+=1}"}.join('+')}
```
[Answer]
## Python 3, 453 bytes (Spaces removed and more) -> 392 bytes
```
import functools
import operator
print([('+'.join(["x^"+str(len(R))]+[str(q)+"x^"+str(r)if r>0else"{0:g}".format(q)for r,q in enumerate([sum(functools.reduce(operator.mul,(-int(R[n])for n,m in enumerate(j)if int(m)==1),1)for j in[(len(R)-len(bin(i)[2:]))*'0'+bin(i)[2:]for i in range(1,2**len(R))]if sum(1-int(k) for k in j)==p)for p in range(len(R))]) ][::-1]))for R in[input().split()]][0])
```
Check [This link](https://stackoverflow.com/a/595409/1683017), Will help understand the reason behind those two imports.
[Answer]
# Haskell, 99
```
l%r=zipWith(-)(0:l)$map(r*)l++[0]
f e='0':do(c,i)<-zip(foldl(%)[1]e)[0..];'+':show c++"x^"++show i
```
prints the lower powers first, with an additional `0+` at the start. for example:
```
>f [1,1]
"0+1x^0+-2x^1+1x^2"
```
The function computes the coefficients by progressively adding more roots, like convolutions, but without the builtin.
Then we use the list monad to implicitly `concat` all of the different monomials.
[Answer]
## Sage, 38 bytes
```
lambda N:prod(x-t for t in N).expand()
```
[Try it online](http://sagecell.sagemath.org/?z=eJxLs81JzE1KSVTwsyooyk_RqNAtUUjLL1IoUcjMU_DT1EutKEjMS9HQ5OXi5SooyswDympEG-oYxWoi8Q10gBBFxFjH0ETH0FTHEqgQAOOyHB8=&lang=sage)
This defines an unnamed lambda that takes an iterable of roots as input and computes the product `(x-x_n) for x_n in roots`, then expands it.
[Answer]
# Mathematica, 26 bytes
```
Expand@Product[x-k,{k,#}]&
```
Mathematica has powerful polynomial builtins.
## Usage
```
f = Expand@Product[x-k,{k,#}]&
f@{3, 14, 15, 92}
x^4 - 124 x^3 + 3241 x^2 - 27954 x + 57960
```
[Answer]
## JavaScript (ES6), 96 bytes
```
a=>a.map(x=>r.map((n,i)=>(r[i]-=x*a,a=n),++j,r.push(a=0)),r=[j=1])&&r.map(n=>n+`x^`+--j).join`+`
```
] |
[Question]
[
This is my first question, so I hope it goes well.
## Background:
It's not the rivers that you might be thinking about. The question revolves around the concept of digital rivers. A digital river is a sequence of numbers where the number following `n` is `n` plus the sum of its digits.
**Explanation:**
12345 is followed by 12360 since 1+2+3+4+5=15 and so 12345 + 15 gives
12360. similarly 145 is followed by 155. If the first number of a digital river is `M` we will call it river `M`.
For e.g: River 480 is the sequence beginning {480,492,507,519....}, and river 483 is the sequence beginning {483,498,519,....}. Normal streams and rivers can meet, and the same is true for digital rivers. This happens when two digital rivers share some of the same values.
**Example:**
River 480 meets river 483 at 519. River 480 meets river 507 at 507 and never meets river 481. Every digital river will eventually meet river 1, river 3 or river 9.
Write a program that can determine for a given integer `n` the value where river `n` first meets one of these three rivers.
## Input
The input may contain multiple test cases. Each test case occupies a separate line and contains an integer `n` (`1 <= n <= 16384`). A test case with value of `0` for `n` terminates the input and this test case must not be processed.
## Output
For each test case in the input first output the test case number (starting from 1) as shown in the sample output. Then on a separate line output the line "first meets river x at y". Here y is the lowest value where river `n` first meets river `x` (x = 1 or 3 or 9). If river `n` meets river `x` at `y` for more than one value of `x`, output the lowest value. Print a blank line between two consecutive test cases.
## Test case
**Input:**
```
86
12345
0
```
**Output:**
```
Case #1
first meets river 1 at 101
Case #2
first meets river 3 at 12423
```
## Scoring:
The fastest algorithm wins. In case of tie. The one with shorter code will win.
Thanks to **mbomb007** for pointing out my error.
p.s: I want to have the fastest solution rather than the smallest one.
I also have a solution of mine which is slow. For that look [here](https://codereview.stackexchange.com/questions/91497/merging-digital-river).
## Note:
I will be using [this](http://rextester.com/) for code testing. And performance checking.
[Answer]
# C, 320 ~~294~~ bytes
Compile with -std=c99
```
#include<stdio.h>
int s(int i){for(int j=i;j;j/=10)i+=j%10;return i;}int main(){int c=0,i;while(scanf("%d",&i)){c++;if(!i)continue;int j,o[]={1,3,9},p[]={1,3,9};Q:for(j=0;j<3;j++){if(o[j]==i)goto D;else if(o[j]<i){o[j]=s(o[j]);goto Q;}}i=s(i);goto Q;D:printf("Case #%d\n\nfirst meets river %d at %d\n\n",c,p[j],o[j]);}}
```
Ungolfed:
```
#include <stdio.h>
int s(int i)
{
for(int j = i; j; j /= 10)
i += j % 10;
return i;
}
int main()
{
int c = 0, i;
while(scanf("%d", &i))
{
c++;
if(!i)
continue;
int j,o[]={1,3,9},p[]={1,3,9};
Q: for(j = 0; j < 3; j++)
{
if(o[j] == i)
goto D;
else if(o[j] < i)
{
o[j] = s(o[j]);
goto Q;
}
}
i = s(i);
goto Q;
D: printf("Case #%d\n\nfirst meets river %d at %d\n\n", c, p[j], o[j]);
}
}
```
[Try it out!](http://rextester.com/PLTPJ23114)
Essentially, the "target" rivers are increased until they're greater than the river we're testing against, and afterwards the test river is increased. This is repeated until the test river is equal to some other river.
~~I'm not reading parameters from the command line in this program, and I'm not sure if you're supposed to.~~ Now you can pass parameters to STDIN. You can terminate by passing a non-numeric input.
Also darn, beaten by half an hour.
[Answer]
# JavaScript (ES6)
This is a quite fast answer using a quite slow language. Really, executing time should not be a problem using any language with hash tables.
All my tests under 100 ms.
Anonymous method with the list of test case as input parameter.
```
F=cases=>{
var t0 = +new Date
var result = 0
var spots = []
var top=[,1,3,,9]
var rivers=[,1,3,1,9,1,3,1]
cases.forEach((n,i)=>{
var found = result = spots[n]
for (;!found;)
{
found = top.some((v,i)=>{
for(;spots[v] |= i, v<n; top[i] = v)
[...v+''].forEach(d=>v-=-d)
return result = v-n ? 0 : i;
}) || (
[...n+''].forEach(d=>n-=-d),
result = spots[n]
)
}
console.log(`Case #${i+1}\nfirst meets river ${rivers[result]} at ${n}`)
})
return 'Time (ms) ' + (new Date-t0)
}
console.log(F([86, 12345, 123, 456, 789, 16384]))
```
[Answer]
# Java 7, ~~519~~ 505 bytes
```
import java.util.*;String c(int i){if(i<=0)return"";ArrayList<Long>r=f(1),s=f(3),t=f(9),x=f(i);String z="first meets river ";for(int j=0;j<r.size();j++){long u=r.get(j),v=s.get(j),w=t.get(j);if(x.contains(u))return z+1+" at "+u;if(x.contains(v))return z+3+" at "+v;if(x.contains(w))return z+9+" at "+w;}return"";}ArrayList f(long i){ArrayList<Long>l=new ArrayList();l.add(i);for(long j=0,x;j<9e4;j++){x=l.get(l.size()-1);for(char c:(x+"").toCharArray())x+=new Long(c+"");l.add(x);if(x>16383)return l;}return l;}
```
Yes, it's long, ugly and can without a doubt be completely changed to code-golf it more.. I'm both distracted and tired, so perhaps I should just delete it again..
It was a pretty hard challenge to be honest.. But at least you have your first answer.. ;) (Which might even be longer than your original ungolfed C++ program.. xD)
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/qLPzHw)
```
import java.util.*;
class M{
static String c(int i){
if(i <= 0){
return "";
}
ArrayList<Long> r = f(1),
s = f(3),
t = f(9),
x = f(i);
String z = "first meets river ",
y = " at ";
for(int j = 0; j < r.size(); j++){
long u = r.get(j),
v = s.get(j),
w = t.get(j);
if(x.contains(u)){
return z+1+y+u;
}
if(x.contains(v)){
return z+3+y+v;
}
if(x.contains(w)){
return z+9+y+w;
}
}
return "";
}
static ArrayList f(long i){
ArrayList<Long> l = new ArrayList();
l.add(i);
for(long j = 0, x; j < 9e4; j++){
x = l.get(l.size() - 1);
for(char c : (x + "").toCharArray()){
x += new Long(c+"");
}
l.add(x);
if(x > 16383){
return l;
}
}
return l;
}
public static void main(String[] a){
System.out.println(c(86));
System.out.println(c(12345));
System.out.println(c(0));
}
}
```
**Output:**
```
first meets river 1 at 101
first meets river 3 at 12423
(empty output)
```
[Answer]
# Scala, 774 bytes
Fiddle: <http://scalafiddle.net/console/4ec96ef90786e0f2d9f7b61b5ab0209b>
I don't feel like golfing it. It finds a solution to the posed problem within 50ms
Usage may not be exactly what you want:
`scala river.scala`
Now you can continuously input numbers followed by an enter. And terminate the program with 0. The result will be printed as soon as you hit enter.
```
io.Source.stdin.getLines.map(_.toInt)
.takeWhile(_ != 0)
.map(stream(_).takeWhile(_ < 16383))
.zipWithIndex
.map { cur =>
Seq(1, 3, 9).map { i =>
val s = stream(i).takeWhile(_ < 16383)
(cur._2+1, i, s.intersect(cur._1).headOption)
}
}.foreach { opts =>
val options = opts.filterNot(_._3.isEmpty)
if(options.isEmpty) {
println("No result")
} else {
val opt = options(0)
println(s"Case #${opt._1}\n\nfirst meets ${opt._2} at ${opt._3.get}\n\n")
}
}
def stream(i:Int): Stream[Int] = {
def sub: Int => Stream[Int] = {
i => i #:: sub(a(i))
}
sub(i)
}
def a(i:Int): Int = i + i.toString.map{_.asDigit}.sum
```
[Answer]
## C, 228 ~~283~~ ~~300~~ bytes
This is a mod of Yakov's code to take advantage of the river patterns. This makes it ~3x faster. Also, unsigned integers avoid the `cltod` penalty on 64-bit machines, so it's a few bytes longer but fractionally faster.
```
#define sum(z) for(y=z;y;y/=10)z+=y%10;
n,x;main(){unsigned i,j,y;while(scanf("%d",&i)){if(i){j=x=1+!(i%3)*2+!(i%9)*6;do{while(j<i)sum(j)}while(j^i&&({sum(i)i;}));printf("Case #%u\n\nfirst meets river %u at %u\n\n",++n,x,i);}}}
```
Ungolfed:
```
#define sum(z) for(y=z;y;y/=10)z+=y%10;
n, x;
main() {
unsigned i, j, y;
while(scanf("%d", &i)) {
if(i){
j = x = 1 + !(i%3)*2 + !(i%9)*6;
do{
while (j < i) sum(j)
}
while(j^i&&({sum(i)i;}));
printf("Case #%u\n\nfirst meets river %u at %u\n\n", ++n, x, i);
}
}
}
```
**Explanation:**
```
j = x = 1 + !(i%3)*2 + !(i%9)*6;
```
This selects the correct river. River 1 meets every other river, so we use this as the fall-back case. If 3 is the greatest common divisor of the test river, we select river 3 (`1 + !(i%3)*2`). If 9 is the greatest common divisor of the test river, we override the previous values and select river 9.
Why does this work? River 9 goes 9, 18, 27, 36, etc. This steps by a multiple of 9 each time thus it will always be the shortest route to a sister river. River 3 will step by a multiple of 3 each time: 3, 6, 12, 15, 21, etc. While rivers that are a multiple of 9 are *also* a multiple of 3, we choose them as river 9 first, leaving only the multiples of 3. The remainder will meet river 1 first: 1, 2, 4, 8, 16, 23, 28, etc.
Once we have selected our correct river, we step the two rivers until they meet.
[Answer]
# Python 3, 144 bytes
```
r,a,b,c,i={int(input())},{1},{3},{9},1
while i:
for x in r,a,b,c:t=max(x);x|={sum(int(c)for c in str(t))+t}
if r&(a|b|c):i=print(*r&(a|b|c))
```
[Answer]
# C
Very simple, it just looks that long because I unrolled all the 3 rivers. It first generates the 3 rivers up to `RIVER_LENGTH` (which I hope is big enough), and then for each step on `N` it does a binary search on all three streams to see if it is in any of them. This works because the streams are already sorted, so we can do the contains check in `log(n)` time.
```
#include <stdio.h>
#define RIVER_LENGTH 10000
int main() {
int num_cases;
scanf("%d", &num_cases);
int cases[num_cases];
int N;
int s1[RIVER_LENGTH] = {1};
int s3[RIVER_LENGTH] = {3};
int s9[RIVER_LENGTH] = {9};
int i;
int temp;
for (i = 1; i < RIVER_LENGTH; i++) {
s1[i] = temp = s1[i-1];
while (temp) {
s1[i] += temp % 10;
temp /= 10;
}
}
for (i = 1; i < RIVER_LENGTH; i++) {
s3[i] = temp = s3[i-1];
while (temp) {
s3[i] += temp % 10;
temp /= 10;
}
}
for (i = 1; i < RIVER_LENGTH; i++) {
s9[i] = temp = s9[i-1];
while (temp) {
s9[i] += temp % 10;
temp /= 10;
}
}
int start;
int end;
int pivot;
for (i=1; i <= num_cases; i++) {
scanf("%d", &cases[i]);
}
for (i=1; i <= num_cases; i++) {
printf("Case #%d\n\n", i);
N = cases[i];
while (1) {
temp = N;
while (temp) {
N += temp % 10;
temp /= 10;
}
start = 0;
end = RIVER_LENGTH;
pivot = 1;
while (end != start && pivot != RIVER_LENGTH - 1) {
pivot = start + ((end - start) >> 1);
if (s1[pivot] == N) {
printf("first meets river 1 at %d\n\n", N);
goto case_done;
} else if (N < s1[pivot]){
end = pivot;
} else {
start = pivot+1;
}
}
start = 0;
end = RIVER_LENGTH;
pivot = 1;
while (end != start && pivot != RIVER_LENGTH - 1) {
pivot = start + ((end - start) >> 1);
if (s3[pivot] == N) {
printf("first meets river 3 at %d\n\n", N);
goto case_done;
} else if (N < s3[pivot]){
end = pivot;
} else {
start = pivot+1;
}
}
start = 0;
end = RIVER_LENGTH;
pivot = 1;
while (end != start && pivot != RIVER_LENGTH - 1) {
pivot = start + ((end - start) >> 1);
if (s9[pivot] == N) {
printf("first meets river 9 at %d\n\n", N);
goto case_done;
} else if (N < s9[pivot]){
end = pivot;
} else {
start = pivot+1;
}
}
}
case_done:;
}
}
```
It takes a number for the number of cases first, instead of using `0` to delimit the end of the inputs, because you know, C. This is just for convenience and doesn't really affect anything, so I hope its okay.
] |
[Question]
[
### Background
I have a string in Python which I want to convert to an integer. Normally, I would just use `int`:
```
>>> int("123")
123
```
Unfortunately, this method is not very robust, as it only accepts strings that match `-?[0-9]+` (after removing any leading or trailing whitespace). For example, it can't handle input with a decimal point:
```
>>> int("123.45")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123.45'
```
And it *certainly* can't handle this:
```
>>> int("123abc?!")
```
On the other hand, exactly this behavior can be had without any fuss in Perl, PHP, and even the humble QBasic:
```
INT(VAL("123abc")) ' 123
```
### Question
Here's my shortest effort at this "generalized `int`" in Python. It's 50 bytes, assuming that the original string is in `s` and the result should end up in `i`:
```
n="";i=0
for c in s:
n+=c
try:i=int(n)
except:0
```
Fairly straightforward, but the `try`/`except` bit is ugly and long. Is there any way to shorten it?
### Details
Answers need to do all of the following:
* Start with a string in `s`; end with its integer value in `i`.
* The integer is the first run of digits in the string. Everything after that is ignored, including other digits if they come after non-digits.
* Leading zeros in the input are valid.
* Any string that does not start with a valid integer has a value of `0`.
The following features are *preferred*, though not required:
* A single `-` sign immediately before the digits makes the integer negative.
* Ignores whitespace before and after the number.
* Works equally well in Python 2 or 3.
(Note: my code above meets all of these criteria.)
### Test cases
```
"0123" -> 123
"123abc" -> 123
"123.45" -> 123
"abc123" -> 0
"-123" -> -123 (or 0 if negatives not handled)
"-1-2" -> -1 (or 0 if negatives not handled)
"--1" -> 0
"" -> 0
```
[Answer]
# Python ~~2, 47~~, 46
It's not as short as using regex, but I thought it was entertainingly obscure.
```
i=int(('0%sx'%s)[:~len(s.lstrip(str(1<<68)))])
```
-1 due to KSab – `str` with some large integer works better than the repr operator since it does not put an `L` on the end.
[Answer]
# 40 bytes
```
import re;i=int("0"+re.split("\D",s)[0])
```
and you can do negatives for 8 characters more:
```
import re;i=int((re.findall("^-?\d+",s)+[0])[0])
```
] |
[Question]
[
# Challenge
Write a function that implements C `printf`-style string formatting.
# Rules
1. You **must** implement at least `%%`, `%c`, `%s`, `%d` and `%f`.
2. You **must not** use a built-in string formatting method.
3. You **must not** run external programs or connect to the Internet from your program.
4. It's up to you to decide how to handle invalid input, but your program **must not** terminate abnormally.
5. You **should** write a [variadic function](https://en.wikipedia.org/wiki/Variadic_function) if possible.
>
> The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119).
>
>
>
[Answer]
## APL (73)
```
{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺}
```
Some tests:
```
'a:%c b:%s c:%d'{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺} 65 'foo' 67
a:A b:foo c:67
printf←{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺}
'1:%s 2:%s 3:%d 4:%c 5:%c' printf 'foo' 'bar' 100 110 'z'
1:foo 2:bar 3:100 4:n 5:z
'The %s brown %c%c%c jumps over the %s dog.' printf 'quick' 102 111 'x' 'lazy'
The quick brown fox jumps over the lazy dog.
```
Explanation:
* `G←'%!',⍺`: prefix a dummy specifier to the string (for easier processing)
* `(Z←G='%')/⍳⍴G`: find the indices of all the `%` characters in the string; also store a bitmask in `Z`
* `⌷∘G¨1↓1+`: select all the characters next to the `%`s, and drop the dummy.
* `⍵,⍪`: match up each specifier with its value from the right argument.
* `{`...`}/`: run the following function on each pair:
+ `'c'0≡⍵,∊⊃⍺`: if the argument is a number and the specifier is `c`:
+ `:⎕UCS⍺`: then return the unicode value of the argument,
+ `⋄⍕⍺`: otherwise, return the string representation of the argument.
* `⊂`: enclose
* `⊂2∘↓¨Z⊂G`: split the string on the `%`s and then remove the first two characters of each substring (this is where the dummy comes in), and enclose the result of that.
* `↑`: make a matrix out of the two enclosed arrays, matching up each substring with the value that should follow it.
* `,⌿`: join each substring with its value.
* `⊃,/`: then join the resulting strings.
[Answer]
# Ruby: 102 characters
```
f=->s,*a{s.gsub(/%(.)/){$1==?%??%:a.shift.send({?c=>:chr,?s=>:to_s,?d=>:to_i,?f=>:to_f}[$1])rescue$&}}
```
Sample run:
```
irb(main):001:0> f=->s,*a{s.gsub(/%(.)/){$1==?%??%:a.shift.send({?c=>:chr,?s=>:to_s,?d=>:to_i,?f=>:to_f}[$1])rescue$&}}
=> #<Proc:0x96634ac@(irb):1 (lambda)>
irb(main):002:0> puts f["percent : %%\n char : %c or %c\n string : %s or %s or %s\ndecimal : %d or %d or %d\n float : %f or %f or %f\ninvalid : %x or %s or %d or %f", 65, 'B', 'format me', 42, Math::PI, 42, Math::PI, '2014', 42, Math::PI, '2014', 'more']
percent : %
char : A or B
string : format me or 42 or 3.141592653589793
decimal : 42 or 3 or 2014
float : 42.0 or 3.141592653589793 or 2014.0
invalid : %x or or 0 or 0.0
=> nil
```
Invalid format specifiers are kept in place. Format specifiers without argument value are replaced with the empty value of the given type.
[Answer]
# Lua 5.2, 115 bytes
```
-- Function definition, 115 chars
function f(f,...)n,t=0,{...}return(f:gsub('%%(%a)',function(s)n=n+1return(({c=s.char})[s]or tostring)(t[n])end))end
-- Usage example
print(f('Happy %cew %d %s %f',78,2014,'Year!',math.pi))
-- Output: Happy New 2014 Year! 3.1415926535898
```
[Answer]
# C++ (281 characters)
```
#include<sstream>
#include<cstdarg>
#define q(x)va_arg(v,x);break;case
std::string p(char*f,...){std::ostringstream r;va_list v;va_start(v,f);while(*f)if(*f=='%')switch(++f,*f++){case's':r<<q(char*)'d':r<<q(int)'c':r<<(char)q(int)'%':r<<'%';}else r<<*f++;va_end(v);return r.str();}
```
I hate C++, but it seemed like a good choice (I really would go with C, if not that `char*` pointer requires too much effort to be actually useful). Takes `char*` arguments, and `std::string` result, but hey, that's C++, so who cares about consistency (in language that itself isn't consistent)?
[Answer]
# [Java](http://openjdk.java.net/), ~~201~~ ~~186~~ 174 bytes
12 bytes thanks to Kevin Cruijssen
```
String f(String s,Object...a){String r="";for(char c,i=0,j=0;i<s.length();r+=c==37?(c=s.charAt(i++))<38?c:c==99?(char)(int)a[j++]:a[j++]:c==37?"":c)c=s.charAt(i++);return r;}
```
[Try it online!](https://tio.run/nexus/java-openjdk#XY/BasMwEETP9VeoAoGEhXCbQhI7wvTWHkILOZWQg6LItowjG2ndEoK/3XUTn3qaZWZn2df1x8ZqpBsVAtoq667jDrx1JSroPAT@cayNBiGEYtfZ9BLjrGg91ZXySHMrE17LJLObIBrjSqgoy3wstZSLZU61DOJv8xWojWPGNotVrtMpXK/z2wlGrQOm9nUcH9JZ7l2MU83@9TNvoPcO@WwYuztBAAWTfLf2hM4Tx/z9/qB8Gdg1ethdApizaHsQ3ZRA46gzPzdmykRB8ZvqugsiejLJCZGACCEF5ssVf06eXjj@Mso/Yr5VUInPd8ayaIiG8Rc "Java (OpenJDK 8) – TIO Nexus")
] |
[Question]
[
Create a program which takes one command-line argument, `n`, which will be an integer less than 2147483648 (2^31), and then reads a file `input.txt` and prints the lines of `input.txt` which contain any substring which is a positive (non-zero) multiple of `n`. You may choose to ignore multiples greater than 2147483647.
### Test case
If `input.txt` contains
```
1. Delaware Dec. 7, 1787
2. Pennsylvania Dec. 12, 1787 1682
3. New Jersey Dec. 18, 1787 1660
4. Georgia Jan. 2, 1788 1733
5. Connecticut Jan. 9, 1788 1634
6. Massachusetts Feb. 6, 1788 1620
7. Maryland Apr. 28, 1788 1634
8. South Carolina May 23, 1788 1670
9. New Hampshire June 21, 1788 1623
10. Virginia June 25, 1788 1607
11. New York July 26, 1788 1614
12. North Carolina Nov. 21, 1789 1660
13. Rhode Island May 29, 1790 1636
14. Vermont Mar. 4, 1791 1724
15. Kentucky June 1, 1792 1774
16. Tennessee June 1, 1796 1769
17. Ohio Mar. 1, 1803 1788
18. Louisiana Apr. 30, 1812 1699
19. Indiana Dec. 11, 1816 1733
20. Mississippi Dec. 10, 1817 1699
21. Illinois Dec. 3, 1818 1720
22. Alabama Dec. 14, 1819 1702
23. Maine Mar. 15, 1820 1624
24. Missouri Aug. 10, 1821 1735
25. Arkansas June 15, 1836 1686
26. Michigan Jan. 26, 1837 1668
27. Florida Mar. 3, 1845 1565
28. Texas Dec. 29, 1845 1682
29. Iowa Dec. 28, 1846 1788
30. Wisconsin May 29, 1848 1766
31. California Sept. 9, 1850 1769
32. Minnesota May 11, 1858 1805
33. Oregon Feb. 14, 1859 1811
34. Kansas Jan. 29, 1861 1727
35. West Virginia June 20, 1863 1727
36. Nevada Oct. 31, 1864 1849
37. Nebraska Mar. 1, 1867 1823
38. Colorado Aug. 1, 1876 1858
39. North Dakota Nov. 2, 1889 1812
40. South Dakota Nov. 2, 1889 1859
41. Montana Nov. 8, 1889 1809
42. Washington Nov. 11, 1889 1811
43. Idaho July 3, 1890 1842
44. Wyoming July 10, 1890 1834
45. Utah Jan. 4, 1896 1847
46. Oklahoma Nov. 16, 1907 1889
47. New Mexico Jan. 6, 1912 1610
48. Arizona Feb. 14, 1912 1776
49. Alaska Jan. 3, 1959 1784
50. Hawaii Aug. 21, 1959 1820
```
then `find_multiples 4` will print the entire file, and `find_multiples 40` will print
```
10. Virginia June 25, 1788 1607
17. Ohio Mar. 1, 1803 1788
21. Illinois Dec. 3, 1818 1720
32. Minnesota May 11, 1858 1805
40. South Dakota Nov. 2, 1889 1859
41. Montana Nov. 8, 1889 1809
```
[Answer]
## Perl, 67 chars
```
open F,"input.txt";print grep/(\d+)(?(?{!$^N+$^N%$ARGV[0]})(*F))/,<F>
```
Please note that the given character count is taking advantage of one of Perl's more horrific features, namely that a special variable of the form `$^X` can be written in two characters instead of three, by replacing the `^X` with a literal ctrl-*X* character.
And, of course, this solution wouldn't be possible without a couple of Perl's arguably-equally-terrifying regex extensions that allows one to embed actual code inside of a regex pattern. (But at least those features are clearly documented as being potentially scary.)
[EDITED to fix bug in argument-handling due to not reading the description carefully enough.]
[Answer]
# Mathematica
```
dates=Import["input.txt"]
f[digits_]:=FromDigits/@Flatten[Table[Partition[digits,k,1],{k,1,Length[digits]}],1]
g[oneline_]:={FromDigits[oneline[[1]]],Complement[Union[Flatten[f/@oneline]],{0}]}
h[n_,{a_,b_}]:={a,MemberQ[Mod[#,n]&/@b,0]};
w[k_]:=Column@dates[[Cases[h[k,g[#]]&/@ToExpression@(Characters /@ (StringCases[#, DigitCharacter ..] & /@ dates)),{j_,True}:>j]]]
```
`f` removes all non-digits;
`g` finds all the numbers that can be found in a single date line.
`h` checks to see whether Mod[x, n] is true for any of the numbers returned by `g`.
`w` calls the subroutines and formats the output.
**Examples**
```
n=40
w[n]
```

---
```
n=51
w[n]
```

---
```
n=71
w[n]
```

[Answer]
# Q, 94
```
-1@m(&){0|/{(x>0)&0=x mod"I"$.z.x 0}"J"$sublist[;x]'[a cross a:(!)1+(#)x]}'[m:(0:)`input.txt];
```
There's undoubtedly a more graceful way to find substrings in q.
```
$ q find_multiples.q 40 -q
10. Virginia June 25, 1788 1607
17. Ohio Mar. 1, 1803 1788
21. Illinois Dec. 3, 1818 1720
32. Minnesota May 11, 1858 1805
40. South Dakota Nov. 2, 1889 1859
41. Montana Nov. 8, 1889 1809
```
.
```
$ q find_multiples.q 51 -q
19. Indiana Dec. 11, 1816 1733
25. Arkansas June 15, 1836 1686
37. Nebraska Mar. 1, 1867 1823
```
[Answer]
# Ruby 2.0, 129 chars
With some help from @chron:
```
IO.foreach('input.txt'){$><<$_ if$_.gsub(/\d+/).any?{(0..s=$&.size).any?{|i|(1..s).any?{|j|(v=$&[i,j].to_i)%$*[0].to_i<1&&v>0}}}}
```
That long line broken up a bit:
```
IO.foreach('input.txt') {
$> << $_ if $_.gsub(/\d+/).any? {
(0..s=$&.size).any? { |i|
(1..s).any? { |j|
(v=$&[i,j].to_i) % $*[0].to_i < 1 && v>0 }}}}
```
Example:
```
$ ruby july4.rb 40
10. Virginia June 25, 1788 1607
17. Ohio Mar. 1, 1803 1788
21. Illinois Dec. 3, 1818 1720
32. Minnesota May 11, 1858 1805
40. South Dakota Nov. 2, 1889 1859
41. Montana Nov. 8, 1889 1809
$ ruby july4.rb 71
29. Iowa Dec. 28, 1846 1788
```
] |
[Question]
[
Cyclic Words
>
> Problem Statement
>
>
> We can think of a cyclic word as a word written in a circle. To
> represent a cyclic word, we choose an arbitrary starting position and
> read the characters in clockwise order. So, "picture" and "turepic"
> are representations for the same cyclic word.
>
>
> You are given a String[] words, each element of which is a
> representation of a cyclic word. Return the number of different cyclic
> words that are represented.
>
>
>
Fastest wins (Big O, where n = number of chars in a string)
[Answer]
# Python
Here's my solution. I think it might still be O(n2), but I think the average case is much better than that.
Basically it works by normalizing each string so that any rotation will have the same form. For example:
```
'amazing' -> 'mazinga'
'mazinga' -> 'mazinga'
'azingam' -> 'mazinga'
'zingama' -> 'mazinga'
'ingamaz' -> 'mazinga'
'ngamazi' -> 'mazinga'
'gamazin' -> 'mazinga'
```
The normalization is done by looking for the minimum character (by char code), and rotating the string so that character is in the last position. If that character occurs more than once, then the characters after each occurrence are used. This gives each cyclic word a canonical representation, that can be used as a key in a map.
The normalization is n2 in the worst case (where every character in the string is the same, e.g. `aaaaaa`), but most of the time there's only going to be a few occurrences, and the running time will be closer to `n`.
On my laptop (dual core Intel Atom @ 1.66GHz and 1GB of ram), running this on `/usr/share/dict/words` (234,937 words with an average length of 9.5 characters) takes about 7.6 seconds.
```
#!/usr/bin/python
import sys
def normalize(string):
# the minimum character in the string
c = min(string) # O(n) operation
indices = [] # here we will store all the indices where c occurs
i = -1 # initialize the search index
while True: # finding all indexes where c occurs is again O(n)
i = string.find(c, i+1)
if i == -1:
break
else:
indices.append(i)
if len(indices) == 1: # if it only occurs once, then we're done
i = indices[0]
return string[i:] + string[:i]
else:
i = map(lambda x:(x,x), indices)
for _ in range(len(string)): # go over the whole string O(n)
i = map(lambda x:((x[0]+1)%len(string), x[1]), i) # increment the indexes that walk along O(m)
c = min(map(lambda x: string[x[0]], i)) # get min character from current indexes O(m)
i = filter(lambda x: string[x[0]] == c, i) # keep only the indexes that have that character O(m)
# if there's only one index left after filtering, we're done
if len(i) == 1:
break
# either there are multiple identical runs, or
# we found the unique best run, in either case, we start the string from that
# index
i = i[0][0]
return string[i:] + string[:i]
def main(filename):
cyclic_words = set()
with open(filename) as words:
for word in words.readlines():
cyclic_words.add(normalize(word[:-1])) # normalize without the trailing newline
print len(cyclic_words)
if __name__ == '__main__':
if len(sys.argv) > 1:
main(sys.argv[1])
else:
main("/dev/stdin")
```
[Answer]
## Python (3) again
The method I used was to calculate a rolling hash of each word starting at each character in the string; since it's a rolling hash, it takes O(n) (where n is the word length) time to compute all the n hashes. The string is treated as a base-1114112 number, which ensures the hashes are unique. (This is similar to the Haskell solution, but more efficient since it only goes through the string twice.)
Then, for each input word, the algorithm checks its lowest hash to see if it's already in the set of hashes seen (a Python set, thus lookup is O(1) in the set's size); if it is, then the word or one of its rotations has already been seen. Otherwise, it adds that hash to the set.
The command-line argument should be the name of a file that contains one word per line (like `/usr/share/dict/words`).
```
import sys
def rollinghashes(string):
base = 1114112
curhash = 0
for c in string:
curhash = curhash * base + ord(c)
yield curhash
top = base ** len(string)
for i in range(len(string) - 1):
curhash = curhash * base % top + ord(string[i])
yield curhash
def cycles(words, keepuniques=False):
hashes = set()
uniques = set()
n = 0
for word in words:
h = min(rollinghashes(word))
if h in hashes:
continue
else:
n += 1
if keepuniques:
uniques.add(word)
hashes.add(h)
return n, uniques
if __name__ == "__main__":
with open(sys.argv[1]) as words_file:
print(cycles(line.strip() for line in words_file)[0])
```
[Answer]
## Haskell
Not sure about the efficiency of this, most likely rather bad.
The idea is to first create all possible rotations of all the words,
count the values that uniquely represent the strings and select the
minimum. That way we get a number that is unique to a cyclic group.
We can group by this number and check the number of these groups.
If n is the number of words in the list and m is the length of a word
then calculating the 'cyclic group number' for all the words is `O(n*m)`,
sorting `O(n log n)` and grouping `O(n)`.
```
import Data.List
import Data.Char
import Data.Ord
import Data.Function
groupUnsortedOn f = groupBy ((==) `on` f) . sortBy(compare `on` f)
allCycles w = init $ zipWith (++) (tails w)(inits w)
wordval = foldl (\a b -> a*256 + (fromIntegral $ ord b)) 0
uniqcycle = minimumBy (comparing wordval) . allCycles
cyclicGroupCount = length . groupUnsortedOn uniqcycle
```
[Answer]
# Mathematica
Decided to start again, now that I understand the rules of the game (I think).
A 10000 word dictionary of unique randomly composed "words" (lower case only) of length 3. In similar fashion other dictionaries were created consisting of strings of length 4, 5, 6, 7, and 8.
```
ClearAll[dictionary]
dictionary[chars_,nWords_]:=DeleteDuplicates[Table[FromCharacterCode@RandomInteger[{97,122},
chars],{nWords}]];
n=16000;
d3=Take[dictionary[3,n],10^4];
d4=Take[dictionary[4,n],10^4];
d5=Take[dictionary[5,n],10^4];
d6=Take[dictionary[6,n],10^4];
d7=Take[dictionary[7,n],10^4];
d8=Take[dictionary[8,n],10^4];
```
`g`takes the current version of dictionary to check. The top word is joined with cyclic variants (if any exist). The word and its matches are appended to the output list, `out`, of processed words. The output words are removed from the dictionary.
```
g[{wds_,out_}] :=
If[wds=={},{wds,out},
Module[{s=wds[[1]],t,c},
t=Table[StringRotateLeft[s, k], {k, StringLength[s]}];
c=Intersection[wds,t];
{Complement[wds,t],Append[out,c]}]]
```
`f` runs through all words dictionary.
```
f[dict_]:=FixedPoint[g,{dict,{}}][[2]]
```
---
**Example 1**: actual words
```
r = f[{"teaks", "words", "spot", "pots", "sword", "steak", "hand"}]
Length[r]
```
>
> {{"steak", "teaks"}, {"hand"}, {"pots", "spot"}, {"sword", "words"}}
>
> 4
>
>
>
---
**Example 2**: Artificial words. Dictionary of strings of length 3. First, timing. Then the number of cycle words.
```
f[d3]//AbsoluteTiming
Length[%[[2]]]
```

>
> 5402
>
>
>
---
**Timings as a function of word length**. 10000 words in each dictionary.

I don't particularly know how to interpret the findings in terms of O. In simple terms, the timing roughly doubles from the three character dictionary to the four character dictionary.
The timing increases almost negligibly from 4 through 8 characters.
[Answer]
This can be done in O(n) avoiding quadratic time. The idea is to construct the full circle traversing the base string twice. So we construct "amazingamazin" as the full circle string to check all cyclic strings corresponding to "amazing".
Below is the Java solution:
```
public static void main(String[] args){
//args[0] is the base string and following strings are assumed to be
//cyclic strings to check
int arrLen = args.length;
int cyclicWordCount = 0;
if(arrLen<1){
System.out.println("Invalid usage. Supply argument strings...");
return;
}else if(arrLen==1){
System.out.println("Cyclic word count=0");
return;
}//if
String baseString = args[0];
StringBuilder sb = new StringBuilder();
// Traverse base string twice appending characters
// Eg: construct 'amazingamazin' from 'amazing'
for(int i=0;i<2*baseString.length()-1;i++)
sb.append(args[0].charAt(i%baseString.length()));
// All cyclic strings are now in the 'full circle' string
String fullCircle = sb.toString();
System.out.println("Constructed string= "+fullCircle);
for(int i=1;i<arrLen;i++)
//Do a length check in addition to contains
if(baseString.length()==args[i].length()&&fullCircle.contains(args[i])){
System.out.println("Found cyclic word: "+args[i]);
cyclicWordCount++;
}
System.out.println("Cyclic word count= "+cyclicWordCount);
}//main
```
[Answer]
I don't know if this is very efficient, but this is my first crack.
```
private static int countCyclicWords(String[] input) {
HashSet<String> hashSet = new HashSet<String>();
String permutation;
int count = 0;
for (String s : input) {
if (hashSet.contains(s)) {
continue;
} else {
count++;
for (int i = 0; i < s.length(); i++) {
permutation = s.substring(1) + s.substring(0, 1);
s = permutation;
hashSet.add(s);
}
}
}
return count;
}
```
[Answer]
## Perl
not sure i understand the problem, but this matches the example @dude posted in the comments at least. please correct my surely incorrect analysis.
for each word W in the given N words of the string list, you have to step through all characters of W in the worst case. i have to assume the hash operations are done in constant time.
```
use strict;
use warnings;
my @words = ( "teaks", "words", "spot", "pots", "sword", "steak", "hand" );
sub count
{
my %h = ();
foreach my $w (@_)
{
my $n = length($w);
# concatenate the word with itself. then all substrings the
# same length as word are rotations of word.
my $s = $w . $w;
# examine each rotation of word. add word to the hash if
# no rotation already exists in the hash
$h{$w} = undef unless
grep { exists $h{substr $s, $_, $n} } 0 .. $n - 1;
}
return keys %h;
}
print scalar count(@words), $/;
```
[Answer]
# [Rust](https://www.rust-lang.org/), brute force
[run it on Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8ef21671e351557adcb2a9796764db8a)
```
use std::collections::HashSet;
use std::time::Instant;
fn count_cyclic_words(input: &[&str]) -> usize {
let mut hash_set = HashSet::new();
let mut count = 0;
for &s in input.iter() {
if hash_set.contains(s) {
continue;
} else {
count += 1;
let mut permutation = String::from(s);
for _ in 0..s.len() {
permutation = format!("{}{}", &permutation[1..], &permutation[0..1]);
hash_set.insert(permutation.clone());
}
}
}
count
}
fn main() {
let test_cases = vec![
vec!["abc", "cab", "bca"],
vec!["aaa", "aaa", "aaa"],
vec!["a", "b", "c"],
];
for (i, input) in test_cases.iter().enumerate() {
let start = Instant::now();
let count = count_cyclic_words(input);
let duration = start.elapsed();
println!("Test case {}: count = {}", i + 1, count);
println!("Time elapsed: {:?}", duration);
}
}
```
] |
[Question]
[
[Othello/Reversi](http://en.wikipedia.org/wiki/Reversi) is a board game in which players take turn placing pieces of a color (dark or light) on the 8x8 board. The possible moves are positions where there are one or more pieces of the opponent's color in a straight (horizontal, vertical, or diagonal) line between that position and a piece of the player's color.
For example, on this board, the numbers on the left mark the row, the letters on the bottom mark the column, the empty spaces are marked `.`, the dark pieces are marked `D`, the light pieces are marked `L`, and the possible moves for dark are marked `*`:
```
1........
2........
3...D....
4...DD...
5.*LLLD..
6.****L..
7.....**.
8........
abcdefgh
```
Your task is to take a board as input and output the positions of the possible moves dark can make.
# Rules
* Input and output can be in any convenient format. Possible input formats include as a string separated by newlines, as a matrix, and as a flattened list of numbers. Output positions can be in a format like `b5`, a list of two numbers, or a complex number. You may also choose to modify the input.
* The output may be in any order but cannot contain duplicates.
* You may use different values to represent `D`, `L`, and `.`, as long as they are distinct.
* You may assume that at least one move exists.
* Standard loopholes apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins.
# Test cases
```
........
........
...D....
...DD...
..LLLD..
.....L..
........
........
```
b5 b6 c6 d6 e6 f7 g7
[[1, 4], [1, 5], [2, 5], [3, 5], [4, 5], [5, 6], [6, 6]]
---
```
........
........
........
...LD...
...DL...
........
........
........
```
c4 d3 e6 f5
[[2, 3], [3, 2], [4, 5], [5, 4]]
---
```
.....L..
...LL...
.DDDD.L.
.LDDDLL.
.LLDLLL.
.L.LD...
..LLL...
.L...L..
```
a4 a5 a6 a7 b7 c1 c6 c8 d1 d8 e1 e8 f6 g6 h3 h4 h5 h6
[[0, 3], [0, 4], [0, 5], [0, 6], [1, 6], [2, 0], [2, 5], [2, 7], [3, 0], [3, 7], [4, 0], [4, 7], [5, 5], [6, 5], [7, 2], [7, 3], [7, 4], [7, 5]]
[Answer]
# [Python 3](https://docs.python.org/3/), ~~245~~ ~~238~~ ~~212~~ ~~197~~ ~~191~~ 184 bytes
```
def f(T,*R):
for m in range(576):
for q in range(1,8*T[m//72][m%8]):
w,z=m//72+m%9//3*q-q,m%8+m%9%3*q-q;d=T[w][z];b=(w>=0<=z)*(q>1<2-d)
if-~d+b:R+=((z,w),)*b;break
return{*R}
```
[Try it online!](https://tio.run/##fVJNj4IwEL33VzQmhoLFz93VVfHEsSfjDYlBKS5RCkIJrhv3r7NtQYluducyb15n3jQzk3zyj5iNytKnAQzQChtLfQpgEKcwgiGDqcf2FL2O3ySr6FNDD/DEWDlRrzceuk7UnrgqCRb4YimyE7Xfe72RcTJPWDzLsK2imW@tnMJ1Lu5sa6FiYfXn1kU30GkxmA9NX5cqYWB@@53tdNmxELrgQse6sZ1tU@odAEwpz1P2ZSyv5c7LaAYt@CWLYKvVWoNubQ/AvgO7AoQQ@5ZDnpKVCa0pHGPwj@gdEPumTv7MaURfMGg0696kKrSFCQoIRdsmChDhFbh3IXUyqcqV5mCCwRVEXpKEbC/nodmaYDHUusL3hSfCm4MrkFsMWZLzDadnjiE9J3THqb@Jcy5YuV811G7IaZQhuVQeHyiTU3acuoOjKFedhILqLOKiYgSQcdOlmyXHkCNtzTTdBdDb8dw73hpa4vKqDmLzSRoyjrI4FT9CD3k6hkfKfnFP39fLHw "Python 3 – Try It Online")
A function that receives a list of strings and outputs a set containing sized-2 tuples.
* *-21* bytes by removing `i`, `j`, `a` and `b`, and replacing the `if T[i][j]=='D':` with a multiplication inside the `range`
* *-7 bytes* thank to [@Dingus](https://codegolf.stackexchange.com/questions/269682/possible-moves-in-othello-reversi/269688?noredirect=1#comment585319_269688) by using two if-s instead of if-elif-else
* *-26 bytes* by removing the `f`lag variable and compacting loops `m` and `n` into one
* *-15 bytes* thank to [@Yousername](https://codegolf.stackexchange.com/questions/269682/possible-moves-in-othello-reversi#comment585317_269688) (OP) by accepting a matrix of integers instead of a matrix of strings, where the empty slot is \$0\$, a dark piece is \$1\$, and a light piece is \$-1\$
* *-6 bytes* by inlining `i` and `j` and simplifying `b`
* *-5 bytes* thank to [@Dingus](https://codegolf.stackexchange.com/questions/269682/possible-moves-in-othello-reversi/269688?noredirect=1#comment585351_269688) by inlining `n`!
* *-2 bytes* by replacing a default argument list with an `*args` tuple
# [Python 3](https://docs.python.org/3/), ~~270~~ 266 bytes
Original version.
```
def f(T):
R=[]
for m in range(64):
i=m//8;j=m%8
if T[i][j]=='D':
for n in range(9):
a=n//3;b=n%3;f=0
for q in range(1,8):
w,z=i+q*a-q,j+q*b-q;d=T[w][z]
if'L'==d:f=1
elif(d=='.')*f*(w>=0<=z):R+=[(z,w)];break
else:break
return{*R}
```
[Try it online!](https://tio.run/##fZJRT8IwFIXf@ytuSMw6rCDBKG5en/bYJ8LbWMxgrRahjK0ExfjbsesGCxi9Lz29@865y@7yT/O21sPDIRMSJJ34AYExxgkBuS5gBUpDkepXQe/vqkegcNXvj8IFrq5G1VXCJFZJvEgQvcirCGfUrfHR@QBS1P3@MJyhvhqGEm9ds2I3LTtgo4aGHdujut5005sNW9hzdrMJM5zEuyTeJzWipMc9xCyQOKg7Yqkkzeyr9Dy/K7t094y3T7j3g/E1xnTPdn4SzgqRvh/xUgTNvRBmW@iv7vj7ME9LUQLCl6M6nc6U9Jo6E9FJRLXgnEdHhl/ArmxWAA@M/BN6Ejw6pvM/mTb0jpE2s5nNa2Nky7aITYwi7gS3pxOnKbyBeW13mYMRI9@kWpHS@da8GPFhGIiPXMyNyF7WW2O71fLcB@spI1YlrfaXzs02XR4BtP9VG9Ar86Uy1Jtqz/cJ5IXShpbrwibSM5/PYCn0r97FeP/wAw "Python 3 – Try It Online")
* *-4 bytes* by using a set-literal instead of a set-function
---
**How does it work?**
The output variable here is `R`. Since the board is 8x8, we can iterate over it as a continuous range (`for m in range(64):`), storing the current row and column on `i` and `j`, respectively.
Every "D" piece has 8 possible directions to be validated: north, south, east, west, northwest, northeast, southwest and southeast. We also assume a "D" piece will be validated against itself: this case will be basically a no-op, and it's only considered here so that we can directly do `for n in range(9):` instead of iterating over a `range(8)` and making additional checks.
We then split `n` into two variables `a` and `b`, each containing values from 0 to 2. Basically, the following transformation is applied:
```
n = 0 --> a = 0; b = 0 --(-1)-> a = -1; b = -1 (southwest)
n = 1 --> a = 0; b = 1 --(-1)-> a = -1; b = 0 (south)
n = 2 --> a = 0; b = 2 --(-1)-> a = -1; b = +1 (southeast)
n = 3 --> a = 1; b = 0 --(-1)-> a = 0; b = -1 (west)
n = 4 --> a = 1; b = 1 --(-1)-> a = 0; b = 0 (no-op)
n = 5 --> a = 1; b = 2 --(-1)-> a = 0; b = +1 (east)
n = 6 --> a = 2; b = 0 --(-1)-> a = +1; b = -1 (northwest)
n = 7 --> a = 2; b = 1 --(-1)-> a = +1; b = 0 (north)
n = 8 --> a = 2; b = 2 --(-1)-> a = +1; b = +1 (northeast)
```
Since a board has a limit of 8 pieces in each direction (8x8), we iterate over `range(1, 8)`. The variable `q` here describes how far we are going into the direction described by `n`: if `n` is north and `q` is 1, we are looking at the first slot on the top of `(i, j)`; if `n` is east and `q` is 2, we are looking at the second slot on the right of `(i, j)`. That slot has coordinates `(w, z)`, with value `d`.
If that slot contains a "L" piece, we can proceed with the validation; set `f`lag to true. That flag implements the requirement
>
> The possible moves are positions where there are one or more pieces of the opponent's color in a straight (horizontal, vertical, or diagonal) line **between that position and a piece of the player's color**.
>
>
>
We can only add a possible move to `R` if the `f`lag has been set; that is, if there is an "L" piece between a "D" piece and an empty slot.
If the next slot on that direction is an empty spot, a "L" piece has already been visited (i.e. if `f` is true) and if `(w, z)` is a valid spot on the board, then add it to `R` and stop validating.
Continue for all "D" pieces, for all possible directions, for all possible offsets.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
E⁸SF⁸F⁸«Jικ¿⊙E⁸⁺⪫KD⁸✳λω.D⁼⌕⁺..×⁶L…λ⌕λD¹*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RU_BSgMxED13vyLkNJE04EUWPElXxRJhwd7Ew5pmbWiarJusUsQv8dKDor9U_Bkn2RYHkvfy5s0j8_GjVk2vfGN3u68httNy_1v3xkW4bTooOblx3RDvIkpPwBg7L1rfEygZOeJbMZkPm27hwXCyRsPEtAQu3PaYUNshwNwbB7XW68r0WkXjXWr9PyxjnLzioaKiiV8-D40NcGXcEnICFYJysjAbHeAMfTLbZltl9WzlO7CcZDMiTRHYPMWbjNvQE4pfe_8MjyocFv2-p9MXSx_21yKVFKJIgIikwkKpEBKJzEQiZoJa9gh5MMtxfIz9Aw) (Only using ATO here because the version of Charcoal on TIO erroneously extends the canvas when you use `PeekDirection`.) Link is to verbose version of code. Outputs by drawing `*`s where the possible moves are. Explanation:
```
E⁸S
```
Copy the input to the canvas.
```
F⁸F⁸«Jικ
```
Jump to each square in turn.
```
¿⊙E⁸⁺⪫KD⁸✳λω.D
```
For every direction, peek in that direction, appending `.D` to the peeked string...
```
⁼⌕⁺..×⁶L…λ⌕λD¹
```
... if after truncating the string at the position of the first `D`, the result is not `.` but is a prefix of `.LLLLLL`...
```
*
```
... overwrite the `.` with a `*`.
[Answer]
# [Perl](https://www.perl.org) (`-p`), 60 bytes
```
for$i(0,7..9){s/D(.{$i}(L.{$i})+)\K\.|\.(?=(?1)D)/*/s&&redo}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kILUoZ0W0kq6BQYFS7IKlpSVpuhY3bdLyi1QyNQx0zPX0LDWri_VdNPSqVTJrNXzAlKa2Zox3jF5NjJ6Gva2GvaGmi6a-ln6xmlpRakp-LcQMqFELbt7SgwIuZIYLnOECYfj4-LjA1PigKYYwsAghM3xcYCb64FSDbBDUEh-IahcgAApxAY1xcfEBM3yANJgBN9oHqtgHqh3iRQA)
[Answer]
# JavaScript (ES11), 115 bytes
Expects a matrix with \$0\$ for *empty*, \$1\$ for *light*, \$2\$ for *dark*. Returns another matrix in the same format, using \$3\$ for the possible moves for dark.
```
m=>m.map((r,y)=>r.map((n,x)=>[...35678+m].some(d=>(g=X=>(q=m[Y+=~-(d/3)]?.[X+=d%3-1])&1&&g(X)|!n)(x,Y=y)*q&2)?3:n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZBLTsMwEIb3PYWJRORpUkOJgIrK6SawssSim1ZpFlXihKDEaZ20asXjImwqBIfqJTgDzqtUCGZh_zP-5rfHbx8iC_juPaSfqyLsDfZ5Su2UpPMFxtLcArVlnQhzoxKXEGJdXl0PjNQjeZZyHFAbR3Si1iVN3alBX3s4OLPAGxF3YtDg1Or1PdD7uh7hCTyfCMAbc0q30F3qFzCybgRAc_WX5MtVLDnWwlwDIvk8uIsTPt4KH58DKbJxIWMRYSD5IokLrM3ETCgwzOTt3H_AOaI2euoglPACpYii_AdUWDlGhZRD5F6V-2WuEeZoJBYB39yH2AcAU5mUIblqQCFOYagqfibyLOEkySKsTioDWRrUX7Ruvbqau_aAPGaxwJoGrSofgQxU7cPOSzP1br8nTXSOhXMQTi0YY07LsF9wLf4oHQvmtI7sX-bYqLmE1bSjQpU6ysZxWCWY2itxsGYNzOr2esJv)
### Commented
```
m => // m[] = input matrix
m.map((r, y) => // for each row r[] at index y in m[]:
r.map((n, x) => // for each value n at index x in r[]:
[...35678 + m] // we coerce 35678 to a string and get the values
// 0, 1 and 2 from m[] (if the board does not
// contain at least one empty, one light and one
// dark square, then there's no possible move and
// some() would fail anyway)
.some(d => // for each direction d:
(g = X => // g is a recursive function taking X
( q = // q is the value of the square on
m[Y += ~-(d / 3)] // the updated row Y
?.[X += d % 3 - 1] // and the updated column X
) & 1 && // if it's a light one:
g(X) // do a recursive call
| !n // and set the final result if n != 0
)(x, Y = y) // initial call to g with the current position
* q & 2 // test whether the last square is dark
) ? // end of some(); if truthy:
3 // set this square as a possible move
: // else:
n // leave it unchanged
) // end of inner map()
) // end of outer map()
```
[Answer]
# Google Sheets, 253 bytes
```
=let(_,lambda(a,r,regexmatch(join(,a),r)),f,"^L+D",b,"DL+$",if((H8=".")*or(_(A8:G8,b),_(I8:O8,f),_(H1:H7,b),_(H9:H15,f),_({A1,B2,C3,D4,E5,F6,G7},b),_({A15,B14,C13,D12,E11,F10,G9},b),_({I7,J6,K5,L4,M3,N2,O1},f),_({I9,J10,K11,L12,M13,N14,O15},f)),"*",H8))
```
Put the input in cells `H8:O15` and the formula in cell `X8`, and copy the formula cell to the range `X8:AE15`. The output is returned as a matrix in the latter cells, mimicking the format shown in the example in the question.
[Try it.](https://docs.google.com/spreadsheets/d/1Tgq5MPXKCjMLl1kq6fqb8PZG9fJ8my6JyxYjIzn5zHU/edit)
Generates strings by joining seven values to the left, right, up and down, and diagonally from a cell. Matches each string against a regex that looks at the start or at the end, depending on the string's direction from the origin.

Ungolfed:
```
=let(
isMatch_, lambda(a, x,
regexmatch(join("", a), x)
),
left, A8:G8,
right, I8:O8,
up, H1:H7,
down, H9:H15,
leftup, { A1, B2, C3, D4, E5, F6, G7 },
leftdown, { A15, B14, C13, D12, E11, F10, G9 },
rightup, { I7, J6, K5, L4, M3, N2, O1 },
rightdown, { I9, J10, K11, L12, M13, N14, O15 },
forward, "^L+D",
backward, "DL+$",
if(
and(
(H8 = "."),
or(
isMatch_(left, backward),
isMatch_(right, forward),
isMatch_(up, backward),
isMatch_(down, forward),
isMatch_(leftup, backward),
isMatch_(leftdown, backward),
isMatch_(rightup, forward),
isMatch_(rightdown, forward)
)
),
"*",
H8
)
)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒJðŒṬ⁹_ZṚ,ƊŒD;$€ẎẆ€ẎẠƇQ€ḂḄ5eðƇ
```
A monadic Link that accepts a list of lists of `0`s (spaces), `1`s (dark pieces), and `2`s (light pieces) and yields a list of valid spaces at which dark may play - each as 1-indexed `[row, column]`.
**[Try it online!](https://tio.run/##y0rNyan8///oJK/DG45OerhzzaPGnfFRD3fO0jnWdXSSi7XKo6Y1D3f1PdzVBmMsONYeCGLvaHq4o8U09fCGY@3/H@7ekukAFAShxn0uPofbQ@MNH@5c9P@/kpJSDJceCPjo6YEYPkAayHABAqAQl54PkOEDZvgAaTADKAZWo@cDVewD0Q40CwA "Jelly – Try It Online")** (The footer translates to the input above, calls the Link, and transforms the output to the sorted, 0-indexed `[column, row]` format used in the question's examples.)
[pretty-print version](https://tio.run/##y0rNyan8///oJK/DG45OerhzzaPGnfFRD3fO0jnWdXSSi7XKo6Y1D3f1PdzVBmMsONYeCGLvaHq4o8U09fCGY@3/H@7ekukAFAShxn0uPofbIWY1rYl3ONb1cHf3o4Y5Lj5aeo8a5h5arR/5/7@SklIMlx4I@OjpgRg@QBrIcAECoBCXng@Q4QNm@ABpMAMoBlaj5wNV7APRDjQLAA "Jelly – Try It Online").
### How?
```
ŒJðŒṬ⁹_ZṚ,ƊŒD;$€ẎẆ€ẎẠƇQ€ḂḄ5eðƇ - Link: Board (.:0 D:1 L:2)
ŒJ - multidimensional indices -> all coords
ð ðƇ - keep those for which - f(coord, Board):
ŒṬ - array with a 1 at {coord} and 0s elsewhere
⁹_ - Board subtract that (i.e. Board -1 @ coord)
ZṚ,Ɗ - rotate {that} a quarter and pair with {that}
ŒD;$€ - concatenate each to its forward diagonals
Ẏ - tighten
Ẇ€ - sublists of each
Ẏ - tighten
ẠƇ - keep if: all? (those with no 0s (spaces))
Q€ - deduplicate each
Ḃ - mod two
Ḅ - convert from binary
5e - five exists?
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 105 bytes
```
s`\.(?=(L+|(.{7}L)+.{7}|(.{8}L)+.{8}|(.{9}L)+.{9})D|(?<=D(L+|(.{7}L)+.{7}|(.{8}L)+.{8}|(.{9}L)+.{9}).))
*
```
[Try it online!](https://tio.run/##lY0xDsIwDEV33wMpoVVWWomqi8e/sTKEgYGFAdhor9UD9GKpE6dRhWDAg/2@9f39uL5u90uYJ6rp5OuadkZGePqzM31nUA3GvQ8jbBVHFI2KJolWRTtaHkx/7PiPC2ct7YP16be0eZIWn7tctAUuwAoAePXgw6xAX4MKgNdE/PRsg/ITqJulZEUSw4wEkJmgRCOboecL "Retina 0.8.2 – Try It Online") Link is to test suite that accepts multiple double-spaced boards. Outputs by drawing `*`s where the possible moves are. Explanation: From each `.` the regular expression tries to look both ahead or behind in each possible direction for at least one `L` followed by a `D`.
# [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1, 70 bytes
```
+s,T,,`.`*`([.D])(L+|(.{7}L)+.{7}|(.{8}L)+.{8}|(.{9}L)+.{9})(?!\1)[.D]
```
[Try it online!](https://tio.run/##dY07DsIwEER734ICycYrS6lIKpotpwsdIJmCgoYC6CDXygFyMbP@xIoQbLEzY80@3y/P6@3chGlUpHpPpNZaJNgH7Ym88xuvD45PRsO@tXttBxgbJYY2hzaFLoduMHq3OjYmXgXjE1jWNMqKZFdGLQ1Xw9kA4LmDr3I26ieoGvBMxN/OElQ@QW6zjDwpwTAjGYgmU9EoZeTzDw "Retina – Try It Online") Link is to test suite that accepts multiple double-spaced boards. Outputs by drawing `*`s where the possible moves are. Explanation: The regular expression matches every pair of `.` and `D` (in either order) that are separated by a run of `L`s in any of the forward directions. The `,T,,` command then transliterates the first and last character (`,,` is a step range using defaults of all three values) of each match (`,` is a regular range using defaults and is only needed so that the second range can be specified) from `.` to `*` (the `D` is therefore unaffected). The `+` then repeats until there are no more matches.
] |
[Question]
[
# Validate a codice fiscale
Every Italian resident/citizen is given a 16-character alphanumeric [*codice fiscale*](https://en.wikipedia.org/wiki/Italian_fiscal_code)
## Challenge
The final letter is a check code, which is calculated as follows :
* Characters of the code are split up into even and odd character according to their positions (check letter excluded)
* Both sets are replaced according to the following tables :
| ODD CHARACTERS (1st, 3rd...) | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Character | Value | Character | Value | Character | Value | Character | Value |
| 0 | 1 | 9 | 21 | I | 19 | R | 8 |
| 1 | 0 | A | 1 | J | 21 | S | 12 |
| 2 | 5 | B | 0 | K | 2 | T | 14 |
| 3 | 7 | C | 5 | L | 4 | U | 16 |
| 4 | 9 | D | 7 | M | 18 | V | 10 |
| 5 | 13 | E | 9 | N | 20 | W | 22 |
| 6 | 15 | F | 13 | O | 11 | X | 25 |
| 7 | 17 | G | 15 | P | 3 | Y | 24 |
| 8 | 19 | H | 17 | Q | 6 | Z | 23 |
| EVEN CHARACTERS (2nd, 4th...) | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Character | Value | Character | Value | Character | Value | Character | Value |
| 0 | 0 | 9 | 9 | I | 8 | R | 17 |
| 1 | 1 | A | 0 | J | 9 | S | 18 |
| 2 | 2 | B | 1 | K | 10 | T | 19 |
| 3 | 3 | C | 2 | L | 11 | U | 20 |
| 4 | 4 | D | 3 | M | 12 | V | 21 |
| 5 | 5 | E | 4 | N | 13 | W | 22 |
| 6 | 6 | F | 5 | O | 14 | X | 23 |
| 7 | 7 | G | 6 | P | 15 | Y | 24 |
| 8 | 8 | H | 7 | Q | 16 | Z | 25 |
* Sum both sets together
* Get the remainder of sum/26 and replace according to the table
| Remainder | Letter | Remainder | Letter | Remainder | Letter | Remainder | Letter |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | A | 7 | H | 14 | O | 21 | V |
| 1 | B | 8 | I | 15 | P | 22 | W |
| 2 | C | 9 | J | 16 | Q | 23 | X |
| 3 | D | 10 | K | 17 | R | 24 | Y |
| 4 | E | 11 | L | 18 | S | 25 | Z |
| 5 | F | 12 | M | 19 | T | | |
| 6 | G | 13 | N | 20 | U | | |
## Input
A 16-character *codice fiscale* in the `XXXXXX00X00X000X` form.
Assume the check letter will always be a letter
## Output
Is the *Codice Fiscale* valid (the language truthy value) or not (language falsy value)?
For the purpose of the challenge, we consider a *codice fiscale* to be valid if the calculated check letter corresponds with the input's check letter.
## Examples
```
TMDVSZ30T13L528J -> true
NWWFBE83P20A181A -> false
YNFLJC39E06C956L -> true
YNFLJC39E06C956E -> false
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest number of bytes wins
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 31 bytes
```
ØWiⱮịÐo“ÐVẈ÷{⁷.ƝİRḟ’Œ?¤’N0¦S26ḍ
```
[Try it online!](https://tio.run/##y0rNyan8///wjPDMRxvXPdzdfXhC/qOGOYcnhD3c1XF4e/Wjxu16x@Ye2RD0cMf8Rw0zj06yP7QESPsZHFoWbGT2cEfvf2ugcgVdO4VHDXOtD7dzPdy95eGOTQ93LFJ51LTmcDuQiPz/P8TXJSw4ytggxNDYx9TIwgukvqSoNJXLLzzczcnVwjjAyMDR0MLQESSRlphTnMoV6efm4@VsbOlqYOZsaWrmA9eCJuEK1wIA "Jelly – Try It Online")
A monadic link taking a string and returning 1 for valid and 0 for invalid.
## Explanation
```
ØWiⱮ | Index of each character in word characters (A-Aa-z0-9)
ịÐo“ÐVẈ÷{⁷.ƝİRḟ’Œ?¤ | Index odd positions in the list into the 15593538177379092215583486‘th permutation of 1..26; leave even ones alone
’ | Decrease by 1
N0¦ | Negate the final value
S | Sum
26ḍ | Is divisible by 26
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 117 bytes
```
f=([a,...x],s=i=0)=>x+x?f(x,s+g(++i%2?'BAFHJNPRTVCESULDGIMOQKWZYX'[g(a)]:a)):g(a)==s%26
g=x=>1/x?+x:parseInt(x,36)-10
```
[Try it online!](https://tio.run/##hcxNC4IwAIDhe/8j3JjZ5khMWGKmlZl9WfZBh1EqRmi0iP17q2sE3d7Dw3vhTy5O9@L2aJXVOa3rjIEDVzVNk0dVsIJhyHoSSTsDUhUoBwgVTd1W@o4/CqL5Mt643modDobj6WwxSfa7rXLIAYdHi0NofYox0dSNRs4k65G2tJG0bvwu0nH5eC@pAVsE16eqFNU11a5VDjKgxNPBZrWnOCY07OhmoEDY@CJRkvh9z6RzHTvEJM4Psov8MHBp18OG2@0Y4X/ifUj9Ag "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~165~~ 159 bytes
```
lambda s:chr((sum(ord(x)-48-17*(x>':')for x in s[1:-1:2])+sum(b"! %')-/135! %')-/135\"$24+#&(,.0*6987"[ord(x)-48-7*(x>':')]-32for x in s[:-1:2]))%26+65)==s[-1]
```
[Try it online!](https://tio.run/##bYxda8IwGEbv9yve1Y8k1mxNYmMa6EBdvZBOBoqitRdaKQqzldZB9@s7i6JeePdwnsM5/p12aSLK2F2VP@vDZruGXEe7DOP894DTbIsLQjuKsm4LFx9IIxKnGRSwTyAPmKZM85CYlbsxXqGBCH1nwr6vlVHnHbPWxO03qyUd1TWCe/TWDKngD91rljS4NKVNXDcPKAvLyogqI3gBQNOvz9lkKawpE77N1Qi1Kzqez4d9T4lvbvWYYr0LXYyH/mggHM@SA8eW/lPqnWmozwfAMdsnJxzjiJDyHw "Python 3 – Try It Online")
*-3 bytes* thanks to [@CommanderMaster's amazing observation](https://codegolf.stackexchange.com/questions/269468/validate-a-codice-fiscale/269477#comment584995_269477) about removing the constant `v`!
*-3 bytes* by using multiplication instead of indexing on the condition.
---
A function that accepts a parameter `s`, which is the code to be validated.
It returns
```
chr((S_E+S_O)%26+65)==s[-1]
```
That is, evaluates the remainder between the sum of both sets (`S_O` odd characters, `S_E` even characters) and 26, adds 65 to it (i.e. transforms a number `0-25` to `A-Z` using ASCII conversion) and checks if it's equal to the last character of the input.
`S_E` is
```
sum(ord(x)-48-17*(x>':')for x in s[1:-1:2])
```
`x>':'` is a condition that evaluates to true (or 1) if the character `x` is a letter (since its ASCII code is higher than `:`'s). Therefore, it'll subtract 48 from the ASCII code of `x` if its numeric, otherwise it'll subtract 65. It basically maps `'0' -> 0`, ... `'9' -> 9`, `'A' -> 0`, ..., `'Z' -> 25` and sum the resulting values.
`S_O` is
```
sum(b"! %')-/135! %')-/135\"$24+#&(,.0*6987"[ord(x)-48-7*(x>':')]-32for x in s[:-1:2])
```
If you take every ASCII code of the bytestring characters and subtract 32, you will see that it'll match the odd-characters table. So that's a transformation similar to `S_E`'s, but it now maps `'0' -> 0`, ... `'9' -> 9`, `'A' -> 10`, ..., `'Z' -> 35`, get the byte at that bytestring index and subtract 32.
[Answer]
# APL+WIN, 161 bytes
Prompts for string.
```
c←8 2⍴⎕⋄c[7;1]=a[26|+/((('BAKPLCQDREVOSFTGUHMINJWZYX'⍳c[;0])~26),(¯65+⎕av⍳'BAFHJNPRTV')[(n⍳c[;0])~10]),(((n←(⍕⍳10)~' ')⍳c[;1])~10),((a←⎕av[65+⍳26])⍳¯1↓c[;1])~26]
```
[Try it online! Thanksto Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tfzKQaaFg9Kh3C1DiUXdLcrS5tWGsbWK0kVmNtr6Ghoa6k6N3gI9zoEuQa5h/sFuIe6iHr6efV3hUZIT6o97NydHWBrGadUZmmjoah9abmWoDjUksA0oA9bl5ePkFBIWEqWtGa@Qh1BoCCR2gyXlAqzUe9U4FyhgaaNapK6hrQhQZghWB1CQClYANjAaZ3LvZyCwWpObQesNHbZOhKoFi/4Fe4fqfxqUe4usSFhxlbBBiaOxjamThpc4FFPQLD3dzcrUwDjAycDS0MHQEC0b6ufl4ORtbuhqYOVuamvlgE3RVBwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 137 bytes
```
$c=pop@F;pairmap{$s+=$b=~s|\D|-65+ord$&|er+($a=~/\d/?1+$a*2-($a==1)+2*($a>4):BAKPLCQDREVOSFTGUHMINJWZYX=~/$a/*"@-")}@F;$_=$s%26+65==ord$c
```
[Try it online!](https://tio.run/##XY9dT4MwAEXf9zOWaoQGaYslDFId40PFgtOx4ZYlBrc9kOBoKG/ifrqVJT75dG9OcnNyxaGtqVJgx0QjprEnyqr9LMUXkJCBD3aS/TbsDZvCpt2Dy/7QwitQspO53Zt3GIJSJ8YZMKxBog/t9kZzZ/7TnAcv4Wu0el7E@f3yIX3MkmKzfhuGoDT18dQYa9@DDbwzIC@IDW3K2NmwUx6QDHkqT8PVYmOhHFucEicZZUURzyLHmhPkYwf7o3UW8ySwJhGygwm1@X8Q/TSiq5qjVEZKrxFGQ/JKdq677Kqa/R1VhqjjXw "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
25Ý•D+>∞¢-‹ ŸΔŒ•.IžKIkι`Šèì`(O₂Ö
```
-4 bytes by porting [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/269479/52210).
Input as a list of characters.
[Try it online](https://tio.run/##AVAAr/9vc2FiaWX//zI1w53igKJEKz7iiJ7Coi3igLkgxbjOlMWS4oCiLknFvktJU2vOuWDFoMOow6xgKE/igoLDlv//WU5GTEpDMzlFMDZDOTU2TA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVw6H8j08NzHzUsctG2e9Qx79Ai3UcNOxWO7jg35egkoKie59F93hHZ53YmHF1weMXhNQka/o@amg5P@6/zP1opxNclLDjK2CDE0NjH1MjCS0lHyS883M3J1cI4wMjA0dDC0BEoFOnn5uPlbGzpamDmbGlq5oMp5KoUCwA).
**Explanation:**
```
25√ù # Push a list in the range [0,25]
•D+>∞¢-‹ ŸΔŒ• # Push compressed integer 15593538177379092215583485
.I # Get the (0-based) 15593538177379092215583485th permutation of the [0,25]-list:
# [1,0,5,7,9,13,15,17,19,21,2,4,18,20,11,3,6,8,12,14,16,10,22,25,24,23]
žK # Push constant "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Ik # Get the (0-based) index of each character of the input in this string
ι # Uninterleave it into two parts
` # Pop and push both parts to the stack
Š # Triple-swap the three lists on the stack
è # Index the 0-based even indices into the permuted list
ì # Prepend-merge the two lists back together
` # Pop and push all integers separated to the stack
( # Negate the last one
O # Sum all integers on the stack together
₂Ö # Check whether this sum is divisible by 26
# (after which it is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•D+>∞¢-‹ ŸΔŒ•` is `15593538177379092215583485`.
The `15593538177379092215583485` is generated using Jelly's \$n^{th}\$ permutation builtin `œ¿`: [try it online](https://tio.run/##y0rNyan8///o5EP7////7@To5uHlFxAUEubsGhzq4@Lu6esf6B0eFRnx39HJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIKAA) (minus 1, because 05AB1E uses 0-based indexing and Jelly 1-based indexing).
[Answer]
# Excel ms365, 199 bytes
Assuming input in `A1`:
```
=CHAR(MOD(SUM(MAP(ROW(1:15),LAMBDA(i,TOROW(FIND(MID(A1,i,1),IF(ISODD(i),{"10 2 3 4 5 6 7 8 9","BAKPLCQDREVOSFTGUHMINJWZYX"},{"0123456789","ABCDEFGHIJKLMNOPQRSTUVWXYZ"})),3)-1))),26)+65)=RIGHT(A1)
```
[Answer]
# [Funge-98](https://esolangs.org/wiki/Funge-98), 108 bytes
```
"NRTS"4(I'0>'v00p
<@.!-+A'g20w1p21-1:g21p20%'+g20+-fg3-+0'*'`9':\-+0'*'`9':
"$!#%('&
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9X8gsKCVYy0fBUN7BTLzMwKOCycdBT1NV2VE83Mig3LDAy1DW0SjcCMgxUpdS1gYLaumnpxrraBupaguoJlupWMUhsLgYOLgF@ETEJGTkFJRVBYUVlKSFRcWlZeUlVDXW1//9DfF3CgqOMDUIMjX1MjSy8uAA)
Contains non-printable characters, so here is a hex dump:
```
00000000: 224e 5254 5322 3428 4927 303e 2776 3030 "NRTS"4(I'0>'v00
00000010: 700a 3c40 2e21 2d2b 4127 6732 3077 3170 p.<@.!-+A'g20w1p
00000020: 3231 2d31 3a67 3231 7032 3025 1a27 2b67 21-1:g21p20%.'+g
00000030: 3230 2b2d 6667 332d 2b30 272a 1127 6039 20+-fg3-+0'*.'`9
00000040: 273a 5c2d 2b30 272a 1127 6039 273a 0a00 ':\-+0'*.'`9':..
00000050: 080a 100f 1416 181c 1e20 2224 1113 2123 ......... "$..!#
00000060: 1a12 1517 1b1d 1f19 2528 2726 ........%('&
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
FS⊞υ⌕⁺α⭆χκι¬﹪⁻⊟υΣEυ⎇﹪κ²ι⌕α§”$⌈⊟⌈σEζ⊖)"⁷hY✂&⊕⧴C”ι²⁶
```
[Try it online!](https://tio.run/##NY3LCsIwEEX3fkVwNYEI2qIIrnxbNRptfXUXbNViTUpMRL8@pj5mMzBzzz3HC1dHyXNrT1IhCERhdKhVJs6AMWLmfgFD0CgTCbDc3IET9H1TXkCjTtAVY4IyjDsV5s4aFlIDlYnJJdBMOILJAozLhOYGJeTqolQJrl7/3JUgryz5eZyiqwORpE@o9rqjyXTB1tG2Pww388E4oMvVbBcf9tWPtRxHt9zqWBvRwTaM/XrU8OdNrz21tUf@Bg "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a valid code, nothing if not. Explanation:
```
FS⊞υ⌕⁺α⭆χκι
```
Loop through the input string, converting each character into its index in the string `A..Z0..9`.
```
¬﹪⁻⊟υΣEυ⎇﹪κ²ι⌕α§”...”ι²⁶
```
Remove the last value, permute alternate elements (permutation string shamelessly stolen from @Arnauld's answer), take the sum, and compare the the removed last value modulo 26.
] |
[Question]
[
Problem author: <https://stats.ioinformatics.org/people/5815>
You are given a system with a hidden permutation of the numbers \$1, 2, 3, \ldots, n\$. Your task is to guess this permutation by asking the system a series of questions.
Each question consists of providing the system with a permutation of the numbers \$1, 2, 3, \ldots, n\$. The system will respond with the length of the [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence) between your permutation and the hidden permutation.
A subsequence is defined as a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. For example, \$1, 2\$ would be considered a subsequence of \$1, 3, 2\$.
You must guess the hidden permutation using at most \$n^2\$ questions. If you exceed this limit, the system will kill your program.
You can pick an interaction protocol from the two below.
Interaction protocol 1:
* Communication with the system occurs over standard input and standard output.
* At first, the system provides you the number \$n\$, which is the length of the array.
* To ask the system, the program should write a single permutation of the numbers \$1, 2, 3, \ldots, n\$ to the standard output, followed by a newline character.
* The system will respond with a single integer, which is the length of the longest common subsequence between the permutation provided by the program and the hidden permutation.
* **You are done when you receive the number \$n\$ from the system.**
Interaction protocol 2:
* You can take a number \$n\$ and a black box function as input. The black box function `f(user_input)` calculates the longest common subsequence between `user_input` and the permutation that the system holds, provided that `user_input` is also a permutation of \$1, 2, 3, \ldots, n\$.
* **You are done when you receive \$n\$ from the black box function.**
* A call to the black box function constitutes asking the system and counts towards your question limit.
In both interaction protocols, if you want, you can communicate by passing permutations of \$0, 1, 2, 3, \ldots, n - 1\$ instead.
### After receiving \$n\$, what can I do?
The system stops monitoring your program. Your program can crash, loop forever or ask additional questions. You already guessed the permutation, congratulations.
Sample interaction:
```
Hidden permutation: 3 2 1
---
Input: 3
Output: 1 2 3
Input: 1
Output: 2 1 3
Input: 2
Output: 3 1 2
Input: 2
Output: 3 2 1
Input: 3
```
Now you've successfully guessed the permutation.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins.
[Answer]
# [R](https://www.r-project.org), ~~112~~ ~~110~~ 101 bytes
```
\(f,n,g=1:n)for(i in g)for(j in g)if((d=f(b<-c((a=g[-match(i,g)])[1:j-1],i,tail(a,n-j))))>F){F=d;g=b}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZJLbtswEIbRpXUKQl2YhMlYCrooZLNAN1kFvYBjGDRNSZQl0iUpWILjK_QC3biLHKo9Rk_Q8TNpBEFDzfwcznzDn7_c4c-Hvx9Rrp0PaKVybRQaLmsh12xpuyHKWyODtiaLQORsg8oQNj4bj7fb7V2h1Nrn1p3sHdhxbU2hfGDSNo01zLdLr763ykjFVhv2aRzV0vNrTtzRnja8VqYIJe4INdd1T8guGjzyRgSnO_ztK21GKTWjlEQDOA9rpA1KsuaoOjmqs8OcHAOdY8158vxcwZegx5mG3dUonfPkGFa1Vwg03UzPOe9n1fw_DSxpNR-lN-mbWCM6fIrDD73451DUYB8dX6dC6wwoLuVCaB-daC6AJt8Znkxeuyc7M50ykE2kCDgGTq6PqaGxbcOmDVlM7ZQBMODklYTchMZPJiYTu99HMA9jt9eR2dahYdEq7xehVAvhnOjfDu9diL-0IWeff6snnMOBBU8B3Q1sQW5ICwKc8IrneDllEmPBixmDqcgSa1qQOZmlWcWAhaZB6BoLalhF4PnyQHYPfDUp-HJ_OezHuQnuRbOpFU6z-4S8Lwzn_Ibr9TpcuifQsyyVXKNQioC2ChU2IIHuE4R1GHoAEpBREjIKp-seZArVAi72GSiyObplJ-eqDoez_Qc)
Uses all `n^2` guesses, even if it receives a response of `n` first. No output (but the ATO link forces the 'black box' function to print its response each time so you can at least see something!).
It's pretty efficient: if the 'black box' doesn't need to print its response ([try it here](https://ato.pxeger.com/run?1=XZJLbtswEIbRpXUKQl2YhMlYCrooZLNAN1kFvYBjGDRNSZQl0iUpWILjK_QC3biLHKo9Rk_Q8TNpBEFDzfwcznzDn7_c4c-Hvx9Rrp0PaKVybRQaLmsh12xpuyHKWyODtiaLQORsg8oQNj4bj7fb7V2h1Nrn1p3sHdhxbU2hfGDSNo01zLdLr763ykjFVhv2aRzV0vNrTtzRnja8VqYIJe4INdd1T8guGjzyRgSnO_ztK21GKTWjlEQDOA9rpA1KsuaoOjmqs8OcHAOdY8158vxcwZegx5mG3dUonfPkGFa1Vwg03UzPOe9n1fw_DSxpNR-lN-mbWCM6fIrDD73451DUYB8dX6dC6wwoLuVCaB-daC6AJt8Znkxeuyc7M50ykE2kCDgGTq6PqaGxbcOmDVlM7ZQBMODklYTchMZPJiYTu99HMA9jt9eR2dahYdEq7xehVAvhnOjfDu9diL-0IWeff6snnMOBBU8B3Q1sQW5ICwKc8IrneDllEmPBixmDqcgSa1qQOZmlWcWAhaZB6BoLalhF4PnyQHYPfDUp-HJ_OezHuQnuRbOpFU6z-4S8Lwzn_Ibr9TpcuifQsyyVXKNQioC2ChU2IIHuE4R1GHoAEpBREjIKp-seZArVAi72GSiyObplJ-eqDoez_Qc)), it guesses an array of 50 elements in a few seconds.
**How?**
Starts with a guess of `1..n`. Then tries all positions of each digit, updating the guess-so-far whenever the 'black box' output improves, so that each digit gets placed into its correct position in the growing longest-common-subsequence-so-far. This uses exactly `n^2` queries to the 'black box' function, with the output of `n` usually received for one of the queries of the last digit tried (unless it was already in the last position in the secret permutation).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 71 bytes
```
M?&GHeS[gGPHgPGH*qeGeHhgPGPH)0JK.pSQ#
=kh?tK.meShMr8SgLbKJK=ZE=KfqZgkTK
```
[Try it online!](https://tio.run/##K6gsyfj/39dezd0jNTg63T3AIz3A3UOrMNU91SMDyAzw0DTw8tYrCA5U5rLNzrAv8dbLTQ3O8C2yCE73SfL28raNcrX1TiuMSs8O8f7/35TLmMsIik0B "Pyth – Try It Online")
Pretty slow, won't run on TIO for \$n>5\$. Truthfully I'm not sure how to prove that this will always guess the permutation in \$n^2\$, but assuming you didn't pose an impossible challenge then this does it. The big idea here is we always ask about the permutation which will provide the maximum amount of information. That is, we keep a list of potential matches, and every time we ask about a permutation and receive the length of the longest common subsequence, we filter this list for permutations that agree with the information. To choose the next permutation to ask about, we look at all permutations and select the one which best splits up our potential matches.
### Explanation
First we define the "length of the longest subsequence" function.
```
M # define g(G,H)
?&GH 0 # if G or H are empty, return 0
eS[ ) # otherwise return the maximum of
gGPH # g(G, H[:-1])
gPGH # g(G[:-1], H)
*qeGeHhgPGPH # 1 + g(G[:-1], H[:-1]), but only if G[-1] == H[-1]
```
Then we guess the array.
```
# implicitly assign Q = eval(input())
JK.pSQ # J = K = all possible permutations of [1, ..., Q]
# # loop infinitely until error
=kh # set (and print) k to the first element of
?tK # if K has more than one element
.m J # elements of J which minimize lambda b
gLbK # map K over g(_, b)
hMr8S # get how many of each element there is
eS # maximum
K # else: K
=ZE # set Z to the next input
=K # set K to
f K # K filtered on lambda T
qZgkT # Z == g(k, T)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 151 bytes
Modified from [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/259203/110802).
---
Golfed version, [try it online!](https://tio.run/##bVLBbtswDL3nK4hcsjUKkOxYVwW6DgE2uMOw7SYIhmzLjrxY6mwZs9Hm2zNStrEZ6MU0@UiRfI@18iddK28ydX13A0fTtB5yXRirYZOeVfZrl7p@A0VnM2@chZv3q3PWij6JTesZDMFKuOXw5PLurMVLDRxibUt/Er1kYP@5A7oxA8OgurAVQIzQo7OtV9Y/NI0axJ4B1m/hQHVoLjLCvKNrhMFcRA3ccajRbrf0QoCqEaoIsmgnCD4XVIUYvL4iykNWLDAYGlRkpAzFIZ8KeoQpxmEQopLy7QKKoY//BIzFbyY@qV5MyWNs8Z6Ucqqd7GjCNyyOuf@zEdLlahV0@ej6SYUF@0T3PrBLf6GMXvrWGOvF@nenmwHWjHhag@v8c@dvyQ@aMmh11mgvQ/NlaOyMJ/LV/ZkPxHUNbMpOt22CV5QoknB5KgH8edKjukWCjZMw7nWet@TflS21sJId@Z7lTLGUGYYHElTnB2buuGWkd9AaAxUFSGXFP@mz9vpRtboVJTMySvkXZ6xQQhyiqNoR4y/mwtDf2W0VRUh5lPNCpDJCtfP7I3bNo5Kjj0gpr@O6SB2Olbv6h6qfccxxxg97YibshAnL3WZN2HzsM5XXvw)
```
Module[{g=Range[n],F=0,d,a,b,i,j},For[i=1,i<=n,i++,For[j=1,j<=n,j++,a=DeleteCases[g,i];b=Join[a[[1;;j-1]],{i},a[[-n+j;;]]];d=f[b];If[d>F,F=d;g=b];]];g]
```
Ungolfed version
```
(* First define 'black-box' function *)
lcs[x_List, y_List] := Module[{m = Length[x], n = Length[y], L, i, j},
L = ConstantArray[0, {m + 1, n + 1}];
For[i = 0, i <= m, i++,
For[j = 0, j <= n, j++,
If[i == 0 || j == 0, L[[i + 1, j + 1]] = 0,
If[x[[i]] == y[[j]], L[[i + 1, j + 1]] = L[[i, j]] + 1,
L[[i + 1, j + 1]] = Max[L[[i, j + 1]], L[[i + 1, j]]]
]
]
]
];
L[[m + 1, n + 1]]
]
blackBox[x_List] := Module[{n = 0},
n = n + 1;
Print["query ", n, " output: ", lcs[x, secret]];
lcs[x, secret]
]
(* Now define our 'guess_the_array' function *)
guessTheArray[f_, n_] := Module[{g = Range[n], F = 0, d, a, b, i, j},
For[i = 1, i <= n, i++,
For[j = 1, j <= n, j++,
a = DeleteCases[g, i];
b = Join[a[[1 ;; j - 1]], {i}, a[[-n + j ;;]]];
d = f[b];
If[d > F, F = d; g = b];
]
];
g
]
secret = RandomSample[Range[20]];
guess = guessTheArray[blackBox, Length[secret]]
```
] |
[Question]
[
Take as input two strings \$A\$ and \$B\$. Output a string \$C\$ that is \$A\$ but with two characters swapped such that the [Levenshtein distance](https://codegolf.stackexchange.com/q/67474) \$d(C,B)\$ is as small as possible. You must swap two characters and you cannot swap a character with itself, although you may swap two identical characters in different positions.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes.
Instead of strings you may instead choose to handle lists of positive integers.
## Examples
Here are some examples of inputs and possible outputs along with the Levenshtein distance achieved.
| A | B | C | Distance |
| --- | --- | --- | --- |
| `abcd` | `adcb` | `adcb` | 0 |
| `ybgh` | `epmn` | `ygbh` | 4 |
| `slime` | `slime` | `silme` | 2 |
| `yeboc` | `yoqqa` | `yobec` | 3 |
| `unnua` | `muuna` | `uunna` | 2 |
| `oobis` | `oobi` | `oobis` | 1 |
| `yuace` | `yuac` | `yuaec` | 1 |
[Answer]
# JavaScript (ES6), 163 bytes
Expects `(a)(b)`, where **a** and **b** are arrays of characters. Returns another array of characters.
This really just tries all possibilities and computes the Levenshtein distance for each of them. It seems very likely that there's a smarter/shorter way.
```
a=>M=b=>a.map((x,i)=>a.map((y,j,[...s])=>j<=i|(s[i]=y,s[j]=x,n=b.length,g=m=>v=m*n?1+Math.min(g(m,--n),g(--m)-(s[m]==b[n++]),g(m)):m+n)(s.length)>M||(M=v,o=s)))&&o
```
[Try it online!](https://tio.run/##dc/BboQgEIDhe5@i8bCBCiS9Nh37BD6B4QDIIkYGt6hZE9/drs2ue1mP/@RjMrRqUsn8@n7gGGu7nmFVUJSgoVAiqJ6QK/N0j5m1rBJCJHmbtd/gF5IqL2FmqWolXBmCFp1FNzTMQYBigvCBP595qYZGBI/EkcA4R8oc4TxQfnsfJICuMM/lNg2UfoUcKUn3RbQol4WUMLEIiVJ6OsXVREyxs6KLjpzJdlGmtKmzd0nvVRu9FX17QWftmie1fcBDmjofbPagj3q91epodjrHy0Ud0RFxVDsN44iHNEbt0063Ov7WqMzz1q3@6foH "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
\ā<.ÆεèyRǝ}Σ¹.L}н
```
Inputs in the order \$B,A\$.
[Try it online](https://tio.run/##AS4A0f9vc2FiaWX//1zEgTwuw4bOtcOoeVLHnX3Oo8K5Lkx90L3//3lvcXFhCnllYm9j) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWFvaGVCYdW/o850mijd7jt3NYIl6LDKyqDjs@tPbf40Do9n9oLe//r/I@OVkpMSU5S0lFKTEpOUYrViVZKLcjNA/Irk9IzwPzinMzcVKAAhAaJVOYXFiaClKQm5SeDRXJLS/NAIqV5eaWJYJH8/KRMoACIKoZoKk1MBukBUkBTYgE).
`ā<.Æεèy` could alternatively be `.ā.Æεø`` for the same byte-count:
[Try it online](https://tio.run/##AS4A0f9vc2FiaWX//1wuxIEuw4bOtcO4YFLHnX3Oo8K5Lkx90L3//3lvcXFhCnllYm9j) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWFvaGVCYdW/o/RO9Kod7jt3NaI4sM7EoKOz609t/jQOj2f2gt7/@v8j45WSkxJTlLSUUpMSk5RitWJVkotyM0D8iuT0jPA/OKczNxUoACEBolU5hcWJoKUpCblJ4NFcktL80AipXl5pYlgkfz8pEygAIgqhmgqTUwG6QFSQFNiAQ).
**Explanation:**
```
\ # Discard the first (implicit) input `B`
ā # Push a list in the range [1, length of second (implicit) input `A`]
< # Decrease it to range [0, length_A)
.Æ # Get all pairs without duplicates
ε # Map over each pair:
è # Index them into the second (implicit) input `A`
yR # Push the pair reversed
ǝ # Insert them into the second (implicit) input `A`
}Σ # After the map: sort the strings by:
.L # The Levenshtein distance with
¹ # the first input `B`
}н # After the sort: pop and leave the first string
# (which is output implicitly as result)
.ā # Enumerate the second (implicit) input,
# pairing each character with its index
.Æ # Get all pairs without duplicates
ε # Map over each pair:
ø # Zip/transpose; swapping rows/columns
` # Pop and push the pair of characters and pair of indices separated to
# the stack
R # Reverse the indices-pair
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes
```
ė2ḋƛ∩÷Ṙ¹∇Ȧ;‡⁰꘍∵
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwixJcy4biLxpviiKnDt+G5mMK54oiHyKY74oCh4oGw6piN4oi1IiwiIiwiXCJhYmNkXCIsIFwiYWRjYlwiXG5cInliZ2hcIiwgXCJlcG1uXCJcblwic2xpbWVcIiwgXCJzbGltZVwiXG5cInllYm9jXCIsIFwieW9xcWFcIlxuXCJ1bm51YVwiLCBcIm11dW5hXCJcblwib29iaXNcIiwgXCJvb2JpXCJcblwieXVhY2VcIiwgXCJ5dWFjXCIiXQ==)
`ė2ḋƛ∩÷` could be `ẏ2ḋƛ¹İ` for the same byte count.
```
ė2ḋƛ∩÷Ṙ¹∇Ȧ;‡⁰꘍∵
ė # Enumerate, make a list [index, x] for each x in the first input.
2ḋ # Combinations without replacement of length 2; pairs.
ƛ # For each:
∩ # Transpose
÷ # Dump; push both items onto the stack.
Ṙ # Reverse the top pair (the pair of two characters). Call this Y, and the other pair X.
¹ # Push the first input
∇ # Push it under the top two values of the stack, aka c,a,b.
Ȧ # Assign; replace each of the indices in X with the corresponding value in Y.
; # Close map.
‡ ∵ # Minimum by:
⁰꘍ # Levenshtein distance with the second input.
```
[Answer]
# [R](https://www.r-project.org), ~~130~~ 97 bytes
```
\(A,B,x=combn(seq(a<-utf8ToInt(A)),2,\(i)intToUtf8(`[<-`(a,i,a[rev(i)]))))x[order(adist(x,B))[1]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Lc87bsMwDAbgWT2Gs1CADNRphwzJkGzdk8kxEEqWEwGRFD9U2Gfp4hboRXqL3qaiXC0_oQ8kwY_Pbv5qdt9haPLNL55hLw5i3ClvpYNet4DbPNrm6N_cAHvOxVqcwXDjhqM_RYBLuc0vgMIILDv9Hq3i8Y2l72rdAdamH2AUB87Loqr-F_00kKFUdSZYhrWSGV8xSvb8FGWS1xuJflhHMl3ljb2S9HdjNdFSROvN3Wq2Tm1aekU4-bbF1OilVuyFMDgXkNCG4BLGdLh0ei9NT0gFWfpgRZoaUKWVVKShAePQYrlknpf8Aw)
Another brute-force solution.
[Answer]
# [Python](https://www.python.org), 216 bytes
```
lambda a,b:(n:=len(a))and min(w(c:=[*a],k%n,k//n)or d(c,[*b])for k in range(n*n)if k%n<k//n)
d=lambda s,t:-~min(d(S:=s[1:],T:=t[1:])-(s[0]==t[0]),d(S,t),d(s,T))if s>""<t else len(s+t)
def w(a,i,j):a[i],a[j]=a[j],a[i]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PZHBjtsgEIa1R3gKhFQJUtxNdnuo0NKX6N68PgwYJ2zscRKwIl_6Ir1Eqtpnavs0hXg3l2_mZ35Gw_Dj92FOuxEvPzvz8mtKXfXl758eBtsCA2W1QG16jwKkBGzZEFCchdOmXkGj9h9Q7e_vUY4n1gqn6pVtZJfFngVkJ8CtF7hCGTqWrU9XK23NW_uokq6-l46t-KZNrDe6Uc_apJLISsR63Zis1o1U2aFSCVE9y9IvfuX8KTHfR8_KfPFjyq19x84CVFCvUkMdGgX1a2MKVJHL-_7d3SUfk-Gcg3UtgdbZBWs62-2O-MOAZN7aHflMYx8GT94Y-swHOns7OjKPxyNkWu_II50QJyDDNCGQjMwHOo42RFJIlnRD5wmcJ4UF-eYmT_EpHvqQBH9BLul1tDrdzhKXrKw0lZWWYkOLzH-jnGpDTIDOv9c0ZexwCphEl9dg5c0gbwVeVRWXyyYulyX-Bw)
A very bloated answer which just iterates through all pairs of swaps. The Levenshtein distance is adapted from an answer to [this question](https://codegolf.stackexchange.com/questions/67474/levenshtein-distance), but slightly shortened.
] |
[Question]
[
### the goal
Build an optimizing Brainfuck implementation. Whether it is a compiler, an interpreter, a JIT compiler, or whatever else is up to you.
### scoring
A reference implementation (`bfi`) will be given. Each implementation will run the same program (`mb.b`) also given at the end.
Your score is
```
time spent to run `mb.b` translated by `bfi`
/ time spent to run `mb.b` translated by your implementation
```
rounded to 3 decimal digits.
If `mb.b` through `bfi` runs in 20 seconds and through yours in 7 seconds, the score is `20 / 7 = 2.8571..` rounded to `2.857`.
If your implementation compiles `mb.b` to an intermediate or final form, such compilation time is not measured.
The time measurement will be done on your machine.(1)
### requirements
Your implementation should work on at least one platform, which may be an obscure one or even a virtual environment, but it should be able to also run the reference implementation for comparison.
You can rely on an existing backend such as `llvm`, or even a source-to-source compiler is possible. You can use any external program during the translation of the Brainfuck program.
### possible strategies
* Compile to native code rather than interpret it.
* Most machines can add or subtract arbitrary numbers very fast. You can replace a series of `+`, `-`, `>`, `<` to a single operation.
* Postpone pointer movements. `>+>->` can be translated to `p[1] += 1; p[2] -= 1; p += 3;`.
* Remove loops. A common way to zero a cell is `[-]`. This is the same as `p[0] = 0`. `[->+<]` is `p[1] += p[0]; p[0] = 0`.
### reference implementation
Compile the program with `gcc` version 9.3 or higher with the given flags. `gcc` 9.3 was released on March 12, 2020 and is ported to a variety of platforms. If you think this requirement is unreasonable for your target platform, let me know on the comments.
```
gcc -obfi -s -O3 -march=native bfi.c
```
**bfi.c**
```
#include <stdio.h>
#include <stddef.h>
typedef unsigned char byte;
static void interpret(byte *cp, byte *ip, int j) {
byte *s[0x100];
size_t i = -1;
for (; *ip; ++ip) {
if (!j) {
switch (*ip) {
case '>':
++cp;
break;
case '<':
--cp;
break;
case '+':
++*cp;
break;
case '-':
--*cp;
break;
case '.':
putchar(*cp);
break;
case ',':
*cp = getchar();
break;
case '[':
if (*cp) {
s[++i] = ip;
} else {
++j;
}
break;
case ']':
if (*cp) {
ip = s[i];
} else {
--i;
}
}
} else if (*ip == '[') {
++j;
} else if (*ip == ']') {
--j;
}
}
}
int main() {
static byte b[0x8000];
FILE *f = fopen("mb.b", "r");
fread(b + sizeof(b) / 2, 1, sizeof(b) / 2, f);
fclose(f);
interpret(b, b + sizeof(b) / 2, 0);
return 0;
}
```
---
**mb.b** ([pastebin](https://pastebin.com/s0TRrwku), [online interpreter](https://copy.sh/brainfuck/?file=https://copy.sh/brainfuck/prog/mandelbrot.b))
---
(1) One may think that the scoring method is not fair because, I know, each machine has its own qualities and the score will be different across different machines. But, this is not a serious competition. I'm just providing a *puzzle*, some subject to think about, that might be interesting enough for some people to spend their time on. If someone comes up with an interesting algorithm, that is an interesting algorithm, nothing changes whether a *fair* score is there or not. The score is there just as a hint showing how effective the optimization was.
\* While there are no rules to prevent you from optimizing *too specifically* for the test program, such as hard-coding the output directly, for example. I believe that won't be interesting to anyone including yourself, so please try to apply *general* optimizations if you'd like to participate.
[Answer]
# C++, 17.497/0.720=24.301
```
#include <stdio.h>
#include <stdlib.h>
int main() {
freopen("mb.b", "r", stdin);
freopen("2g.c", "wb", stdout);
puts("char b[100000]; int main(){ char*p = b+50000;");
while (1) {
switch (getchar()) {
case '+': puts("++*p;"); break;
case '-': puts("--*p;"); break;
case '>': puts("++p;"); break;
case '<': puts("--p;"); break;
case '[': puts("while(*p){"); break;
case ']': puts("}"); break;
case ',': puts("*p=getchar();"); break;
case '.': puts("putchar(*p);"); break;
case -1: goto done;
}
} done:;
puts("}");
fclose(stdout);
system("gcc -s -O3 -march=native 2g.c -o 2g");
}
```
Just use the optimization of gcc
[Answer]
# [Java](https://en.wikipedia.org/wiki/Java_(programming_language)) with [ObjectWeb ASM](https://asm.ow2.io/), \${98.055\over19.52}\$ = 5.023
Compiles BF to JVM bytecode. Applies optimizations such as collapsing `[-]` and collapsing multiple `<>+-` into one operation.
**One thing to note:** On my computer, the reference program crashes after printing 2/3 of the set. It takes 65.37 seconds before crashing, so I have manually adjusted my score using \${2\over3} x = 65.37\$
```
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.ListIterator;
public class Main implements Opcodes {
public static void main(String[] args) throws IOException {
String program = Files.readString(Paths.get("mb.b"));
Files.write(Path.of("Main.class"), compile(program));
}
private static byte[] compile(String program) {
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
writer.visit(V16, ACC_PUBLIC + ACC_SUPER, "Main", null, "java/lang/Object", null);
writer.visitSource("Main.bf", null);
// filter out unnecessary characters
StringBuilder programBuilder = new StringBuilder();
for (char c : program.toCharArray()) {
if ("[]<>+-.,".indexOf(c) != -1) {
programBuilder.append(c);
}
}
program = programBuilder.toString();
program = program.replace("[-]", "z");
Deque<JumpPair> recurStack = new ArrayDeque<>();
MethodVisitor mv = writer.visitMethod(ACC_PUBLIC + ACC_STATIC,
"main",
"([Ljava/lang/String;)V", null, null);
mv.visitCode();
// pointer, in var 0
mv.visitInsn(ICONST_0);
mv.visitVarInsn(ISTORE, 0);
// memory, in var 1
mv.visitLdcInsn(1000);
mv.visitIntInsn(NEWARRAY, T_INT);
mv.visitVarInsn(ASTORE, 1);
ListIterator<Character> programIterator = program.chars().mapToObj(c -> (char) c).toList().listIterator();
while (programIterator.hasNext()) {
char c = programIterator.next();
switch (c) {
case '>' -> mv.visitIincInsn(0, count(c, programIterator));
case '<' -> mv.visitIincInsn(0, -count(c, programIterator));
case '+' -> {
mv.visitVarInsn(ALOAD, 1);
mv.visitInsn(DUP);
mv.visitVarInsn(ILOAD, 0);
mv.visitInsn(IALOAD);
chooseNumberInsn(count(c, programIterator), mv);
mv.visitInsn(IADD);
mv.visitVarInsn(ILOAD, 0);
mv.visitInsn(SWAP);
mv.visitInsn(IASTORE);
}
case '-' -> {
mv.visitVarInsn(ALOAD, 1);
mv.visitInsn(DUP);
mv.visitVarInsn(ILOAD, 0);
mv.visitInsn(IALOAD);
chooseNumberInsn(count(c, programIterator), mv);
mv.visitInsn(ISUB);
mv.visitVarInsn(ILOAD, 0);
mv.visitInsn(SWAP);
mv.visitInsn(IASTORE);
}
case '.' -> {
mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
load(mv);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "print", "(C)V", false);
}
case ',' -> {
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ILOAD, 0);
mv.visitFieldInsn(GETSTATIC, "java/lang/System", "in", "Ljava/io/InputStream;");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/InputStream", "read", "()I", false);
mv.visitInsn(IASTORE);
}
case '[' -> {
JumpPair jumpPair = new JumpPair(new Label(), new Label());
recurStack.push(jumpPair);
load(mv);
mv.visitJumpInsn(IFEQ, jumpPair.nextLabel());
mv.visitLabel(jumpPair.thisLabel());
}
case ']' -> {
JumpPair jumpPair = recurStack.pop();
load(mv);
mv.visitJumpInsn(IFNE, jumpPair.thisLabel());
mv.visitLabel(jumpPair.nextLabel());
}
case 'z' -> {
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ILOAD, 0);
mv.visitInsn(ICONST_0);
mv.visitInsn(IASTORE);
}
}
}
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
writer.visitEnd();
return writer.toByteArray();
}
private static record JumpPair(Label thisLabel, Label nextLabel) {
}
private static int count(char c, ListIterator<Character> programIterator) {
int count = 1;
while (programIterator.hasNext() && programIterator.next() == c) {
count++;
}
programIterator.previous();
return count;
}
private static void chooseNumberInsn(int number, MethodVisitor mv) {
switch (number) {
case -1 -> mv.visitInsn(ICONST_M1);
case 0 -> mv.visitInsn(ICONST_0);
case 1 -> mv.visitInsn(ICONST_1);
case 2 -> mv.visitInsn(ICONST_2);
case 3 -> mv.visitInsn(ICONST_3);
case 4 -> mv.visitInsn(ICONST_4);
case 5 -> mv.visitInsn(ICONST_5);
default -> {
if (number > Byte.MIN_VALUE && number < Byte.MAX_VALUE) {
mv.visitIntInsn(BIPUSH, number);
} else if (number > Short.MIN_VALUE && number < Short.MAX_VALUE) {
mv.visitIntInsn(SIPUSH, number);
} else {
mv.visitLdcInsn(number);
}
}
}
}
private static void load(MethodVisitor mv) {
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ILOAD, 0);
mv.visitInsn(IALOAD);
}
}
```
```
[Answer]
# Python 3 / gcc, 17.737/0.527 = 33.657
This simple solution is based on @l4m2's, compiling to C which is then compiled by gcc. It collapses blocks composed only of `<`, `>`, `+` and `-` as much as possible and also squashes the simplest possible loops, those which contain one block between `[` and `]`, have no overall data pointer movement, and change the loop counter by \$\pm 1\$.
A few years ago I wrote a much more complicated optimizing BF compiler (see comments above for the link) but the result is no faster than this on the Mandelbrot program.
```
#
# Python 3
#
import os
import sys
src = open('/tmp/bf.c', 'w')
print("""#include <stdio.h>
unsigned char b[100000];
int main(void)
{
unsigned char *p = b + 50000;
int c;
""", file=src)
def output_bb():
global bb, ptr
if start == '[':
print(" while (*p != '\\0') {", file=src)
elif start == ']':
print(" }", file=src)
elif start == '.':
print(" putchar(*p);", file=src)
elif start == ',':
print(" *p = ((c = getchar()) == EOF ? '\\0' : (unsigned char)c);", file=src)
else:
assert start == '*'
for ofs, diff in bb.items():
if diff != 0:
print(f" p[{ofs}] += {diff};", file=src)
if ptr != 0:
print(f" p += {ptr};", file=src)
bb = {}
ptr = 0
def optimize_bb():
global bb, ptr
for ofs, diff in bb.items():
if diff != 0 and ofs != 0:
print(f" p[{ofs}] += {-diff * bb.get(0, 0)} * p[0];", file=src)
print(" *p = '\\0';", file=src)
bb = {}
ptr = 0
bb = {}
ptr = 0
start = '*'
for ch in sys.stdin.read():
if ch not in {'[', ']', '+', '-', '<', '>', ',', '.'}:
continue
if ch == ']' and start == '[' and ptr == 0 and bb.get(0, 0) in {1, -1}:
optimize_bb()
start = '*'
elif ch == '+':
bb[ptr] = bb.get(ptr, 0) + 1
elif ch == '-':
bb[ptr] = bb.get(ptr, 0) - 1
elif ch == '<':
ptr -= 1
elif ch == '>':
ptr += 1
else:
output_bb()
start = ch
output_bb()
print(""" return 0;
}""", file=src)
src.close()
os.system("gcc -s -Wpedantic -W -Wall -Wextra -O3 -march=native -o /tmp/bf /tmp/bf.c")
```
] |
[Question]
[
Typescript is a typed superset of Javascript. For this challenge, we'll consider the following classic [basic types](https://www.typescriptlang.org/docs/handbook/basic-types.html):
* `string`
* `number`
* `boolean`
* `undefined`
* `null`
And two "meta" types:
* `any`
* `never`
The type `any` annotates that any type is valid:
```
const a: any = "foo";
const b: any = 42;
const c: any = true;
const d: any = undefined;
```
Whereas `never` annotates that no type is valid:
```
const e: never = <no valid literal assignment possible>;
```
We'll also consider two compositions of types: [unions and intersections](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html), annotated as `|` and `&` respectively.
A union type expects either one or the other type:
```
const f: string | number = "foo";
const g: string | number = 42;
```
While an intersection creates a combination of both types:
```
const h: string & any = "foo";
const i: string & any = 42;
const j: string & number = <no valid literal assignment possible>;
```
The order of operands within unions and intersections doesn't matter, `string | number` is equal to `number | string`.
## The challenge
Given one of the above type declarations, return the resulting resolved type. The input will be one of the following:
* a basic type as listed above or;
* a meta type as listed above or;
* a union of two basic and/or meta types or;
* an intersection of two basic and/or meta types.
## Examples
```
// All basic and meta types simply map to themselves
string → string
number → number
any → any
never → never
// Unions between basic types create unions except with themselves
string | number → string | number
string | undefined → string | undefined
string | string → string
// Intersections between basic types create never except with themselves
string & number → never
string & undefined → never
string & string → string
// Unions with any create any
any | string → any
any | never → any
// Intersections with any result in any except with never
any & string → any
any & number → any
any & never → never
// Unions with never yield the other half
never | string → string
never | any → any
never | never → never
// Intersections with never return never
never & string → never
never & any → never
never & never → never
```
A good way to get a feel for the types is to try out [the Typescript playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAEg9gNwgJwLLQLxQM7GQSwDsBzKAMikIiWQG4g).
Any reasonable and consistent input-output format, standard loop holes, [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
[Answer]
# [Python 3](https://docs.python.org/3/), 261 bytes
```
lambda x,o="&",y="":("any"in x+y)*(o<"|")*-~-("never"in x+y)*"any"or(lambda r:r==31and"any"or"|".join("ubsnnnotuudormleliblfene iagr nn e d"[i::5]for i in range(5)if r&2**i)or"never")(eval(o.join(str(min(31,2**"dormlyv".find(k[2])%64))for k in[x,y or x])))
```
[Try it online!](https://tio.run/##ZVDNjpswED7DU4wsFdksQcqm2wNa@iI0B6eY1F0YIxuiIEV99XTAQMjuATP@5vsZTzt0fwwe7lX@617L5lRKuCYmZxFLhpyxjDOJA9MI15dBxNy8sxsT8e7fjjNUF2XX1sQzls8mNrN5fthLLOcG6dK/RiNn/ckhoun6vjS2qVWtT3WlUIGWZwuIAKDog5IVOsvejpWxoIFyrMSz4m9CV2Cj1zjWgmz9FIKri6y58RGus7yh/2GfEI1NMcOFpZXGkn8Ur0fx7cd3IUbjDzIurskAVF@PQoi7blpjO3CDC8ORUetxNByB1HWlxtQqWXKRurbW3dh1XGRhICGfuB7nIgyscoRVPJZFttsfBQnbWv5WnAFLgDGiSOcUhU3MHGRBtDBorcZuURFx95PoRBF3epjGcxAEvgixb07K0t0XIa2aLnSG01rGxvgPPR1usAg8cJtla7vHUtGSVBms1W2OWjnLDM94tFo/JUYby0@NTz409MZ8fIJH5ocsQPSF8kjeIF7kE6fz6@ALPO1sXdkjcSt@pD6jk/YZ2qr/Aw "Python 3 – Try It Online")
-1 byet thanks to ovs
[Answer]
# JavaScript (ES6), ~~113 110 106~~ 99 bytes
```
f=b=>(N='never',[x,o,y]=b.split` `,X=x<f?2:x!=N,Y=y<f?2:y!=N,!y|x==y?x:X*Y>1?'any':o>f?X?Y?b:x:y:N)
```
[Try it online!](https://tio.run/##dVExTsMwFN1zik@H2kYhKowBN1MZu2RpVZBIE6e4Su1gp1Uiyg2QWBjhHpyHC3CEkjRBtVvhIYrfe37vfXsZbSIdK54XF0ImbLdL6ZwO8ZgiwTZMIXdWutKt7unc03nGiwd4cCe0vEmDK788o2N3Sqv9pmo2Z9W2pLQKSn9yPh1eBigSFfLlMA0mwTSY@6Vf@WOyU@xpzRXDKNWIeIpFyS3PWFiJGA@IV8iwUFwsMGkjce9O9IiXSjWK4kesgQ7h2QEIgYL2dMZjhgcuXDVHFV9hcl2TrMxZXLDE0NSChoml0DJjXiYXeBa6oFjtCCkOSfdPD4cDQD9fb98f7/UXgQ/o@/MV3XurKG9raLNsHiUjkTQxxFtKLjBChDgvZKf3CrBWizlivZozZVMt5tRXB8erxpz9uxzhe8zpcrZguB5hB81aJCzloh4STrGDzOjeVe6Qvpli5fdN7yPm1K4Z04rpxmxxe9g/vP@P3upk45ZPW6rF7Oy/Z@ko8w0Od2/XMs3sYjZjetnMidsv "JavaScript (Node.js) – Try It Online")
### How?
Although this function is not recursive, it is named explicitly and uses the argument `b` so that we can test if a string is *any* (which is the first of all types in lexicographical order) by comparing it with \$f\$. The same trick is used to distinguish between `&` and `|`.
```
f = b => ...
```
We load the first type in \$x\$, the operator in \$o\$ and the second type in \$y\$. Both \$o\$ and \$y\$ may be undefined if only one type is passed in the input string.
```
[x, o, y] = s.split` `
```
The pair of strings \$(x,y)\$ is turned into a pair of integers \$(X,Y)\$ by applying the following rules:
* if the type is *any*, map it to \$2\$
* if the type is *never*, map it to \$0\$
* if the type is anything else, map it to \$1\$
```
N = 'never'
X = x < f ? 2 : x != N
Y = y < f ? 2 : y != N
```
We then apply the following logic:
```
!y | x == y ? // if y is undefined or x = y:
x // return x
: // else:
X * Y > 1 ? // if X * Y > 1, which means that one of the types
// is 'any' and the other one is *not* 'never':
'any' // return 'any'
: // else:
o > f ? // if this is a union, i.e. o = '|':
X ? // if X is not equal to 0:
Y ? // if Y is not equal to 0:
b // return the original union
: // else (Y = 0 / y = 'never'):
x // return x
: // else (X = 0 / x = 'never'):
y // return y
: // else (intersection):
N // return 'never'
```
[Answer]
# C++ TMP, ~~476~~ 466 bytes
I'm surprised I got this far with it. `U` is union, `I` is intersection, `R` is the solution function that defines the solution type `t`. [Online version with tests.](https://godbolt.org/z/KcK4nfKs4)
```
#define Z template
#define C class
#define K Z<C A>C R
#define T(x){public:using t=x;};
C string;C number;C boolean;C undefined;C null;C any;C never;using X=any;using Y=never;Z<C...>C U;Z<C...>C I;K T(A)K<U<A,A>>T(A)K<I<A,A>>T(A)Z<C A,C B>C R<I<A,B>>T(Y)K<U<A,X>>T(X)K<U<X,A>>T(X)K<I<X,A>>T(X)K<I<A,X>>T(X)Z<>C R<I<Y,X>>T(Y)Z<>C R<I<X,Y>>T(Y)K<U<A,Y>>T(A)K<U<Y,A>>T(A)Z<>C R<U<Y,X>>T(X)Z<>C R<U<X,Y>>T(X)Z<>C R<U<Y,Y>>T(Y)K<I<Y,A>>T(Y)K<I<A,Y>>T(Y)Z<>C R<I<Y,Y>>T(Y)
```
I'm certain this could be compacted further, maybe even to around 350 bytes. If anyone wants to give it a try, here is the version without preprocessor directives:
```
struct string;
struct number;
struct boolean;
struct undefined;
struct null;
struct any;
struct never;
using X=any;
using Y=never;
template<class A>struct T{using t=A;};
template<class...>struct U;
template<class...>struct I;
template<class A>struct R:T<A>{};
template<class A>struct R<U<A,A>>:T<A>{};
template<class A>struct R<I<A,A>>:T<A>{};
template<class A,class B>struct R<I<A,B>>:T<Y>{};
template<class A>struct R<U<A,X>>:T<X>{};
template<class A>struct R<U<X,A>>:T<X>{};
template<class A>struct R<I<X,A>>:T<X>{};
template<class A>struct R<I<A,X>>:T<X>{};
template<>struct R<I<Y,X>>:T<Y>{};
template<>struct R<I<X,Y>>:T<Y>{};
template<class A>struct R<U<A,Y>>:T<A>{};
template<class A>struct R<U<Y,A>>:T<A>{};
template<>struct R<U<Y,X>>:T<X>{};
template<>struct R<U<X,Y>>:T<X>{};
template<>struct R<U<Y,Y>>:T<Y>{};
template<class A>struct R<I<Y,A>>:T<Y>{};
template<class A>struct R<I<A,Y>>:T<Y>{};
template<>struct R<I<Y,Y>>:T<Y>{};
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 120 bytes
```
never \| (\w+)|(\w+) (\| never|[|&] \1)
$1$2
any & never|never & any
never
any [|&] \w+|\w+ [|&] any
any
\w+ & \w+
never
```
[Try it online!](https://tio.run/##hVNLTsMwEN3nFLOoIqouqnIDlhyAFWXhJlNqyZlG9qQhktccgCNykeBf82kDLGzZ7734vbEnGlmS6HvCC2rYW3jYt5u1DbNbWwiEfbX5G@x362y1Wz1mgjrIExM/zMFhWVgHNurbjXUjbjzvhwdyT0V132@38KQUHISRhVOVUCEL4K5GA0ZWteqgEjXwGfiElUF1QZMZ1pLe4fvzC@Iyo6Y6uCAeicuQw2@HZJEMGTPn@kLyTAYOyC0ipQDRt9AoGKGJCvwosGZoJZ8WMliYWN9go6ahEo@SsJzLBnhU3pfmwz4TozZY8H@ZY6V/R86nkeOFDMw86A25nC1dZDDzl56SpBeflzSC45N47L7G4TiNplEMksJuWtnYb/mSx6zMCfh7L4ynQidRlf7u4OwmDSehjqmNlt7oytw3nV00XKg1yjRyoykprz/XxG9OXO3m6I3hDw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
never \| (\w+)|(\w+) (\| never|[|&] \1)
$1$2
```
Simplify unions with `never` and self-unions and intersections.
```
any & never|never & any
never
```
Simplify intersections between `any` and `never`.
```
any [|&] \w+|\w+ [|&] any
any
```
Simplify any other intersections of `any`.
```
\w+ & \w+
never
```
Simplify any other intersections.
] |
[Question]
[
Sequel to [Verify Tents and Trees solution](https://codegolf.stackexchange.com/q/206786/78410).
## Background
**Tents and Trees** (try [here](https://www.brainbashers.com/tents.asp)) is a puzzle played on a square (or rectangular) grid, where the objective is to place tents horizontally or vertically adjacent to each of the trees, so that no two tents touch each other in 8 directions (horizontally, vertically, and diagonally) and the number of tents on each row/column matches the given clues.
### Example puzzle and solution
In these examples, trees are `T` and tents are `A`.
```
Puzzle
2 0 2 0 2 1
2 . T . T . .
1 . . . . T .
1 T . T . . .
2 . . . . . T
1 T . . . . .
0 . . . . . .
Solution
2 0 2 0 2 1
2 . T A T A .
1 A . . . T .
1 T . T . A .
2 A . A . . T
1 T . . . . A
0 . . . . . .
```
## Challenge
Given a grid with some trees, determine whether it is possible to place tents next to each of the trees so that they don't touch each other in 8 directions. Ignore the number clues in this challenge.
You may take the input in any reasonable way to represent a matrix containing two distinct values to represent a tree and an empty space respectively.
You can choose to follow your language's convention of truthy/falsy, or use two distinct values for true/false respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
This uses the same notation as the above example; `T` for trees and `.` for empty spaces.
### Truthy
```
. . .
. . .
. . . (empty board)
T .
. T .
. . T
. .
T T
. .
. T .
T . T
. T .
. . .
T T .
. T T
. . .
. T . .
. . . T
T T . .
. . . .
. T . . . .
. . . . . .
. . T . . T
. T . T . .
T . T . . .
. T . . T .
```
### Falsy
```
(No space to place a tent)
T
T . T
T . T
. T .
. . . .
. T T T
T . . .
. T .
T T .
. T .
T . T
. . .
. T .
T . . . .
. . T . .
. T . T .
T . T . .
. T . . .
. . . . .
. T . . .
. T T . .
. . T T .
. . . . .
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~253~~ 244 bytes
```
from itertools import*
f=lambda b,h,w:all(set(t:=[i%w+i//w*1jfor i,e in enumerate(b)if e])&set(s:=[*map(sum,zip(t,T))])or~any(abs(a-b)<2for a,b in combinations(s,2))+all(h>a.imag>-1<a.real<w for a in s)for T in product(*[[1,1j,-1,-1j]]*sum(b)))
```
[Try it online!](https://tio.run/##bVLRkpsgFH33Kxh2tgFD3HX70snEfewX8GacDhpsyCo4gOukD/31FNCo2Sk6eDncc@5Bbne1ZyW//@j07VZr1QJhubZKNQaItlPaxlGdNawtTwyU5EyGPWsaZLhFdp/l4nnYipeXIU4vtdJAEA6EBFz2LdfMclRiUQNe4G@eYBwhblmHTN@SP6JDllCMC6z0XyaviJUGsV2JD29eipHSS1WqLYVkVihpkCFvGG99/fM7S0TLfr/v0gNLNGfNYQCB5kkG@5D6sNPq1FcWxXmekvRCdql7L0UROw/OHca3ihluMghhAtwTreeI@ikBdEKoXyQOpeE77dCwM8YTkU6UKXPOvSs7mD6sl4Q1OMd0Io0RnWrMjJkbLNBosvQfZ3dXwcC68MpyshCTR@iLocXOYmY5RhStz0Afqi8ydH1adwlR1GkhLYJU9/Z83UMc@bv0l/TLWB1awl9YYrpGuLSjPEqI9xFww7XanJdlAFI44n5Mqkf5kzWGB90vlPy1CKynFatS0grZ8wA8jSLrGN3Jo1qVbfJ8A7azpuvMrmEV94UhgQXJIV6wxEGvZI1Qh6QOcRKbotgE0VIxfQIZ4J@sQdVYaCxeo/wjNL1Wg/8xY6YHPvzSoQUBDZcobOBV7M7qW/8f "Python 3.8 (pre-release) – Try It Online")
*-6 bytes thanks to @user202729 (chain comparisons)*
*-3 bytes thanks to @ovs (`1jfor`; `…or a+1^b` → `…or~a+b` for "implies" boolean operator)*
```
# Itertools for combinations and product
from itertools import*
f=lambda b,h,w: all(
# Test if a given set of tent position deltas works:
# Positions are complex numbers: real part increasing to the right, imaginary part increasing down
# (De Morgan shortened, so many expressions negated)
# No tree is on a tent:
# t:=Tree positions (1s)
set(t:=[i%w+i//w*1j for i,e in enumerate(b)if e])
# s:=Tent positions as sum of tree positions and deltas
& set(s:=[*map(sum,zip(t,T))])
# and difference between all distinct pairs oftrees is at least 2:
or any(abs(a-b)<2for a,b in combinations(s,2))
# and all trees are within rectangular boundary
# (Using Python 2's quirky complex floordiv doesn't work since those return complex nums,
# which don't have a total order.
# Plus Python 38 has saves so much here; using 2 would be a waste anyway)
>= all(h > a.imag > -1 < a.real < w for a in s)
# For each possible delta (four directions, distance 1)
# sum(b) is the number of tents since each tent contributes 1
for T in product(*[[1,1j,-1,-1j]]*sum(b))
)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 82 bytes
```
WS⊞υι≔⟦⟦⟧⟧θFLυF⌕A§υιT«≔⟦⟧ηFθ«υFλ«J§μ⁰§μ¹A»F⁴«JκιM✳⊗μ¿›⁼.KK№KMA⊞η⁺λ⟦⟦ⅈⅉ⟧⟧»⎚»≔ηθ»ILθ
```
[Try it online!](https://tio.run/##VZDPS8MwFMfPzV8RenqBGBS8eSqbysTBwB6U0kPdsjUsTdY0mYL0b6@v6To0h4TvN@993o9tXbmtrfQwfNVKSworcwr@zTtlDsAY3YSuhsCpYg8k6zp1MFAUZclpi8beOgqv0hw8xmBw1E/K7DKtIfMrs5PfUzKnaZ5ixA9JZgoyamQkMamNX8kGy3pEoT35evKTl9CccntlNpzeIvOPvGMx6UJIszTKfubc/@ccp4HQWNuzhKVycuuVNbC04VPLHTTswlN7Cs9OVl46eGxDpTtIRcrpRsoj7ofThQ1YcJRra52EcVSsPq@uxlAdOtCcFsX7@PsBrCzZtb2FlpWDUfbX3dTTensyTbOoOj@vuR0bGwaRCzxEiMuDMid440viLUj0BBluzvoX "Charcoal – Try It Online") Link is to verbose version of code. Takes input as newline-terminated strings and outputs the number of solutions. Explanation:
```
WS⊞υι
```
Read in the grid.
```
≔⟦⟦⟧⟧θ
```
Start with 1 solution for 0 tents.
```
FLυF⌕A§υιT«
```
Loop over the positions of the trees.
```
≔⟦⟧η
```
No tent positions for this tree found so far.
```
Fθ«
```
Loop over the tent positions for the previous trees.
```
υ
```
Print the grid.
```
Fλ«J§μ⁰§μ¹A»
```
Print the tents for this partial solution.
```
F⁴«
```
Check the four orthogonal directions.
```
JκιM✳⊗μ
```
Move to the relevant adjacent square.
```
¿›⁼.KK№KMA
```
If this square is empty and is not bordered by a tent, ...
```
⊞η⁺λ⟦⟦ⅈⅉ⟧⟧
```
... then append its position to the previous partial solution and add it to the list of new partial solution.
```
»⎚
```
Clear the canvas after testing this tree.
```
»≔ηθ
```
Save the new solutions as the current solutions.
```
»ILθ
```
Print the final number of solutions.
] |
[Question]
[
Inspired by [Find the largest fragile prime](https://codegolf.stackexchange.com/questions/41648/find-the-largest-fragile-prime)
A recurring prime (or whatever you choose to call it) is a prime that, when removing leading digits, always remain prime regardless of how many digits are removed.
```
for example
6317 is a recurring prime because...
317 is a recurring prime because...
17 is a recurring prime because...
7 is a prime
```
727 is a prime but not a recurring prime because 27 is not a prime.
**Goal**
Like the original question, your score is the largest recurring prime found by your program/ algorithm.
**Rules**
I copied these from the original question
```
You may use any language and any third-party libraries.
You may use probabilistic primality tests.
Everything is in base 10.
```
Edit: Welp... turns out I have not factored in adding zeros in this question. Although I have not thought about adding 0 at first but it indeed satisfy my requirements, since removing a digit in front of (any number of) zeros skips many digits of prime tests and returns trivially true if the last few digits is a recurring prime. To make this question less of a "zero spam" but also reward strategic use of zeros, **at most 2 consecutive zeros can be present in your answer**. (Sorry to Level River St who asked me this)
[Answer]
# [Python 3](https://docs.python.org/3/), 79 digits (probably optimal)
A simple depth first search that allows up to two consecutive zeros.
```
from sympy.ntheory.primetest import isprime
def dfs(n=0, k=1):
yield n
if 100*n > k:
yield from dfs(n, k*10)
for i in range(1,10):
if isprime(k*i + n):
yield from dfs(k*i + n, k*10)
l = 1
for prime in dfs():
if prime > l:
d = len(str(prime))
print(f'{d} digits: {prime}')
l = 10**d
```
[Try it online!](https://tio.run/##bY/BjsIgGITvPMXcpKwxoIdNTOq7uAGUtP1pgAsxPnuXYrWayAX4Z@YbGHO6ejpMkw1@QMzDmHeUrsaHvBuDG0wyMcENow9li3XEmDYW2kZOrdyia1VzZCgrO9NrUD07CyWlIJzQPdTVUbtqvqSFkk3VrQ9wcIRwpovhaluENVl4Sz3vhMMP6E38gl5MzwLWo4Vic0eFzD2zbYEU@mN8Qr9idcn0hnhMgVe5aV5auVPidnPTd2h3cSkecaum@2Z11VYphH7/R8G2@N1/Pv8vmHM3Tf8 "Python 3 – Try It Online") [Validate the result!](https://tio.run/##rY47DsIwEESv4gNQTGxnEzqOADWisFAkUpgCuUOc3awVhAAZ@ZdmvLvzZmRr3GWyxs1n4/3@Nl/dkdVOB7ETd7UREmCl5RnxGjTe4xb42Ajf@wj8nobITSF27VmjBm9/PQUk7ATRpRHWDErnYayZJG/58FBEE8p4VRqg4oQsj@iKDAWyJlYZ7MOpMrt4DfHGgq65QaK9Qwd4ja9glabHyfsn)
Finds `200400201909005006060042636079002004200130030090050030780060900408062003` (72 digits) in 8 seconds on TIO. I let the program run on my computer a little longer and the highest recurrent prime it found is `7030560306007020600400306654060053003909007054300609009069003056030702030330347` ([validation](https://tio.run/##rYw5DsIwEEWv4gNQfGW8KB1HgBpRWCgSKUyB3CHObmxCxBaMt8LLvPn/GW2Pg9F2PGjnNufxZHf@NsOWrdlFrRj3h@4Xpmd@Mf86PP8KrxPhfZb4JOIbERZgDyxy@WvRI7JCZCsR3xPwL8ITMiIlpJAU8zw5mZ6lrLDnOXmRW5BAdoejpCXKarK0V1okFFd54MVt36kTdKhWhKlaIoEmHkIrUyCtXKKl7AFb6RSaCq97524)). The program actually completed after finding this number, so this is probably the longest prime meeting the challenges requirement.
Note that sympys [`isprime`](https://docs.sympy.org/latest/modules/ntheory.html?highlight=isprime#sympy.ntheory.primetest.isprime) could theoretically return `true` for pseudoprimes `>2^64`, though no examples are known as of now.
---
# [Python 3](https://docs.python.org/3/), 24 digits
only considers numbers without zeros
```
from sympy.ntheory.primetest import isprime
def dfs(n=0, k=1):
yield n
for i in range(1,10):
if isprime(k*i + n):
yield from dfs(k*i + n, k*10)
l = 1
for prime in dfs():
if prime > l:
print(f'{len(str(prime))} digits: {prime}')
l *= 10
```
[Try it online!](https://tio.run/##TY7LDoMgEEX3fMXdFa1pNN2Z2H9pIrQTcTDAhhi/3QK1j9lA7lzOYYnhafm679rZGT7OS7xweCrr4mVxNKugfADNi3Xp8CUSYlQao/aSh7bBNHRVL5AmkjIjuNy1dSAQw935oWTXdO3RykP6A5NTTTiD/5Y/VPlUFh2lJKsTRwiDAZ3IjgLJnlw7IIn@jm8wP2yKOEh9Wo1i6YOTpVNVG0Z6UPA91pJsp@r7xqBOonbfXw "Python 3 – Try It Online") [Validate the result!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvJBpI5qYGKjgoVJvrKBgDsSGIsASTRhDKDEqbwxhmcJYpgmmGxDZE5hih8MxQuSZofDN0ASMMEUNMIWMsYmbYBC2wipphFzbHIW6KXaI29v9/AA)
Finds `357686312646216567629137` in less then a second on TIO.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
F37⊞υιFυFE⁹⁺⊕κι¿⬤…²Iκ﹪Iκλ«κD⎚
```
[Try it online!](https://tio.run/##RU5LCsIwEF23pxi6mkCEqguRrqRuBAvFG4Q2/eA0Kfm4Ec8ekyK4mXm8H6@bhOm0oBAGbQCL46lg0Ho7oecwsyrfaM9g@41Y8cyhJW/xpjojF6mc7PHJkpkxmAfACxE@hBolHjjUwrooR73RvSeNP4IDJf87z1ozq8RUeXb1y4oJ1CSF2VAqvEtr41Gji6ticl@W7D8yJT8hhN2Lvg "Charcoal – Try It Online") Finds all zero-free recurring primes, but is inefficient, so the TIO link is limited to just under 60 seconds' worth of primes. Explanation:
```
F37⊞υι
```
Start with the two possible last digits of all recurring primes (except the trivial `2` and `5`).
```
Fυ
```
Perform a breadth first search of recurring primes as they are found.
```
FE⁹⁺⊕κι
```
Prefix each non-zero digit to the prime so far.
```
¿⬤…²Iκ﹪Iκλ«
```
Use trial division to find out whether this is a new prime.
```
κD⎚⊞υκ
```
If it is then output it and add it to the list of recurring primes.
] |
[Question]
[
# Challenge
Design a compression algorithm specialized for compressing ASCII mazes. You will need to create both a compression algorithm and a decompression algorithm. Your score will be based on the size of your compressed mazes.
# Mazes
These mazes are made primarily of the characters (floors), `+`, `-`, `|`, and `#` (walls), and *exactly one* each of `^` (start) and `$` (end). They may also contain ASCII letters, which count as floor tiles. For the purposes of this challenge, mazes do not have to be solvable and the actual meaning of maze contents is irrelevant.
* `+` will be used for wall cells where there is at least one horizontally adjacent wall cell and at least one vertically adjacent wall cell.
* `|` will be used for wall cells where there is at least one vertically adjacent wall cell, but no horizontally adjacent wall cells.
* `-` will be used for wall cells where there is at least one horizontally adjacent wall cell, but no vertically adjacent wall cells
* `#` will only be used for wall cells that are not orthogonally adjacent to other wall cells.
All mazes are rectangular, but do not necessarily have a regular grid/wall alignment.
# Mazes To Compress
Maze 1
```
+----+----
| o | |
| -- | o--+
| | | $
--^-+-+---
```
Maze 2
```
+-----+---+
| a | |
^ +-+-+ # |
| | | B |
| | | --+ |
| c | $
+-------+--
```
Maze 3
```
----------+-+-+-----+-+
^ | | | | |
+-- --+R # | |p| | | |
| | | | | |
+---+ +-+-+-- +-+ | | |
| m| | | | | | | |
| +-+ | | | | | --+ | |
| | | h | | | | |
| | | | | | # --+-+ |
| | | | | | S| $
+-----+-+-+-+-+---+----
```
Maze 4
```
+-----+---+-+---+-------^-----+
| |x | | | tsrq |
+-+-- +-- | +-- # --+---- --+
| | | | | |
| | | | | +-+-+---+ | +-- | +-+
| | | u | | | | | | | | |
| +-+ | | | | +---- +-+---+ | |
| | | | | y | w |
| | --+ | --+ +-- | +---- | | |
| | | | | | | | | |
+-- --+ +-+ | | | | +-- | +-+-+
| | | | | | | | | |
$ | --+-+ | --+-+ | +-+-+-- --+
| | | z| | | v |
+-+---+-------+---+---+-------+
```
Maze 5
```
++ -----------+
++- Beep|
$ ----+---+--+
+-+boop| | |
| +--- | | | ++
| | | +++
+------+-+--+ ^
```
Maze 6
```
+-$---------------+-+--
| | |j
| |l ---- # ---+ | |
| | | m | +--+ |
| | | +-+---- # |
| | | | | +----+ |
|o| | | | +----+ | |
| | | | -- | |
| | | | | | -+ | | |
| | | | | | | +--- | |
| | | | +- | | | | ++
+-+ |n| | | ++ +--+ |
| | -+- | | | +-
+---+ +--- | | | ^
| | --+ --+ | |
| -- | | k | | ++
| | | +--- | ++
| | | | | |
+-- -+---- | +----+--+
```
Maze 7
```
+---+-+-------------+-+^+-----+-------+---+-+---+-+---+-+---+
| |c| | | | c | | | | | | |c| |
+-- | | +-- +-- # | | | +-- --+ +---- +-- | +-+ | | +-+ | --+
| | | | | | | | |c| | |
| | +-- | +-+-- +-+ +-- # +- # -+-- +-- | | --+ | | | | --+C|
|c| | | | c | | |c | | | |
+-+-+---+-+-----+---------+---------+---+-------------+---+$|
```
Maze 8
```
------+-+-+---+-+---+-----------+---+-----+---------------+-+
^ | | | | | | | | | r | |
+-- | | | t | | +-- +----- # ---+-- +-- --+-- ----+-+ --+ | |
| | | | | | | r | | | | | |
| | | | | +-+ --+ --+-- --------+-- | ----+ --+ | | | --+ | |
| |r| | rotation | | | | | | $
+-+-+-+-----------------------------------+---+-+---+---+-+--
```
Maze 9
```
|$|^--+-+---+-----+-+---+-+-+---+---+-+---+-----+
| | | | | | | | | | f | | | | |
| +-+ | | # +-+ --+ +-+ | | | # | +-+ +-- | ----+
| | | | f| | | | | | f |
| |F+-+ | | | | +---+ | | | ----+-+ | | --+ --+-+
| | | | | | | | | f | | | |
| | | | +-+-+---+-- | | | +-+-+-+ +-+ +--- # -+ |
| | | | | | | | | | | | | | |
+-+-+ | +---+ --+ | +---+-+ | | --+ f | | | | --+
| | | | | | | | | |
| --+f| | | +-- --+--f--+ --+ | ----+ | +-+ +---+
| | | | | | | | | |
+---+-----+-+-----+-----+---+-+-----------+-----+
```
Maze 10
```
+-----+-+-----------+
| q | | q |
|Q+-+ | +-+-+-+---- |
$ | | | | | q |
+-+ | | | | | +-- +-+
| | | | | | |
| +-- +-+ |q| +-+ | |
| q| | | | |
| | | +-- | +-+ | --+
| | | | | | | |
+-+-+-+ +-+-+ +-- | |
| | | |
+--- # -+ | | +-- | |
| q | | | | ^
+-+ +-- | | +-+ | +-+
| | | | |q| | |
| +-+-+ | +-+-- | | |
| | | | | | |
| | | +-+-+-- +-+ +-+
| | | | q |
+-+-+---------+-----+
```
# Rules, Assumptions, Scoring
* Standard loopholes are banned
+ Write a general program, not one that only works for the ten test cases. It must be able to handle any arbitrary maze.
* You may assume there will be exactly one entrance and one exit. Entrances and exits will always be on the border of the maze.
* You may assume that all inputs use walls that follow the rules enumerated above. Your compression algorithm does not have to work for mazes containing walls that violate those rules.
* Input mazes may or may not be solvable.
* You may assume the maze will be no larger than 100 characters in either direction.
* You may assume that letters will not appear on the edge of the maze. (since this is the case for the examples provided)
* Your score is the total size, in bytes (octets), of all of the compressed mazes.
+ You may use hex, base64, binary strings, or any similar format as a representation for your compressed maze if you find that more convenient. You should still count the result in whole octets, rounded up for each maze (e.g. 4 base64 digits is 3 bytes, 2 hex digits is 1 byte, 8 binary digits is 1 byte, etc...)
+ Lowest score wins!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), score = ~~586 541 503 492~~ 479 bytes
The walls are stored as a Huffman-encoded stream of bits describing whether a prediction function is returning the correct guess or not.
The special characters are stored as \$(d, c)\$, where \$d\$ is the distance from the previous special character and \$c\$ is the ASCII code.
[Try it online!](https://tio.run/##hVdtd9PGEv7uXzGUFEms5ViQpIEQeoBDTnva3p7b3Hv6wdgH4chYYEuOrCR2kPnrdGbfdyUXQWRpdnbe55nVp/Q2XU@rfFXHRXmVfZuWxbqGX/5/cfHHq//AOYx6AMFwGPRBXIeHMMSLUxNNFtSEqAn@SjKnJpw3SRIlRFATISGxJSRCbjL0qImUkFgSEimX1AqyoEpe27JE2ksCEi0hGRq50jZO1fYqbkFVvlleJMnQ8CZaQqLjoNzjVEsukjU16Y3Per1FVsOHvMB4h0Uf7iI4fwnFoC4v6yovPoZPosEqvbqs06oO7/oYtyCSm@7SxeJynq4y2lqVuLjpw5bv/4L6iOX2b@SRy6MtxJCMoWlgNI5GG3xSdObQ@z0RvrnczHnGo43cbt5pG9oCUGX1TVVAAHHDgpFaH8PP0oDH8AT3CXnPYYibdsKFVZVd5dPaslI4gXHow9xxZVXd/lXeKXMsV86MAQ82qObBFm8bOD@HO@LCly29zOVLKAQJ/x3XIngED9Qqp6Cd37judPoZNa/ryrao4uYgcbBeLfI6DN4VQTRYpquQs40Gg0E1jlQ0lenD8WCRFR/ruQ6zWJBUHk@VXblCIsNK5bYS71OMFH9nh6OYNePDQZ2t63AaRRGXkc8onIN1ucyczYKgd5Mama1Hj0xJhfSkCurBOZBY7jhAPSfHf8iL23SRX8Eyvc9@oBzseCXwmNDmbqtvlV4r85YulfcJ3JIbSp4KQiUkfSrzIgyCKNJPLmuVrRbpNAsPB1@S/tHu8GMf1rRTIttolVbr7NeiDtfUWm@Lq/BINFYfnkRjET6ea@4vJVhLHL0rGhaPSSSqNXR4HL67jIgcrvsYLVUndFE2qb2ng@k8rd4g0r6qQ10XdOW4GkwOHgaDvLjKNn/OMI3cCrpkbYeaH8ECLRflAi/h5Cn22XBz8QZBB0tar1C5P3de@3ASAXPkfM1xc458BbyAZwm@hAXKPB1ymcnFkPp1k7wdRij6a1xgiyTHnD2GZxi140iK4ynAIogGCFvLMLJxQZj@@mY2y6rBrCqXypeQTMCM/4RmcXPm8plyySjySjymv57ORUZPMaOiz3hW29k8NdkU@yMDpwGqSattQAuRxqGbot3i/JF3MT6Nub4prZGdXirh1KlF2cGioBHTc6w/le4Vlzrs6@SmV/heuI4QpCxyrCvk7vMtDHm4Qw6c4Obwp8gBEpckemIkUHpWVuGGfKRqC85MabxAaY9hfqY6/GtIBSm7RZfkhozg8hMCA0QLjD@SKB7o4RGat@GSI4EGQiFJ2pLHZ/jzApXAljGliBgEBHMrhQDk3JBJ@GM4AcxUOXfAozUzJrAe5YyNZUG6yPR9ODUQaEaqhFTlD1qIKRrxvOD5YHxm@yPNFfNcZeQEA4YzaLh5eoGNJYJ4RIWe8F7C3zO9LxZzIodDTEuD0xIff4S7MQkIIFCM6KKobfiyE1CxZxeIyueN90ZWrW5AbeExWvjynPe6spAbSBycTIafkrknxxHeR9T9T0/w73g8KvgoJj@eHfU0GuwMAnwHwGlwqllLUwyNSu1Ju75Z8rCTn@kAo/w2RTCgPsH@srCW897LoexOWeBDPKNmowfaa0Hw6vPlvVzJrlo7ER0IGwRIhIJJ4TOdmctFNliUH1VQ3/@BIxEOvoQ8sRb2WCe5J9HuObKs7ztXn0Y7@LDFSED8ErnIuu/whaiOO/GYDrdYBOt7UnyRbzLq192PEcoRfpwLlPsZgj9/CzCTwcWrX38Pdu97FoxTwLG1SSLPJCfbrr5/V/yvrNMFd@JmKc14LxCVH0T4xwOL8eI3wBzz2RM0ACVWKF6NRUOOBkpktvmQhTgPNA3ZJiiPJAb9ntbACc7OFLgKo2ECtI3BQ0crF/8aWjSU5tDQeW6MsUTo5ZqlJbG@mDSRP1kWqEvqFU@2RNL7F5pI9JXgcq0AvVM9OfvRaqmbftv7l43W3Sg7rHW9x8SgHS2aM1pGe11yoQ/c@077Jc8lUfyIMv1PFk47z2YtpnKI41bVQLMBy088s66ra/CiJaJEZUd3ZXEssuB4BTrmoCMnnzu819ZLyZzi8d2YKMC@aNrZEHYZuU3LPm3V1lh35/GJvaJKYi11f5XZd98@Wa2@lcr/zqwDuPVnx@9AWKYslNETWdqbj/vGzsdtK7@x1aXuu6oqBrHVt2Y3i2UMX2fZyrYSLHHM1vahLFfSFDeLKsTA/KiIUDDGfFThxjOY6No/iN2LM/jSnBptPtmI2yy43VjksoDof7uz8VqCSCRr1bbENGqUvbXPLwH69nrp1DHzkc9FNJDDoBtZhPWwZ10r6VxnsVV@TtRRaCH3MybdN/ExtsVSBBfWQt44lvjAWSb@JKOLGGULgz/9kOOzboxWtTjh7Vx3Y@j3qkiezoHVAxpTnfqaGMT1kde6OzY008avQjJkauGljy3T1gzTSMJ4rRlkUTE2qM1UXQrM6KgnAH9qgoPm0pJpswfRDaKJiSpsYryRzPzQs1I9v7GkTI2/05Zu@TR1J4y2y0EzO0/MylTsYVzsUg4a53zCvCzGHftZG228U0wDrbnTEXPx3WZVQyvPDdR2vg1EydjGEv/FRGjPPusc401mUuzbZtu7Z3KrBpVaZTR4Vu3W7TwdVW6V4UdPndZ5WbSwGbwz2IGXZz/@XZebQ2adQ5uDZuLm12ScdZyh2P6zhDO1Z@3VjtPKQx1FczJ4KGNrRbKVQ6tLZ363Gp0zN@IX/hnJZEedIRqd0S4/7UpV7zOvbroniY6gQ2HKT4EQHTvtHvFPRLbfXu9r/2LzbPk3s9Fn7xeD3w3eedz7HmMzB3vjeGb0x/p8K7ztyqcf3W4U9r5frHq10Yi1kMqdXy0O255rV/O17ed/7ZOmPA87Z1KnNq69vEDjnH3Znl5q47nmh@Za946bt@vmX/HKnoFx6/vCq28fX0Dd4z3nsD2Yrapa62@8OLv9OnFiZWY76/wm4juvu/xl1vfA/u@Vrq8Up1tltbLOcy/tvO6IlV9zvXF09u0f "JavaScript (Node.js) – Try It Online")
### Common
```
const HUFFMAN = [
'00', // 0000
'010', // 0001
'1001', // 0010
'11100', // 0011
'011', // 0100
'101', // 0101
'11110', // 0110
'100010', // 0111
'110', // 1000
'11101', // 1001
'1111100', // 1010
'1111101', // 1011
'10000', // 1100
'1111110', // 1101
'100011', // 1110
'1111111' // 1111
];
let bin = (n, w) => n.toString(2).padStart(w, '0');
let wallShape = (row, x, y) => {
let vWall = (row[y - 1] || [])[x] | (row[y + 1] || [])[x],
hWall = row[y][x - 1] | row[y][x + 1];
return ' -|+'[row[y][x] ? vWall * 2 | hWall : 0];
}
let predictWall = (row, x, y, w, h) => {
let prvRow = row[y - 1] || [];
return !x | !y | x == w - 1 | y == h - 1 | (prvRow[x] | row[y][x - 1]) & !prvRow[x - 1];
}
```
### Compression
```
let pack = str => {
let row = str.split('\n').map(r => [...r]),
w = row[0].length,
h = row.length;
let wall = row.map((r, y) => r.map((c, x) => +/[-+|]/.test(c)));
if(row.some((r, y) => r.some((c, x) => wall[y][x] && wallShape(wall, x, y) != c))) {
throw "invalid maze";
}
row = wall.map((r, y) => r.map((v, x) => predictWall(wall, x, y, w, h) ^ v));
row = row.map(r => r.join('')).join('');
row = row.replace(/.{1,4}/g, s => HUFFMAN[parseInt(s.padEnd(4, '0'), 2)]);
str =
str.replace(/[\n|+-]/g, '').replace(/ *(\S)/g, (s, c) => {
let n = c.charCodeAt(),
i = '^$#'.indexOf(c);
return (
bin(s.length > 63 ? 0xFC000 | s.length - 1 : s.length - 1, 6) +
bin(~i ? i : n < 91 ? (n > 80 ? 0x1F0 : 0x1E0) | ~-n & 15 : n - 94, 5)
);
}).trim();
return (
Buffer.from(
(bin(w, 7) + bin(h, 7) + row + str)
.match(/.{1,8}/g).map(s => parseInt(s.padEnd(8, '0'), 2))
).toString('binary')
);
}
```
### Decompression
```
let unpack = str => {
str = [...str].map(c => bin(c.charCodeAt(), 8)).join('');
let x, y, n, i, s,
ptr = 0,
read = n => parseInt(str.slice(ptr, ptr += n), 2),
w = read(7),
h = read(7),
row = [];
for(x = s = ''; s.length < w * h;) {
~(i = HUFFMAN.indexOf(x += read(1))) && (s += bin(i, 4), x = '');
}
for(i = y = 0; y < h; y++) {
for(row[y] = [], x = 0; x < w; x++) {
row[y][x] = predictWall(row, x, y, w, h) ^ s[i++];
}
}
row = row.map((r, y) => r.map((c, x) => wallShape(row, x, y)));
for(i = 0; str[ptr + 10];) {
for(
n = (n = read(6)) == 0x3F ? read(14) + 1 : n + 1;
n -= row[i / w | 0][i % w] == ' ';
i++
) {}
row[i / w | 0][i % w] = String.fromCharCode(
(n = read(5)) >= 0x1E ? read(4) + (n == 0x1F ? 81 : 65) : [94, 36, 35][n] || n + 94
);
}
return row.map(r => r.join('')).join('\n');
}
```
## How?
A maze is encoded as a bit stream which is eventually converted to a string.
### Header
The header consists of:
* the width \$w\$ on 7 bits
* the height \$h\$ on 7 bits
### Wall data
We walk through the entire maze and attempt to predict if the next cell is a wall or not, based on the previously encountered cells. We emit a \$0\$ if we are correct, or a \$1\$ if we are wrong.
This results in a sequence of correction bits with (hopefully) significantly more \$0\$'s than \$1\$'s. This sequence is split into nibbles and stored using hard-coded Huffman codes:
* `00` → `0000`
* `010` → `0001`
* `1001` → `0010`
* `11100` → `0011`
* `011` → `0100`
* etc.
To decode the wall \$W\_n\$, the decompression routine computes the same prediction \$P\_n\$ and toggles the result if needed, using the correction bit \$C\_n\$:
$$W\_n=P\_n\oplus C\_n$$
The final wall shapes are deduced in a way that is similar to [Nick Kennedy's answer](https://codegolf.stackexchange.com/a/181621/58563).
### Special characters
Each special characters is encoded as:
* The distance minus \$1\$ from the last special character (ignoring the walls):
+ on 6 bits if it's less than \$63\$
+ or as \$111111\$ + 14 bits otherwise (never used in the test cases, but required in theory)
* The code of the character:
+ on 5 bits if it's `^`, `$`, `#` or `[a-z]`
+ or \$11110\$ + 4 bits for `[A-O]`
+ or \$11111\$ + 4 bits for `[P-Z]`
[Answer]
# R, score 668 bytes
This takes advantage of the fact that the wall character is determined by its surroundings. As such, wall characters can be encoded as bits. The remaining info that needs to be stored are the dimensions of the maze, the positions of the start and finish and the positions of any other non-wall characters. Since the non-wall characters are ASCII, I've used the most significant bit of each byte to indicate whether there is another character that follows so that some of the words in the mazes don't have to have the location of each character stored separately. Note also that for mazes less than or equal to 256 characters (e.g. up to 16x16 or equivalent rectangular mazes), the positions can be stored in one byte, whereas for larger mazes the positions need two bytes.
### Utility functions
```
r <- as.raw
int_as_raw <- function(int, bytes = 2) {
if (bytes == 1) {
r(int)
} else {
do.call(c, lapply(int, function(.x) r(c(.x %/% 256, .x %% 256))))
}
}
raw_as_int <- function(raw, bytes = 2) {
if (bytes == 1) {
as.integer(raw)
} else {
sapply(
seq(1, length(raw) - 1, 2),
function(.x) as.integer(as.integer(raw[.x + 0:1]) %*% c(256, 1))
)
}
}
```
### Compression algorithm
```
compress_maze <- function(maze) {
maze_array <- do.call(rbind, strsplit(maze, ""))
simple_maze <- r(maze_array %in% c("+", "#", "-", "|"))
simple_maze <- packBits(c(simple_maze, rep(r(0), (8 - length(simple_maze)) %% 8)))
maze_dim <- int_as_raw(dim(maze_array), 1)
bytes_needed <- 1 + (length(maze_array) > 256)
start_finish <- int_as_raw(sapply(c("^", "$"), function(.x) which(maze_array == .x)) - 1, bytes = bytes_needed)
other_ascii_locs_rle <- rle(!(maze_array %in% c(" ", "+", "#", "-", "|", "$", "^")))
other_ascii_locs <- cumsum(
c(1, other_ascii_locs_rle$lengths[-length(other_ascii_locs_rle$lengths)])
)[other_ascii_locs_rle$values]
other_ascii_locs_length <- other_ascii_locs_rle$lengths[other_ascii_locs_rle$values]
encode_ascii <- function(loc, len) {
text <- charToRaw(paste(maze_array[loc:(loc + len - 1)], collapse = ""))
if (len > 1) {
text[1:(len - 1)] <- text[1:(len - 1)] | r(128)
}
c(int_as_raw(loc - 1, bytes = bytes_needed), text)
}
other_ascii_encoded <- Map(encode_ascii,
other_ascii_locs,
other_ascii_locs_length
)
other_ascii_encoded <- do.call(c, other_ascii_encoded)
c(maze_dim, simple_maze, start_finish, other_ascii_encoded)
}
```
### Decompression algorithm
```
decompress_maze <- function(c_maze) {
dim_maze <- as.integer(c_maze[1:2])
len_maze <- prod(dim_maze)
len_maze_b <- ceiling(len_maze / 8)
bit_maze <- rawToBits(c_maze[-(1:2)])[1:len_maze]
dim(bit_maze) <- dim_maze
bit_maze[-1, ] <- bit_maze[-1, ] | rawShift(bit_maze[-nrow(bit_maze), ] & r(1), 1)
bit_maze[-nrow(bit_maze), ] <- bit_maze[-nrow(bit_maze), ] | rawShift(bit_maze[-1, ] & r(1), 1)
bit_maze[, -1] <- bit_maze[, -1] | rawShift(bit_maze[, -ncol(bit_maze)] & r(1), 2)
bit_maze[, -ncol(bit_maze)] <- bit_maze[, -ncol(bit_maze)] | rawShift(bit_maze[, -1] & r(1), 2)
bit_maze[(bit_maze & r(1)) == r(0)] <- r(0)
array_maze <- c(" ", "#", "|", "-", "+")[(as.integer(bit_maze) + 1) %/% 2 + 1]
dim(array_maze) <- dim_maze
bytes_needed <- 1 + (len_maze > 256)
start_finish <- raw_as_int(c_maze[2 + len_maze_b + 1:(bytes_needed * 2)], bytes_needed) + 1
array_maze[start_finish] <- c("^", "$")
i <- 3 + len_maze_b + 2 * bytes_needed
while (i < length(c_maze)) {
loc <- raw_as_int(c_maze[i + 1:bytes_needed - 1], bytes_needed) + 1
i <- i + bytes_needed
text <- character(0)
while (c_maze[i] & r(128)) {
text <- c(text, rawToChar(c_maze[i] & r(127)))
i <- i + 1
}
text <- c(text, rawToChar(c_maze[i]))
array_maze[loc:(loc + length(text) - 1)] <- text
i <- i + 1
}
apply(array_maze, 1, paste, collapse = "")
}
```
[Try it online!](https://tio.run/##jVlLb9tGEL7vr5jKckFmSSdS0TYw6hwSoKf20CQ3QRJoiorYUKJE0rGd0r/dndn3LikjRKKsduf9@GbFNM/PDfyRQtZeNdk9Y@WhW2ftGte0u7075F1ZHyLcTuD2sStauIF5DP8xgHILkdq6gZncA2iINsblExRVW6jdTX2VZ1UV5QlU2fFYPUqJRv7VQ4ycOf4Ll68vYf7rbwnQWixjfEgge2IMDSP7kNuzD7d/0D50FJmLL0VDTANDW2mdWOO34hTN0OTi8KXbCXpIATfmcaIoPA8c2b6aBfrC4c31bBnD5atLyCPh4Uz4BWC8y@v9sSnadr3Pvheeg7QhXaDVOmua7JEIdGCb2/KwSaDtmvZYlZ2gT2AyERracn@sCiO0iRwZl@WB7JnwCZJf0EdKH/0o5zHLv74vuxYz5Zwk0BTHqInexAlEbzFCKl4OSRxTLt/KRArtm3JPEm29RbjjGBZTeJBYZHB9KIpNsSGGGQYyUgocangnKoVM7rKmW2/LQ9nuAg0quejtinycTuKgBO93Ze6KpcrBfZV1XV@uSaSx7nZFgzryslxXdY66Khnnqoh@Gos1kPZBwIVF@LGayDCFYklkfrdv7/ayPHMqzTHdUxmedpGqOL1EFC9JV7wYpfmWVXdFuxzzUbKTTS@a8KJYlFsc8npTSAKv4JFYNJ7u2654EC2f77Lmc/0Rs3nM2q5wwrtAlmviwwpBRspZvEwgryuEHGzwG90OEhqI5J3FBalhMbuODC@pG2722D@z@Vsp6EllwikyMuB8uSRComx4Yg1CK8MhCv3v7Bi50ZGIE8ZzfFdlx4DLGRUOKo9QEGMe6WZNwOt4t8vOcCOebYrziJavLaahfEPgIKckwfDPRZGiUxaJmnoTaTb3cH0rqqQoq/LwJTIsr0Fk7LbsLAxm959riWZSTxqhJuwHVKj5ltK4SPPFImxKrSNvkWLCRcEEOz2p@bQrt11kTw5NfW9FEtnPVFQG8l4g9DQMj0fVzc5rSCCd@ULlzpgcPMHUVlahFToPhYaEgYbw@Iy62TkNhkqdxwTUNICWcr69IWoBCibbGnYvDNimEoXjhTusbaI5YYO4jNBSF4IVOiiFM4NKWnB2PNkLjS7DucQvXc2o/DryhL/CaCwTH1eIzPN54SpaqgjosUe3I9r6JVQ1R@GuXCTEmYjjLEJ6PddzPdIlchLgjTpSCts90zEsZyxXFhFPYICP/VneFSrBxjatT5ULgrOP6tJ7WiWy6z@goAHX77GaDo4pMwflf0CSEuBkwZ9JFD2B//6AYQOdpFFeVqyshIaKGHrhUGNPz0QgbghNkW3@Kg9FKxR9qA@HQuItm/AUH/EBrMehgG2HT49r3OmhxkMmt@hkynB7hfTEwZjgE2tBlIHg7tkKiILDhRAkON@DWSO1WOMkEXKnSo6QxFhqHq4UiRUK1Y8SKVfETCI/ojb6fpSnUgEYSr0S9GiAkk3/Wvp9b2T3Wg/uGxprvnUMYGdkO/vqFG0S1nv2qLNPtDM1QeTGX7HjRddupxT/NDVpgf4BHJOxItvmBMpR6SDlkT61MakMGHO5dIjsd9cRY5iSJHbU@Z11CMJAuIGTeq2cnllapfXRar9X55JWJiw1UoYJdj@1flUYoRXaHy8hAH7qyf@p1KwtUN7LqA7i97134/fNxD91atv/jgnmkDrVjt9T5f77ojiSAeBwchJ4W9dHpUUGWEcDuHZIesE5120l7OCwooqapv4jzphbA0bGvwQIfSVMwNJRaaM/tvTx2YMMKzcVo5qWym1QSeKRmEP7tVcdXLe037KgsMhvLWkNBPtGmLfPUye5IjDIfFD0nCvzgVmdqWIRzAYy0lR1iThaaWCkhwhUYYMGTzz5asrJJMgLg7fv@6wrWAbTxEhWjgEFL5UrCxkhdDifQl2f92HCSWfuAEDYXLnBT9NKXKTZtpYOk4UdrktCNhHrB1DTDyDI05/3ASTZFpboLW3gokYt4Bmc1usPyJ1bf/KBLrXKfUg0djDuRTF1ou@vwqzg32mvxxoPEpKOsPJhj6rh18MAM0fCKZ7GSaxJWQ@dmzrb2CpsqcI2iXYWp51xGEwJUhTa4toXTBHdJkqL8lYkyG0gb8g2foFAU3cZXV4GiAXB6J4y7lwhXn78nEhUZP20X/mpssnjI6OZD0eaN1y2w1NnSF6YANmBdaHC5gSJeUNarrZhD1kdWxnEP8NRbAOtR1tvkuP64RaV/r4NUu5DrYmIt8O1H7JPHQ63fMNB7PqlOtDYn9q1Y//W7Xk2RJjRUWc1CujmWw/R0nRr9aXmGiS9cfMRRmsc29QN1Kknt/H5ABQM4A8OSfXJV3IiF/5x7yrqxiRuM14aTyqk0Hu3Ix6UsQVAcw79yZStDPGpH@16dwik5sYYlBZzCsSUeu8NCg/JdAEZ@b2Kg1/6K@ZIAxMR5lhwcu3lzg1veMN075VeoatC4CwoVmGQHRpeOid4hcJfhebnmX073ybiFYF6oysJbtQ7SkOu/rNE0Xvvqq8e6H8VfiKOZcyY/A06wuS9gYvZZkCnOBMI3tah0GNDP@f36pdoVV0Vp7usSkAzSE40WBKSI@rFr5aKv6mf/wc "R – Try It Online")
] |
[Question]
[
The question: Given an a number `n` ≥ 2, how many distinct pairs of points on an `n`-dimensional `n x n x n x n x n x n ... x n` lattice, where the coordinates range from `0` to `n - 1`, are a distance **at least** `n` apart? The pairs `{(2,1,3,1), (3,2,1,3)}` and `{(3,2,1,3), (2,1,3,1)}` are not considered distinct from each other, as they consist of the same two points in reverse order. Note that the total number of pairs grows very rapidly. The number of total pairs goes `6`, `351`, `32 640`, `4 881 250`, `1 088 367 840`, etc.
Test cases:
```
2 -> 0 (all pairs are at most a distance of sqrt(2) < 2 apart)
3 -> 28 (They must either be (2,2,1) or a permutation apart, or (2,2,2) apart. Each corner
has three non-corner (2,2,1) points corresponding to it. And each corner is associated
with a corner pair that is a (2,2,2). Thus. 3.5 * 8 = 28.
4 -> 4,888
5 -> 1,501,948
6 -> 486,039,360 (I would like someone to verify this if possible)
```
Your code should work for n <= 5, at least in theory. Don't hardcode it, that's a standard loophole.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
tt:Z^tZPR>~z
```
[**Try it online!**](https://tio.run/##y00syfn/v6TEKiquJCogyK6u6v9/UwA "MATL – Try It Online")
### Explanation
```
tt % Implicit input n. Duplicate twice
% STACK: n, n, n
: % Range [1 2 ... n]
% STACK: n, n, [1 2 ... n]
Z^ % Cartesian power. Gives an n^n × n matrix C where each row is a Cartesian tuple
% STACK: n, C
t % Duplicate
% STACK: n, C, C
ZP % Euclidean distance. Gives an n^n × n^n matrix D of pairwise distances
% STACK: n, D
R % Upper triangular part: sets elements below the main diagonal to 0. Call that U
% STACK: n, U
>~ % Less than or equal? Element-wise. Gives a true-false matrix B
% STACK: n, B
z % Number of nonzeros. Implicitly display
% STACK: number of entries in B that equal true
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes
1 byte thanks to Dennis.
```
ṗ⁸Œc_/€ÆḊ€<ċ0
```
[Try it online!](https://tio.run/##y0rNyan8///hzumPGnccnZQcr/@oac3htoc7uoC0zZFug////5sAAA "Jelly – Try It Online")
## Quick maffs version
```
ŒgL€!P:@L!$×P
²S<
ḶœċçÐḟ²ð>0S’2*×⁸ạ⁹$Ѥð€S
```
[Try it online!](https://tio.run/##AVIArf9qZWxsef//xZJnTOKCrCFQOkBMISTDl1AKwrJTPArhuLbFk8SLw6fDkOG4n8Kyw7A@MFPigJkyKsOX4oG44bqh4oG5JMORwqTDsOKCrFP///82 "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~137~~ 133 bytes
```
lambda n:sum(n*n<=sum((o[i]-p[i])**2for i in range(n))for o,p in q(q(range(n),repeat=n),repeat=2))/2
from itertools import*
q=product
```
Mr Xcoder & ovs: -4 bytes.
[Try it online!](https://tio.run/##RcgxDsIwDEDRvafwGEdFSIEJkZMAQ6AJRGps100HTh/oUHX5evryrR8m15K/tzGU5xCALvNSDFm6@hWGb/lxkH/QWpdYIUMm0EDvaAhxPdzL@iYzme33GiWG6nc5xKPrknKBXKNW5nGGXIS12m7yojwsr9pEM1VIxmG38bTzjO0H "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 40 bytes
```
2%~[:+/^:_]<:[:+/&.:*:"1[:-"1/~#~#:i.@^~
```
[Try it online!](https://tio.run/##y/r/P81Wz0i1LtpKWz/OKj7WxgrEUtOz0rJSMoy20lUy1K9TrlO2ytRziKv7n5qcka@QppBallpUqWCkYKxgomD6HwA)
Will time out on TIO for 5 if you use extended precision (`5x` instead of `5`). I'm not going to bother trying with 6 on my computer since that will no doubt crash the interpreter.
Looking for advice on golfing, specifically the part past the generation of the coordinates. I feel like there ought to be a way to remove some of the caps.
`]<:[:+/&.:*:"1` may be equivalently replaced by `*:<:[:+/"1[:*:`.
# Explanation
This explanation is done on the REPL (three spaces indicate a command, no spaces indicate an output). I will be building up to the answer.
### Generating the coordinates
`#~ #: i.@^~` gives all the coordinates we care about on the lattice.
`^~` is a number raised to itself, and `i.` gives the range [0,n)
where n is its input. `@` composes those functions.
```
i.@^~ 2
0 1 2 3
```
`#~` copies a number by itself, e.g.
```
#~ 3
3 3 3
```
`#:` converts its right argument to the base specified by the *array* given as its left argument. The number of digits in the array corresponds to the number of digits in that base output (and you can have a mixed base) For example,
```
3 3 3 #: 0
0 0 0
5 5 #: 120
4 0
NB. If you want 120 base 5 use #.inv
#.inv 120
4 4 0
```
So, all together, this says enumerate through all of the values base n (where n is the input) up to n^n, effectively giving us our coordinates.
```
(#~ #: i.@^~) 2
0 0
0 1
1 0
1 1
```
### Getting the distances between each pair
First we take the difference of each coordinate with all of the others using the dyad `/`-table and `~`-reflexive. Note that this doesn't account for the fact that order doesn't matter for the pairs: this generates duplicate distances.
```
NB. 2 {. takes the first two elements (I'm omitting the rest).
2 {. -"1/~ (#~ #: i.@^~) 2
0 0
0 _1
_1 0
_1 _1
0 1
0 0
_1 1
_1 0
```
Then we use this verb `+/&.:*:` on each coordinate (at `"1`, aka rank one). This verb is sum (`+/`) under (`&.:`) square (`*:`). Under applies the right verb (square) then collects its results and gives it as the argument to the left verb (sum). It then applies the inverse of the right verb (which would be square root).
```
+/&.:*: 3 4
5
+/&.:*:"1 ([: -"1/~ #~ #: i.@^~) 2
0 1 1 1.41421
1 0 1.41421 1
1 1.41421 0 1
1.41421 1 1 0
```
Unsurprisingly, many distances are the same.
### Counting the distances greater than or equal to the input
The last part is seeing if the distance is greater than or equal to the input using `]<:`. Then all of the results are summed using `+/^:_` (sum until converge), counting the number of truthy values. Then this value is divided by 2 (`2%~`, here `~` means swap the order of the arguments supplied to `%`). The reason why we can divide by 2 is because for each truthy pairing, there will be another one for the flipped order *except* for pairings which are a coordinate with itself. That's ok, though, since those will result in a distance of 0.
] |
[Question]
[
# Description
Given a length `n`, and an alphabet size `k>0`, your program must determine the number of strings with those parameters which have a maximal number of unique substrings. In the case of `k=2`, this generates OEIS [A134457](https://oeis.org/A134457).
# Example
For example, `2210` has the substrings , `2`, `22`, `221`, `2210`, `2`, `21`, `210`, `1`, `10`, and `0`, for a total of 11. However, `2` appears twice, so it only has 10 unique substrings.
This is as many as possible for a length 4 string containing 3 different symbols, but it ties with 35 other strings for a total of 36 tieing strings including `0012`, `2101`, and `0121`. Therefore, for `n=4` and `k=3`, your program should output 36.
# Test Cases
```
n k output
0 5 1
1 3 3
5 1 1
9 2 40
2 3 6
5 5 120
```
[Answer]
# Pyth, 12 bytes
```
l.Ml{.:Z)^UE
```
[Try it online.](https://pyth.herokuapp.com/?code=l.Ml%7B.%3AZ%29%5EUE&input=9%0A2&debug=0)
Pure brute force.
### Explanation
* Implicit: append `Q` to the program.
* Implicit: read and evaluate a line of input (`n`) in `Q`.
* `E`: read and evaluate a line of input (`k`).
* `U`: get a range `[0, ..., k-1]`.
* `^`: get all `n`-length strings of `[0, ..., k-1]`.
* `.M`: find the ones that give a maximum for function `f(Z)`:
+ `.:Z`: find the substrings of `Z`
+ `{`: remove duplicates
+ `l`: get the number of unique substrings
* `l`: get the number of such strings
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ṗµẆQLµ€ML
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//4bmXwrXhuoZRTMK14oKsTUz///8y/zk "Jelly – Try It Online")
Input in reversed order. Brute force.
[Answer]
# Mathematica, 96 bytes
```
Last[Last/@Tally[Length@Union@Flatten[Table[Partition[#,i,1],{i,s}],1]&/@Tuples[Range@#2,s=#]]]&
```
[Answer]
## Haskell, 82 bytes
```
import Data.Lists
l=length
n#k=l$argmaxes(l.nub.powerslice)$mapM id$[1..k]<$[1..n]
```
Usage example: `9 # 2` -> `40`.
How it works:
```
[1..k]<$[1..n] -- make a list of n copies of the list [1..k]
mapM id -- make a list of all combinations thereof, where
-- the 1st element is from the f1st list, 2nd from 2nd etc
argmaxes -- find all elements which give the maximum value for function:
l.nub.powerslice -- length of the list of unique sublists
l -- take the length of this list
```
] |
[Question]
[
Eyeballing the binary values printed as ovals and sticks is not so easy...
To help with that, you must write a function (or a program) that prints numbers in custom binary representation.
So I want to take a number, say 3 (`00000011`) and output the bits in user-defined format, for example with space separated pairs:
```
00 00 00 11
```
or, say, in reversed order and with some decorators, e.g.:
```
11_00_00_00
```
Furthermore, there must be possibilty to show '0' and '1' as custom characters to distinguish them better, e.g.:
```
XX oo oo oo
```
So the challenge is to write the code which does that all whithin the following specification.
## Specification
The function takes input like this: **f(A, mask, zeros, ones)**
Parameters:
**A** -- input number -- any (unsigned) integer in range 0-255.
**mask** -- a string parameter which defines the construction of the output.
**zeros** -- a string of the same length, defines 'zero' glyphs for each output slot.
**ones** -- a string of the same length, defines 'one' glyphs for each output slot.
**Rules for the output construction:**
Look at this image with example closely to understand how the output is generated:
[](https://i.stack.imgur.com/35Czz.png)
So only the *single digits* in the mask are parsed and replaced by corresponding bits of A, other characters are *left as is*. Further, if the value of the taken bit is 1 then it shows up in the final output as "X" and if it is 0 then it shows up as "o".
In the above example all four taken bits are "1" so we see "X" in all slots.
If the input number was 128, then, logically, the output would be `X foo bar ooo`. Characters in parameters "zeros" and "ones": any printable ASCII chars, assume they are always char-aligned with the mask.
**Notes**:
* Bits are 0-indexed: 0th bit is the MSB.
* Assume that digits 8,9 are not allowed in the mask string.
* Input Strings include any printable ASCII chars.
* 'Zeros' and 'ones' are char-aligned with the mask.
* For special characters/modifiers in your language: we can assume they will not appear in the input string.
For the clarity, see more examples.
## Input -> Output examples
Output all 8 bits in common order with a space delimiter, in common oval-and-stick notation:
```
mask = "0123 4567"
zeros = "0000 0000"
ones = "1111 1111"
A=1 -> 0000 0001
```
Output in reversed order, in dash-and-glyph notation:
```
mask = "| 7654 3210 |"
zeros= " ---- ---- "
ones = " ssss ssss "
A=1 -> | s--- ---- |
A=3 -> | ss-- ---- |
A=128-> | ---- ---s |
```
Diverse notations in one output, e.g. for packed data:
```
mask = "0 | 123 4567"
zeros= " --- ----"
ones = "X kkk ssss"
A= 15 -> | --- ssss
A= 16 -> | --k ----
A= 32 -> | -k- ----
A= 128 -> X | --- ----
A= 255 -> X | kkk ssss
```
Repeating patterns:
```
mask = "| 7 66 555 4444 |"
zeros= " . .. ... .... "
ones = " 0 00 000 0000 "
A= 0 -> | . .. ... .... |
A= 1 -> | 0 .. ... .... |
A= 2 -> | . 00 ... .... |
A= 3 -> | 0 00 ... .... |
A= 4 -> | . .. 000 .... |
```
---
## Update
The rules have been slightly simplified - the program must print one number only (not array/list of numbers as it was proposed initially).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->a,f,*b{f.gsub(/\d/){b[a[55-$&.ord]][$`.size]}}
```
The zeroes and ones parameters are treated as an array (`*b`) and with the zeroes parameter is stored in `b[0]` and the ones parameter stored in `b[1]`.
The mask parameter `f` has each digit (`/\d/`) substituted with a character from the appropriate array. The special variable `$``, which holds the text leading up to the current match, is (ab)used here to keep track of position.
Ruby's bit indexing calls 0 the least-significant bit, but the challenge calls 0 the most significant bit. ASCII subtraction from 55 (the '7' character) yields a usable Ruby bit index.
[Try it online!](https://tio.run/nexus/ruby#vZNda8IwFIbv8yteoo5N0mg/UnejsH8xqIVVmzrp1orRG1t/u8vHOkTxYrB5aA@HvOnpycObVf1RyBzTkzfLWMGGi6bgK7VfPI7m@eipWSRZIoTXf@D1Nk/TpP/G1fog0@Px9JmpEpgCdOwHISIRTyhADnJbK7esAyaZ5bqSyu32dcAkSshmv1OgXadeYyq@rtRGLndH@i13HXuNra70rnWvMdWFTBI/5TJbviOv0WYtATbbdbUrQF@mgzD3ZhioeUUZMoaVhZFkzMzB7N@Y6Zl2TYmsctKNrb8ahoTY6fXB9NFaTGIRIQz8MVrqUDgF8HS4BOpodIrS4RLuhYSFzA@eb4HRWPS8vwdzA4s5peaBH5ecgXEELB0L5xyN0V51KsvS4rkXHMH8mIWBIcQCIf7ZPhf@QRxDCIFIx5WHOLh57MuvfGQuG7o7dzcvjZnPAu2n6K85nVM6fQE "Ruby – TIO Nexus")
[Answer]
# JavaScript (ES6), 57 bytes
```
(A,M,O,I)=>M.replace(/[\d]/g,(d,i)=>(A>>7-d)%2?I[i]:O[i])
```
```
f=
(A,M,O,I)=>M.replace(/[\d]/g,(d,i)=>(A>>7-d)%2?I[i]:O[i])
console.log( f(1, "0123 4567", "0000 0000", "1111 1111") )
console.log( f(3, "| 7654 3210 |", " ---- ---- ", " ssss ssss ") )
console.log( f(4, "| 7 66 555 4444 |", " . .. ... .... ", " 0 00 000 0000 ") )
```
[Answer]
# [Perl 6](http://perl6.org/), 60 bytes
```
->\a,$_,\o,\z{S:g|\d|{substr (z,o)[a+>(7-$/)%2],$/.from,1}|}
```
[Answer]
## Python, 97 bytes
```
lambda A,M,Z,O:"".join([[Z,O][1&(A>>7-int(d))][i] if d.isdigit() else d for i,d in enumerate(M)])
```
[Answer]
## Mathematica, 131 bytes
```
""<>Table[(f/@{##2})[[x[[i]],i]],{i,Length[x=(f=Characters)@#2/.Table[ToString@i->2+Floor[#/2^(7-i)]~Mod~2,{i,0,7}]/._String->1]}]&
```
[Answer]
# q/kdb+, ~~86~~ 64 bytes
**Solution:**
```
f:{[A;M;Z;O]@[M;m;:;((-8#0b vs A)"I"$'M m)(Z;O)'m:(&)M in .Q.n]}
```
**Examples:**
```
q)f[1;"0123 4567";"0000 0000";"1111 1111"]
"0000 0001"
q)f[1;"| 7654 3210 |";" ---- ---- ";" ssss ssss "]
"| s--- ---- |"
q)f[15;"0 | 123 4567";" --- ----";"X kkk ssss"]
" | --- ssss"
q)f [0;"| 7 66 555 4444 |";" . .. ... .... ";" 0 00 000 0000 "]
"| . .. ... .... |"
```
**Explanation:**
Pull out indices where input mask `M` is a numeral, call it `m` this is where we will be modifying the input mask. Take the numerals out of the string, cast to integers and then index into our 8-bit array to get the correct ordering.
Use this 8-bit array to index into either `O` (if 1 is set) or `Z` (if 0 is set), and then index into these lists at the indices given by `m`.
Finally apply (`:`) this new list to the original mask at indices `m`.
```
{[A;M;Z;O] } / lambda function with 4 parameters
@[ ; ; ; ] / apply, applies 3rd parameter to 1st parameter at indexes from parameter 2 with parameter 4 :)
(-8#0b vs A) / convert input number to binary (64 bit), take the last 8 items
m:(&)M in .Q.n / returns indices where mask is in "0123..789", stores in variable m
"I"$'M m / index into mask at indices m, then cast these numbers to an integer array
( ) / we then index into our 8 bits a these offsets to get the output order
(Z;O) / 2-item list of the zeroes and ones mask
' / take each item on the left and right and apply them to (Z;O) (ie index in at 0 / 1 and then 123..67)
M m : / apply *this* list to M at each index given by m
```
**Notes:**
Could shave off a further 14 bytes if we were allowed to give the arguments in the form:
`[A;M;(Z;O)]`
as q allows for up to 3 arguments to be given to a function without being explicitly named (they are `x`, `y` and `z` respectively):
```
f:{@[y;m;:;((-8#0b vs x)"I"$'y m)z'm:(&)y in .Q.n]}
```
] |
[Question]
[
I though this would be a good challenge : <http://adventofcode.com/2016/day/1>
# Task description
Given a sequence of rotations and distances following the pattern (L|R)[1-9][0-9]\*, give the manhattan distance between the start and the ending points, that is the minimal number of vertical and horizontal moves on a grid.
# Examples
For example, if we assume you started facing North:
Following R2, L3 leaves you 2 blocks East and 3 blocks North, or 5 blocks away.
R2, R2, R2 leaves you 2 blocks due South of your starting position, which is 2 blocks away.
R5, L5, R5, R3 leaves you 12 blocks away.
# Technical details
You can choose the separator between the moves (e.g. : "\n", ", ", or ",").
You must give the answer as an integer in base 10.
# Not a duplicate!
It is not a duplicate for multiple reasons :
* The moves are not the same. Here they are **rotations**, not directions.
* I want the Manhattan distance, not the euclidian.
[Answer]
# Python 3, ~~109~~ ~~99~~ ~~104~~ 101 bytes
This is a simple answer that uses complex numbers, with input as a space-separated string or a newline-separated string. Golfing suggestions welcome!
**Edit:** -13 bytes thanks to Labo. +5 bytes for converting to an int.
```
d=p=0
for r in input().split():d+=1-2*(r<'R');p+=1j**d*int(r[1:])
print(int(abs(p.real)+abs(p.imag)))
```
**Ungolfing**
```
def manhattan_rotation(seq, nsew=0, pos = 0):
for rot in seq.split():
# change direction
if rot[0] == "L":
nsew += -1
else:
nsew += 1
# move in that direction rot[1:] times
pos += 1j ** nsew * int(rot[1:])
return int(abs(pos.real)+abs(pos.imag))
```
[Answer]
# PHP, 93 bytes
```
while($m=$argv[++$i])${chr(80|3&$d+=(P<$m)-(M>$m))}+=substr($m,1);echo abs($P-$R)+abs($Q-$S);
```
**breakdown**
```
while($m=$argv[++$i]) // loop through arguments:
${ // 5. use as variable name
chr( // 4. cast to character (P,Q,R,S)
80| // 3. add 80
3& // 2. modulo 4
$d+=(P<$m)-(M>$m) // 1. change direction depending on letter
)}+=substr($m,1); // 6. add number to variable
echo abs($P-$R)+abs($Q-$S); // calculate distance, print
```
[Answer]
## Python 2, 86 bytes
```
x=y=0
for d in input().split():c=cmp(d,'M');x,y=int(d[1:])-y*c,x*c
print abs(x)+abs(y)
```
Tracks the current `x` and `y` coordinates. When turning, instead of updating the direction, rotates the current value so that the motion is always in the x-positive direction. Complex numbers were too costly to extract the coordinates from.
[Answer]
# Python 2, ~~103~~ 102 bytes
```
l=c=0
for i in input().split():c+=cmp(i[0],'N');l+=1j**c*int(i[1:])
print int(abs(l.imag)+abs(l.real))
```
**[repl.it](https://repl.it/EfIt)**
Input is a string of space delimited directions, e.g. `"R5 L5 R5 R3"`.
Prints out the Manhattan distance between the starting location and the destination.
### How?
Starts at the origin of the complex plane, `l=0`;
With a cumulative quarter-right turn counter, `c=0`;
For each instruction, `i`, the rotation is parsed is by comparing the first character of the direction to the character `'N'`, and `c` is adjusted accordingly.
The distance to travel is parsed with `int(i[1:])` and the instruction is enacted by taking that many block sized steps in the direction given by taking the `c`th power of `0+1j` with `1j**c`.
The final Manhattan distance is the sum of the absolute distances from the origin in the two directions - imaginary and real; achieved with `abs(l.imag)+abs(l.real)`
[Answer]
# JavaScript (ES2016), 98 ~~100~~
2 bytes saved thx @Neil
```
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x*x)**.5+(y*y)**.5
```
**100** bytes for ES6
```
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x>0?x:-x)+(y>0?y:-y)
```
*Less golfed*
```
d => d.replace(/.(\d+)/g,
(d,l)=>( // L or R in d, distance in l
o += d>'M' || 3, // orientation in o, used %4
l *= ~-(o&2), // convert to number and change sign if needed
o&1 ? x -= l : y += l // move based on orientation
), x = y = o = 0)
&& (x>0?x:-x) + (y>0?y:-y)
```
**Test** (ES6)
```
F=
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x>0?x:-x)+(y>0?y:-y)
function update() {
O.textContent=F(I.value)
}
update()
```
```
<input id=I value='R5, L5, R5, R3' oninput='update()'><pre id=O></pre>
```
] |
[Question]
[
**The challenge**
Simply write a program that outputs its own source code.
Nothing more than a regular quine.
**The problem**
We don't have a computer so we have to run the program on a programmable logic device (such as an FPGA, a CPLD, a gate array ...).
**The rules**
* Any device available on the market (such as a printer connected via Centronics port, an LED display, an RS232 terminal ...) connected to the logic device can be used to output the program.
* If you use any kind of programmable device as output device you are not allowed to put any program logic there!
Example: If you use RS232 to send data to a computer the computer must do nothing but displaying the data received from the RS232. However you are allowed to switch on RS232 options like echoing data back to the logic device if any existing terminal program has this feature.
* Any (recent or historic) "standard" coding (ASCII, UNICODE, EBCDIC, Morse code ...) can be used.
* The program needs only to output its own source code. The file only containing the mapping between VHDL/Verilog/... "wires" and the actual I/O pins, the file containing the compiler settings and similar files are not considered as "source code" and need not to be written.
* You have one clock input pin with the frequency of your choice (if you need that).
* On-chip units (like on-chip SRAM or on-chip multipliers) must not be used.
* For testing the code you can simulate the output device using additional code; of course you may simulate the logic device, too (if you don't have a real one).
* Standard loopholes apply.
**The winner**
* For calculating the size of the program it is assumed that the real output device (e.g. the printer) is connected to some I/O pins of the logic device.
* The code that requires the fewest "LE" cells on my FPGA (Altera EP2C20F484C7) wins.
* If my FPGA is too small (= not large enough for the smallest solution) we compile for the largest one having "LE"-type cells (EP4CGX150DF31I7).
* If that one is still not enough we try the largest one supported by the free-of-charge compiler (EP2AGX260FF35I5).
* If that device is still too small the size of the source code counts.
**Note**
Searching for "quine VHDL" in Google I found at least three quines written in VHDL on the first page!
Unfortunately none of them will work on a real logic device but only in the emulator because the standard output (of the emulator) is used.
Good luck!
[Answer]
# Verilog, optimized for area, 130 LE gates
The quine itself (the actual file is encoded in [DEC SIXBIT](https://en.wikipedia.org/wiki/Six-bit_character_code#Examples_of_six-bit_ASCII_variants)):
```
module q(s,d);inout s,d;wire[0:1023]v=1024'b0110111100101001011001111110110110010110100100001111011010010111010101110101010110010110111100101001011001111110110100100110100100001111011010100111010101110110111000011100111100111010011001111011100000001001000111011010100111000101100111111010100111010111010100100110101101101110111010011111010110111000011011001101111000011110011100111000000010001100001011111100111001011001001001111001010000001100110010011010011001100010001010100111100101010010011000101001011001111010011011100000001010010111011010010010110100010110111010100111011010100001100100011111100000011010010111110101110110100100010110111001011011101001000000001001011011001100111001010000001010100111011010100010110100010110111001011011101001001011011011111001001101011011001001010000000000000000101101101111100100110101101100100101000000110001001000110011001100100100001001011011101001101110101111110101110100000000110011001100100100011011110111101001110010100101111011010000011010010001010000010010010011111101110110011101010001010000010010010100000111100010;reg[9:0]i=759;reg[2:0]j=7;assign d=j<6?j==2:v[i];always@(posedge s)if(j>5)begin i=i+1;j=j&1^!i?7:1;end else j=j+1;endmodule
```
Readable version with comments and a testbench:
```
module q(s,d);
// Declare the ports. Making them both "inout" is shortest.
inout s,d;
// Data storage for the program.
wire[0:1023]v=1024'b{DATA GOES HERE};
// i is the current bit number within the program.
// This is relative to the /end of the data storage/ (not to the start
// of the program), so it starts at a nonzero value so that the output
// starts at the start of the program.
reg[9:0]i=759;
// When expanding bits to (6-bit) bytes, j is the bit number within
// the expansion, from 1 for the first bit up to 6 for the last.
// When not expanding, j is always 7.
// DEC SIXBIT encoding for 0 is (from MSB to LSB) 010 000.
// DEC SIXBIT encoding for 1 is (from MSB to LSB) 010 001.
// We use SSI encoding for the output, so the MSB is sent first.
reg[2:0]j=7;
assign d=j<6?j==2:v[i];
// When we get a strobe:
always@(posedge s)
// If we just output a bit, move onto the next bit.
// We may also need to reset j.
if(j>5)
begin
i=i+1;
j=j&1^!i?7:1;
end
else
// If we're inside a bit, continue to output that bit.
j=j+1;
endmodule
// {TESTBENCH BELOW HERE}
`timescale 10ns / 1ns
module testbench();
reg clock = 0;
wire data, strobe;
always
#1 clock <= !clock;
initial
#14304 $finish;
assign strobe = clock;
q testquine(.s(strobe),.d(data));
always @(negedge strobe)
$display("%d", data);
endmodule // testbench
```
The use of Verilog gives me considerably more control over the low-level details than I'd have with Verity. In particular, it lets me control the clock and reset rules myself. This program's intended for a synchronous serial connection with strobe input `s` and data output `d`. Although each is only used in one direction, I declared them both as bidirectional to save a few bytes; I had to golf the non-data parts of the program down to 1024 bits to be able to use 10-bit logic gates internally (extra bits would be more expensive in area), and it only just scrapes under at 1008, so savings like this are important. In order to save a substantial amount of code, I rely on the FPGA's hardware reset circuitry rather than adding my own, and I merge the strobe and clock inputs (which is an old trick that's kind-of frowned upon nowadays because it makes it hard to keep the clock tree balanced at high clock speeds, but it's useful for golfing.) I hope that's synthesizable; I don't know how well Verilog synthesizers cope with using a bidirectional port as a clock.
The source is encoded in DEC SIXBIT (I'm assuming here that we interpret its single alphabet of letters as lowercase; a Verilog synthesizer would have no reason to use an uppercase interpretation). I used a six-bit character set internally in my other solution, then wasted bytes converting it; it's better to use a character set that's "naturally" six bits wide so that no conversion is necessary. I picked this particular six-bit character set because `0` and `1` differ only in their least significant bit, and only have one other bit set, meaning that the circuitry for converting a binary digit to DEC SIXBIT (i.e. "escaping" a string) can be very simple. Interestingly, the character set in question is missing a newline character; the original program's all on one line not *just* to make it easier to generate, but to make it possible to encode! It's a good thing that Verilog mostly doesn't care about whitespace.
The protocol for sending data to the host is based on [Synchronous Serial Interface](https://en.wikipedia.org/wiki/Synchronous_Serial_Interface). I picked it because it's clocked (allowing me to use the clock/strobe trick, and also allowing me to write a portable program that doesn't rely on on-chip timing devices), and because it's very simple (thus I don't have to waste much code implementing it). This protocol doesn't specify a method of specifying where the message ends (the host is supposed to know); in this particular case, I padded the output up to a multiple of 1024 bits with zero bits (a total of 16 padding bits), after which (as required by SSI) the message restarts. (I don't implement an idle mode timer; its purpose is to determine whether to send a new message or whether to repeat the previous message, and as this program always sends its own source code as the message, the distinction isn't visible. You can consider it to be length 0, or infinitely long, depending on your point of view.)
In terms of the actual logic, the most interesting thing is the way that I split up the variables to reduce the amount of area needed on the chip. `i`, the larger register, holds the current "address" within the program's data, and is only ever changed via incrementing it; this means that its logic can be synthesized using the half-adder construction (which, as the name suggests, uses only half the resources that an adder does; this mostly only matters on the smallest FPGAs, larger ones will use 3-input or even 4-input LUTs which are powerful enough that they'll have lots of wasted capacity synthesizing a half-adder). The smaller register, `j`, is basically a state machine state and thus handles most of the program's complex logic. It's small enough that it can be handled entirely via lookup table on a larger FPGA (making the logic basically disappear); in case the program is synthesized for a small FPGA, I chose its encoding in such a way that few parts of the code care about all three of its bits at once.
It's also worth noting that I cyclically permuted the data storage. We can start `i` pointing anywhere inside it, not necessarily at the start. With the arrangement seen here, we can print from the initial value of `i` to the end directly, then print the entire array escaped, then print from the start to the initial value of `i`, in order to print the all the parts of the data in the right places without needing to save and restore the value of `i`. (This trick might be useful for quines in other languages too.)
The source is 1192 6-bit bytes long, the equivalent of 894 8-bit bytes. It's kind-of embarrassing that this contains fewer source bytes than my Verity submission, despite being optimized for something entirely different; this is mostly because Verilog has strings and Verity doesn't, meaning that even though I've encoded the program in binary rather than octal (which is substantially less efficient in terms of source code size), I can encode each byte of the program using six six-bit characters (one for each bit) rather than eight eight-bit characters (four for each octal digit). A Verilog submission that encoded the program in octal would probably be smaller in terms of source code size, but would almost certainly be larger in area.
I don't know how much area this program will end up using; it depends a lot on how powerful the optimizer is in your Verilog synthesizer (because the minimization problem of converting the stored data into a set of logic gates is something that's done in the synthesizer itself; throwing the work onto the synthesizer makes the source code itself much shorter, and thus reduces the area needed to store it). It should have a complexity of O(n log n), though, and thus be much smaller than the O(n²) of the other program. I'd be interested to see the OP try to run it on their FPGA. (It may take quite some time to synthesize, though; there are various steps you can take to optimize a program for compile time but I didn't take any here as it'd cause a larger program = larger area.)
[Answer]
# Verity 0.10, optimized for source code size (1944 bytes)
I originally misread the question and interpreted it as a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). That was probably for the best, as it's much easier to write a quine with short source code than short object code under the restrictions in the question; that made the question easy enough that I felt I could reasonably produce an answer, and might work as a stepping stone on the way to a better answer. It also prompted me to use a higher-level language for the input, meaning that I'd need to express less in the program itself. I didn't create Verity as a golfing language for hardware (I was actually hired to create it a while ago in an entirely different context), but there's quite a reminiscence there (e.g. it's substantially higher level than a typical HDL is, and it has much less boilerplate; it's also much more portable than the typical HDL).
I'm pretty sure that the correct solution for short object code involves storing the data in some kind of tree structure, given that the question disallows the use of block ROM, which is where you'd normally store it in a practical program; I might have a go at writing a program that uses this principle (not sure what language, maybe Verity, maybe Verilog; VHDL has too much boilerplate to likely be optimal for this sort of problem) at some point. That would mean that you wouldn't need to pass every bit of the source code to every bit of your "manually created ROM". However, the Verity compiler currently synthesizes the structure of the output based on the precedence and associativity of the input, meaning that it's effectively representing the instruction pointer (thus the index to the lookup table) in unary, and a unary index multiplied by the length of the lookup table gives this O(n²) space performance.
The program itself:
```
import <print>new x:=0$1296in(\p.\z.\a.new y:=(-a 5-a 1-a 1-a 2-a 4-a 2-a 3-a 2-a 6-a 2-a 0-a 3-a 0-a 4-a 4-a 7-a 4-a 2-a 6-a 2-a 5-a 1-a 2-a 2-a 0-a 3-a 6-a 7-a 2-a 2-a 1-a 1-a 3-a 3-a 0-a 4-a 4-a 3-a 2-a 7-a 5-a 7-a 0-a 6-a 4-a 4-a 1-a 6-a 2-a 6-a 1-a 7-a 6-a 6-a 5-a 1-a 2-a 2-a 0-a 5-a 0-a 0-a 4-a 2-a 6-a 5-a 0-a 0-a 6-a 3-a 6-a 5-a 0-a 0-a 5-a 0-a 6-a 5-a 2-a 2-a 1-a 1-a 3-a 3-a 0-a 4-a 5-a 3-a 2-a 7-a 5-a 7-a 0-a 5-a 5-a 5-a 1-a 4-a 4-a 3-a 1-a 5-a 5-a 1-a 2-a 2-a 0-a 4-a 3-a 3-a 4-a 1-a 5-a 1-a 0-a 2-a 1-a 1-a 1-a 4-a 4-a 3-a 6-a 7-a 0-a 6-a 0-a 1-a 3-a 2-a 0-a 5-a 4-a 2-a 0-a 5-a 5-a 1-a 2-a 1-a 0-a 4-a 6-a 3-a 4-a 7-a 3-a 6-a 2-a 6-a 0-a 3-a 4-a 1-a 1-a 1-a 2-a 2-a 0-a 4-a 6-a 3-a 3-a 5-a 1-a 7-a 2-a 6-a 1-a 1-a 0-a 2-a 7-a 2-a 1-a 1-a 0-a 4-a 6-a 3-a 1-a 5-a 3-a 7-a 5-a 1-a 2-a 1-a 0-a 4-a 6-a 3-a 5-a 7-a 5-a 7-a 4-a 6-a 5-a 6-a 0-a 3-a 4-a 1-a 1-a 1-a 2-a 2-a 0-a 4-a 3-a 3-a 4-a 1-a 5-a 1-a 0-a 2-a 1-a 1-a 1-a 4-a 5-a 3-a 6-a 7-a 0-a 6-a 0-a 1-a 3-a 2-a 0-a 5-a 4-a 2-a 0-a 4-a 1-a 7-a 7-a 6-a 3-a 7-a 4-a 2-a 0-a 4-a 3-a 6-a 2-a 6-a 3-a 7-a 4-a 2-a 0-a 5-a 4-a 6-a 0-a 7-a 2-a 0-a 1-a 4-a 5-a 3-a 4-a 4-a 4-a 4-a 3-a 6-a 4-a 4-a 4-a 4-a 3-a 6-a 2-a 6-a 1-a 5-a 3-a 7-a 4-a 2-a 0-a 4-a 4-a 6-a 5-a 6-a 3-a 7-a 5-a 3-a 2-a 7-a 5-a 7-a 1-a 4-a 5-a 3-a 6-a 7-a 6-a 7-a 3-a 6-a 1-a 5-a 1-a 1-a 0-a 2-a 7-a 2-a 1-a 1-a 0-a 4-a 7-a 2-a 7-a 1-a 5-a 1-a 4-a 2-a 3-a 7-a 4-a 3-a 2-a 7-a 5-a 7-a 1-a 4-a 4-a 3-a 6-a 7-a 6-a 7-a 6-a 6-a 1-a 5-a 1-a 5-a 4-a 2-a 6-a 2-a 5-a 1-a 2-a 2-a 0-a 3-a 0-a 5-a 1-a 4-a 4-a 3-a 4-a 4-a 4-a 4-a 6-a 6-a 4-a 4-a 4-a 4-a 3-a 6-a 2-a 6-a 1-a 5-a 0-a 5-a 0-a 0-a 0-a 1-a 6-a 5-a 4-a 3-a 2-a 7-a 5-a 7-a 1-a 4-a 4-a 3-a 6-a 7-a 6-a 7-a 3-a 6-a 2-a 0-a 0-a 1-a 4-a 7-a 4-a 7-a 1-a 6-a 2-a 6-a 1-a 7-a 3-a 6-a 3-a 7-a 0-a 6-a 1-a 5-!x)in while!x>0do(p(if z<32then z+92else z);if z==45then while!y>0do(p 97;p 32;p(48^!y$$3$$32);p 45;y:=!y>>3)else skip;x:=!x>>6))print(!x$$6$$32)(\d.x:=!x>>3^d<<1293;0)
```
More readable:
```
import <print>
new x := 0$1296 in
(\p.\z.\a.
new y := (-a 5-a 1-
# a ton of calls to a() omitted...
-a 1-a 5-!x) in
while !x>0 do (
p(if z<32 then z+92 else z);
if z==45
then while !y>0 do (
p 97;
p 32;
p(48^!y$$3$$32);
p 45;
y:=!y>>3 )
else skip;
x:=!x>>6
)
)(print)(!x$$6$$32)(\d.x:=!x>>3^d<<1293;0)
```
The basic idea is that we store the entire data in the variable `x`. (As usual for a quine, we have a code section and a data section; the data encodes the text of the code, and can also be used to regenerate the text of the data.) Unfortunately, Verity doesn't currently allow very large constants to be written in the source code (it uses OCaml integers during compilation to represent integers in the source, which clearly isn't correct in a language that supports arbitrarily wide integer types) – and besides, it doesn't allow constants to be specified in octal – so we generate the value of `x` at runtime via repeated calls to a function `a`. We could create a void function and call it repeatedly as separate statements, but that would make it hard to identify where to start outputting the text of the data section. So instead, I made `a` return an integer, and use arithmetic to store the data (Verity guarantees that arithmetic evaluates left to right). The data section is encoded in `x` using a single `-` sign; when this is encountered at run time, it's expanded to the full `-a 5-a 1-`, etc., via the use of `y`.
Initializing `y` as a copy of `x` is fairly subtle here. Because `a` returns zero specifically, most of the sum is just zero minus zero minus… and cancels itself out. We end with `!x` (i.e. "the value of `x`"; in Verity, as in OCaml, a variable's name works more like a pointer than anything else, and you have to dereference it explicitly to get at the variable's value). Verity's rules for unary minus are a little complex – the unary minus of `v` is written as `(-v)` – thus `(-0-0-0-!x)` parses as `(-(0-0-0-!x))`, which is equal to `!x`, and we end up initializing `y` as a copy of `x`. (It's also worth noting that Verity is *not* call-by-value, but rather allows functions and operators to choose the order they evaluate things; `-` will evaluate the left argument before the right argument, and in particular, if the left argument has side effects, those will be visible when the right argument is evaluated.)
Each character of the source code is represented using two octal digits. This means that the source code is limited to 64 different characters, so I had to create my own codepage for internal use. The output is in ASCII, so I needed to convert internally; this is what the `(if z<32 then z+92 else z)` is for. Here's the character set I used in the internal representation, in numerical order (i.e. `\` has codepoint 0, `?` has codepoint 63):
```
\]^_`abcdefghijklmnopqrstuvwxyz{ !"#$%&'()*+,-./0123456789:;<=>?
```
This character set gives us most of the characters important for Verity. Notable characters missing are `}` (meaning that we can't create a block using `{}`, but luckily all statements are expressions so we can use `()` instead); and `|` (this is why I had to use an exclusive rather than inclusive OR when creating the value of `x`, meaning I need to initialize it to 0; however, I needed to specify how large it was anyway). Some of the critical characters that I wanted to ensure were in the character set were `<>` (for imports, also shifts), `()` (very hard to write a program that can be parsed without these), `$` (for everything to do with bitwidth), and `\` (for lambdas; theoretically we could work around this with `let…in` but it would be much more verbose).
In order to make the program a bit shorter, I constructed abbreviations for `print` and for `!x$$6$$32` (i.e. "the bottom 6 bits of `!x`, cast to be usable to the `print` library) via temporarily binding them to lambda arguments.
Finally, there's the issue of output. Verity provides a `print` library that's intended for debug output. On a simulator, it prints the ASCII codes to standard output, which is perfectly usable for testing the program. On a physical circuit board, it depends on a `print` library having been written for the particular chip and board surrounding it; there's a `print` library in the Verity distribution for an evaluation board I had access to that prints the output on seven-segment displays. Given that the library will end up taking space on the resulting circuit board, it may be worth using a different language for an optimized solution to this problem so that we can output the bits of the output directly on wires.
By the way, this program is O(n²) on hardware, meaning that it's much worse on a simulator (I suspect O(n⁴); not sure, though, but it was hard enough to simulate that it seems unlikely to be even cubic, and based on how the time reacted to my changes as I was writing the program, the function seems to grow very quickly indeed). The Verity compiler needed 436 optimization passes (which is much, much more than it'd typically use) to optimize the program, and even after that, simulating it was very hard for my laptop. The complete compile-and-simulate run took the following time:
```
real 112m6.096s
user 105m25.136s
sys 0m14.080s
```
and peaked at 2740232 kibibytes of memory. The program takes a total of 213646 clock cycles to run. It does work, though!
Anyway, this answer doesn't really fulfil the question as I was optimizing for the wrong thing, but seeing as there are no other answers yet, this is the best by default (and it's nice to see what a golfed quine would look like in a hardware language). I'm not currently sure whether or not I'll work on a program that aims to produce more optimized ouptut on the chip. (It would likely be a lot larger in terms of source, as an O(n) data encoding would be rather more complex than the one seen here.)
] |
[Question]
[
# Background
### Visualizing λ-calculus terms
Famous lambda-juggler (and [code golfer](https://codegolf.stackexchange.com/users/5241/john-tromp)) John Tromp devised an [interesting visualization](https://tromp.github.io/cl/diagrams.html) of terms in the λ-calculus. In his words:
>
> abstractions (lambdas) are represented by horizontal lines, variables by vertical lines emanating down from their binding lambda, and applications by horizontal links connecting the leftmost variables.
>
>
>
For example, the lambda term λf.λx.f (f (f (f x))) corresponds to the visualization:
```
-------------------
| | | |
-------------------
| | | | |
| | | |----
| | |----
| |----
|----
|
```
Read it from top to bottom:
* The first horizontal line represents the first λ.
* The four lines descending from it represent the **f**s in the body.
* Similarly, the second horizontal line represents the second λ, and the single new line descending from it represents the **x** in the body.
* The rightmost **f** line and the **x** line are connected by a horizontal line representing an application **(f x)**.
* The next application is **(f (f x))**, et cetera.
### Church numerals
The [Church numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals) are a specific sequence of terms in the λ-calculus, taking on the following pattern:
```
0 = λf. λx. x
1 = λf. λx. f x
2 = λf. λx. f (f x)
3 = λf. λx. f (f (f x))
...
```
# Task
Given an input number **n**, print some ASCII art that visualizes the **n**th Church numeral. For instance, the example above is your target output when given **n = 4**. For **n = 0**, print:
```
---
---
|
|
```
# Test cases
Your answer must output **exactly** the same text (modulo trailing newlines) as this stack snippet for all integer inputs **n ≥ 0**:
```
function visualize() {
var vin = document.getElementById('visualize-in');
var vout = document.getElementById('visualize-out');
var n = Number(vin.value);
if (n < 0) n = 0;
var line = '-'.repeat(4 * n + 3);
var bars = function(k) { return ' |'.repeat(k).substr(2); };
var img = [line, bars(n), line, bars(n + 1)];
for (var i = n; i > 0; --i) img.push(bars(i) + '----');
vout.innerHTML = img.join('\n') + '\n |';
}
```
```
<label for="visualize-in">n <input style="width:50px;" type="number" id="visualize-in" name="visualize-in" onchange="visualize()"/></label>
<pre style="background-color: #eff0f1" id="visualize-out"></pre>
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~74~~ ~~67~~ 63 bytes
Byte count assumes ISO 8859-1 encoding.
```
.
|
^
$.'$*----¶
\z
¶$` |
+`(.+\|) .+$
$&¶$1----
$
¶ |
¶
¶
```
Input is in [unary](https://codegolf.meta.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary), using any character except linefeeds as the digit.
[Try it online!](http://retina.tryitonline.net/#code=LgogfCAgCl4KJC4nJCotLS0twrYKXHoKwrYkYCB8CitgKC4rXHwpIC4rJAokJsK2JDEtLS0tCiQKwrYgfAogIMK2CsK2&input=MTExMQ)
### Explanation
```
.
|
```
We start by turning each unary digit into `|` (note the trailing spaces). This gives us the second line of the output (plus two trailing spaces if the input is at least `1`).
```
^
$.'$*----¶
```
We match the beginning of the string in order to prepend the first line. This is done using some Retina-specific substitution features. `$*` repeats the character on the right as many times as its left arugment. `$.'` evaluates the number of characters to the right of the match. Since the match is only the beginning of the string this gives as many `-` as there are characters in the string and `---` appends three more. The `¶` is an alias for a linefeed. So now we've got the first two lines.
```
\z
¶$` |
```
Now we append the next two lines. We do this by matching the end of the string and appending a linefeed, the entire string again and then `|` to get the fourth line right.
```
+`(.+\|) .+$
$&¶$1----
```
Time for the applications. The leading `+` makes Retina repeat this stage until the output stops changing (in this case because the regex no long matches). The regex matches the entire last line, provided it contains a `|` follows by a space. We capture everything up to the `|` (which will be the second to last) in group `1`. We write the line back with `$&`, a linefeed, then group 1 (thereby dropping the last `|`) and then `----`.
```
$
¶ |
```
This just adds the final line containing only a single `|`.
```
¶
¶
```
Finally we need to get rid of the trailing spaces on the second line.
[Answer]
## JavaScript (ES6), 112 bytes
```
f=
n=>`${d=`-`.repeat(n*4+3)}
${(b=` | `.repeat(n)).slice(0,-2)}
${d}
${b} |
${b.replace(/ \| /g,`$' |----
`)} |`
;
```
```
<input id=i type=number min=0 oninput=o.textContent=f(this.value)>
<pre id=o></pre>
```
[Answer]
# Python, 201 bytes
```
from pylab import*
n=input()
p=array(list(' -|\n'))
a=zeros((n+5,n*4+4),int)
for k in range(n):l=4*k+5;a[:-k-1,l]=2;a[-k-2,l-3:l+1]=1
a[:,1]=2
a[1,-3]=0
a[0]=a[2]=1
a[:,-1]=3
print''.join(ravel(p[a]))
```
[Answer]
# Python 2, 138 bytes
```
def f(n,a=1):
if ~n:b="---\n";c=" |";d=" "+c;print("-"*n*4+b+c*(n>0)+d*(n-1)+"\n"+"-"*n*4+b+c+d*n+"\n")*a+c+d*(n-1)+"-"*4*(n>0);f(n-1,0)
```
The function contains an extra parameter, but it is for internal use only. It has a default value and should be omitted when calling the function. I hope this doesn't violate the rules.
The function draws the first 5 rows, then recursively calls itself to draw the remaining rows.
[Try it online](https://repl.it/CYeq/1)
] |
[Question]
[
Inspired by the *C*-directive `#define`.
### Challenge
Given one phrase with some alias, and one array with each alias text. Output the initial phrase replacing each alias with its respective text.
An alias is defined by one sharp `#` followed by its index in the array (the index may start at zero or one). Alias can contains another alias inside its text, and you must resolve all them (maybe recursively). You can assume the alias will never run into an infinite-loop. Alias won't have leading zeroes (`#02` is not alias at index `2`, it is alias at index `0` followed by the text `2`).
You can assume the array will not pass 20 items in length.
You can write a program, or a function or even a `#define`*-it would be nice :)*
You can also use another input-method that fits better for your language.
### Example
```
phrase: "#0 & #3"
array: [
"Programming #1",
"Puzzles",
"Code",
"#2 Golf"
]
output: "Programming Puzzles & Code Golf"
```
Step by step:
```
0> "#0 & #3"
1> "Programming #1 & #2 Golf"
2> "Programming Puzzles & Code Golf"
```
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins!
### Another samples
```
phrase: "#0!"
array: [
"We are #1",
"#2",
"#3",
"#4 !",
"graduating"
]
output: "We are graduating !!"
```
---
```
phrase: "##0#1#0#21#3#4"
array: [
"a",
"m",
"z",
"n",
"g"
]
output: "#amaz1ng"
```
---
```
phrase: "##1#23"
array: [
"WEIRD",
"0 C",
"AS"
]
output: "WEIRD CAS3"
```
---
```
phrase: "#1#7#6y#4#7#10s#7b#11#0#0#11r#7#0h#6#5#2#5#9#4."
array: [
"t",
"#12#3",
"#11ga#3",
"#0#10v#11",
"#0h#10#8g",
"#7#8",
"a#8",
" ",
"n",
"o",
"i",
"e",
"P#9s#10"
]
output: "Positive anything is better than negative nothing."
```
The examples above used Array with index starting at zero.
[Answer]
# JavaScript (ES6) 58
Recursive function
```
f=(s,h,r=s.replace(/#(1?\d)/g,(_,x)=>h[x]))=>r==s?r:f(r,h)
```
*Test*
```
f=(s,h,r=s.replace(/#(1?\d)/g,(_,x)=>h[x]))=>r==s?r:f(r,h)
// Version without default parameters, same length but using a global
// f=(s,h)=>(r=s.replace(/#(1?\d)/g,(_,x)=>h[x]))==s?r:f(r,h)
console.log=x=>O.textContent+=x+'\n'
;[
['##1#23',['WEIRD','0 C','AS']],
["#0!",["We are #1","#2","#3","#4 !","graduating"]],
["##0#1#0#21#3#4",["a","m","z","n","g"]],
["##0#1#0#21#13#4",["a","m","z","","g","","","","","","","","","n"]],
["#1#7#6y#4#7#10s#7b#11#0#0#11r#7#0h#6#5#2#5#9#4.",
["t","#12#3","#11ga#3","#0#10v#11","#0h#10#8g","#7#8","a#8"," ","n","o","i","e","P#9s#10"]
],
["#0 & #3",["Programming #1","Puzzles","Code","#2 Golf"]]
].forEach(t=>{
var a=t[0],b=t[1]
console.log(a+' ['+b+']\n -> '+f(a,b))
})
```
```
<pre id=O></pre>
```
[Answer]
# Mathematica, 74 bytes
```
FixedPoint[#~StringReplace~a&,a=0;a=Reverse["#"<>ToString@a++->#&/@#2];#]&
```
Not too complicated. Most of it is just dedicated to creating the indices.
[Answer]
# Julia, ~~112~~ ~~107~~ 66 bytes
```
f(s,x)=(r=replace(s,r"#1?\d",m->x[1+parse(m[2:end])]))==s?s:f(r,x)
```
This is a recursive function that accepts a string an an array and returns a string. It uses 0-based indexing.
We begin by constructing a string *r* as the input string *s* with all matches of the regular expression `#1?\d` replaced with the element of *x* corresponding to 1 + the integer parsed out of the match. If this is equal to *s*, we return *s*, otherwise we recurse, passing *r* as the string.
[Answer]
# C, ~~269~~ 232
```
#define f(p,a,l)char*n,o[999],i=0,c,x;for(strcpy(o,p);o[i];)o[i]==35&isdigit(o[i+1])?c=o[i+1]-48,c=isdigit(o[i+2])&c?10*c+o[i+2]-48:c,n=a[c<l?c:c/10],x=strlen(n),memmove(o+i+x,o+i+2+c/10,strlen(o+i)),i=!memmove(o+i,n,x):++i;puts(o);
```
As requested, a single `#define` solving the problem! C macros can't be recursive, so the problem had to be solved iteratively. The macro takes 3 arguments; the phrase `p`, the array `a`, and the length of the array `l`. ~~I only stripped whitespace from my ungolfed solution; I know there are a few more characters I can save, but I don't think it will get me below 200. This will definitely not be a competitive solution.~~ Solution is fully golfed. Ungolfed solution in the form of a function below:
```
f(char*p,char**a,int l){
char o[999]={0},i=0;
strcpy(o,p);
while(o[i]){
if(o[i]=='#'&&isdigit(o[i+1])){
int c = o[i+1]-'0';
if(isdigit(o[i+2])&&c)
c=10*c+o[i+2]-'0';
if(c>=l)
c/=10;
char *n=a[c];
memmove(o+i+strlen(n),o+i+2+c/10,strlen(o+i));
memmove(o+i,n,strlen(n));
i=0;
}else{
i++;
}
}
puts(o);
}
```
And test code:
```
void test(char *phrase, char **array, int length) {
f(phrase, array, length);
}
main() {
const char *t1[] = {
"Programming #1","Puzzles","Code","#2 Golf"
};
test("#0 & #3", t1, 4);
const char *t2[] = {
"We are #1","#2","#3","#4 !","graduating"
};
test("#0!", t2, 5);
const char *t3[] = {
"a","m","z", "n","g"
};
test("##0#1#0#21#3#4", t3, 5);
const char *t4[] = {
"WEIRD","0 C","AS"
};
test("##1#23", t4, 3);
const char *t5[] = {
"t","#12#3","#11ga#3","#0#10v#11","#0h#10#8g","#7#8","a#8"," ","n","o","i","e","P#9s#10"
};
test("#1#7#6y#4#7#10s#7b#11#0#0#11r#7#0h#6#5#2#5#9#4.", t5, 13);
}
```
EDIT: Worked some golfing magic. It's as about as short and unreadable as I think it can get.
] |
[Question]
[
Recently I've been having [some trouble](https://github.com/vihanb/TeaScript/issues/16) with the new [TeaScript](https://github.com/vihanb/teascript) interpreter. The biggest problem is identifying whether or not a string contains any special characters.
---
# Challenge
A special character is defined as a character with codepoint 160 to 255. You will be given an input which is a string of characters with codepoints 0 to 255, at most one of which is a special character. The input will consist of a prefix of zero or more characters, a quoted string, and a suffix of zero or more characters. If there is a special character in the quoted string you should output a truthy value, otherwise a falsey value.
## Details
* The characters `"'` are considered quotes.
* Inside the quoted string, a backslash `\` will be used to escape the following character. In the prefix and suffix, it has no special meaning.
* Quotes will always be balanced.
* There will only be one quoted string.
## Examples
```
"Hello, World¡"
true
"Hello, World"¡
false
"Hello' Wo\"rld\\"¡
false
ab"cd\"ef\\gh\i\\"£
false
\"foo¡"
true
```
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~19~~ 17 bytes
*Thanks to user81655 for saving 2 bytes.*
Byte count uses ISO 8859-1.
```
['"].*[¡-ÿ].*['"]
```
Output is 0 or 1.
[Try it online.](http://retina.tryitonline.net/#code=WyciXS4qW8KhLcO_XS4qWyciXQ&input=XCJmb2_CoSI)
### Explanation
Due to the assumptions of the challenge, the first `'` or `"` will start the only string of the input and the last `'` or `"` ends it. We also don't need to worry about them being the same because they are guaranteed to be the same anyway.
Therefore, the regex just tries to find a character with code point 161 to 255, inclusive, which is preceded by one quote and followed by another. There will always be either 0 or 1 match.
[Answer]
**Note:** This can be done with a simple regular expression. `s=>s.match`['"].*[¡-ÿ].*['"]`` is 29 bytes in JavaScript, but it's more fun without regular expressions:
# JavaScript (ES6), ~~84~~ 82 bytes
```
s=>[...s].map((c,i)=>q?i<s.lastIndexOf(q)&c>" "?r=1:s:c=="'"|c=='"'?q=c:0,q=r=0)|r
```
## Explanation
Returns `1` for `true` and `0` for `false`. The `" "` in the code below is a `U+00A0 NO-BREAK SPACE` (code point 160).
```
s=>
[...s].map((c,i)=> // for each character c in the string
q?
i<s.lastIndexOf(q) // if we are still inside the string
&c>" "?r=1 // and c is a "unicode character", set the result to 1 (true)
:s // returning s for false guarantees that the array returned by map
// will cast to NaN, which allows us to use |r instead of &&r
:c=="'"|c=='"'? // if we are starting a string
q=c // set the end of string character
:0,
q= // q = end string character
r=0, // initialise r to 0 (false)
)|r // return r
```
## Test
```
var solution = s=>[...s].map((c,i)=>q?i<s.lastIndexOf(q)&c>" "?r=1:s:c=="'"|c=='"'?q=c:0,q=r=0)|r
```
```
<input type="text" id="input" value='ab"cd\"ef\\gh\i\\"£' />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
] |
[Question]
[
NB : Everything presented in the situation is totally fake and had just been put here to make the challenge a little more fun ;) ... Or maybe not ;)
---
=== === BEGINNING TRANSMISSION === ===
Hello,
I recently had a disk failure. I hopefully had backups and I now want my photos back. However, EVERY backup looks corrupted in the parallel universe where I live. But that's not a problem, because we had special tools to help user find their files back. They work a little bit like yours, and looks around a disk for headers that look like images. As they are still in beta, the software recovers any image it finds, gives it a random name and outputs a list containing:
* The model of the camera that took the photo, or a single `-` if not available. Note that the model could contain spaces, but no `-`.
* A tab char (`\t`, ASCII 9)
* The name of the photo file.
The file is a standard text file and looks like that:
```
[...]
- uyfeiebsvH.jpg
- hv754ce758.gif
- 8321214736.jpg
- FgnvsfHJBs.jpg
- OMGILOVYOU.jpg
- HElloDearH.png
- umanHAYYSG.jpg
COOLCAM S1332 umanIAYYSG.jpg
iCell 7G 1234567890.jpg
[...]
```
The file is quite big, and I can't rely on my little Ubro to move all the file that have a model in a separate directory.
---
Dear Human, I need your help. I want you to move all photos that have data about the camera in a separate directory, so I could find my little cute cat pictures out of this mess of icons, screenshots...
However, these backups are taking place on My LiquidStateDrive46X, so I don't have a lot of space left (and I'm actually downloading the Internet, so, you know, it's difficult to download something else while doing that. I just can barely surf the web and you are the only one I've found, human!)
Don't let me live that way ! Please, write my a small program that will do the work for me, and save a little Ubro.
---
* As this is code-golf, the shortest program wins
* I need to be able to launch you program, HUMAN ! So make sure your program has an existing interpreter.
* You can expect the list file to be in the directory where I launch your script. It will be named ./list.txt
* You need to move images to ./withmodel/
* Every image recovered is in the same directory from where I launch your program
* No image have a - in his name. Same goes for camera models
* It need to be a real program, not a simple function.
* No internet access, I'm DOWNLOADING! This is really important.
* I need my cat images quickly, or I can't survive: This code-golf will end on the 10th of October, if I'm still alive on this day.
=== === END OF TRANSMISSION === ===
[Answer]
### PowerShell (v4), 58 49 bytes
```
(gc list.txt)-replace"^[^-]*`t"|mv -des withmodel
# Previous 58 byte version
(gc list.txt)-notmatch'^-'-replace".+`t"|mv -des withmodel
```
* get-content of the list
* remove camera models up to the tab by replacing them with nothing. This won't change the lines starting with "-".
* pipe into the move command, destination folder 'withmodel'. This will hit a lot of errors for the unchanged lines starting with "-", but since none of the files has a "-" in the name, that won't move any incorrect files, only the right files will be moved.
] |
[Question]
[
The idea here is to produce an *almost* repeating pattern. That is, the sequence being constructed changes at the last moment to avoid a repetition of some subsequence. Subsequences of the type AA and ABA are to be avoided (where B is no longer than A).
## Examples:
I'll go ahead and start by listing all of the small examples to make my description clearer. Let's start with 0.
```
Valid: 0
Invalid: 00 (AA pattern)
Valid: 01
Invalid: 010 (ABA pattern)
Invalid: 011 (AA pattern)
Valid: 012
Valid: 0120
Invalid: 0121 (ABA pattern)
Invalid: 0122 (AA pattern)
Invalid: 01200 (AA pattern)
Invalid: 01201 (ABA pattern; 01-2-01)
Invalid: 01202 (ABA pattern)
Valid: 01203
```
Now, I strongly believe that a `4` is never needed, though I do not have a proof, because I have easily found sequences of hundreds of characters long that use only `0123`. (It's probably closely related to how only three characters are needed to have infinite strings that do not have any AA patterns. There's a [Wikipedia page](https://en.wikipedia.org/wiki/Square-free_word) on this.)
## Input/Output
Input is a single, positive, non-zero integer `n`. You may assume that `n <= 1000`.
Output is an `n`-character sequence with no subsequences that match either prohibited pattern (AA or ABA).
### Sample inputs and outputs
```
>>> 1
0
>>> 2
01
>>> 3
012
>>> 4
0120
>>> 5
01203
>>> 50
01203102130123103201302103120132102301203102132012
```
## Rules
* Only the characters `0123` are allowed.
* B is no longer than A. This is to avoid the situation where `012345` has to be followed by `6` because `0123451` has this: `1-2345-1`. In other words, the sequence would be trivial and uninteresting.
* `n` may be inputted through any method desired, **except** hard-coding.
* Output may be either a list or a string, depending on which is easier.
* **No brute force**; the run time should be on the order of minutes, at most an hour on a really slow machine, for `n=1000`. (This is intended to disqualify solutions that just loop through all `n`-length permutations of `{0,1,2,3}`, so that trick and similar tricks are disallowed.)
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed, as usual.
* Scoring is in bytes. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest entry wins (probably - see bonus).
* **Bonus:** pick the lowest allowed digit at each step. If `1` and `3` are possible choices for the next digit in the sequence, pick `1`. Subtract **5** bytes from your score. However, take note of the note below.
## Note!
Dead-ends are possible. Your program or function must avoid these. Here's an example:
```
Stump: 0120310213012310320130210312013210230120310213201230210312013023103201230213203102301203210231201302103123013203102130120321023013203123021032012310213012031023013203123021320123102130120
Stump: 0120310213012310320130210312013210230120310213201230210312013023103201230213203102301203210231201302103123013203102130120321023013203123021032012310213012031023013203123021320123102130123
Stump: 012031021301231032013021031201321023012031021320123021031201302310320123021320310230120321023120130210312301320310213012032102301320312302103201231021301203102301320312302132012310320
Stump: 012031021301231032013021031201321023012031021320123021031201302310320123021320310230120321023120130210312301320310213012032102301320312302103201231021301203102301320312302132012310321301203102130
```
Each of these sequences cannot be extended any further (without using a `4`). But also note that there is a crucial difference between the first two and the second two. I'll replace the shared initial subsequence with an `X` to make this clearer.
```
Stump: X2130120
Stump: X2130123
Stump: X320
Stump: X321301203102130
```
The last two digits of `X` are `10`, so the only possible choices for the next digit are `2` and `3`. Choosing `2` leads to a situation where the sequence *must* terminate. **The greedy algorithm will *not* work here.** (Not without backtracking, anyway.)
[Answer]
# [Retina](https://github.com/mbuettner/retina), 86 bytes - 5 = 81
```
$
_
(r`^(?<-2>.)+_((.)+)\b$
$1!
\b$
0
3#
#
0#
1
1#
2
2#
3
)r`\1(?<-2>.)*((.)+)$
$0#
!
<empty>
```
Where `<empty>` represents an empty trailing line. You can run the above code from a single file with the `-s` flag.
The input should be given in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary), e.g. `111111`. I haven't tested it for output on the order of thousands yet - two of the regexes might get a bit slow after a while - but it can easily handle a couple of hundred in a few seconds.
## Explanation
This is a simple backtracking solution.
1. Append a `0`.
2. While the current sequence is invalid, remove all trailing 3s and increment the last non-`3`.
3. Repeat until we have a valid sequence of the desired length.
This backtracking is implemented by a loop of regex substitutions which aborts once the string remains unchanged through one iteration.
```
$
_
```
This appends a `_` to the input, which is used to separate the unary input from the sequence we're building.
```
(r`^(?<-2>.)+_((.)+)\b$
$1!
```
This is the first substitution in the loop (indicated by the leading `(`). The regex matches if a) there is a word character (i.e. a digit) at the end the string (which means the string is valid - we'll see below that invalid sequences are marked with a trailing `#`) and b) there are at least as many characters in the sequence as in the input (this is checked using [balancing groups](https://stackoverflow.com/a/17004406/1633117)). If that's the case, we remove the input and append a `!`. This `!` serves to make all regexes in the loop fail, such that it terminates.
```
\b$
0
```
If there is a word character at the end (i.e. the sequence is valid, and the loop wasn't terminated by the previous step), append a `0`.
```
3#
#
```
If (instead) the sequence had been marked invalid and ended in `3`, we remove that `3` (but leave the sequence as invalid, because there's no possible continuation for the current prefix... so the next character needs to be backtracked as well).
```
0#
1
1#
2
2#
3
```
If the sequence is marked invalid and any digit other than `3` is at the end, we increment the digit and remove the marker.
```
)r`\1(?<-2>.)*((.)+)$
$0#
```
The last substitution in the loop (as indicated by the `)`). It checks whether the string ends in `ABA` (where `B` is not longer than `A` but potentially empty). The relative lengths of `A` and `B` are again checked using balancing groups, and the repetition of `A` is checked with a simple backreference.
If this regex matches, we mark the sequence invalid by appending `#`.
```
!
<empty>
```
Once the loop terminates, all we need to do is remove the `!` and are then left with the desired output.
[Answer]
# Python 2, 175 - 5 = 170 bytes
```
n=input();s='';u=j=-1
while n>len(s):
while u>2:u=int(s[0]);s=s[1:]
u+=1;t=`u`+s;m=c=0
while t[c:]*0**m:c+=1;i=t[c:].find(t[:c]);m=j<i<=c
if c>=len(t):s=t;u=j
print s[::j]
```
This is the greedy algorithm with backtracking. I wish it were shorter. I hope it's correct (see below).
It builds the string one digit at a time. Given a string of `d` digits that it has found already, it tries to append a `0` as the `(d+1)`st digit. If that doesn't work, then it tries a `1`, then a `2`, then a `3`. If none of these works, then it goes back to the `d`th digit and increments it (if less than `3`) or removes it (if equal to `3`, in which case it increments the previous one, etc.).
The check for validity is the line with `.find` in it. In case anyone decides to read my code, I should say that this program is actually storing the string backwards, meaning that it's adding digits to the *front*. So the check involves looking for places where the *first* `c` digits appear again later on in the string (anyplace after the first `c` digits), and if there are any such places, whether the intervening length is at most `c`.
(Of course it reverses the string before printing.)
It could also easily be faster; I originally had it exiting various loops early for efficiency, but that cost precious bytes. It still does OK in the range of `n=1000`, though.
Anyway, the program does seem to exhibit a preference for the smaller digits, but it's not a very strong preference. For example, running it with `n=2000` gave me a string with `523` zeros, `502` ones, `497` twos and `478` threes, ending in `30210312013021`. So if anyone else is working on a greedy algorithm, maybe they can confirm this result. Or with `n=1000` I got `[263, 251, 248, 238]` for the counts by digit.
Finally, I would mention that these counts are sort of suggestive of symmetry, almost (though not exactly) as if we had started with a uniform distribution and then converted some of the `3`'s to `0`'s and a few of the `2`'s to `1`'s. But obviously that could just be coincidence. I have no idea!
[Answer]
# Haskell, 115 (120 bytes − 5 bonus)
```
x?_|or[t x==t(drop i x)|i<-[1..length x],t<-[take$div(i+1)2]]=[]
x?0=[x]
x?n=(?(n-1)).(:x)=<<"0123"
f=reverse.head.([]?)
```
[Run online at Ideone](http://ideone.com/ZtVE56)
Example run:
```
*Main> f 40
"0120310213012310320130210312013210230120"
```
] |
[Question]
[
# The Challenge
Consider the 3x3 king grid, as shown in the following ASCII graphic:
```
A--B--C
|\/|\/|
|/\|/\|
D--E--F
|\/|\/|
|/\|/\|
G--H--I
```
You are given as input a length-9 list of integers that represent a labeling of the nodes. For example, the input `[0,1,1,2,1,0,5,5,1]` represents the following labeling:
```
0--1--1
|\/|\/|
|/\|/\|
2--1--0
|\/|\/|
|/\|/\|
5--5--1
```
Your output is the set of integers in the input that form connected sets of nodes. More explicitly, the output should contain an integer `n` from the input if and only if the set of nodes with label `n` is connected. In this example, an acceptable output would be `[1,2,5]`, since the two `0`s are not connected. The lowest byte count wins.
# Detailed rules
* You can choose a **fixed ordering** for the nodes in your input list, and you should state this in your answer. In the order EFBDHCAGI, the above labeling would be given as `[1,0,1,2,5,1,0,5,1]`.
* You can write either a full program or a function. In the latter case, the output can be a set of integers if your language supports those.
* The output list may contain duplicates, but its length must not exceed 9.
* Standard loopholes are disallowed.
# Test cases
These have single-digit numbers aligned to the grid; adjust them to your chosen order.
```
011
210 => 1 2 5
551
010
202 => 0 2
221
110
123 => 0 2 3
221
111
111 => 1
111
111
141 => 1 4
111
```
[Answer]
# J, 54 bytes
```
#~3 :'0<*/,+/ .*/^:8~y#|:y#,/,"1/({0&,:)3 3$#:13'"1@e.
```
A function taking a list in the order `ABCDEFGHI`.
Given an adjacency matrix *A* of a graph of order *n*, the graph is connected if and only if all the entries of (*A* + *I*)*n* are nonzero, where *I* is the *n*×*n* identity matrix.
We start with the (fixed) adjacency-plus-identity matrix of the 3×3 king grid (in the order `ABCDEFGHI`,) namely:
```
1 1 0 1 1 0 0 0 0
1 1 1 1 1 1 0 0 0
0 1 1 0 1 1 0 0 0
1 1 0 1 1 0 1 1 0
1 1 1 1 1 1 1 1 1
0 1 1 0 1 1 0 1 1
0 0 0 1 1 0 1 1 0
0 0 0 1 1 1 1 1 1
0 0 0 0 1 1 0 1 1
```
.
For each label `l`, we select the rows and columns corresponding to the nodes of label `l`.
This gives us the adjacency-plus-identity matrix of the subgraph of `l`-labeled nodes.
We then use this matrix to test if the subgraph is connected, as described above.
We construct the above matrix by noting that if we let
```
0 0 0
Z = 0 0 0
0 0 0
```
and
```
1 1 0
O = 1 1 1
0 1 1
```
, then the matrix can be seen as the 3×3 block matrix
```
O O Z
O O O
Z O O
```
, which has the same pattern as `O`!
`O` is produced by repeating the pattern `1 1 0 1` in a 3×3 block.
[Answer]
# CJam, 56 67 bytes
```
q~4/~\@{a1$2<-\(+}%)_)-{_(+{\(a@-\}}A?%+:+[$_(d+1$)c\+@]zLf|2f>:+|`
```
Order: `CIGABFHDE`.
Example input:
```
[1 1 5 0 1 0 5 2 1]
```
Output:
```
[1 2 5]
```
It firstly removes numbers in the corners which are the same as connected numbers on the sides. Then it removes numbers on the sides which are the same as the numbers on the next sides. Finally it removes all numbers occurred two or more times and add the center number.
[Answer]
# CJam, 90 bytes
This is based on a iterative flood fill explained [here](https://codegolf.stackexchange.com/a/41404/31414) and can be golfed a lot!
```
q~:Q{:IQ3/S*Sca5*+:T;G,G*{:AT=1$={[WXZ5 4_~_)_)]Af+Tf=AT='#a+&,g{TA'#t:T;}*}*}%;aT\/,3<},p
```
Requires the input in order of `ABCDEFGH` like:
```
[0 1 1 2 1 0 5 5 1]
```
and output is the connected nodes:
```
[1 1 2 1 5 5 1]
```
**Brief Explanation**
* First, I iterate over the input array for each label.
* In each iteration, I perform floodfill to figure out disconnected nodes.
* If the number of disconnected nodes is greater than 1, then that label is disconnected.
+ 1 because a label can have just 1 occurrence in the input array too.
* Then I simply filter out disconnected labels and print the array.
*Full explanation to follow*
[Try it online here](http://cjam.aditsu.net/)
] |
[Question]
[
# Sequences
You are given four number sequences, numbered `1` through `4`.
1. [OEIS](https://oeis.org/A003607) The location of `0`'s when the natural numbers are listed in binary. Here's an example of how to calculate the sequence:
```
0,1,10,11,100,101,110,111
^ ^ ^^ ^ ^
0 3 78 10 14
```
The start of the sequence goes like this: `0, 3, 7, 8, 10, 14, 19, 20, 21, 23, 24, 27, 29, 31, 36, 37, 40, 45, 51, ...`
---
2. [OEIS](https://oeis.org/A161983) This sequence includes the first natural number, skips the next two, then includes the next three, then skips the next four, and continues.
```
0, 3, 4, 5, 10, 11, 12, 13, 14, 21, 22, 23, 24, 25, 26, 27, 36, ...
```
---
3. [OEIS](https://oeis.org/A143072) Positive integers where both the number of `0`'s and the number of `1`'s in the binary representation of the number are powers of `2`.
```
2, 4, 5, 6, 9, 10, 12, 16, 23, 27, 29, 30, 33, 34, 36, 39,
```
---
4. [OEIS](http://oeis.org/A005185) The Hofstadter Q [sequence](http://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence).
>
> a(1) = a(2) = 1;
>
> a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2.
>
>
>
```
1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6, 8, 8, 8, 10, 9, 10, 11, 11, 12, 12, 12, 12, 16, 14, ...
```
Little is proven rigorously about this sequence, but many empirical results exist. One is particularly important, and you may assume it's valid for the entire series:
[This paper](http://arxiv.org/pdf/chao-dyn/9803012v2.pdf) observed that the elements of the series can be grouped into generations. If we number them starting at 1, then the *k*th generation contains exactly 2k elements. The relevant property is that all numbers in generation *k* are obtained by summing two numbers from generations *k-1* and/or *k-2*, but never from earlier generations. You may use this (and only this) observation to put a lower bound on the remaining elements in the sequence.
---
# Challenge
Your challenge is to print the first `x` numbers in the intersection of the given input sequences.
**Input:** Two numbers separated by a space on `STDIN`. The first number is an integer from `1` to `15` inclusive where each bit corresponds to a sequence. The lowest bit corresponds to sequence `1`, and the highest corresponds to sequence `4`. The second is amount of numbers, `x`, to output on `STDIN`.
**Output:** The first `x` numbers that intersect with the given input sequences. Print the numbers on `STDOUT` with any clear whitespace or punctuation as a delimiter (spaces, tabs, newlines, commas, colons, periods, etc).
---
# Examples
**1.** Print the first `3` numbers that are in every sequence.
Input: `15 3`
Output: `10,23,40`
---
**2.** Print the first `12` numbers in sequences number `1` and `4`.
Input: `9 12`
Output: `3,8,10,14,19,20,21,23,24,31,37,40`
---
**3.** Print the first `10` numbers in sequence `2`.
Input: `2 10`
Output: `0,3,4,5,10,11,12,13,14,21`
---
**4.** Print the first `6` numbers in sequences `3` and `4`.
Input: `12 6`
Output: `2,4,5,6,9,10`
---
# Details
* You may print the output as you go or all at once at the end.
*Huge thanks to everyone who helped out with this in chat! This question benefited greatly from being in the [sandbox](http://meta.codegolf.stackexchange.com/questions/2140/sandbox-for-proposed-challenges).*
[Answer]
# Python 3, ~~590~~ 639 characters
```
from itertools import count as C
D=lambda n,t='1':bin(n).count(t)
Y=range
def O():
for n in C(0):yield from bin(n)[2:]
def B():
s=i=0
while 1:
i+=s
for j in Y(i,i+s+1):yield j
s+=2;i+=s-1
def s(i):return D(i)==1
def F():
a=[1]*3
for n in C(3):a+=[a[n-a[n-1]]+a[n-a[n-2]]];yield a[-1]
L,R=input().split()
J=[x for x,U in zip([F(),(n for n in C(0)if s(D(n,'0')-1)and s(D(n))),B(),(i for i,c in enumerate(O())if'1'>c)],"{0:04b}".format(int(L)))if U>'0']
X=[set()for _ in J]
M=[]
Z=int(R);K=1
while len(M)<Z:
for x,j in zip(X,J):x.add(next(j))
for _ in Y(K):X[0].add(next(J[0]));K+=1
M=X[0]
for x in X:M=M&x
print(sorted(M)[:Z])
```
This is the straight-forward solution: use generators to define each of the infinite sequences, and so long as the intersection isn't large enough, add a step to each sequence.
To account for the non-monotonically-increasing Hofstadter sequence: at each step I generate twice as many for that sequence, e.g. 1, then 2, 4, 8, 16, 32, etc. I think that satisfies the bound stated in the question, and it's still fast enough for all the test cases presented there.
[Answer]
**C#, 1923**
It probably wont be the shortest program but i found the challenge interesting, so here is my solution.
Running all 4 with 35 Numbers (15 35) takes about 5 seconds.
You can test it [here](https://dotnetfiddle.net/auyE8t), but note that if you want OEIS4 the amount of digits you want needs to be small or netfiddle runs out of memory.
**Golfed**
```
using System;using System.Collections;using System.Collections.Generic;using System.Linq;class p{public static void Main(string[] args){int b=0;IEnumerable<int>a=null;foreach(char c in Convert.ToString(int.Parse(args[0]),2).Reverse()){++b;if(c=='0')continue;switch(b){case 1: a=d(a,e());break;case 2: a=d(a,f());break;case 3: a=d(a,g());break;case 4: a=d(a,h(),true);break;}}if(a==null)return;bool j=true;foreach(int i in a.Take(int.Parse(args[1]))){if(j)j=false;else Console.Write(",");Console.Write(i);}}static IEnumerable<int>d(IEnumerable<int>k,IEnumerable<int>l,bool m=false){if(k==null)foreach(int n in l)yield return n;int o=0;int p=1;foreach(int i in k){Dictionary<int,HashSet<int>>q=m ? new Dictionary<int,HashSet<int>>(): null;int s=0;foreach(int n in l){if(!m){if(i<n)break;}else{if(!q.ContainsKey(o))q.Add(o,new HashSet<int>());q[o].Add(n);if(q.Count==1){int r=q[o].OrderBy(gi =>gi).Take(2).Sum();if(i<r)break;}else{int r=q[o].Concat(q[o-1]).OrderBy(gi =>gi).Take(2).Sum();if(i<r)break;}if(++s==p){o++;p=(int)Math.Pow(2,o);}}if(i==n){yield return i;break;}}}}static IEnumerable<int>e(){int t=0;for(int i=0;i<int.MaxValue;i++)foreach(char c in Convert.ToString(i,2)){if(c=='0')yield return t;t++;}}static IEnumerable<int>f(){int t=1;int u=0;bool v=true;using(IEnumerator<int>w=Enumerable.Range(0,int.MaxValue).GetEnumerator()){while(w.MoveNext()){if(v){if(u==0)u=t+1;yield return w.Current;if(--t==0)v=false;}else{if(t==0)t=u+1;if(--u==0)v=true;}}}}static IEnumerable<int>g(){for(int i=0;i<int.MaxValue;i++){string s=Convert.ToString(i,2);if(x(s.Count(c =>c=='0'))&& x(s.Count(c =>c=='1')))yield return i;}}static bool x(int y){return(y != 0)&&((y &(y-1))==0);}static IEnumerable<int>h(){return Enumerable.Range(1,int.MaxValue).Select(z);}static Dictionary<int,int>_=new Dictionary<int,int>();static int z(int n){int a;if(!_.TryGetValue(n,out a)){if(n<3)a=1;else a=z(n-z(n-1))+z(n-z(n-2));_.Add(n,a);}return a;}}
```
**Readable**
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Programm
{
public static void Main(string[] args)
{
int index = 0;
IEnumerable<int> intersection = null;
foreach (char c in Convert.ToString(int.Parse(args[0]), 2).Reverse())
{
++index;
if (c == '0')
continue;
switch (index)
{
case 1: intersection = _join(intersection, OEIS1()); break;
case 2: intersection = _join(intersection, OEIS2()); break;
case 3: intersection = _join(intersection, OEIS3()); break;
case 4: intersection = _join(intersection, OEIS4(), true); break;
default: throw new ArgumentException();
}
}
if (intersection == null)
return;
bool first = true;
foreach (int i in intersection.Take(int.Parse(args[1])))
{
if (first) first = false;
else Console.Write(",");
Console.Write(i);
}
Console.ReadKey();
}
private static IEnumerable<int> _join(IEnumerable<int> intersection, IEnumerable<int> newSequence, bool hof = false)
{
if (intersection == null)
foreach (int n in newSequence) yield return n;
int generation = 0;
int generationMax = 1;
foreach (int i in intersection)
{
Dictionary<int, HashSet<int>> generationCache = hof ? new Dictionary<int, HashSet<int>>() : null;
int count = 0;
foreach (int n in newSequence)
{
if (!hof)
{
if (i < n)
break;
}
else
{
if (!generationCache.ContainsKey(generation))
generationCache.Add(generation, new HashSet<int>());
generationCache[generation].Add(n);
if (generationCache.Count == 1)
{
int lowerBound = generationCache[generation].OrderBy(gi => gi).Take(2).Sum();
if (i < lowerBound)
break;
}
else
{
int lowerBound = generationCache[generation].Concat(generationCache[generation - 1]).OrderBy(gi => gi).Take(2).Sum();
if (i < lowerBound)
break;
}
if (++count == generationMax)
{
generation++;
generationMax = (int)Math.Pow(2, generation);
}
}
if (i == n)
{
yield return i;
break;
}
}
}
}
static IEnumerable<int> OEIS1()
{
int position = 0;
for (int i = 0; i < int.MaxValue; i++)
foreach (char c in Convert.ToString(i, 2))
{
if (c == '0')
yield return position;
position++;
}
}
static IEnumerable<int> OEIS2()
{
int take = 1;
int skip = 0;
bool doTake = true;
using (IEnumerator<int> enumerator = Enumerable.Range(0, int.MaxValue).GetEnumerator())
{
while (enumerator.MoveNext())
{
if (doTake)
{
if (skip == 0)
skip = take + 1;
yield return enumerator.Current;
if (--take == 0)
doTake = false;
}
else
{
if (take == 0)
take = skip + 1;
if (--skip == 0)
doTake = true;
}
}
}
}
static IEnumerable<int> OEIS3()
{
for (int i = 0; i < int.MaxValue; i++)
{
string s = Convert.ToString(i, 2);
if (_isPowerOfTwo(s.Count(c => c == '0')) && _isPowerOfTwo(s.Count(c => c == '1')))
yield return i;
}
}
static bool _isPowerOfTwo(int number)
{
return (number != 0) && ((number & (number - 1)) == 0);
}
static IEnumerable<int> OEIS4()
{
return Enumerable.Range(1, int.MaxValue).Select(HofstadterQ);
}
static Dictionary<int, int> _hofstadterQCache = new Dictionary<int, int>();
static int HofstadterQ(int n)
{
int result;
if (!_hofstadterQCache.TryGetValue(n, out result))
{
if (n < 3)
result = 1;
else
result = HofstadterQ(n - HofstadterQ(n - 1)) + HofstadterQ(n - HofstadterQ(n - 2));
_hofstadterQCache.Add(n, result);
}
return result;
}
}
```
**Explanation**
This makes use of lazy evaluation bigtime which makes it prett fast i bellieve. Also i was lazy doing any "bitlogic" by using the frameworks Convert.ToString(number, 2) method. This turns any number into its binray representation as a string.
I had to write my own method to intersect the seuqences as the Linq-Method intersect computes the intersection of the full sequence, and that was literally impossible.
[Answer]
# Haskell, 495 442 402
```
import Data.List
d=1:1:1%2
f=filter
p 0="0"
p 1="1"
p n=p(div n 2)++p(mod n 2)
l=length
u z[a,b]=sort.head.dropWhile((<b).l)$m(nub.foldl1 intersect.y(tail.p$31-a).(`m`[d,f(v.group.sort.p)[1..],z#1,y(z>>=p)z]).take)z
w=(=='0')
v[a]=1>2
v x=all(all w.tail.p.l)x
y x=m snd.f(w.fst).zip x
x#n=n`take`x++drop(n+n+1)x#(n+2)
n%m=d!!(m-d!!n)+d!!(m-d!!(n-1)):m%(m+1)
main=interact$show.u[0..].m read.words
m=map
```
It performs reasonably well. Here are a couple of OP's examples:
```
Flonk@home:~>echo 15 10 | codegolf
[10,23,40,57,58,139,147,149,212,228]
Flonk@home:~>echo 9 12 | codegolf
[3,8,10,14,19,20,21,23,24,31,37,40]
Flonk@home:~>echo 2 10 | codegolf
[0,3,4,5,10,11,12,13,14,21]
Flonk@home:~>echo 12 6 | codegolf
[2,4,5,6,9,10]
```
] |
[Question]
[
Find the greatest gcd of the numbers \$n^m + k\$ and \$(n+1)^m + k\$ for given `m` and `k`.
For example, for `m=3, k=1` we have:
* \$n = 1\$: \$\gcd(1^3 + 1, 2^3 + 1) = 1\$
* \$n = 2\$: \$\gcd(2^3 + 1, 3^3 + 1) = 1\$
\$\vdots\$
* \$n = 5\$: \$\gcd(5^3 + 1, 6^3 + 1) = 7\$ (max)
\$\vdots\$
* \$n \to \infty\$
### Input/Output
Input is L lines through file or stdin, EOF terminated. Each line contains two integers: `m` and `k` separated by a space.
Output is L integers separated by *any pattern* of whitespace characters (tabs, spaces, newlines etc).
### Examples
**Input**
```
2 4
2 7
3 1
4 1
3 2
5 4
10 5
```
**Output**
```
17
29
7
17
109
810001
3282561
```
### Update
I can't find a proof that the solution is bounded for all `n` given some `m` and `k`, so you only have to find the GGCD for \$n < 10,000,000\$.
[Answer]
Update:
GGCD for given `m` and `k` is good [defined](https://math.stackexchange.com/questions/56120/number-of-solutions-for-pair-of-discrete-logarithm-like-equations).
This is table of GGCD tested for n up to 500000.
```
m/k 1 2 3 4 5 6 7 8 9 10
2 5 9 13 17 21 25 29 33 37 41
3 7 109 61 433 169 973 331 1729 547 2701
4 17 33 49 65 81 97 113 129 145 2093
5 341 52501 258751 810001 1 131371 1 1 501311 2846591
6 65 129 193 257 21507 385 449 22059 577 641
7 3683 235747 1 1 71 438299 940507 33461 757 110503
8 4369 513 769 13325 1281 149089 202609 2049 975937 617201
9 359233 232537 202927 470983 123019 708589 241117 5601589 398581 19783
10 62525 514299 183757 807517 1094187 16856405 97477 8193 377897 25919971
```
For `m==2 or 4` it looks quite good :-)
It seems that if **p\_in\_i** is gcd for some **n**, where **p\_i** is a prime, than every combination of products of **p\_i**'s with exponents **<= n\_i** is also gcd for some **n**. E.g. for m=8,k=2, 3^3 and 19 are gcd of type **p\_in\_i**, also 57, 171 and 513 are gcd's.
Some theory background: If `g = gcd(n) > 1` for some `n`, and `d > 1` and `d divide g` (it can be `d=g`) than `d divide gcd(n±d)`. It is easy to prove. That means:
* If you find some `g = gcd(n) > 1` for some `n`, than `gcd(n±d) > 1`. So, it is enough to jump for found prime number of steps while iterating `n`.
* If prime `p` divide some `gcd()` than there is `n <= p` where `p` divide `gcd(n)`. Prime `p` will 'appear' in `gcd(n)` for some `n <= p`.
These properties can speed up search, but still there is a question is GGCD good defined.
[Answer]
# Ruby - 84 81 80 79 chars
Passes all test cases, not sure if it can handle larger numbers.
```
$<.map{|l|m,k=l.split.map &:to_i;p (1..$$).map{|n|(n**m+k).gcd (n+1)**m+k}.max}
```
### Test
```
D:\tmp>ruby cg_gcd.rb < cg_gcd.in
17
29
7
17
109
3361
```
[Answer]
**Sage, 92**
```
for l in sys.stdin.readlines():m,k=l.split();print max(gcd(n^m+k,(n+1)^m+k)for n in[1..1e7])
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
*@Ɱȷ7+gƝṀ
```
[Try it online!](https://tio.run/##y0rNyan8/1/L4dHGdSe2m2unH5v7cGfD/8PL9R81rfn/P5qLM9pIR8EkVgfCMAczjHUUDMEMExgDKGIEZpjCFBsa6CiYAlmxAA "Jelly – Try It Online")
This times out on TIO no matter the input due to the `Ɱȷ7` which iterates over the range \$1, 2, ..., 10^7\$. By reducing the `7` to a smaller value, we can get TIO to actually output some results (obviously it gets it wrong for inputs where \$n > 10^5\$): [Try it online!](https://tio.run/##y0rNyan8/1/L4dHGdSe2m2qnH5v7cGfD/8PL9R81rfn/P5qLM9pIR8EkVgfCMAczjHUUDMEMExgDKGIEZMQCAA "Jelly – Try It Online")
Not exactly spec-conforming, but given the age I didn't see much issue with that. Takes input in the form of command line arguments. \$m\$ first, then \$k\$
## How it works
```
*@Ɱȷ7+gƝṀ - Main link. Takes m as a left argument and k on the right
ȷ7 - 10000000
Ɱ - Over each n between 1 and 10000000:
*@ - Calculate n^m
+ - Add k
Ɲ - Over each neighbouring pair in the list (i.e. n^m+k and (n+1)^m+k):
g - Calculate their GCD
Ṁ - Output the maximum
```
] |
[Question]
[
I encountered some silly code from a game and I figured this would actually turn into a fun golfing problem, so:
Given any ASCII string in the limited char range specified below.
Append as few characters as possible such that, given:
```
i = 1
sum = 0
for char in string
sum += char.intval * i++
end for
```
`sum % 1000 == 0`
Where `intval` is the ASCII value of the character.
Both the string prefix and your permitted chars are: `A-Z a-z 0-9 . _`
You may assume the numeric result of the pseudo-code above is a number that fits within an unsigned 32-bit int (i.e. no input will be given that causes `sum` to exceed 2^32-1 after appending the minimum possible chars to satisfy `sum`)
You may choose to output the input concatenated with your calculated suffix string, or just your suffix string as you prefer.
## Example
Given the input `ddd` the shortest solution would be appending one more `d` because `(100 + (100*2) + (100*3) + (100*4)) % 1000 == 0`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
⊞υωFυ¿¬ⅈ¿﹪ΣE⁺θι×⊕λ℅κφFΣ⟦αβ⭆χκ._⟧⊞υ⁺ικι
```
[Try it online!](https://tio.run/##NY7BDsIgEETvfsXG05Kg0XOPHoyHapN6MDGmwQKWdAtKQT8faY3HmZ15O20nfOsEpVTFscPI4cOKhXYeMDIwGvDoAl6QsZ8qnYzksI4DluKJFcURXxwM43A2gxrxYFuvBmWDkkjZPXlprCDsMyFLnTkzfSJcBYc7hzp4Yx8Tbrvh0OfUct0sbzn53zS/MdONFaBoVFDlSkDDipR2Tqpm70in1Zu@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υωFυ
```
Start a breadth-first search with an empty suffix.
```
¿¬ⅈ
```
Check that a solution hasn't yet been found.
```
¿﹪ΣE⁺θι×⊕λ℅κφ
```
If the input plus current suffix is not a multiple of `1000`, then:
```
FΣ⟦αβ⭆χκ._⟧
```
Loop over all valid characters.
```
⊞υ⁺ικ
```
Append the character to the suffix and add this to the list of suffixes to check.
```
ι
```
But if it is then output the suffix as the solution.
Would be only 36 bytes to output the full string:
```
⊞υSFυ¿¬ⅈ¿﹪ΣEι×⊕λ℅κφFΣ⟦αβ⭆χκ._⟧⊞υ⁺ικι
```
[Try it online!](https://tio.run/##NY7LCsIwEEX3fsXgagJRdN2lC@miWqgLQaTEJrWh06Tk4e/H1OLyDvecO90gXGcFpVRHP2DkUJo5hiY4bd7IWLHprQOMDHQPeLEB7/m6psrKSBabOGElZtQcbnpSHkvTOTUpE5REYhyuTmojCMcM5thn/CddwIfg8OKw7i2W44HDmFvbfbt95ub/rZqiXyaypABFXkGdkYCaFSmdrFTt2VKfdh/6Ag "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Python](https://www.python.org), 147 bytes
*-7 bytes, thanks to STerliakov*
```
def f(s,q="",Q=[]):
while(i:=0)+sum((i:=i+1)*ord(c)for c in s+q)%1000:*Q,q=[q+c for c in{*map(chr,range(46,123))}-{*"/:;<=>?@[\\]^`"}]+Q
return q
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3J6ekpimkaRTrFNoqKekE2kbHalpxKZRnZOakamRa2RpoaheX5mqAmJnahppa-UUpGsmaaflFCskKmXkKxdqFmqqGBgYGVlqBQBOiC7WTFWCS1Vq5iQUayRlFOkWJeempGiZmOoZGxpqatbrVWkr6VtY2tnb2DtExMbFxCUq1sdqBXApFqSWlRXkKhVCn5RYUZeaVaKRpKClpanLBOSkpKSj8kNTiEhQBj9ScnHyF8PyiHFSFRsam5oaGKELO-Smp7vk5aUBBiKWwcAEA)
`{*map(chr,range(46,123))}-{*"/:;<=>?@[\\]^`"}` produces an iterable of the allowed characters by taking all ASCII-characters form `.` to `z` (smallest and largest allowed character) and the removing the additional characters.
Using the standard library would take the same amount of characters: `from string import*` `"._"+digits+ascii_letters`
---
# [Python](https://www.python.org), 140 bytes
```
def f(s,Q=[]):
while(i:=0)+sum((i:=i+1)*ord(c)for c in s)%1000:*Q,s=[s+c for c in{*map(chr,range(46,123))}-{*"/:;<=>?@[\\]^`"}]+Q
return s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3e1JS0xTSNIp1Am2jYzWtuBTKMzJzUjUyrWwNNLWLS3M1QMxMbUNNrfyiFI1kzbT8IoVkhcw8hWJNVUMDAwMrrUCdYtvoYu1kBZhUtVZuYoFGckaRTlFiXnqqhomZjqGRsaZmrW61lpK-lbWNrZ29Q3RMTGxcglJtrHYgl0JRaklpEdBIqJtyC4oy80o00jSUlDQ1ueCclJQUFH5IanEJioBHak5OvkJ4flEOqkIjY1NzQ0MUIef8lFT3_Jw0oCDEUliAAAA)
---
# [Python](https://www.python.org), 129 bytes
*suggested by STerliakov, uses binary strings instead of strings*
```
def f(s,Q=[]):
while(i:=0)+sum(c*(i:=i+1)for c in s)%1000:*Q,s=[[*s,c]for c in{*range(46,123)}-{*b"/:;<=>?@[\\]^`"}]+Q
return s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9NTsMwEIX3PcXIEpLtuBC35UeBABIL2EZCYuEaQWKbWgpxZTtCVdUF52DTTbkTtyFJ29W8-dH35v38Lldx4ZrtdtdGM776-1bagMGBFbmQJBvB18LWGtssT0kS2k9c0b6xCSfGeajANhDICU_TNKMFC7kQNLBKHpdr6t-bD41nF4xPpmQzXtMSnWXXN_nt3b2Yz-XrG9rIpBiB17H1HezwiOkJoceLEiEGJVJKDfVZhziIJ107eHG-3s8n0_NLzgf54JR-dLVBsksAsPS2ibhcRR1wl42QU6Wr7gQTsnc7xv8H)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
ṃØW;”.¤Ḋ
Ç;@O×JSƊȷḍ
0ç1#ḢÑ
```
[Try it online!](https://tio.run/##ATkAxv9qZWxsef//4bmDw5hXO@KAnS7CpOG4igrDhztAT8OXSlPGisi34biNCjDDpzEj4biiw5H///8ubGw "Jelly – Try It Online")
A full program that takes a string argument and implicitly prints the suffix needed.
*Thanks to Neil for pointing out a problem related to base decompression, now fixed (at a cost of two bytes and a 64-fold efficiency penalty!*
## Explanation
```
ṃØW;”.¤Ḋ # ‎⁡Helper link 1: takes an integer and generates a suffix
ṃ # ‎⁢Base decompress into:
ØW;”.¤ # ‎⁣- Word characters (A-Za-z0-9_) concatenated to "."
Ḋ # Remove first character (avoids issue related to suffixes that start with .)
‎⁤
Ç;@O×JSƊȷḍ # ‎⁢⁡Helper link 2: Takes an integer as left argument and the original string as right argument and returns 1 if it meets the requirements and zero if not
Ç # ‎⁢⁢Call helper link 1
;@ # ‎⁢⁣Concatenate the output of this to the original string
O # ‎⁢⁤Codepoints
Ɗ # ‎⁣⁡As a monadic chain:
×J # ‎⁣⁢Multiply by indices
S # ‎⁣⁣Sum
ȷḍ # ‎⁣⁤Divisible by 1000
‎⁤⁢
0ç1#ḢÑ # ‎⁤⁣Main link: takes a string as its argument and returns the suffix needed
0ç1# # ‎⁤⁤Starting with zero, find the first integer that when called into helper link 2 returns truthy
·∏¢ # Head (since # returns a list)
Ñ # ‎⁢⁡⁡Call helper link 1 to regenerate the suffix
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Scala 2](https://www.scala-lang.org/), ~~153~~ ~~142~~ 136 bytes
```
s=>{def z:Stream[String]=s#::z.flatMap(x=>'.'to'z'diff "/:;<=>?@[\\]^`"map(x+))
z.find(_.zipWithIndex.map{case(c,j)=>j*c+c}.sum%1000<1)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY_PTsJAEIfP8hSTNaatSKEYolnZqokHTSQc1HAA1LXdrUu226a7NVjC3XfwwkWfwIOvwtvY8ucic5lkvm8mv_n81gGVtP07RA1JVZTTiOE00YaLaT_VaLz0kpcJCwz0qFAwqwG8UQkcw53JhIqA-NBPjUjUcD0YA_nKDW-cLj808Wch41DgEjEabw2i9zEuXC6p6dHUnhLfci2TWIUVCs4BNfFZl_jnF8PRaPz4jOLKqTtOrVwRKrSf3EKkA2Feb1TIpm6JZwHVzA6OJg7xJ4dBPZi7Oo8PvFar1fWc-SbPD0CVJi7_sGkWaQyXWUbft6kcDA9KGCCrJwHScmqksrmNkOPsldVsAkL_2T3TZs0r7Kkd4ZpJmcAgyWRYeZXVudqx2sedE89bHaoM97Yy5rVN9sVi3f8A)
Recursively constructs an infinite Stream of possible suffixes and chooses the first with the correct sum. They iterate from shortest to longest, so it produces the correct output.
## Alternative Solution, ~~158~~ 139 bytes:
```
s=>Stream.iterate(Seq(s))(_.flatMap(s=>'.'to'z'diff "/:;<=>?@[\\]^`"map(s+))).flatten.find(_.zipWithIndex.map{case(c,j)=>j*c+c}.sum%1000<1)
```
Same idea as above, without a recursive function. Sadly, `Stream.iterate` and `flatten` is very verbose.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 121 bytes
*-3 thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
*-3 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
```
s=>{for(B=Buffer,g=n=>S=n?B([n&127])+g(n>>7):"",n=0;B(s+g(n++)).map(c=>t+=c*++i,i=t=0),t%1e3|/[^\w.]/.test(S););return S}
```
[Try it online!](https://tio.run/##dc5BC4IwGMbxe58ihGJvM7U6CMm7wA59AI9mIHMTwzbZZh2qz24FncKuv/9zeM7ltbTcNJ1bKl2JQeJgkd2lNiTFtJdSGL9GhSxDtUtJruardVwArYliLIat5/kKoyQl9kOUAgSXsiMcmaPIF5Q2foMOI/DdbCU2jzA/HW9BEQZOWEcySCAxwvVGTbPnwLWyuhVBq2siiecBTH6oqqoR3b@fj/BBt/LP@puGFw "JavaScript (Node.js) – Try It Online")
Or **[118 bytes](https://tio.run/##dc69DoIwGIXh3aswJpp@FvnRgUTy1QQHL4ARMSGlJRhsSVt0UK8dGZwMrs97hnMt76XlpuncRulKDBIHi@wptSEKQy/FtJdSGK9GhSxDdaiJYiwGmpJcraJtXMDeJikZmVIA/1Z2hCNzFPma0sZr0GEInltGYvcK8sv54ReB74R1JIMEEiNcb9Q8ew9cK6tb4be6JpIsFgCzH6qqakKP4@0JPulW/ll/0/AB)** if we can return the full string instead of just the suffix.
### Commented
```
s => { // s = input string
for( // loop:
B = Buffer, // B = alias for Buffer
g = // g is a recursive helper function
n => // taking n = integer encoding the suffix
S = // save the suffix in S
n ? // if n is not 0:
B([n & 127]) // append the char. with ASCII code n & 127
+ g(n >> 7) // and do a recursive call with n >> 7
: // else:
"", // stop
n = 0; // start with n = 0
B( // get the ASCII codes of:
s + // the input string
g(n++) // followed by the suffix computed with g(n)
) // (increment n afterwards)
.map(c => // for each ASCII code c:
t += c * ++i, // increment i and add c * i to t
i = t = 0 // start with i = 0 and t = 0
), // end of map()
t % 1e3 | // continue while t is not divisible by 1000
/[^\w.]/ // or there is an invalid character ...
.test(S); // ... in the suffix
); // end of for()
return S // return the suffix
} //
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žj'.«∞δã˜õš.Δ«ÇƶO₄Ö
```
[Try it online](https://tio.run/##ATAAz/9vc2FiaWX//8W@aicuwqviiJ7OtMOjy5zDtcWhLs6UwqvDh8a2T@KChMOW//9kZGQ) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXo/6P7stT1Dq1@1DHv3JbDi0/PObz16EK9c1Miig@tPtx@bJv/o6aWw9P@1@r8j1ZKSUlR0lECopDU4hIg5ZGak5OvEJ5flAMSNzI2NTc0BDKc81NS3fNz0oBMvZwcpVgA).
**Explanation:**
```
žj # Push builtin string "ab...yzAB...YZ01...89_"
'.¬´ '# Append an "."
‚àû # Push an infinite positive list: [1,2,3,...]
δ # Use each integer in this list as separated argument on the string:
√£ # Cartesian power
Àú # Flatten this list of lists of strings
õš # Prepend an empty string ""
.Δ # Pop and find the first value that's truthy for:
¬´ # Append the current potential suffix to the (implicit) input-string
Ç # Convert it to a list of codepoint-integers
∆∂ # Multiply each integer by its 1-based index
O # Sum the list together
₄Ö # Check whether this sum is divisible by 1000
# (after which the found result is output implicitly)
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~267~~ 190 bytes
A port of [@bsoelch's Python answer](https://codegolf.stackexchange.com/a/266556/110802) in Scala.
Saved 77 bytes thaks to @corvus\_192
---
Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=ZY9LTsMwEIbXzSksS0g2SUNSKJRAKkHLo1CeLS0PsTCJk6Zyk2C7BRLlJGxgAWdgxTnobUgosIDF6J_5_0-amcdX4RBGKm9XsMxI6I-JT604EtIL7o9iAa-nH9HNkDoSHJAgBKkCgEs9MMoHRLgvLLDBOXm46kgehP41tsBZGEhgf5EAxLkrWYg8BCHGpdLCAoDwb9KlQv6mZvgv36WMRaAfceYWWEFVm_-oymJ1xTR_AL1dAFleE8KAZ4HZgcCu_3YvY-mVa9N3YdfTCeGIaInGsI069PbnHYQ1CDWoG2Zlcam6vFJb3dhsNLe2d3Zbe_vtg8Oj45PTTves1z-_uIRYKVb1bKYyXUbt6I7yBhFUuRsEjCJjHQk1wXoSxP1ADlqhS-_1EYlTJ2eQow2xXR_OO6qT6WI8mjMNw8ApsYnu8ihGJlbVXoGjRMVrSW4PKHEzJclmXzx_69PTTD8B)
```
s=>{var(a,z,l)=(Seq[String](),"",".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
val V=l+l.toLowerCase
while(0<(s+z).zipWithIndex.map{case(c,j)=>j*c+c}.sum%1000){a=a.drop(1)++V.map(z+);z=a.head}
z}
```
Ungolfed version. [Try it online!](https://tio.run/##bZHrT8IwFMW/81ccl5i0siwbvkkwQXyh@EBAfMSQuhWoKRtsU3yEvx3vHhBi@NTe3z2nPbeNXKHFfB68vUs3xrVQPn4LgCf7GFHBRDiIyqiGofh@acWh8gevvIyOr2JUUiUwJhprn/WZYXD@H7VlFK/BF1LrAN0g1N6abml7d99xssaskOfpM0qSZTAxWWwphmGYUGXU/SSTbaJZRkNF8SIvwaRk3IRedVm2U9re2d3bPzisHtdOTs/OL@qXV43rm9u75n2r3XnoPj49G3zFks37KTR0I5jKkJBGEdqKg7SuiUjmkhDNGzklQXMJJhmYLIHKgErBdKi0BGMRHZgouTUSY9ajo2kubv2ocVfFw7rvya@kg1@4dBuYS7P7HkflCIw25HY4tuBiZkUfI2zCsW0bG/QwPM@PZTRaLC8MxowsxWI@VHpvmrWIHs8dkxXHUAovx/kEdlrOCgtl@muz@fwP)
```
object Main {
def main(args: Array[String]): Unit = {
println(f(""))
println(f("Test"))
println(f("Hello World"))
println(f("235711"))
}
def f(s: String, q: String = "", i: Int = 0, Q: List[String] = List(), l: String = ".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): String = {
val lLower = l + l.toLowerCase
var QNew = Q
var qNew = q
var iNew = i
while ((s + qNew).map(_.toInt).zipWithIndex.map { case (c, ind) => (ind + 1) * c }.sum % 1000 != 0) {
QNew = QNew.drop(1) ++ lLower.map(qNew + _)
qNew = QNew.head
iNew = 0
}
qNew
}
}
```
[Answer]
# [Go](https://go.dev), ~~309~~ 305 bytes
Saved 4 bytes thanks to the comment of @ceilingcat
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=bZDfTsIwFMbjJX2KpolJK4WsIILgTPyPisoURSVoJnbLQum2bsSLZU_iDZr4UPo0FjZjolx9zfnO-Z3T7_Xd9Wefb4E9GtsuhxPbkwB4k8BXMcSggJxJjLREsfKkGyFAAHCmcrRoxAQmoKA7yl3txkJiByNEyL9aj0fxsnqbC-HDvq_E8zK7Uq3VGZs7KfiYxk6p8bXCFtsdHMHsJJJJong8VRK6OKIIUYMOhrmRUlQ2WKW6XtuoNzZ3dvf2Dw6P2scnp52z84uudXnVu77p397dI5JmP5sjwpxOPaivodYPjYo_a0XRzKMp9_yO_8IVFqTl-CpRTdMA-gE9OmqaypY63agYJqpkPnhrmopHJG15DlSrzDCMLZY8KW6PFyXBJbbINkss0xqw5jCdE-HjL0hoxw4CLp-xRcNidoIGamKoRww9kQcSpllys1xy_QY)
```
func f(s string)string{return g(s,"",0,[]string{},".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")}
func g(s,q string,i int,Q[]string,l string)string{l+=strings.ToLower(l);for{r:=0
for i,c:=range s+q{r-=^i*int(c)};if r%1000<1{break};if len(Q)>1{Q=Q[1:]};for _,c:=range l{Q=append(Q,q+string(c))};q=Q[0]};return q}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=hVLbSsNAEAXfmq8YAsLGxpLUS2shgve7tlqtF4rEdlNDt5t2d6MPki_xRQR_yEe_xtkkrRXEPoTJnDlz5szuvr73ore3j1gFi9Wvuc-h3-n7PQoDP-SGEQ6GkVBAjIIZDJSJQSoR8p40Dcswgph3UiKx4MUoIKNUx6pinAStUD1u08CPmZLENC3r33qTSjWLs08Zi6AVCdadRS0vrVRcV7OS3OVvgoRsDSuP2r2gKhYcAiJtME0bHBvu2ln5JUGo5LjlpeWV1Up1bWNza3tnd2__4PDo-OT0rN44v2heXrWub27NqYmTKTaMJn8hoGEbGhNtG9gfZthx9EwF1DysFnNclppRChOG2z_5Ahqn9Bk8aGTZKMtGeDKR0CIpKuOBHomZRkPetaGjdYXP8ZYlqqd9ml7Q3KIHBFmIuxYs6FbSwXGFBL8w0HLzruM44HngZF0Pgvr9HwajnGhjFqyDmzHGPjHcubV2ztV-7n-5ybee7vGHQ8q7qaCdOi1mh4Gmxq5GU-oOiieTu9QVI8medv7Cxy_9Gw)
```
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(fWithDefaults(""))
fmt.Println(fWithDefaults("Test"))
fmt.Println(fWithDefaults("Hello World"))
fmt.Println(fWithDefaults("235711"))
}
func fWithDefaults(s string) string {
return f(s, "", 0, []string{}, ".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
}
func f(s string, q string, i int, Q []string, l string) string {
lLower := l + strings.ToLower(l)
var QNew = Q
var qNew = q
for {
var sum int
for ind, c := range s + qNew {
sum += (ind + 1) * int(c)
}
if sum%1000 == 0 {
break
}
if len(QNew) > 1 {
QNew = QNew[1:]
}
for _, c := range lLower {
QNew = append(QNew, qNew+string(c))
}
qNew = QNew[0]
}
return qNew
}
```
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Santa has a bunch of presents wrapped in cuboid boxes of various sizes. As his sled flies above a chimney, a stack of presents will be automatically dropped through it. Santa wants to carefully choose the presents so that all of them fit into a rectangular chimney.
All presents must be center-aligned due to *magical physics* issues (i.e. placing two small presents side-by-side is not allowed). The presents can be rotated, but four of the faces must be parallel to that of the chimney. A present fits in the chimney if both its width and length are `<=` those of chimney after rotation.
[On second thought](https://codegolf.stackexchange.com/q/255793/78410), Santa decides that choosing the maximum number of presents is not great, because a single large present is more valuable than a bunch of tiny ones.
## Task
Given the dimensions of the presents and the chimney, determine the maximum **volume** of presents that fit in the chimney (i.e. sum of the presents' heights is `<=` that of the chimney). All dimensions are positive integers.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Presents and chimney are given as `[width, length, height]`.
```
Presents: [[6, 6, 4], [2, 2, 2], [2, 2, 2], [2, 2, 2]]
Chimney: [6, 6, 6]
Answer: 152
Explanation: Use the large box and a small cube.
Presents: [[6, 10, 9], [10, 7, 6], [10, 7, 5], [10, 7, 4], [5, 10, 10]]
Chimney: [6, 5, 999]
Answer: 0
Explanation: No present fits in the chimney
Presents: [[1, 2, 6], [1, 6, 2], [2, 1, 6], [2, 6, 1], [6, 1, 2], [6, 2, 1]]
Chimney: [2, 6, 6]
Answer: 72 (=6*(1*2*6))
Explanation: All six presents can be rotated to [2, 6, 1],
which fits the chimney and takes up only 1 unit of height
Presents: [[1, 2, 6], [1, 6, 2], [2, 1, 6], [2, 6, 1], [6, 1, 2], [6, 2, 1]]
Chimney: [1, 6, 6]
Answer: 36
Explanation: All six presents can be rotated to [1, 6, 2]
Presents: [[1, 2, 6], [1, 6, 2], [2, 1, 6], [2, 6, 1], [6, 1, 2], [6, 2, 1]]
Chimney: [1, 3, 13]
Answer: 24
Explanation: All six presents can be rotated to [1, 2, 6]
```
[Answer]
# [Python 3](https://docs.python.org/3.8/), 180 bytes
```
lambda W,L,H,c:max(sum(h*w*l for h,w,l in a[::2])for a in P(c+[[0]*3]*len(c))if sum(min(h+H*(w>W or l>L)for h,w,l in P(b))for b in a[::2])<=H)
from itertools import*
P=permutations
```
[Try it online!](https://tio.run/##tY69boMwFEZ3nsJSF9vxgKGkBZXMDBnYMlAGQ0BY8g8yjmifnmKgKgzdWulKPv70@Vz3n7bTKnztzdSm75NgsrozcCNXkpE6kewDDg8JOzxiAVptQEdGIgBXgBVJEpTIZczdc1ifisIvcVhi0ShYI8Rb4B5LrmB3yjAcLzcw18Xlig6qHFZoSaqd@C3NkNcaLQG3jbFaiwFw2WtjsZenfWPkwzLLtRqm3nBlYQvPBKxTFOv5XM4cEODmFywR8p52goiAOI43BfXnm2s7eJmVO452vOyJ1j71j87g51N02blKluj7J3RL1y51eF7SYEPXOWrpv2nDOQz/xjt9AQ "Python 3.8 (pre-release) – Try It Online")
It works on first two testcases. But It sadly timeout for third one.
\$O((2N+1)!)\$ solution, where \$N\$ is the number of presents.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org)\*, 153 bytes
*\* This code relies on a specific implementation of `sort()`. The engine used on TIO is Node 11.6.0. This was also succesfully tested with Node 16.14.0.*
Expects `(w,l,h,a)` where `w,l,h` are the dimensions of the chimney and `a` is the list of dimensions for the presents.
```
f=(w,l,h,a,V=o=0)=>a.map((b,i)=>f(w,l,h-(g=H=>m=n?([W,L,H]=b.sort(_=>-40%n--),W>w|L>l|H>g(v=W*L*H)?m:H):1/0)(n=42),a.filter(_=>i--),V+v),h<0|V<o?0:o=V)|o
```
[Try it online!](https://tio.run/##tY6xboMwEED3fgVLJTs9qE0gFSg2KwMzDBGKnBQIFeAIEFn4d4oxVSM13VrpJL873727DzGI7tyW195s5Hs2TTlDN6jgAgJiJhnBjAurFleETlDOSa6/TVSwkPGaNQE6JBBBmLKT1cm2R0fGTYc8N6aJIeG3MeLVGPICDSzZRJsQB7UfYp@@Eowa5tgYhJWXVZ@1arJUU/HLgOGyJ2O8lwHxJYvxKKezbDpZZVYlC5SjHRg6Dgf9OunMNhgqfsEU46cfFhcMz/NWDyVzpkYUvM3eO3bveFnm6n5KHojt7/Posl2bltLXTXSt6l6qcLdU7RVVzwM3/V/3dv7Z/o18@gQ "JavaScript (Node.js) – Try It Online")
Just like [my answer to the previous challenge](https://codegolf.stackexchange.com/a/255801/58563), this is sponsored by the Ministry of Silly Sorts.
[Answer]
# Python3, 221 bytes:
```
lambda c,p:max(max(f(c,[*i]))for i in P(p,len(p)))
from itertools import*
P=permutations
def f(c,p,H=0,v=0):
yield v
if p:
for w,l,h in P(p[0],3):
if c[0]>=w>0<l<=c[1]and H+h<=c[2]:yield from f(c,p[1:],H+h,w*l*h+v)
```
[Try it online!](https://tio.run/##tY8/b8MgEMV3f4objXODsZu2tuKMUcbslMH1HxkJG0Ro0nx6F7AjJUO3VoD07nj83qFvdlBT/q7NfKg@ZlmPn20NDepyrL9jf/q4QZYITkivDAgQE5xijbKbYk0IiXqjRhC2M1YpeQYxamVsEp0q3Znxy9ZWqOkctV0PnqTxWKV4qVJSRnATnWzhEoHoQbsafMIVJQ5rCks55t4J3tK4cl9d9@lO7qqGUV5PLRw3gy8yXi60ME5IYrTk6K7xmshk2FzIrI2YbHyI2Su6xZE5AW6/cASWIfj9i3Tfjx6eb7EoihVAU4TCe714c8AHvX3QIWW7@Gn6TMzuA9GQtyDCbPcp6NrNQpd6@Rq62Sq95xm6AP4Dm7tm/jfc@Qc)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 80 bytes
```
Fθ«≔E³E³§ι⁺κμζ≔Φ⁺ζEζ⮌κ⬤꬛μ§ηνζ¿ζ⊞υ⟦Πι⌊Eζ⊟κ⟧»I⌈EΦEX²LυΦυ﹪÷ιX²μ²¬›↨Eι⌊λ¹↨η⁰↨Eι⌈λ¹
```
[Try it online!](https://tio.run/##dY/BS8MwFMbP7q/I8RUi6JRddqqKMrASvJYeQputYWkyk7SOin97fUnjNg@GhDx4v@9976tbbmvD1TRtjSXwkZGvxVXunNxpKPgB7ihJX@43uhFHkJQw1TvYU9JleCgZs/VJ8yyVFxYiMc5a/N7FIKwTsI98rlRQvxkPL1bwwHfn@S0lOrsYLLcExoyw3rXQU1Iya5q@9iARKKSWXd9BsmHmEC0q1H0vmJXawyN3HvvHE5c2DCUzn1gtKXkVeudxfDBNfbQq0EgZ2Gj/JAfZiBj9V9IFdhnXvAzywDFmmC3P26kA3eKLTcx3M8f7w6YNExvOeprKslxRgve@wuToGu4/ZahneFVV0/WgfgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on my answer to [CGAC2022 Day 21: Present stack headache](https://codegolf.stackexchange.com/q/255793).
```
Fθ«
```
Loop over the presents.
```
≔E³E³§ι⁺κμι
```
Rotate them 120° and 240° around a corner.
```
≔Φ⁺ιEι⮌κ⬤꬛μ§ηνι
```
Also rotate them 180° around their length axis, then filter on which orientations fit in the chimney.
```
¿ζ⊞υ⟦Πι⌊Eζ⊟κ⟧
```
If there were any then push the shortest such orientation to the predefined empty list along with the volume of the present.
```
»I⌈EΦEX²LυΦυ﹪÷ιX²μ²¬›↨Eι⌊λ¹↨η⁰↨Eι⌈λ¹
```
Generate the powerset of the list of presents that fit, filter on those whose height fits in the chimney, and output the maximum volume.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 38 bytes
```
K_EeSmsm*FkdfghKshMTyhM_#SmSf.AtgVKT.p
```
[Try it online!](https://tio.run/##K6gsyfj/3zveNTU4tzhXyy07JS09w7s4wzekMsM3Xjk4NzhNz7EkPcw7RK/g///oaDMdBSAyidVRiDbSUQAhHMxYLqhas1gA "Pyth – Try It Online")
### Explanation
Picks the shortest orientation for each present, then looks at all possible sets of presents and picks the highest volume one which fits.
```
K_EeSmsm*FkdfghKshMTyhM_#SmSf.AtgVKT.pdQ # implicitly add dQ to the end
# implicitly assign Q = eval(input())
K_E # assign K to the second input reversed
m Q # map Q over lambda d
f .pd # filter permutations of d over lambda T
gVKT # vectorize >= over K and T
.At # true if the last two element are true (we've now filtered out orientations which don't fit in the chimney)
S # sort (this orders the orientations from shortest to tallest)
S # sort (this orders our presents shortest to tallest)
_# # filter out empty lists (avoids indexing errors)
hM # map each element to the first element of itself
f y # filter the power set over lambda T
ghKshMT # first element of K >= sum of the first element(s) of T (leaving only sets of presents that fit)
m # map over lambda d
s # sum of
m d # map d over lambda k
*Fk # k reduced on multiplication (we've now mapped the sets to their volumes)
eS # take the largest element
```
] |
[Question]
[
Given a base type `T`, this can be augmented with `*` or `[]`, each meaning pointer and array. For example, `[]*T` means "array of pointer to `T`" and `*[]T` means "pointer to array of `T`".
Let's call `*` and `[]` type *modifiers*. C has a way of ordering these modifiers tied to the evaluation order. `[]*T` in C-style becomes `T *[]`, and `*[]T` becomes `T (*)[]`. You may be able to understand how the conversion works by having a look at the examples below. An explanation is also given at the end of this post.
```
* -> *
[] -> []
[]* -> *[]
*[] -> (*)[]
*[]* -> *(*)[]
[]*[] -> (*[])[]
*[][]* -> *(*)[][]
[]**[] -> (**[])[]
[]*[]* -> *(*[])[]
*[]*[] -> (*(*)[])[]
```
Your program or function should process an input string to an output string as the examples above. The input will only contain `*` and `[]` without whitespaces.
---
This challenge is [this challenge](https://codegolf.stackexchange.com/questions/174677/read-out-the-c-variable-declaration) in reverse, simplified.
---
Rules for C-fix:
* All of the `*`s always come before all of the `[]`s (in real C code, the variable name comes between the last `*` and the first `[]`).
* Evaluation starts in the middle, where the variable name would be.
* If there is both a `*` on the left and a `[]` on the right, without any parentheses to determine the order, the `[]` is bound first, and comes first in prefix:
+ C-fix `*[]`
= C `*a[]` (where `a` is the variable name) = "array of pointers" =
prefix `[]*`.
* In order to change the order of evaluation so that a `*` gets bound first, it must be put in parentheses (with where the variable name would be):
+ prefix `*[]`
= "pointer to an array" = C `(*a)[]`(where `a` is the variable name) =
C-fix `(*)[]`.
---
From the last example, `(*(*)[])[]` in actual C code would be something like `int (*(*a)[])[]` (where `a` is the variable name). The evaluation starts from `a` and `[]` is bound first unless a set of parentheses blocks the binding.
If you put `int (*(*a)[])[]` to [cdecl.org](https://cdecl.org/?q=int+%28*%28*a%29%5B%5D%29%5B%5D), the output is "declare a as pointer to array of pointer to array of int". This is because:
* The first `*` is bound first due to the parentheses.
* There are no parentheses between the variable name and the `[]`, causing that to be bound before the next `*`.
* Then, the next `*` is bound because it is in the parentheses with the variable name, whereas the remaining `[]` is not.
* Finally, the remaining `[]` is bound.
This is `*[]*[]int a` in prefix. Hence, `*[]*[] -> (*(*)[])[]`.
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 90 bytes
```
f s@(""?"[]")=s
f(s++"*")='*':f s
f(s++"*[]")="(*"++f s++")[]"
f(s++"][]")=f(s++"]")++"[]"
```
[Try it online!](https://tio.run/##RY7NCoMwEITveYplL@anvoCg7VVo6aFHkSJSixQlmHjo06dj6s9lM/NNJpt2nqZvaptP60LoyF0k85mrmlXuRCedMayhE51kSDcSc5aajQEFUSBrWMdw1awwAYJ/OU9ZRg8/9eOb0oLKO0klIneUk509Msii2DQv1/gA15Ek1ikhhqYf0Rkae3tSfKLCN0@0rIozGv13erU4dnAgvVeO1sLq8AM "Curry (PAKCS) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 52 bytes
```
^((.])*)(\**)
$3$1¶
{G`.
(.+)¶((.])+)(\**)
$4($1)$2¶
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP05DQy9WU0tTI0ZLS5NLxVjF8NA2rmr3BD0uDT1tzUPbwNLaMGkTDRVDTRWjQ9v@/9fiio4FIi0uLSCtBWIAMYQJ5WhBFEDVABEA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^((.])*)(\**)
$3$1¶
```
Process any initial `[]`s or `*`s into an output line.
```
{`
```
Repeat until there is nothing left to process.
```
G`.
```
Delete the original input line once there is nothing left.
```
(.+)¶((.])+)(\**)
$4($1)$2¶
```
Process some more `[]`s and `*`s.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
FS≔⎇⁼ι*⁺ιω⁺⎇∧ω⁼§ω⁰*⪫()ωωιωω
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLQkuKQoMy9dQ1NTwbG4ODM9TyMktSgvsahSw7WwNDGnWCNTR0FJS0lTRyEgpxTMK4exYQod81I0ynUUoOodSzzzUlIrQCIGmhC9QMorPzNPQ0lDUwmiH4QzNcEMa64AoANKNICs//@jY7WA6L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FS
```
Loop over all of the input characters.
```
≔⎇⁼ι*⁺ιω⁺⎇∧ω⁼§ω⁰*⪫()ωωιω
```
If the current character is a `*`, then prepend it. Otherwise, append it, but if the output string starts with a `*` then wrap it in `()` first.
```
ω
```
Output the final string.
[Answer]
# [Python 3.8+](https://docs.python.org/3/), ~~92~~ 83 bytes
```
f=lambda p,c="":f(p[1:],["*"+c,[f"({c})",c][c[:1]!="*"]+p[0]][p[0]>"*"])if p else c
```
[Try it online!](https://tio.run/##XclBCsIwEAXQvacYZ9OkzcLiRgLxBN5gyCLGBAu1HZqASOnZY6u4ET6f/3n8yvdxOJ54KiWa3j2uNwesvEHUUTC12irCGhuvKKKY/SJReUuedGv3ZhXbMB2spa3P25ddBIbQpwC@8NQNWeDFpQz5OUIO6/AuhaRR7r4acY6iIluvqSQYWP6o/tiPyhs)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~119~~ 117 bytes
*-2 bytes thanks to @ceilingcat*
```
*b;f(char*a,l){return l&&asprintf(&b,a[--l]<43?"*%*s":a[l]<93?:--l&&a[l-1]<43?l--,"(*%*s)[]":"%*s[]",l,f(a,l))?b:"";}
```
[Try it online!](https://tio.run/##XY9NboMwEIX3OYU7VZBt2Ysq3QQqoS666BmAhW0gRXIsCiatFOXqpcOvSCxZnnnzvWfbSGOVO/U911FJzZdquBKWXZvCd40jNghUWzeV8yUNtFCJlDZ7ez3EwPe8hVAl2B4PcYg6oomVL@PYSimADgxLMggBCzyFFSUd4lmsQ4Do1p9V5Si77urOtxQ@HZ6pfze@Uzb1H791YXyRY/WNArBo95wXZeUKcsEYzcj8Mti3qV93njoQRAky3NX6xhaOKsYE0YI8YW/ONX0YaYbZFwocjePCalKGV08KVos0Y8BXjS8cfppt1QkFvpVRnXCEk@wOnwwzvjVMDjTcOcakxfEQtTrGrHl06/9MadWp7eXPPw "C (clang) – Try It Online") Takes input as a character array and its length; returns an allocated string.
] |
[Question]
[
## Background
In [Scrabble](https://en.wikipedia.org/wiki/Scrabble), players take turns placing tiles on a grid so that each contiguous set of (more than one) tiles in every row and column makes a word. In one play, tiles can be placed anywhere in a single row or column as long as there is a contiguous set of tiles that includes all of the ones placed.1 A word is scored (without considering premium score spaces) by adding up the point value of each of its letters. The point values of the letters are as follows[:](https://codegolf.stackexchange.com/questions/162596/scrabble-scorer/)
```
1 point: E, A, I, O, N, R, T, L, S, U
2 points: D, G
3 points: B, C, M, P
4 points: F, H, V, W, Y
5 points: K
8 points: J, X
10 points: Q, Z
```
A play is scored by adding up the scores of each new word created in a play. For example, in the play below, N and W were played to form three new words, scoring 5 (PAN) + 6 (SEW) + 6 (NEW) = 17 points.
```
PAST PAST
AXE -> AXE
E NEW
```
Apart from the starting play, each play must involve at least one already existing tile, so that it is connected to the rest of the board.
## The Challenge
Your challenge is to write a function which takes a play and returns the total points scored in that turn. **You do not have to consider the legality of the words formed by the play, or any premium score squares.** However, you should assume that the placement of the play will be valid (i.e. will connect to the board and be placed in a line) and that the board will be nonempty before the play. Unlike in Scrabble, a play can be more than 7 tiles, and the grid can be larger than 15x15.
Your function should take a mapping of the letters to their point values as a parameter. **In addition** to the letter point values, the function should take input in one of the following acceptable ways:
* Two grids representing the board, with one showing the board before the play and one showing the board after the play.
* A grid showing the board after the play and a list of the coordinates at which tiles were placed.
* A grid showing the board either before or after the play, and a map containing each letter of the play with the coordinate at which it was placed.
The grid can be exactly big enough to contain the relevant squares, or can be padded to any larger size. This is Code Golf so the fewest bytes wins.
## Examples
The examples use the first input method, with the board before and after the play separated with `|` and the expected output in bold along with the words formed above each example.
**17** (PAN, SEW, NEW)
```
PAST | PAST
AXE | AXE
E | NEW
```
**18** (ST, OO, LO, IT, DE, TOOTED)
```
SOLID | SOLID
| TOOTED
```
**9** (HOPE)
```
| H
ROLL | ROLL
| P
| E
```
**4** (DOT)
```
BAD | BAD
A | A O
NOT | NOT
```
**6** (NEW)
```
PASTURE | PASTURE
AXE Y | AXE Y
NEW E | NEW NEW
```
**13** (PROGRAMS)
```
GRAM | PROGRAMS
```
---
1 This set must be in a single row or column, but can include letters that were already on the board, i.e. `GRAM` -> `PROGRAMS`
[Answer]
# Python3, 387 bytes:
```
import re,itertools as I
lambda o,n:sum(sum(p[i]for i in j)for j in q(n)if all(j not in k for k in q(o))and len(j)>1)
q=lambda o:[j for k in[*map(list,I.zip_longest(*o,fillvalue=' '))]+o for j in re.findall('\w+',''.join(k))]
p={'E':1,'A':1,'I':1,'O':1,'N':1,'R':1,'T':1,'L':1,'S':1,'U':1,'D':2,'G':2,'B':3,'C':3,'M':3,'P':3,'F':4,'H':4,'V':4,'W':4,'Y':4,'K':5,'J':8,'X':8,'Q':10,'Z':10}
```
[Try it online!](https://tio.run/##dZJvb9owEMZfz5/ixBvb1ELjn1RFYhIdWcughAFbuwU0BZFsDsFO47BpG/vszD7aqFJZpPzu8txj@@Rc/qv8rlX7Mi@OSW95zKLdehOBFsoz@x1zbx7KVaILkCAVpNylqUsfmOIygSjLWApKl07bgitvT2XNeaQ2kMWKpfxNkxO5y3VRQhELWcZFqXVmIDIwJA@9p3O9MK22COu7KGeZNKUYNn7L/Gum1bfYlKyuRSKz7EeU7eMeBcr56kJD1VgRNxKpNq4xuvx5QQWljVRLxbbWSPLeH@pTryloHzlEBsgJcoZcIMfIOfIjckC9lqDXyCvqtQV9i7xFTpHvqNcR9Ab5CXmH/IwcUa8r6HvqXQp6j/xgd34t6BcX/h7/c02SmF6tVpv25ws4gAukf@@DzTEQsLAfE/8OrI2YpnOTeTAeDqyMkQA@B1gEwcIfEPS1nO9RhxsyC8Zjm7lAntRplfm4pO2WXPXdvpakj7U@BGQSuN4sT1t3sIWXRnhmHKE2sotxSffU9XBy7Zq2wZ9hYRMn7g/vopKtuUdeFXG5LxSEYVhPG4UpC5kzvqpm4NnI2slh9dAOhckzWdqRMMvD0lAheWWx02Rvmk20isW68ik3WG5iCqlKlrD64/mGc/5SbJ5VW2fV9lm1c1btWvX4Dw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes
```
SθWS⊞υιUMυ⭆S⌈⟦λ↧§ιμ⟧IΣE⁺υE§υ⁰⭆υ§λκΣE⪪ι ∧∧‹¹Lλ№α⌊λΣE↥λ⊕§θ⌕αν
```
[Try it online!](https://tio.run/##VY5Ra4MwFIXf/RWhTwk4iDoopU/FriBYFOyexh6ChhqWxNQkbf@9u@nqsBcCuSc53zltz8Z2YHKaCm28a9wo9BlfyDa69UJyhJcyIaj2tsc@RgJ@HJnJB6WY7oLy9we0V0uMjuwulFf4S8aoHG58bJnleOcK3fE7FjFShHwTAsAaLA7nzDrcgCGwaultoIf7bIGVkmUgCPMbZPwAKzw/CY2RwoWYFVqBvIO24ZTcWpxAI67PrscyWPLBQz6DNKEfleUL6dOYZ3kJaqHbkSuuHe/@m11idBAAB4Qmi9lOE03ThGZJRtfvNKU03VCYLFtnm6ipymKPIvSYaF5PVXX62E9vV/kL "Charcoal – Try It Online") Link is to verbose version of code. Takes as input:
1. A string of 26 digits representing the values of the letter tiles minus `1`.
2. The previous board state, as a rectangular list of strings
3. An empty line to delimit the two boards
4. The new board state, as a rectangular list of strings
The two boards must be the same size rectangle. Explanation:
```
Sθ
```
Input the decremented tile values.
```
WS⊞υι
```
Input the previous board state.
```
UMυ⭆S⌈⟦λ↧§ιμ⟧
```
Input the new board state, but lowercase all letters that aren't new.
```
E⁺υE§υ⁰⭆υ§λκ
```
Loop over the new board and its transpose.
```
ΣE⪪ι
```
Map over each word and take the sum.
```
∧∧‹¹Lλ№α⌊λ
```
Only score words of at least two letters of which at least one is upper case.
```
ΣE↥λ⊕§θ⌕αν
```
Calculate the score of the word.
```
IΣ
```
Output the final total.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
,ZḲÇ€€$€€Ẏ)œ-"/ẎḊƇFS
```
A monadic Link that accepts a pair of boards (lists of lists of characters), the first being the board's state *after* the turn has been played, that yields the score. The boards must fully align, using spaces to pad as necessary.
**[Try it online!](https://tio.run/##y0rNyan8/6hhjqujp79fUIhPcCiQ4@IOJJycfQOAlJtHWHgkkPYGYgjyioDQgVGPGuYe6X7UtCbk4Y5F/3WiHu7YdLgdyAUiFQj1cFef5tHJukr6QMbDHV3H2t2C////Hx2tFOAYHBIa5KrEpaCj5BjhqqAQqQBm@7mGKwAxkB3LpYNbmQKQCVMWCwA "Jelly – Try It Online")** (The header is a Link that performs the lookup of the value of a tile by its character\*)
Or see the [test-suite](https://tio.run/##bY6xTsMwEIb3e4pTxYJExTO4xE1D0jjYhpbsLKgvUJShZYkEEks3BAusTAhFKUgdWsp7OC9izg6qOmCd7/v/O/t011eTydQ2syfOIpFKnahzMkFIqXcyzAj9wcXokhjTbeN03PIsb2bP3/fN7Zs29Ys9yk39vinJUhy0MJ8Ph9tFt3NMwtR3P2VfWfP1sV2Y5at7MV8VeONFlRNys3zclNC256t1ta78QGszpjQW6ABszJG0ByAlMikfIYASSRSQ8wT0p0AthOYBwJ/FAUiRJKQcdtVspzhAj7kxlIH5GkMBqXAbUP6vjXvt2Ndi@gIqSkO3D4FLv0Eo2dC1MymcVL8 "Jelly – Try It Online").
\* Blank tiles can be incorporated by using a new character, e.g. `b`, too.
### How?
```
,ZḲÇ€€$€€Ẏ)œ-"/ẎḊƇFS - Link: pair of lists of equal-length lists of characters
) - for each grid in the pair:
Z - tranpose
, - pair the grid and its transpose
$€€ - for each line in each of those:
Ḳ - split at spaces
€€ - for each tile character in each of those:
Ç - call our tile value finding function
Ẏ - tighten
/ - reduce by:
" - zip with:
œ- - multiset difference
Ẏ - tighten
Ƈ - keep only those for which:
Ḋ - dequeue -> falsey for length one words
F - flatten
S - sum
```
[Answer]
# [Clojure](https://clojure.org/), 180 bytes
```
#(let[s(fn[x](frequencies(for[y(concat x(apply map vector x))w(partition-by #{\ }y):when(second w)]w)))b(s %2)](apply +(for[[k v](merge-with -(merge b(s %3))b)n k](*(or(% n)0)v))))
```
[Try it online!](https://tio.run/##bZJfT9swFMXf@RRHQUg2uBJ/NgnxFtYM2EpT0jBgdh7S4I6M1glpaFohPnvx9RLQplnxz/K5515fW8lmxe/nSm/YvZ5i/qICHAjlEy4IIWFIiAgxYUAYE64JfRwKdUY4xZFQXwiXhBHhKz4JdU74Qbgh3BG@47NQ33As1C3hCgf7Qv20fOVbrpnpZpvNdC0XbGrkKmHTSj89a5Pl2ipFJdcsK0yW1lixtCxna8zTEkud1UWFFecNK9Oqzuu8ML3JGtsvCq9rftI8aMMW2qbeo@FJwzmfsAV2DnnSltlz1eUjlgmb6@qX7jV5/YDenw2c@8hmcYPHhO2yomI7MHyfL20tvqHui4V@gpQTpAnklpTeyB/HnvD82wB2QQB4NvKPPAxurJyQfxwOLvrO6oYzv2txGMZBv3W6sPCicDBo7d1COTj/KzrCx/Eu@9Tv0/lOHoaxy@m0sNOS7gbXUdB2i7uuYVvs/Sr/i9v50elZ5F@29iikzZhi9mNllZt6ZsDsTwj7bvSSbw "Clojure – Try It Online")
Anonymous function, accepts the three arguments in the order of: scoring map, board before, board after.
] |
[Question]
[
## Background
A polyomino of size \$n\$ is a contiguous shape made from joining \$n\$ unit squares side by side. A domino is a size-2 polyomino.
A **polydomino** of size \$2n\$ is defined as a polyomino of size \$2n\$ which can be tiled with \$n\$ dominoes.
The following are some examples of polydominoes for \$n=3\$ (hexominoes).
```
. O O | . O . . | O O O . | O O O O O O
O O . | O O O O | O . O O |
O O . | O . . . | |
```
The following are some hexominoes that are *not* polydominoes.
```
. O . | O . . . | O . O .
O O O | O O O O | O O O O
O O . | O . . . |
```
## Challenge
Given a positive integer \$n\$, count the number of distinct polydominoes of size \$2n\$. Rotations and reflections are considered as the same shape. Different tilings of the same shape does not count either. You may take the value of \$2n\$ as input instead (you may assume the input is always even in this case).
The following shape has two ways to tile with dominoes, but it is counted only once just like other hexominoes.
```
. O O
O O .
O O .
```
The sequence is [OEIS 056786](http://oeis.org/A056786).
## Test cases
The following are the expected results for \$n=1 \cdots 9\$.
```
1, 4, 23, 211, 2227, 25824, 310242, 3818983, 47752136
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~266 250~~ 242 bytes
```
->n,*z{j=(h=1,m=1i,-1,*r=[-m,0]).product h;(r.map{|c|j.map{|v,w|k=r+[v+=c,v+w];k|k==k&&(w=j.map{|y,q|(x=k.map{|v|y*[v,v.conj][q*q]}).map{|g|g-x.map(&:real).min-m*x.map(&:imag).min}.sort_by &:rect})-z==w&&z<<w[0]}};r,*z=z)until r[-n];z.size+1}
```
[Try it online!](https://tio.run/##NY/bjoMgGIRfxSuCCKRssjdr/74IIRvrtlatJ6qgFJ7dtVv3bvLNTCajp/OyXmFlp5YS96wA30DQBkRJmaBEg2QNPaiY97r7mfIxuqVY8ybrnz731VsYan0NOpEmgZyaxKq03gDUCGELe2ihg8cz1HvFL0QaanjetZWSAxlUiN9W4Qs2vyRGX/qS3Tdctqwh/6xssuKPBf7o9Ph9XqJXMB9DzByARcgdj1YeVAip3j6Bi6d2LO@RlqxVqeOP0l0SEVYsOP/cR2ffR3KmVzmTD6XC@gs "Ruby – Try It Online")
Not particularly original, I just recycled my [solution](https://codegolf.stackexchange.com/a/199813/18535) to a similar problem, and changed some small details:
* start with the basic domino (instead of single tile)
* add 2 tiles on each step (instead of one)
* check for reflection by using the complex conjugate (instead of only rotation using powers of i)
* ~~stop when reaching size 2n (instead of n)~~ -> Accept 2n as input
## How it works:
See the linked [post](https://codegolf.stackexchange.com/a/199813/18535) for the full explanation. Basically, use complex numbers to make it easier.
## Performance:
43 seconds for n=5 (size 10) on TIO
Thanks Dingus for saving some bytes, the function is a mess and could probably be much shorter anyway if implemented properly.
[Answer]
# JavaScript (ES10), 343 bytes
Expects \$2n\$ as input.
```
n=>(c=0,g=(m,k)=>k<n?m.map((r,y)=>m.map((Y,x,[...m])=>(h=(p,R=m[Y=y+!p],P=p-~p<<x)=>(p?x:y)>n-2|(q=r|R)&P|k*!(q&P/2+P*2|(m[y-1]|m[Y+1])&P)?0:m[g(m,k+2,m[y]|=P,m[Y]|=P),m[y]=r,Y]=R)(0)|h(1))):(F=i=>i&&g[M=(m=m.map((r,y)=>m.map((v,x)=>a|=b|=(i&1?r>>n+~x:v>>y)%2<<x,b=0)|b,a=0)).flatMap(v=>v/(a&-a)||[])]|F(i-1))(8)?0:g[M]=++c)([...Array(n)],0)|c
```
[Try it online!](https://tio.run/##bZBBb4JAEIXv/optYsmMLCi0h4Y6a3qoNxPizZBNXKkiVRZEQySu/nW6ND329LLv7b75Zr9Vo85pnVcXT5df225HnSYBKU14RlDwA5I4TPWs8AtVAdS8tcbfYcWvPPF9v5DWgz1BxZdUJCtq3adK8pgq71FNp9c@rWbXqEWhvdDAiWqzRCc2h9ETnJx4HLrxyPpF0nqBNLbBDaTNcTaJiiTrKdyQ21Qaiq2uesVfg2q@krREmKDZQ4CIEcwpJ5E7TpYs7Ab0H3nDeyhlaGMIcieY1UJo93GNGiFafA4tNN@Q7dxwZQX93VFdFvZlQ6IZg3I8hcYkEqWZQ@7ZufDW09qRklw3Rej/5aOuVQsaJbdNafeeBJyFnL1w9ir9XVl/qnQPmpFgtwFjaanP5XHrH8sM1gqGN31HRmx429k7IxbifY2DO3Y/ "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
## Background
*Match Land* is a mobile game that falls into the Match-3 genre (think Bejeweled or Candy Crush Saga series): swap two orthogonally adjacent pieces to make a 3-in-a-row or longer. However, Match Land has an additional rule that makes the game much more interesting.
Once you make a valid match-3 move, the matched blocks are not removed immediately; instead, you get a small time window where you can create more/longer match-3 chains by swapping not-yet-matched blocks. If you make a wrong swap (that does not create a new match or extend existing matches), your turn ends immediately.
Exact rules for this challenge are as follows (I don't play this game right now, so the details might be different from the actual game. And the details not relevant to this challenge are omitted):
* The game is played on a rectangular board. It is turn-based, and the player can make one or more moves in a turn.
* The board is filled with tiles, each of which has one of six different types (denoted 1 to 6 in the examples later).
* The player makes a *"match"* (three or more same tiles in a row, horizontally or vertically) by swapping two orthogonally (horizontally or vertically) adjacent tiles. The action of swapping two tiles is called a *"move"*.
* After the initial match, the player can make an additional move if the move extends the length of an existing match or it creates at least one new match (3-in-a-row).
In the following example, B4-C4 and B3-B4 are valid moves but A3-B3 is not (simply moving the 4 adjacent to an existing match without creating a 3-in-a-row is not valid):
```
| 1 2 3 4
--+------------
A | 2 1 4 3
B | 1 2 3 4
C |(4)(4)(4) 5
```
* The player cannot move already matched tiles.
For example, consider the following 5x7 board (with coordinates for ease of explanation):
```
| 1 2 3 4 5 6 7
--+---------------------
A | 2 4 4 3 5 2 4
B | 3 2 1 4 1 3 5
C | 4 2 4 4 3 1 4
D | 2 4 3 1 4 2 3
E | 2 4 2 2 3 3 4
```
The player can make a move at A3-A4 to match three 4's:
```
| 1 2 3 4 5 6 7
--+---------------------
A | 2 4 3 (4) 5 2 4
B | 3 2 1 (4) 1 3 5
C | 4 2 4 (4) 3 1 4
D | 2 4 3 1 4 2 3
E | 2 4 2 2 3 3 4
```
Then D7-E7 to match some 3's:
```
| 1 2 3 4 5 6 7
--+---------------------
A | 2 4 3 (4) 5 2 4
B | 3 2 1 (4) 1 3 5
C | 4 2 4 (4) 3 1 4
D | 2 4 3 1 4 2 4
E | 2 4 2 2 (3)(3)(3)
```
Then C5-D5 (note that a match is extended only if the new tile to be matched is aligned with the existing match, so the 3 moving into D5 is not matched with the existing E5-E7):
```
| 1 2 3 4 5 6 7
--+---------------------
A | 2 4 3 (4) 5 2 4
B | 3 2 1 (4) 1 3 5
C | 4 2 (4)(4)(4) 1 4
D | 2 4 3 1 3 2 4
E | 2 4 2 2 (3)(3)(3)
```
You can continue this until you run out of possible moves.
I found a sequence of 9 moves from the initial state that matches **26** tiles in total (not confirmed yet if it is optimal):
```
C1-C2 B1-B2 A2-B2 C5-D5 D6-E6 E5-E6 D3-D4 B6-C6 B3-B4
| 1 2 3 4 5 6 7
--+---------------------
A |(2) 3 (4) 3 5 2 4
B |(2)(4)(4)(1)(1)(1) 5
C |(2)(4)(4)(4)(4)(3) 4
D |(2)(4) 1 (3)(3)(3)(3)
E |(2)(4)(2)(2)(2)(3) 4
```
## Challenge
Given a board state in Match Land, output the maximum number of tiles that can be matched in a single turn.
The input is a 2D array of integers from 1 to 6 inclusive. You can use any equivalent representation of a rectangular 2D array in your language, and any 6 distinct values in place of the integers. You can further assume that the input does not already have any 3-in-a-rows (as is the case in the actual game), and it has at least one valid initial move.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins. Imaginary brownie points for a solution that is provably correct and works reasonably fast in practice.
## Test cases
```
Input:
1 1 2 1 1
Output: 4
Input:
1 1 2
2 2 3
3 3 1
Output: 9
Input:
2 2 1 2 1
2 1 2 1 2
3 2 1 2 1
Output: 14 (A3-A4, B4-B5, B2-B3, B3-B4, C3-C4)
Input:
3 2 1 2 2
2 1 2 1 2
3 2 1 2 1
Output: 12 (B4-C4, B2-C2, A2-A3)
(I believe matching 13 tiles is impossible without breaking existing matches)
```
[Answer]
# JavaScript (ES6), ~~315 307~~ 303 bytes
Brute force, but quite fast on the test cases.
```
f=(m,T=M=0,C=c=>m.map((r,y)=>r.map((_,x)=>c(x,y,1,0)|c(x,y,0,1))))=>C((x,y,X,Y,r=m[y],v=r[x],R=m[y+Y]||0,V=R[X+=x])=>V<8&v<8&&(Y=m.map(r=>[...r]),r[x]=V,R[X]=v,a=[n=0,1,2],C((x,y,w,z)=>a.some(p=i=>p-(p=(m[y+z*i]||0)[x+w*i]&7))||a.map(i=>n+=(R=m[y+z*i])[i=x+w*i]<(R[i]|=8)))|n&&f(m,T+n),m=Y),M=T>M?T:M)|M
```
[Try it online!](https://tio.run/##bVBNT4NAEL3zKzYe6I6MG6AHjXbwYPSGh9o0NkgMUqqYsuBSK1X87XUAPy5uMpl5M@/tm93nZJvUqcmrzZEul9l@vyJZ4IxCcvGCUgoKVSSVlAZ3QIEZwD02DFLZ4A49dKEdShc94EPBhezxLS7QUBHtYtySiZoYpx1yFnHbujinaXTrUBOzYD45sbcctlzQYGgoiJRSJgbslDRHZse0xYQizbt56Mf47fOG73xHouqyyGRFOQXVEWfZeb0f5p0bRI3zxqV9DNC2SW/BPO2QHHbqeBDlNNAmchqxjk74Oa227VX3J44GLGgBGNIsCM9npyG04d5kL6@5yeRoVY9AmSxZXuXr7GanU@mC2pQ3G5PrRwmqrtb5Rh7c6Tt9AGpVmsskfZK1oEB8WEIUgkT9R2JKt2M//mmPxGjoXr8WD5kBOGNdWuq6XGdqXT5KXhPA@oS9Jzzhc3iW1ZeWz3BsjcW4a/n9jMP6zkwY//Z@S/@/8Rc "JavaScript (Node.js) – Try It Online")
### Commented and speed-optimized
By adding a cache, we can make it fast enough to solve the 7x5 example given in the challenge in a few seconds.
A solution for 30 tiles in 11 moves is:
```
A4-B4 B5-C5 C4-D4 C3-D3 B3-C3 B1-B2 D7-E7 A7-B7 E1-E2 D1-E1 C1-C2
```
```
f = (
// m[] is the input grid
m,
// T is the current score, M is the best score
T = M = 0,
// ungolfed version only: keep track of the moves and use a cache
P = [],
S = new Set,
// C is a helper function that walks through all cells and invokes a callback
// function with the position (x, y) and a vector (+1, 0) or (0, +1)
C = c => m.map((r, y) => r.map((_, x) => c(x, y, 1, 0) | c(x, y, 0, 1))),
B
) =>
// cache hit? (ungolfed version only)
( S.has(key = JSON.stringify(m))
||
// look for all pairs of cells that can be swapped
C((x, y, X, Y, r = m[y], v = r[x], R = m[y + Y] || 0, V = R[X += x]) =>
// valid only if none of them already belongs to a match
// ungolfed version only: also make sure they're not equal
V < 8 && v < 8 && v ^ V && (
// make a backup of the grid
B = m.map(r => [...r]),
// swap the cells
r[x] = V,
R[X] = v,
// check the grid
a = [n = 0, 1, 2],
C((x, y, w, z) =>
// 3 cells in a row?
a.some(p = i =>
p - (p = (m[y + z * i] || 0)[x + w * i] & 7)
) ||
// if yes, mark them as matched and increment n for each new cell
a.map(i =>
n += (R = m[y + z * i])[i = x + w * i] < (R[i] |= 8)
)
) | n &&
// do a recursive call if at least one new cell was added
f(m, T + n, [...P, [[x, y], [X, y + Y]]], S),
// restore the grid
m = B
),
// update M to max(M, T)
M = T > M ? (best = P, T) : M,
// update the cache (ungolfed version only)
S.add(key)
),
[ best, M ]
)
```
[Try it online!](https://tio.run/##dVVtb9s2EP7uX3EfCpuaFTV20q3I6haIvw3IFtRB0ELTVkaiLNYUqVL0W5v89uyOlN@Q1bAt3pH38LlXfeUr3uZWNu5Mm0I8P5cwAdYDeP0a6jQD2YKrBEjdLB3MrSxwq47D/t1uN19aK7SDNjdWxHCz0z@ItlOiwR0C3@DvvLNe6rlRpShgJWwrjQaj1fYKFkI04CzPF2BKj1KblWiB6wKWrQAOOc8rArxFsDQjtBmutFjDTLgOfEoUOFRCNcJCudS5oytcxR2suVoQP2uW8wq4UpALpcINUq/Mgm7DW5R6QBYBb4@wlq7yrBrTSq9hmxi2kbfm6EvujAU2HMVwHgEtz2MYjiKEmSLLHCbvoU5q3jBmvR3KNsj/xrDxcu4hYwgYj3sZkUZRFJGL1z06Gbj5eEAl3Qdg/xtUupzBLKl4yxZiizT@mP31Z9I6K/VclltWR3QE4PHRPxBTGbOAEulTeBoubUvZCHHyQcy5xvRCu@ZNIwpvNmUdz08xfI7B4j11us1iWOHKphtcfQw6GMLnDG8jj@5R9TH9BMMJbLLOqY7EiitZeA9AlqCNFl1J1EjLCl5skYIyeo6cDAa/5i6vDuY/KTCuWoNHF0h@aQXBbQf41MaB@LbkqgO4h3fwFvp9ZL9f/INaXLDuSGgSQuJApbJsdiXbNUr4XJPTPsWWspsmSWIzn8U9CIUxdBJFeL9DQUPj@8NZjBRpVifWmH7slhf3cuoP7TuOSmmcHYz2qVrH8P0o6B3gRZdpqRHEmvWHo22etKYWrEFceWoI0MAZ@B0WkvwdfgEZEh2lG1Ssg6IPv0VHhtGu8PYEMN1b0cYYXLvoEt6G9GI6Q5/mVtQ0c7QvU4E94EcAET9hS3F/QVRTubFDNQaiUYoH4YjnOzyTkgMTeHtCuHdEHcH6/eN0FFSLVuBQbOVK@EFCDmHTKMFxIFId76jiMMJhUxTikLaS1TEOyyHo2NfKLT5Syhb2T4qtFbonQ2l2WkQWp60JFX1aCDV6dd1JexNqkKbgTuBQdtQQG3aD9@5co0l9B@/xiVPFz/EJ3NI@XMHNSwxfu34O/XwE0WeWoLM0hIKiY5P6NwW9ODKUo2ea@JQbapeZn1JJaU09rbid4ksKq2uUYRR@fRPhP0rnJI2i33u9FIeVq6hwNkCNUrK0R/jjGC799yKGN7EXwfdDSpqxb5BL/08HdluX8Ynh6MhqfKz0xy5Ot8ZB6b9o1cuiXi83ujVKJMrM2ZdXP5DkEziphO@0Vz@IeqKEnrvqKbz1rv7Wndq/IVIew4Mfkn6bcfJ/cDbAfy8/RFHy1UjNBjCInr5Ez/8B "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 239 bytes
```
f=function(m,x=!m,w=nrow(m),`+`=sum,`/`=c){for(i in seq(m))for(j in 0:1){l=m
k=i--(i%%w&!j)-j*w*(i>w)
l[i/k]=l[k/i]
n=0
for(d in 1:2)n=t(n|apply(l,d,function(v,r=rle(v)$l)unlist(Map(rep,r>2,r)))&!+x[i/k])
if(+n>+x)F=max(F,+n,f(l,t(n)))}
F}
```
[Try it online!](https://tio.run/##lY/PbsIwDIfvfopQDWTT8KftDckce9sTIKRW0IpAErq00E6MZ@9StHGcxsGKfk6@z47r@5LLi9016mzRyI5HRrZs3blFQzILM64vRmaLjHd0K88OlVBW1MWHv6YhH4e8XEV002zgxGo2QzUet5PRkWbHaTtFtW4J9EYtTlvWm9NCbcHyEgZ4P8DRKibLDdqvvKr0J2q5l8@VrtKx0wVe6U3TxWpVN/ieV@iKSrp1LB0RTUZh99ATqBJDuw47StnkHaYytLL0Rm/3D@@Q3nvDeT03eeNU5y35fr6rr3jgVNZFxYEIZFN0DQeRiETsKwqIoPS/BfgnCQ8UYo8nkIhERPC6I34M9wU/pzcmz97rvl82/tPXfwM "R – Try It Online")
### Semi-ungolfed
```
# m - input matrix
# x - matrix of existing matches initialized with FALSEs of the shape of m
# w - number of rows
f = function(m, x=!m, w=nrow(m)) {
# loop through each cell in m twice:
# once for a vertical match and once for a horizontal one
for(i in seq(m)) for(j in 0:1) {
# Work on a copy of m
l = m
# The index of the cell to swap:
# one cell down from i (except the last row), or
# one cell left from i (except the first column)
k = i + (i%%w&!j) - j*w*(i>w)
# Swap ith and kth cell
l[c(i,k)] = l[c(k,i)]
# Record new matches, start with 0
n = 0
# If neither i, nor k was matched earlier, check both dimensions:
if(!any(x[c(i,k)])) for(d in 1:2) {
# Find runs of 3-in-a-row across the given dimension:
# take Run Length Encoding of a row/column,
# expand it so that runs longer than 2 get mapped to TRUE
# e.g.: 1 2 2 2 3 3 => F T T T F F,
# then logical OR with previous n
n = n | apply(l, d, function(v, r=rle(v)$l)unlist(Map(rep, r>2, r)))
# Apply always collects the results columnwise, so that
# a transpose is necessary to make the results conformable
n = t(n)
}
# If there are new matches compared to previous iteration
if(sum(n)>sum(x))
# Call itself recursively with the modified input l, and
# n transposed to original shape, as new existing matches
# The maximum of all iterations will be the final result
F = max(F, sum(n), f(l,t(n)))
}
F
}
```
] |
[Question]
[
Do you know the game Battleship? Well, I want to play with my little brother, but before we can begin we need to set up our ships on the board. This is your input.
Now, we need to check that the ships that we set up are valid. This is where you come in to help. Your task is to write a program or function which checks whether the given 2d array (your board/input) is a valid board or not.
The input will be a 2d array, where `1` represents part of a ship and `0` represents part of the ocean.
**The rules:**
* There must be:
+ One battleship (size 4)
+ Two cruisers (size 3)
+ Three destroyers (size 2)
+ Four submarines (size 1)
* Any additional ships are not allowed, and neither are missing ships
* Each ship must be either vertical or horizontal (aside from submarines, which are a single grid space)
* The ships cannot overlap, but may be adjacent
in addition, you must solve this with a `BF` function (naturally the class will be called `BF`) which receives the 2d array(input) and uses a `validate` function. Afterward, you are free to manipulate the 2d array however you want and add any functions that you want.
here are some more examples(inputs) that your code must pass:
is valid:
```
{1,1,1,1,0,0,0,0,0,0},
{1,1,1,1,0,0,0,0,0,0},
{1,1,1,1,0,0,0,0,0,0},
{1,1,1,1,0,0,0,0,0,0},
{1,1,1,1,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,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},
```
InvalidShapeOfBoat which is invalid->
```
{1,0,0,0,0,1,1,0,0,0},
{1,0,0,0,0,0,0,0,1,0},
{1,1,0,0,1,1,1,0,1,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,0},
{0,0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,0,1,0},
{0,1,0,1,0,0,0,0,0,0},
{0,1,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,0,0},
```
wrong ships, result is false-
```
{1,0,0,0,0,1,1,0,0,0},
{1,0,1,0,0,0,0,0,1,0},
{1,0,1,0,1,1,1,0,1,0},
{1,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,0},
{0,0,0,0,1,1,1,0,0,0},
{0,1,0,0,0,0,0,0,1,0},
{0,0,0,1,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,0,0},
```
missing ships, is false->
```
{0,0,0,0,0,1,1,0,0,0},
{0,0,1,0,0,0,0,0,1,0},
{0,0,1,0,1,1,1,0,1,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,0},
{0,0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,0,1,0},
{0,0,0,1,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,0,0},
```
check contact, is true->
```
{1,1,1,0,0,0,0,0,0,0},
{1,1,0,0,0,0,0,0,1,0},
{1,1,0,0,1,1,1,0,1,0},
{1,0,0,0,0,0,0,0,0,0},
{1,0,0,0,0,0,0,0,1,0},
{0,0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,0,0},
```
check another one with contact->
```
{1,1,1,0,0,0,0,0,0,0},
{1,1,0,0,0,0,0,0,1,0},
{1,1,0,0,1,1,1,0,1,0},
{1,0,0,0,0,0,0,0,0,0},
{1,0,0,0,0,0,0,0,1,0},
{0,0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,0,0},
```
check invalid, is false->
```
{0,1,1,1,0,0,0,0,0,0},
{0,0,0,1,1,1,0,0,0,0},
{0,1,1,1,0,0,0,0,0,0},
{0,0,0,1,1,1,0,0,0,0},
{0,1,1,1,0,1,1,0,0,0},
{0,1,0,0,0,0,1,1,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
```
random board which is false->
```
{0,1,0,0,0,0,0,0,0,0},
{1,1,1,1,0,0,0,0,0,0},
{1,0,1,1,1,0,0,0,0,0},
{1,1,0,0,0,0,0,0,0,0},
{1,1,0,0,0,0,0,0,0,0},
{0,1,0,0,0,0,0,0,1,0},
{0,0,1,0,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,1,0,0,0,0,0},
{0,0,0,0,1,0,0,0,0,0},
```
Who's code will be the shortest byte solution that passes all these examples successfully?! Good luck. ;)
Any language is allowed.
on the 16th I will award the winner with a nice green tick:)
[Answer]
# JavaScript (ES6), ~~162~~ 158 bytes
Returns `0` if the grid is invalid, or a positive integer otherwise.
```
m=>(o=0,g=u=>m.some((r,y)=>r.some((v,x)=>v&&[0,1].map(d=>(r=(w,X=x+!d*w,R=m[y+d*w]||0)=>R[X]&&R[R[X]--,u&(k=1<<w*3)*7&&g(u-k),r(-~w),X]++)``)))|u||++o)(668)*o
```
[Try it online!](https://tio.run/##7ZXNaoNAEIDvPkV6WXZ1lR0KaQ9ZH8KTIEIkmtAmZoNWTUD66tbQ2MR/EeOpzEGXmdmZ@ZiZ/XRiJ9wEH6cv9ShcL9vyzOc6FpzRHY@47muh8D2MA3ohXA9up5ie81OMkMUo2JrvnLCbewUcJ9TkZ@XFlRNqcN@6KPmfnaYsNzcs00bIsK5fVaURwnsOq1UivxL5DaEdjtQ9oQFWvxNCTVtRyHpNCEmjNFUUQfBy@U5kkW3EMRQHTzuIHd5iS1osLKC/wu5i07kUjNZkFoVkEyI1wihs/tItKihfAY@lFfbwqBicT80DqsE7PG4h6zGgbD85DGiGUWRUgQFTwoAuj94mGwmDtcFgbTBYG4x5OuOZMGrTXJ2G4WPS2hkwNQz2D@P5MFj3pi8p7/M81qNjNUBfBTO8JtVVNeShrOFo7qV@ReeehFGdAUMUVxjZDw "JavaScript (Node.js) – Try It Online")
### Commented
```
m => ( // m[] = input matrix
o = 0, // o = result
g = u => // g is a recursive function taking a bit mask u
// holding the ship counters on 4 x 3 bits
m.some((r, y) => // for each row r[] at position y in m[]:
r.some((v, x) => // for each value v at position x in r[]:
v && // abort if v is not set
[0, 1].map(d => // otherwise, look for a horizontal ship (d = 0)
( // or a vertical ship (d = 1):
r = ( // r is a recursive function taking:
w, // w = ship width - 1
X = x + !d * w, // X = position of the cell in ...
R = m[y + d * w] // ... R[] = row of the cell
|| 0 // (force it to 0 if undefined)
) => //
R[X] && // abort if R[X] is not set
R[ //
R[X]--, // otherwise, set the cell to 0
u & 7 * // if there's still at least one ship of
(k = 1 << w * 3) // width w to be found in the grid:
&& g(u - k), // do a recursive call to g with u updated
r(-~w), // do a recursive call to r with w + 1
X //
]++ // restore the cell afterwards
)`` // initial call to r with u zero'ish
) // end of map()
) // end of some()
) // end of some()
| u || ++o // increment o if the grid has been cleared and all
// boats have been found
)(668) // initial call to g with u = 668 (001 010 011 100)
* o // multiply by o
```
[Answer]
# [R](https://www.r-project.org/), 211 bytes
```
v=function(b,f=c(3:1,2,1,1))`if`(any(f),{any(sapply(list(b,t(b)),function(m)any(apply(h<-which(m[1:(dim(m)[1]-f[1]),]>0,T),1,function(x)`if`(all(m[y<-t(x+rbind(0:f[1],0))]),{m[y]=0;v(m,f[-1])},F)))))},sum(b)==4)
```
[Try it online!](https://tio.run/##jVJNb9swDL37VwjIRcJkwG5TdHDq3TZgpwFDdgqCVI7lWoUlG6KUxCv62zPKSVsn86GGv0S@Rz480h53olGlcHJTCOcaCbXqID/u8sqbrVOtoQWv8i29zVJ@w1OeMvaoqkcqTE8rxl/CF0TXNT1tFDhE48MYf6drFiAnRP0Q72u1ralepRktlcbsKl3HFb4YX39L@JJhj3fu4dyraZDRP8SOHr7YQpmSJlng8IQxJL5gcp0nix3VvFrFWOuV/2DheuXgNerJ8zk7Fq2wZa6Fs@pAE56Gmy2GKMq542k2X@dpNCNTltABx8iMOKUlxK13pDVk@fNXFBjSqqonHpR5IqB010hLQDrfZeTZQ4BK8lGND@et9QoQJ0w5nEsJzrY9RmjXeCCulgSElmROwBdaWGUkMOzWCThnsRa2@yuBaGWQEsrQvXJ1kDcgPohEABH2yWtpXBZJ3bl@M2lJNIsGB87ZEXIxiqNlc56iYZdBfpvdXQfvs68TyITfZ2kSHJ/0e4Q9LWBYPxbEmdZsxgJH/4urHOrBxglOjZp2HxyxEk2QxO3bN/9hGIBpR/Nh05Kuil/I@jTh5kQIkhwO/Lwz/@m5XIicLH//@c6i4z8 "R – Try It Online")
**How?**
Pseudo-code version:
```
# recursive function:
validate_battleships=
v=function(board,fleet_without_submarines)
if there's nothing left in the fleet,
and the board contains the right number of submarines:
return(TRUE)
else if any of these:
try all positions:
if we can place the first ship in the fleet:
return result of recursive call
after removing this ship from the board and the fleet
return(TRUE)
else return(FALSE)
```
And the actual, ungolfed [R](https://www.r-project.org/) code:
```
validate_battleships=
v=function(b,f=c(3:1,2,1,1)) # f=fleet=ship sizes minus 1, without submarines
`if`(any(f),{ # if there are any ships in the fleet:
any( # return TRUE if any of these are true:
sapply(list(b,t(b)), # test the board and the transpose of the board (to try horizontal & vertical ship-placements)
function(m)any( # check if any of these are true:
apply(h<- # test each nonzero position on the board (excluding the last rows that would make the ship go off the edge)
which(m[1:(dim(m)[1]-f[1]),]>0,T),1,
function(x) # consider the first ship: f[1] (first item in fleet argument)
`if`(all(m[y<-t(x+rbind(0:f[1],0))]),
# if all the adjacent positions up to the ship size are nonzero (so we can place this ship),
{m[y]=0; # set all these positions to zero
v(m,f[-1])} # and return the result of a recursive call without this ship;
,F) # otherwise return FALSE
))))}
,sum(b)==4) # if there were no ships in the fleet, check that the nonzero positions on the board
# add-up to 4 (number of submarines): if they do, return TRUE.
```
[Answer]
Here is my answer in Java, I am definitely not skilled enough to get it down to a minimal amount of bytes and I prefer not to say(shortest byte solution for this code is down at the bottom of this post, credit to @ceilingcat for getting my code down to **482 bytes**:P) [try it,](https://tio.run/##tZFPb6MwEMW/CnuJ7Nog0l31EO9kb1UjQQ70aPnAH9N1oaaxCQsi7FfPmiRsV9pz9SQM459m5j1e0y71X4vqnNeptV48npVuvYomXHBBUy5Ay1@eq3ExfqNfne5nTbSgklra04FlTVPLVHtP6IJxkdG5xw6PXWq8A@wAHpgq0ZcDLhszQ14EKd8RIqiBArKglvql/UlzGtM9Vcz4/jZkFzgHyfKPzxj2oGDNMt6DEXyAXGzDlfoeMUUIPpwAxQQMQRYivC1@hJuMG6IEzwUGiFarJ5SgjK4x3eHTCe0J5CTayivnKIf@y4Uzx4xsj0Z7Bzbd7CWLT33x2eBxXi35G1QFheBSsOq6d8IrF6J7BHndaIkwm3Fml9ue2LvGefHt3W@/ERAuExM2LdF2y8gSjxJKNyIUt9Qu3eagh02Jl/d@M@CKQL@0qgDuQ@eqdJ7YdH4/ZrXKPdumrTu6RhXeW6o0em6N0i9cWDze5j3COK7pVeGHJvpp1ZD@p0@rTux5sK18C5pjG7w7722t0fwbY4SDDj1iF9Z0/gM)
it works!
thanks to ceilingcat with the **482bytes** solution:
```
int k,R[][],a[]=new int[]{4,3,3,2,2,2},d,e,s,x,y;boolean H(int[][]b,int I){var q=I==6;if(!q)for(int L=a[I++],r=d=b.length,c,M,N,i;r-->0;)for(c=e;c-->0;)for(M=N=i=1;b[x=r][y=c]>0&i<L;i++)q|=(M+=r+(s=L)>d?0:b[r+i][c])==L&&H(R(b,1),I)||(N+=c+L>e?0:b[r][c+i])==L&&H(R(b,0),I);return q;}int[][]R(int[][]n,int o){for(R=new int[k=d][e];k-->0;)R[k]=n[k].clone();for(;s-->0;)R[x+s*o][y-s*~-o]=0;return R;}boolean v(int[][]f){e=f[k=0].length;for(var y:f)for(var x:y)k+=x;return k==20&H(f,0);}
```
so here is my solution. (I went with a recursive solution for finding the ships)
```
public class BF {
private static int[][] fields;
public BF(int[][] field) {
fields=field;
}
public boolean validate() {
int cnt=counter(fields);
if(cnt!=20)return false;
return checkBoard(fields, new int[]{4,3,3,2,2,2},0);
}
public static boolean checkBoard(int[][] board,int[] allBoats,int index){
if (index == allBoats.length) {
return true;
}
int boatLen = allBoats[index];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[0].length; col++) {
if(board[row][col]==1 && row+ boatLen <=board.length) {//vertically
int cnt=1;
for(int i=1;i<boatLen;i++) {//check vertically
if(board[row+i][col]==1) {cnt++;}
}
if(cnt>=boatLen) {
int[][] newBoard = deepcopy(board);
newBoard= remove(newBoard , row, col, boatLen, "ver");
if(checkBoard(newBoard,allBoats,index+1)) { return true;}
}
}
if(board[row][col]==1 && col+boatLen<=board[0].length) {//horizontally
int cnt=1;
for(int i=1;i<boatLen;i++) {//check horizontally
if(board[row][col+i]==1) {cnt++;}
}
if(cnt>=boatLen) {
int[][] newBoard = deepcopy(board);
newBoard= remove(newBoard , row, col, boatLen, "hor");
if(checkBoard(newBoard,allBoats,index+1)) { return true;}
}
}
}
}
return false;
}
public static int[][] remove(int[][] newBoard,int row,int col,int size,String orien){
int[][] removedBoard= deepcopy(newBoard);
if(orien=="ver") {
for(int i=0;i<size;i++) {
removedBoard[row+i][col]=0;
}
return removedBoard;
}
else if(orien=="hor") {
for(int i=0;i<size;i++) {
removedBoard[row][col+i]=0;
}
return removedBoard;
}
return removedBoard;
}
public static int[][] deepcopy(int[][] fields){
int[][] copy= new int[fields.length][fields[0].length];
for (int row = 0; row < fields.length; row++) {
for (int col = 0; col < fields[0].length; col++) {
copy[row][col]= fields[row][col];
}
}
return copy;
}
public static int counter(int[][] f) {// counts amount of tiles on the board with 1's
int cnt=0;
for (int col = 0; col < f[0].length; col++) {
for (int row = 0; row < f.length; row++) {
if (f[row][col] == 1) {
cnt++;
}
}
}
return cnt;
}
}
```
here is my Pseudo code on the Check board function
```
/*
*
* function gets length of boat(field, size, ships){{3,2,1};
* loop go through each position in field
* checks vertically {
* finds option for where the boat can be
* copies the board
* removes the boat from the copy
* call remove boat(function gets length of boat) for size-1, deepcopy
* if true then return true
* }
* check horizontal{
* finds option for where the boat can be
* copies the board
* removes the boat from the copy
* call remove boat(function gets length of boat) for size-1, deepcopy
* if true then return true
* }
* else find next size 4 option
* }
*/
```
let me know what u think:P
if you want to test it, here is some code for testing in my Java Solution:
```
import org.junit.Test;
import static org.junit.Assert.*;
public class SolutionTest {
@Test
public void testContact() {
int[][] field = {};
assertTrue("Must return true", new BF(field).validate());
}
}
```
] |
[Question]
[
This challenge is about the following variant of [edit distance](https://en.wikipedia.org/wiki/Levenshtein_distance#:%7E:text=Informally%2C%20the%20Levenshtein%20distance%20between,considered%20this%20distance%20in%201965.). Say we have a cost of 1 for inserts, deletes and substitutions as usual with one exception. A substitution for a given letter `x` for a letter `y` only costs `1` the first time. Any further substitutions of `x` for `y` cost 0.
As simple examples:
```
A = apppple
B = attttle
```
cost 1 (not 4) to transform A into B. This is because we change `p` for a `t` four times but we only charge for the first one.
```
A = apxpxple
B = atxyxtle
```
cost 2 (not 3) as the `p` to `t` substitution only costs 1 even though we do it twice.
```
A = apppple
B = altttte
```
cost 3. `p` -> `l` costs 1. `p` -> `t` costs 1 as does `l` -> `t`.
If we assume the total length of the input is `n`, you must give the big O() of your algorithm. The best time complexity wins.
---
We should assume the alphabet size can be as large as `n`.
[Answer]
# Naive recursive algorithm \$ O(\frac{(1+\sqrt2)^n}{\sqrt{n}}) \$
The basic idea is try adding, removing and replacing one character and recursive.
```
def f(str1, str2):
l1, l2 = len(str1), len(str2)
mapping = set()
def g(p1, p2):
if l1 == p1 or l2 == p2:
return l1 + l2 - p1 - p2
cost1 = g(p1 + 1, p2) + 1
cost2 = g(p1, p2 + 1) + 1
if str1[p1] != str2[p2] and (str1[p1], str2[p2]) not in mapping:
mapping.add((str1[p1], str2[p2]))
cost3 = g(p1 + 1, p2 + 1) + 1
mapping.discard((str1[p1], str2[p2]))
else:
cost3 = g(p1 + 1, p2 + 1)
return min(cost1, cost2, cost3)
return g(0, 0)
```
The function `g` will be invoked \$ O(\frac{(1+\sqrt2)^n}{\sqrt{n}}) \$ times[1]. While adding, discarding, or checking an element in the mapping cost \$ O(1) \$ on average.
[1]: Based on <https://oeis.org/A027618> ; I don't know why actually...
[Answer]
Based on the Wagner–Fischer algorithm, each cell (here I just store a single row rather than the whole matrix) contains a list of tuples of edit distances and their associated transpositions. The matrix itself requires \$ O(n^2) \$ to traverse, but I don't know the cost of tracking the sets of transpositions, which varies across the grid roughly in line with Delannoy numbers. The code also merges distances with the same transpositions; I don't know whether that increases or reduces the complexity.
```
def dist(fr, to):
costs = [[(i, frozenset())] for i in range(len(fr) + 1)]
for j in range(len(to)):
editcosts = costs[0]
delcosts = costs[0] = [(costs[0][0][0] + 1, frozenset())]
for i in range(len(fr)):
inscosts = costs[i + 1]
allcosts = [(c + 1, s) for c, s in delcosts + inscosts] + [(c, s) if fr[i] == to[j] or fr[i] + to[j] in s else (c + 1, s | {fr[i] + to[j]}) for c, s in editcosts]
allcosts = [min((c, s) for c, s in allcosts if s == e) for e in {s for c, s in allcosts}]
costs[i + 1] = allcosts
editcosts = inscosts
delcosts = allcosts
return min(costs.pop())
print(dist("apxpxple", "atxyxtle"))
```
[Try it online!](https://tio.run/##bVLbaoQwEH33Kw4@JbiUlr4V9kvEB1nHNotNJEnB7Xa/3U5iDLqIgsmcORdmHG/@y@j3ee6oR6ecF709wRv5UQAX47zDGXUt1Am9Nb@kHXkhZYPeWCgoDdvqTxIDaWZKVHiTDVMDfN3DLBpVAeqUX7Xjt35tItDR8FwP9mK9LG8weYoT2ceRkicYcHtxFYSahLZDtma/xcLJqHnhU5DN6aqsFbJwe2xVPWeqFSc@8wDrawPmLpUqFVjEgQZHyBb4w33X9Nib5lkdBf1WWiT3LSe3cCQX4tCCUwDv7rD3sepvZ8MeK57Q7erWISRos7wNyZL/sRohaSy9jGbkjRXFaJX2Iv5yZTtO/AxUnlC2frpNns9SzvM/ "Python 3 – Try It Online")
[Answer]
A\* Search, unknown complexity. Seems to at least achieve \$o(2^{n})\$ and is quite fast in practice. No reason to think it's optimal, but making it better seemed like too much work.
```
import collections
import heapq
def dist(s0, s1):
l0, l1 = len(s0), len(s1)
suffix_sets = tuple([frozenset(s[i:]) for i in range(len(s) + 1)] for s in (s0, s1))
q = []
def push_node(g, i, j, substs):
suff0, suff1 = suffix_sets[0][i], suffix_sets[1][j]
substs = frozenset(
t for t in substs if t[0] in suff0 and t[1] in suff1
)
substs0, substs1 = {c0 for c0, _ in substs}, {c1 for _, c1 in substs}
h0 = abs((l0 - i) - (l1 - j))
h1 = max(len((suff0 - suff1) - substs0), len((suff1 - suff0) - substs1))
h = max(h0, h1)
heapq.heappush(q, (g + h, -g, -len(substs), i, j, substs))
closed = collections.defaultdict(lambda: set())
push_node(0, 0, 0, frozenset())
while True:
(f, neg_g, _, i, j, substs) = heapq.heappop(q)
g = -neg_g
if (i == l0) or (j == l1):
return f
closed_ij = closed[(i, j)]
if (g, substs) in closed_ij:
continue
subsumed = False
for (g1, substs1) in closed_ij:
if g1 <= g and substs.issubset(substs1):
subsumed = True
break
if subsumed:
continue
if substs:
closed_ij.add((g, substs))
c0, c1 = s0[i], s1[j]
if (c0 == c1) or ((c0, c1) in substs):
push_node(g, i + 1, j + 1, substs)
continue
push_node(g + 1, i + 1, j, substs)
push_node(g + 1, i, j + 1, substs)
push_node(g + 1, i + 1, j + 1, substs | frozenset([(c0, c1)]))
```
[Answer]
I worked a bit more on this, against my better judgement :). A\* search, more complicated than my other answer.
```
import collections
import heapq
import itertools
class SubsumptionTrie:
def __init__(self):
self.max_len = 0
self.min_v = float('inf')
self.children = {}
def insert(self, k, v, i=0):
self.max_len = max(self.max_len, len(k) - i)
self.min_v = min(self.min_v, v)
if i >= len(k):
return
c = k[i]
if c not in self.children:
self.children[c] = SubsumptionTrie()
self.children[c].insert(k, v, i + 1)
def subsumption_test(self, k, v, i=0):
if i >= len(k):
return self.min_v <= v
if (self.min_v > v) or (self.max_len < (len(k) - i)):
return False
c = k[i]
for b, child in self.children.items():
if b < c and self.children[b].subsumption_test(k, v, i):
return True
if c in self.children:
return self.children[c].subsumption_test(k, v, i + 1)
return False
def heuristic(s0, s1, n0, n1, substs):
substs0 = {a for a, _ in substs} | set(s1.keys())
substs1 = {b for _, b in substs} | set(s0.keys())
if n0 > n1:
s0, s1 = s1, s0
n0, n1 = n1, n0
substs0, substs1 = substs1, substs0
h0 = 0
m1 = sum(n for c, n in s1.items() if c in substs1)
for c, n in sorted(s0.items(), key=lambda t: t[1]):
if (c not in substs0) or (m1 < 0):
h0 += 1
else:
m1 -= n
h1 = 0
for c, n in sorted(s1.items(), key=lambda t: (t[0] in substs1, t[1]), reverse=True):
n0 -= n
if n0 < 0:
excess = min(-n0, n)
h1 += excess
n -= excess
if n and (c not in substs1):
h1 += 1
return max(h0, h1)
def dist(s0, s1):
labels = itertools.count()
relabel = collections.defaultdict(lambda: next(labels))
s0, s1 = [relabel[c] for c in s0], [relabel[c] for c in s1]
label_count = next(labels)
l0, l1 = len(s0), len(s1)
suffix_counts = tuple([collections.Counter(s[i:]) for i in range(len(s) + 1)] for s in (s0, s1))
q = []
def push_node(g, i, j, substs):
suff0, suff1 = suffix_counts[0][i], suffix_counts[1][j]
substs = frozenset(
t for t in substs if t[0] in suff0 and t[1] in suff1
)
h = heuristic(suff0, suff1, l0 - i, l1 - j, substs)
heapq.heappush(q, (g + h, -g, -len(substs), i, j, substs))
push_node(0, 0, 0, frozenset())
closed = collections.defaultdict(lambda: SubsumptionTrie())
while True:
(f, neg_g, _, i, j, substs) = heapq.heappop(q)
g = -neg_g
if (i == l0) or (j == l1):
return f
closed_ij = closed[(i, j)]
k = sorted(a * label_count + b for a, b in substs)
if closed_ij.subsumption_test(k, g):
continue
closed_ij.insert(k, g)
c0, c1 = s0[i], s1[j]
if (c0 == c1) or ((c0, c1) in substs):
push_node(g, i + 1, j + 1, substs)
continue
push_node(g + 1, i + 1, j + 1, substs | frozenset(((c0, c1),)))
push_node(g + 1, i + 1, j, substs)
push_node(g + 1, i, j + 1, substs)
```
[Answer]
# [Rust](https://www.rust-lang.org/)
Port of [@tsh's answer](https://codegolf.stackexchange.com/a/215159/110802)
[run it on Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ccd38baa446cb8a3cec175a4ab67278a)
```
use std::cmp;
use std::collections::HashSet;
use std::time::Instant;
fn f(str1: &str, str2: &str) -> usize {
let mut mapping = HashSet::new();
fn g(p1: usize, p2: usize, str1: &str, str2: &str, mapping: &mut HashSet<(char, char)>) -> usize {
let l1 = str1.len();
let l2 = str2.len();
if l1 == p1 || l2 == p2 {
return l1 + l2 - p1 - p2;
}
let cost1 = g(p1 + 1, p2, str1, str2, mapping) + 1;
let cost2 = g(p1, p2 + 1, str1, str2, mapping) + 1;
let c1 = str1.chars().nth(p1).unwrap();
let c2 = str2.chars().nth(p2).unwrap();
let cost3 = if c1 != c2 && !mapping.contains(&(c1, c2)) {
mapping.insert((c1, c2));
let cost = g(p1 + 1, p2 + 1, str1, str2, mapping) + 1;
mapping.remove(&(c1, c2));
cost
} else {
g(p1 + 1, p2 + 1, str1, str2, mapping)
};
cmp::min(cost1, cmp::min(cost2, cost3))
}
g(0, 0, str1, str2, &mut mapping)
}
fn main() {
let test_cases = [
("apppple", "attttle", 1),
("apxpxple", "atxyxtle", 2),
("apppple", "altttte", 3),
];
for (a, b, expected) in test_cases.iter() {
let start = Instant::now();
let result = f(a, b);
let duration = start.elapsed();
println!("A: {}, B: {}, Output: {}, Expected: {}", a, b, result, expected);
println!("Time elapsed: {:?}", duration);
}
}
```
] |
[Question]
[
Given a grid of directions and a start and end position, determine the minimum number of substitutions in the direction grid that needs to be made to complete the path between the two points. The grid is doubly-cylindrical. This is clearer given an example.
## Example
Let's take the following grid as an example:
```
>>>>v
>>>><
<<<<<
```
Let's start at `(1, 1)` and end at `(1, 3)` (where the coordinates are `(x, y)` or `(col, row)`, with the top row and left column being `1`). Then, one possible solution is to replace the `(1, 1)` and `(1, 2)` with `v`, so that the final grid looks like this:
```
v>>>v
v>>><
<<<<<
```
Starting from `(1, 1)`, the path would lead us to `(1, 3)`. However, a shorter solution exists, which is to replace `(5, 2)` with `v`, so the final grid is this:
```
>>>>v
>>>>v
<<<<<
```
Starting from `(1, 1)`, a rather long path leads to `(1, 3)`.
Replacing anything in the top row with `^` works too (thanks @Spitemaster).
## Input
The input will consist of a rectangular grid of 4 possible values, as well as two coordinates. You can take the grid in any reasonable format; for example, character or integer matrix, string list, etc. You can also request the dimensions of the grid. You can take the coordinates in any reasonable format; for example, integer pair, complex number, etc. You can choose 0- or 1-indexing.
## Output
The output should be a single integer, the minimal number of grid replacements necessary to close the path from the start to the end.
## Rules and Specifications
* Standard Loopholes Apply
* the grid is doubly cylindrical, meaning that moving up from the top goes to the bottom, left from the left goes to the right, etc.
## Sample Cases
The sample cases are given as a character matrix and 1-indexed coordinates.
### Case 1
**Input**
```
>>>>v
>>>><
<<<<<
1 1
1 3
```
**Output**
```
1
```
**Explanation**
See example.
### Case 2
**Input**
```
<<<<<
v>v>v
>>>>>
1 1
5 3
```
**Output**
```
1
```
**Explanation**
You can either replace `(1, 1)` with `v` or `(2, 1)` with `v`. In the first case, starting from `(1, 1)`, the path goes straight down and then to the right to the destination. In the second case, the path loops off the left to the right, reaches `(2, 1)`, goes down, right, down, and then right until it hits the destination.
### Case 3
**Input**
```
^^^^^^
><<>>>
vvvvvv
2 2
5 2
```
**Output**
```
2
```
**Explanation**
The best change is to make the center row wrap around the left to the point; that is, make the first and last items in the center row `<`. Alternatively, make `2 2` and `3 2` both `>`.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins!
[Answer]
# JavaScript (ES6), ~~140~~ 135 bytes
Takes input as `(a, width, height, x1, y1)(x0, y0)` where `a[]` is a matrix of integers and all coordinates are 0-indexed.
Directions: \$-2\$ for *left*, \$-1\$ for *up*, \$0\$ for *right* and \$1\$ for *down*.
```
(a,w,h,X,Y)=>m=g=(x,y,n=0,r=a[y%=h],v=r[x%=w])=>x-X|y-Y?[-1,0,1,2].map(d=>r[v<2&&g(x+w+d%(r[x]=2),y+h+--d%2,n+(v!=d)),x]=v)|m:m=m<n?m:n
```
[Try it online!](https://tio.run/##hY5fa4MwFMXf/RR3D9YEb0TttoeSmz7sA@y1RRyI2j@jxqIjKvS7u9gN2jJhB8IhJ7nndz8zk7V5czx/CV0X5bijkWXY4QE3uOWkKtoT63FATSE2lCWDS4cUDTVJ71KX2i@92FwGsV0nIsIQI4zToMrOrCDVJEbGi8We9X7nFy6zMynFHAf/4AtRuDFqn5knKjhH@2L4pVpVVEm9rlZ6bOoOCFogBUkQBO1PbT7dPfmhjBccdVH27zuWcxAQc8fJa93WpzI41XvmvWVtCdEKPPBhxxyAxB4AW8s8ZWU8jo@JfEjkJI/bIJ3SF4Tl5CFC7HBmLeSzyHge@Vt3BzDKzCyh/iKf/0Mu55EfVz0SpLwi7te46kZ9vVEjS42scT5@Aw "JavaScript (Node.js) – Try It Online")
### How?
We use a breadth-first search to try all possible paths from \$(x,y)\$ to \$(X,Y)\$ without visiting twice the same cell.
We keep track of the number of times \$n\$ where the direction that was chosen did not match the direction stored in the input matrix.
We eventually return \$m\$, which is defined as the minimum value of \$n\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~73~~ 72 bytes
```
W,0+Ɱ⁴PṬ€×Ɱ3¤Ẏ¤,€ɗ/€Ẏ$‘ƭ€ịØ.,N;U$¤;ɗ/0ị+æ.Ɱ⁴‘Ṫịʋ¥Ɗ%⁴ṭƲ⁴P¤¡ŒHṪe¥/Ʋ€Ẹ¬Ɗ/¿Ṫ
```
[Try it online!](https://tio.run/##y0rNyan8/z9cx0D70cZ1jxq3BDzcueZR05rD04Fc40NLHu7qO7REByhwcro@kARyVR41zDi2FsTe3X14hp6On3WoyqEl1kB5A6CI9uFlehCDgMoe7lwFFDrVfWjpsS5VoNDDnWuPbQLZcWjJoYVHJ3kA5VMPLdUHioFM3nFozbEu/UP7gaL///@PNtSBQGMdGMtExwgGY3Wio410DICUAZCM/W@sYwoA "Jelly – Try It Online")
[Example using case 3 that requires two changes](https://tio.run/##y0rNyan8/z9cx0D70cZ1jxq3BDzcueZR05rD04Fc40NLHu7qO7REByhwcro@kARyVR41zDi2FsTe3X14hp6On3WoyqEl1kB5A6CI9uFlehCDgMoe7lwFFDrVfWjpsS5VoNDDnWuPbQLZcWjJoYVHJ3kA5VMPLdUHioFM3nFozbEu/UP7gaL/HzXMsbMpi3vUMDcTaJoO0PDDy///V4oDAzsbGzs7uzIwUNKJjjbUMYnVAZKGsbH/jXXMAA) (also has a footer to translate the `><v^` into numbers).
A full program that expects the following arguments:
* Left: a list of two lists; first the flattened direction grid encoded as 1=right, 2=left, 3=down, 4=up, followed by a list of the end position and start position as zero-indexes [row, column]. For first example, `[1,1,1,1,3,1,1,1,1,4,2,2,2,2,2],[[2,0],[0,0]]`.
* Right: a list of the number of rows followed by columns. For first example `[3,5]`
Returns the number of changes required to get from start to end. Slow once this is more than one change. On TIO the third example case takes approx. 30 seconds to complete.
Full explanation below, but overview is:
1. Initialise a counter to zero.
2. Work out positions after each of \$\mathit{row} × \mathit{column}\$ moves.
3. Check if the end position is included:
* If false, increment a counter and create \$3 × \mathit{row} × \mathit{column}\$ new versions of the grid, each with a single grid position changed to one of the three possible alternative moves. Then go back to step 2.
* If true, terminate and output the counter
### Full explanation:
```
W,0 | Wrap input in a list, and then pair with 0 (thus initialising the counter)
Ɗ/¿ | While the following is true for the first item of the input pair (i.e. the list of all grids to be tested, paired with the end and start grid positions):
Ʋ€ | - For each member of the list:
ɗ/ | - Reduce using the following as a dyad (so left argument is flattened grid and right is end/start positions)
ị ¤ | - Index into the following as a nilad
Ø. | - [0, 1]
,N | - Pair with negative [[0, 1], [0, -1]]
;U$ | - Concatenate to upended version of this [[0, 1], [0, -1], [1, 0], [-1, 0]]
; | - Concatenate (to end/start positions)
Ʋ⁴P¤¡ | - Repeat the following links the number of times indicated by the product of the grid dimensions:
Ɗ | - Following as a monad:
0ị | - Last item (current grid position)
+ ¥ | - Add to the following as a dyad:
æ.Ɱ⁴ | - Dot product of current position with each of grid dimensions
‘ | - Increase by 1
Ṫ | - Tail (which is current position in flattened grid)
ị | - index into flattened grid
%⁴ | - Mod grid dimensions
ṭ | - Tack onto end of current grid/position list
ŒH | - Split into halves (first half will be flattened grid and desired end position, second half will be all positions reached after moving through grid)
¥/ | - Following as a dyad, with the first half from above step as left argument and the second half as right
Ṫ | - Tail (i.e. the desired end position)
e | - Exists within (the list of all positions reached)
Ẹ¬ | - Not true for any of the input grids
ƭ€ | For each of the pair (list of grids, counter), do one of the following:
$ | - For the list of grids, do the following as a monad:
ɗ/€ | - Do the following as a dyad, with the flattened grid as the left argument and end/start positions as the right:
+Ɱ | - Add to the flattened grid list each of:
¤ | - The following as a nilad
¤ | - The following as a nilad:
⁴P | - The product of the grid dimensions
Ṭ€ | - Convert each (using an implicit range from 1 to the grid dimension product) to a boolean list with a 1 at the relevant position (i.e. [[1], [0, 1], [0, 0, 1]...])
×Ɱ3 | - Multiply by each of 1..3
Ẏ | - Flatten to a single list of lists
,€ | - Pair each with the end/start positions
Ẏ | - Tighten to a single list of grids paired with end/start positions
‘ | - For the counter increment it
Ṫ | Finally, take the tail (which is the final value of the counter)
```
] |
[Question]
[
Take the numbers `0, 1, 2, 3, 4, ...` and arrange them in a clockwise spiral, starting downward, writing ***each digit*** in its own separate square.
Then, given one of four distinct and consistent ASCII characters (your choice) representing an axis, and an input integer `n`, output the first `n` terms of the sequence described by selecting squares along the corresponding axis.
For example, below is the arranged spiral up to partway through `29`. Suppose we use `u / d / l / r` for our four characters, representing `up / down / left / right`. Then, given `u` as input, we output `0, 5, 1, 4 ...` (the positive y-axis) up to the `n`th term. If we were instead given `l` as input, then it would be `0, 3, 1, 1 ...` up to the `n`th term.
```
2---3---2---4---2---5---2
| |
2 1---3---1---4---1 6
| | | |
2 2 4---5---6 5 2
| | | | | |
1 1 3 0 7 1 7
| | | | | | |
2 1 2---1 8 6 2
| | | | |
0 1---0---1---9 1 8
| | |
2---9---1---8---1---7 2
```
These are sequences on OEIS:
* <http://oeis.org/A033953> for the positive x-axis
* <http://oeis.org/A033988> for the positive y-axis
* <http://oeis.org/A033989> for the negative x-axis
* <http://oeis.org/A033990> for the negative y-axis
### Examples
```
d 19
[0, 1, 1, 8, 3, 7, 6, 2, 1, 5, 1, 1, 6, 2, 2, 1, 3, 4, 0]
r 72
[0, 7, 1, 7, 4, 2, 8, 1, 1, 3, 1, 2, 0, 2, 3, 1, 3, 4, 6, 5, 5, 5, 7, 7, 8, 8, 9, 6, 8, 1, 1, 1, 2, 3, 1, 8, 0, 6, 1, 7, 0, 9, 2, 8, 4, 3, 2, 1, 1, 7, 2, 6, 2, 1, 3, 3, 5, 5, 3, 2, 2, 0, 4, 3, 2, 5, 4, 6, 5, 0, 5, 1]
u 1
[0]
```
## Rules
* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* If you're using integers to represent the four axes, you can use negative integers without breaking the rules.
* The input and output can be given by [any convenient method](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.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~94~~ ~~89~~ ~~84~~ ~~83~~ ~~74~~ ~~72~~ 70 bytes
I used WolframAlpha and determined that an upper bound of 5n > 4n2+3n seems to be enough. It can be changed to 9n at no cost. For trying larger inputs, use `9*n*n` instead of `5**n` to avoid running out of memory.
```
lambda d,n:["".join(map(str,range(5**n)))[x*(4*x+d)]for x in range(n)]
```
[**Try it online!**](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFFJ88qWklJLys/M08jN7FAo7ikSKcoMS89VcNUSytPU1MzukJLw0SrQjtFMzYtv0ihQiEzTwGiIE8z9n9BUWZeiUKahrGOhSYXjKOLyjNE5hmiSRlq/gcA "Python 2 – Try It Online")
The inputs for directions are:
* 3: right
* -3: down
* -1: left
* 1: up
*Saved 14 bytes thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod)*
*Saved 2 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)*
[Answer]
# [MATL](https://github.com/lmendo/MATL), 32 bytes
```
tE1YLtn:qVXzw)3Lt3$)iX!w:qyfYm+)
```
Input is `n`, `a`, where `a` represents the axis as follows:
* `0`: left;
* `1`: up;
* `2`: right;
* `3`: down.
Output is a string.
[Try it online!](https://tio.run/##y00syfn/v8TVMNKnJM@qMCyiqlzT2KfEWEUzM0Kx3KqwMi0yV1vz/39zIy4jAA) Or [verify all test cases](https://tio.run/##y00syfmf8L/E1TDSpyTPqjAsoqpc09inxFhFMzNCsdyqsDItMldb879LyH9DSy5jLnMjLiMuQy5DAA).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Uses the 5n trick from [mbomb007's Python answer](https://codegolf.stackexchange.com/a/162578/53748)
```
4,0jḅɗ@€ị5*D€FʋṖ0;
```
A dyadic link taking `n` on the left and `d` and integer from: `[-3,-1,1,3]:[v,<,^,>]`
**[Try it online!](https://tio.run/##y0rNyan8/99Uy@VR05pjXW4Pd3c7mOgYZD3c0XpyugNQ7OHOaQbW////N/@vawwA "Jelly – Try It Online")**
A 20 byte alternative that is both much faster and does not segfault for such small n is:
```
²×5D€ƲFị@4,0jḅɗ@€Ṗ0;
```
**[Try it online!](https://tio.run/##y0rNyan8///QpsPTTV0eNa05tsnt4e5uBxMdg6yHO1pPTncAij3cOc3A@v///4YGpv8NAQQ "Jelly – Try It Online")**
### How?
```
4,0jḅɗ@€ị5*D€FʋṖ0; - Link: integer, n; integer, d
ɗ@€ - last three links as a dyad with sw@pped arguments for €ach (of implicit range [1,n])
4,0 - literal list [4,0]
j - join with d = [4,d,0]
ḅ - convert from base n = 4*n^2+d*n+0
ị - index into...
ʋ - last four links as a monad:
5 - five
* - exponentiate = 5^n
D€ - decimal list of each (in implicit range [1,5^n])
F - flatten into a single list of the digits
Ṗ - pop (drop the final element)
0; - prepend a zero
```
[Answer]
will work for considerable n (like +1000)
# [JavaScript (Node.js)](https://nodejs.org), 104 bytes
```
f=(d,n)=>--n?[...f(d,n),C(n*(4*n+d))]:[0]
C=(n,N=i=0)=>n>N?C(n-N,(p=10**i)*9*++i):+((p+--n/i|0)+"")[n%i]
```
[Try it online!](https://tio.run/##TY/RioMwEEXf/YogLCQ6uhNttQppH/reHxChpeqSUqLUdlno9tvdONZFGEIyuffM3Mvp@9Sfb7q7B6at6mFoFK/ACLUNArMrwjBs6A17bjy@8oxfCVHmBZbOXnEDB6UVWrXZHnZWEhyAd0qi52nhZZ7va5H7nHe@pX3qXxS@64rCfOhyuNf9nSk20oHVP52FPB3Gzq3p22sdXtsv3vBnlQcxXPNAwiOXcMvjV1GVdp/w0mpzPCplne@7cF7OCOVu5YLMoEBgkmoDLAaWAkuARdRZz19TZ2pazQoYluKNubnWFIEzglJSpKSIiChnj6QO0hkvQAmNmSql2lBl9PVPkAvjhjjJPAtJPI1bkSaaLSndk8Xq8TwrniPhwrVerIRTfpvzHfThMpBjTttqOIJERDH8AQ "JavaScript (Node.js) – Try It Online")
### Explanation
* 3: right
* -3: down (-3 is legit according to comments)
* -1: left
* 1: up
(like @mbomb007)
C- nth digit of Champernowne's constant
## \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
Less efficient method (wont work for 1000+)
# [JavaScript (Node.js)](https://nodejs.org), 81 bytes
```
f=(d,n)=>eval(`for(r=[],s=i=I="";I<n;)(s+=i++)[u=I*(4*I+d)]&&r.push(s[I++,u]),r`)
```
[Try it online!](https://tio.run/##TU/bioMwEH33K4IPJaljMWq1tZt99xtEUBrbtYhKUstC6be7cdRFGEI4cy5zHuWr1FdV90@37WQ1jjdBJbRMfFevsqHFrVNUiSwHLWqRCtu@pF/thVHtiNpxWDaIdE/DfepIlu926tAP@ofqLHUcGHIGqmDjs9JPIshkC6T67Y332yLk2rW6a6pD093pjb5l4gbQJC6HIeGgkuCTydwccnh0dVsUQhjl8mfWx5pMqS1t4GfIPCAc5wQkABIDiYD4iBzX1YzMoOGEQLycLTbKNiIfrMkoRkaMDB8d@arhiHj4BhujCGPmiXFOOGdc/TvwjfCEPtGa5SF5jguR46@SGP/R5vRgzQrWSt5Gddyc5M39Tc@l6GAT4FNPA41/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
â╞ê←τ"(]]⌐┘?N
```
[Run and debug it](https://staxlang.xyz/#p=83c6881be722285d5da9d93f4e&i=3+1%0A7+19%0A1+72&m=2)
It takes input with the direction, followed by the count. Right, up, left, and down are `1`, `3`, `5`, and `7` respectively. It takes a full minute to run the three provided test cases.
] |
[Question]
[
## Challenge:
Create a program or function that takes an integer input, which outputs a new program/function as specified below.
### Input:
Integer `n`: Time in seconds before the Time Bomb explodes.
### Output:
The original program which had the time in seconds `n` as input, will output a new program/function that does the following:
* Has `n` seconds passed since the previous program was run? Print `BOOM!`
* Else: Print a program/function which, when run itself, resets the timer back to `n` seconds (and acts the same as the first outputted program/function).
NOTE: It is not exactly the same as the first outputted program/function (in most languages at least), because the starting time has changed (see clarification example below).
### Pseudo-code Example:
Let's say the original program is `ABC` and the input is `60` seconds:
`ABC` & `60` outputs `DEF(60)`.
* If `DEF(60)` is run within 60 seconds, it will output `DEF_G(60)`, which acts exactly the same as `DEF(60)`, but with a new starting time.
* If `DEF(60)` is run after 60 seconds, it will output `BOOM!`.
### Clarification example what I mean with 'starting time':
1. Base program with input `60` seconds is run at `12:00:00`. It outputs the first output program with a starting time of `12:00:00`.
2. This first output program with starting time of `12:00:00` is run at `12:00:45`. It outputs a second output program with a starting time of `12:00:45`.
3. This third output program with a starting time of `12:00:45` is run at `12:01:25`. It outputs a fourth output program with a starting time of `12:01:25`.
4. This fourth output program with a starting time of `12:01:25` is run at `12:05:00`. It will output `BOOM!`.
Note how the first output would print `BOOM!` after `12:01:00`, but the output program has progressed so even though it's `12:01:25` at step 3, it will still output the next program instead of `BOOM!` (because the output-of-output programs has starting times beyond that first output program).
## Challenge Rules:
* [Default quine rules apply.](https://codegolf.meta.stackexchange.com/questions/12357/we-need-a-new-proper-quine-definition)
* At least `n` seconds should have passed. So if the input is `60` and starting time was `12:00:00`, at `12:01:00` it will still output the v2 program, but at `12:01:01` it will output `BOOM!`.
* The output programs will not take any input ([except for an empty unused parameter if it's shorter](https://codegolf.meta.stackexchange.com/questions/12681/are-we-allowed-to-use-empty-input-we-wont-use-when-no-input-is-asked-regarding)). The starting time should be given to the next programs as 'hard-coded' value (which is why the output of an output program isn't exactly the same as the previous (in most languages).
* Only the size of your main program/function is counted in terms of bytes.
* You can output the program/function either as string (or comparable reasonable format, like byte/character array/list), as function if your language supports this, or other reasonable formats (please ask if you aren't sure).
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
[Answer]
# JavaScript, 53 bytes
```
f=(d,t=1/0,n=Date.now()/1e3)=>n>t?'BOOM!':_=>f(d,d+n)
```
```
g=
f=(d,t=1/0,n=Date.now()/1e3)=>n>t?'BOOM!':_=>f(d,d+n)
// please notice that `delay` may take longer time than experted time on a slow / busy machine
// which may lead an incorrect result
delay=n=>new Promise(r=>setTimeout(r,n*1e3));
assertFine=s=>console.log(s!=='BOOM!'?s:'FAIL');
assertBoom=s=>console.log(s==='BOOM!'?s:'FAIL');
(async function () {
console.log('start test');
let p1 = g(3);
assertFine(p1); // should not boom
await delay(2);
let p2 = p1();
assertFine(p2); // should not boom
await delay(2);
let b1 = p1();
assertBoom(b1); // should boom
let p3 = p2();
assertFine(p3); // should not boom
await delay(2);
let b2 = p2();
assertBoom(b2); // should boom
}());
```
---
Old answer (returning should be a string)
# JavaScript, 78 bytes
```
(f=(o,t,d)=>(x=d,n=Date.now()/1e3)=>o&&n>t?'BOOM!':`(f=${f})(${[1,n+x,x]})`)()
```
```
g=
(f=(o,t,d)=>(x=d,n=Date.now()/1e3)=>o&&n>t?'BOOM!':`(f=${f})(${[1,n+x,x]})`)()
// please notice that `delay` may take longer time than experted time on a slow / busy machine
// which may lead an incorrect result
delay=n=>new Promise(r=>setTimeout(r,n*1e3));
assertFine=s=>console.log(s!=='BOOM!'?s:'FAIL');
assertBoom=s=>console.log(s==='BOOM!'?s:'FAIL');
(async function () {
console.log('start test');
let p1 = g(3);
assertFine(p1); // should not boom
await delay(2);
let p2 = eval(p1)();
assertFine(p2); // should not boom
await delay(2);
let b1 = eval(p1)();
assertBoom(b1); // should boom
let p3 = eval(p2)();
assertFine(p3); // should not boom
await delay(2);
let b2 = eval(p2)();
assertBoom(b2); // should boom
}());
```
[Answer]
# JavaScript, 51 bytes
```
f=(t,o=setTimeout(_=>o=0,t*1e3))=>_=>o?f(t):'BOOM!'
```
[Test in browser](https://jsfiddle.net/jngxuk5L/6/)
## old version
```
f=(t,o=0)=>{setTimeout(()=>o=1,t*1000);return ()=>o?'BOOM!':f(t)}
```
[Test in browser](https://jsfiddle.net/cyc948w6/30/)
[Answer]
# Java 8, 234 bytes
```
n->"v->{long t=System.nanoTime();t/=1e9;String s=\"v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>"+n+"?%1$cBOOM!%1$c:s.format(s,34,s,t);}\";return t-"+(System.nanoTime()/1e9)+">"+n+"?\"BOOM!\":s.format(s,34,s,t);}"
```
Sorry to post my own challenge right away. It is mainly meant as further clarification of the challenge, and I was doubting whether to add it to the question itself or post it as an answer (and decided to post it as an answer to not clutter the challenge post).
And although I would like to say it's also something to (try and) beat, that isn't even worth mentioning because, well.. Java (almost) always gets beaten. ;p
[Try it online.](https://tio.run/##lZA9a8MwEIb3/IqrqEHCH0loKbTGLnTrkGRItziDKivBqX0y1tmlBP92V24MHdKlIA7pPt5X95xkJ0NTazzlH4MqpbWwkgWeZwAFkm4OUmlYj0@ALTUFHkFxVwEUsUv2MxcsSSoUrAEhgQHDlHVhei6N66Vk@2VJVxFKNG9FpbmIaZ4s9WM8qdkk@1@7pzzrLW9V3GhqGwQKvTxlPvrseUy/bDarm/HyZKODaSpJ3AZ394ENSMR9xn7HmM@v3ObOSvhs0svYj1rG/tRiw0jAnbp9L93@E4bOFDlUjiG/fHm3l2Lid3EzLUW1qxDHSHHUn/DqSB91w@VusRdiAtsPw8PiGw)
Example output:
```
v->{long t=System.nanoTime();t/=1e9;String s="v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>60?%1$cBOOM!%1$c:s.format(s,34,s,t);}";return t-70492.687613232>60?"BOOM!":s.format(s,34,s,t);}
```
[Try the outputted lambda-function here.](https://tio.run/##lVDBasMwDL33K7SwgA1J1iQlXRfSwe5tDx27jB08xx3uEjvYSmCUfHtmr4FddhkIIT3pCb13ZgOLdSfUuf6ceMOshR2T6rIAkAqFOTEuYO9bgCMaqT6Akxctaxho6dBx4ZJFhpLDHhRUMA3x9tJot4jV8cuiaBPFlH6WrSC0xLsqFZtyPmWr4F/bIQ9tmN7y0gjsjQKMw3pbLB899nQ47G588WCTkzYtQ2KjfBXZCGk5Br@U9XK1yZLifl2keZZnnh/8kIM/mZOX6aLr3xsnctY6eAta5xS5Pvf6xujs0lWF7jHp3ASJSjhRfdPQ2bBx@gY)
Example output:
```
v->{long t=System.nanoTime();t/=1e9;String s="v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>60?%1$cBOOM!%1$c:s.format(s,34,s,t);}";return t-70548>60?"BOOM!":s.format(s,34,s,t);}
```
### Explanation:
The main function takes an integer input and returns a String. It basically returns a function which is a quine, with the integer input and starting time (in seconds as timestamp) as hard-coded values.
**Main function:**
```
n-> // Method with integer parameter and String return-type
"v->{long t=System.nanoTime();t/=1e9;String s=\"v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>"
// First part of the output-function
+n // With the integer input placed as hard-coded value
+"?%1$cBOOM!%1$c:s.format(s,34,s,t);}\";return t-"
// The second part of the output-function
+(System.nanoTime()/1e9)
// With the current time in seconds as hard-coded starting time
+">"+n // And the integer input again (for the output of the output function)
+"?\"BOOM!\":s.format(s,34,s,t);}"
// The final part of the output-function
```
`n=60` was used in the examples below:
**First output program:**
```
v->{ // Method with empty unused parameter and String return-type
long t=System.nanoTime();t/=1e9;
// New starting time in seconds
String s="v->{long t=System.nanoTime();t/=1e9;String s=%c%s%1$c;return t-%d>60?%1$cBOOM!%1$c:s.format(s,34,s,t);}";
// Unformatted (quine) result-function
return t- // If the difference between the new starting time
70492.687613232 // and hard-coded starting time from the main function
>60? // is larger than the hard-coded integer from the main function
"BOOM!" // Return "BOOM!"
: // Else:
s.format(s,34,s, // Return the formatted (quine) result-function,
t);} // with this new starting time as new hardcoded value
```
**Second output program:**
The same as the first output program, except that `70492.687613232` is replaced with `70548`.
[Answer]
## [Perl 5](https://www.perl.org/) + `-p`, 88 bytes
```
$_="\$s=$_;\$t=$^T;".'$_=q{say$^T-$t<$s?qq{\$t=$^T;\$s=$s;\$_=q{$_};eval}:"BOOM!"};eval'
```
Output programs must be run with `-M5.010` for `say`, but not `-p`.
[Try it online!](https://tio.run/##K0gtyjH9/18l3lYpRqXYViXeOkalxFYlLsRaSU8dKFpYXZxYCeTqqpTYqBTbFxZWw@TByouBFEiRSnytdWpZYk6tlZKTv7@vohKEq/7/v5nBv/yCksz8vOL/ugUA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"‘ÒÞ!""žažb‚žcª60β"D.VsI’"34ç ìD«ÿÿ©ÿDU-›iX®:ëÿ’D«
```
Can definitely be golfed a bit more, but it's quite tricky to output a semi-quine which outputs a quine-program with modified values.
[Try it online](https://tio.run/##AVoApf9vc2FiaWX//yLigJjDksOeISIixb5hxb5i4oCaxb5jwqo2MM6yIkQuVnNJ4oCZIjM0w6cgw6xEwqvDv8O/wqnDv0RVLeKAumlYwq46w6vDv@KAmUTCq///MzA) or [try a 20-second example run](https://tio.run/##yy9OTMpM/X@k3SVMyTMvsyQzMUchM6@gtMRK4fB@rqDU4tKcksy8dIWCovz0osRcKwUlnf9KjxpmHJ50eJ6iktLRfYlH9yU9aph1dF/yoVVmBuc2KbnohRVHPmqYqWRscni5wuE1LodWH95/eP@hlYf3u4TqPmrYlRlxaJ3VYaAgUBFQ8r@LzqFt9lzFZZWHJyiFJ2aWAC1WKE5Nzs9LKVbSedTUoqUXzqWEEFPISCxLVShILC5OTdFT8EstV8gvLQE7WEmHSy8MbNr/aFMdBWMdBSMdBUODWAA).
**Explanation:**
```
"‘ÒÞ!" # Push the string "‘ÒÞ!"
"žažb‚žcª60β" # Push the string "žažb‚žcª60β"
D # Duplicate it
.V # Execute it as 05AB1E code:
# ža : Push the current hours
# žb : Push the current minutes
# ‚Äö : Pair them together
# žcª : Append the current seconds
# 60β : Convert from this integer list to base-60
s # Swap the seconds-integer and duplicated "žažb‚žcª60β"-string
I # Push the input
’"34ç ìD«ÿÿ©ÿDU-›iX®:ëÿ’ "# Push the string '"34ç ìD«ÿÿ©ÿDU-›iX®:ëÿ',
# where the `ÿ` are automatically replaced with the stack-values
D¬´ # Duplicate it, and append them together
# (after which the string is output implicitly as result)
```
Example resulting program:
```
"34ç ìD«30žažb‚žcª60β©35555DU-›iX®:ë‘ÒÞ!"34ç ìD«30žažb‚žcª60β©35555DU-›iX®:ë‘ÒÞ!
```
Which is based on the default quine: [`"34çìD«"34çìD«`](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1wOrUaw/v8HAA).
```
"34ç ìD«30žažb‚žcª60β©35555DU-›iX®:ë‘ÒÞ!"
# Push this string
34ç # Push 34, converted to a character: '"'
ì # Prepend it in front of the string
D¬´ # Duplicate this string, and append them together
# (we now have the quine-string at the top of the stack)
žažb‚žcª60β # Get the current time in seconds similar as above
© # Store it in variable `®` (without popping)
35555 # Push the time this program was generated
DU # Store a copy in variable `X`
- # Subtract the two times
30 ›i # If the original input-integer is larger than this:
X®: # Replace integer `X` with `®` in the generated quine-string
ë # Else:
‘ÒÞ! # Push dictionary string "BOOM!"
# (and output the top of the stack implicitly as result)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `‘ÒÞ!` is `"BOOM!"`.
NOTE: The reason the space is there between `çì` is because otherwise it's interpret as a dictionary-string (`triumph`) due to the `’...’`.
] |
[Question]
[
Oh no, I am lost on the way to finding the great treasures of Marakov! And all I have are these useless instructions that look like `S10R10D30`... I have no idea what they mean! Can you help me?
## Challenge
Given directions consisting of `N E S W U D L R 1 2 3 4 5 6 7 8 9 0`, output how far I will be from where I started when I follow those directions (i.e. Euclidean Distance).
`N E S W` refer to me turning North, East, South, and West;
`U D L R` refer to me turning Up, Down, Left, and Right (So `NR` is the same as `E`, and so is `SL`; `SLL` is the same as `N`). Up means keep going forward; Down means turn around.
After each letter direction will be a number, which is how far I will go in that direction. `N10E20` means go North 10 units, then turn East, and go East 20 units.
## Input Details
* Input will always start with one of `NESW` (so blank input need not be accounted for).
* Two letter instructions in a row are allowed. `NE` should be interpreted, "Turn North, then immediately turn East". It's the same as just `E`. `SLL` is "Turn South, then immediately turn Left twice". It's the same as `N`.
* All numbers will be integers (note how `.` isn't in the character set)
* Input will only consist of `NESWUDLR1234567890` (If it *needs* something else, like '\0' in C; or if your language's input functions has a trailing newline, or something, that's fine.)
## Output
* [The norm.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* If using a function, should output a numeric datatype or a string.
* Must be accurate to 3 decimal places.
## Test Cases
* `N10`: `10`
* `N10E10`: `14.1421`
* `N10S10`: `0`
* `NSEWUDLR10`: `10`
* `N100RR20E300D40L12`: `268.7452`
* `ERR10LL20UN30D100`: `70.71067`
[The unimaginative Python program I used to make these.](https://tio.run/##fZLLboMwEEXX8VeM3E1IWtWQ9IWUVcMOeUGEWERRlQbSIqU4MqRSv57OOA8IKF5gaXyP597B3v9V36qY1DXLi7LSh02Vq6KEGfAgilwRhp6I5UTMXSE4u2bGCMWcbVKkpSoygDt4P2idFRWkuc4MxorDzye1E5x0iVWmoayUXn9lbKOUTsltKe5BrNhWaUAP/KBt5bNBvj0L3PUm06fnl9c3wVEYGAPMgjIbZLsWKINFEs/D6IJ9/K53QGQ1pNI5nzbxsMCzNA2WkvtwDLd0V9T9fBwp43HiFlfcw00uaThh44Irru17jNcejdAUToM3k8/MtfiwX5e9/bn5Fd05qQlOQkpvNqPJnnYxx8RdLbhoCe8GCG8HSCwmtnC2ALIXILodwNbIFsAWHAOwvaYHd7xV51QNm0sejcCDcesV0YZD69B99Bynrv8B)
## Winning
This is codegolf, so lowest bytes after a week wins!
[Answer]
# [Python 3](https://docs.python.org/3/), 137 bytes
```
v=n=0
d=1
for i in input()+'U':x="NUERSDW0123456789".find(i);c=x<7;v+=d*n*c;n=[n*10+x-7,0][c];d=[d,d**(x%2)*1j**(~-x/2)][c]
print(abs(v))
```
[Try it online!](https://tio.run/##FclBC4IwGIDhu79ChHCbWt9mZbV205t4MKSDeCiHtA5TzGRd@uvL4D088A6f6dHr2NpZaAGOFNTp@tFVrtJLw3tCOPAr/2SEV1RZeUmvQFm83e2Tw9Fbd0pLpDBvhTknfA6EJJq0XItaEwqBiZIQmrptuBS1DCUhyKwYJvS56BuZDcP/6wyj0hO63V9oxtjarCwp5DmDqoghpQA/ "Python 3 – Try It Online")
-9 bytes thanks to Jonathan Allan
[Answer]
# [(Go)Ruby](https://www.ruby-lang.org/), 111 bytes
```
x=0
c=1,1i,-1,-1i
gs.sc(/(\w)(\d*)/){|o,a|x+=c.ro!('URDL'.ix(o)||'NESW'.ix(o)+c.ix(1)).fs*a.toi}
p Mh::hy *x.rc
```
[Try it online!](https://tio.run/##pVZtb9s2EP7uX3Gxg1hyXNnu9smokRZr1g1oMyDFMGBpJlAUbbOlRIGkEjuW89ezIynJjusWHRYY0eneX54jpcpk/dTrwQepDcg5mCUDuiT5gmmkiYF3UqEKZOQLcuZKZqDYohREgeV3OlQQreGP5DOjpgPw@vVCinm8JHoJM9hsO8hL2RwyZpYyjTOuNc8XkA1hQIZwlqAYwKDqnuEN3KBcMzGPnPdbuIWqmmEOhi7ROvbOdJCFN@Nb54Fj5nB2Bt4fQBxrlqdxHBgbKIRNNSBqoataDJBECc9TdBaxOyKCbqEk3VQuBRcmJYZUcPqImT1nwrYbRpQIEZw@hjbu6eOeUydwocKau3VPJjSrGQYuDtKzfQhhCrosmPLqedrx/5v2HZauMbF@fwgZPm1QkgjWCH1ohZLRP72NjoyMdbTQZRKMolG46QbR4CLswjlcswVbFRHTlBQsOD0Lt9uRs82ihWJFoMJIS2VinH8qoeJN@7h36ZKySmhuSsUspwjOppo/sBBevQJ@vBg/WZlr0@KBfgMHdPgDMKBDcN5IbnSLCAMkTxGrmFjuxfGCmcDUzSFcM7giGbtUSqohdMuc59xwIjD5tPUHvQ3ddoeuxUwFk/CgkiW2h6FrkiSK3XFiuMx/YDZWw8/FvcpSxZRgQjMILt5E0cXfIcxmqLIH7yxCvLJV4M3WWYOvSVQWRiLbdX1TPVToGQeau2FjmzMEus/rIbQD2lRGYZm7VcjZykCZC4Z7HDyL7xQxB/vWJtnaOSkMbK0tr@63F/EjuHUSbI2dk6vEutbNrny1LDkXxzF02Fff1hYr1qs/k3DbahUEfKH4HTGtEe7czrx2Xqs0cZYBsdP8DceZWOIeCWqJk76fQFEaDd3ehmyZEHKIgEm2UonUAWfnFnFFNGiydgaN91TG90sufLVjcDSsORMH1aJemZu6F2Nw9DM9p@srf6MUWbcRpUhj1@YabJ7rOJ8lz/cNfyXY918s@U1rm0uL2m736@C/5wbPFNU6YIQuwfCMWROeU1GmDC7zMmPKTm/f9CNCI1@0liPQheCms4tK/IwtN@j39zYxcCXjftiVpbvpvoAjrJupdaXWQ5gaRXJdSM2QngtiDMt31AmSuDwFoWZHWSbmKvHEmSpH3IaRrXFT2Qh@p@yFAl1H2sx7Gyva@lvBHvVC0i/N9lpwtaXZ9dGlsKcgib5rhoezIJQFJLJDbLi4b97BbgcaMPi/ejput70mbiEuSG2FFX4J@nTQt5dRzXMg8da4lkci1MM0Uu0dAk7FXwYuQbvpDBV3ntiBdiNxe@6etoPbfYA8i3Qcn/8RCXUbb/FkcLDQ/3OadpLfG1xb1X7@mFlhz6n62coaflPjs11ZZ4kUe0fhsWj2k8bd24rRu6pFDr2L2s8Pe2DaL5Bjme6W@2k1G3fobDKc8OGLCf54Z2HvmGAUfLoPg0/pIMTPikoOSbU6n9FIyZOg/@f12/f9iK8CGVZV/@ry41/12zm1z0kYRnM9IIgMvu0U8GE5nS7XMFhFij49XU3G4@vrl@PLn8bjtz@P309e/gs "Ruby – Try It Online")
Takes input on STDIN, outputs it on STDOUT.
Basically, this approach uses complex numbers to store the current position, as well as a stack (`c`), containing offsets for each direction. If a direction is in `URDL`, the stack is rotated by the index of the direction in that string; if the direction is in `NESW`, it's rotated by the index of the direction in that string, plus the index of `1` in the stack. This transforms a rotation relative to the current position into a rotation relative to the position of 1. In any event, the top of the stack is multiplied by the number of steps in the direction and added to the current position.
[Answer]
# JavaScript (ES6), ~~148~~ ~~142~~ ~~140~~ ~~138~~ ~~137~~ 134 bytes
```
s=>s.replace(/\d+|./g,_=>~(i='NESW'.search(_))?d=i:~(i='URDL'.search(_))?d+=i:a[d&3]+=+_,a=[0,0,0,0])&&Math.hypot(a[1]-a[3],a[0]-a[2])
```
```
f=
s=>s.replace(/\d+|./g,_=>~(i='NESW'.search(_))?d=i:~(i='URDL'.search(_))?d+=i:a[d&3]+=+_,a=[0,0,0,0])&&Math.hypot(a[1]-a[3],a[0]-a[2])
for(test of [
'N10',
'N10E10',
'N10S10',
'NSEWUDLR10',
'N100RR20E300D40L12',
'ERR10LL20UN30D100',
]) console.log(f(test))
```
-2 bytes: Use `.search()` instead of `.indexOf()` ([@Shaggy](https://codegolf.stackexchange.com/questions/137235/be-my-navigator/137241?noredirect=1#comment335996_137241))
-1 byte: Rearrange program to remove enclosing parentheses ([@Shaggy](https://codegolf.stackexchange.com/questions/137235/be-my-navigator/137241?noredirect=1#comment335998_137241))
-3 bytes: Use `.replace()` instead of `.match().map()` ([@ThePirateBay](https://codegolf.stackexchange.com/questions/137235/be-my-navigator/137241?noredirect=1#comment336036_137241))
[Answer]
# [Perl 5](https://www.perl.org/), 149 + 1 (-p) = 150 bytes
```
while(s/(\D+)(\d+)//){$p=/N/?0:/E/?1:/S/?2:/W/?3:/L/?$p-1:/R/?$p+1:/D/?$p+2:$p for split//,$1;$m[$p%4]+=$2}$_=sqrt(($m[0]-$m[2])**2+($m[1]-$m[3])**2)
```
[Try it online!](https://tio.run/##HcixDoIwFEDRX2GoSUut77XIUkO6wIYMGOMgxEWMJCgVSByMv24tLDc3xzZDFzv3vrddQ0egVcoZra6cAbAPsQkUYFBDBkZqOIBRGk5gIg05GGKFx3Ie7iddRmlig1s/BKPt2glgTeSOPM7ErrY1T4j6kksyvoaJUq9YC19VszBUfAa5QLQAcy4rS4l5rvBYRJhKxF9vp7Z/jk7s4w1KdML@AQ "Perl 5 – Try It Online")
**Explained:**
```
# Each direction is assigned a number:
#
# 0 North
# 1 East
# 2 South
# 3 West
#
# Variables:
# $p present direction
# @m total movement in each direction
# Inside loop:
# $1 a set of direction instructions
# $2 distance
while(s/(\D+)(\d+)//) # Remove and preserve the first direction set and distance
for split//,$1 # Loop through individual letters to set new direction
$p=/N/?0: # North
/E/?1: # South
/S/?2: # East
/W/?3: # West
/L/?$p-1: # Turn left
/R/?$p+1: # Turn right
/D/?$p+2: # Turn around
$p # Do not change direction
$m[$p%4]+=$2 # Add the directional movement to previous movements
$_=sqrt( # Calculate distance
($m[0]-$m[2])**2 # Net North/South movement
+($m[1]-$m[3])**2 # Net East/West movement
)
```
] |
[Question]
[
# Inspiration:
Heavily inspired by [Smallest chess board compression](https://codegolf.stackexchange.com/questions/19397/smallest-chess-board-compression) I decided to make a similar but distinctly different competition.
# tl;dr
Take the file [Chess\_Games.txt](https://pastebin.com/raw/4q0tt98y) and compress it as much as you can so that you can expand it to the original file.
# Objective:
Write an algorithm to encode and decode an entire chess database from start position to end
The encoding must be able to determine for all of the games all the positions:
* The location all the pieces
* Whose turn it is
* Whether the player can castle on each side.
* Whether the player can perform an en-passant, and if so, which of their pawns?
* The previous position
Additionally:
* Each game should also include who won and how it ended (forfeit, draw, checkmate, stalemate, etc...)
# Input/Output:
There should be 2 algorithms Compress/Expand which satisfy the following properties:
* Compress takes in a file of games via a sequence of moves via [chess notation](https://en.wikipedia.org/wiki/Portable_Game_Notation) and output compressed file
* Expand does the opposite, taking in a compressed file and outputting the original file with all the games in the same order
* Correctness: Expand(Compress(file)) = file for all properly formed files
Any game that is not well formed or violates the rules of chess is considered bad. All bad games may be skipped.
It must be able to parse sen notation. Look at [chessgames.com](http://www.chessgames.com) and <https://database.lichess.org/> for some examples.
I have compiled a file of the first 10000 games from ["May 2017"](https://database.lichess.org/lichess_db_standard_rated_2017-05.pgn.bz2) in [Chess\_Games.txt](https://pastebin.com/raw/4q0tt98y)
The file should look like the following:
```
e4 d5 exd5 Nf6 d3 Qxd5 Nc3 Qf5 Be2 Bd7 g4 Qe6 g5 Nd5 Ne4 Bc6 Bg4 Qe5 f4 Qd4 Nf3 Qb6 Qe2 e6 Be3 Qa6 O-O Nd7 c4 Ne7 f5 Bxe4 dxe4 exf5 exf5 O-O-O f6 gxf6 gxf6 Nc6 Nd4 Nxd4 Bxd4 Bc5 Bxc5 Rhg8 Be7 Rde8 b4 Qxf6 Bxf6 Rxe2 h3 h5 Kh1 hxg4 Rg1 Nxf6 Rae1 Rxe1 Rxe1 gxh3 Kh2 Ng4+ Kxh3 Nf2+ Kh2 Ng4+ Kg3 f5 Kf4 Nh6 Re7 Rg4+ Ke5 Kd8 Kf6 Ng8+ Kf7 Nxe7 Kf8 f4 c5 f3 c6 f2 cxb7 Nc6 b8=Q+ Nxb8 Kf7 Kd7 0-1
d3 e6 e3 d5 Nf3 Nf6 Be2 Be7 O-O O-O Nc3 Nbd7 Ne1 c5 f3 e5 e4 d4 Nb1 b6 f4 exf4 Rxf4 Qc7 Rf3 Bd6 g3 Ng4 Rf1 Ndf6 Bxg4 Bxg4 Qd2 Rae8 Qf2 Re5 Bf4 Rh5 Bxd6 Qxd6 Nf3 c4 e5 Rxe5 Nxe5 Qxe5 Nd2 cxd3 cxd3 Be2 Rfe1 Qe3 Qxe3 dxe3 Ne4 Bxd3 Nxf6+ gxf6 Rxe3 Bg6 Rae1 Kg7 h4 h5 R1e2 Bf5 Rg2 Bg4 Re4 Kg6 Rge2 f5 Re5 f6 Re6 Rg8 Re7 Rg7 Re8 1-0
d4 d5 e4 dxe4 c4 Nf6 Qc2 Bf5 Nc3 Qxd4 Be3 Qe5 Nge2 e6 Ng3 Bb4 a3 Bxc3+ bxc3 Nc6 Be2 Na5 O-O Nxc4 Bd4 Qb5 Nxf5 exf5 Bxf6 gxf6 Rab1 Nxa3 Qa2 Qxb1 Rxb1 Nxb1 Qxb1 O-O-O Qb3 b6 Ba6+ Kb8 Qb5 Rhe8 Qc6 1-0
e3 c5 d3 d5 Nf3 Nc6 Be2 Nf6 O-O g6 h3 Bg7 Re1 O-O Nbd2 Re8 Nf1 e5 c3 b6 N3h2 Bb7 Qc2 Qc7 b3 Rac8 Bb2 a5 Rac1 a4 Qb1 axb3 axb3 Ba6 d4 Bxe2 Rxe2 exd4 cxd4 Qb8 dxc5 d4 Ree1 dxe3 Rxe3 Nd5 Rxe8+ Rxe8 Bxg7 Kxg7 Re1 Rxe1 Qxe1 bxc5 Qd1 Nd4 Ne3 Nf4 Neg4 Qxb3 Qe1 Qd5 Ne3 Qe6 Qf1 c4 Nhg4 Nde2+ Kh2 c3 g3 c2 gxf4 c1=Q Qxc1 Nxc1 Ng2 Qe4 Kg3 Nd3 f3 Qe2 Nh4 h5 Nh2 Qe1+ Kg2 Nf2 Nf5+ gxf5 Kg3 Qg1+ Kh4 Nxh3 Kxh5 1-0
e4 d5 exd5 Qxd5 Nc3 Qd8 d4 Bf5 Nf3 e6 Nh4 Bg6 Nxg6 hxg6 Be3 Bd6 Bc4 a6 Qf3 c6 O-O-O Nd7 Ne4 Qc7 Nxd6+ Qxd6 Bf4 Qb4 Bb3 Ngf6 Rhe1 O-O-O Bg3 a5 Qf4 Qb6 Re3 Rh5 Bc4 Rf5 Qd6 Ne8 Qa3 Qa7 Red3 b5 Bxb5 cxb5 Rc3+ Kb7 Qe7 b4 Rc5 Rxc5 dxc5 Qxc5 Qxd8 Ndf6 Qb8+ Ka6 Rd8 Qa7 Rxe8 Nxe8 Qxe8 Qc5 Qa8+ Kb5 Qb8+ Ka4 b3+ Ka3 Qf4 Qc3 Qe5 1-0
e4 d5 exd5 Qxd5 Nf3 Qd8 Nc3 e6 Bc4 Nf6 Bb3 Be7 a3 a6 O-O O-O h3 b6 d3 Bb7 Bg5 Nbd7 Ne4 h6 Bh4 Nxe4 Bxe7 Qxe7 dxe4 Bxe4 Re1 Bb7 Ba2 Nf6 b4 Rfd8 Qc1 Qd6 c4 Qc6 Qc2 Rd7 Rac1 Rad8 c5 bxc5 Qxc5 Qb5 Qxb5 axb5 Ne5 Rd2 Bb3 Rb2 Bd1 Rdd2 Re2 Rxe2 Bxe2 Rxe2 Nf3 Ra2 Rxc7 Bd5 Rc8+ Kh7 Ne5 Rxa3 Rf8 Ra1+ Kh2 h5 Rxf7 Kh6 Rf8 Kg5 g3 Kf5 Nd7 Ra2 Nxf6 gxf6 Rg8 Rxf2+ Kg1 Rg2+ Kf1 Rh2 g4+ hxg4 hxg4+ Ke5 Re8 Rh1+ Kf2 Rh2+ Kg3 Rg2+ Kh4 Rf2 Kg3 Rf4 g5 Re4 gxf6 Kxf6 Rf8+ Ke5 Rh8 Re3+ Kf2 Re4 Rh5+ Kd4 Rh6 Rf4+ Kg3 Re4 Rh8 Re3+ 0-1
...
```
# Scoring:
In order to make things objective, the winner is the algorithm that can compress the files at <https://database.lichess.org/> as small as possible. The target database is the ["May 2017"](https://database.lichess.org/lichess_db_standard_rated_2017-05.pgn.bz2). The winner is whoever has the smallest file that expands properly.
The file to use is [Chess\_Games.txt](https://pastebin.com/raw/4q0tt98y) which is the first 10000 games from the ["May 2017"](https://database.lichess.org/lichess_db_standard_rated_2017-05.pgn.bz2) database at <https://database.lichess.org/> with all of the header information removed. This file will be the benchmark to use. It should be 2,789,897 bytes with a SHA-256 hash of `56b6d2fffc7644bcd126becd03d859a3cf6880fa01a47fa08d4d6a823a4866bc` (Pastebin might remove the last newline after game 10000)
# Naive Solution:
Using generic compression algorithms:
* zip: 647,772 bytes (76.841%)
* 7z: 652,813 bytes (76.661%)
* bz2: 722,158 bytes (74.182%)
* xz: 784,980 bytes (71.936%)
* rar: 853,482 bytes (69.487%)
* gz: 923,474 bytes (66.985%)
[Answer]
# Python, score = 418581 bytes
This uses a bijective variant of [asymmetric numeral systems](https://en.wikipedia.org/wiki/Asymmetric_Numeral_Systems). Because it’s bijective, you can not only compress any valid list of chess games into a file and expand it back to the same list—you can also **expand any file** into a valid list of chess games and compress it back to the same file! Perfect for hiding your porn collection.
Requires [python-chess](https://pypi.python.org/pypi/python-chess). Run with `python script.py compress` or `python script.py expand`, both of which will read from standard input and write to standard output.
```
import chess
import sys
RESULTS = ['1-0\n', '1/2-1/2\n', '0-1\n', '*\n']
BITS = 24
def get_moves(board):
if board.is_insufficient_material() or not board.legal_moves:
return [board.result() + '\n']
else:
return RESULTS + sorted(
board.legal_moves,
key=lambda move: (move.from_square, move.to_square, move.promotion))
def read_bijective():
buf = bytearray(getattr(sys.stdin, 'buffer', sys.stdin).read())
carry = 0
for i in range(len(buf)):
carry += buf[i] + 1
buf[i] = carry & 0xff
carry >>= 8
if carry:
buf.append(carry)
return buf
def write_bijective(buf):
carry = 0
for i in range(len(buf)):
carry += buf[i] - 1
buf[i] = carry & 0xff
carry >>= 8
while carry:
carry = (carry << 8) + buf.pop() + 1
getattr(sys.stdout, 'buffer', sys.stdout).write(buf)
def add_carry(buf, carry):
for i in range(len(buf)):
if carry == 0:
break
carry += buf[i]
buf[i] = carry & 0xff
carry >>= 8
return carry
def do_compress():
board = chess.Board()
state = 0
buf = bytearray()
games = []
for sans in sys.stdin:
game = []
for san in sans.split(' '):
move = san if san in RESULTS else board.parse_san(san)
moves = get_moves(board)
game.append((len(moves), moves.index(move)))
if move in RESULTS:
board.reset()
else:
board.push(move)
games.append(game)
for game in reversed(games):
for (n, i) in reversed(game):
q = ((1 << BITS) - 1 - i) // n + 1
while state >= q << 8:
buf.append(state & 0xff)
state >>= 8
hi, j = divmod(state, q)
lo = n * j + i
state = hi << BITS | lo
state += add_carry(buf, 1)
while state:
buf.append(state & 0xff)
state >>= 8
write_bijective(buf)
def do_expand():
board = chess.Board()
state = 0
buf = read_bijective()
while True:
while buf and state < 1 << BITS:
state = state << 8 | buf.pop()
if state == 0:
break
state += add_carry(buf, -1)
while True:
moves = get_moves(board)
while buf and state < 1 << BITS:
state = state << 8 | buf.pop()
n = len(moves)
hi, lo = divmod(state, 1 << BITS)
j, i = divmod(lo, n)
q = ((1 << BITS) - 1 - i) // n + 1
state = j + q * hi
move = moves[i]
if move in RESULTS:
sys.stdout.write(move)
board.reset()
break
else:
sys.stdout.write(board.san(move).rstrip('+#') + ' ')
board.push(move)
if __name__ == '__main__':
{'compress': do_compress, 'expand': do_expand}[sys.argv[1]]()
```
[Answer]
# Python, score = 426508 bytes
### Compression Function:
(
m+1
)
⋅
log2
(
b+1
)
**m** is number of moves and **b** is branching factor
# Attempt 1:
I answered the question at [Smallest chess board compression](https://codegolf.stackexchange.com/a/132695/72259) so I'm trying to fix it up to post here.
Naively I thought that I can encode each move in 12 bits, 4 triplets of the form (start x, start y, end x, end y) where each is 3 bits.
We would assume the starting position and move pieces from there with white going first. The board is arranged such that
(
0
,
0
)
is white's lower left corner.
For example the game:
```
e4 e5
Nf3 f6
Nxe5 fxe5
... ...
```
Would be encoded as:
```
100001 100010 100110 100100
110000 101010 101110 101101
101010 100100 101101 100100
...
```
This leads to an encoding of 12 *m* bits where *m* is the number of moves made.
# Attempt 2:
I realized that each move in the previous attempt encodes many illegal moves. So I decided to only encode legal moves. We enumerate possible moves as follows, number each square such that
(
0
,
0
)
→
0
,
(
1
,
0
)
→
1
,
(
x
,
y
)
→
x
+
8
y
. Iterate through the tiles and check if a piece is there and if it can move. If so add the positions it can go to to a list. Choose the list index that is the move you want to make. Add that number to the running total of moves weighted by 1 plus the number of possible moves.
Example as above:
From the starting position the first piece that can move is the knight on square 1, it can move to square 16 or 18, so add those to the list `[(1,16),(1,18)]`. Next is the knight on square 6, add it's moves. Overall we get:
`[(1,16),(1,18),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]`
Since we want the move
(
12
,
28
)
, we encode this as 13 in base 20 since there are 20 possible moves.
So now we get the game number
g0
=
13
Next we do the same for black except we number the tiles in reverse (to make it easier, not required) to get the list of moves:
`[(1,16),(1,18),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]`
Since we want the move
(
11
,
27
)
, we encode this as 11 in base 20 since there are 20 possible moves.
So now we get the game number
g1
=
(
11
⋅
20
)
+
13
=
233
Next we get the following list of moves for white:
`[(1,16),(1,18),(3,12),(3,21),(3,30),(3,39),(4,12),(5,12),(5,19),(5,26),(5,33),(5,40),(6,12),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27)(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]`
Since we want the move
(
6
,
21
)
, we encode this as 13 in base 29 since there are 29 possible moves.
So now we get the game number
g2
=
(
(
13
⋅
20
)
+
11
)
20
+
13
=
5433
Next we get the following list of moves for black:
`[(1,11),(1,16),(1,18),(2,11),(2,20),(2,29),(2,38),(2,47),(3,11),(4,11),(4,18),(4,25),(4,32),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]`
Since we want the move
(
10
,
18
)
, we encode this as 19 in base 29 since there are 29 possible moves.
So now we get the game number
g3
=
(
(
(
19
⋅
29
+
13
)
20
)
+
11
)
20
+
13
=
225833
And continue this process for all the remaining moves. You can think of *g* as the function
g
(
x
,
y
,
z
)
=
x
y
+
z
. Thus
g0
=
g
(
1
,
1
,
13
)
,
g1
=
g
(
g
(
1
,
1
,
11
)
,
20
,
13
)
,
g2
=
g
(
g
(
g
(
1
,
1
,
13
)
,
20
,
11
)
,
20
,
13
)
,
g3
=
g
(
g
(
g
(
g
(
1
,
1
,
19
)
,
29
,
13
)
,
20
,
11
)
,
20
,
13
)
To decode a game number *g*0, we start at the initial position and enumerate all possible moves. Then we compute *g*1 = *g*0 // *l*, *m*0 = *g*0 % *l*, where *l* is the number of possible moves, '//' is the integer division operator and '%' is the modulus operator. It should hold that *g*0 = *g*1 + *m*0. Next we make the move *m*0 and repeat.
From the example above if *g*0 = 225833 then *g*1 = 225833 // 20 = 11291 and *m*0 = 225833 % 20= 13. Next *g*2 = 11291 // 20 = 564 and *m*1 = 11291 % 20 = 11. Then *g*3 = 11291 // 20 = 564 and *m*2 = 11291 % 20 = 11. Therefore *g*4 = 564 // 29 = 19 and\_m\_3 = 564 % 29 = 13. Finally *g*5= 19 // 29 = 0 and *m*4 = 19 % 29 = 19.
# So how many bits are used to encode a game this way?
For simplicity, let's say there are always 35 moves each turn (<https://en.wikipedia.org/wiki/Branching_factor>) and for the worst case scenario we always pick the biggest one, 34. The number we will get is
34
⋅
35m
+
34
⋅
35m-1
+
34
⋅
35m-2
+
⋯
+
34
⋅
35
+
34
=
35m+1
−
1
where \_m is the number of moves. To encode
35m+1
−
1
we need about
log2
(
35m+1
)
bits which is about
(
m
+
1
)
⋅
log2
(
35
)
=
5.129
⋅
(
m
+
1
)
On average *m* = 80 (40 moves per player) so this would take 416 bits to encode. If we were recording many games we would need a universal encoding since we don't know how many bits each number will need
Worst case when *m* = 11741 so this would take 60229 bits to encode.
# Additional Notes:
Note that *g* = 0 denotes a valid game, the one where the piece on the lowest square moves to the lowest square it can.
If you want to refer to a specific position in the game you may need to encode the index. This can be added either manually e.g concatenate the index to the game, or add an additional "end" move as the last possible move each turn. This can now account for players conceding, or 2 in a row to denote the players agreed to a draw. This is only necessary if the game did not end in a checkmate or stalemate based on the position, in this case it is implied. In this case it brings the number of bits needed on average to 419 and in the worst case 60706.
A way to handle forks in a what-if scenario is to encode the game up to the fork and then encode each branch starting at the forked position instead of the initial position.
# Implementation:
Take a look at my github repo for the code:
<https://github.com/edggy/ChessCompress>
] |
[Question]
[
[Choi Hong Hi](https://en.wikipedia.org/wiki/Choi_Hong_Hi) died on the 15th June 2002 at the honorable age of 83. He founded [Taekwondo](https://en.wikipedia.org/wiki/Taekwondo).
15 years after his death, I would like to be a Taekwondo master. This is my time to shine !
# Task
Given a string you should output a *Taekwondo* version.
# Rules
* You will receive a non-empty string/sentence by any valid input
* You must replace each titles (case insensitive) by the [revised romanization](https://en.wikipedia.org/wiki/Revised_Romanization_of_Korean) equivalent.
* You must add `, *side kick*` at the end of the sentence because I like to do side kicks.
* You must output this changed sentence as a string.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") you should aim to minimize the byte count of your answer
# Examples
```
"I am a Student and I do Taekwondo twice a week"
=> "I am a Geup and I do Taekwondo twice a week, *side kick*"
"I am a Teacher willing to be a President"
=> "I am a Gyosa nim willing to be a Gwanjang nim, *side kick*"
```
# List of titles
```
English => Revised Romanization
============================================
President => Gwanjang nim
Founder => Gwanjang nim
Master instructor => Sabeom nim
Teacher => Gyosa nim
Black Belt => Dan
Student => Geup
Color Belt => Geup
Master level => Godanja
```
[Answer]
# [PHP](https://php.net/), 241 bytes
```
<?=preg_replace(["#\b(President|Founder)\b#i","#\bMaster instructor\b#i","#\bTeacher\b#i","#\bBlack Belt\b#i","#\b(Studen|Color Bel)t\b#i","#\bMaster level\b#i"],[Gwanjang.$n=" nim",Sabeom.$n,Gyosa.$n,Dan,Geup,Godanja],"$argn, *side-kick*");
```
[Try it online!](https://tio.run/##ZZDNboMwEITvPIXl5ACR0xegaaSkKeLQHynckihaYAUuYFuLKaoU9a17pnZ6SKXedmdWn2bW1Ga6X5vaBEik6UxoNFmpqvBrd355zdLtLoqDOVClVjxl0DFgezuUqCwDVbKUlZplgM2olZvsKAt0JyNiw@Ng/eDgK0NYeXALBYYHPjvm4RthLz3k8qQHVSJFx3wmufDmM/QWiUnVWxoKq@lmZQhFjX@EjWM2bIOtvWnhb77LVreavBfZf/AWP7C9qidxSEZQ76Cqu7nryJTsuNhDjrpzgkg@dQ9@eAS34GBEokt/fxL8@hbBFr7KspFFs@BRPE3fSi8LH/QH "PHP – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 154 bytes
```
i(`president|founder
Gwanjang_
master instructor
Sabeom_
teacher
Gyosa_
black belt
Dan
student|color belt
Geup
master level
Godanja
_
nim
$
, *side kick*
```
[Try it online!](https://tio.run/##TY5BboMwEEX3cwovqihCvURLGlqJQgRkTQczTVyMB9kmVaXendpEUbp78/X151nyyuCyqO3HZMmpnoz//eTZ9GQh@0bzhebUwojOkxXKOG9n6dlCjR3x2IInlOfY/WGHLXQa5SA60h52aMD5eV2UrNle44zm6ban6UIaMu7jH2hBGDXCAzyKJJqIQckhWZbDTUxsxPSP9@Wx2L1UgcanugnwVtRNdUyb0oYsiKWvFOnuFI56NWoCpZxzJZ4pj/H7VSiPQn8 "Retina – Try It Online")
[Answer]
# C#, 262 bytes
```
s=>{for(int i=0;i<8;)s=s.ToUpper().Replace("PRESIDENT|FOUNDER|MASTER INSTRUCTOR|TEACHER|BLACK BELT|MASTER LEVEL|STUDENT|COLOR BELT".Split('|')[i],(i<2?"GWANJANG":i>3?"GEUP":"SABEOM|GYOSA|DAN|GODANJA".Split('|')[i-2])+(i++<4?" NIM":""));return s+", *SIDE KICK*";}
```
Full/Formatted version:
```
class Program
{
static void Main(string[] args)
{
System.Func<string, string> f = s =>
{
for (int i = 0; i < 8;)
s = s.ToUpper().Replace("PRESIDENT|FOUNDER|MASTER INSTRUCTOR|TEACHER|BLACK BELT|MASTER LEVEL|STUDENT|COLOR BELT".Split('|')[i],
(i < 2 ? "GWANJANG"
: i > 3 ? "GEUP"
: "SABEOM|GYOSA|DAN|GODANJA".Split('|')[i-2])
+ (i++ < 4 ? " NIM" : ""));
return s + ", *SIDE KICK*";
};
System.Console.WriteLine(f("I am a Student and I do Taekwondo twice a week"));
System.Console.WriteLine(f("I am a Teacher willing to be a President"));
System.Console.ReadLine();
}
}
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 163 bytes
```
i`President|Founder
Gwanjang¶
i`Master instructor
Sabeom¶
i`Teacher
Gyosa¶
i`Black Belt
Dan
i`Student|Color Belt
Geup
i`Master level
Godanja
¶
nim
$
, *side kick*
```
[Try it online!](https://tio.run/##RY9NCsJADIX3c4osXBVPUcXiQhDqAZq2ocZOMzKTsQieywN4sbE/oNvvke@9eFIWTImrs6fALYm@Di5KS94UI8oNpfu8DVcnDEoeWIL62KjzpsSa3LCEF8LmOl88XcCF5BabHnKyavYoEyg1LvKds86vQUHx/jdbepA1hWvnUjNJQHgwG7OFbN4FPTd9ltIRcAAEXRthZGtZOlAHNU3898UX "Retina – Try It Online")
[Answer]
# tcl, 212
```
puts "[string map -nocase {President Gwanjang\ nim Founder Gwanjang\ nim Master\ instructor Sabeom\ nim Teacher Gyosa\ nim Black\ Belt Dan Student Geup Color\ Belt Geup Master\ level Godanja} $argv], *side kick*"
```
## [demo](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMNWw0Uk9uV1JpZkk)
[Answer]
# [Python 3](https://docs.python.org/3/), 281 bytes
```
import re
x=input();a="Gwanjang";b=" nim";c="Geup";d="Master";e=" Belt"
for i in range(8):x=re.sub("(?i)"+["President","Founder",d+" instructor","Teacher","Black"+e,"Student","Color"+e,d+" level"][i],[a+b,a+b,"Sabeom"+b,"Gyosa"+b,"Dan",c,c,"Godanja"][i],x)
print(x+", *side kick*")
```
[Try it online!](https://tio.run/##PY9BT8MwDIXv/RXWO7Vr4MIFUVWTBmLigIQ0btUOaWq2sDSp0pR1P5xzSWBCliX72Z/lN1zC0dm7ZdH94Hwgz9lcaztMIS8qWWN7lvZT2gOqtgZZ3aNSUeVpQNXVeJVjYI@K43DDJiD7cJ40aUs@UpzfFw9z7fl2nNoc@VoXKBu8eR51xzZA4NlNtosnRFciYmPwkwou9nhnqY5pgo2R6oSSBXZhunKPzsStqCXO8Bcb7Bu9F40sW5ESO9my65HK7cWN8rd6khZCxcDWdcnaHzUX2eC1DflcQtAqfUcnrU4rFMvyQrInSdd/6KyN0fZAwVHLUf93823djUo7Pw "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), 251 bytes
```
a=>a.replace(RegExp(b='president|founder|master instructor|teacher|black belt|student|color belt|master level','gi'),c=>((d='Gwanjang nim|')+d+'Sabeom nim|Gyosa nim|Dan|Geup|Geup|Godanja').split`|`[b.split`|`.indexOf(c.toLowerCase())])+', *side kick*'
```
[Try it online!](https://tio.run/##dZDNTsMwEITvfQrfbLclb5BeAEWVkEC0N4TUjb0JbhxvZDtNkfzuwf2BG5fVaOxvtTNHOEFQ3gzxwZHGeW7KBZQbKDwOFhSKd2yfz4OoSz54DEaji6mh0Wn0qYcQ0TPjQvSjiuRTRFBf@aXObMdqtDGFOF4hRZb8zbpzFk9o@Zq3hsu1KjdC6JJXE7gjuJY50ycuV3rFd1Aj9Vej@qYAV/UELlU4DvdB@oJxWYTBmnhIh4/6TxYmX3t@bYQqIr3QhP4RAgopP@WKr9nykop1RnVLvlgocoEsFpZa0Qi@ZdAzYLtbCAZOsy3TxPaA3UQuqzgZhfnLhNhxKf9ZsL8VwyZjrcnpIuUqsv/2W2pG5/kH)
This is not as compact as it could be since JavaScript is so verbose, but it's a great question. I recognized most of these terms as I am a 2nd Dan Black Belt in Taekwondo.
**Explanaion**
```
a=>
a.replace( // Replace on input string
RegExp( // Regex matching English phrases
b='president|founder|master instructor|teacher|black belt|student|color belt|master level',
'gi' // Match all, case insensitive
),
c=>
((d='Gwanjang nim|')+d+ // Duplicate string portion
'Sabeom nim|Gyosa nim|Dan|Geup|Geup|Godanja') // Add remaining phrases
.split`|` // Split into array by pipe
[b.split`|`.indexOf(c.toLowerCase())]) // Access Korean phrase by corresponding index of matched English phrase
+', *side kick*' // I like to do side kicks
```
[Answer]
# JavaScript (ES6), 233 bytes
```
s=>(btoa`>·¬×§·mÁ©ãjx4)µ§uêö§©àÒx¦ÔƬµêô{-®ç-¢½i·¨IâTÞiÈ^¯a²¢Æ´)µV@^Ýj}R¶ç^Ýzêu
h¯@^Ýzêu1«-z½%z÷¥ØjjxÚ`.split(0).join` `.split`1`.map(d=>([a,b]=d.split(/2+/),s=s.replace(RegExp(a,'gi'),b))),s+', *side kick*"')
```
```
f=
s=>(btoa`>·¬‰×§·m†Á©ãjx4ž)µ‹§uêö§©àÒx¦ÔƬµêôŠ{-®ç-¢½’i·¨›Iâ›TÞiÈ^¯a²¢Æ´ž)µVœ“@^–݃j}R¶ç^žÝ†zêu
‰h¯@^–݆zêu1«-z½%z÷¥Øj
jx√ö`.split(0).join` `.split`1`.map(d=>([a,b]=d.split(/2+/),s=s.replace(RegExp(a,'gi'),b))),s+', *side kick*"')
console.log(f('I am a Teacher willing to be a President'))
```
---
# JavaScript (ES6), 243 bytes
```
s=>(`President${A=':Gwanjang nim|'}Founder${A}Master instructor:Sabeom nim|Teacher:Gyosa nim|Black Belt:Dan|Student:Geup|Color Belt:Geup|Master level:Godanja`.split`|`.map(r=>([a,b]=r.split`:`,s=s.replace(RegExp(a,'gi'),b))),s+', *side kick*')
```
```
f=
s=>(`President${A=':Gwanjang nim|'}Founder${A}Master instructor:Sabeom nim|Teacher:Gyosa nim|Black Belt:Dan|Student:Geup|Color Belt:Geup|Master level:Godanja`.split`|`.map(r=>([a,b]=r.split`:`,s=s.replace(RegExp(a,'gi'),b))),s+', *side kick*')
console.log(f('I am a Teacher willing to be a President'))
```
] |
[Question]
[
This challenge was greatly inspired by [this Stack Overflow post](https://stackoverflow.com/questions/43831137/how-to-determine-the-most-busy-period-of-time).
# Challenge
Given a bunch of clients in terms of when they enter a room and when they exit it, determine the period(s) of time when the room has a maximum number of people. The time resolution should be to the minute.
For example, if there are three clients `8 - 10`, `9 - 11`, `10 - 12`, then the correct answer would be `9 - 11`; during this time period, there are two clients in the room, which is the largest possible.
# Input
Input will be a list of pairs in some form. That can be either a list of 2-tuples, an even-length list with elements interleaved, etc, any reasonable input format. The times can be given in any reasonable format, in either 12- or 24- hour time. You may also input time as the number of minutes past midnight.
# Output
Output should be a list of pairs in some form, but the output is stricter. The output cannot be a flat list, it must be a list of 2-tuples or a list of lists, etc. The times can be output in any reasonable format, in either 12- or 24- hour time. You may also output time as the number of minutes past midnight.
# Examples
```
input
output
INPUT
08:00 - 10:00
09:00 - 11:00
10:00 - 12:00
OUTPUT
09:00 - 11:00
INPUT
08:20 - 09:20
09:00 - 09:10
08:00 - 09:30
08:50 - 10:40
OUTPUT
09:00 - 09:10
INPUT
08:00 - 10:00
09:00 - 10:00
09:30 - 11:00
OUTPUT
09:30 - 10:00 # The output is not always in the input list
INPUT
00:00 - 02:00
01:00 - 03:00
04:00 - 06:00
05:00 - 07:00
OUTPUT # This is the expected output for when there are multiple time ranges with the same "business".
01:00 - 02:00
05:00 - 06:00
```
You may assume that the second time in a pair will always be after the first time. Time ranges will not run over midnight.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes
```
⟦₂ᵐkᵐcoḅlᵒlᵍthᵐ~c{~k~⟦₂}ᵐ
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9o/rJHTU0Pt07IBuLk/Ic7WnMebp0ExL0lGUCRuuTquuw6iKJaIP///@hoAx0jA4NYnWhDAwMdYzDLBMgyA7NMgSxzICv2fxQA "Brachylog – TIO Nexus")
There's an obvious structure to this answer, which becomes even more obvious if you write it like this:
```
{⟦₂k}ᵐc oḅ lᵒlᵍ thᵐ ~c{~k~⟦₂}ᵐ
```
Unfortunately, Brachylog's evaluation order makes it so that the program goes into an infinite loop if you try to take advantage of the structure in question. Still, it's certainly possible to imagine a Brachylog-like language in which this is much shorter.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ ~~21~~ 20 bytes
```
r/€Ṗ€F©®ċ$ÐṀQœ^‘$Ṣs2
```
[Try it online!](https://tio.run/nexus/jelly#@1@k/6hpzcOd04Ck26GVh9Yd6VY5POHhzobAo5PjHjXMUHm4c1Gx0f/D7UD5o5Me7pwBpCP//4/m4oyONrEw0DEzMIjViTY1AbLMQCwgX8fcyCA2VgekwkBHwQikQCHaECiuYAxhm4DYZhC2KYhtDmTHcsUCAA "Jelly – TIO Nexus")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 58 bytes
```
⟦₂ᵐkᵐcoḅBlᵐ⌉;B↔z{hl~t?}ˢhᵐhᵐ{∋+₁.¬∈?∧|∋.-₁¬∈?∧}ᶠo~c.{l2}ᵐ∧
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9o/rJHTU0Pt07IBuLk/Ic7Wp1ygKxHPZ3WTo/aplRVZ@TUldjXnl6UARQF4epHHd3aj5oa9Q6tedTRYf@oY3kNUERPFygEF6l9uG1Bfl2yXnWOUS3IsI7l//9HRxvoKBgZGMTqKEQbGgDZxhC2CYhtBmGbgtjmQHbs/ygA "Brachylog – TIO Nexus")
This has to be the longest Brachylog answer ever...
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~33~~ 24 bytes
```
JsrMQcSs-M_BhMBS{.M/JZJ2
```
[Try it online!](http://pyth.herokuapp.com/?code=JsrMQcSs-M_BhMBS%7B.M%2FJZJ2&test_suite=1&test_suite_input=%5B%5B480%2C600%5D%2C%5B540%2C660%5D%2C%5B600%2C720%5D%5D%0A%5B%5B0%2C+200%5D%2C+%5B100%2C+300%5D%2C+%5B400%2C+600%5D%2C+%5B500%2C+700%5D%5D&debug=0)
[Answer]
# Mathematica, 104 bytes
```
Reduce[#==#~MaxValue~x,x]&@PiecewiseExpand@Tr[Piecewise@{{1,#<=x<#2}}&@@@#]/.{Or->List,a_<=x<b_->{a,b}}&
```
Of course, this assumes that several high-power Mathematica built-ins are correct...
] |
[Question]
[
[AWG (American Wire Gauge)](https://en.wikipedia.org/wiki/American_wire_gauge) is a common way of specifying wire sizes. Your task in this challenge is to convert from a given gauge to the diameter of the wire in inches.
The size in inches for the gauges from `4/0` to `40` are shown in the table below:
## Gauge to inches table
```
| AWG | Diameter (Inches) |
|-----|-------------------|
| 4/0 | 0.46 |
| 3/0 | 0.4096 |
| 2/0 | 0.3648 |
| 1/0 | 0.3249 |
| 1 | 0.2893 |
| 2 | 0.2576 |
| 3 | 0.2294 |
| 4 | 0.2043 |
| 5 | 0.1819 |
| 6 | 0.162 |
| 7 | 0.1443 |
| 8 | 0.1285 |
| 9 | 0.1144 |
| 10 | 0.1019 |
| 11 | 0.0907 |
| 12 | 0.0808 |
| 13 | 0.072 |
| 14 | 0.0641 |
| 15 | 0.0571 |
| 16 | 0.0508 |
| 17 | 0.0453 |
| 18 | 0.0403 |
| 19 | 0.0359 |
| 20 | 0.032 |
| 21 | 0.0285 |
| 22 | 0.0253 |
| 23 | 0.0226 |
| 24 | 0.0201 |
| 25 | 0.0179 |
| 26 | 0.0159 |
| 27 | 0.0142 |
| 28 | 0.0126 |
| 29 | 0.0113 |
| 30 | 0.01 |
| 31 | 0.00893 |
| 32 | 0.00795 |
| 33 | 0.00708 |
| 34 | 0.0063 |
| 35 | 0.00561 |
| 36 | 0.005 |
| 37 | 0.00445 |
| 38 | 0.00397 |
| 39 | 0.00353 |
| 40 | 0.00314 |
```
## Clarifications
* For gauges less than `0`, you can take the input as either `3/0` or `000`
* You only have to support from the given `4/0` to `40`
* The [Wikipedia page](https://en.wikipedia.org/wiki/American_wire_gauge) has some helpful formulas you can try to use if you don't want to hardcode everything
* Output your answers to at least 3 sig-figs
* This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
[Answer]
## JavaScript (ES7), 36 bytes
```
s=>.46/92**(((+s||1-s.length)+3)/39)
```
Takes input in "0000" format.
[Answer]
# [J](http://jsoftware.com/), ~~33~~ 26 bytes
```
0.46%92^39%~*@".{3+".,~1-#
```
[Try it online!](https://tio.run/nexus/j#@5@mYGulYKBnYqZqaRRnbKlap@WgpFdtrK2kp1NnqKvMxZWanJGvoGGdpqlmp6BuAATq1uowEkQAsSEQGwGxsSWQMDFQ//8fAA)
Takes input as a string with gauges less than zero as a string of zeroes. Finds the index of that string and divides 0.46 (the diameter of `0000`) by the 39th root of 92 (the ratio between gauges) that many times.
## Explanation
```
0.46%92^39%~*@".{3+".,~1-# Input: string S
# Length of S
1- Subtract it from 1
".,~ Eval S and append it, forms [1-len(S), eval(S)]
3+ Add 3 to each
*@". Sign of the eval
{ Use that to index into the previous list
39%~ Divide by 39
92^ Raise 92 to that power
0.46% Divide 0.46 by that and return
```
[Answer]
# Bash + GNU utils, 47
```
bc -l<<<"e(l(92)*(36-(${1/\/0/*-1+1}))/39)/200"
```
Straightforward arithmetic expression evaluation using `bc`. Input given as a command-line parameter.
Gauges less than 0 are given as `n/0`. The bash parameter expansion `${1/\/0/*-1+1}` converts these to -ve numbers and adds one which makes the arithmetic come out right.
`bc -l` gives 20 decimal places by default. `bc`'s exponentiation operator `^` can only handle integer exponents so `ln(y*e(x))` is used instead.
[Try it online](https://tio.run/nexus/bash#DcFBCoMwEAXQfU/xEReJMpkZDQUxR@mqNZWCGNDuQs4efe@bDqz47cjeOS0syOqclzJjSQ/czvgHEdq1vj@gLYTQRLOZabCdGZ9k2qz8YuGOtNdiLY@T5UGkqUvaY70A).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
VoLC$+3÷39µ92*.46÷
```
**[Try it online!](https://tio.run/nexus/jelly#@x@W7@Osom18eLux5aGtlkZaeiZmh7f///9f3cRAHQA "Jelly – TIO Nexus")**
A monadic link taking a tring and returning a number. The `'0...0'` cases produce some extra output, but the return value is correct, as may be seen by ignoring the first two lines [here](https://tio.run/nexus/jelly#Nc4xCgIxEEbhywgBFdmZiaupba0FEc/gGbTxEJ5AEDsJ2yYncS8S5y0Y9k/1vrDtcNnvZgur2VL5JJ2vYl9zq/fx9irP7/AYr9m/8j62dgqdn7AM/5vLJz71mS/61r7et/FtfYlmCimFVGiFWKiFXOgFIAhF6PQ2QhGKUIQiFKEIRRjCEDb9DsIQhjCEIQxhiNiF8w8).
### How?
```
VoLC$+3÷39µ92*.46÷ - Main link: guageString
V - evaluate as Jelly code (a string of zeros evaluates to 0)
$ - last two links as a monad
L - length
C - complement (1-length)
o - Or (integer value for > 0, 1-lenght for strings of zeros)
+3 - add 3
÷39 - divide by 39
µ - monadic chain separation (call the result p)
.46÷ - 0.46 divided by
92* - 92 raised to the power of p
```
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
lambda s:.46/92**((3+(int(s)or 1-len(s)))/39)
```
**[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQbKVnYqZvaaSlpaFhrK2RmVeiUayZX6RgqJuTmgdkamrqG1tq/k8DChUrZOYpRKsbAIG6jjqMVI9V0FaILi4p0sjUVAApywQpK0rMS0/VMDHUjLXi4iwoAhmrXm1gZVKrrgdUk5sIskVHIQ1kAUxe8z8A)**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ 23 bytes
```
8Ø50/92ID1‹ig(>}3+39/m/
```
[Try it online!](https://tio.run/nexus/05ab1e#@29xeIapgb6lkaeL4aOGnZnpGna1xtrGlvq5@v//GxgYAAA "05AB1E – TIO Nexus")
**Explanation**
```
8Ø # push the 8th prime (0-indexed) = 23
50/ # divide by 50 = 0.46
92 # push 92
I # push input
D1‹i } # if input < 1
g(> # calculate -len(input)+1
3+ # add 3
39/ # divide by 39
m # raise 92 to this power
/ # divide 0.46 by this
```
[Answer]
# Excel, ~~53~~ 49 bytes
```
=92^((36-IF(ISNUMBER(A1),A1,49-CODE(A1)))/39)/200
```
Takes gauges less than Zero as String (1/0, 2/0 etc.)
[Answer]
# [Perl 5](https://www.perl.org/), 39 + 1 (-p) = 40 bytes
```
s/(.).0/1-$1/e;$_=.005*92**((36-$_)/39)
```
[Try it online!](https://tio.run/##BcFLCoAgEADQy7hQYX7JBBIdoTO4chFEDtn5m96z/lzqPiliQiaBINS30HZk1lyXnGMsK4SWqNTkLsTfsPcc93Q4FFnYwX4 "Perl 5 – Try It Online")
Takes the bigger gauges as "n/0".
] |
[Question]
[
I have a counter. It's a small device that looks like this:
[](https://i.stack.imgur.com/ZwQRk.jpg)
The display goes from `0000` to `9999`. It has a little push-button at the top that increases the count by 1, and a little knob at the right whose purpose is to reset the counter back to 0.
Now, the thing about the little knob is that if you turn it backwards, you can make it increase any digit that you want once you turn it forwards again. So if I push the counter button 10 times so that the counter shows `0010`, I can then turn the knob backwards until i hear a tiny click, then turn it forwards again and make it go straight to `0090`.
But, the knob will always increase all occurrences of the same digit by 1 every time it pushes numbers forward. So if the counter shows `6060`, you can only make it increase to `7070`, not to `6070` or `7060`. Also, the knob will roll `9`s over to `0` without carrying, so `0990` will advance to `0000` instead of `1000` or `1100`.
---
I want to know the most efficient way to set the counter to a certain number. Your task is to write a program or function that will determine the shortest sequence of button pushes and knob advancements required to do so.
Your program will take as input a 4-digit number from `0000` to `9999`, and return a series of steps in the following format:
```
> 0001
C
> 0093
C12345678C12345678CCC
> 1000
C12345678C12345678C12345678C12345678C12345678C12345678C12345678C
> 9999
012345678
```
Where `C` stands for "push the counter button" and any digit `D` from 0 to 9 stands for "use the knob to advance all occurrences of `D` by 1".
Your program must produce a valid sequence of steps for all possible four-digit combinations, and will be scored by the total number of steps required for all 10,000 cases. In the case of a tie (most likely when the optimal algorithm is found), the shorter code will win.
[Answer]
# Lua, 327763 steps (optimum, 276 bytes)
Golfed version:
```
a={[0]=""}t=tonumber for i=0,52 do A={}for k,v in pairs(a)do A[k]=v L=("%04d"):format(k)for i=1,4 do c=L:sub(i,i)d=L:gsub(c,(t(c)+1)%10)e=a[t(d)]A[d]=(not e or #e>#v)and v..c or e end b=k+1 if k<9999then e=a[b]A[b]=(not e or #e>#v)and v.."C"or e end end a=A endprint(a[(...)])
```
Improved version of the examples in question (only `1000` is improved):
```
0001:C
0093:CCCCCCCCCC12345678CCC
1000:0CCCCCCCCCCC2345678C23456789
(0000>1111>1122>1199>1200>1000)
9999:012345678
```
Ungolfed version:
```
a = {[0]=""}
for i=0,52 do
A = {}
for k,v in pairs(a) do
A[k] = v
L=("%04d"):format(k)
for i=1,4 do
c=L:sub(i,i)
d=L:gsub(c,(tonumber(c)+1)%10)
e=a[tonumber(d)]
A[d] = (not e or #e > #v) and v..c or e
end
b=k+1
if k < 9999 then
e=a[b]
A[b] = (not e or #e > #v) and v.."C" or e
end
end
a=A
end
print(a[93],a[1000],a[9999])
```
[Answer]
# Mathematica, score 512710
```
Unprotect[StringRepeat]
StringRepeat[x_String, 0]:=""
Protect[StringRepeat]
#<>StringRepeat["C",#3-#2*1111]&[Array[ToString@#&,#,0],##]&[If[#<10^3,0,Quotient[#,1111]],#]&
```
Fixes a bug with `StringRepeat` (behaves incorrectly for `StringRepeat[x_String,0]`)
[Answer]
# Pyth, 327763 steps (optimum, 130 bytes)
Since the online compiler is inept at dealing with such enormous task, I have given it less work, so that it only generates `0`, `1`, and `1111`. However, it can theoretically solve the problem, because it uses the same algorithm as the Lua at the top.
[Try it online!](https://pyth.herokuapp.com/?code=%3DY.d%28%280k%3BV1%3DZYFGY+XZG%3Dk%40YG%3DN%25%22%2504d%22GV4%3Db%40NH%3Ddi%3ANb%25%22%25d%22ehibTT+XZd.x%3F%3El%40Ydlk%2Bkb%40Yd%2Bkb%29%3DbhGI%3CG9999+XZb.x%3F%3El%40Yblk%2Bk%5CC%40Yb%2Bk%5CC%29%29%3DYZ%3B%40YQ&input=1111&debug=0)
```
=Y.d((0k;V53=ZYFGY XZG=k@YG=N%"%04d"GV4=b@NH=di:Nb%"%d"ehibTT XZd.x?>l@Ydlk+kb@Yd+kb)=bhGI<G9999 XZb.x?>l@Yblk+k\C@Yb+k\C))=YZ;@YQ
```
---
How it works:
```
=Y.d((0k;V53=ZYFGY XZG=k@YG=N%"%04d"GV4=b@NH=di:Nb%"%d"ehibTT XZd.x?>l@Ydlk+kb@Yd+kb)=bhGI<G9999 XZb.x?>l@Yblk+k\C@Yb+k\C))=YZ)@YQ
assign_copy('Q',eval_input())
=Y.d((0k; assign_copy('Y',dict(0=k))
V53 for N in range(0,53):
=ZY assign_copy('Z',Y)
FGY for G in num_to_range(Y):
XZG=k@YG no_print(Z[G] = assign_copy('k',lookup(Y,G)))
=N%"%04d"G assign_copy('N',format("%04d",G))
V4 for H in range(0,4):
=b@NH assign_copy('b',lookup(N,H))
=di:Nb%"%d"ehibTT assign_copy('d',base(replace(N,b,format("%d",mod10(increment(base(b,10))))),10))
XZd.x?>l@Ydlk+kb@Yd+kb no_print(Z[d]=try_and_catch(greater_than(Plen(lookup(Y,d)),Plen(k)) ? concat(k,b) : lookup(Y,d)), lambda:plus(k,b))
) <anti-indent>
=bhG assign_copy('b',head(G))
I<G9999 if less_than(G,9999):
XZb.x?>l@Yblk+k\C@Yb+k\C no_print(Z[b]=try_and_catch(greater_than(Plen(lookup(Y,b)),Plen(k)) ? concat(k,"C") : lookup(Y,b)), lambda:plus(k,"C"))
) <anti-indent>
) <anti-indent>
=YZ assign('Y',Z)
) <anti-indent>
@YQ print(lookup(Y,Q))
```
[Answer]
# JavaScript (ES6), 327763 steps (optimum, 184 bytes)
A Breadth First Search, not so smart and not so fast.
```
t=>eval("for(k=[],s=[['0000',i='']];[u,p]=s[i++],u-t;k[v=(1+u-~0+'').slice(-4)]=k[v]||s.push([v,p+'C']))[...u].map(x=>k[v=[...u].map(y=>x-y?y:-~x%10).join``]=k[v]||s.push([v,p+x]));p")
```
**Less golfed**
```
t=>{
k=[]; // mark values already found to reduce search
for( i=0, s=[['0000','']];
[u,p]=s[i++], // u: current code, p:current steps
u != t; // exit if target found
)
{
// try all digits present in current code
[...u].map(x=> {
v=[...u].map(y=>x-y?y:-~x%10).join`` // apply digit x to u
if (!k[v]) // check if value v not found already
k[v] = s.push([v,p+x]));
})
v=(1+u-~0+'').slice(-4); // try operator C
if (!k[v]) // check if value v not found already
k[v] = s.push([v,p+'C']))
}
return p
}
```
**Test**
```
f=t=>eval("for(k=[],s=[['0000',i='']];[u,p]=s[i++],u-t;k[v=(1+u-~0+'').slice(-4)]=k[v]||s.push([v,p+'C']))[...u].map(x=>k[v=[...u].map(y=>x-y?y:-~x%10).join``]=k[v]||s.push([v,p+x]));p")
function SingleTest()
{
var i=S.value
if (/^\d{4}$/.test(i)) X.value=f(i)
else X.value='invalid input'
}
SingleTest()
function LongTest()
{
var i=0,v,r,t=0
var step=_=>{
v = ('000'+i).slice(-4);
r = f(v);
t+= r.length
V.value = v;
R.value = r;
T.value = t;
++i;
if(i<10000) setTimeout(step, 0)
}
step()
}
```
```
#V,#T,#S { width:5em }
#R,#X { width: 25em }
```
```
Single Test <input id=S value='0093'><button onclick="SingleTest()">-></button><input readonly id=X><hr>
Long test (0000 ... 9999) <button onclick="LongTest()">Go</button>(i mean <i>long</i>, runtime 1 hour)<br>
<input readonly id=V>
<input readonly id=R>
Total steps:<input readonly id=T>
```
] |
[Question]
[
Your challenge is to determine whether the given input is an integer, a string, or a decimal.
# Rules
* A string is any input that is not an integer or a float
* An integer must contain only numeric characters and must not start with a zero
* A decimal is any input that contains the period (`.`) and the period is surrounded by numeric characters.
**Note:** .01 is **not** considered a valid decimal.
* The program should output a raw string either "string", "integer", or "decimal".
* You may assume only printable ASCII characters are used
Cases:
```
asdf -> string
asdf3.4 -> string
2 -> integer
2.0 -> decimal
02 -> string
40. -> string
. -> string
.01 -> string
0.0 -> decimal
.9.9.9 -> string
[empty space] -> string
```
EDIT: Fixed the typo. I meant .01 without the leading zero, not with. If that made it unclear, its fixed now!
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins.**
[Answer]
# Pyth, 33 bytes (39 without packed string)
```
@_c."at%¸Ã`9hàãáÊ"7.x/`MsB+vz0z0
```
Some bytes are stripped due to Markdown. [Official code and test suite.](https://pyth.herokuapp.com/?code=%40_c.%22at%25%C2%B8%C3%83%609h%C3%A0%C3%A3%C3%A1%C2%9B%C3%8A%227.x%2F%60MsB%2Bvz0z0&test_suite=1&test_suite_input=asdf%0Aasdf3.4%0A2%0A2.0%0A02%0A40.%0A.%0A.01%0A0.0%0A.9.9.9%0A%0A%5B%5D&debug=0)
Without packed string:
```
@_c"integerdecimalstring"7.x/`MsB+vz0z0
```
It passes all of above test cases. Basically, to check if a string is a integer or decimal, it checks whether the string can be evaluated as a python literal (`v`), and if so, if you can add 0 to it and covert it back to its string representation, and get the input string. If so, it's an integer or a decimal. If you can also cast it to an int and still get the original string back, it's an integer.
[Answer]
# Javascript, ~~112~~ ~~121~~ 87 bytes
*Thanks to @edc65 for saving 34 bytes by converting the original code (in the explanation) to ES6. I didn't change the explanation because it shows the logic better.*
```
b=a=>/^[1-9]\d*$/.test(a)?"integer":/^([1-9]\d+|\d)\.\d+$/.test(a)?"decimal":"string"
```
This basically converts the rules for an integer and decimal in the question into regex checks, and tests them against the given input. If the input doesn't match, then it must be a string. It passes all of the tests given in the question.
## Ungolfed + explanation
```
function b(a) {
if(/^[1-9]\d*$/.test(a)) // regex check for the rules of an 'integer':
return"integer"; // ^[1-9] - check to make sure the first digit
// \d* - check to make sure that it is followed by zero or more digits
// $ - ensures that the previous check continues to the end of the word
if(/^([1-9]\d+|\d)\.\d+$/.test(a)) // regex check for the rules of a 'decimal', starting from the middle
return"decimal"; // \. checks for a '.' in the word
// the ([1-9]\d+|\d) and \d+ check to make sure the '.' is surrounded by
// one or more numerical characters on each side.
// the ^,$ ensure that the match is for the whole word
return"string"; // none of the others match, so it must be a string.
```
}
[Answer]
# Java, 133 bytes
```
String t(String v){if(v.matches("[1-9]\\d*"))return "integer";if(v.matches("(0|[1-9]\\d+)\\.\\d+"))return "decimal";return "string";}
```
[Answer]
# JavaScript (ES6), 74 ~~75~~
**Edit** 1 byte saved thx Zequ
```
f=i=>(i=i.match(/^(0|[1-9]\d*)(\.\d+)?$/))?i[2]?'decimal':'integer':'string'
```
**Test**
```
f=i=>(i=i.match(/^(0|[1-9]\d*)(\.\d+)?$/))?i[2]?'decimal':'integer':'string'
console.log=x=>O.textContent +=x +'\n';
// test cases from the question and some more
s=['asdf','asdf3.4','02','40.','.','.01','.9.9.9','','0.0.0','00.00','02.00']
i=['2', '11', '1000']
d=['2.0','0.0', '1.009', '911.1','123.4567890']
console.log('Strings:')
s.forEach(x=>console.log('<'+x+'> -> '+f(x)))
console.log('Integers:')
i.forEach(x=>console.log('<'+x+'> -> '+f(x)))
console.log('Decimals:')
d.forEach(x=>console.log('<'+x+'> -> '+f(x)))
```
```
<pre id=O></pre>
```
[Answer]
# Perl 5, 59 bytes
With the `-p` argument on the command line (which is calculated into the byte count):
```
chop;$_=!/\D|^0/?"integer":/^\d+\.\d+$/?"decimal":"string"
```
[Answer]
# [Perl 6](http://perl6.org), 61 bytes
```
{<string integer decimal>[?/^[(\d+\.\d+)|<[1..9]>\d*]$/+?$0]} # 61
```
Usage:
```
say «asdf asdf3.4 2 2.0 02 40. . .01 0.0 .9.9.9 ''».map: {...}
```
```
(string string integer decimal string string string string decimal string string)
```
[Answer]
# Python 2, 148 bytes
```
def f(s):
try:
t=float(s);assert s[0]!='0'
if `t+0`==s:return'decimal'
if `int(t)`==s:return'integer'
return'string'
except:return'string'
assert f('asdf') == 'string'
assert f('asdf3.4') == 'string'
assert f('2') == 'integer'
assert f('2.0') == 'decimal'
assert f('.') == 'string'
assert f('.01') == 'string'
assert f('.9.9.9') == 'string'
assert f(' ') == 'string'
assert f('40.') == 'string'
assert f('02') == 'string'
assert f('0.0') == 'string'
assert f('00.00') == 'string'
```
[Answer]
## JavaScript ES6, ~~74~~ 70 bytes
```
w=>w.match(/^\d+\.\d+$/)?"decimal":w.match(/^\d+$/)?"integer":"string"
```
] |
[Question]
[
Output coordinates of the vertices of a cube. Then, output a list of twelve triangles that will cover the cube, each triangle being a list of three vertex-indexes, consistently oriented. Output must be an ASCII string of distinct decimal numbers. This golf has no input. Winner is the fewest characters, where the character set is Unicode.
For an example, consider a 1x1x1 cube cornered at 0,0,0. The eight vertices of the cube can be described by the following xyz coordinates on a 3d Cartesian grid:
```
x y z = (0,0,1) (1,0,1) (1,1,1) (0,1,1) (0,0,0) (1,0,0) (1,1,0) (0,1,0)
```
Each vertex can be given an index: `x y z->index: 0 0 1->0, 1 0 1->1, 1 1 1->2, 0 1 1->3, 0 0 0->4, 1 0 0->5, 1 1 0->6, 0 1 0->7`
Now consider the top face, vertexes indexed zero to three. The two covering triangles can be described by three indices each:
```
[0,1,2] [2,3,0]
```
Here is a picture of this top face, viewed from above the cube:
```
3_____2
| /|
| / |
| / |
| / |
0_____1
```
And here is a view from an angle.
```
3____2
/ __-/|
0/_`__1 |
| | /6
|____|/
4 5
```
Note the orientation, or 'winding', of both of these triangles is 'counterclockwise' when viewed from 'outside' the cube directly looking at the face in question (imagine visiting each vertex as listed, it goes counterclockwise). Now imagine this done for all six sides of the cube.
```
vertices: (0,0,1) (1,0,1) (1,1,1) (0,1,1) (0,0,0) (1,0,0) (1,1,0) (0,1,0)
triangles as indices: [0,1,2], [2,3,0], [6,5,4], [4,7,6],
[5,2,1], [2,5,6], [0,3,4], [4,3,7], [2,6,3], [3,6,7], [0,4,1], [1,4,5]
```
You can output any size of cube located at any coordinates. You can number and order the vertex coordinates however you wish. Indices can be 0 based or 1 based. The triangle's orientation can be either clockwise or counterclockwise when viewed from outside the cube as long as it is consistent for all triangles.
The output can be formatted however you wish, as long as each ASCII decimal number is separated by at least one non-numeric ASCII character. For instance the above example could also be output as follows:
```
0 0 1 1 0 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0
0 1 2 2 3 0 6 5 4 4 7 6 5 2 1 2 5 6 0 3 4 4 3 7 2 6 3 3 6 7 0 4 1 1 4 5
```
This golf is inspired by various 3d graphics systems and formats, including OpenGL, OBJ, OFF, AMF, CGAL, etc. This golf is similar to the golf by Calvin's Hobbies named [Output a Face on a Numbered Cube](https://codegolf.stackexchange.com/questions/48838/output-a-face-on-a-numbered-cube) , the big difference being you need to output the x y z coordinates of the vertices yourself and output triangle indices. Thanks for reading.
Per user inspiration here is a "helper" validation program in python2 (non-golfy) that will print 'ok' or 'not ok' for test output data in variables vertstr and idxstr. It doesn't work perfectly... but it can catch some errors.
Edit: fixed typo in example and bugs in validation code.
```
#vertstr = '0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1'
#idxstr = '1 2 0 2 1 3 7 5 6 4 6 5 2 4 0 4 2 6 7 3 5 1 5 3 4 1 0 1 4 5 7 6 3 2 3 6'
vertstr = '0 0 1 1 0 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0'
idxstr = '0 1 2 2 3 0 6 5 4 4 7 6 5 2 1 2 5 6 0 3 4 4 3 7 2 6 3 3 6 7 0 4 1 1 4 5'
class Vector:
def __init__(self,v):
self.x,self.y,self.z=v[0],v[1],v[2]
def __add__(self,v):
return Vector([self.x+v.x,self.y+v.y,self.z+v.z])
def __sub__(self,v):
return Vector([self.x-v.x,self.y-v.y,self.z-v.z])
def __str__(self):
return str(self.x)+','+str(self.y)+','+str(self.z)
def cross(v1,v2):
x = v1.y*v2.z-v2.y*v1.z
z = v1.x*v2.y-v2.x*v1.y
y = v1.z*v2.x-v2.z*v1.x
return Vector([x,y,z])
# http://mathforum.org/library/drmath/view/55343.html & http://sympy.org
def winding(v1,v2,v3,obs):
x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4=v1.x,v1.y,v1.z,v2.x,v2.y,v2.z,v3.x,v3.y,v3.z,obs.x,obs.y,obs.z
d = x1*(y2*z3 - y2*z4 - y3*z2 + y3*z4 + y4*z2 - y4*z3)
d = d + y1*(-x2*z3 + x2*z4 + x3*z2 - x3*z4 - x4*z2 + x4*z3)
d = d + z1*(x2*y3 - x2*y4 - x3*y2 + x3*y4 + x4*y2 - x4*y3)
d = d - x2*y3*z4 + x2*y4*z3 + x3*y2*z4 - x3*y4*z2 - x4*y2*z3 + x4*y3*z2
return d
def normals(v1,v2,v3):
va = v2-v1
vb = v3-v2
vc = v1-v3
n1 = cross(va,vb)
n2 = cross(vb,vc)
n3 = cross(vc,va)
return [n1,n2,n3]
def triplify(str):
nums,triples=[],[]
for num in str.split(' '): nums+=[int(num)]
for i in range(0,len(nums),3):
triples += [[nums[i],nums[i+1],nums[i+2]]]
return triples
verts = triplify(vertstr)
indices = triplify(idxstr)
nsum = Vector([0,0,0])
windsum = 0
xs,ys,zs=[],[],[]
for v in verts:
xs+=[v[0]]
ys+=[v[1]]
zs+=[v[2]]
#print xs,ys,zs,len(xs)
center=Vector([float(sum(xs))/len(xs),float(sum(ys))/len(ys),float(sum(zs))/len(zs)])
for triangle in indices:
v1 = Vector(verts[triangle[0]])
v2 = Vector(verts[triangle[1]])
v3 = Vector(verts[triangle[2]])
norms = normals(v1,v2,v3)
print v1,v2,v3,norms[0],norms[1],norms[2]
for n in norms:
nsum += n
w = winding(v1,v2,v3,center)
print 'winding',w
if w<0: windsum-=1
elif w>0: windsum+=1
if abs(windsum)==12: print 'winding ok'
else: print 'winding not ok'
if (nsum.x==0 and nsum.y==0 and nsum.z==0): print 'normal sum ok'
else: print 'normal sum not ok'
```
[Answer]
# CJam, 35 bytes
```
YZm*`3{[XY4]m<)\0+_:+1$f-+_@f+W%}%`
```
[Try it online](http://cjam.aditsu.net/#code=YZm*%603%7B%5BXY4%5Dm%3C)%5C0%2B_%3A%2B1%24f-%2B_%40f%2BW%25%7D%25%60)
The output is:
>
> [[0 0 0] [0 0 1] [0 1 0] [0 1 1] [1 0 0] [1 0 1] [1 1 0] [1 1 1]][[1 2 0 2 1 3] [7 5 6 4 6 5] [2 4 0 4 2 6] [7 3 5 1 5 3] [4 1 0 1 4 5] [7 6 3 2 3 6]]
>
>
>
Triangle orientation is clockwise from the outside. I checked this manually, and it looks correct to me.
Explanation:
```
YZ Push 2 and 3 on stack.
m* Cartesian power, creates the coordinates of the 8 vertices.
` Convert to string for output. Done with vertices.
3{ Start loop over 3 coordinate directions.
[XY4] Push [1 2 4], which are the vertex index offsets for the 3 directions.
m< Rotate by loop counter. So the remaining loop body will be executed once
with [1 2 4], once with [2 4 1], once with [4 1 2].
) Pop off last offset. Will use this as index offset between the two
parallel faces.
\ Swap pair of remaining two offsets to top. These are the index offsets
within the face.
0+ Add a 0 to the list. These 3 indices define the first triangle.
_:+ Calculate the sum. This is the vertex index of the opposite corner.
1$ Copy first triangle to the top.
f- Subtract all indices from the index of the opposite corner, producing
the second triangle of the face.
+ Concatenate the indices of the two triangles, resulting in a list with
the 6 vertex indices for the face.
_ Copy the list.
@ Bring the offset between the two faces to the top.
f+ Add the offset to each index in the copied list.
W% Revert the order, resulting in the properly oriented list of the 6 vertex
indices for the parallel face.
}% End of loop over 3 coordinate directions.
` Convert to string for output. Done with triangles.
```
[Answer]
# Pyth, 18 characters
```
j`CM"⭧勛囃勦⾽仵ᶌﻘꚱ쥎➡˻ì
```
Same idea as my Haskell answer; prints:
```
[
1
1
1
1
1
,
2
1
2
1
1
...
```
[Answer]
# JavaScript (ES6) 78
```
alert([...'1010011100101110111:120213756465240426735153410145763236'].join` `)
```
Sorry but I really don't understand these challenges with no input.
[Answer]
# Ruby, ~~98~~106
Fixed error spotted by Reto Koradi.
```
s=sprintf'%024b',342391
6.times{|i|t='15462315'[i,3];t+=t.reverse;t[1+i%2*3]='07'[i%2];s+=t}
p s.split(//)
```
Given that coordinates are required, the only corner numbering scheme that made sense seemed to be the one where each corner is the binary representation of its coordinates. That's quite different from the linked question, where various different numbering schemes were tried. In the end I decided to print the coordinates with a dirty hardcode: `s` is initialised to the string version of 24-bit number`000001010011100101110111` whose decimal representation is 342391. Actually with this method of printing coordinates, the numbering of the vertices is flexible, so I may do another answer.
Going round the equator of the cube, we find the vertices 1,5,4,6,2,3 and we can define one triangle for each face from any 3 consecutive numbers on this list (wrapping back to the beginning at the end.) The other triangle on each face is defined by reversing the digits, and substituting the middle digit with 0 or 7 as appropriate.
This gives all the required output, but without any separating characters. To achieve that, I simply convert to an array of characters and print the array, like this (linebreaks inserted to prevent scrolling):
```
["0", "0", "0", "0", "0", "1", "0", "1", "0", "0", "1", "1", "1", "0", "0",
"1", "0", "1", "1", "1", "0", "1", "1", "1", "1", "0", "4", "4", "5", "1",
"5", "4", "6", "6", "7", "5", "4", "0", "2", "2", "6", "4", "6", "2", "3",
"3", "7", "6", "2", "0", "1", "1", "3", "2", "3", "1", "5", "5", "7", "3"]
```
[Answer]
# Haskell, 38 characters
```
f=mapM(mapM print.show)"⭧勛囃勦⾽仵ᶌﻘꚱ쥎➡˻ì"
```
Prints the right numbers, separated by a whole lot of junk:
```
'\''
'\\'
'1'
'1'
'1'
'1'
'1'
'\''
'\''
'\\'
'2'
'1'
'2'
'1'
'1'
...
```
The cube's diagonal is from (1, 1, 1) to (2, 2, 2).
[Answer]
# CJam, 20 characters
```
"⭧勛囃勦⾽仵ᶌﻘꚱ쥎➡˻ì":isS*
```
Same idea as my Haskell answer; prints:
```
1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1 2 2 2 1 2 0 2 1 3 7 5 6 4 6 5 2 4 0 4 2 6 7 3 5 1 5 3 4 1 0 1 4 5 7 6 3 2 3 6
```
[Answer]
# Ruby, Rev 1 62
```
29.downto(0){|c|p c>5?73888640>>c&1:[c,c^1,c|6,c|6,(c+3)%6,c]}
```
Got rid of the `c-6` by multiplying the magic number by 64.
The assignment of coordinates is below. It's odd that I assigned `100` to number 1. I could have saved a byte in rev 0 by exchanging the axes and assigning `001` to number 1. The reason it was that way was because originally I had up counting in the loop, which would have meant I had to put everything in reverse in the magic string. Anyway, with the change I've made now, there's no additional saving to be made, so i'll leave the coordinates as they are
```
Cube rotated with 0163 face at back
Top layer from above
01 000 100
74 010 110
Bottom layer from above
36 001 101
25 011 111
```
# Ruby, Rev 0 63
```
29.downto(0){|c|p c>5?1154510>>c-6&1:[c,c^1,c|6,c|6,(c+3)%6,c]}
```
Using hardcoding of the coordinates data to give flexibility in picking the corners. There are 54 digits in the output, meaning that the naive solution would have 63-54=9 bytes available for code. As I can't think of a way to insert spaces in 9 bytes, I believe this is shorter than the naive solution.
**Numbering scheme** (adapted from my Ruby answer to the linked question <https://codegolf.stackexchange.com/a/48867/15599>)
```
4---7
| /|
| / |
|/ |
1---0---7
| /| /|
| / | / |
|/ |/ |
6---3---2---7
| /| /|
| / | / |
|/ |/ |
6---5---4
| /|
| / |
|/ |
6---1
```
Output
```
0
0
0
1
0
0
0
1
1
0
0
1
1
1
0
1
1
1
0
0
1
1
1
0
[5, 4, 7, 7, 2, 5]
[4, 5, 6, 6, 1, 4]
[3, 2, 7, 7, 0, 3]
[2, 3, 6, 6, 5, 2]
[1, 0, 7, 7, 4, 1]
[0, 1, 6, 6, 3, 0]
```
] |
[Question]
[
# Input
Two lists `A` and `B` of nonnegative integers.
# Output
Either `1`, `0`, or `-1`, depending on whether `A` is larger than, equal to, or smaller than `B` with respect to the *twisted lexicographical ordering* as defined below.
If you want, you can replace `1`, `0` and `-1` with any other three constant values.
The twisted lexicographical ordering is like the ordinary lexicographical ordering, in that you compare the lists element by element, and decide their order at the first differing index.
However, in the twisted version we use a different ordering for nonnegative integers at each index.
Namely, at every index `i` (indexing starts from `1`), the order of the first `i` nonnegative integers (from `0` to `i-1`) is reversed, and they are moved above all the other numbers.
Moreover, the "missing element" that signifies one list being shorter than the other is moved directly below `i-1`.
Visually, the order at index `i` is
```
i < i+1 < i+2 < i+3 < ... < [missing element] < i-1 < i-2 < i-3 < ... < 2 < 1 < 0
```
Note that the first `...` denotes infinitely many numbers. This means that the following lists are in ascending order with respect to the twisted lexicographical ordering:
```
[3,2,3,4]
[3,2,3,5]
[3,2,3,10]
[3,2,3,1341]
[3,2,3]
[3,2,3,3]
[3,2,3,2]
[3,2,3,1]
[3,2,3,0]
```
# Rules
You can give a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
# Test Cases
```
Output 1:
[0] []
[] [1]
[] [1,2,1,2]
[2,1] [1,1]
[0,1,2] [0,2,1]
[3,0] [3,1]
[3,1] [3]
[2] [2,2]
[2] [2,23]
[2,24] [2,23]
[2,1] [2,23]
Output 0:
[] []
[0] [0]
[1,1] [1,1]
[2,1,2] [2,1,2]
Output -1:
[1,2,1,1,2] [1,2,1,1,1]
[1,2,1,1,5] [1,2,1,1,4]
[1,2,1,1,5] [1,2,1,1]
[1,2,1] [1,2,1,1]
[1,2,1,1,5] [1,2,1,1,6]
[1,2,1,1,6] [1,2,1,1,7]
```
[Answer]
# Python 2, 76 bytes
```
c=lambda*a:cmp(*[[(max(i-x,-1),x)for i,x in enumerate(L)]+[(0,)]for L in a])
```
This replaces each integer in both lists with a 2-tuple to account for the twisted ordering. Python 2's [`cmp`](https://docs.python.org/2/library/functions.html#cmp) builtin does the rest.
Usage:
```
>>> c([1,2,1,1,6], [1,2,1,1,7])
-1
```
[Answer]
# CJam - 57
```
q:S~=0{S~]:A:,~e>{A{_,I>{I=_I>0{W*2}?}1?[\]}%}fI]z~>2*(}?
```
Yeah it's still very long...
[Try it online](http://cjam.aditsu.net/#code=q%3AS~%3D0%7BS~%5D%3AA%3A%2C~e%3E%7BA%7B_%2CI%3E%7BI%3D_I%3E0%7BW*2%7D%3F%7D1%3F%5B%5C%5D%7D%25%7DfI%5Dz~%3E2*(%7D%3F&input=%5B0%201%202%5D%20%5B0%202%201%5D)
Brief explanation:
The code outputs 0 if the arrays are equal in the traditional sense, otherwise it converts each item of each array to a 2-element array: [0 ai] if ai>i (0-based), [1 whatever] if ai is missing, and [2 -ai] if ai<=i. In the process, the shorter array is also extended to the larger size. Then the transformed arrays are compared lexicographically and the result is adjusted to -1/1.
[Answer]
# Perl, 74
Without good array manipulation functions perl is not the optimal tool for the job, but it works.
```
#!perl -pa
$i=0,s/\d+,?/$s=sprintf"%9d",$&;$&>$i++?$s:~$s/ge for@F;$_=$F[0]cmp$F[1]
```
Test [me](http://ideone.com/WgFjGZ).
[Answer]
# J, 95 bytes
(Not super-short but whatever. Definitely golfable.)
```
f=.4 :0
m=.>:>./x,y
t=.(|+(1+m)*0>:*)@(i.@#-~])@(],m$~>&#*-&#)
x(t~(*@-&((m+#x,y)&#.))t)y
)
```
[Passing all the test cases.](https://gist.github.com/randomra/066a2f33414f5d6c04b1) (Great test case set! Thanks!)
Method:
* Padding the shorter list with maxvalue+1 (`m=.>:>./x,y`). `(],m$~>&#*-&#`
* Transforming list elements so normal comparison could be used. `(|+(1+m)*0>:*)@(i.@#-~])`
* Calculating two baseX numbers from the two list with sufficient X. `((m+#x,y)&#.)`
* Returning the signum of the two numbers difference.`*@-&`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
J_»0;1ż)M
```
[Try it online!](https://tio.run/##y0rNyan8/98r/tBuA2vDo3s0ff8fbteM/P8/mis62iBWRyE6NlYHyASxDJGYOkY6QAwRADIhYlAFBmApoIgBSBVEzFgHbJgxgg/WYww1AcQ2gpsH5cEkdYxM0EUMUQUQ7gTbYgBhG6K5ywjmLiS3QzwCFYdxDFHlTJHlTHDLIclgF0U3ywxVzgxZzjw2lisWAA "Jelly – Try It Online")
Direct port of grc's Python solution. Monadic link taking a pair of its arguments and returning `[1]` for `1`, `[1, 2]` for `0`, and `[2]` for `-1`.
```
) For each element of the input:
_ Subtract each element from
J its 1-index,
»0 take the maximum of each of those and 0,
;1 append 1,
ż and zip those with the original elements.
M Return the list of maximal indices.
```
[Answer]
# Mathematica, 65
```
f=-Order@@MapIndexed[If[#>Last@#2,#,a-b#]&,PadRight[{##}+1],{2}]&
```
Usage:
```
f[{1, 2, 1, 1, 6}, {1, 2, 1, 1, 7}]
```
>
> -1
>
>
>
] |
[Question]
[
Repdigits are numbers of the form `a * (10^n - 1)/9` with `a in [-9,9]\{0}` (in other words 111, -3333, 66, numbers which are made by repeating only one digit)
**Goal:** Write a program or function which takes a single positive integer `N` and prints `N = s_1 + s_2 + ... + s_k`. There should be one number per line and the numbers need to be right-aligned. No two summands should have the same number of digits and adding zeros is not allowed. The output should be ordered in ascending or descending order (by number of digits)
**Examples:**
```
in:
24192
out:
24192 =
22222 +
2222 -
222 -
33 +
3
in:
24192
out:
-7
-22
+888
+1111
+22222
=24192
in:
113
out:
113= NOT 111+ no empty lines 111+
111+ 00+
2 2 2
```
As you can see there can be multiple solutions and some artistic freedom is allowed. Leading and trailing whitespace in each line is allowed
Shortest byte count wins
[Answer]
# perl 5 - 97 92 93 86
```
$x=$_=pop;{printf"%15s
",$_;$_=$x,s!\d!//,$&!eg,$x-=$_,$i++?s/^\b/+/:s/^/=/;/0/||redo}
```
Input given as a parameter:
```
$perl a.pl 2224192
2224192
=2222222
+1111
+888
-22
-7
```
[Answer]
## CJam, ~~55~~ 50 bytes
```
'=l:L+Li{_W>"-+"=1$zs(\,)*+:Ii-L,_S*I+\~>\}h;]W%N*
```
[Test it here.](http://cjam.aditsu.net/)
Uses the output format
```
-7
-22
+888
+1111
+2222222
=2224192
```
I might golf this more once I'm beaten.
Explanation:
```
'=l:L+Li{_W>"-+"=1$zs(\,)*+:Ii-L,_S*I+\~>\}h;]W%N*
'= "Push = character.";
l:L "Read STDIN and store in L.";
+L "Concatenate, push new copy of L.";
i "Convert to integer.";
{ }h "Do-while loop. Leaves the condition on the
stack. I will use the remainder for that.";
_W> "Duplicate remainder, compare with -1.";
"-+"= "Select appropriate sign character.";
1$ "Copy remainder again.";
zs "Take abs() and convert to string.";
( "Shift off first digit.";
\ "Swap with string.";
, "Get length.";
) "Increment.";
* "Repeat digit that often.";
+ "Concatenate with sign.";
:I "Store in I.";
i- "Convert to integer. Subtract from remainder.";
"Now we'll right-justify I.";
L, "Load input, get length.";
_ "Duplicate.";
S* "Repeat space that often.";
I+ "Load string and concatenate.";
\~ "Swap with length. Bitwise complement.";
> "Take that many characters from the right.";
\ "Swap with remainder.";
; "Discard final remainder (0).";
] "Wrap in array.";
W% "Reverse.";
N* "Join with line feeds.";
```
The resulting array is printed automatically at the end of the program.
[Answer]
# JavaScript ES6 - 145
```
i=0;f=n=>{return g=n<0,n=Math.abs(n)+'',l=n.length,r=l-1?n[0].repeat(l):n,(i>0?g?'-':'+':n+'=')+'\n'+' '.repeat(i++)+(l-1?r+f((+n-r)*(g?-1:1)):r)}
```
Paste into Firefox console. Run as `f(24192)`.
Output for `f(24192)`:
```
24192=
22222+
1111+
888-
22-
7
```
[Answer]
## GolfScript 77
```
~.[{..0>2*(.@*`.,\[0=]*''+~*.@\-.}do;]-1%{[.0>' +'=\`n].1=,2$`,\-' '*\+}%'='@
```
Online demo links:
* [24192](http://golfscript.apphb.com/?c=OycyNDE5MicKCn4uW3suLjA%2BMiooLkAqYC4sXFswPV0qJycrfiouQFwtLn1kbztdLTEle1suMD4nICsnPVxgbl0uMT0sMiRgLFwtJyAnKlwrfSUnPSdA&run=true)
* [2147483648](http://golfscript.apphb.com/?c=OycyMTQ3NDgzNjQ4JwoKfi5bey4uMD4yKiguQCpgLixcWzA9XSonJyt%2BKi5AXC0ufWRvO10tMSV7Wy4wPicgKyc9XGBuXS4xPSwyJGAsXC0nICcqXCt9JSc9J0A%3D&run=true)
* [1 trillionth prime](http://golfscript.apphb.com/?c=OycyOTk5NjIyNDI3NTgzMycKCn4uW3suLjA%2BMiooLkAqYC4sXFswPV0qJycrfiouQFwtLn1kbztdLTEle1suMD4nICsnPVxgbl0uMT0sMiRgLFwtJyAnKlwrfSUnPSdA&run=true)
A slightly more readable version (if GolfScript can be called readable) with unit tests version is available [here](https://github.com/clupascu/codegolf/blob/9cc152756fffb96f59a1cb8fea2e0816b6cc1739/decompose_number_in_repdigits/decompose.gs).
] |
[Question]
[
# Emulate the Professor's typing
**Background**
Unfortunately, the Professor is not able to use his keyboard properly: whenever he is meant to use the `Shift` key, he presses `Caps Lock` **once** before typing, and doesn't bother to correct himself. If there are two or more keys in a row that require `Shift`, he presses `Caps Lock` before the first one and does nothing before the others.
As his secretary, I want to replicate this effect so that people think that he is the one replying to his emails, not me. He knows his typing looks stupid, but he doesn't care.
**Task**
Write a program that takes STDIN or file input of some text, and then outputs that text as if it had been typed by the Professor.
This is **code golf**, and standard loopholes are not allowed.
**Keyboard layout**
```
Default:
` 1 2 3 4 5 6 7 8 9 0 - =
q w e r t y u i o p [ ]
a s d f g h j k l ; ' #
\ z x c v b n m , . /
With shift:
¬ ! " £ $ % ^ & * ( ) _ +
Q W E R T Y U I O P { }
A S D F G H J K L : @ ~
| Z X C V B N M < > ?
With caps lock:
` 1 2 3 4 5 6 7 8 9 0 - =
Q W E R T Y U I O P [ ]
A S D F G H J K L ; ' #
\ Z X C V B N M , . /
```
**Example input / output**
(The `CapsLock` line is just there for your understanding, and should not be outputted in your program)
```
Input: abc ** def ! (ghijkl) mnop
Output: abc 88 DEF 1 9GHIJKL0 mnop
CapsLock: * * * * (* means Caps Lock was pressed before this character)
Input: print("Hello, World!"); sys.exit()
Output: print92HELLO, world120; SYS.EXIT90
CapsLock: * * * *
Input: !ABC!abc!ABC!abc!x!y!z
Output: 1ABC1ABC1abc1abc1X1y1Z
CapsLock: * * * * *
```
[Answer]
## Python 2 - 269 ~~275 290 318 337~~
Input is mostly safe if you use triple-quotes:`"""print("Hello, World!"); sys.exit()"""`
```
C=D=0
r=''
l,u,c=" `1234567890-=qwertyuiop[]asdfghjkl;'#\\zxcvbnm,./",' \xac!"\xa3$%^&*()_+QWERTYUIOP{}ASDFGHJKL:@~|ZXCVBNM<>?'," `1234567890-=QWERTYUIOP[]ASDFGHJKL;'#\\ZXCVBNM,./"
for h in input():w=h!=' ';U=h in u;C^=w&U&~D;D=U&w;r+=[l,c][C][[l,u][U].find(h)]
print r
```
Encoding doesn't seem to help much, ~~except with the awkward ¬ and £ characters (I've tried looking at other problems like this and I think I should try to use split?)~~(It doesn't seem like the keyboard compresses enough to make it worth `.decode`, etc...)
Also, spaces suck.
Edit note: Indexing is *weird*
[Answer]
# PowerShell - 295
Takes input from the console (Read-Host), and outputs to the console.
```
$d=@("``1234567890-=qwertyuiop[]asdfghjkl;'#\zxcvbnm,./ ","``1234567890-=QWERTYUIOP[]ASDFGHJKL;'#\ZXCVBNM,./ ",'¬!"£$%^&*()_+QWERTYUIOP{}ASDFGHJKL:@~|ZXCVBNM<>? ')
((Read-Host).ToCharArray()|%{if($_-eq' '-or$d[2].IndexOf($_)-lt0){$a=0}else{if(!$a){$b=!$b}$a=2}$d[$b][$d[$a].IndexOf($_)]})-join''
```
] |
[Question]
[
## Challenge
Given a list a notes, you must return the corresponding tablature.
## Notes
The notes must be in the range of A to G inclusive and the octave range being 2 to 6 inclusive. The format is note-octave with `#` representing a sharp and `b` representing a flat. E.g: `A7` or `F#3`.
## Tabs
Tablature is a method of writing music, by diagrammatically representing the instrument. It is usually represented as five lines with numbers on them.
The numbers that are written on the lines represent the fret used to obtain the desired pitch. For example, the number 3 written on the top line of the staff indicates that the player should press down at the third fret on the high E (first string). Number 0 denotes the nut — that is, an open string.
Fret numbers may not be greater than 22 and the guitar is six string.
The tablature must be in the [standard ASCII format](http://en.m.wikipedia.org/wiki/ASCII_tab). You must not include any technique indicators (hammer on, slide etc.). Separate each note by five dashes. In the case of double digits, reduce the number of dashes to four.
The beginning of the tab should look like this:
```
e |-----
B |-----
G |-----
D |-----
A |-----
E |-----
```
And the end should look like:
```
-----|
```
for all lines.
[](https://i.stack.imgur.com/ax6yN.gif)
(source: [justinguitar.com](https://www.justinguitar.com/images/IM_images/IM-126-open_position_notes.gif))
## Example
```
Input: C3 C3 D3 E3 F3
Output:
e |-----------------------------------|
B |-----------------------------------|
G |-----------------------------------|
D |-----------------0-----2-----3-----|
A |-----3-----3-----------------------|
E |-----------------------------------|
```
## Winning
The shortest code wins
[Answer]
# Python 3 – ~~329~~ ~~328~~ ~~319~~ 300
This is my first post on codegolf.se, and probably not nearly optimal; I have read a lot of posts here but did my first code golf ever maybe 50 hours ago. Wanted to try, though!
**EDIT:** Removed 1 byte, didn't need to output an extra dash there
**EDIT 2:** Removed 9 bytes, removed some spaces from the note string
**EDIT 3:** Removed 19 bytes by converting `filter()` to a generator
```
a,b='C B#oC#DboD oD#EboE FboF E#oF#GboG oG#AboA oA#BboB Cb',input().split()
for f in range(6):print('eBGDAE'[f]+' |-----'+''.join([((str(d[-1])if f==6-len(d)else'')+'-'*6)[:6]for d in[[c-d+9for d in b"%*/48="if c+9>=d]for c in[12*int(g[-1])+a[:a.index((g[:-1]+' ')[:2])].count('o')for g in b]]])+'|')
```
A bit ungolfed:
```
a='C B#oC#DboD oD#EboE FboF E#oF#GboG oG#AboA oA#BboB Cb' # string of notes
b=input().split() # read user input
for f in range(6): # loop through the strings
print('eBGDAE'[f] + ' |-----' + # string identifier and start of string
''.join([ # join notes of tablature
((str(d[-1]) # highest string the note can be played on
if f == 6 - len(d) # if this is the correct string print the fret
else '') # if not then only dashes
+ '-' * 6) # print the dashes after the fret
[:6] # but only until 6 chars per note
for d in [ # loop through strings
[c - d # calculate fret number
+ 9 # add back the 9 (explained below)
for d in b"%*/48=" # string values increased by 9 as ASCII bytes
if c + 9 >= d] # filter to remove too high-pitched strings
for c in [ # loop through note values
12 * int(g[-1]) + # octave value
a[:a.index( # part of note string before this note
(g[:-1] + ' ')[:2])] # unique note identifier
.count('o') # o's (frets) between C and this note
for g in b]]]) # loop through notes
+ '|') # end tablature
```
] |
[Question]
[
What you need to do to win this challenge is to write the shortest "timeago" script that outputs the number of decades, years, weeks, days, hours, minutes, and seconds between a given [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time) and the time the script is run.
You must give the time difference in "lowest terms", e.g. `1 week` not `7 days`, `9 years` not `0 decades 9 years`. You also must use plural forms correctly, e.g. `1 day` not `1 days`.
Your script must be accurate to within plus or minus 1 second (so the exact second rounding method is unimportant).
```
Time Equivalency Table
1 decade = 10 years
1 year = 31536000 seconds (not technically correct but close enough)
1 week = 7 days
1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds
```
The output should be of the form
```
A decade(s) B year(s) C week(s) D day(s) E hour(s) F minute(s) G second(s)
```
where `A...G` are all non-negative integers and the `s` is only there for plurals.
# Notes
* The timestamp will always be a time from the past. **It may be negative.**
* Input and output may be anything reasonable: stdin/stdout, function input and return value, etc.
* You may not use any tools that already do this. i.e. if your language has a `timesince(timestamp)` function built in you may not use that function.
*I have vastly edited this to make it clearer in hopes to assuage the somewhat silly battle between new users with unclear questions and old users who require perfection. It was not a terrible question (though now it may be too similar to [this](https://codegolf.stackexchange.com/questions/1702/the-time-traveler)).*
Given that enough time is passed since the last answer, I declare **Three If By Whiskey** with its *177 bytes* Ruby implementation the winner of this context!
[Answer]
## Ruby, ~~184~~ 177
```
->n{x=Time.now.to_i-n;d=[3650*y=86400,365*y,7*y,y,3600,60,1];(0..6).map{|i|c=x/d[i];(x%=d[i]*c;"#{c} #{%w[decade year week day hour minute second][i]}#{c<2?'':'s'}")if c>0}*' '}
```
There's nothing particularly clever here, but I suspect it's still very close to optimal.
**Example run**
```
p ->n{x=Time.now.to_i-n;d=[3650*y=86400,365*y,7*y,y,3600,60,1];(0..6).map{|i|c=x/d[i];(x%=d[i]*c;"#{c} #{%w[decade year week day hour minute second][i]}#{c<2?'':'s'}")if c>0}*' '}[0]
"4 decades 4 years 41 weeks 3 days 14 hours 20 minutes 48 seconds"
```
[Answer]
## J , 165
```
;' '&,@":&.>@((#~([:*&>{."1))@((;:' decades years weeks days hours minutes seconds')(],.([}.~[:-1=])&.>)<"0@(_ 10 52 7 24 60 60&#:)@(-~([:".@}:[:2!:0'date +%s'"_))))
```
Can probably be golfed more. Uses a shell call to date for getting the current unix epoch time, since Unix epoch is unavailable in J.
Example run:
```
;' '&,@":&.>@((#~([:*&>{."1))@((;:' decades years weeks days hours minutes seconds')(],.([}.~[:-1=])&.>)<"0@(_ 10 52 7 24 60 60&#:)@(-~([:".@}:[:2!:0'date +%s'"_)))) 0
4 decades 4 years 41 weeks 3 days 12 hours 54 minutes 1 second
```
[Answer]
# Python - 183
```
import time;t=int(time.time()-input());d=86400
for f,u in zip((3650*d,365*d,7*d,d,3600,60,1),'decade year week day hour minute second'.split()):
if t/f:print`t/f`,u+'s'*(t/f>1),;t%=f
```
Output for a timestamp 999996400 seconds in the past:
```
3 decades 1 year 37 weeks 46 minutes 39 seconds
```
[Answer]
# JavaScript, 392
```
t=function(c){i=function(){var a=+new Date/1e3-c,b=document;29>a?b.write("just now"):60>a?b.write((a|0)+" seconds ago"):60<a&&120>a?b.write("1 minute ago"):60>a/60?b.write((a/60|0)+" minutes ago"):60<a/60&&120>a/60?b.write("1 hour ago"):24>a/3600?b.write((a/3600|0)+" hours ago"):24<a/3600&&48>a/3600?b.write("1 day ago"):1<=a/86400&&b.write((a/86400|0)+" days ago")};i();setInterval(i,3e4)};
```
*Also the unminified code for the curious ones*
```
t = function(timestamp){
i = function() {
var diff = (+new Date/1e3)-(timestamp),
d = document;
if( (diff) < 29) {
d.write( 'just now' )
}
else if( diff < 60) {
d.write( ( (diff) |0 ) + ' seconds ago' )
}
else if( diff > 60 && diff < 120) {
d.write( '1 minute ago' )
}
else if( (diff)/60 < 60) {
d.write( ( (diff)/60 |0 ) + ' minutes ago' )
}
else if( (diff)/60 > 60 && (diff)/60 < 120) {
d.write( '1 hour ago' )
}
else if( (diff)/3600 < 24) {
d.write( ( (diff)/3600 |0 ) + ' hours ago' )
}
else if( (diff)/3600 > 24 && (diff)/3600 < 48) {
d.write( '1 day ago' )
}
else if( (diff)/86400 >= 1) {
d.write( ( (diff)/86400 |0 ) + ' days ago' )
}
}
i()
setInterval(i, 3e4)
}
```
It updates every 30 seconds and calculates both singular and plural.
To run it use `t(unix_timestamp)`
[Answer]
# Javascript, 287
```
function p(e,n){return e>2?e+" "+n+"s ":e+" "+n+" "}function t(e){n=new Date/1e3,l=e-n,c=1,m=60,h=60*m,d=24*h,w=7*d,y=365*d,a=10*y,s="",v={a:"Decade",y:"Year",w:"Week",d:"Day",h:"Hour",m:"Minute",c:"Second"};for(i in v)k=v[i],i=window[i],(r=Math.floor(l/i))>0&&(s+=p(r,k)),l%=i;alert(s)}
```
to run use `t(secondsInFuture)`;
[Answer]
# Javascript, 263
```
i=[315360000,31536000,604800,86400,3600,60,1];s=['decade','year','week','day','hour','minute','second'];function g(d){return p(parseInt((new Date().getTime()-d)/1000), 0);}function p(d,n){k=d-d%i[n];r=k/i[n];return (r>0?r+' '+s[n]+'(s) ':'')+(n<6?p(d-k,n+1):'');}
```
to run from the Javascript console, call
```
g(unixTimestamp);
```
] |
[Question]
[
## Challenge
>
> In this task you would be given an
> integer N you have to output the
> nearest prime to the integer.
>
>
>
If the number is prime itself output the number.
The input N is given in a single line,the inputs are terminated by EOF.The number of inputs would not exceed 10000 values.
The challenge is to implement the fastest solution so that it can process a maximum of 10000 values as fast as possible.
**Input**
```
299246598
211571591
71266182
645367642
924278231
```
**Output**
```
299246587
211571573
71266183
645367673
924278233
```
**Constraints**
* N is less than 2^64
* Take care of your fingers do not use more than 4096 bytes in your solution.
* You can use any language of your choice as long as you are not using it's any inbuilt things for the primes.
* Fastest solution,with the most efficient time complexity wins!
**ADDED:**
[This](http://golf.shinh.org/p.rb?Find+the+nearest+Prime) is a easier version of the this same problem (with N < 2^31) so that you may try checking your approach in smaller cases before building it up for this actual problem.
[Answer]
## Python
```
import sys,random
# Miller-Rabin primality test, error rate 2^-200.
def prime(N):
if N<3:return N==2
s=0
d=N-1
while (d&1)==0:s+=1;d>>=1
for i in xrange(100):
a=random.randrange(1,N)
if pow(a,d,N)!=1 and all(pow(a,d<<r,N)!=N-1 for r in xrange(s)):return 0
return 1
for N in map(int,sys.stdin):
d=0
while 1:
if prime(N+d):print N+d;break
if prime(N-d):print N-d;break
d+=1
```
[Answer]
## PARI GP
```
a(n)=x=[precprime(n),nextprime(n)];print(if(x[1]-n<n-x[2],x[1],x[2]))
while(1,print(a(input())))
```
[Answer]
# Haskell
```
import Data.Numbers.Primes
-- Assuming, we are on x64
nearestPrime :: Int -> Int
nearestPrime n | n - s < l - n = s
| otherwise = l where
l = head $ dropWhile (not . isPrime) [n..]
s = head $ dropWhile (not . isPrime) [n,n-1..]
main = readLine >>= print . nearestPrime . read
```
Should be quite fast. Requires the package `primes`, available from hackage.
[Answer]
**Ruby**
```
require 'prime'
gets(p).split.each{|n|
a=b=n.to_i
a,b = a-1,b+1 while !a.prime? and !b.prime?
p a.prime? ? a : b
}
```
[Answer]
# Java
This takes <1 second until num starts being greater than 10^8. Not efficient enough, considering 2^64 is about 1.8\*10^19. (Started 10^15 6 minutes ago, and is still running D:)
```
import java.util.*;
class ClosestPrime {
public static double closest(double num) {
double returnme = 0;
if (isPrime(num)){returnme = num;}
for (double i = 0; i < num / 2; i++) { //checks each side of num
if (isPrime(num - i)) {returnme = num - i;
break;}
if (isPrime(num + i)) {returnme = num + i;
break;}
}
return returnme;
}
private static boolean isPrime(double num) {
long sqrtnum = (long) Math.sqrt(num); //no need to check for factors above sqrt(num)
List<Double> primes = new LinkedList<Double>();
primes.add((double) 2);
for (double i = 3; i < sqrtnum; i+=2) {primes.add(i);} //fill list with odd numbers
for (long i = 2; i <= sqrtnum; i++) {
if (num / i % 1 == 0) {return false;}
ListIterator<Double> iter = primes.listIterator();
while (iter.hasNext()) {if ((iter.next()) / i % 1 == 0){iter.remove();}} //sieving by Eratosthenes
}
return true;
}
}
```
This gives a surefire answer every time, since it doesn't use a probabilistic algorithm, but pays heavily for that in terms of efficiency - 10^18 would have over 5 million primes in the list, and even more before sieving. May improve this sometime with a better sieve algorithm. I don't expect this to beat any of the others :)
[Answer]
# Haskell
This is pretty fast, and non-deterministic up to a large limit. Also my first ever Haskell :). `wc` says 903b uncompiled.
Edit: If anyone wants to estimate the time complexity, be my guest...
```
import System.Environment
import Math.NumberTheory.Moduli -- arithmoi
import Data.List.Ordered -- data-ordlist
main :: IO ()
main = interact processInputStrings
processInputStrings :: String -> String
processInputStrings input = unlines $ map show $ getClosestMembers $ map read $ lines $ input
isPrime :: Integer -> Bool
{- Implement the Miller–Rabin test with basis valid up to somewhere > 2^64 -}
isPrime 2 = True
isPrime 3 = True
isPrime t = let
factor :: (Integer, Integer) -> (Integer, Integer)
factor (d,s) = if even d then factor (d `div` 2, s+1) else (d,s)
(d,s) = factor (t-1, 0)
in
and $ map (\a ->
or [(powerMod a d t) == 1, or [(powerMod a (2^r * d) t) == t-1 | r <- [0..s-1]]]
) $ filter (<t) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
getClosestMembers :: [Integer] -> [Integer]
getClosestMembers inputs = map (\i -> head [n | n <- concat [[i-d, i+d] | d <- [0..]], isPrime n]) inputs
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/647/edit).
Closed 6 years ago.
[Improve this question](/posts/647/edit)
You are writing a program for an automatic cash register. The user needs change with the least number of coins used. Write a program which takes an amount (say $1.53) and gives change in US denominations - in this instance: 1 x one dollar note, 1 x fifty cents and 3 x one cent. The shortest program shall be the winner. Bonus points for supporting other currencies (i.e. UK denominations) and unusual currencies (1, 2, 3 cents?)
You have these US denominations: 1 cent, 5 cents, 10 cents, 25 cents, 50 cents, 1 dollar (note or coin), 2 dollars, 5 dollars, 10 dollars.
You have these UK denominations: 1 pence, 2 pence, 5 pence, 10 pence, 20 pence, 50 pence, £1, £2, £5 (note or coin), £10.
[Answer]
### Windows PowerShell, 108 ~~111~~ ~~117~~
Very first attempt, ungolfed so far:
```
$i=+("$input"-replace'[^\d.]')
$args|%{0d+$_}|sort -des|%{$a=[math]::floor($i/$_)
if($a){$i-=$a*$_
"$a×$_"}}
```
Implementation notes:
1. Accepts the quantity to return via the pipeline
2. Accepts the list of currency denominations via the command-line
3. The quantity can be given with a currency sign; that will be stripped (in fact, anything non-numeric).
4. The list of denominations does not need to be sorted.
5. The program will output the largest change smaller than the requested quantity achievable with the given denominations, i.e. 1.5 for 1.53 if the 1-cent coin is missing.
If 3 and 4 do not need to be satisfied (i.e. *I* control the input format ;-)), then the following program suffices (71):
```
$i=+"$input"
$args|%{$a=[math]::floor($i/$_)
if($a){$i-=$a*$_
"$a×$_"}}
```
[Answer]
## Mathematica: 110 chars
```
Sort[IntegerPartitions[Rationalize@#,Infinity,{10,5,2,1,1/2,1/4,1/10,5/100,1/100}],
Length@#1<Length@#2&][[1]]&
```
Usage
```
%[0.98]
{1/100, 1/100, 1/100, 1/10, 1/10, 1/4, 1/2}
```
Or
```
Tally@Sort[IntegerPartitions[Rationalize@#,Infinity,
{10,5,2,1,1/2,1/4,1/10,5/100,1/100}],
Length@#1<Length@#2&][[1]]&
```
(6 chars more) gives
```
{{1/100, 3}, {1/10, 2}, {1/4, 1}, {1/2, 1}}
```
For other denominations, just change the rationals table {10,....,5/100,1/100}
[Answer]
# D: 225 Characters
```
import std.algorithm,std.conv,std.stdio;void main(string[]args){auto m=args[1].findSplit(".");void p(T,S)(T t,T u,S s){foreach(v;[u,10,5,1]){writefln("%s %s%s",t/v,v,s);t-=(t/v)*v;}}p(to!int(m[0]),20,"");p(to!int(m[2]),25,"/100");}
```
More Legibly:
```
import std.algorithm,std.conv,std.stdio;
void main(string[] a)
{
auto m = a[1].findSplit(".");
void p(T, S)(T t, T u, S s)
{
foreach(v; [u, 10, 5, 1])
{
writefln("%s %s%s", t / v, v, s);
t -= (t / v) * v;
}
}
p(to!int(m[0]), 20, "");
p(to!int(m[2]), 25, "/100");
}
```
Only handles US currency. Takes the value as a floating point value on the command line (must have the leading 0 for values under 1 dollar). Does not accept $ as part of value. Outputs the number of each type of bill/coin on a separate line.
E.g. an input of 1.53 results in:
0 20
0 10
0 5
1 1
2 25/100
0 10/100
0 5/100
3 1/100
[Answer]
# Mathematica, 51 bytes
```
#~NumberDecompose~{10,5,2,1,.5,.25,.1,.05,.01}&
```
input
>
> [1.53]
>
>
>
output
>
> {0, 0, 0, 1, 1, 0, 0, 0, 3.}
>
>
>
# Mathematica, 82 bytes --WITH BONUS--
```
(s=#~NumberDecompose~#2;Row@Flatten@Table[Table[#2[[i]]"+",s[[i]]],{i,Length@s}])&
```
**Input**
>
> [37.6, {15, 7, 2.5, 1, 0.88, 0.2, 0.01}]
>
>
>
**output**
>
> 15 +15 +7 +0.2 +0.2 +0.2 +
>
>
>
[Answer]
# Javascript, ~~84~~ 83 bytes
```
(n,v=[10,5,2,1,.5,.25,.1,.05,.01],l=[])=>{for(i in v)l[i]=n/v[i]|0,n%=v[i];return l}
```
```
(n,v=[10,5,2,1,.5,.25,.1,.05,.01],l=[])=>eval("for(i in v)l[i]=n/v[i]|0,n%=v[i];l")
```
Uses a greedy algorithm.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 19 bytes
Prompts for desired amount and then for denominations expressed in smallest unit (pennies/cents).
```
⎕CY'dfns'
⎕ stamps⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9OSMxLz31/6O@qc6R6ilpecXqXEC2QnFJYm5BMZAFUvNfAQwgSrkMjYy5DBVMFQwNFIxMFUwNgAwgC4hNDcBsA4VHvXMVQoO5UHRZmFsCdRlB9Rng1ucNAA "APL (Dyalog Unicode) – Try It Online")
`⎕CY'dfns'` **C**o**p**y [the `dfns` workspace](http://dfns.dyalog.com/)
`⎕ stamps⎕` ask for inputs and use as arguments to [the `stamps` function](http://dfns.dyalog.com/n_stamps.htm)
] |
[Question]
[
Code-Golf caddy Eddie Brackets was getting tired of quine challenges, which appeared to be much too easy for the grand poobahs. He has this idea to spice up things and is sending quines to the car crusher.
**Challenge**:
Write a quine that prints itself "squeezed" for output purposes into an n x n square followed by that same square three more times, each time rotated **90 degrees to the right**, for a total of **4 squares**.
(By *squeezed* quine, Eddie means one that has all its printable characters but has all the white space (spaces, tabs, line feeds) removed. Of course, it may or may not work as a real quine after being squeezed, but it's what Eddie is talking about for his output.)
Example: If a solution quine in some language were: `A%C~?5 F$G &G52[/<`
its **Output** must be:
```
A%C~
?5F$
G7G5
2[/<
2G?A
[75%
/GFC
<5$~
</[2
5G7G
$F5?
~C%A
~$5<
CFG/
%57[
A?G2
```
**Rules**
1. All *whitespace* in the code **counts** toward the final byte count, but must be *removed* in the output squares. There must be at least 4 printable (i.e. visible, non whitespace) characters in the quine, i.e. a minimum of 16 printable characters output.
2. The four squares may be printed **either** horizontally **or** vertically, but **must** be separated by at least one space or delineating character(s) (horizontally) or at least one blank line or delineating character(s) (vertically). The first square is the "squeezed" program code (whitespace removed) printed n characters to a line. Nothing should appear *between* the output characters in each output square, which should each be a solid block of characters. Each square must contain all the printable characters of the quine.
3. Orientation of all characters in the rotated output remains just as it is in the code, e.g. < remains < and never changes to > or ^.
4. Code golf: shortest code in bytes wins.
In summary, your quine will have n^2 printable characters, and each of the four output squares will be n x n.
[Answer]
# [J](http://jsoftware.com/), 49 bytes
```
apply~'][:echo[:|:@|.^:(<4),~@7$''apply~'',quote'
```
[Try it online!](https://tio.run/##y/r/P7GgIKeyTj022io1OSM/2qrGyqFGL85Kw8ZEU6fOwVxFXR2qQl2nsDS/JFX9/38A "J – Try It Online")
The [standard J quine](https://codegolf.stackexchange.com/a/171826/78410) (26 bytes plus newline) is required to have even length because it is a string repeated twice. The square formatting and rotating 4 times do not fit into 36 bytes and therefore must be lengthened to 64 bytes.
This quine circumvents this even-length problem by using a built-in that works just like Jelly's `v` built-in: eval the string as a verb and feed one argument. The basis then becomes the following at **30 bytes**. (technically 29 because `[:` can be shortened to `@`, but we need to do something more on that string after all)
```
apply~'[:echo''apply~'',quote'
```
[Try it online!](https://tio.run/##y/r/P7GgIKeyTj3aKjU5I19dHcpV1ykszS9JVf//HwA "J – Try It Online")
Now we just need to insert **one** copy of the string manipulation code, which barely fits in 49 bytes without whitespace.
```
][:echo[:|:@|.^:(<4),~@7$'apply~',quote NB. the eval-ed string
quote NB. uneval the string; double each quote and surround with quotes
'apply~', NB. prepend this string
,~@7$ NB. equal to `7 7$`; format into a square (`_7]\` also works)
[:|:@|.^:(<4) NB. generate four rotations
[:echo NB. print the resulting 3d array of chars
NB. each matrix is printed with an empty line between them
] NB. a no-op padding to make 49 bytes
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes
```
“Ṿ;⁾v`s5ṚZ$3СYY¹¹¹¹¹¹”v`
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/dZP2rcV5ZQbPpw56woFePDEw4tjIw8tBMBHzXMLUv4/x8A "Jelly – Try It Online")
A full program that takes no arguments and prints itself formatted as a 5x5 square with its three 90° rotations. Note the 5 `¹` are just padding - the program would work without them but would give a 5x4 rectangle.
## Explanation
### Main link
```
“Ṿ…¹”v` | Evaluate the string as Jelly code, supplying itself as an argument
```
### Code within string
```
Ṿ | Uneval (wraps argument in “”
;⁾v` | Append "v`"
s5 | Split into pieces of length 5
$3С | Do the following three times, keeing all intermediate results as well as the start:
Ṛ | - Reverse
Z | - Transpose
Y | Join with newlines
Y | Join with newlines
¹¹¹¹¹¹ | Identity function (repeated 6 times)
```
Implicit print at the end.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
00"D34çý6ô4FD»,¶?øí"D34çý6ô4FD»,¶?øí
```
[Try it online.](https://tio.run/##MzBNTDJM/f/fwEDJxdjk8PLDe80ObzFxczm0W@fQNvvDOw6vxSX@/z8A)
**Explanation:**
```
00 # Push 00
"D34çý6ô4FD»,¶?øí" # Push this string
D # Duplicate this string
34 # Push 34
ç # Convert it to a character: '"'
ý # Join the stack with this character as delimiter:
# '00"D34çý6ô4FD»,¶?øí"D34çý6ô4FD»,¶?øí'
6ô # Split it into parts of size 6
4F # Loop 4 times:
D # Duplicate the current list of strings
» # Join it by newlines
, # Print it with trailing newline
¶? # And also print an empty line
# Then rotate it around 90 degrees clockwise, by:
ø # Zipping/transposing; swapping rows/columns
í # And then reverting each row
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~147~~ 121 bytes
```
s="a='s=%r;exec(s*4)'%s;*map(print,map(''.join,[*zip(*[iter(a)]*11),''])),;a=(11*('_'+a))[-11:0:-11];aaaaaaaaa";exec(s*4)
```
[Try it online!](https://tio.run/##RY3LCgIhFED/ZWC4jyy61GrELxGJSwgZ5Ii6mPp5q0V0FoezO@XZb2s@jdHcpA6am6uNW7xi4zPB3Cw/tGCpKXfzLYDDfU3ZeH6lguxTjxWVAouQAQhExqpDEUa4wE6J/F5kOS4fB6s/pv9kjDc "Python 3 – Try It Online")
prints in a 11x11 square.
## How it works:
* start from the quine `s="print('s=%r;exec(s)'%s)";exec(s)`
* `a='s=%r;exec(s*4)'%s` store our string in `a`
* `zip(*[iter(a)]*11)` split the string `a` in rows of 11 chars
* `*map(print,map(j,[* <...> ,''])),` display each row plus a newline
* `a=(11*('_'+a))[-11:0:-11]` rotates `a` and store the new value in `a`
* `;aaaaaaaaa` adjust the size of the square
* `exec(s*4)` execute the code 4 times, the `;aaaaaaaaa` transform the initialisation of `a` to avoid overriding `a` and keep it rotated
because of `a` is 121 char long, the result fits in a 11x11 box
] |
[Question]
[
Given a ASCII string containing control characters, compute what it should look like when printed to a terminal. Imagining the behaviour of a cursor, this is how to treat each character in the input:
* 0x08 backspace (`\b`): go left one (if already at the start of a line, do not go up)
* 0x09 horizontal tab (`\t`): go right one, and then right until the column number (0-indexed) is a multiple of 8
* 0x0A line feed (`\n`): go down one line and back to the start of the line
* 0x0B vertical tab (`\v`): go down one line without changing horizontal position
* 0x0D carriage return (`\r`): go back to the start of the line
* 0x20 space (): overwrite the previous character with a space, and go right one (This is the same behaviour as a normal character but it's here just for clarity)
* Any other printable ASCII character should be appended literally
* Any characters that aren't listed above (other control characters, NULL bytes, Unicode, etc.) will not be given in the input, so you don't have to handle them
Note: The behaviours above are those of modern terminal emulators; in the *olden days*, on a printer or teletype, `\n` would have done what `\v` does here, and `\v` would have moved the print head down so that the line number was a multiple of 8 (or however else the tab stops were configured). [More information](https://en.wikipedia.org/wiki/Control_character#Printing_and_display_control)
Since this is like a terminal or printer, you can assume the output will never be longer than 80 columns.
Gaps that were never printed on (because the cursor moved over it) should be filled in with spaces, but gaps that are further to the right than the cursor ever went should be stripped off.
If you try these in a shell (particularly those with `\b` and `\r`), the shell prompt may overwrite some of the text - try printing a newline afterwards or add a `; sleep 1` to see the effect properly.
Here is a reference implementation: [Try it online!](https://tio.run/##rVTLjpswFF3DV9wyqoBMMppUqhRFzSIkmceqm@7iqGOIGZgSg4whyVf1I/ph6fWDFqYjzaYLzLnHh3OPwbg6y6zkny5XMJqMICn3OX@eQyPTyUwxlz1LkT1UjWRBLQXOhnPXKRuJDCzA913nCjj99bNlcKRnKFEuGJUoBApxk6ZMjIHWdXNQlMyoBF5CkXPU50UBrGUCYgZFyZ8RoYDD7NZ1tGIBWx/8HYw0lfM9OyGH8JjvZWZgWgpIMiog52ASYkAnTw25wIwk9hVln58sYKqrFAzxBW71dN/fYcXAgRsHu@5rtfCblzLngYoZbuc6zw6utVQp34g/bNBfwutu7X/p1jXQXf9tIvov5c0Ysq/AFDOY2Ff2EWb9Dgd6CjQem/lQe9Vs3mXbanqHUuU@MJ2@Y/TOS3AdwWQjOBjd5ZjlBYNvolHNpTirCDU6C3r8nnNUBOjJTgmrJGy@3m2EKIXSxLhpf7hOhftHQn1TvDS1DKafwzE8dduftbQI6jB8uhGsKmjCAs/3xuB7fnjxPNdb4gV4Ea4KwiPCV6qUurSjvhO5NFVEpJIso9V6c2ckGt738cOgeDQOsTawY2QaWhCRmMQrM6PzCI3tGNkbEbYzEeuO4itrZFRgn5HmHpHWikmreTtG3eTaAuz@B4oOyq4RQhtPBf27tEFxP6weXpWPtqaAp8dZnx323zcnTF4DrSpR0iQzHMN/YpKURXPgePYccvwOH9R3@g0)
### Test cases
Input and output are given in C-style escaped string syntax. To clarify, your program does not need to interpret backslash escape sequences - the input will contain the literal control codes themselves.
```
Input Output
-----------------------------------
"" ""
"A" "A"
" " " "
"\n" "\n"
"A\nB\nC" "A\nB\nC"
"\t" " "
"A\t" "A "
"A\t\t" "A "
"\tA" " A"
"A\tB\tC" "A B C"
"ABCDEF\t" "ABCDEF "
"ABCDEFG\t" "ABCDEFG "
"ABCDEFGH\t" "ABCDEFGH "
"ABCDEFGHI\t" "ABCDEFGHI "
"\b" ""
"A\b" "A"
"A\bB" "B"
"A\n\bB" "A\nB"
"AB\b\bC" "CB"
"A\b " " "
"\r" ""
"A\r" "A"
"A\rB" "B"
"A\rB\rC" "C"
"ABC\rD" "DBC"
"A\rB\nC" "B\nC"
"A\n\rB" "A\nB"
"A \r" "A "
"A\t\r" "A "
"AB\vC\rD" "AB\nD C"
"\v" "\n"
"A\v" "A\n "
"A\vB" "A\n B"
"AB\vCD" "AB\n CD"
"AB\v\bCD" "AB\n CD"
"AB\v\rCD" "AB\nCD"
"AB\tC\rD" "DB C"
"AB\t\bC" "AB C"
"AB\b\t" "AB "
"ABCDEF\b\t" "ABCDEF "
"ABCDEFG\b\t" "ABCDEFG "
"ABCDEFGH\b\t" "ABCDEFGH"
"ABCDEFGHI\b\t" "ABCDEFGHI "
"a very long string that is approaching the 80-column limit\t!\n" "a very long string that is approaching the 80-column limit !\n"
```
## Rules
* You may input and output a list of ASCII integer code-points instead of a string
* You may use any [sensible I/O format](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
FS≡℅ι⁸M¬¬ⅈ←⁹M⁻⁸﹪ⅈ⁸→χ⸿¹¹M↓¹³Mⅈ←ι
```
[Try it online!](https://tio.run/##PY2xCsIwFEV3vyJkSqCCxaXGSe0iWBVdBOsQ07QNhETSpB3Eb4@xth3e8A6Hc1lNDdNUel9qA9BevZy9WiNUhTAGTScsqwE6mUIoKpEI7D1jtOEgISDTLUdHbfu7BR9HgBx4afH676wGJxPKNSiJwlc4qX9uBJJev4iqnvx4QcA5bFsEcwMnGg8ZkupOTXQ50D42zha8pE7aMSMC@nh/h5tt3ubPXQofft7KLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FS
```
Loop over the input string.
```
≡℅ι
```
Switch over the ordinal of the character, since Charcoal doesn't have ASCII control characters in its code page.
```
⁸M¬¬ⅈ←
```
For `\b`, move left if not already in the left column.
```
⁹M⁻⁸﹪ⅈ⁸→
```
For `\t`, move right until the next multiple of 8.
```
χ⸿
```
For `\n`, move to the start of the next line.
```
¹¹M↓
```
For `\v`, move down a line.
```
¹³Mⅈ←
```
For `\r`, move to the start of the current line.
```
ι
```
Otherwise just overwrite the character and move right.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~250~~ ~~246~~ ~~249~~ 248 bytes
Thanks to ceilingcat for the -4/-1, which exposed a logic error which is fixed.
Takes the original string and returns the processed string.
**Annotated version:**
```
p,q, // position, max length
i,
c,a; // current character, buffer
f(s,u)char*s,*u;{
for(u=a=calloc(strlen(s),9), // allocate a buffer able to handle all tabs
p=q=0;c=*s++;)
c-8? // backspace
c-9? // tab
c-10? // newline
c-11? // vertical tab
c-13? // carriage return
*u++=c,q=++p>q?p:q // default
// store and advance position, updating the maximum
:(u-=p,p=0) // carriage return
// reset position, not updating the maximum
:(*u++='\n',memset(u,' ',p),u+=p) // vertical tab
// store newline and p spaces
:(*u++='\n',p=q=0) // newline
// store newline and reset position and maximum
:(i=8-p%8,i+p>q?u=memset(u+(q-p),' ',p+i-q)+(p+=i)-q,q=p:(u+=i,p+=i)) // tab
// advance position, adding spaces to the end if needed
:p&&u--+p--; // backspace
// retreat position if not at start
s=a;
}
```
```
p,q,i,c,a;f(s,u)char*s,*u;{for(u=a=calloc(strlen(s),9),p=q=0;c=*s++;)c-8?c-9?c-10?c-11?c-13?*u++=c,q=++p>q?p:q:(u-=p,p=0):(*u++=10,u=memset(u,32,p)+p):(*u++=c,p=q=0):(i=8-p%8,i+p>q?u=memset(u+q-p,32,p+i-q)+(p+=i)-q,q=p:(u+=i,p+=i)):p&&u--+p--;s=a;}
```
[Try it online!](https://tio.run/##pVXfb5swEH7PX3HLtAYCTOn6ksJoVZJtrVRtT3sa1QoOaawRMLZJNVX515f5ByaQpA/TkGLfnb@7831cDuQ9IbTbEbdysYvcJFhazK1ttEromLnjOnhZltSqwyRESZ6XyGKc5llhMdu9tF0SVuEkQOGYOU5gI296jbxL8TufyOVcLhfX49pxQuRWoeOQq@qa@JVv1V5IhPfE9i11fD5x63CdrVnGrdq9@OAS2yHmEOk8QsXh1CPvpi5WkfYeTuUR5eVgr7Idizghtr1K5CQil1BcZbF9cnZWe55DPC9gYRJsd29xgfJ6kcFHxhe4fL@6GvRMOU6lbbAp8QIIxQX/icqC0zK3xM44SKZgzGx4GQCQmkvdGj2O7EDokrtAnAYgCLKFAYA9Y4GxjAcASlgGozgd@Tr@0hrGcTq0A0hplvwKuiDeA/HToKIHKk6DNj3Q5jSI9kD0ALTIlkmdc7@tWtSkT7aaCmYNH4XPYDsYiBiwTnBhSR515Zq4hNIfD6FmAmA4dGF4IxeQi7i81OMiiouZMnBtMJsWYn7T6FHMFe4mms0/fW5gSv4iFZOlMd32ALd3TbRUBzNb1NzBSFGcxumsOdTXpFqjnQwxbfxoFFNzp5jOW2MxM3EbJJgwvBGieGM8xAtSR5tuhk3UwuZGEjfby7SVeZtayOb2spAOAVo7oKgPEYylh5z1vBLYZPQ35GXxBGJQYLHxVcIBM0gIoWWCVtqWwXTioTKv1wXkeI3Fm3wj37YJJDlWnCvWG@vX7/f3ur9c@Z8atE1U1ly02z/0ETSPJv5Y7p4b@aYLiJq9021NBE0MHDdbL6ehr2Nrr2waTu2zqK2iD1CZ55HaOt0UdRIflyeAc33nlhIwu@mmQlQ1b@W9qKV51Cv8SD4q/JCWffGnifj/VtIBeu3UI2bfRqqF5IyW4wmLLxnIcYQfAsBiXDfz2QzAu0L0mA/DZsb1vwXaz1YB9y7fVF/68IoTC5fG8dBzpiGvpWsavpNRTVvv6DHuS5pllh7P28F29wct8@SJ7bznvw "C (gcc) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 140 bytes
```
s=>[l=[],...s.flatMap(n=>(p=n>31,c={8:c&&c-1,9:c+8&-8,11:c}[n]||p*c,p?l[c++]=n:(F=t=>t?F(--t,l[t]||=32):l)(c),9<n&n<12?[F(c,l=[])]:[]),c=0)]
```
[Try it online!](https://tio.run/##pVXBcpswEL3zFaoOjkiAxM7FcSJ7jB236UybQ47ATEDFNhlZMEKhzcT5dlcgjKWWmR6qA2j37eq9lRbxEldxSXhWCJflP9LDGh9KPA0oDiLH87zSW9NYfIsLxPAUFZhNr4cOwe/jCRkMiDt0bibkYjxwx85wOCEfAYv2@@KcOMWMBuTiIsJsglZY4KmYrZDrCocGIsL1Y7@/HtkTaiNiOzd3bMDuhqNZsELEqbntaCIfkunKjg4iLQWJy7QEGDwJnrGNx@Ofz9YDK14FOI3HV3FyWO6/hwUhMAaEFpybPmlbEPzhA9IXMsNZ2zI5ZH7IFrBLbm0ZLszwblInGRicG5AOdpCWHQpDcTefq3Q/FJqcduK371rY3F8s71cdS2sr9mb6@YgdbQ360mKdrZfVuh5UzMnWtCfwr@03fVCVkfiaE/pqp3Vvs9MNaZiEyanihYpN9BNUx8d7qHkPNe@h5n7INQ5VbMiXJzlLf3GM1Nqh7YVaO@/RDgwB0m47gMP@5vDDSmOtbbZszjSsenuzMssLmSKojAprt39cXauoXl12zLKF5CYbxBrCTeQICF3r0tc7UNaondnc16FE@wCO0Km9OrivbxOz84y@VVhnG/3aYH39GoMq5W@A5mwDyuYmAmIbC5CVIC4Knsdkq3wpGF@5JKevOwZotsvkV/ypvjD@YwUlol7FevZk5g7ZXlnQTKCzkJ3JOc1Iika2t5O3NQV4CqicCrJFl9A7n8HLjW3fWt1d6q1zfi/ZEAqy@h51QPqrSImI7Dr13QIgV9cpBl@fHr97Smy2fkNrFMg/Q1rFFDWZdtRQZnVe5pFtzBfyTzIXyLZbMXjaXttrnu8WbQCSi1AZ8ZJnTJUg5QFAclbmNPVovkFKEcC41eK0bxn4Yd8efgM "JavaScript (Node.js) – Try It Online")
Tio link use `l[t]=l[t]||32` since the node version is a bit old. Changing to `l[t]||=32` should work for newer version.
Input an array of integers. Output an array of array of integers.
```
s=>[
l=[], // l is current line, output first line (may be modified later)
...s.flatMap(n=>( // for each char
p=n>31, // p: is printable?
c={ // c: position (column) of cursor; adjust cursor
8:c&&c-1, // chr(8): move left
9:c+8&-8, // chr(9): tab
11:c // chr(11): no move
}[n]|| // based on current char
p*c, // for other printable chars, keep cursor original position
// for other control chars, move corsor to beginning
p?
l[c++]=n: // printable, print
(F=t=>t?F(--t,l[t]||=32):l)(c), // control char, fill gaps with spaces
9<n&n<12? // shall we move to next line?
[F(c,l=[])]: // output the next line
[] // output nothing
),c=0 // cursor start with 0
)]
```
] |
[Question]
[
# Follow the Path
I got directions to my friend's house, but it looks like his map might have some mistakes. He's expecting me soon, so I need some short code to figure out if I can get there.
# The Challenge
The code should, when given an ASCII representation of a path as input, traverse from the start to the end, and output depending on whether there is a valid path.
# Input
Input is an ASCII representation of a map. It will use only the following symbols:
```
Character = Meaning
(space) = Blocked area
| = Vertical Path
- = Horizontal Path
+ = Intersection
^ or v = Horizontal Bridge
< or > = Vertical Bridge
$ = Start Location
# = End Location
```
# Traversal Rules
* Execution always starts on `$` and will end when all paths are blocked, an infinite loop, or the pointer hits `#`. It is guaranteed that input will have exactly 1 of each.
* The pointer starts moving to the right and down.
* Vertical paths will only connect to vertical paths, vertical bridges, or intersections.
* Horizontal paths will only connect to horizontal paths, horizontal bridges, or intersections.
* If a vertical and horizontal path meet at a non-bridge, it is considered blocked at that point.
* Bridges function according to the following:
```
| |
-^- OR -v- = Horizontal path going over a vertical path
| |
| |
-<- OR ->- = Vertical path going over a horizontal path
| |
```
* When the pointer hits an intersection, movement precedence is in the clockwise direction (up, right, down, left). The pointer will not go back the way it came.
* The program must detect/calculate infinite loops and branching paths from `+`.
# Output
The length of the path, or `-1`, according to the following conditions:
* If the program reaches `#`, output the path length.
* If the program detects only blocked paths, return `-1`.
* If the program detects an infinite loop, return `-1`.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
# Test Cases
```
$
|
+-|
#+-+
= 6 (going north at `#+-` will lead to a blocked path, but going to the west is a valid path)
#-+-+
| |
$-^-+
+-+
= -1 (Will infinitely loop)
$#
= 1
#^^^^+
>
$----^-+
> +
+-+
= 20
$------+
|-----+|
--#--+|
+--+---+
+------+
= 23
$ #
= -1 (Blocked by the space)
$|#
= -1 (Can't go onto a vertical path from the sides)
$
-
#
= -1 (Can't go onto a horizontal path from the top or bottom)
$|#
|--|
++++
= -1 (No valid paths exist)
```
[Answer]
# JavaScript (ES6), 219 bytes
Takes input as a list of lists of characters.
```
a=>((g=(X,Y,D,n=o=0)=>!(a+0)[n++]|a.some((r,y)=>r.some((c,x)=>D=='975'[i='-| #+$'.indexOf(c),x-X+1]-'450'[y-Y+1]?i-3?i-2?i>3?[3,0,7,4].some(d=>D^d^4&&g(x,y,d,n)):~i&&i^D&1?0:g(x,y,D,n):0:o=-n:X+1|i<5?0:g(x,y,2))))(),~o)
```
[Try it online!](https://tio.run/##hZFfa4MwFMXf@ykyFU1Irth/lMmiL33fa4soiNqS0SWjHcNC6Fd3aTtKdGwe8OGce/O7ufGt/CpP1VF8fIJUddPteFfyBOM9xxu2ZWsmueIR4ckTLmlEMklprsvwpN4bjI/sbCrHH1ex1rg158HzahlkggegkUu9IBSybtrXHa4Ia2FDpzkEi2UUZGfYGpMKmJtvlopknmZzFrEVW@R3aG2ARV0sfH@PW3ZmNZOExBfh@6JY@9M0iu@5uSeJo1hxkLEZoMXL8lGbESNM2EWRrlLypA5NeFB7vMPZBKEsDEMHIeQ5ObOsti0F27oUqJNPckImf@BcuLVYPN0DelAM6qNIzx0ZWRhRQ@ptgVDSizwwGs6@dqFf0fiN4Cb7oL4nvbcDcAcRNX5wkD5Y/05EI4/g6bEGaybYv3Sci3pr9vYxuloD6L4B "JavaScript (Node.js) – Try It Online")
### How?
Because they need to be tried in a specific order, the way the directions are handled in this code is a bit unusual.
Given a direction \$D\$ and the source coordinates \$(X,Y)\$, we want to figure out which target coordinates \$(x,y)\$ correspond to a move by one square along \$D\$.
We use the following test for each candidate pair \$(x,y)\$:
```
D == '975'[x - X + 1] - '450'[y - Y + 1]
```
This test always fails if \$|x-X|>1\$ or \$|y-Y|>1\$ because we get an undefined value from at least one of the 2 lookup strings.
Otherwise, we have the following table:
$$\begin{array}{r|c|ccc}
&x-X&-1&0&+1\\
\hline
y-Y&&9&7&5\\
\hline
-1&-4&5&3&1\\
0&-5&4&2&0\\
+1&-0&9&7&5
\end{array}$$
Because diagonal moves are not used, our final compass looks as follows:
$$\begin{array}{cccc}
&&3\\
&&↑\\
4&←&2&→&0\\
&&↓\\
&&7
\end{array}$$
The lookup values were chosen in such a way that we end up with some handy properties:
* Opposite directions can be detected by testing if \$d\operatorname{xor}d'=4\$. Hence the code to try all directions in clockwise order except the one that would make us going back the way we came:
```
[3, 0, 7, 4].some(d => D ^ d ^ 4 && g(x, y, d, n))
```
* Vertical moves are connected to odd values.
* Horizontal moves are connected to even values (except direction \$2\$, for no move at all, which is only used at the beginning of the process when the starting point has been identified).
[Answer]
# Python3, 934 bytes:
```
E=enumerate
V=lambda b,X,Y:0<=X<len(b)and 0<=Y<len(b[0])and b[X][Y]!=' '
def U(D,x,X):D[x]=D.get(x,[])+[X];D[X]=D.get(X,[])+[x]
def f(b):
m,W=[[0,1,'-^'],[1,0,'|>'],[0,-1,'-^'],[-1,0,'|>']],{'^':'-','>':'|'}
x,y=[[x,y]for x,r in E(b)for y,t in E(r)if'$'==t][0]
q,D=[(x,y,0,not V(b,x,y+1))],{}
while q:
x,y,p,l=q.pop(0)
if'#'==b[x][y]:return p
if b[x][y]in'>^':
for j,k,I in[(X,Y,i)for i,(X,Y,u)in E(m)if b[x][y]in u]+[(m[l][0],m[l][1],l)]:
if(x+j,y+k)not in D.get((x,y),[])and(b[x+j][y+k]in'>#^+'or b[x+j][y+k]==W[b[x][y]]):U(D,(x,y),(x+j,y+k));q+=[(x+j,y+k,p+1,I)];break
elif'+'==b[x][y]:
T,O=[0,1,2,3],[]
for i in T[l:]+T[:l]:
if V(b,X:=x+m[i][0],Y:=y+m[i][1])and(X,Y)not in D.get((x,y),[]):
if'#'==b[X][Y]:return p+1
O+=[((X,Y),i)]
if O:U(D,(x,y),O[0][0]);q+=[(*O[0][0],p+1,O[0][1])]
elif V(b,X:=x+m[l][0],Y:=y+m[l][1])and b[X][Y]in(m[l][2]+'#+'):U(D,(x,y),(X,Y));q+=[(X,Y,p+1,l)]
```
[Try it online!](https://tio.run/##dVNNc9owED3Xv0KNmZEVrTMY8ulEnMghl3JJExhVdPBgGgdjjDFTmLq/PV1JxqUzrg6S9mm1@96ulB/Kt3XWv82Lj49HEWe7VVzMyth5EelsFc1nJIIxTMLugxg/pHHmRWyWzQmaE2vKrjJIJMdKTtRnQQl15vGCfPWGsIcxC4dyr8Tw4kdcenuQinH0vB/iVINjC@6VubbADKFDVvAqpOxCANSfUgUygC7QaqC3XfAb2G9wBb/olIbUp0AHuFb0t0P2cMAwOKvFukCrIElGHjGFNg9QWrNgyYJ2qBClQjkO2cBQSCR7wNjZuiQvXoRSDjxgDLNg2J9vSRqTDfLUGSCHVGwu8nXudRlCGMzFYBFKkgcVFnG5KzKSmxNSo0lGB8gWMaKpvMMSnpCMxGpMIDH0EjDGjhmOK3Z6mewUl95KppowmDVQkDJlImIeb8/fkfGSaf7ob0utNTFdbuwYtg59MBxfGjbulFPMeoIK8SrrjIqFup/2fhOb3W@4LpQ1IecBPDF1HxXxbEnsQDpxigXhJwXRFJ9hJEx7e9DHNqpjIRJN9lmmoeLPMkwbPaYH41Ds@UomRvQkFAdrBFYPFus/am2Qv30xL7XpCw/s8UhrMVGwAYYQph2d6B5hWv3crerz2jSyzR55qFrvKd30lG56pHv8MElm29hTnLqc/lNnzaXOpl@CToQt/tDfpFx/j9azYu7NUd2nWoqU54lqqrhI0jIuvC/rLAYyv9jmaVJ69FtG8RU7zjYggpydnWmdHT1V2CvuV47Lfe7og21P6MX1NaDPK6fjT82@celrl46r98720vpPcXDTeRwD/QY6Pg5700D1polyZS4aLx@xyq6VQ3zfNRuOszniRx9z79pK6BBDYHtTm5U1b21Ux3esfWftytUJMCYOEyYvkqz0Fl5T0i3@c9YC99rhfjt82Q5ftcPX7fBNO3zbDt8h/PEH)
] |
[Question]
[
What general tips do you have for golfing in [Grass](http://www.blue.sky.or.jp/grass/)? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Grass (e.g. "remove no-op characters" is not an answer).
Please post one tip per answer.
[Answer]
# Define λx.f x instead of copying f
In Grass you could usually copy something to the top of the stack to reduce the length of code referring to them.
But instead of defining the identity function and applying it:
```
wvWwwwww
```
You could define a new function that calls the original function instead:
```
wWWWWWw
```
Depending on the surrounding code and the number of items to be copied, it could be sometimes longer than the copying code. But it would likely still save you characters because it has one less item in the stack, and makes all references across this point shorter.
It doesn't work for characters that you would apply Out or Succ on them. It also cannot be used in a function. But it's likely you'll find other workarounds and make it still shorter.
[Answer]
# Hide intermediate values in a function
For the intermediate values in a chain of statements that only one final result is useful afterwards, you could hide all the intermediate values in a function, to not use spaces in the main stack.
If the function is pure (doesn't involve I/O), and the argument isn't used, instead of defining the function and immediately calling it, you could save one item in the stack by defining the function to apply the argument as a function to the supposed return value and delaying the call to where it is used.
That is, for such a function, its application and further uses of its return value:
```
w WWwwww WWWw WWWWw v
Ww
WWWw WWWWww
```
Apply the argument to the supposed return value in the end of the function, remove the application, and swap the function and the argument when you need to use the supposed return value later:
```
w WWwwww WWWw WWWWw WWWWw v
Www WWwww
```
If you try them as full programs, they give different results, because the function calls Out which isn't pure, and they ran twice for the two calls.
[Answer]
# Fluent interface for printing
It's often more useful to make the output function return itself, instead of the outputted character, when you are writing programs to print a block of hardcoded text. You could do this by quining:
```
ww WWWw WWWwww v a = λf.λx.(Out(x);f(f))
Ww Out2 = a(a)
```
] |
[Question]
[
**Contest Finished! Read comments on blobs to view their score.**
This KoTH is loosely inspired by [Primer's Natural Selection Simulation](https://www.youtube.com/channel/UCKzJFdi57J53Vr_BkTfN3uQ). Your bot is a blob. In order to survive, you must eat pellets to regain energy, which is used to move. With extra energy, blobs can split into two.
### Energy and Movement
Your blob starts off each round with 100 energy, and it has no limit on the amount of energy it can collect. Each round is run in turns, with each blob having the option to move North, East, South, or West in any given turn, or stand still. Moving uses 1 energy, and standing still uses 0.25 energy. The map's side length is `ceil(0.25 * blobCount) * 2 - 1` units, with a minimum of 9 units. All blobs start on the edge of the map, with one placed in each corner and every subsequent blob being placed 2 units away from any others. Every 30 turns, a wave of pellets are placed in random spots around the map, at least 1 unit from any edge. Each time a wave of pellets appears, the quantity of pellets (originally twice the number of blobs or the width of the map, whichever is larger) in the next wave is decreased by 1, forcing the number of blobs to decrease over time. Each pellet restores between 5 and 15 energy. When a blob's energy is less than or equal to 0, it dies.
### Eating
If two or more blobs attempt to occupy the same location, the one with the most energy will eat the others, receiving their energy. If both have equal energy, both vanish.
### Detection and Information
Blobs can see any pellets or other blobs within a distance of 4 units. When their functions are called, blobs are provided with:
* The side length of the map
* The position of the blob on the map
* The positions of all pellets within their search radius, as well as their values
* The positions of all blobs within their search radius, as well as their energy and UIDs
* The energy, UID, and locations of the blob whose function is being executed
* A storage object unique to the blob
* A storage object shared by all blobs related to the blob through splitting
### Splitting
If a blob has more than 50 energy, it can choose to split. Splitting costs 50 energy, and any remaining energy is divided evenly between the two blobs. All blobs are either originals or split copies, with every copy tracing back to an original. All of these together are "relatives." All relatives have one communal storage object. Relatives can still eat each other, and can split, use their own storage object, or collect energy without affecting others.
### Energy Transfer
If two blobs are next to each other (after moving), one of the bots can transfer energy to the other. This is done by returning `SendNorth(amt)`, `SendEast(amt)`, `SendSouth(amt)`, or `SendWest(amt)`, with `amt` being a number representing the amount sent. This can be any amount that the sender can afford, including all of their energy. It is recommended that the blob who is receiving energy is told to stay still through communal storage, so that it does not move away when the energy is being transferred (though the energy would not be deducted from the sender's total in this case).
### Functions, Storage, and UIDs
In order to allow more complex learning behaviors, all blobs will be given an integer UID (Unique Identifer). These UIDs will be randomly generated each map, preventing strategies based on individual targets. When a blob's function is called, it is passed four arguments:
1. The side length of the map as an integer
2. An object with two arrays: `pellets`, and `blobs`. Both arrays contain objects, both having a `pos` property containing the pellet or blob's position formatted as `[x,y]`. Pellets will have an `energy` property, while blobs will have a `uid` property and an `energy` property
3. An object containing various properties of the blob it is passed to: `energy`, `uid`, and `pos`. The `pos` array is formatted as `[x,y]`
4. An object containing the two storage objects of the blob. A `self` property contains an individual storage object which can be modified however the blob sees fit (by manipulating properties of the object that is passed), and a `communal` property which can be modified by any relative.
Blobs are not moved immediately to prevent earlier/later turns having an advantage. All movements are processed in groups (All collisions/eating, then all pellets, then splitting, etc.) If a blob lands on a pellet or smaller blob and, in the process uses its last energy, the blob will still consume the pellet/energy independent of whether that would would bring its total energy above 0.
In order for relative blobs to recognize one another, the communal storage must be used for each blob to record its UID in an array, or through some other system.
### Return Values
In order to move or split, the return value of the function is used. First, the meaning of the cardinal directions in terms of coordinates:
* North = -Y
* East = +X
* South = +Y
* West = -X
Note that `[0,0]` is the *top left corner*, and Y increases as you go down. The return value of the function should follow these rules:
* **To do Nothing:** Return nothing, 0, null, undefined, false, or any other value that equates to false
* **To Move:** Return one of four global variables: North, East, South, or West, which equate to "north", "east", "south", or "west" (which could also be used as a return value)
* **To Split:** Return the global variable SplitNorth, SplitEast, SplitSouth, or SplitWest, the direction indicating where to place the new blob
If a split command is returned and the amount of energy required is greater than or equal to the energy of the blob, nothing will happen. Blobs will not be able to leave the map.
### Predefined Library Functions
There are a few basic functions available by default, to save some time:
**taxiDist(pt1, pt2)**
Returns the taxicab distance between two points (X distance plus Y distance).
```
taxiDist([0, 0], [2, 2]) //4
taxiDist([3, 4], [1, 5]) //3
taxiDist([1.25, 1.3], [1.3, 1.4]) //0.15
taxiDist([0, 0], [5, 2.5], 2.5) //3
taxiDist([0, 0], [2, 4], 2.5) //2.4
```
**hypotDist(pt1, pt2)**
Returns distance between two points according to the pythagorean theorem
```
hypotDist([0, 0], [5, 12]) //13
hypotDist([4, 6], [8, 9]) //5
hypotDist([0, 1], [2, 1]) //2
hypotDist([1, 1], [2, 2]) //sqrt(2)
```
**modDir(dir, amt)**
Takes the inputted direction, rotates 90 degrees clockwise `amt` times, then returns the new value.
```
modDist(North, 1) //East
modDist(East, 2) //West
modDist(West, 3) //South
modDist(South, 4) //South
```
### Example Blob
This blob will not move until it finds a pellet nearby. Then, it will move in the direction it thinks is most likely to reward it. If its energy is ever above 150, it will split.
```
function(map, near, me, storage) {
if (me.energy > 150)
return SplitNorth;
if (!near.pellets.length)
return null;
var dirs = [0, 0, 0, 0];
for (let p, i = 0; i < near.pellets.length; i++) {
p = near.pellets[i];
dirs[0] += me.pos[1] - p.pos[1];
dirs[1] += p.pos[0] - me.pos[0];
dirs[2] += p.pos[1] - me.pos[1];
dirs[3] += me.pos[0] - p.pos[0];
}
return [North, East, South, West][dirs.indexOf(Math.max(...dirs))];
}
```
### Rules
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are prohibited. Also, no Unstandard Loopholes.
* No blob may attempt to modify or read any data not passed to it via its parameters
* No blob may attempt to modify a return-value variable to sabotage other blobs
* A round lasts until the only remaining blobs are relatives
* No blob may modify data by injecting functions into its parameters which modify values using the `this` keyword
* All submissions must either be in Javascript or a language which is not too different from Javascript (Python, for example). All answers will be converted to Javascript for the competition.
* The winner is the blob which has collected the highest amount of energy in total across all rounds (from either pellets or consuming smaller blobs that are not relatives)
**Controller:** <https://gist.github.com/Radvylf/1facc0afe24c5dfd3ada8b8a2c493242>
**Chatroom:** <https://chat.stackexchange.com/rooms/93370/hungry-blobs-koth>
[Answer]
# Introvert
The Introvert doesn't like other blobs. When it sees an unrelated blob, it eats it if it can, and begrudgingly accepts its presence it if it can't, though running away if it sees signs of aggression. When it sees a *related* blob, it distances itself. However, it can't help but split apart a lot.
### Technical Details
The core feature of this blob is to split apart and spread out so as to maximize the combined vision of the blobs. It also employs a system to prevent two of them from competing over a pellet.
```
function introvert(mapSize, vision, self, storage) {
if (!storage.communal.friends)
storage.communal.friends = {};
if (!storage.communal.claims)
storage.communal.claims = {};
storage.communal.friends[self.uid] = true;
for (var i in storage.communal.claims)
if (storage.communal.claims[i] === self.uid) {
storage.communal.claims = {};
break;
}
var food = {};
for (var p of vision.pellets) {
var score = p.energy - taxiDist(p.pos, self.pos);
if (score > 0)
food[p.pos] = score;
}
var danger = {};
for (var i = 0; i < mapSize; i++) {
danger['-1,' + i] = true;
danger[mapSize + ',' + i] = true;
danger[i + ',' + mapSize] = true;
danger[i + ',-1'] = true;
}
var relatives = {};
for (var b of vision.blobs) {
if (b.uid in storage.communal.friends) {
relatives[b.pos] = true;
} else if (!storage.self.justSplit && b.energy < self.energy - taxiDist(b.pos, self.pos) * 0.75) {
var score = b.energy - taxiDist(b.pos, self.pos) * 1.25;
if (score > 0)
food[b.pos] = score;
} else {
danger[b.pos] = true;
danger[b.pos[0] + ',' + (b.pos[1] - 1)] = true;
danger[b.pos[0] + 1 + ',' + b.pos[1]] = true;
danger[b.pos[0] + ',' + (b.pos[1] + 1)] = true;
danger[b.pos[0] - 1 + ',' + b.pos[1]] = true;
}
}
storage.self.justSplit = !danger[self.pos] && self.energy > 150;
function fromData(n) {
return n.split(',').map(s => parseInt(s));
}
function fs(f) {
return food[f] / taxiDist(f, self.pos);
}
var target = Object.keys(food).filter(f => !(f in storage.communal.claims)).map(fromData).sort((a, b) => fs(b) - fs(a))[0];
if (target)
storage.communal.claims[target] = self.uid;
function ms(m) {
if (danger[m])
return 99999999;
var dists = Object.keys(relatives).map(r => hypotDist(fromData(r), m));
return (target ? taxiDist(target, m) : 0) - (dists.length ? dists.reduce((a, b) => a + b) / dists.length : 0);
}
var candidates = [
{p: self.pos},
{p: [self.pos[0], self.pos[1] - 1], d: storage.self.justSplit ? SplitNorth : North},
{p: [self.pos[0] + 1, self.pos[1]], d: storage.self.justSplit ? SplitEast : East},
{p: [self.pos[0], self.pos[1] + 1], d: storage.self.justSplit ? SplitSouth : South},
{p: [self.pos[0] - 1, self.pos[1]], d: storage.self.justSplit ? SplitWest : West}
];
if (storage.self.justSplit)
candidates.shift();
return candidates.sort((a, b) => ms(a.p) - ms(b.p))[0].d;
}
```
[Answer]
## Animated Meal
A simple bot, just to start off the competition. Finds the nearest coin, and goes toward it. Based off the example bot.
```
function(map, near, me, storage) {
var targs = near.pellets.map(el => taxiDist(el.pos, me.pos));
var targ = near.pellets[targs.indexOf(Math.max(...targs))].pos;
if (targ[0] == me.pos[0])
return targ[1] < me.pos[1] ? North : South;
return targ[0] < me.pos[0] ? West : East;
}
```
[Answer]
# bloblib tester
```
function(map, near, me, storage) {
// BlobLib, the main purpose of this post
const bloblib = {
// Returns only pellets and blobs that are within the immediate neighbourhood (within 1 space of) me
getNeighbours: (known) => {
let neighbours = {};
neighbours.pellets = known.pellets.filter(x => x.pos[0] >= me.pos[0] - 1 && x.pos[0] <= me.pos[0] + 1 && x.pos[1] >= me.pos[1] - 1 && x.pos[1] <= me.pos[1] + 1);
neighbours.blobs = known.blobs.filter(x => x.pos[0] >= me.pos[0] - 1 && x.pos[0] <= me.pos[0] + 1 && x.pos[1] >= me.pos[1] - 1 && x.pos[1] <= me.pos[1] + 1);
return neighbours;
},
// Gets the blob or pellet at the given location
getByPos: (pos, known) => {
let pellets = known.pellets.filter(x => x.pos[0] == pos[0] && x.pos[1] == pos[1]);
let blobs = known.blobs.filter(x => x.pos[0] == pos[0] && x.pos[1] == pos[1]);
if (blobs.length) return blobs[0];
if (pellets.length) return pellets[0];
return null;
},
// Returns a 2d array of size, containing any known blobs or pellets
areaMatrix: (size, known) => {
let matrix = [];
for (let x = 0; x < size; x++) {
let row = [];
for (let y = 0; y < size; y++) {
let realPos = [me.pos[0] - (x + Math.floor(size / 2)), me.pos[1] - (y + Math.floor(size / 2))];
row.push(getByPos(realPos, known));
}
matrix.push(row);
}
return matrix;
},
// Gets a cardinal direction pointing from from to to
cardDirTo: (to, from = me.pos) => {
let diff = bloblib.multiDist(from, to);
if (diff[0] == 0 && diff[1] == 0) return null;
if (Math.abs(diff[0]) > Math.abs(diff[1])) {
// Gunna be east or west
return diff[0] > 0
? East
: West;
} else {
return diff[1] > 0
? South
: North;
}
},
// Returns a vector of the X and Y distances between from and to
multiDist: (from, to) => {
return [to[0] - from[0], to[1] - from[1]]
},
// Gets the closest object in objs to position to
getClosest: (objs, to = me.pos) => {
if (!objs || !objs.length) return null;
let sorted = objs.concat().sort((a, b) => taxiDist(a.pos, to) - taxiDist(b.pos, to));
return sorted[0];
},
// Should be run at startup. Calculates which directions are unsafe to move in
dangerSense: (origin) => {
let neighbours = bloblib.getNeighbours(near);
let matrix = bloblib.areaMatrix(3, neighbours);
if (me.pos[1] == 0 || (matrix[1,0] && isThreat(matrix[1,0]))) bloblib.unsafeDirs.push(North);
if (me.pos[0] == map - 1 || (matrix[2,1] && isThreat(matrix[2,1]))) bloblib.unsafeDirs.push(East);
if (me.pos[0] == 0 || (matrix[0,1] && isThreat(matrix[0,1]))) bloblib.unsafeDirs.push(West);
if (me.pos[1] == map - 1 || (matrix[1,2] && isThreat(matrix[1,2]))) bloblib.unsafeDirs.push(South);
},
isThreat: (blob) => {
if (!blob.uid) return false;
if (storage.communal.blobs.includes(blob.uid)) return true;
return blob.energy >= me.energy - 1;
}
// Attempts to move in the given direction
// Rotates the direction 90 if it can't safely move
attemptMove: (dir = North) => {
for (let i = 0; i < 4; i++) {
if (bloblib.unsafeDirs.includes(dir)) dir = modDir(dir, i);
else return dir;
}
return null;
},
// Attempts to split in the given direction
// Rotates the direction 90 if it can't safely split
attemptSplit: (dir = SplitNorth) => {
for (let i = 0; i < 4; i++) {
if (bloblib.unsafeDirs.includes(dir)) dir = modDir(dir, i);
else return dir;
}
return null;
},
// Returns the next direction in which to move toward pos
// Don't bother checking if we have enough energy, because if
// we have < 1 energy we're basically dead anyway
moveTo: (pos) => {
return bloblib.performAction(bloblib.attemptMove(bloblib.cardDirTo(pos)));
},
// Simply registers the action in communal history, then returns it unmodified
performAction: (action) => {
storage.communal.history[me.uid].push(action);
return action;
},
// Stores directions in which there is another blob
// This wouldn't make sense to store across turns, so we don't bother
unsafeDirs: []
};
bloblib.dangerSense(me.pos);
// Register this blob
if (!storage.communal.blobs) storage.communal.blobs = [];
if (!storage.communal.blobs.includes(me.uid)) storage.communal.blobs.push(me.uid);
// Register history for this blob
if (!storage.communal.history) storage.communal.history = {};
if (!storage.communal.history[me.uid]) storage.communal.history[me.uid] = [];
// Split if we can and there are fewer than 10 blobs in our community
if (me.energy > 150 && storage.communal.blobs.length < 10) {
let split = bloblib.getSplit();
if (split) return split;
}
// If we can't see any pellets or blobs, don't do anything
if (!near.pellets.length && !near.blobs.length) return null;
// Move toward the nearest pellet
return bloblib.moveTo(bloblib.getClosest(near.pellets));
}
```
The actual bot is fairly simple, but this is more designed as a proof of concept of `bloblib`, a collection of functions and functionality I plan to use and develop across other bots (feel free to use/expand on it yourself too)
In short, this bot does the following:
```
If energy > 150 and blobs_in_team < 10: Try to split
If visible_pellets = 0 and visible_blobs = 0: do nothing
Move toward the closest pellet in a safe way
that avoids moving into other stronger or equal blobs
or off the edge of the map
```
[Answer]
# Greedy Coward
```
import random
def greedy_coward(map_length, near, me, storage):
interesting_objects = [] #objects I can eat
bad_objects = [] #objects that eat me
allowed_directions = ["North", "East", "South", "West"]
# add pellets to objects that I'm interested in
for i in near.pellets:
interesting_objects.append(i)
# figure out which blobs are good and which are bad
for i in near.blobs:
# if I'm under or equal powered, add it to bad_objects
if i.energy >= me.energy:
bad_objects.append(i)
# if I can eat it, add it to interesting objects.
else:
interesting_objects.append(i)
# if there are any bad objects, process them.
if not len(bad_objects) == 0:
# find the nearest bad object and make sure I don't move towards it
bad_objects_distances = []
for i in bad_objects:
bad_objects_distances.append(taxiDist(i.pos, me.pos))
worst_object = bad_objects[bad_objects_distances.index(min(bad_objects))]
# find the direction of the worst object
bad_object_xy_distance = [worst_object.pos[0] - me.pos[1], worst_object.pos[1] - me.pos[1]]
closest_number = min(bad_object_xy_distance)
bad_object_direction_vague = [["West","East"],["North","South"]][bad_object_xy_distance.index(closest_number)]
if closest_number < 0:
bad_object_direction = bad_object_direction_vague[1]
else:
bad_object_direction = bad_object_direction_vague[0]
# remove bad object direction from allowed directions
allowed_directions.remove(bad_object_direction)
# process interesting objects if they exist
if not len(interesting_objects) == 0:
# find the nearest interesting object
interesting_objects_distances = []
for i in interesting_objects:
interesting_objects_distances.append(taxiDist(me.pos, i.pos))
interesting_object = interesting_objects[interesting_objects_distances.index(min(interesting_objects_distances))]
# find the direction of the best object
good_object_xy_distance = [interesrting_object.pos[0] - me.pos[1], interesting_object.pos[1] - me.pos[1]]
closest_number = min(good_object_xy_distance)
good_object_direction_vague = [["West","East"],["North","South"]][good_object_xy_distance.index(closest_number)]
if closest_number < 0:
good_object_direction = good_object_direction_vague[1]
else:
good_object_direction = good_object_direction_vague[0]
# if the good and bad objects are in the same direction, move randomly in a different direction
if good_object_direction == bad_object_direction:
return random.choice(allowed_directions)
else: # otherwise go towards the good object.
return good_object_direction
return 0 # when in doubt, stay still
```
Or, in JavaScript,
```
function(map_length, near, me, storage) {
var interesting_objects = []; //objects I can eat
var bad_objects = []; //objects that eat me
var allowed_directions = ["north", "east", "south", "west"];
//add pellets to objects that I'm interested in
for (let i in near.pellets) {
interesting_objects.push(near.pellets[i]);
}
//figure out which blobs are good and which are bad
for (let i in near.blobs) {
//if I'm under or equal powered, add it to bad_objects
if (near.blobs[i].energy >= me.energy) {
bad_objects.push(near.blobs[i]);
}
//if I can eat it, add it to interesting objects.
else {
interesting_objects.push(near.blobs[i]);
}
}
//if there are any bad objects, process them.
if (bad_objects.length) {
//find the nearest bad object and make sure I don't move towards it
var bad_objects_distances = [];
for (i in bad_objects) {
bad_objects_distances.push(taxiDist(bad_objects[i].pos, me.pos));
}
var worst_object = bad_objects[bad_objects_distances.indexOf(Math.min(...bad_objects_distances))];
//find the direction of the worst object
var bad_object_xy_distance = [worst_object.pos[0] - me.pos[1], worst_object.pos[1] - me.pos[1]];
var closest_number = Math.min(...bad_object_xy_distance.map(el => Math.abs(el)));
var bad_object_direction_vague = [["west","east"],["north","south"]][bad_object_xy_distance.map(el => Math.abs(el)).indexOf(closest_number)];
if (closest_number < 0) {
var bad_object_direction = bad_object_direction_vague[1];
} else {
var bad_object_direction = bad_object_direction_vague[0];
}
//remove bad object direction from allowed directions
allowed_directions = allowed_directions.filter(el => el !== bad_object_direction);
}
//process interesting objects if they exist
if (interesting_objects.length) {
//find the nearest interesting object
var interesting_objects_distances = [];
for (i in interesting_objects) {
interesting_objects_distances.push(taxiDist(me.pos, interesting_objects[i].pos))
}
var interesting_object = interesting_objects[interesting_objects_distances.indexOf(Math.min(...interesting_objects_distances))];
//find the direction of the best object
var good_object_xy_distance = [interesting_object.pos[0] - me.pos[1], interesting_object.pos[1] - me.pos[1]];
var closest_number = Math.min(...good_object_xy_distance.map(el => Math.abs(el)));
var good_object_direction_vague = [["west","east"],["north","south"]][good_object_xy_distance.map(el => Math.abs(el)).indexOf(closest_number)];
if (closest_number < 0) {
var good_object_direction = good_object_direction_vague[1];
} else {
var good_object_direction = good_object_direction_vague[0];
}
//if the good and bad objects are in the same direction, move randomly in a different direction
if (good_object_direction == bad_object_direction) {
return allowed_directions[allowed_directions.length * Math.random() | 0];
} else{ //otherwise go towards the good object.
return good_object_direction;
}
}
return 0; //when in doubt, stay still
}
```
This bot isn't very interesting. It acts according to two priorities:
1. Don't get eaten.
2. Eat the nearest thing.
It never spits to maximize its ability to eat other things.
[Answer]
# SafetyBlob
This bot uses some of the same logic as Safetycoin from the previous KOTH.
### How it functions
This bot will head towards food which it can either reach before any bigger bots do or at the same time/before a smaller bot. If it can't see any food which meets these criteria, it will move in a random direction(biased towards the center). If it gets to 150 energy and can not see safe food, it will split in one of the directions it has labeled as safe to move.
This bot doesn't keep track of its own children but they should not collide anyway due to the safety mechanisms.
```
function SafetyBlob(map,local,me,stor){
var center=(map/2|0)+1;
var [x,y]=me.pos
var uid=me.uid
var others=local.blobs;
var pellets=local.pellets;
//Bot doesnt use storage because it just tries to find what it can.
var willSplit=me.energy>150;
var bestSafePelletValue=0;
var bestSafePellet=null;
var pellet;
var other;
//Head towards the best valued pellet (energy/distance) which can be reached before any larger or equal sized blobs or can be reached at the same time as smaller blobs
for(i=0;i<pellets.length;i++){
pellet=pellets[i]
if(bestSafePelletValue<=pellet.energy/taxiDist(pellet.pos,me.pos)){
for(j=0;j<others.length;j++){
other=others[j];
if(other.energy<me.energy){
if(taxiDist(pellet.pos,me.pos)<=taxiDist(other.pos,pellet.pos)){
if(taxiDist(pellet.pos,me.pos)<taxiDist(bestSafePellet.pos,me.pos)){
bestSafePellet=pellet;
bestSafePelletValue=pellet.energy/taxiDist(pellet.pos,me.pos);
}
}
}
if(other.energy>=me.energy){
if(taxiDist(pellet.pos,me.pos)<taxiDist(other.pos,pellet.pos)){
if(taxiDist(pellet.pos,me.pos)<taxiDist(bestSafePellet.pos,me.pos)){
bestSafePellet=pellet;
bestSafePelletValue=pellet.energy/taxiDist(pellet.pos,me.pos);
}
}
}
}
}
}
if(bestSafePellet){
[xPellet,yPellet]=bestSafePellet.pos;
if(x<xPellet&&Math.abs(x-xPellet)>=Math.abs(y-yPellet)){
return East;
}
if(x<xPellet&&Math.abs(x-xPellet)>=Math.abs(y-yPellet)){
return West;
}
if(y<yPellet&&Math.abs(x-xPellet)<Math.abs(y-yPellet)){
return South;
}
if(y<yPellet&&Math.abs(x-xPellet)<Math.abs(y-yPellet)){
return North;
}
}
var validMoves=["North","East","South","West","Stay"];
var removeIndex=0;
var safeEnergy;
if(x==0)
validMoves.splice(validMoves.indexOf("West"));
if(x==map)
validMoves.splice(validMoves.indexOf("East"));
if(y==0)
validMoves.splice(validMoves.indexOf("North"));
if(y==map)
validMoves.splice(validMoves.indexOf("South"));
var possibleMoves=[...validMoves];
possibleMoves.splice(possibleMoves.indexOf("Stay"));
//If there is no safe pellet try to stick somewhat towards the middle
//Ignore enemies unless at 2 distance from self and there is no safe pellet
for(i=0;i<others.length;i++){
other=others[i];
safeEnergy=willSplit?(me.energy-50)/2:me.energy;
if((other.energy>=safeEnergy)&&(taxiDist(me.pos,other.pos)<=2)){
if(taxiDist(me.pos,other.pos)==1){
if((removeIndex=validMoves.indexOf("Stay"))>=0){
validMoves.splice(removeIndex,1)
}
}
if(other.pos[0]<x){
if((removeIndex=validMoves.indexOf("West"))>=0){
validMoves.splice(removeIndex,1)
}
}
if(other.pos[1]<y){
if((removeIndex=validMoves.indexOf("South"))>=0){
validMoves.splice(removeIndex,1)
}
}
if(other.pos[0]>x){
if((removeIndex=validMoves.indexOf("East"))>=0){
validMoves.splice(removeIndex,1)
}
}
if(other.pos[1]>y){
if((removeIndex=validMoves.indexOf("North"))>=0){
validMoves.splice(removeIndex,1)
}
}
}
}
//If there are no safe moves move in a random direction (Reduce energy as much as possible with a slight chance of survival)
if(!validMoves.length){
switch (possibleMoves[Math.random()*possibleMoves.length|0]){
case "North":
return North;
case "South":
return South;
case "East":
return East;
case "West":
return West;
}
}
//If there are safe moves bias towards moving towards the center block of 1/3 of the way from the sides
if(!willSplit){
//bias moving towards near the center
biasedMoves=[];
for(var i=0;i<validMoves.length;i++){
switch(validMoves[i]){
case "North":
biasedMoves=biasedMoves.concat(y>center?"0".repeat(center/3|0).split``:"0".repeat(y-center).split``);
break;
case "South":
biasedMoves=biasedMoves.concat(y<center?"2".repeat(center/3|0).split``:"2".repeat(center-y).split``);
break;
case "East":
biasedMoves=biasedMoves.concat(y>center?"1".repeat(center/3|0).split``:"1".repeat(x-center).split``);
break;
case "West":
biasedMoves=biasedMoves.concat(y<center?"3".repeat(center/3|0).split``:"3".repeat(center-x).split``);
break;
case "Stay":
biasedMoves=biasedMoves.concat(["4"]);
break;
}
}
}
if(willSplit){
switch (biasedMoves[Math.random()*biasedMoves.length|0]){
case "0":
return SplitNorth;
case "2":
return SplitSouth;
case "1":
return SplitEast;
case "3":
return SplitWest;
case "4":
return Stay;
}
}
else{
switch (biasedMoves[Math.random()*biasedMoves.length|0]){
case "0":
return North;
case "2":
return South;
case "1":
return East;
case "3":
return West;
case "4":
return Stay;
}
}
}
```
] |
[Question]
[
**This question already has answers here**:
[The lowest initial numbers in a Fibonacci-like sequence](/questions/147836/the-lowest-initial-numbers-in-a-fibonacci-like-sequence)
(10 answers)
Closed 5 years ago.
Consider a sequence `F` of positive integers where `F(n) = F(n-1) + F(n-2)` for `n >= 2`. The Fibonacci sequence is *almost* one example of this type of sequence for `F(0) = 0, F(1) = 1`, but it's excluded because of the positive integer requirement. Any two initial values will yield a different sequence. For example `F(0) = 3, F(1) = 1` produces these terms.
```
3, 1, 4, 5, 9, 14, 23, 37, 60, 97, ...
```
### Challenge
The task is to find `F(0)` and `F(1)` that minimize `F(0) + F(1)` given some term of a sequence `F(n)`. Write a function or complete program to complete the task.
### Input
Input is a single positive integer, `F(n)`. It may be accepted as a parameter or from standard input. Any reasonable representation is allowed, including direct integer or string representations.
Invalid inputs need not be considered.
### Output
The output will be two positive integers, `F(0)` and `F(1)`. Any reasonable format is acceptable. Here are some examples of reasonable formats.
* Written on separate lines to standard output
* Formatted on standard output as a delimited 2-element list
* Returned as a tuple or 2-element array of integers from a function
### Examples
```
60 -> [3, 1]
37 -> [3, 1]
13 -> [1, 1]
26 -> [2, 2]
4 -> [2, 1]
5 -> [1, 1]
6 -> [2, 2]
7 -> [2, 1]
12 -> [3, 2]
1 -> [1, 1]
```
### Scoring
This is code golf. The score is calculated by bytes of source code.
[Sandbox](https://codegolf.meta.stackexchange.com/a/17030/527)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
pWạ\Ṛ$</¿€SÞḢ
```
[Try it online!](https://tio.run/##y0rNyan8/78g/OGuhTEPd85SsdE/tP9R05rgw/Me7lj031pJ4XA7kKvg/v@/mYGOgrG5joKhsY6CkZmOgomOgqmOApABEjMCYgA "Jelly – Try It Online")
### How it works
```
pWạ\Ṛ$</¿€SÞḢ Main link. Argument: n
W Wrap; yield [n].
p Cartesian product; promote the left argument n to [1, ..., n] and take
the product of [1, ..., n] and n, yielding [[1, n], ..., [n, n]].
€ Map the link to the left over the pairs [k, n].
¿ While...
</ reducing the pair by less-than yields 1:
ạ\ Cumulatively reduce the pair by absolute difference.
Ṛ Reverse the result.
In essence, starting with [a, b] := [k, n], we keep executing
[a, b] := [b, |a - b|], until the pair is no longer increasing.
SÞ Sort the resulting pairs by their sums.
Ḣ Head; extract the first pair.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 34 bytes
```
_Ì<U?[ZÌZx]gV:ZÌ
õ ïUõ)ñx æ_gV ¥U
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=Cl/MPFU/W1rMWnhdZ1Y6WswK9SDvVfUp8XggZl9nViClVcNn&input=WzYwLAozNywKMTMsCjI2LAo0LAo1LAo2LAo3LAoxMiwKMV0KLVJt)
The empty first line is important.
Explanation:
```
_ Declare a function V:
Ì<U? :ZÌ If the second number is >= n, return it
[ZÌZx]gV Otherwise call V again with the second number and the sum
õ ïUõ) Get all pairs of positive integers where both are less than n
ñx Sort them by their sum
æ_gV ¥U Return the first (lowest sum) one where V returns n
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 52 bytes
```
->\n{(1..n X 1..n).max:{(n∈(|$_,*+*...*>n))/.sum}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4mr1rDUE8vTyFCAURp6uUmVlhVa@Q96ujQqFGJ19HS1tLT09Oyy9PU1NcrLs2trf1fnFipkKahEq@pkJZfpGBmoKNgbK6jYGiso2BkpqNgoqNgqqMAZIDEjID4PwA "Perl 6 – Try It Online")
Brute-force solution.
[Answer]
# [Haskell](https://www.haskell.org/), ~~81~~ 80 bytes
* -1 byte thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)
```
f x=[(a,s-a)|s<-[2..],a<-[1..s-1],let u=s-a:zipWith(+)u(a:u),x`elem`take x u]!!0
```
[Try it online!](https://tio.run/##JYuxCsMgFAD3foXZlL5ITFoLoX5C5w5BmjcYItEgVUFK/90Gut1x3IpxM87VupCiJooQW2TfeG@nnnMNeIDgPLZCgzOJZHX08WPD06aVnlmmOGYGZTbO@DnhZkghWTdNV@0ecopqkh0MNxAD9BIucAUJh/Ug9Mmj3ZXH8HjR8LZ74gv7T/UH "Haskell – Try It Online")
[Answer]
# JavaScript, 216 bytes
```
function f(r){for(var n=1;;){var f=p(n);for(var u in f)if(s(f[u][0],f[u][1],r))return f[u];n++}}function p(r){for(var n=[],f=1;0<r;)n.push([r,f]),r--,f++;return n}function s(r,n,f){return n==f||(f<n?null:s(n,r+n,f))}
```
<https://jsfiddle.net/twkz2gyb/>
(Ungolfed code):
```
// For a given input n, return all combinations of positive integers that sum to n.
function findPairs(n) {
var arr = [];
var b = 1;
while(n > 0) {
arr.push([n, b]);
n--;
b++;
}
return arr;
}
// Run a sequence for a and b, and continue fibonacci'ing until r is found(or quit if past r).
function sequence(a, b, r) {
if(b === r) {
return true;
} else if(b > r) {
return null;
}
var nextFibo = a + b;
return sequence(b, nextFibo, r);
}
// For a given n, find the first 2 numbers of the fibonacci sequence with the smallest sum that result in n.
function find(n) {
var i = 1;
while(i < 10) {
var pairs = findPairs(i);
for(var p in pairs) {
var result = sequence(pairs[p][0], pairs[p][1], n);
if(result) {
return pairs[p];
}
}
i++;
}
}
```
] |
[Question]
[
[<< Prev](https://codegolf.stackexchange.com/questions/149950/advent-challenge-5-move-the-presents-to-the-transport-docks) [Next >>](https://codegolf.stackexchange.com/questions/150150/advent-challenge-7-balance-the-storage-carts)
Thanks to the PPCG community, Santa managed to sort his presents into the correct order for moving into the transportation dock. Unfortunately, the transportation dock signs are broken so he doesn't know where to put all the presents! The presents are all grouped together and not by their ranges, which Santa admits would have been a better idea.
Now, given the presents in the sorted order, determine all possible minimal range configurations that would result in the present being in the correct order. That is, find all minimal range configurations such that sorting the presents according to the algorithm in Challenge #5 would not change the order.
# Challenge
A minimal range configuration is a list of ranges such that the ranges are each as small as possible. That is, if a range is designated to cover a specific subset of presents, then the minimum and maximum of the range must be the same as that of the subset. In other words, shrinking any range in the cover would cause it to no longer be a cover.
The challenge is to find all possible minimal range configurations that would apply to the present sizes. Let's take an example: `[3, 1, 2, 5, 4, 7, 6]`
There is a trivial case, which is to take the range of the entire present configuration. In this case, `[[1, 7]]` would be a solution.
For examples with unique elements, another trivial case would be `[[3], [1], [2], [5], [4], [7], [6]]` (because the ranges don't need to be ordered).
For this example, we also see that `[[1, 3], [4, 7]]` and `[[1, 3], [4, 5], [6, 7]]` would work, as well as `[[1, 3], [5], [4], [6, 7]]` and `[[1, 3], [4, 5], [7], [6]]`.
The final answer for `[3, 1, 2, 5, 4, 7, 6]` would be `[[[3], [1], [2], [5], [4], [7], [6]], [[3], [1], [2], [5], [4], [6, 7]], [[3], [1], [2], [4, 5], [7], [6]], [[3], [1], [2], [4, 5], [6, 7]], [[3], [1], [2], [4, 7]], [[3], [1, 2], [5], [4], [7], [6]], [[3], [1, 2], [5], [4], [6, 7]], [[3], [1, 2], [4, 5], [7], [6]], [[3], [1, 2], [4, 5], [6, 7]], [[3], [1, 2], [4, 7]], [[1, 3], [5], [4], [7], [6]], [[1, 3], [5], [4], [6, 7]], [[1, 3], [4, 5], [7], [6]], [[1, 3], [4, 5], [6, 7]], [[1, 3], [4, 7]], [[1, 5], [7], [6]], [[1, 5], [6, 7]], [[1, 7]]]`.
# Formatting Specifications
The input will be given as a flat list of positive integers within your language's reasonable supported number range in any reasonable format. The input may contain duplicate elements. The output should be given as a 3D list of positive integers in any reasonable format.
Each range in your output (which is at the second layer) can be represented either as `[min, max]`, `[num]` if it's a single-value range, or as the entire range itself, but your output format must be consistent. Please specify if you wish to use a slightly different reasonable output format.
Duplicate values must be covered by a single range in the output; that is, no two ranges in the output may have any overlap.
Your solution may return the ranges in any order and this does not have to be deterministic.
# Rules
* Standard Loopholes Apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins
* No answer will be accepted
# Test Case for a list with duplicate elements:
```
2 3 2 4 -> [[[2, 3], [4]], [[2, 4]]]
```
# [Reference Implementation](https://tio.run/##XZLNbiMhEITP5ilKWikCZTS287eSJd/2soc8wWgOPTZOSBhAwCiefXlvDyRWdi@AWkX3VwVhzq/e3V8uZgw@ZpisY/beJiEoRpqxhzUpy5GCNC43MC5MWao2BWt4V0qIoz4hUMwmG@@SJLXDDxz8USPTu3Y4RT9i/Us7Z9KzyYdXbe36jZd5PVg/rEdKPLVW2jBj0AeaksZvfFAC08DSn5kPGLkfxhn@w4lV1Jnpul6sTj4y11GfeUUk96LltoHVjlnUTqyKIE1DdcSa77Rdubnri3D1pWqNS5yE3DSgblckvVoEPLWlELQ7yi@tEt@rHfW1MEWG0VkIP2XOrLKKBeU6/n@W0o05ioe03Eg6y@poNE4G1XAGZ95xi61SKN3@6cJxmBPIWln84waDwn6PTdFSg2GRX5@5PfhxMI4qQJ3b4K7GVsGvxspHWIC6hSV@skTVf4LEa/yJIxAh8oeRtYe6XO6xxR0e8YCfePoL)
The header is the link.
Note: I drew inspiration for this challenge series from [Advent Of Code](http://adventofcode.com/). I have no affiliation with this site
You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge [here](https://codegolf.stackexchange.com/questions/149660/advent-challenge-1-help-santa-unlock-his-present-vault).
Happy golfing!
[Answer]
# Mathematica, 106 bytes
```
sSelect[MinMax/@s~TakeList~#&/@Join@@Permutations/@IntegerPartitions@Tr[1^s],Unequal@@Join@@Range@@@#&]
```
[Try it online!](https://tio.run/##LctdCoJAEADgqywIPQ2I/T4F81okSNmTGAwy2pKOtDtCEHmIbtAJO8IW0esHX0d65o7UVhTqdfDv5@vALVdapFZSusXox5wuvLNex2gS47a3gpix6wb9tl58jBtRbthl5NT@CHNXJCdfwlH4OlCL/7YnaRgRo0kZMmdFsS7uMzAJmCmYBZg5mBWY5aMMHw "Wolfram Language (Mathematica) – Try It Online")
Martin saved 16 bytes
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~17~~ 16 bytes
```
{~c⟨⌋⟦₂⌉⟩ᵐ.c≠∧}ᶠ
```
Works on lists with duplicates as well.
Ranges are represented by the lists of elements they contain.
[Try it online!](https://tio.run/##AUEAvv9icmFjaHlsb2cy//97fmPin6jijIvin6bigoLijInin6nhtZAuY@KJoOKIp33htqD//1syLDYsNSw0LDYsM13/Wg "Brachylog – Try It Online")
## Explanation
The idea is to break the list into blocks and transform the blocks into ranges, then verify that they don't overlap.
```
{~c⟨⌋⟦₂⌉⟩ᵐ.c≠∧}ᶠ Input is a list.
{ }ᶠ Compute all possible outputs for this predicate:
~c Break the list into contiguous blocks.
⟨ ⟩ᵐ For each block,
⌋ ⌉ take its minimum and maximum,
⟦₂ and create the range between them.
. This is the output.
c Also, if you concatenate the output,
≠ its elements are distinct.
∧ Prevent the interpreter from thinking this is also the output.
```
[Answer]
# JavaScript (ES6), ~~166~~ 164 bytes
*Edit: updated version that now supports duplicates*
Prints the results directly to the console in **[min, max]** format.
```
f=(a,r=[],l=0)=>a[l++]?f([...a],r,l,f(a,[...r,[Math.min(...x=a.splice(0,l)),Math.max(...x)]])):a[0]|r.some(([x,y],i)=>r.some(([z])=>i--&&z>=x&z<=y))||console.log(r)
```
### Test cases
```
f=(a,r=[],l=0)=>a[l++]?f([...a],r,l,f(a,[...r,[Math.min(...x=a.splice(0,l)),Math.max(...x)]])):a[0]|r.some(([x,y],i)=>r.some(([z])=>i--&&z>=x&z<=y))||console.log(r)
consoleLog = console.log;
console.log = s => consoleLog(JSON.stringify(s))
consoleLog('Test case: [3, 1, 2, 5, 4, 7, 6]')
f([3, 1, 2, 5, 4, 7, 6])
consoleLog('Test case: [2, 3, 2, 4]')
f([2, 3, 2, 4])
```
[Answer]
# [Python 2](https://docs.python.org/2/), 179 bytes
```
lambda l:[l for l in[[range(min(x),max(x)+1)for x in P]for P in p(l)]if len(sum(l,[]))==len(set(sum(l,[])))]
p=lambda l:[[l[:i]]+a for i in range(1,len(l))for a in p(l[i:])]+[[l]]
```
[Try it online!](https://tio.run/##ZY3NDoJADITvPEWP29ALvyYkvAP3tYc1srpJWQhigk@P7GrUxFOnM51@02O5jj7fbHvcxAynswFptIAdZxBwXuvZ@EuvBufVijSYdR9phiFf9xw6DrILclKC7CxI79XtPighzYhtG/d@@fGQk6n94rToxjGnJmJd@PWiZhS6ghFn3gztGkZO9xbzNs3OL2CVziingjGJRvKxC4KMICeoCEqCA0H9f5RTTRWVtEfbEw "Python 2 – Try It Online")
Outputs a list of full ranges.
Heavily inspired by the reference implementation.
Builds all partitions, then ranges of min/max for each partition. A list of ranges is valid if no value appears more than once in the list.
---
`sum(l,[])` flattens a list of lists, and allows me to check for duplicates:
```
l=[[1, 2], [2, 3]]
sum(l,[]) = [1,2,2,3]
len([1,2,2,3] == len(set([1,2,2,3])) -> False (duplicates)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
f{IsTmm}hSkeSkd./
```
**[Try it here!](https://pyth.herokuapp.com/?code=f%7BIsTmm%7DhSkeSkd.%2F&input=%5B3%2C+1%2C+2%2C+5%2C+4%2C+7%2C+6%5D&debug=0)**
Now that's *much* better. Outputs the whole ranges. See [the revision history](https://codegolf.stackexchange.com/revisions/0466605c-f8ec-44c4-9c18-c770055e5985/view-source) for the previous version (at a staggering 31 bytes).
### How it works
```
f{IsTmm}hSkeSkd./ ~> Full program.
./ ~> List partition.
m ~> Map using a variable d.
m d ~> Map over d using a variable k.
hSk ~> The minimum of k.
eSk ~> The maximum of k.
} ~> Inclusive integer range.
f ~> Filter those...
sT ~> Which, when flattened,
{I ~> Are invariant over deduplication.
```
] |
[Question]
[
Let's say you have a 20-sided die. You start rolling that die and have to roll it a few dozen times before you finally roll all 20 values. You wonder, how many rolls do I need before I get a 50% chance of seeing all 20 values? And how many rolls of an `n`-sided die do I need to roll before I roll all `n` sides?
After some research, you find out that a formula exists for calculating the **chance** of rolling all `n` values after `r` rolls.
```
P(r, n) = n! * S(r, n) / n**r
```
where `S(a, b)` denotes [Stirling numbers of the second kind](https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind), the number of ways to partition a set of n objects (each roll) into k non-empty subsets (each side).
You also find the [OEIS sequence](http://oeis.org/A073593), which we'll call `R(n)`, that corresponds to the smallest `r` where `P(r, n)` is at least 50%. The challenge is to calculate the `n`th term of this sequence as fast as possible.
**The challenge**
* Given an `n`, find the **smallest** `r` where `P(r, n)` is greater than or equal to `0.5` or 50%.
* Your code should theoretically handle any non-negative integer `n` as input, but we will only be testing your code in the range of `1 <= n <= 1000000`.
* For scoring, we will be take the total time required to run `R(n)` on inputs `1` through `10000`.
* We will check if your solutions are correct by running our version of `R(n)` on your output to see if `P(your_output, n) >= 0.5` and `P(your_output - 1, n) < 0.5`, i.e. that your output is actually the smallest `r` for a given `n`.
* You may use any definition for `S(a, b)` in your solution. [Wikipedia](https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind) has several definitions that may be helpful here.
* You may use built-ins in your solutions, including those that calculate `S(a, b)`, or even those that calculate `P(r, n)` directly.
* You can hardcode up to 1000 values of `R(n)` and a million Stirling numbers, though neither of these are hard limits, and can be changed if you can make a convincing argument for raising or lowering them.
* You don't need to check every possible `r` between `n` and the `r` we're looking for, but you do need to find the smallest `r` and not just any `r` where `P(r, n) >= 0.5`.
* Your program must use a language that is freely runnable on Windows 10.
The specifications of the computer that will test your solutions are `i7 4790k, 8 GB RAM`. Thanks to [@DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem) for providing his computer for the testing. Feel free to add your own *unofficial* timing for reference, but the official timing will be provided later once DJ can test it.
**Test cases**
```
n R(n)
1 1
2 2
3 5
4 7
5 10
6 13
20 67 # our 20-sided die
52 225 # how many cards from a huge uniformly random pile until we get a full deck
100 497
366 2294 # number of people for to get 366 distinct birthdays
1000 7274
2000 15934
5000 44418
10000 95768
100000 1187943
1000000 14182022
```
Let me know if you have any questions or suggestions. Good luck and good optimizing!
[Answer]
# Python + NumPy, 3.95 Seconds
```
from __future__ import division
import numpy as np
def rolls(n):
if n == 1:
return 1
r = n * (np.log(n) - np.log(np.log(2)))
x = np.log1p(np.arange(n) / -n)
cx = x.cumsum()
y = cx[:-1] + cx[-2::-1] - cx[-1]
while True:
r0 = np.round(r)
z = np.exp(y + r0 * x[1:])
z[::2] *= -1
r = r0 - (z.sum() + 0.5) / z.dot(x[1:])
if abs(r - r0) < 0.75:
return np.ceil(r).astype(int)
for n in [1, 2, 3, 4, 5, 6, 20, 52, 100, 366, 1000, 2000, 5000, 10000, 100000, 1000000]:
print('R({}) = {}'.format(n, rolls(n)))
import timeit
print('Benchmark: {:.2f}s'.format(timeit.timeit(lambda: sum(map(rolls, range(1, 10001))), number=1)))
```
[Try it online!](https://tio.run/##XVJNb6MwEL3zK@ZWkwKLySaVULnsT1jtLUKRA6axFn/IQAuJ8tvTsd2kUX3wzDy/NzMe2yzjUav19dpZLWG/76Zxsny/ByGNtiO04l0MQqvoK1aTNAuwAZSJopZ3YHXfD0TFZQS4RAcKqgpoCN2yHDMqoB6wUCFhBUSZrNdvqIMUbn4wRRzHnjs7rseocYfMMvXGneQXpCpwGkeas2aSwyRJwBaEmnlXprSGZ@elRemD1Ae09qyPo@g5/LMTf2g1DyWtnlRLbHw/OAWcz4YsmBN5K5h3tKwfKLuyLGpYVZDS74SoQ3IK5JT5BlGcZxt3g1PW6pH8SILjY4eBWFTYPIZXJL9svvt7GCd203DRY5MZG8bFcCLUGF87bXG@QsGOJlAksE7gdwKbBLYY5ughRnN01tut93KHu33jd4fczN3mdWjBWKxBnv6S8yXGi50vTxnWk2wkKrn/A3y8218ZheRijL5kf7hqjpLZ/yWcy6zoLsNdHohZMKRn8tCyEtzAJDPEZ8YC/vVpaIpincR9xgO3lQuunw "Python 3 – Try It Online")
### How it works
This uses the closed-form series for *P*(*r*, *n*), and its derivative with respect to *r*, rearranged for numerical stability and vectorization, to do a Newton’s method search for *r* such that *P*(*r*, *n*) = 0.5, rounding *r* to an integer before each step, until the step moves *r* by less than 3/4. With a good initial guess, this usually takes just one or two iterations.
*x**i* = log(1 − *i*/*n*) = log((*n* − *i*)/*n*)
*cx**i* = log(*n*!/((*n* − *i* − 1)! ⋅ *n**i* + 1)
*y**i* = *cx**i* + *cx**n* − *i* − 2 − *cx**n* − 1 = log binom(*n*, *i* + 1)
*z**i* = (-1)*i* + 1 ⋅ binom(*n*, *i* + 1) ⋅ ((*n* − *i* − 1)/*n*)*r*
1 + ∑*z**i* = n! ⋅ *S*(*r*, *n*)/*n**r* = *P*(*r*, *n*)
*z**i* ⋅ *x**i* + 1 = (-1)*i* + 1 ⋅ binom(*n*, *i* + 1) ⋅ ((*n* − *i* − 1)/*n*)*r* log((*n* − *i* − 1)/*n*)
∑*z**i* ⋅ *x**i* + 1 = d/d*r* *P*(*r*, *n*)
] |
[Question]
[
`;#` is a very simple language. It has 2 commands:
* `;` will increment the accumulator
* `#` outputs the accumulator modulo 127, and then resets the accumulator
`;$` is also very simple and is very similar (and also does not yet exist). It has 2 commands:
* `;` will increment the accumulator
* `$` outputs the accumulator modulo 127. However, it does not reset the accumulator.
# Challenge
Create a program that will convert `;#` code to `;$` code. That is, given input `a` using standard methods, output he shortest `b` such that `a` in `;#` outputs the same thing as `b` in `;$`. The input will only contain the characters `';'` and `'#'`. The input will not have trailing semicolons. That is, it will match the regex `(;*#)+`. This also means input will not be blank. Note that `;;;;##` is possible (equivalent to `ord(4) ord(0)`).
# Examples
```
;# code -> ;$ code
;;;;;;;;;;#;;;;;;;;;;;;# -> ;;;;;;;;;;$;;$
;;;;;;;;;;;;;;#;;;# -> ;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# -> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;$$;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;$;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$ (Hello, World!)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
ṣ”#L€ṙ-I%127”;ẋp”$
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuYq@zxqWvNw50xdT1VDI3OggPXDXd0FQFrl////1ihAGYQB "Jelly – Try It Online")
### How it works
```
ṣ”#L€ṙ-I%127”;ẋp”$ Main link. Argument: s (string)
ṣ”#L€ Split s at hashes. Take the length of each resulting chunk.
ṙ- Rotate the result -1 units to the left / 1 unit to the right.
Since s won't have trailing semicola, the length of the last
chunk will be 0. Rotating moves this 0 to the beginning.
I Increments; take all forward differences. Because of the 0 we
removed to the beginning, the first forward difference will be
the length of the first chunk.
%127 Take the differences modulo 127. In Python, `n % d' is either 0
or has the same sign as d, so this reports how many semicola
are needed to get from one code point to the next one.
”;ẋ Repeat ';' k times, for each modulus k.
p”$ Take the Cartesian product with "$", appending '$' to each run
of semicola.
```
[Answer]
## JavaScript (ES6), 68 bytes
```
s=>s.replace(/;*#/g,s=>';'.repeat((127-a+(a=s.length))%127)+'$',a=1)
```
### Examples
```
let f =
s=>s.replace(/;*#/g,s=>';'.repeat((127-a+(a=s.length))%127)+'$',a=1)
console.log(f(";;;;;;;;;;#;;;;;;;;;;;;#"))
console.log(f(";;;;;;;;;;;;;;#;;;#"))
console.log(f(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"))
```
[Answer]
# PHP, 99 bytes
```
while(~$c=a^$argn[$p++])j^$c?r^$c?:$a=-$b*$b=print str_repeat(";",(127+$a%127)%127)."$":$b+=!!++$a;
```
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
[:;';$'<@#~1,.~127|2-~/\0,=&'#'#;._2]
```
[Try it online!](https://tio.run/nexus/j#@5@mYGulEG1lrW6tom7joFxnqKNXZ2hkXmOkW6cfY6Bjq6aurK5srRdvFMvFlZqcka@QpqBuDQfK1khAWf3/fwA "J – TIO Nexus")
[Answer]
# Python, ~~101~~ ~~100~~ ~~97~~ 85 bytes
*1 bytes saved thanks to @WheatWizard*
```
def t(c,s=0):
for x in map(len,c.split('#')[:-1]):print(end=';'*((x-s)%127)+'$');s=x
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 52 bytes
```
^
##
#
127$*;$
^;+\$;+\$|(;+)(?<=\$\1(;{127})?\$\1)
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/gfx6WszKXMZWhkrqJlrcIVZ60dowLCNRrW2poa9ja2MSoxhhrW1UAFtZr2II4m1///1nCgbI0ElLmsUYAyFjHygbI1PQB9bBn2lpFqn/JAuX5Qh8poKiPXEmUA "Retina – TIO Nexus") Includes test suite. Explanation: 127 is added to each `#` to make the subtraction modulo 127 easier; the `#`s are changed to `$` at the same time. The subtraction itself is handled by the lookbehind `(?<=\$\1(;{127})?\$\1)` which ensures that we subtract either the number of `;`s between the previous two `#`s (which handles the case when there are more `;`s) or 127 fewer than that number (which handles the case when there are fewer `;`s and they need to wrap past 127). A lookbehind is used so that all the replacements can be calculated in one pass. In order for there always to be two previous `#`s, two extra `#`s are temporarily prefixed.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 65 bytes
```
s/(;*)#/$b=($q+$b)%127;';'x($q+=(($q=length$1)<$b)*127-$b).'$'/ge
```
[Try it online!](https://tio.run/##7VXbCsIwDH33KwKN7CJbVRAf4vwXJ3UbzK2uFfx6awXx/qCbbCIeSkvISZOm5VSKKp8Yo7hLvsc4xpGLmwHGXn80npJDzu5oR66do1wUiU5x5M2s37f@wK6hgw5PhCHFIfQ5J0u0uwxJVlmhkRMwSEUlYFVWoIXSWZHAepvrTOYClgsllKEzGF2BQTCHi4l29OgG7JF1YraP@9rqg7VSL2uzOb@b7N18rKvqv7or/1dWN8kT@WugYS95EZtqbBcCjZ@Ow44O0uEf1/je96XUWVkoE8gD "Perl 5 – Try It Online")
] |
[Question]
[
The ECMAScript 6 standard added many new features to the JavaScript language, including a new [arrow function notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
Your task is to write a basic ES6-to-ES5 transpiler. Given only an ES6 arrow function as input, output its ES5-compatible counterpart.
It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! May the shortest program in bytes win!
---
## The Basics
An arrow function looks like this:
```
(a, b, c) => { return a + b - c }
```
And its equivalent ES5 function expression looks like this:
```
function(a, b, c) { return a + b - c }
```
In general, you can copy the body of the function (everything between the curly braces) verbatim.
---
## Implicit Return Statement
Instead of a body with curly braces, a single expression can be used; the result of this expression is then returned.
```
(a, b, c) => a + b - c
function(a, b, c) { return a + b - c }
```
Another example:
```
(a, b, c) => (a + 1, b - 2 * c / 3)
function(a, b, c) { return (a + 1, b - 2 * c / 3) }
```
Again, you may simply copy the expression verbatim - BUT take care that you do not output a line break between it and the `return` keyword to avoid automatic semicolon insertion!
---
## One Argument
Parentheses are optional if one argument is provided.
```
foo => { return foo + 'bar' }
function(foo) { return foo + 'bar' }
```
---
## Whitespace
Finally, you must be able to account for any number of whitespace characters (space, tab, newline) before or after parentheses, variables, commas, curly braces, and the arrow\*.
```
( o , O
, _ )=>{
return "Please don't write code like this."
}
```
Whether or not you choose to preserve whitespace in the output is up to you. Keep 'em, remove 'em, or add your own - just make sure it's valid code!
\*It's technically illegal for an arrow to come immediately after a line break, but I doubt this fact would help you. :)
---
## A quick way to validate your output:
Enter `var foo = <your output>; foo()` into your browser console. If it doesn't complain, you're probably on the right track.
---
## More rules for the wizards:
* Input is a syntactically valid ES6 arrow function.
* Assume the body of the function is ES5-compatible (and doesn't reference `this`, `super`, `arguments`, etc). This also means that the function will never contain another arrow function (but you may not assume that "=>" will never occur within the body).
* Variable names will only consist of basic Latin letters, `$` and `_`.
* You need not transpile ES6 features that aren't listed above (default parameters, rest operator, destructuring, etc).
* The space after a `return` statement is optional if followed by `(`, `[`, or `{`.
* It isn't strictly necessary to match my test cases exactly - you can modify the code as much as you need if it'll help lower your byte count. Really, as long as you produce a syntactically valid, functionally equivalent ES5 function expression, you're golden!
[Answer]
## JavaScript (ES6), ~~123~~ ~~110~~ ~~100~~ 97 bytes
*Saved 3 bytes thanks to @Neil*
```
s=>s.replace(/\(?(.*?)\)?\s*=>\s*([^]*)/,(_,a,b)=>`function(${a})${b[0]=='{'?b:`{return ${b}}`}`)
```
Assumes the input is a syntactically valid arrow function and nothing else. Correctly handles the case `a =>\na`, though not handling is not any shorter as far as I can tell.
Output when the code is run through itself:
```
function(s){return s.replace(/\(?(.*?)\)?\s*=>\s*([^]*)/,(_,a,b)=>`function(${a})${b[0]=='{'?b:`{return ${b}}`}`)}
```
---
I can save 9 bytes with a possibly invalid format:
```
s=>s.replace(/\(?(.*?)\)?\s*=>\s*({?)([^]*?)}?$/,(_,a,z,b)=>Function(a,z?b:'return '+b))
```
Output for itself:
```
function anonymous(s) {
return s.replace(/\(?([^=)]*)\)?\s*=>\s*({?)([^]*?)}?$/,(_,a,z,b)=>Function(a,z?b:'return '+b))
}
```
(Specifically, the `function anonymous` is what I'm worried about.)
[Answer]
# Retina, ~~86~~ ~~80~~ 79 bytes
```
^([^(]*?)=
($1)=
s(`\s*$
>\s*(.*[^}])$
>{return $1}
)`(.*?)=>(.*)
function$1$2
```
[Try it Online!](https://tio.run/nexus/retina#jYvBCsIwGIPv/1OEUbAtMqh36yPM@1ydbBWLo4W2w4Ps2Wv1CcwhXyBJMbw3fJAncSTOVPXEx0uSjEhX8Fb2ZhsEI/2ONq/Rg6mNxFiLetEVgu6rn7ILnil2KAUcAcAe6Aj4pesXdY0/RM15sbdkMQe/y3hFly2mMFss7mmRHy61DX0A)
*Saved a byte thanks to Neil*
*Saved 6 bytes with help from ETHproductions*
**Edit:** Fixed for possibility of newlines in function body.
75 byte solution assuming the input won't contain `§`: [Try it Online!](https://tio.run/nexus/retina#@29rx3VoOVecRnScRqyWJpCpoWIIoooTDi2PKdYCilfHFMfqaWkClVUXpZaUFuUpqBjWAuU19EDqQSRXWmlecklmfp6KoYrR//9p@fkKtnYg0k5BPSmxSJ0LAA)
[Answer]
# PHP, 112 bytes
```
preg_match("#\(??(.*)\)?=>(\{?)(.*$)#U",$argn,$m);echo"function($m[1])",trim($b=$m[3])[0]=="{"?$b:"{return $b}";
```
takes input from STDIN; run with `-R`
] |
[Question]
[
## Introduction
According to the [Riemann Hypothesis](https://en.wikipedia.org/wiki/Riemann_hypothesis), all zeroes of the [Riemann zeta function](https://en.wikipedia.org/wiki/Riemann_zeta_function) are either negative even integers (called *trivial zeroes*) or complex numbers of the form `1/2 ± i*t` for some real `t` value (called *non-trivial zeroes*). For this challenge, we will be considering only the non-trivial zeroes whose imaginary part is positive, and we will be assuming the Riemann Hypothesis is true. These non-trivial zeroes can be ordered by the magnitude of their imaginary parts. The first few are approximately `0.5 + 14.1347251i, 0.5 + 21.0220396i, 0.5 + 25.0108576i, 0.5 + 30.4248761i, 0.5 + 32.9350616i`.
## The Challenge
Given an integer `N`, output the imaginary part of the `N`th non-trivial zero of the Riemann zeta function, rounded to the nearest integer (rounded half-up, so `13.5` would round to `14`).
## Rules
* The input and output will be within the representable range of integers for your language.
* As previously stated, for the purposes of this challenge, the Riemann Hypothesis is assumed to be true.
* You may choose whether the input is zero-indexed or one-indexed.
## Test Cases
The following test cases are one-indexed.
```
1 14
2 21
3 25
4 30
5 33
6 38
7 41
8 43
9 48
10 50
50 143
100 237
```
## OEIS Entry
This is OEIS sequence [A002410](http://oeis.org/A002410).
[Answer]
## Mathematica, 23 bytes
```
⌊Im@ZetaZero@#+.5⌋&
```
Unfortunately, `Round` rounds `.5` to the nearest even number, so we have to implement rounding by adding `.5` and flooring.
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 25 bytes
There's not much support in GP for analytic number theory (it's mostly algebraic), but just enough for this challenge.
```
n->lfunzeros(1,15*n)[n]\/1
```
[Answer]
## Sage, 34 bytes
```
lambda n:round(lcalc.zeros(n)[-1])
```
[Try it online](http://sagecell.sagemath.org/?z=eJwNzDsKgDAQBcA-kDtsqfiURI0_8CRiET8BIa4SrTy9aaYcN3p7LpslHg5-E79avxbfHq4n4XTK9ZwVJpVCCncFYjqYJo0SFWoYNGjRoYdWMCqq5kEKojvEihjk4vEDYFUZ0w==&lang=sage)
This solution is a golfed form of the program found on the OEIS page.
`lcalc.zeros` is a function (which is thankfully spelled the shorter way, rather than `zeroes` for an extra byte) that returns the imaginary parts of the first `n` non-trivial Riemann zeta zeros. Taking the `-1`st index returns the `n`th zero (1-indexed), and `round` rounds it to the nearest integer. In Python 3, `round` uses banker's rounding (half-to-nearest-even), but thankfully Sage runs on Python 2, where `round` uses half-up rounding.
] |
[Question]
[
# Introduction
There is a tax collector that has some trouble managing the taxes of his kingdom: the historical records have burnt down in a great fire.
He wants to find out how many possible pasts there could be in terms of where the current money was inherited from. Luckily, his kingdom is very simple.
The kingdom can be modelled by a 2D boolean matrix, where `l` represents someone who has inherited money, and `O` represents someone who has not. For example:
```
l O l l
O O O l
l O l O
O O O l
```
(It will always be a rectangle)
In the next generation, the kingdom is smaller (The wolves are strong!).
The next generation would look like this, superimposed on the previous generation (`x` is a placeholder for a descendent in the next generation)
```
l O l l
x x x
O O O l
x x x
l O l O
x x x
O O O l
```
A descendent will look at the ancestors that are directly around them (So the top-left `x` will see {`l`, `O`, `O`, `O`}, called an [Unaligned rectangular neighbourhood](https://en.wikibooks.org/wiki/Cellular_Automata/Neighborhood#Unaligned_rectangular_neighborhood))
If only one ancestor has inherited money, the descendant will inherit money from them. If more than one ancestor has inherited money, they will squabble and the descendant will end up not inheriting money. If no one has inherited money, the descendant will not inherit any money.
(More than one descendant can inherit from one ancestor)
So, the next generation would look like:
```
l l O
l l O
l l O
```
# Challenge
## Input
The current state of the generation, as an array of arrays of any two distinct values, where the inner arrays are all of the same length.
E.g., for the example above, it could be:
```
[
[True, True, False],
[True, True, False],
[True, True, False]
]
```
## Output
An integer representing the number of unique previous generations where the next generation is the input.
You can assume that the answer will always be less than 2^30 - 1. (or 1073741823).
The previous generation would be called a "preimage" and this challenge would be to [count the preimages](https://en.wikibooks.org/wiki/Cellular_Automata/Counting_Preimages).
## Scoring
This is a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge, so each submission will be tested on my computer, and the submission that takes the least time will be the winner.
# Example Input and Output
(Where `1` is a descendent who inherited money, and `0` is a descendent who did not inherit money)
## Input:
```
[[1, 0, 1],
[0, 1, 0],
[1, 0, 1]]
```
### Output:
```
4
```
## Input:
```
[[1, 0, 1, 0, 0, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 0, 1, 1, 1]]
```
### Output:
```
254
```
## Input:
```
[[1, 1, 0, 1, 0, 1, 0, 1, 1, 0],
[1, 1, 0, 0, 0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0, 1, 1, 0, 0]]
```
### Output:
```
11567
```
[Answer]
## C++ using the [BuDDy library](http://buddy.sourceforge.net/manual)
This seemed like a nice excuse to play with [binary decision diagrams](http://en.wikipedia.org/wiki/Binary_decision_diagram).
The kingdom is converted into a big boolean formula where we have to count the number of ways in which it can be satisfied. That can (sometimes) be done more efficiently than it sounds.
The kingdom must be given as a program constant as a flat array and explicitely given dimensions. (Nice input is left as an execise for the reader :-)
Here is the embarrassingly simple code:
```
#include <iostream>
#include <bdd.h>
// describe the kingdom here:
constexpr int ROWS = 4;
constexpr int COLS = 10;
constexpr int a[] = {
1, 1, 0, 1, 0, 1, 0, 1, 1, 0,
1, 1, 0, 0, 0, 0, 1, 1, 1, 0,
1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, 1, 1, 0, 0,
};
// end of description
// check dimensions
static_assert(ROWS*COLS*sizeof(int)==sizeof(a),
"ROWS*COLS must be the number of entries of a");
// dimensions of previous generation
constexpr int R1 = ROWS+1;
constexpr int C1 = COLS+1;
// condition that exactly one is true
bdd one(bdd a, bdd b, bdd c, bdd d){
bdd q = a & !b & !c & !d;
q |= !a & b & !c & !d;
q |= !a & !b & c & !d;
q |= !a & !b & !c & d;
return q;
}
int main()
{
bdd_init(1000000, 10000); // tuneable, but not too important
bdd_setvarnum(R1*C1);
bdd q { bddtrue };
for(int j=COLS-1; j>=0; j--) // handle high vars first
for (int i=ROWS-1; i>=0; i--){
int x=i+R1*j;
bdd p=one(bdd_ithvar(x), bdd_ithvar(x+1),
bdd_ithvar(x+R1), bdd_ithvar(x+R1+1));
if (!a[COLS*i+j])
p = !p;
q &= p;
}
std::cout << "There are " << bdd_satcount(q) << " preimages\n";
bdd_done();
}
```
To compile with debian 8 (jessie), install `libbdd-dev` and do `g++ -std=c++11 -o hist hist.cpp -lbdd`. (Optimizing options make almost no difference because the real work is done in the library.)
Big examples can lead to messages about garbage collection. They could be suppressed, but I prefer to see them.
`bdd_satcount` returns a `double`, but that is good enough for the expected range of results. The same counting technique is possible with exact (big) integers.
The code is optimized for `ROWS<COLS`. If you have a lot more rows than columns, it might be a good idea to transpose the matrix.
[Answer]
# Python 2.7
This is just a naïve first attempt. It's not particularly fast, but it is correct.
The first observation is that each cell is dependent on exactly four cells in the previous generation. We can represent those four cells as a 4-bit number (0-15). According to the rules, if exactly one neighboring cell in the previous generation is `1`, then a given cell in the current generation will be `1`, otherwise, it will be `0`. Those correspond to the powers of two, namely, `[1, 2, 4, 8]`. When the four ancestors are represented as a 4-bit number, any other number will result in a `0` in the current generation. With this information, upon seeing a cell in the current generation, we can narrow down the possibilities of the neighborhood in the previous generation to one of four or one of twelve possibilities respectively.
I've chosen to represent the neighborhood as follows:
```
32
10
```
where 0 is the least-significant bit, and so on.
The second observation is that for two adjacent cells in the current generation, the two neighborhoods from the previous generation overlap:
```
32 32
10 10
```
or:
```
32
10
32
10
```
In the horizontal case, the `2` from the left neighborhood overlaps with the `3` from the right neighborhood, and similarly with the `0` on the left and the `1` on the right. In the vertical case, the `1` from the top neighborhood overlaps with the `3` from the bottom neighborhood, and similarly with the `0` on the top and the `2` on the bottom.
This overlap means that we can narrow down the possibilities for yet-unchosen neighborhoods based on what we've already chosen. The code works it's way from left to right, top to bottom, in a recursive depth-first search for possible preimages. The following diagram indicates which previous neighborhoods we have to consider when looking at the possible neighborhoods of a current cell:
```
f = free choice
h = only have to look at the neighborhood to the left
v = only have to look at the neighborhood to the top
b = have to look at both left and top neighborhoods
[f, h, h, h, h],
[v, b, b, b, b],
[v, b, b, b, b],
[v, b, b, b, b]
```
Here's the code:
```
def good_horizontal(left, right):
if (left & 4) >> 2 != (right & 8) >> 3:
return False
if left & 1 != (right & 2) >> 1:
return False
return True
def good_vertical(bottom, top):
if (bottom & 8) >> 3 != (top & 2) >> 1:
return False
if (bottom & 4) >> 2 != (top & 1):
return False
return True
ones = [1, 2, 4, 8]
zeros = [0, 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15]
h = {}
v = {}
for i in range(16):
h[i] = [j for j in range(16) if good_horizontal(i, j)]
v[i] = [j for j in range(16) if good_vertical(i, j)]
def solve(arr):
height = len(arr)
width = len(arr[0])
if height == 1 and width == 1:
if arr[0][0] == 1:
return 4
else:
return 12
return solve_helper(arr)
def solve_helper(arr, i=0, j=0, partial=None):
height = len(arr)
width = len(arr[0])
if arr[i][j] == 1:
poss = ones
else:
poss = zeros
if i == height - 1 and j == width - 1: # We made it to the end of this chain
if height == 1:
return sum([1 for p in poss if p in h[partial[-1][-1]]])
else:
return sum([1 for p in poss if partial[-2][-1] in v[p] and p in h[partial[-1][-1]]])
if j == width - 1:
new_i, new_j = i + 1, 0
else:
new_i, new_j = i, j + 1
if i == 0:
if j == 0:
# first call
return sum([solve_helper(arr, new_i, new_j, [[p]]) for p in poss])
# still in the first row
return sum([solve_helper(arr, new_i, new_j, [partial[0] + [p]]) for p in poss if p in h[partial[0][-1]]])
if j == 0: # starting a new row
return sum([solve_helper(arr, new_i, new_j, [r for r in partial + [[p]]]) for p in poss if partial[i - 1][0] in v[p]])
return sum([solve_helper(arr, new_i, new_j, [r for r in partial[:-1] + ([partial[-1] + [p]])]) for p in poss if p in h[partial[i][-1]] and partial[i - 1][j] in v[p]])
```
To run it:
```
test3 = [
[1, 1, 0, 1, 0, 1, 0, 1, 1, 0],
[1, 1, 0, 0, 0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0, 1, 1, 0, 0]
]
expected3 = 11567
assert(solve(test3) == expected3)
```
] |
[Question]
[
Given a positive integer `n`, output the `2^n` binary sequences of length `n` sorted in the following precise ordering.
Test cases:
0:
```
0 or 1 (defining this is a matter of debate)
```
1:
```
0
1
```
2:
```
00
01
10
11
```
3:
```
000
001
010
100
011
101
110
111
```
4:
```
0000
0001
0010
0100
1000
0011
0101
1001
0110
1010
1100
0111
1011
1101
1110
1111
```
etc.
Additionally, the pattern of combinatorics is related to Pascal's Triangle.
0:
```
1 (this is given regardless of the definition given to 2^0)
```
1:
```
1
1
```
2:
```
1
2
1
```
3:
```
1
3
3
1
```
4:
```
1
4
6
4
1
```
etc.
[Answer]
## Haskell, 78 bytes
```
import Data.List
f n=sortOn(\x->sum x:reverse(map(1-)x))$mapM id$[0,1]<$[1..n]
```
Usage example: `f 2` -> `[[0,0],[0,1],[1,0],[1,1]]`.
How it works:
```
[0,1]<$[1..n] -- make n copies of the list [0,1]
mapM id -- make all lists where the ith element is from the ith list.
-- that gives us all binary sequences
sortOn -- sort this list of list
sum x -- first by number of ones
reverse(map(1-)x) -- then by the reversed list with bits flipped
```
[Answer]
## Python 2, 146 bytes
```
from itertools import*
lambda i:sum([sorted({''.join(b)for b in permutations((i-n)*"0"+"1"*n)},key=lambda x:x[::-1])[::-1]for n in range(i+1)],[])
```
I'm still working on this, though any suggestions would be greatly appreciated!
Ungolfed
```
i=input()
import itertools
p=[]
for n in range(i+1):
x=(i-n)*"0"+"1"*n
t=[]
for b in itertools.permutations(x):t+=[''.join(b)] if ''.join(b) not in t else []
p.append(sorted(t, key=lambda x:x[::-1])[::-1])
p=sum(p,[])
print
for line in p:print line
```
[Answer]
# Python 2, ~~122~~ ~~120~~ ~~102~~ 98 bytes
*18 bytes saved thanks to Flp.Tkc*
*4 bytes saved thanks to xnor*
```
lambda x:sorted([bin(i)[2:].zfill(x)for i in range(2**x)],key=lambda x:(sorted(x),int(x[::-1],2)))
```
## Explanation
This makes all the binary strings of length x with:
```
[bin(i)[2:].xfill(x)for i in range(2**x)]
```
I then sort them according to:
```
lambda x:(sorted(x),int(x[::-1],2))
```
`sorted(x)` prioritizes the number of `1`s while `int(x[::-1],2)` prioritizes the second condition
Lastly these are joined with newlines and printed.
[Answer]
## Perl, 63 bytes
*-4 thanks to @Ton Hospel.*
*-2 thanks to @Gabriel Benamy.*
```
say~~reverse for sort{$b=~y/0//-$a=~y/0//||$b-$a}glob"{1,0}"x<>
```
Run with `-E` (which enable the feature `say`) :
```
perl -E 'say~~reverse for sort{$b=~y/0//-$a=~y/0//||$b-$a}glob"{1,0}"x<>' <<< 5
```
---
**Short explanations**:
* `"{1,0}"x$_` creates a string composed of `$_` times`{1,0}` (`$_` is the input). For instance with `3` : `{1,1}{1,0}{1,0}`.
* Then [`glob`](http://perldoc.perl.org/functions/glob.html) does some magic and generates all combinations of one element from each group of braces (that is, all the combinations we want to print).
* And then the sort : `$b=~y/1//c-$a=~y/1//c` compares the number of `1` in each string, and if they have the same number, `$b-$a` will sort according to the second rule.
[Answer]
# Perl, ~~116~~ ~~106~~ ~~105~~ 102 bytes
```
sub e{sprintf"%0$%b",@_}sub f{$_=e@_;/0*$/;$%*y/1//-$-[0]}map{say e$_}sort{f($a)<=>f$b}0..2**($%=<>)-1
```
Readable:
```
sub e{
sprintf"%0$%b",@_
}
sub f{
$_=e@_;/0*$/;$%*y/1//-$-[0]
}
map{
say e$_
} sort {
f($a)<=>f$b
} 0..2**($%=<>)-1
```
The subroutine `e` converts its argument into a binary value, padded with zeros, to be the input length (e.g. input of 5 pads with zeros until it's 5 characters long). The subroutine `f` takes such a binary value, and gives it sorting weight according to how it should be processed.
The range 0 .. [input]2-1 is then put through a stable sort, ordering by the weight (here, "stable" means that when two values have the same weight, they are returned in the same order they appear in the input), and then they are fed back to the subroutine `e` and output.
Some of you may have seen my original post, but I entirely misread the problem yesterday and deleted it immediately after I realized it.
[Answer]
## Racket 109 bytes
```
(let loop((s ""))(if(= n(string-length s))(displayln s)(for((i '("0" "1")))(loop(string-append s i)))))
```
Ungolfed:
```
(define (f n)
(let loop ((s ""))
(if (= n (string-length s))
(displayln s)
(for ((i '("0" "1")))
(loop (string-append s i))))))
```
Testing:
```
(f 2)
(println "-------------")
(f 3)
(println "-------------")
(f 4)
```
Output:
```
00
01
10
11
"-------------"
000
001
010
011
100
101
110
111
"-------------"
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
```
[Answer]
# Ruby 2.x, 129 bytes
```
f=->(n){z='0';p=n.bit_length;(0..n).map{|i|sprintf("%0#{p}d",i.to_s(2))}.sort{|a,b|a=a.delete(z).size-(b=b.delete(z).size)||b-a}}
```
[Answer]
# PHP, 49 bytes
```
while($i<1<<$n=$argv[1])printf("%0${n}b\n",$i++);
```
Run with `-r`.
[Answer]
## MATLAB, 68 bytes
```
d=@(n)dec2bin(sortrows([sum(dec2bin(0:2^n-1)');0:2^n-1]')*~eye(2,1))
```
[Answer]
# Bash, 65 bytes
**Golfed**
```
seq -f "obase=2;%g+2^$1-1" $[2**$1]|bc|cut -c2-|tr 0 ~|sort|tr ~ 0
```
**Test**
```
>./binseq 4
0000
0001
0010
0100
1000
0011
0101
0110
1001
1010
1100
0111
1011
1101
1110
1111
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
2Ḷṗ⁸TṪ$N$ÞSÞYȯ
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//MuG4tuG5l@KBuFThuaokTiTDnlPDnlnIr////zQ "Jelly – Try It Online")
Surprised this hadn't been posted yet.
] |
[Question]
[
*Koronkorko* is the Finnish word for *compound interest*. We don't want compound interest in our strings, so let's find the shortest possible regular expression to exclude it.
Given a string consisting only of the uppercase alphabetic characters A-Z, determine the shortest possible regular expression that matches the string if it does not contain the substring `KORONKORKO`. Any string that contains `KORONKORKO` as a substring should not be matched by the regex.
Only the characters `A`-`Z`, `[`, `]`, `-`, `^`, , `?`, `*`, `+`, `|`, `(`, and `)` should be used in the expression.
I think this can be done with 118 characters in the expression. Can you make it shorter?
Note: This challenge is from [Ohjelmointiputka](http://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=kala) (in Finnish).
[Answer]
# 204 characters
```
(K((O(R(O(NKORO)*(NK(O(RK)?)?)?)?)?)?K)*(O(R(O(NKORO)*(N(K(O(RK?[^KO]|[^KR])|[^KO])|[^K])|[^KN])|[^KO])|[^KR])|[^KO])|[^K])*(K((O(R(O(NKORO)*(NK(O(RK)?)?)?)?)?)?K)*(O(R(O(NKORO)*(N(K(O(RK?)?)?)?)?)?)?)?)?
```
Generated by turning `.*KORONKORKO.*` into a finite state machine, inverting the finite state machine, and turning it back into a regex.
[Answer]
# Python, ~~77~~ ~~79~~ ~~97~~ 118 bytes
**Edit 3:** Rewrite. Uses nested lookaheads
```
^([^K]|K(?=$|[^O]|O(?=$|[^R]|R(?=$|[^O]|O(?=$|[^N]|N(?=$|[^K]|K(?=$|[^O]|O(?=$|[^R]|R(?=$|[^K]|K(?=$|[^O]))))))))))*$
```
[Regex 101](https://regex101.com/r/kO7vM2/2)
**Edit 2:** Added '$|' throughout the regex. Now, if a prefix of KORONKORKO has been matched, the next item to match is end-of-string, a character that ends the prefix, or a character that extends the prefix if it is followed by something that ends the prefix.
This regex works with `re.fullmatch()`, which was added in Python 3.4. To use with `re.match()`, `^` and `$` need to be added to the beginning and end of the pattern, respectively, for 2 more bytes.
```
([^K]|K($|[^O]|O($|[^R]|R($|[^O]|O($|[^N]|N($|[^K]|K($|[^O]|O($|[^R]|R($|[^K]|K($|[^O]))))))))))*
```
[Regex101 link](https://regex101.com/r/kO7vM2/1)
Previous **incorrect** solution (see comments):
```
K|([^K]|K([^O]|O([^R]|R([^O]|O([^N]|N([^K]|K([^O]|O([^R]|R([^K]|K[^O])))))))))*
```
**Edit:** Added single K
] |
[Question]
[
## Introduction
You are probably familiar with the ["puts on sunglasses"](http://knowyourmeme.com/memes/puts-on-sunglasses-yeeeeaaahhh) emoticon-meme:
```
(•_•)
( •_•)>⌐■-■
(⌐■_■)
```
In this challenge, your task is to take the first line as input, and output the last one, effectively putting sunglasses on that little button-eyed person.
To make the task a bit more difficult, the characters have been scaled up and converted to (ugly) ASCII art.
## Input
Your input is *exactly* this multi-line string, with an optional trailing newline:
```
r t
/ \
: :
/ ,##. ,##. \
| q##p q##p |
| ** ** |
\ /
: :
\ /
L ########## j
```
## Output
Your output is *exactly* this multi-line string, again with an optional trailing newline:
```
r t
/ \
: ______ ______ :
/ |######| |######| \
| _______ |######| |######| |
| #"""""" |######| |######| |
\ # |######| |######| /
: " """""" """""" :
\ /
L ########## j
```
Note that there are no trailing spaces in the input and output.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
[Answer]
# Retina, ~~210~~ ~~161~~ ~~156~~ 133 bytes (ISO 8859-1 encoding)
Completely remade, doesn't care about input anymore.
```
s`.+
3r41t¶2/43\¶1:15,13,5:¶1/10 e\¶|5_,e |¶|5#'e |¶1\4#5 e/¶1:4"10'13'5:¶2\43/¶3L19 10$*#11j
e
3~11~4
~
|6$*#|
,
6$*_
'
6$*"
\d+
$*
```
There is a trailing space at the end of last line. Also, a trailing newline is included in the output. If you want to suppress it, change the second last line to `\`\d+`
Old version, which uses parts of input in output:
```
( {3})(.+¶){3}.{10}( +)\S+( +).¶.( +)(.+¶){5}.+?(#+).+
$1rq te /q$1\e:pf,p$1,f:e/p$4~$3~$4\¶|f,_$1~$3~f|¶|f#'$1~$3~f|e\$4#$4f~$3~$4/e:$4"p'p$1'f:e \q$1/¶$1Lpp$7$3j
~
|6$*#|
,
6$*_
'
6$*"
q
pppp
p
ff
e
¶
f
5$*
```
[Try it online! (210-byte version)](http://retina.tryitonline.net/#code=KCB7M30pKC4rwrYpezN9LnsxMH0oICspXFMrKCArKS7Cti4oICspKC4rwrYpezV9Lis_KCMrKS4rCiQxcnEgdGUgL3EkMVxlOnBmLHAkMSxmOmUvcCQ0fiQzfiQ0XMK2fGYsXyQxfiQzfmZ8wrZ8ZiMnJDF-JDN-ZnxlXCQ0IyQ0Zn4kM34kNC9lOiQ0InAncCQxJ2Y6ZSBccSQxL8K2JDFMcHAkNyQzagp-Cnw2JCojfAosCjYkKl8KJwo2JCoiCnEKcHBwcApwCmZmCmUKwrYgCmYKNSQqIA&input=ICAgciAgICAgICAgICAgICAgICAgICAgICAgdAogIC8gICAgICAgICAgICAgICAgICAgICAgICAgXAogOiAgICAgICAgICAgICAgICAgICAgICAgICAgIDoKIC8gICAgLCMjLiAgICAgICAgICAgLCMjLiAgICBcCnwgICAgIHEjI3AgICAgICAgICAgIHEjI3AgICAgIHwKfCAgICAgICoqICAgICAgICAgICAgICoqICAgICAgfAogXCAgICAgICAgICAgICAgICAgICAgICAgICAgIC8KIDogICAgICAgICAgICAgICAgICAgICAgICAgICA6CiAgXCAgICAgICAgICAgICAgICAgICAgICAgICAvCiAgIEwgICAgICAjIyMjIyMjIyMjICAgICAgIGo)
[Try it online! (161-byte version)](http://retina.tryitonline.net/#code=c2AuKwppcnEgdGUgL3FpXGU6cGYscGksZjplL3BpIH5wIH5pIFzCtnxmXyxpfnAgfmZ8wrZ8ZiMnaX5wIH5mfGVcaSAjZmkgfnAgfmkgL2U6aSAicCdwaSdmOmUgXHFpL8K2aUxwcDEwJCojcCBqCn4KfDYkKiN8CiwKNiQqXwonCjYkKiIKcQpwcHBwCnAKZmYKZgppICAKaQozJCogCmUKwrYg&input=ICAgciAgICAgICAgICAgICAgICAgICAgICAgdAogIC8gICAgICAgICAgICAgICAgICAgICAgICAgXAogOiAgICAgICAgICAgICAgICAgICAgICAgICAgIDoKIC8gICAgLCMjLiAgICAgICAgICAgLCMjLiAgICBcCnwgICAgIHEjI3AgICAgICAgICAgIHEjI3AgICAgIHwKfCAgICAgICoqICAgICAgICAgICAgICoqICAgICAgfAogXCAgICAgICAgICAgICAgICAgICAgICAgICAgIC8KIDogICAgICAgICAgICAgICAgICAgICAgICAgICA6CiAgXCAgICAgICAgICAgICAgICAgICAgICAgICAvCiAgIEwgICAgICAjIyMjIyMjIyMjICAgICAgIGo)
[Try it online! (156-byte version)](http://retina.tryitonline.net/#code=c2AuKwppcnEgdGUgL3FpXGU6cGYscGksZjplL3BnXMK2fGZfLGTCtnxmIydkZVxrI2ZnL2U6ayJwJ3BpJ2Y6ZSBccWkvwrZpTHBwMTAkKiNwIGoKZAppfnAgfmZ8CmcKa35wIH5rCn4KfDYkKiN8CiwKNiQqXwonCjYkKiIKcQpwcHBwCnAKZmYKZgprIAprCmkgCmkKMyQqIAplCsK2IA&input=ICAgciAgICAgICAgICAgICAgICAgICAgICAgdAogIC8gICAgICAgICAgICAgICAgICAgICAgICAgXAogOiAgICAgICAgICAgICAgICAgICAgICAgICAgIDoKIC8gICAgLCMjLiAgICAgICAgICAgLCMjLiAgICBcCnwgICAgIHEjI3AgICAgICAgICAgIHEjI3AgICAgIHwKfCAgICAgICoqICAgICAgICAgICAgICoqICAgICAgfAogXCAgICAgICAgICAgICAgICAgICAgICAgICAgIC8KIDogICAgICAgICAgICAgICAgICAgICAgICAgICA6CiAgXCAgICAgICAgICAgICAgICAgICAgICAgICAvCiAgIEwgICAgICAjIyMjIyMjIyMjICAgICAgIGo)
[Try it online! (133-byte version)](http://retina.tryitonline.net/#code=c2AuKwozcjQxdMK2Mi80M1zCtjE6MTUsMTMsNTrCtjEvMTAgZVzCtnw1XyxlIHzCtnw1IydlIHzCtjFcNCM1IGUvwrYxOjQiMTAnMTMnNTrCtjJcNDMvwrYzTDE5IDEwJCojMTFqCmUKM34xMX40Cn4KfDYkKiN8CiwKNiQqXwonCjYkKiIKXGQrCiQqIA&input=ICAgciAgICAgICAgICAgICAgICAgICAgICAgdAogIC8gICAgICAgICAgICAgICAgICAgICAgICAgXAogOiAgICAgICAgICAgICAgICAgICAgICAgICAgIDoKIC8gICAgLCMjLiAgICAgICAgICAgLCMjLiAgICBcCnwgICAgIHEjI3AgICAgICAgICAgIHEjI3AgICAgIHwKfCAgICAgICoqICAgICAgICAgICAgICoqICAgICAgfAogXCAgICAgICAgICAgICAgICAgICAgICAgICAgIC8KIDogICAgICAgICAgICAgICAgICAgICAgICAgICA6CiAgXCAgICAgICAgICAgICAgICAgICAgICAgICAvCiAgIEwgICAgICAjIyMjIyMjIyMjICAgICAgIGo)
[Answer]
# Bubblegum, 97 bytes
```
0000000: e001 e500 595d 0010 6818 841b 8ec4 c1cd ....Y]..h.......
0000010: edc4 82fe b74a b6dd affc 98aa dccc 0d35 .....J.........5
0000020: 6869 7333 10ec f862 efbc 1475 9496 cacf his3...b...u....
0000030: 5379 f091 507e 3df4 4a1d 51fc 98f7 4fb8 Sy..P~=.J.Q...O.
0000040: a8e0 2e3e 3b1b dc32 cbcf 5f0c d010 9d96 ...>;..2.._.....
0000050: 63e9 c49a fc44 60ef 7680 9b58 9027 c000 c....D`.v..X.'..
0000060: 00
```
Compressed using LZMA. [Try it online.](http://bubblegum.tryitonline.net/#code=MDAwMDAwMDogZTAwMSBlNTAwIDU5NWQgMDAxMCA2ODE4IDg0MWIgOGVjNCBjMWNkICAuLi4uWV0uLmguLi4uLi4uCjAwMDAwMTA6IGVkYzQgODJmZSBiNzRhIGI2ZGQgYWZmYyA5OGFhIGRjY2MgMGQzNSAgLi4uLi5KLi4uLi4uLi4uNQowMDAwMDIwOiA2ODY5IDczMzMgMTBlYyBmODYyIGVmYmMgMTQ3NSA5NDk2IGNhY2YgIGhpczMuLi5iLi4udS4uLi4KMDAwMDAzMDogNTM3OSBmMDkxIDUwN2UgM2RmNCA0YTFkIDUxZmMgOThmNyA0ZmI4ICBTeS4uUH49LkouUS4uLk8uCjAwMDAwNDA6IGE4ZTAgMmUzZSAzYjFiIGRjMzIgY2JjZiA1ZjBjIGQwMTAgOWQ5NiAgLi4uPjsuLjIuLl8uLi4uLgowMDAwMDUwOiA2M2U5IGM0OWEgZmM0NCA2MGVmIDc2ODAgOWI1OCA5MDI3IGMwMDAgIGMuLi4uRGAudi4uWC4nLi4KMDAwMDA2MDogMDAgIA&input=ICAgciAgICAgICAgICAgICAgICAgICAgICAgdAogIC8gICAgICAgICAgICAgICAgICAgICAgICAgXAogOiAgICAgICAgICAgICAgICAgICAgICAgICAgIDoKIC8gICAgLCMjLiAgICAgICAgICAgLCMjLiAgICBcCnwgICAgIHEjI3AgICAgICAgICAgIHEjI3AgICAgIHwKfCAgICAgICoqICAgICAgICAgICAgICoqICAgICAgfAogXCAgICAgICAgICAgICAgICAgICAgICAgICAgIC8KIDogICAgICAgICAgICAgICAgICAgICAgICAgICA6CiAgXCAgICAgICAgICAgICAgICAgICAgICAgICAvCiAgIEwgICAgICAjIyMjIyMjIyMjICAgICAgIGoK)
[Answer]
# JavaScript (ES6), 200 bytes
```
a=>a.split`
`.map((l,i)=>l[s="slice"](0,6)+(["_7 3",'#"6 3',"# 9",'" 9'][i-4]||" 9")+(g=[" _5 ",x="|#5|",x,x,x,' "5 '][i-2]||" 7")+l[s](10,21)+g+l[s](25)).join`
`.replace(/.\d/g,m=>m[0].repeat(m[1]))
```
## Explanation
Replaces the eyes of the input with run-length encoded glasses, then decodes them.
```
var solution =
a=>
a.split`
`.map((l,i)=> // for each line of the input
l[s="slice"](0,6) // left outline
+(["_7 3",'#"6 3',"# 9",'" 9'][i-4]||" 9") // glasses frame
+(g=[" _5 ",x="|#5|",x,x,x,' "5 '][i-2]||" 7") // left glasses lens
+l[s](10,21) // mouth
+g // right glasses lens
+l[s](25) // right outline
)
.join`
` // combine altered lines
.replace(/.\d/g,m=>m[0].repeat(m[1])) // run-length decoding
result.textContent = solution(
` r t
/ \\
: :
/ ,##. ,##. \\
| q##p q##p |
| ** ** |
\\ /
: :
\\ /
L ########## j`
);
```
```
<pre id="result"></pre>
```
[Answer]
## Python 3, 283 bytes
```
import zlib;print(zlib.decompress('x\x9cSPP(R \x16\x94p)(è\x13\xadZA!\x86KÁ\nM(\x1e\x0cp\tYq¡\x9b_£\x0c\x0658\x84b¸j\x90Ì\x88\'¬A¡\x06ªCY\t\x0c\x88Ò¡\x10\x03ÖA¬£ô¡ÞVBHÃ-Ã*\x04ô6Ä\n"\x01Ð\x02\x05\x05\x1fl2Êp\x80$\x98\x05\x00ð>KB\n'.encode('latin-1')).decode())
```
[Try it online](http://ideone.com/kyRyOV)
Doing the encoding and decoding to deal with the fact that `zlib.decompress` expects a `bytes` object is about 30 bytes cheaper than just directly passing a bytes object:
```
import zlib;print(zlib.decompress(b'x\x9cSPP(R \x16\x94p)(\xe8\x13\xadZA!\x86K\xc1\nM(\x1e\x0cp\tYq\xa1\x9b_\xa3\x0c\x0658\x84b\xb8j\x90\xcc\x88\'\xacA\xa1\x06\xaaCY\t\x0c\x88\xd2\xa1\x10\x03\xd6A\xac\xa3\xf4\xa1\xdeVBH\xc3-\xc3*\x04\xf46\xc4\n"\x01\xd0\x02\x05\x05\x1fl2\xcap\x80$\x98\x05\x00\xf0>KB').decode())
```
[Answer]
# [~~05AB1E~~ Osable](https://github.com/Adriandmen/05AB1E), 174 bytes
Well, this was a mistake... 05AB1E doesn't have any compression built-in except for a dictionary compression method. Code:
```
2FSð18×sJ,}17÷\?'_6×Dð13×sð5×VY':J,ð'/ð14×J?'|'#6×'|JDð11×sð4×JUX'\J,'|Y'_7×ð3×Xð'|J,'|Y'#'"6×ð3×Xð'|J,ð'\ð4×'#ð9×X'/J,ð':ð4×'"ðT×'"6×Dð13×sY':J,\\\\\Sð18×sJ,5÷ð4×srð14×srJ?,
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MkZTw7AxOMOXc0osfTE3w7dcPydfNsOXRMOwMTPDl3PDsDXDl1ZZJzpKLMOwJy_DsDE0w5dKPyd8JyM2w5cnfEpEw7AxMcOXc8OwNMOXSlVYJ1xKLCd8WSdfN8OXw7Azw5dYw7AnfEosJ3xZJyMnIjbDl8OwM8OXWMOwJ3xKLMOwJ1zDsDTDlycjw7A5w5dYJy9KLMOwJzrDsDTDlyciw7BUw5cnIjbDl0TDsDEzw5dzWSc6SixcXFxcXFPDsDE4w5dzSiw1w7fDsDTDl3Nyw7AxNMOXc3JKPyw&input=ICAgciAgICAgICAgICAgICAgICAgICAgICAgdAogIC8gICAgICAgICAgICAgICAgICAgICAgICAgXAogOiAgICAgICAgICAgICAgICAgICAgICAgICAgIDoKIC8gICAgLCMjLiAgICAgICAgICAgLCMjLiAgICBcCnwgICAgIHEjI3AgICAgICAgICAgIHEjI3AgICAgIHwKfCAgICAgICoqICAgICAgICAgICAgICoqICAgICAgfAogXCAgICAgICAgICAgICAgICAgICAgICAgICAgIC8KIDogICAgICAgICAgICAgICAgICAgICAgICAgICA6CiAgXCAgICAgICAgICAgICAgICAgICAgICAgICAvCiAgIEwgICAgICAjIyMjIyMjIyMjICAgICAgIGo)
Uses **CP-1252** encoding.
[Answer]
# Python 2, 120 bytes
This source contains non-printable characters, so it is presented as a hexdump that can be decoded with `xxd -r`.
```
00000000: efbb bf70 7269 6e74 2778 018d cea7 1503 ...print'x......
00000010: 310c 5c30 50ae 29fe 3b0f 60ee 19b2 411a 1.\0P.).;.`...A.
00000020: 0f4b 81de 3dbd b7d3 67ea c246 d62e a8f2 .K..=...g..F....
00000030: 66a1 79b5 3cfb 956a a17a d1cb 59ff 919a f.y.<..j.z..Y...
00000040: 4507 cb8b f101 3d3a 28c3 596a c20c 4af6 E.....=:(.Yj..J.
00000050: a91a 1a0c eeee c7be a65a 3093 5703 135f .........Z0.W.._
00000060: 943b 0fab 03f0 3e4b 4227 2e64 6563 6f64 .;....>KB'.decod
00000070: 6528 277a 6970 2729 e('zip')
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 214 bytes
```
3\r꘍41\t꘍+,2\/꘍43\\꘍+,1\:꘍2꘍13\_6*꘍d5\:꘍Wṅ,1\/꘍3꘍11\|\#3*+m꘍d4\\꘍Wṅ,\|5꘍\_7*` |###`m3꘍øm2\|꘍Wṅ,\|5꘍\#\"6*` |###`m3꘍øm2\|꘍Wṅ,1\\꘍4\#꘍ð6*` |###`m3꘍øm1\/꘍Wṅ,1\:꘍4\"꘍₀\"6*3꘍꘍d2\:꘍Wṅ,2\\꘍43\/꘍+,3\L꘍20\#₀*꘍11\j꘍++,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=3%5Cr%EA%98%8D41%5Ct%EA%98%8D%2B%2C2%5C%2F%EA%98%8D43%5C%5C%EA%98%8D%2B%2C1%5C%3A%EA%98%8D2%EA%98%8D13%5C_6*%EA%98%8Dd5%5C%3A%EA%98%8DW%E1%B9%85%2C1%5C%2F%EA%98%8D3%EA%98%8D11%5C%7C%5C%233*%2Bm%EA%98%8Dd4%5C%5C%EA%98%8DW%E1%B9%85%2C%5C%7C5%EA%98%8D%5C_7*%60%20%20%20%7C%23%23%23%60m3%EA%98%8D%C3%B8m2%5C%7C%EA%98%8DW%E1%B9%85%2C%5C%7C5%EA%98%8D%5C%23%5C%226*%60%20%20%20%7C%23%23%23%60m3%EA%98%8D%C3%B8m2%5C%7C%EA%98%8DW%E1%B9%85%2C1%5C%5C%EA%98%8D4%5C%23%EA%98%8D%C3%B06*%60%20%20%20%7C%23%23%23%60m3%EA%98%8D%C3%B8m1%5C%2F%EA%98%8DW%E1%B9%85%2C1%5C%3A%EA%98%8D4%5C%22%EA%98%8D%E2%82%80%5C%226*3%EA%98%8D%EA%98%8Dd2%5C%3A%EA%98%8DW%E1%B9%85%2C2%5C%5C%EA%98%8D43%5C%2F%EA%98%8D%2B%2C3%5CL%EA%98%8D20%5C%23%E2%82%80*%EA%98%8D11%5Cj%EA%98%8D%2B%2B%2C&inputs=&header=&footer=)
A hardcoding mess.
] |
[Question]
[
While we're on a [triangular grids kick](https://codegolf.stackexchange.com/questions/68996/alignment-on-triangular-grids), I'd like to point out that there is an equivalent to [polyominoes](https://en.wikipedia.org/wiki/Polyomino) on a triangular grid. They are called [polyiamonds](https://en.wikipedia.org/wiki/Polyiamond), and they are shapes formed by gluing equilateral triangles together along their edges. In this challenge you are going to be deciding which subsets of a triangular grid are polyiamonds, and whether they have holes in them. Because it only takes 9 triangles to make a polyiamond with a hole in it, your code needs to be as short as possible.
### The grid
We'll use [Martin's triangular grid layout](https://codegolf.stackexchange.com/questions/68996/alignment-on-triangular-grids) for the input:
[](https://i.stack.imgur.com/es3Pb.png)
Pay attention to the fact that the centers of the triangles form a roughly rectangular grid and that the top left triangle "points" upward. We can describe a subset of this grid, then, by giving a rectangular "star map" indicating which triangles are included and which are not included. For instance, this map:
```
** **
*****
```
corresponds to the smallest polyiamond which contains a hole:
[](https://i.stack.imgur.com/Mu124.png)
### Holes
A polyiamond which contains a hole like the example above (a region not a part of the polyiamond, which is surrounded on all sides by regions which *are*) is not, topologically speaking, *simply connected*.
### The Challenge
Write a function or program which takes as input a "star map" as described above and output a truthy if and only if the indicated subset of the triangular grid is a *simply connected polyiamond*.
### More Examples
```
*** ***
*******
```
corresponds to the polyiamond
[](https://i.stack.imgur.com/Nzceh.png)
which is simply connected.
---
```
* *
** **
***
```
corresponds to the polyiamond
[](https://i.stack.imgur.com/ArEXt.png)
which is simply connected.
---
```
** **
*** **
****
```
corresponds to the *non*-polyiamond
[](https://i.stack.imgur.com/k8dCp.png)
which would not be simply connected even if it *were* a polyiamond.
### Input Spec
* The input will consist only of asterisks, spaces, and line feeds.
* The first character of input will always be a space or asterisk (corresponding to the upward pointing triangle in the top left corner of the grid).
* There will always be at least one asterisk on the first and last lines.
* There is NO guarantee that lines after the first line won't be empty. Two linefeeds in a row may appear in a legitimate input.
* Line lengths need not all be the same.
### Winning Condition
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
### Test Cases
Truthy maps:
```
1) *
2) *
*
3) **
4) *** ***
*******
5) * *
** **
***
6) *
**
*
7) **
***
****
8) ****
** *
*****
9) ***********
** ** **
**** ** **
**
************
```
Falsy maps:
```
1) *
*
*
2) * *
3) *
*
4) **
**
5) ***
***
6) ** **
*****
7) ** **
*** **
****
8) *
*
9) *****
** *
*****
```
[Answer]
# [Snails](https://github.com/feresum/PMA), 95 bytes
```
F&
lr|=((ul.)2 ,l~a~)d|!((ul.)2 ,l~a~)u}\*}+l\ ,~a~|{\ (lr|=((ul.)2 ,l~a~)d|!((ul.)2 ,l~a~)u}+~
```
This really suffered from duplication, as I haven't implemented macros or any kind of back-reference. What it does is to check that for each star, there exists a path to the leftmost star on the top line; and for each space, there is a path to an edge of the grid.
```
F& ,, option F: pad lines with spaces to the length of the longest
,, option &: print 1 iff match succeeds from every cell
lr ,, direction left or right, or
| =((ul.)2 ,l~a~) d ,, direction down, if we are an even number of orthogonal moves from the top left
| !((ul.)2 ,l~a~) u ,, or, direction up if we are odd number of moves from the top left
} \* ,, literal '*'
}+ ,, 1 or more times
l\ ,~a~ ,, check that we are on the leftmost * in the top line
| ,, the part before this is for starting on '*'; part after for starting on ' '
{ \ ,, literal ' '
( lr ,, direction left or right, or
| =((ul.)2 ,l~a~) d ,, same drill as before...
| !((ul.)2 ,l~a~) u
}+ ,, 1 or more times
~ ,, end on an out of bounds cell
```
[Answer]
## CJam, ~~101~~ 98 bytes
```
qN/_z,f{' e]}{S2*f+W%z}4*:eeee::f+:~{_(aL{+_{_2,.+1$2,.-@_:+1&!2*(a.+}%2${a1$&},\;@1$-@@}h;\;-}2*!
```
[Try it online.](http://cjam.tryitonline.net/#code=cU4yKi97Ti8zZj5OKjpROwoKUU4vX3osZnsnIGVdfXtTMipmK1clen00KjplZWVlOjpmKzp-e18oYUx7K197XzIsLisxJDIsLi1AXzorMSYhMiooYS4rfSUyJHthMSQmfSxcO0AxJC1AQH1oO1w7LX0yKiEKCl1vTm99Lw&input=MSkgKgoKMikgKgogICAqCgozKSAqKgoKNCkgKioqICoqKgogICAqKioqKioqCgo1KSAqICAgKgogICAqKiAqKgogICAgKioqCgo2KSAqCiAgICoqCiAgICAqCgo3KSAgICAqKgogICAgICoqKgogICAqKioqCgo4KSAqKioqCiAgICoqICAgKgogICAgKioqKioKCjkpICoqKioqKioqKioqCiAgICoqICAgICoqICAqKgogICAgKioqKiAgKiogICoqCiAgICAgICAgICAgICAgKioKICAgKioqKioqKioqKioqIAoKMSkgKgogICAqCiAgICoKCjIpICogKgoKMykgKgogICAgKgoKNCkgICoqCiAgICoqCgo1KSAqKioKICAgCiAgICoqKgoKNikgKiogKioKICAgKioqKioKCjcpICoqICAqKgogICAqKiogKioKICAgICoqKioKCjgpICAqCiAgICAqCgo5KSAqKioqKgogICAqKiAgICoKICAgICoqKioq&debug=on)
I finally overcame my fear of implementing a flood fill in CJam. It's about as ugly as I expected, and it can most definitely be golfed.
The general idea is to perform two flood-fills (which are actually implemented as removals from the list of unvisited cells). The first pass will remove all spaces that are reachable from the edge. The second pass will then pick the first `*` in reading order and remove all the triangles reachable from that. If and only if the resulting list is empty, the polyiamond was simply connected:
* If the polyiamond had a hole, the first flood fill is unable to reach and remove that hole.
* If the input consists of several disconnected polyiamonds, the second flood fill is unable to reach and remove all of them.
] |
[Question]
[
When you round a number, if the next digit is `>= 5` you add 1. For example:
```
3.1415926535 rounded to 1dp is 3.1
3.1415926535 rounded to 4dp is 3.1416 <-- Note the 5 changed to 6
3.1415926535 rounded to 5dp is 3.14159
3.1415926535 rounded to 9dp is 3.141592654 <-- Note the 3 changed to 4
```
You challenge is to receive an integer as input and output the number of decimal places before which you would have to round the square root of the number - i.e. the number of decimal places before anumber digit which is `>= 5` occurs.
The integer will be between 0 and 100,000 inclusive so for the edge case of 59752 you need to support 17 decimal points (to check the 17th).
If you programming language can't change the number of decimal points, you can display a "?" message to the user.
Example:
```
Input Root Output
5 -> 2.23 606797749979 -> 2
41 -> 6.40312423 743284 -> 8 (Largest gap under 100)
596 -> 24.4131112314 674 -> 10 (Largest gap under 1000)
59752 -> 244.44222221212112029 -> 16 (Largest gap under 100000)
```
Do what you want on perfect squares.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins.
---
For anyone interested, the number 310,617 is the biggest under 1,000,000 and has 18 before you reach a digit `>= 5`.
[Answer]
# CJam, 17 bytes
```
rie40mQsJ~>'4f>1#
```
[Try it online.](http://cjam.aditsu.net/#code=rie40mQsJ~%3E'4f%3E1%23&input=59752)
[Answer]
# Pyth, 13 bytes
```
f<5e@=*QC\d2Z
```
[Test suite](https://pyth.herokuapp.com/?code=f%3C5e%40%3D%2aQC%5Cd2Z&test_suite=1&test_suite_input=3%0A5%0A41%0A596%0A59752&debug=0)
Start with `Q` equal to the input.
At each time step, multiply `Q` by 100, calculated as `chr('d')`. Take its square root. Take this mod 10. If the result is greater than `5`, terminate. Print the number of iterations it took to terminate, 0-indexed.
In detail:
```
f<5e@=*QC\d2Z
Q = eval(input())
f Z Filter for the first truthy result over the infinite sequence
starting at Z (= 0)
=*Q Q *=
C\d chr('d') (= 100)
---------------------
@ Q 2 Q ^ (1/2)
e % 10
<5 5 <
```
[Answer]
# CJam, ~~29~~ ~~26~~ 28 bytes
```
rimqs_'.+'.#)>{'5<}%0#]W'?er
```
[Try it Online.](http://cjam.aditsu.net/#code=rimqs_'.%2B'.%23)%3E%7B'5%3C%7D%250%23%5DW'%3Fer&input=81)
Puts a "?" if the number does not appear that can be rounded up (perfect square or too long).
[Answer]
## Pyth, 22 bytes
```
J`%@Q2 1x.e<\4@Jbr2lJ1
```
Explanation
```
- Autoassign Q to evaluated input
@Q2 - Get the square root of Q
J`% 1 - Get the stuff after the decimal point and put it in a string. Store in J
.e r2lJ - Create a range between 2 and the length of the string (forget about the 0. bit) and enumerate over it
@Jb - Get the current decimal place
<\4 - Is it bigger than 4
x 1 - Find the position of the first True value
```
I'm absolutely certain this can be golfed. If the input doesn't have a digit higher than 4, it will print -1. Supports 17dp.
[Answer]
## Javascript, 59 bytes
```
f=a=>(a=/\.(.*?)[5-9]/.exec(Math.sqrt(a)),a?a[1].length:'?')
```
Returns `?` for 59752 because JavaScript only uses double precision.
[Answer]
# Linux shell, 52 bytes
```
dc -e'34k?vp'|cut -d. -f2|sed 's/.[5-9\s].*//'|wc -m
```
I tried for a pure `dc` solution, but failed. Precision is adjustable (first number).
As the OP kindly specifies that "you can do what you want on perfect squares", in this case this solution outputs the precision + 1, in this case 35.
[Answer]
# Mathematica 60 bytes
```
(Position[Drop@@RealDigits[N[Sqrt@#,99]],x_/;x>4][[1,1]]-1)&
```
---
**Example**
```
(Position[Drop@@RealDigits[N[Sqrt@#, 99]], x_ /; x > 4][[1, 1]] - 1) &[59752]
```
>
> 16
>
>
>
[Answer]
# Ruby, 46 Bytes
This may not be valid, as it only fits 16 digits.
```
p (gets.to_i**0.5).to_s.split('.')[1]=~/[5-9]/
```
] |
[Question]
[
`dog` is a command-line utility that takes in an arbitrary number of arguments,
the first of which is the text to be written and the others are arbitrarily many files.
The `dog` utility will split the text in equal portions over these files. If there is a remainder `n`, the first `n` files get an additional byte
`dog` is the opposite of `cat`, as such, forall `x`, the following should hold.
```
$> dog x a.txt b.txt ...
$> cat a.txt b.txt ...
x$>
```
Where `...` indicates arbitrarily many files.
An example (12 bytes, 3 files, can be split evenly):
```
$> ./dog.py "Dogs vs Cats" a.txt b.txt c.txt
$> cat a.txt
Dogs$> cat b.txt
vs $> cat c.txt
Cats$> cat a.txt b.txt c.txt
Dogs vs Cats$>
```
An example with remainder (13 bytes, 5 files, remainder 3):
```
9$>./dog.py "0123456789abc" a.txt b.txt c.txt d.txt e.txt
$> cat a.txt
012$> cat b.txt
345$> cat c.txt
678$> cat d.txt
9a$> cat e.txt
bc$> cat a.txt b.txt c.txt d.txt e.txt
0123456789abc$>
```
[Answer]
# Pyth - 12 bytes
```
.wMC,cl.zz.z
```
Uses builtin split function and then uses splat-map on the write function. Doesn't work online.
[Answer]
# Python - 181 bytes
```
import sys
a=sys.argv
l=len
d=a[2:]
s=a[1]
n,r=divmod(l(s),l(d))
p=0
for i in range(l(d)):
with open(d[i],'w') as f:
o=n+int(i<=n)
f.write(s[p:p+o])
p+=o
```
[Answer]
# PHP, 107 bytes
The golfed code:
```
for($i=1;++$i<$argc;fputs(fopen($argv[$i],w),substr($s=$argv[1],($i-2)*$l=ceil(strlen($s)/($argc-2)),$l)));
```
The detailed code:
```
$len = ceil(strlen($argv[1])/($argc - 2));
for ($i = 2; $i < $argc; $i ++) {
$fh = fopen($argv[$i], 'w');
fputs($fh, substr($argv[1], ($i - 2) * $len, $len));
fclose($fh); // omitted in the golfed version
}
```
[Answer]
### Pure bash: 97
```
s=$1;shift;for((l=${#s}/$#,m=${#s}-l*$#,i=1;i<=$#;p+=q,i++)){
printf "${s:p:q=i>m?l:l+1}">${!i};}
```
As a function: (`p=` is only required for second run)
```
dog() { p=
s=$1;shift;for((l=${#s}/$#,m=${#s}-l*$#,i=1;i<=$#;p+=q,i++)){
printf "${s:p:q=i>m?l:l+1}">${!i};}
}
```
Tests
```
$> rm *
$> dog "Dogs vs Cats" a.txt b.txt c.txt
$> ls -l
total 12
-rw-r--r-- 1 user user 4 May 13 22:09 a.txt
-rw-r--r-- 1 user user 4 May 13 22:09 b.txt
-rw-r--r-- 1 user user 4 May 13 22:09 c.txt
$> cat {a,b,c}.txt;echo
Dogs vs Cats
$>
```
All files is 4 byte len and concatenated in right order, contain *"Dogs vs Cats"*.
```
$> rm *
$> dog "$(printf "%s" {0..9} {a..c})" {a..e}.txt
$> ls -l
total 20
-rw-r--r-- 1 user user 3 May 13 22:09 a.txt
-rw-r--r-- 1 user user 3 May 13 22:09 b.txt
-rw-r--r-- 1 user user 3 May 13 22:09 c.txt
-rw-r--r-- 1 user user 2 May 13 22:09 d.txt
-rw-r--r-- 1 user user 2 May 13 22:09 e.txt
$> cat *;echo
0123456789abc
$>
```
Firsts files is 3 byte len and last only 2, concatenated by alphabetic order, contain *"0123456789abc"*.
### Explanation (ungolfing):
If you hit: `declare -f dog`, [bash](/questions/tagged/bash "show questions tagged 'bash'") will answer:
```
$> declare -f dog
dog ()
{
p=;
s=$1;
shift;
for ((l=${#s}/$#,m=${#s}-l*$#,i=1; i<=$#; p+=q,i++))
do
printf "${s:p:q=i>m?l:l+1}" > ${!i};
done
}
```
This could be written:
```
dog2 ()
{
position=0;
string=$1;
shift;
partLen=$((${#string}/$#));
oneMore=$((${#string}-partLen*$#));
for ((i=1; i<=$#; i++))
do
if ((i<=oneMore)); then
partQuant=$((partLen+1));
else
partQuant=$partLen;
fi;
printf "${string:position:partQuant}" > ${!i};
((position+=partQuant));
done
}
```
[Answer]
# Ruby, ~~93~~ 87 bytes
Full program using command line arguments.
If I could use `s.slice!` to mutate the string, I'd do that instead of needing to use `s[c..-1]`, but Ruby doesn't let you mutate the strings from argv without duplicating them first
```
s,*t=$*
d,r=s.size.divmod t.size
t.map{|e|open(e,?w)<<s[0,c=(0>r-=1)?d:d+1];s=s[c..-1]}
```
] |
[Question]
[
Any binary floating point can be formatted exactly in decimal. The resulting string might be somewhat long, but it is possible. In [my article on floating point](http://mortoray.com/2015/07/06/essential-facts-about-floating-point-calculations/) I cover the importance of precision, and now I want this function. This challenge is to write a program, or function, that takes a floating point value as input and formats an exact decimal string as output.
To ensure we are working with the correct floating point numbers a precise format must be provided as input to the program. This format will be two integers `Significand Exponent`, where the actual floating point value is `Significand * 2 ^ Exponent`. Note that either value can be negative.
Specifics:
* The range and precision of at least a 32-bit float must be supported (no input will go beyond that)
* The decimal formatted value must be an exact representation (simply close enough to guarantee a correct round-tip back to float is not good enough)
* We don't trust standard library floating point formatting functions to be correct enough nor fast enough (ex: `printf`), and thus they may not be used. *You* must do the formatting. Integral formatting/conversion functions are allowed.
* There may not be any leading or trailing zeros, except for the required one leading zero in front of the `.` if there is no whole number component
* A function, or whole program, is allowed.
Examples:
```
1 -2 => 0.25
17 -3 => 2.125
-123 11 => -251904
17 50 => 19140298416324608
23 -13 => 0.0028076171875
3 120 => 3987683987354747618711421180841033728
3 -50 => 0.00000000000000266453525910037569701671600341796875
-3 -50 => -0.00000000000000266453525910037569701671600341796875
10 -2 => 2.5
-12345 -3 => -1543.125
0 0 => 0
161 -4 => 10.0625
512 -3 => 64
```
Shortest code wins.
[Answer]
# CJam, 43
```
r_'-&\ize999rim<s1e3'0e[W%999/(i_L?\+'.*sW%
```
[Try it online](http://cjam.aditsu.net/#code=r_'-%26%5Cize999rim%3Cs1e3'0e%5BW%25999%2F(i_L%3F%5C%2B'.*sW%25&input=-12345%20-3)
**Explanation:**
The program works with exponents up to ±999, close to double precision (64 bit). It separates the minus sign (if present) from the significand, multiplies it by 10999 then does a bit shift with the exponent, which is now an exact calculation. It then pads to the left with zeros if the result has less than 1000 digits, separates the last 999 digits as the fractional part, removes trailing zeros by converting its reverse to integer, adds a decimal point if needed, and puts everything back together.
```
r_ read and duplicate the significand in string form
'-& keep only the minus sign, if present
\ swap with the other copy of the significand
iz convert to integer and get absolute value
e999 multiply by 10^999
ri read the exponent and convert to integer
m< shift left by it; negative values will shift right
the result is an exact non-negative integer
s convert to string
1e3'0e[ pad to the left with zero characters up to length 1000
longer strings will be left intact
we need 1 more than 999 for the 0.xxx case
W% reverse the string
999/ split into slices of length 999
( take out the first slice (reversed fractional part)
i convert to integer
this removes the leading zeros (trailing in reverse)
_L? if it's zero, replace with an empty string
\+ concatenate back (to the left) with the second slice
'.* join the with the dot character
if the fractional part was zero, we only have the second slice
(reversed integer part) and there is nothing to join
s convert to string; this is the reversed result without the sign
W% reverse back
```
At the end, the minus sign (if any) and the final string are automatically printed together.
[Answer]
# CJam, 50 bytes
```
q~A1$z#\_0>K5?\z:E#@_s'-&oz*\md_sE'0e[W%isW%'.\+Q?
```
This is a full program that reads from STDIN. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~A1%24z%23%5C_0%3EK5%3F%5Cz%3AE%23%40_s'-%26oz*%5Cmd_sE'0e%5BW%25isW%25'.%5C%2BQ%3F&input=-12345%20-3).
[Verify all test cases at once.](http://cjam.aditsu.net/#code=qN%2F%7B%5B~A1%24z%23%5C_0%3EK5%3F%5Cz%3AE%23%40_s'-%26oz*%5Cmd_sE'0e%5BW%25isW%25'.%5C%2BQ%3FN%5Do%7D%2F&input=1%20-2%0A10%20-2%0A17%20-3%0A-123%2011%0A17%2050%0A23%20-13%0A-12345%20-3%0A3%20120%0A3%20-50%0A-3%20-50)
[Answer]
# GNU sed + dc, 65
Score includes +1 for sed's `-r` option.
```
y/-/_/
s/.*/dc -e"C8k& 2r^*p"/e
s/\\\n//
s/0+$//
s/^(-?)\./\10./
```
I was tempted to claim this `dc`-only answer `C8k& 2r^*p` for a score of 10, but `dc` has some formatting quirks:
* the -ve sign is `_` instead of `-`
* long lines are broken with backslashes
* trailing zeros must be removed
* leading 0 for `|n| < 1` must be added
So the dc expression is wrapped and evaled by `sed` to take care of the above.
### Test output:
```
$ echo "1 -2
17 -3
-123 11
17 50
23 -13
3 120
3 -50
-3 -50
8388608 127
1 -127" | sed -rf float.sed
0.25
2.125
-251904
19140298416324608
0.0028076171875
3987683987354747618711421180841033728
0.00000000000000266453525910037569701671600341796875
-0.00000000000000266453525910037569701671600341796875
1427247692705959881058285969449495136382746624
0.0000000000000000000000000000000000000058774717541114375398436826861112283890933277838604376075437585313920862972736358642578125
$
```
] |
[Question]
[
A *musical string* is any string that can be played on a piano keyboard.
For those of us who weren't forced to learn the piano as kids, here is what the keyboard looks like.

So the string `feed a dead cabbage` is a musical string because every single letter corresponds to one of these nots.
Your challenge is to write a program that takes a string as input from STDIN, and finds the longest musical substring. Then your program must print the substring, and it's length. Here are some sample inputs/outputs.
>
> Input: "FEED ME! I'm hungry!"
>
>
> Output: feed 4
>
>
>
>
> Input: No no no, no musistrin!
>
>
> Ouput: 0
>
>
>
>
> Input: `"A **bad** !!!fAd82342"`
>
>
> Output: abadfad 7
>
>
>
>
> Input: "Good golfing!"
>
>
> Output: dg 2
>
>
>
# Rules
* Your output may be upper or lower-case, but there must be no punctuation or spaces.
* There will capitalization and punctuation in the input string, but this doesn't affect whether or not a substring is considered "musical" or not.
* There must be a space between the musical substring, and the number.
[Answer]
# Pyth, ~~25~~ 23 bytes
```
pdJef!-T<G7+k.:@Grz0)lJ
```
2 bytes saved thanks to @Jakube.
[Demonstration.](https://pyth.herokuapp.com/?code=pdJef!-T%3CG7%2Bk.%3A%40Grz0)lJ&input=%22FEED+ME!+I%27m+hungry!%22&debug=0) [Test harness.](https://pyth.herokuapp.com/?code=Fz%2Bz.z+%0ApdJef!-T%3CG7%2Bk.%3A%40Grz0)lJ&input=%22FEED+ME!+I%27m+hungry!%22%0ANo+no+no%2C+no+musistrin!%0A%22A+**bad**+!!!fAd82342%22%0A%22Good+golfing!%22&debug=0)
Explanation:
* `rz0`: The input, in lowercase.
* `@Grz0`: Strip any non-alphabetic characters.
* `.:@Grz0)`: Generate all substrings.
* `+k.:@Grz0)`: Add in the empty string.
* `f ... +k.:@Grz0)`: Filter over these strings.
* `-T<G7`: Filter each string for non musical characters.
* `!-T<G7`: Negate the result. This is `True` if and only if the string was musical.
* `f!-T<G7+k.:@Grz0)`: Filter out the musical strings.
* `ef!-T<G7+k.:@Grz0)`: Take the last such string. `.:` orders substrings by size, so this is also the longest musical substring.
* `Jef!-T<G7+k.:@Grz0)`: Assign the result to `J`.
* `pdJ`: Print `J`, with `d`, space, as the ending character.
* `lJ`: Then, print the length of `J`.
[Answer]
# Ruby, ~~83~~ 75 characters
Fairly self-explanatory.
```
puts"#{s=gets.gsub(/[^a-z]/i,'').split(/[^a-g]/i).max_by &:size} #{s.size}"
```
Takes advantage of the fact that Ruby can split strings on regex (`.split(/[^a-g]/)`).
[Answer]
# Perl, 58
```
#!perl -p
$\=0;map{$i++;$\="$& $i"if/[a-g]{$i}/i}(s/\W//gr)x y!!!cd
```
Use:
```
$ perl ~/mus.pl <<<"FEED ME! I'm hungry!"
FEED 4
```
or
```
$ perl -pe'$\=0;map{$i++;$\="$& $i"if/[a-g]{$i}/i}(s/\W//gr)x y!!!cd' <<<"FEED ME! I'm hungry!"
FEED 4
```
[Answer]
# Java, 268
```
class Z{public static void main(String[]a){String s=new java.util.Scanner(System.in).nextLine().toLowerCase().replaceAll("[^a-z]",""),t;for(int i=s.length();i-->0;)if(!(t=s.replaceFirst("^(.*)([a-g]{"+i+"})(.*)$","$2")).equals(s)){System.out.println(t+" "+i);break;}}}
```
Expanded:
```
class Z {
public static void main(String[] a) {
String s = new java.util.Scanner(System.in).nextLine().toLowerCase().replaceAll("[^a-z]", ""), t;
for (int i = s.length(); i-- > 0;) {
if (!(t = s.replaceFirst("^(.*)([a-f]{" + i + "})(.*)$", "$2")).equals(s)) {
System.out.println(t + " " + i);
break;
}
}
}
}
```
[Answer]
## Perl 5 (106)
```
use List::Util reduce;$_=lc<>;s/[^a-z]//g;$_=reduce{length$a>length$b?$a:$b}m/[a-g]+/g;print"$_ ",0+length
```
[Answer]
# R, ~~98~~ 94 bytes
```
p=strsplit(gsub("[^a-z]","",readline(),T),"[^a-gA-G]+")[[1]];m=max(n<-nchar(p));cat(p[n==m],m)
```
Ungolfed + explanation:
```
# Read from STDIN and remove all non-alphabetic characters
r <- gsub("[^a-z]", "", readline(), ignore.case = TRUE)
# Split r into a vector of substrings on characters other than a-g
p <- strsplit(r, "[^a-g]+")[[1]]
# Get the number of characters in each substring
n <- nchar(p)
# Get the length of the longest substring
m <- max(n)
# Print the string and length
cat(p[n == m], m)
```
Suggestions are welcome!
Note: The output is now mixed-case, which is allowed per the OP's edit. This saved 4 bytes.
[Answer]
# [golflua](http://mniip.com/misc/conv/golflua/), ~~84~~ ~~85~~ 84 bytes
```
B=I.r():g("%A",""):g("[^a-gA-G]"," ")M=0Q=""~@W B:gm("(%w+)")?#W>M M=#W Q=W$$w(Q,M)
```
I first ~~force lowercase, then~~ strip ~~spaces~~ non-letter characters, then remove all non-musical letters on the input (stdin). I then scan through each remaining word and compare its length before outputting the largest and length (stdout). There's probably a shorter way to do the loop, but at the moment this is what I've got.
An ungolfed Lua code would be
```
Line = io.read() -- read stdin
NoSpaced = Line:gsub("%A","") -- strip non-letter chars
MusicalLetters = NoSpaced:gsub("[^a-gA-g]", " ") -- remove non-musical letters
WordLen = 0, LongWord = "" -- helpers
for words in MusicalLetters:gmatch("(%w+)") do -- scan for longest word
if words:length() > WordLen then
WordLen = words:length()
LongWord = words
end
end
print(LongWord, WordLen) -- output solution
```
] |
[Question]
[
In some cases, often in physics, you have to sum graphs. Your challenge is to write, in a language of your choice, a program or function that takes multiple graphs as images, calculates all possible sums, and outputs the result.
## Graphs
The graphs are images that contain a white (`rgb(255, 255, 255)`) background with a non-white pixel in each column. Examples:



The values of the script are represented as the Y positions of the colored pixels. The value at a certain X coordinate is equal to the Y position of the uppermost colored pixel in that column, with coordinates starting from 0 at the bottom left. There may or may not be additional colored pixels below those pixels for aesthetical reasons.
## Task
Your task is to write, in a language of your choice, a program or function that takes multiple graphs as images, calculates all the possible `2^n - 1` sums, and outputs the result.
A sum of graphs is a graph where each column's value is equal to the sum of the values of the corresponding column in each of the input graphs.
The graphs will come in multiple colors. The result image must contain all possible sums of the graphs as other graphs, including the original graphs but excluding the zero sum.
The color of each sum is determined by the average of the colors of the graphs included, for example, graphs of colors `rgb(255, 0, 255)` and `rgb(0, 255, 255)` would produce a graph of `rgb(128, 128, 255)` (may also be rounded down).
The resulting image should be as high as required to fit all graphs. This means you may have to output an image larger than any of the inputs.
The order in which the resulting graphs are drawn to the resulting image does not matter, i.e. if result graphs overlap, you may choose which one is on top, but it has to be one of the graphs, not a combination of their colors.
You may assume that the input images are of equal width, that all columns of the images have at least one non-white pixel, and that the heights of the images (including output) are below 4096 pixels.
## Example
Input A:

Input B:

Example output:

(In case someone is interested, I copy-pasted the data for these from random companies' stock charts. That was the first way I found to get realistic data as CSV.)
## Rules
* You may choose any bitmap image input file format.
* You may choose any bitmap image output file format, which doesn't have to match the input.
* You may use image processing libraries, however any functions to complete this task directly are banned.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
## Graph generator script
Here is a Python 2 script that generates graphs. Input is given in lines, with the three first lines as the RGB color and the rest as data, terminated by EOF.
```
import PIL.Image as image
import sys
if len(sys.argv) < 2:
sys.stderr.write("Usage: graphgen.py <outfile> [infile]")
exit(1)
outfile = sys.argv[1]
if len(sys.argv) > 2:
try:
stream = open(sys.argv[2], "r")
data = stream.read()
stream.close()
except IOError as err:
if err.errno == 2:
sys.stderr.write("File \"{0}\" not found".format(sys.argv[2]))
else:
sys.stderr.write("IO error {0}: {1}".format(err.errno, err.strerror))
exit(1)
else:
data = sys.stdin.read()
try:
items = map(int, data.strip().split("\n"))
red, green, blue = items[:3]
items = items[3:]
highest = max(items)
except (ValueError, TypeError, IndexError):
sys.stderr.write("Invalid value(s) in input")
img = image.new("RGB", (len(items), highest + 1), (255, 255, 255))
prev = items[0]
img.putpixel((0, highest - items[0]), (red, green, blue))
for x, item in enumerate(items[1:]):
img.putpixel((x + 1, highest - item), (red, green, blue))
if item < prev:
for i in range(item + 1, prev):
img.putpixel((x, highest - i), (red, green, blue))
else:
for i in range(prev + 1, item):
img.putpixel((x + 1, highest - i), (red, green, blue))
prev = item
img.save(outfile, "png")
```
[Answer]
# Python, 422
Call from commandline `python plotsum im1.png im2.png im3.png`
```
import sys
from numpy import*
from scipy import misc as m
R=m.imread
r=range
a=array
N=sys.args[1:]
L=len(N)
P=[map(argmin,R(n,1).T)for n in N] #converts image to list of heights, counting from the top
C=a([R(N[i])[P[i][0],0,:]for i in r(L)]) #finds and stores the colour
P=a([len(R(N[i]))-a(P[i])for i in r(L)]) #flips the numbers, measures actual heights from bottom
w=len(P[0])
h=max(sum(P,0))+1 #compute dimensions
G=ones((h,w,3))*255 #and make a white grid
for i in r(1,2**L):
z=where(a(list(bin(i)[2:].zfill(L)))=='1');y=sum(P[z],0) #sum the graphs
for x in r(w):G[y[x],x,:]=average(C[z],0) #average the colours
m.imsave('S.png',G[::-1]) #flip image vertically and save
```
Example output

Another example

That was a tricky one, high-level array operations and using arrays as indices helps a lot here. I dont expect to see solutions under 1000 bytes except in Mathematica and Matlab
[Answer]
## MATLAB, 405
Call via: `f('https://i.stack.imgur.com/ffCzR.png','https://i.stack.imgur.com/zHldg.png')`
```
function f(varargin)
for k=1:nargin
i=im2double(imread(varargin{k}))
V(k,:)=size(i,1)-cellfun(@(V)find(any(V~=1,3),1),num2cell(i,[1,3]))
C(k,:)=i(find(any(i(:,1,:)~=1,3),1),1,:)
end
s=2^nargin-1
G=dec2bin(1:s)-'0'
C=bsxfun(@rdivide,G*C,sum(G,2))
V=G*V
m=max(V(:))
r=ones(m+1,size(V,2))
g=r
b=r
for i=1:s
M=bsxfun(@eq,(m:-1:0).',V(i,:))
r(M)=C(i,1)
g(M)=C(i,2)
b(M)=C(i,3)
end
imwrite(cat(3,r,g,b),'S.png')
```
] |
[Question]
[
A downhill maze is given as a series of rows of space separated digits from 0 to 9 inclusive, plus one "S" and one "X", where the S denotes the start and the X denotes the finish. In a downhill maze, you may only go to a space that is adjacent to you to the north, south, east, or west (no diagonals), and you may only go to spaces with a value less than or equal to the value you are currently on.
The program should output a path to navigate through the maze in the same format as the input, only all traversed spaces should have a "." in them, and all unvisited spaces should have a "#" in them. The starting and ending cells should also keep their "S" and "X", respectively. You can assume there is always a solution to the maze.
Example input:
```
3 3 3 3 2 1 S 8 9
3 1 1 3 3 0 6 8 7
1 2 2 4 3 2 5 9 7
1 2 1 5 4 3 4 4 6
1 1 X 6 4 4 5 5 5
```
Example output:
```
. . . . # # S . #
. # # . . # # . .
. # # # . # # # .
. # # # . # # # .
. . X # . . . . .
```
[Answer]
# C# - 463
Accepts input via STDIN, and should produce an optimal path, tested for the given test case, but not otherwise. Assumes there is always a solution.
I'm in a bit of a hurry, I have a deadline in 7 hours, but this just looked like too much fun to miss out on. I'm also out of practice. It could be very embarrassing if this goes wrong, but it's reasonably golfed.
```
using C=System.Console;class P{static void Main(){var S=C.In.ReadToEnd().Replace("\r","").Replace('X','+');int s=S.IndexOf('S'),e=S.IndexOf('+'),w=S.IndexOf('\n')+1,L=S.Length,i,j=L;var K=new int[L];for(K[s]=s+2;j-->0;)for(i=0;i<L;i+=2){System.Action<int>M=z=>{if((z+=i)>=0&z<L&&S[z]<=S[i]&K[z]<1&K[i]>0&(i%w==z%w|i/w==z/w))K[z]=i+1;};M(2);M(-2);M(w);M(-w);}for(w=e;w!=s+1;w=i){i=K[w]-1;K[w]=-1;}for(;++j<L;)C.Write(j%2<1?K[j]<0?j==s?'S':j==e?'X':'.':'#':S[j]);}}
```
Code with comments:
```
using C=System.Console;
class P
{
static void Main()
{
var S=C.In.ReadToEnd().Replace("\r","").Replace('X','+'); // read in the map, replace X with + because + < 0
int s=S.IndexOf('S'),e=S.IndexOf('+'),w=S.IndexOf('\n')+1,L=S.Length,i,j=L; // find start, end, width, length
var K=new int[L]; // this stores how we got to each point as loc+1 (0 means we havn't visited it)
for(K[s]=s+2; // can't risk this being 0
j-->0;) // do L passes
for(i=0;i<L;i+=2) // each pass, look at every location
{
// if a whole load of bouds checks, point new location (i+z) at i
System.Action<int>M=z=>{if((z+=i)>=0&z<L&&S[z]<=S[i]&K[z]<1&K[i]>0&(i%w==z%w|i/w==z/w))K[z]=i+1;};
// try and move in each direction
M(2);
M(-2);
M(w);
M(-w);
}
for(w=e;w!=s+1;w=i) // find route back
{
i=K[w]-1; // previous location
K[w]=-1; // set this so we know we've visited it
}
for(;++j<L;) // print out result
C.Write(j%2<1?K[j]<0?j==s?'S':j==e?'X':'.':'#':S[j]); // if K < 0, we visit it, otherwise we don't
}
}
```
[Answer]
# JavaScript (ES6) 219
A function returning true or false. The solution (if found) is output on the console.
It does not try to find an optimal solution.
```
f=o=>(r=(m,p,w=0,v=m[p])=>
v>':'
?console.log(' '+m.map(v=>v<0?'#':v,m[f]='X').join(' '))
:v<=w&&[1,-1,y,-y].some(d=>r([...m],d+p,v),m[p]='.')
)(o.match(/[^ ]/g).map((v,p)=>v>'S'?(f=p,0):v>':'?v:v<'0'?(y=y||~p,v):~v,y=0),f)
```
**Ungolfed** to death and explained more than needed
```
f=o=>{
var r = ( // recursive search function
m, // maze array (copy of)
p, // current position
w // value at previous position
)=>
{
var v = m[p]; // get value at current position
if (v == 'S') // if 'S', solution found, output and return true
{
m[f] = 'X'; // put again 'X' at finish position
m = m.map(v => { // scan array to obtain '#'
if (v < 0) // a numeric value not touched during search
return '#'
else
return v
}).join(' '); // array to string again, with added blanks (maybe too many)
console.log(' '+m) // to balance ' '
return true; // return false will continue the search and find all possible solutions
}
if (v <= w) // search go on if current value <= previous (if numeric, they both are negative)
{
m[p]='.'; // mark current position
return [1,-1,y,-y].some(d=>r([...m], d+p, v)) // scan in all directions
}
// no more paths, return false and backtrack
return false
}
var f, // finish position (but it is the start of the search)
y = 0; // offset to next/prev row
o = o.match(/[^ ]/g) // string to char array, removing ' 's
.map((v,p) => // array scan to find f and y, and transform numeric chars to numbers
{
if (v > 'S') // check if 'X'
{
f = p;
return 0; // 'X' position mapped to min value
}
if (v > ':') // check if 'S'
return v; // no change
if (v < '0') // check if newline
{
if (!y) y = ~p; // position of first newline used to find y offset
return v; // no change
}
return ~v; // map numeric v to -v-1 so have range (-1..-10)
})
return r(o, f, 0) // start with a fake prev value
}
```
**Test** in Firefox/FireBug console
```
f('3 3 3 3 2 1 S 8 9\n3 1 1 3 3 0 6 8 7\n1 2 2 4 3 2 5 9 7\n1 2 1 5 4 3 4 4 6\n1 1 X 6 4 4 5 5 5')
```
*Output*
```
. . . . # # S . #
. # # . . # # . .
. # # # . # # # .
. # # # . # # # .
. . X # . . . . .
true
```
] |
[Question]
[
Find Hole 1 [here](https://codegolf.stackexchange.com/questions/39748/9-holes-of-code-golf-kickoff).
Make a quine that, when run, outputs its own source code block multiple times. In fact, it must output it n times, where n in the next prime number.
I think an example shows it best.
```
[MY QUINE][MY QUINE]
[MY QUINE][MY QUINE][MY QUINE]
[MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE]
[MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE]
[MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE]
```
Each Program will output its base "block" (so [MY QUINE]) *the next prime number* times.
Built in functions to calculate whether a number is prime, (like an isPrime function), or to determine the next prime (like a nextPrime() function) are not allowed.
* This means that functions to list the number of divisors is not allowed
* Functions that return the prime factorization are likewise disallowed
This should be a true quine (except for some leeway, see next point), so you should not read your own source code.
Because languages like Java and C# are already at a disadvantage, You need not output totally working code. If it could be put in a function (that is called) and output the next quine, you are good.
This is code-golf, so shortest code wins!
[Answer]
# CJam, 31 bytes
```
{'_'~]-3>U):U{)__,1>:*)\%}g*}_~
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%7B'_'~%5D-3%3EU)%3AU%7B)__%2C1%3E%3A*)%5C%25%7Dg*%7D_~).
### Idea
To check for primality, we'll use [Wilson's theorem](https://en.wikipedia.org/?title=Wilson%27s_theorem), which states that an integer **n > 1** is prime if and only if **(n - 1)! ≡ -1 (mod n)**, which is true if and only if **(n - 1)! + 1 % n == 0**.
### Code
```
{ }_~ e# Define a block and execute a copy.
e# The original block will be on top of the stack.
'_'~] e# Push those characters and wrap the stack in an array.
-3> e# Keep only the last three elements (QUINE).
U):U e# Increment U (initially 0).
{ }g e# Do-while loop:
)__ e# Increment the integer I on the stack (initially U).
,1> e# Push [1 ... I-1].
:* e# Multiply all to push factorial(I-1).
)\% e# Push factorial(I-1) + 1 % I.
e# While the result is non-zero, repeat.
e# This pushes the next prime after U.
* e# Repeat QUINE that many times.
```
[Answer]
## CJam, ~~36~~ 35 bytes
```
{]W="_~"]U):U{)_,{)1$\%!},,2>}g*}_~
```
This can ~~definitely~~ be golfed further.
**How it works:**
```
{ }_~ "Copy this code block and execute the copy";
]W= "Take just the last element from the stack";
"The other thing on stack is the block from above";
"_~"] "Put "_~" on stack and wrap the 2 things in an array";
"At this point, the string representation of stack"
"elements is identical to the source code";
U):U "Increment U and update U's value. This variable"
"actually counts the number of [Quine] blocks";
{)_,{)1$\%!},,2>}g "Find the next prime number"
* "Repeat the array that many times, thus repeat the"
"[Quine] block, the next prime times";
```
Thanks to Martin for reminding me the `]W=` trick :)
[Try it online here](http://cjam.aditsu.net/)
[Answer]
## Mathematica, ~~248~~ 222 bytes
**Edit:** Fixed the usage of a prime-related function, but also improved the quining a bit.
**Edit:** Thanks to Dennis for introducing me to Wilson's theorem.
```
1;n=If[ValueQ@n,n+1,1];StringJoin@Array[#<>ToString[1##,InputForm]<>#2&@@\("1;n=If[ValueQ@n,n+1,1];StringJoin@Array[#<>ToString[1##,InputForm]<>#\2&@@("*"&,For[i=n,Mod[++i!/i+1,i]>0,0];i]")&,For[i=n,Mod[++i!/i+1,i]>0,0];i]
```
This assumes that the kernel is quit between subsequent runs of the quine (or at least `n` is reset), because it relies on `n` being undefined before the first instance of `[MyQuine]` is run.
This can probably be shortened a lot, but I don't have a lot of experience with quines, especially in Mathematica.
Here is an explanation:
```
1;
```
This doesn't do anything, but if concatenated onto the end of the previous quine, it multiplies the result of the last expression by `1` (which is a no-op) and the semicolon suppresses output. This ensures that only the last copy of `[MyQuine]` prints anything.
```
n=If[ValueQ@n,n+1,1];
```
This initialises `n` to `1` in the first copy of `[MyQuine]` and then increments it by `1` in each further copy - i.e. this just counts how many copies there are in `n`.
Skip ahead to the end now:
```
For[i=n,Mod[++i!/i+1,i]>0,0];i
```
This finds the next prime using [Wilson's theorem](http://en.wikipedia.org/wiki/Wilson's_theorem).
```
StringJoin@Array[#<>ToString[1##,InputForm]<>#2&@@\("QUINE_PREFIX"*"QUINE_SUFFIX")&,NEXTPRIME[n]]
```
This is the actual quine. It creates `NextPrime@n` copies of the code itself. It's also a bit weird. Yes, I'm multiplying two strings there, and no that doesn't have a meaningful result. `QUINE_PREFIX` contains all the code before the two strings and `QUINE_SUFFIX` contains all the code after the two strings. Now usually you use `Apply` (or `@@`) to turn a list into a series of arguments. But you can replace any `Head` with `Apply` - e.g. multiplication. So despite this being a product I can still turn it into into two arguments to my function. That function does:
```
#<>ToString[1##,InputForm]<>#2
```
Where `#` is the first argument (the prefix string), `#2` is the second argument (the suffix string), `##` is a sequence of both arguments. I need to prepend `1` to preserve the multiplication - otherwise `##` would splat into the argument list to `ToString`. Anyway, `ToString[1##,InputForm]&@@("abc"*"def")` returns `"abc"*"def"`... just what I need!
I think with all the stuff I need around the quine, an `eval`-based quine would be more appropriate here. I'll look into that later or tomorrow.
[Answer]
# J - 60 char
Uses the next-prime method like the other answers. (That's the `4 p:` bit.)
```
((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
```
A cute little J trick is that `f :g` acts like `f` when given one argument and `g` when given two. So, if you write out, say `f :;'a'f :;'a'f :;'a'` then that acts like `f'a';'a';'a'`, which is great because that's a boxed list whose items are `'a'` and whose length is the number of occurrences.
So we can lift that into a quiney sort of thing. The `f` we use looks like `(foo $~ bar)`, where `foo` constructs the string part that we repeat over and over, `bar` finds the next prime number and multiplies it by 60, the length of the string in `foo`.
```
((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
# ((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
180
((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
# ((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
300
```
[Answer]
# Python 2.7, 214
```
from sys import*;R,s=range,chr(35)
def N(n):
if n<3:return n+1
for p in R(n+1,n+n):
for i in R(2, p):
if p%i==0:break
else:return p
P=file(argv[0]).read();print(P.split(s)[0]+s)*N(P.count(chr(37)));exit(0)
#
```
] |
[Question]
[
Yesterday, I bought a harmonica:

*Figure 1: The harmonica.*
However, my dreams of being able to play soulful blues harmonica that moves people and causes a grown man to cry were quickly dashed by two problems:
1. The harmonica can only play certain notes;
2. I am depressingly bad at playing the harmonica.
Despite my lack of skill at the harmonica, there are still some songs that I can play on it. However, it is not immediately obvious if I am able to play some piece of music on the harmonica or not. Given the notes of a piece of music, write a program to determine if I could play it on my harmonica or not.
As the above picture shows, my harmonica has ten holes in it. With each hole, I can either exhale into it or inhale into it -- the hole that I choose, and whether I inhale or exhale into it changes the pitch of the resulting sound. Each hole has a different pitch on exhaling and inhaling, but there are some combinations that result in the same note. Overall, my harmonica can play 19 unique different pitches. The pitches are presented in musical scientific notation - the letter represents the note, and the number represents which octave it is in.
```
Hole Breathing Note
1 Exhale C4
1 Inhale D4
2 Exhale E4
2 Inhale G4
3 Exhale G4
3 Inhale B4
4 Exhale C5
4 Inhale D5
5 Exhale E5
5 Inhale F5
6 Exhale G5
6 Inhale A5
7 Exhale C6
7 Inhale B5
8 Exhale E6
8 Inhale D6
9 Exhale G6
9 Inhale F6
10 Exhale C7
10 Inhale A6
```
For example, if I exhaled on hole 3, I'd get a `G4` note. If I inhaled on hole 2, I'd *also* get a `G4` note. If I exhaled on hole 7, I'd get a `C6`.
When I breathe into the harmonica, apart from exhaling or inhaling, I can also choose whether to breathe *thinly* or *widely*. Breathing thinly causes only one hole to sound, whereas breathing widely causes one hole and both holes on either side of that hole to sound. I do not have the embouchure skills to blow onto two holes - it is either one or three.
For instance, if I thinly exhaled onto hole 4, only hole 4 would sound, so I would get a C5 sound. If I widely exhaled onto hole 4, holes 3, 4, and 5 would sound, and I'd get a G4,C5,E5 chord. If I widely inhaled onto hole 4, holes 3, 4, and 5 would sound but they would play the inhale pitches instead, which results in a B4,D5,F5 chord. Note that for the holes on either end, if I breath widely into them only two holes would sound (because there is no hole 0 or hole 11).
However, I cannot inhale and exhale at the same time. For instance, I could exhale into holes 4, 5, and 6 to result in the notes C5, E5, and G5 sounding at the same time, forming a chord. However, I can't inhale and exhale at the same time, so it would be impossible for me to play the chord C5,F5,A5 as I'd have to somehow exhale in hole 4 and inhale in hole 5 and 6. If this is stil unclear, [this comment thread](http://meta.codegolf.stackexchange.com/questions/2140/sandbox-for-proposed-challenges?cb=1#comment9273_2149) might be useful.
The input is the notes of the music. The notes are notated in the same way they are above in the table, and they are comma separated. Notes wrapped in curly brackets represent a chord. For instance:
```
C4,D4,G4,{D5,F5,A5},B5
```
This means, "C4, then D4, then G4, then D5, F5, and A5 at the same time, then B5." Your program will take a string in this format as input and output `True` if it is possible for me to play the music on my harmonica, or `False` otherwise. For sample inputs and outputs, the example above should output `True`. The input `{C5,F5,A5}` on the other hand will output `False`.
This is code golf, so the shortest entry wins.
Here are some test cases:
Input (A C Major scale):
```
C4,D4,E4,F4,G4,A4,B4,C5
```
Output:
```
False
```
(because the harmonica cannot play F4 or A4)
Input (the opening 2 bars of [Let It Go](https://www.youtube.com/watch?v=moSFlvxnbgk)):
```
E6,F6,A5,E6,F6,F6,E6,A5,F6,E6
```
Output:
```
True
```
Input:
```
{E6,G6,F6}
```
Output:
```
False
```
Input:
```
{G4,C5,E5},{F5,A5,B5}
```
Output:
```
True
```
**You may assume that chords will come in lower to higher pitch order.**
[Answer]
# Python - ~~218~~ ~~209~~ 189 chars
Minimal:
```
def t(s):from re import sub as r;exec('l=bool([x for x in['+r('"{','("',r('}"','")',r(',','","','"'+s+'"')))+']if"".join(x)not in"C4E4G4C5E5G5C6E6G6C7|D4G4B4D5F5A5B5D6F6A6"])');return not l
```
For ease of reading:
```
def t(s):
from re import sub as r
exec('l=bool([x for x in'
' [' + r( '"{' , '("' ,
r( '}"' , '")' ,
r( ',' , '","' , '"' + s + '"' ))) +
']'
' if "".join(x) not in "C4E4G4C5E5G5C6E6G6C7|D4G4B4D5F5A5B5D6F6A6"])')
return not l
```
Given a string formated as in the problem description, `t` return `True` if the sequence is playable on the described harmonica, and `False` if it isn't.
There is no check for the order of the notes in the chords. Unless told otherwise, I believe this is sufficient since that isn't in the problem statement, and it passes all given tests in:
```
assert not t("C4,D4,E4,F4,G4,A4,B4,C5")
assert t("E6,F6,A5,E6,F6,F6,E6,A5,F6,E6")
assert not t("{E6,G6,F6}")
assert t("{G4,C5,E5},{F5,A5,B5}")
```
[Answer]
# Javascript - ~~245~~ 243 chars
Minified:
```
function p(s){function f(s){s=s.replace(/\W/g,'');l=s.length;return((l-6)*(l-2)?l-4?'':'C4E4 G6C7 D4G4 F6A6':'C4E4G4C5E5G5C6E6G6C7 D4G4B4D5F5A5B5D6F6A6').indexOf(s)<0?0:''}return s.replace(/{.*?}/g,f).split(',').map(f).join('')?'False':'True'}
```
And expanded:
```
function p(s) {
function f(s) {
s = s.replace( /\W/g, '' );
l = s.length;
return ( (l-6)*(l-2) ? ( (l-4) ? '' : 'C4E4 G6C7 D4G4 F6A6' ) : 'C4E4G4C5E5G5C6E6G6C7 D4G4B4D5F5A5B5D6F6A6' ).
indexOf( s ) < 0 ? 0 : ''
}
return s.replace( /{.*?}/g, f ).split( ',' ).map( f ).join( '' ) ? 'False' : 'True'
}
```
The function `p` accepts a string as input and returns `True` if the note/chord sequence is playable, `False` otherwise.
It returns undefined results if the input isn't syntactically valid.
It also boldly assumes that chord notes are entered in order of ascending hole (such as in the example).
The character count can be reduced by 14 if the function is allowed to return logical `true` and `false` rather than their string equivalents.
[Answer]
# JavaScript (ES6), 230
Just a rewritten version of @COTO's answer:
```
f=s=>{s=s.replace(/\W/g,'');l=s.length;return((l-6)*(l-2)?(l-4?'':'C4E4 G6C7 D4G4 F6A6'):'C4E4G4C5E5G5C6E6G6C7 D4G4B4D5F5A5B5D6F6A6').indexOf(s)<0?0:''};p=s=>{return s.replace(/{.*?}/g,f).split(',').map(f).join('')?'False':'True'}
```
Would appreciate any tips on golfing this down further as I am starting to learn ES6! :-)
[Answer]
# Scala 178
```
print(readLine./:(""){(a,c)=>if("..C4E4G4C5E5G5C6E6G6C7...D4G4B4D5F5A5B5D6F6A6...."sliding(6)flatMap(y=>Seq("{"+y.diff("..")+"}",y take 2))contains a+c)""else a+c diff ","}=="")
```
Ungolfed:
```
print(
readLine.foldLeft(""){(a,c)=> # loop through the input
if("..C4E4G4C5E5G5C6E6G6C7...D4G4B4D5F5A5B5D6F6A6...." # from the harmonica
.sliding(6) # take 6 at a time
.flatMap(y=>Seq("{"+y.diff("..")+"}",y take 2)) # chords + single notes
.contains(a+c)) "" # clear matches
else a+c diff "," # drop commas
}=="" # did everything match?
)
```
Note that malformed input is handled badly - any string is accepted, and many malformed strings return true, for example:
```
{C,7.D}.C
```
prints true.
[Answer]
# Rebol - 188
```
t: func[s][trim/with s ","h: next split n:"C4E4G4C5E5G5C6E6G6C7..D4G4B4D5F5A5B5D6F6A6"2 forskip h 2[i
```
Ungolfed:
```
t: func [s] [
trim/with s ","
h: next split n: "C4E4G4C5E5G5C6E6G6C7..D4G4B4D5F5A5B5D6F6A6" 2
forskip h 2 [insert h '|]
h: head h
parse s [
any [
h | "{" x: copy c to "}" (unless find n c [c: n])
:x c "}"
]
]
]
```
Example usage (in Rebol console):
```
>> t "C4,D4,G4,{D5,F5,A5},B5"
== true
>> t "{C5,F5,A5}"
== false
>> t "C4,D4,E4,F4,G4,A4,B4,C5"
== false
>> t "E6,F6,A5,E6,F6,F6,E6,A5,F6,E6"
== true
>> t "{E6,G6,F6}"
== false
>> t "{G4,C5,E5},{F5,A5,B5}"
== true
```
While this code will catch gibberish like this:
```
>> t "{C,7.D}.C"
== false
```
However it will allow things like this through:
```
>> t "C,4,D4"
== true
```
Because its parsing it as "C4,D4".
Here's a more stricter version of the code:
```
t: func [s] [
h: next split n: "C4E4G4C5E5G5C6E6G6C7..D4G4B4D5F5A5B5D6F6A6" 2
forskip h 2 [insert h '|]
h: head h
d: ["," | end]
parse s [
any [
[
h | "{" x: copy c to "}" (
unless all [
parse c [any [h d]]
find n trim/with copy c ","
] [c: n]
)
:x c "}"
]
d
]
]
]
```
This golfs down to 228 chars and now returns `false` on...
```
>> t "C,4,D4"
== false
```
[Answer]
## JavaScript ES6, ~~211~~ ~~209~~ 190 chars
I know this can be golfed further. I will try to do so in a few hours;
Run this code in Latest Firefox's Web Console, you will get a method named `C` which you can then call like `C("{G4,C5,E5},{F5,A5,B5}")` and it will return `True` or `False` accordingly.
```
C=n=>(s='D4G4D5F5A5B5D6F6A6,C4E4G4C5E5G5C6E6G6C7',n.split(/[,}{]/g).some(a=>a&&!~s.search(a))||(m=n.match(/{[^}]+/g))&&m.some(a=>a.length!=9|!~s.search(a.replace(/{|,/g,"")))?'False':'True')
```
I am assuming a syntactically valid input.
**EDIT**: Simplified the regex and the length check.
] |
[Question]
[
## Some background
[Counting rods](http://en.wikipedia.org/wiki/Counting_rods) are small bars (3-14 cm long) that were used by mathematicians from many asian cultures for more than 2000 years to represent any whole number or fraction. (In this chqllenge we'l focus on unsigned integers though) There was also a written version, called rod numerals.
## Here's how it works:
(If at any point you get confused, go check out the ascii representation of each digit and some examples I have included at the bottom)
Rod numerals are a true positional numeral system with digits for 1-9 and blank for 0.
The digits consist of horizontal and vertical lines; the more lines, the higher the digit. Once you get past five, you put a horizontal line on top to add 5 to the numer of lines below.
One vertical line is 1, two vertical lines 2, five vertical lines is 5, one vertical line with a horizontal line on top is 6, four vertical lines with a horizontal line on top is 9 (the highest digit).
A vertical 3 digit:
```
|||
|||
|||
|||
|||
```
To make reading rod numerals easier though, they used different notation for each alternating digit. The second notation swaps the role of the horizontal and vertical lines. so that 3 is represented by three horizontal lines and 8 by three horizontal lines with a vertical line on top.
A horizontal 8 digit:
```
|
|
__|__
_____
_____
```
Knowing which notation to use is easy, as previously said, tehy are used alternatingly and [Sun Tzu](http://en.wikipedia.org/wiki/Sun_Tzu_(mathematician)) wrote that "one is vertical, ten is horizontal". So the rightmost digit is vertical and we alternate from there on.
## The challenge
These rods were used to represent negative numbers and fractions (as explained in the [wikipedia article on them](http://en.wikipedia.org/wiki/Counting_rods#Place_value). For the purpose of this challenge we'll only focus on positive integers though. The objective is simple:
Write a function or full program that takes an integer value as input in any way and prints the rod numeral representation of this integer to STDOUT (you may also write to a file if that works out better). Shortest code in bytes wins.
Every digit will be represented by 5x5 ascii characters and seperated by two collumns of 5 spaces. The exact representation you'll use for each digit is as follows:
```
space between two digits (two colums):
0 digit, both vertical and horizontal (five columns):
1 digit, vertical:
|
|
|
|
|
2 digit, vertical:
| |
| |
| |
| |
| |
3 digit, vertical:
|||
|||
|||
|||
|||
4 digit, vertical:
|| ||
|| ||
|| ||
|| ||
|| ||
5 digit, vertical:
|||||
|||||
|||||
|||||
|||||
6 digit, vertical:
_____
|
|
|
|
7 digit, vertical:
_____
| |
| |
| |
| |
8 digit, vertical:
_____
|||
|||
|||
|||
9 digit, vertical:
_____
|| ||
|| ||
|| ||
|| ||
1 digit, horizontal:
_____
2 digit, horizontal:
_____
_____
3 digit, horizontal:
_____
_____
_____
4 digit, horizontal:
_____
_____
_____
_____
5 digit, horizontal:
_____
_____
_____
_____
_____
6 digit, horizontal:
|
|
|
|
__|__
7 digit, horizontal:
|
|
|
__|__
_____
8 digit, horizontal:
|
|
__|__
_____
_____
9 digit, horizontal:
|
__|__
_____
_____
_____
```
The digits are to be printed next to each other. Trailing spaces beyond the bounding box of the last digit are not allowed. Trailing spaces to complete the bounding box of the last digit(s) are required. You should end the output with a single trailing newline. Leading spaces that do not belong to the bounding box of the first digit are also forbidden.
[Standard loopholes apply.](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny)
## Example output
Lines starting with `>` are to be interpreted as input.
```
>12
| |
| |
| |
| |
_____ | |
>8037
| _____
| | |
__|__ _____ | |
_____ _____ | |
_____ _____ | |
>950
_____ _____
|| || _____
|| || _____
|| || _____
|| || _____
```
[Answer]
# Python 2 - 216
My first shot, might be some stuff to take out, but my brain hurts, so it's good enough for now
```
x=raw_input()
for l in range(5):print' '.join((' '*7+'| | | ||| || '+'|'*7+'__|'+'_'*7)[[7*(4-l<n%6+n/6)+(n>5)*(l<10-n)-(l==10-n),n%6+n/6+(l<1)*(n>5)*(12-n)][(len(x)-i)%2]*5:][:5]for i,n in enumerate(map(int,x)))
```
[Answer]
# JavaScript (ES6) 223
Function with numeric parameter, output to console. NB If the input parameter could be a string, the code would be 5 char shorter and without the limit of 17 significative digits of JS numbers.
```
F=n=>{
for(r=s='',n+=s;r<5;r++,s+=q)
for(f=q='\n',p=n.length;f=!f,p--;q=(p?' ':'')+' 1 | 1 | | 1 ||| 1|| ||1|||||1_____1__|__'.split(1)[d]+q)
if(d=~~n[p])e=d+r,d=d>5?f?e<10?1:e>10?6:7:r?d-5:6:f?e>4?6:0:d;
console.log(s)
}
```
**Test**
Test in Firefox console.
`F(12)`
Output
```
| |
| |
| |
| |
_____ | |
```
`F(8037)`
Output
```
| _____
| | |
__|__ _____ | |
_____ _____ | |
_____ _____ | |
```
`F(950)`
Output
```
_____ _____
|| || _____
|| || _____
|| || _____
|| || _____
```
**Ungolfed**
```
F=n=>{
z=' 1 | 1 | | 1 ||| 1|| ||1|||||1_____1__|__'.split(1);
s='';
n+=s;
for (r = 0; r < 5; r++)
{
for(q='\n',f=1,p=n.length;f=!f,p--;)
{
d = ~~n[p];
if (d)
{
e=d+r;
if (d > 5)
{
if (f)
{
d = e < 10 ? 1 : e >10 ? 6 : 7;
}
else
{
d = r ? d-5 : 6;
}
}
else
{
if (f)
d = e > 4 ? 6 : 0;
}
}
q = (p ? ' ' : '') + z[d] + q;
}
s+=q
}
console.log(s)
}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 229 bytes
```
$n="$args"
0..4|%{$l=$_;$h=$n.Length%2
($n|% t*y|%{(' '*7+'| | | ||| || '+'|'*7+'_'*7+'|__')|% S*g(5*(('0123456666'+'0123451234'*4+'00000611110000661117000666117600666617660666667666')[50*($h=!$h)+10*$l+"$_"]-48))5})-join' '}
```
[Try it online!](https://tio.run/##rVPbToNAEH3frxhxcYECoS2XGkPSD/BN39Qgabe0hiwVaLTp9tvr7NI2RH2wiWcDnLmdmYTZdfXB62bJy/JAF5DC7kBFatC8LhqDBL4fSnNHy5Rmd3SZUuHfc1G0S3NELCqkCa2zxQSLAXOSAZMAIPGAlPiRwNClA1kXzjJmY9GDU1iRY1ksGI7GYRQjMLMz1Is5IZoK8RChiWKJJsiSWJMYSaxJnCgN@ykKHAvnvKJLezAMHFoODJoZL144se1ob3tv1UowALY/7Am5hkfetDDLG97ApuEwr9oGFlUNHF1QLaDm@XwlCqhEuSVkaqlnOHKnBvGPkHj@amQKJ8OY2q6SmwTjpBOU/g/oit9DJ0mpJXvp37tdFjqNdRsFaqpjrF9AJCbKf/RhS0Js3BoTdgQXCKhwgfLPNZ@1fI4rSbPO3XeduVfzdZnPOLBnn7m4h3Dhb9XSNW82ZYvCN3gJqOg79c4Yr8Lw@Pu5bT@B7A9f "PowerShell – Try It Online")
Where this string present digits:
```
# 0 1 2 3 4 5 6 7
# ' '.' | ',' | | ',' ||| ','|| ||','|||||','_____','__|__'
```
vertical rods:
```
" | | | ||| || |||||||____________________"+ # 0123456666
" | | | ||| || ||||||| | | | ||| || ||"+ # 0123451234
" | | | ||| || ||||||| | | | ||| || ||"+ # 0123451234
" | | | ||| || ||||||| | | | ||| || ||"+ # 0123451234
" | | | ||| || ||||||| | | | ||| || ||" # 0123451234
```
horizontal rods:
```
" _____ | | | | "+ # 0000061111
" __________ | | | __|__"+ # 0000661117
" _______________ | | __|_______"+ # 0006661176
" ____________________ | __|____________"+ # 0066661766
" ___________________________|_________________" # 0666667666
```
Unrolled script:
```
$digits=' '*7+'| | | ||| || '+'|'*7+'_'*7+'|__'
$positions = '0123456666'+'0123451234'*4+'00000611110000661117000666117600666617660666667666'
$n="$args"
0..4|%{
$line=$_
$horizontal=$n.Length%2
$chunks=$n|% toCharArray|%{
$horizontal=!$horizontal
$startFrom = 5*($positions[50*$horizontal+10*$line+"$_"]-48)
$digits|% Substring $startFrom 5
}
$chunks-join' '
}
```
] |
[Question]
[
Just like jQuery's `$.fn.text`, write one or two functions that can get and set the text on an element.
You can't use `textContent` or `innerText`, and even less `innerHTML`.
Plain javascript. No DOM library. It has to work on major browsers. (No need to care about old IE.)
Shortest code wins.
Enjoy!
[Answer]
## JavaScript (167)
```
function t(e,h,f){if(h||h==''){while(f=e.lastChild)e.removeChild(f);e.appendChild(document.createTextNode(h))}h=e.data||'';for(c in f=e.childNodes)h+=t(f[c]);return h}
```
Usage :
```
var textContent = t(yourElement); // get the text content
t(yourElement, ''); // clear
t(yourElement, newText); // sets a new text
```
Note that there is no pollution of the global namespace
[Demonstration](http://jsbin.com/ekusan/8/edit), with a multi-level DOM tree and a few tests
[Answer]
## JavaScript (175)
```
function t(e,v,f){if(!v&&v!=''){v=e.data||'';for(c in f=e.childNodes)v+=t(f[c]);return v}else{ while(c=e.lastChild)e.removeChild(c);e.appendChild(document.createTextNode(v))}}
```
I have significantly less morality than @dystroy, so I didn't bother with **var**. I did have to scope **f** though, and I did it somewhat cleverly.
That said, our answers are pretty similar, and I'm not sure there's much of a better way to go about it.
With collection recognition **(173)**:
```
function t(e,v){if(!v&&v!=''){v=e.data||'';for each(c in e.childNodes)v+=t(c);return v}else{ while(c=e.lastChild)e.removeChild(c);e.appendChild(document.createTextNode(v))}}
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 143 bytes
```
t=(e,h)=>h?.sub?[...e.children].map(c=>e.removeChild(c))&&e.appendChild(document.createTextNode(h)):(e.data||'')+[...e.childNodes].map(c=>t(c))
```
] |
[Question]
[
# Objective Requirements
* A main 'parent' file and a 'child' file.
* The parent file creates a new child file that contains code that must execute after creation.
* The child file that is created must delete the existing sibling file. It wants all the attention, afterall.
* No matter how many times the parent file is executed, a new child file must be created and executed.
* Every time a child file is executed, it must delete it's sibling.
* Since no two siblings are ever truly identical, each child file must also be unique.
* No matter how many child files are created, their names and file contents MUST be unique.
* Only the parent file may explicitly know the child names. (Parent may tell the new child it's older sibling's name.)
* Child files may not simply be renamed.
# Things to consider
* The parent may be modified by the child (children give us all grey hairs anyways, right?), but it's methods may not change.
* The child has to kill its sibling. It cannot force its sibling to commit suicide.
* No human interaction may occur beyond the execution of the parent (such as manual input).
# Winning Requirements
* Only the parent file character length / byte size will be measured.
* Fewest bytes/shortest length wins.
[*Inspired by this challenge.*](https://codegolf.stackexchange.com/questions/11101/creating-and-deleting-files-back-and-forth)
[Answer]
# Perl, 4 characters
Parent file (parent.pl):
```
do a
```
Initial child file (named a):
```
if ($0 =~ /parent\.pl$/)
{
$ARGV[0]=(-f 'a' ? 'a' : <a*>);
open B,'>'.($a='a'.time);
print B <>,'a';
exec "perl $a";
}
else
{
open PARENT,'>parent.pl';
print PARENT "do <a*>";
close PARENT;
while (<a*>)
{
if ($0 !~ /\Q$_\E$/)
{
unlink $_;
}
}
}
#
```
Nowhere does the question state that a child file does not exist at the beginning. Further, it *might* even be interpreted as requiring an initial child file (it states that the child must delete its sibling, never mentioning a special case when a sibling does not exist).
I assert that this fulfills all the requirements stated in the question.
One might object that "the child creates its own sibling"; however, this is not true. The parent is the program which is being executed when the child is created. It just gets some code stored in another file and runs that code.
This child not only kills its sibling; it also kills anyone else who is unlucky enough to have a name starting with `a` (consider that collateral damage). This is an artifact of my earlier attempts at the problem. Obviously, any method of killing the sibling could be implemented without changing the score.
[Answer]
## Lua, 80
```
n=io.open(0,'a'):write' ':seek()os.execute('echo rm '..n-1 ..' >'..n..'&sh '..n)
```
Parent file (filename `0`) appends one character to its own body on each run and treats its new length as name of next child file (so, first child file will be given name `82` and will contain `rm 81`).
Lua 5.2 required.
Usage: `lua 0`.
[Answer]
## Perl 68 bytes
```
utime$a+open(C,'>',$a=(stat$0)[8]),print(C"unlink~-$a"),$0;`perl $a`
```
Works in a similar fashion to the PHP script below, by updating its own access time to keep track of children names. As with all solutions below, the parent script may be named anything you choose.
---
## PHP 87 bytes
It seems that since our parent is reproducing asexually, all it really needs to do is touch itself.
```
<?touch($f=__FILE__,1+$t=filemtime($f));fputs(fopen($t,w),"<?@unlink($t-1);");`php $t`;
```
---
## PHP 110 (104) bytes
```
<?$f=$g=AAAAAAAA;fputs(fopen(++$f,w),"<?@unlink($g);fputs(fopen('".__FILE__."',c),'<?\$f=\$g=$f');");`php $f`;
```
If the parent is allowed to self-modify, a few bytes can be saved, mainly on quotation marks:
```
<?$f=$g=AAAAAAAA;fputs(fopen(++$f,w),"<?@unlink($g);");fputs(fopen(__FILE__,c),"<?\$f=\$g=$f");`php $f`;
```
Admittedly, the parent isn't very creative when naming its children. The first will be called `AAAAAAAB`, the second `AAAAAAAC` and so forth. The created child will delete its previous sibling, and modify its parent, making it somewhat 'older'.
The first child will contain the following (if the parent script is named `parent.php`):
```
<?@unlink(AAAAAAAA);fputs(fopen('parent.php',c),'<?$f=$g=AAAAAAAB');
```
[Answer]
**python 2.7 - 110 Characters**
```
c=0
import os
i=`c+1`
o(__file__,'r+').write('c='+i)
o('c'+i,'w').write('rm c'+`c`)
os.system('sh c'+i)
```
The above code would throw an error that can be ignored, the first time it is run.
A slightly longer modified version (128 characters) won;t complain the first time its run
```
c=0
import os
i=`c+1`
o(__file__,'r+').write('c='+i)
o('c'+i,'w').write('rm c'+`c`)
os.system('sh c'+i+'>/dev/null 2>&1')
```
[Answer]
# PHP 279
```
<?php $s="00000000.php";$c="11111111.php";$n=fopen($c,"w");fwrite($n,"<?php \$h=fopen('p.php','r');\$d=fread(\$h,328);\$h=fopen('p.php','w');fwrite(\$h,'<?php \$s=\"'.basename(__FILE__).'\";\$c=\"'.hash('crc32',microtime(true)).'.php\";'.substr(\$d,42));unlink('$s');");`php $c`;
```
It uses crc32 as a hash function, so it's not ENTIRELY 100% unique... I'll try to think of another solution. This one does cause a warning on the first execution, but works as expected every time there-after.
Here is a semi-ungolfed readable version (changed `substr()` start point so it would work ungolfed as a bit of copy+pasta):
```
<?php
$s="02204f88.php";
$c="4b2e0cfb.php";
$n = fopen($c, "w");
fwrite($n,"<?php
\$h=fopen('p.php','r');
\$d=fread(\$h,328);
\$h=fopen('p.php','w');
fwrite(\$h,'<?php
\$s=\"'.basename(__FILE__).'\";
\$c=\"'.hash('crc32',microtime(true)).'.php\";'.substr(\$d,43));
unlink('$s');
");
exec("php $c");
```
[Answer]
## python2 - 154
Needs a subdirectory called `c` to be at the same directory.
Generates sh. I took the liberty of calling the file contents unique when it contains the files random (enough?) name. Seems to work although I never close the generated file.
```
import os,binascii
l=os.listdir("c")
n="c/"+binascii.b2a_hex(os.urandom(15))+".py"
open(n,"w+").write("rm $1\n#"+n)
for v in l:os.system("sh "+n+" c/"+v)
```
If we know there is ALWAYS one child, we can shorten the script to 146 bytes:
```
import os,binascii
l=os.listdir("c")[0]
n="c/"+binascii.b2a_hex(os.urandom(15))+".py"
open(n,"w+").write("rm $1\n#"+n)
os.system("sh "+n+" c/"+l)
```
[Answer]
# Tcl - 131 chars
```
set n c[expr rand()].tcl;set f [open $n w+];puts $f [string map "@ $n" {lmap f [glob -ta -di . c*] {if {$f ne {@}} {file del $f}}}]
```
Not sure if I understand this correctly. (Delete all siblings, or only delete last one?)
I use glob and kill all other siblings in the same directory.
Names are unique, files are unique (contains own file name).
] |
[Question]
[
**This question already has answers here**:
[Spoonerise words](/questions/69385/spoonerise-words)
(44 answers)
Closed 8 years ago.
A spoonerisation is swapping the first letter/pronounceable syllable of two or more words.
**Example**: A lack of pies = A pack of lies. Bad salad = Sad ballad (ish) :)
Challenge: Write a program to spoonerise two words in the shortest characters possible.
Rules:
1. If the first letter is a consonant, you must include subsequent letters until you reach a vowel. (e.g. 'thanks' - the th gets removed and put on the front of the other word).
2. With words that start with vowels, do not remove anything from the start of the word.
Good luck :)
---
**UPDATE:** Multiple word spoonerisms are [not strictly applicable](http://www.fun-with-words.com/spoon_history.html), however from a programatic view we must cater for them so this is the rule: **Every word must change.** Example:
Weird Keen Monkey -> Meird Ween Konkey **OR** Keird Meen Wonkey **NOT** Meird **Keen** Wonkey
Also 'y' is treated as a **vowel** (just to simplify things a bit)
[Answer]
## Ruby (60) (61) (93) (80) (75) (71) (69 / 57)
Program changed to handle the new requirement of handling multiple words.
EDIT: Golfed down to 80. 75. 71. 69.
```
w=[];gets.gsub(/(\S*?)([aeiouy]\S*)/i){w+=[$2,' ',$1]};$><<w.pop+w*''
```
If we're only spoonerizing words that start with a consonant, here's a solution in 73. 65. (I realized I can just use scan instead of gsub.) 57.
```
$><<gets.gsub(p=/\b[^aeiouy\s]+/i){($'+$`+$&).scan(p)[0]}
```
Old program (two words only):
```
p='(.*?)([aeiou].+)';puts gets.gsub(/#{p} #{p}/i,'\3\2 \1\4')
```
[Answer]
## Haskell, 81
```
f[(a,b),(c,d)]=unwords[c++b,a++d]
main=interact$f.map(break(`elem`"aeiou")).words
```
[Answer]
## Ruby, 57 56
This only works for the original problem (with only two words).
```
$><<gets.sub(/#{r='([^aeiou]*)(.+)'} #{r}/i,'\3\2 \1\4')
```
[Answer]
## J, 77
*Answers the original version of the question, "spoonerise two words"; a solution for the changed question may follow.*
Couldn't shrink this to compete with the Ruby answers, so fell back on my more-familiar Perl.
```
exit([:;3 1 2 0 4{[:,({.@I.@e.&'aeiouAEIOU'({.;' ';~}.)]);._2@,&' ')&.stdin''
```
* `,&' '` appends a space
* `(`...`);._2` splits on the last character (the space) and applies
the parenthesized code to each element (i.e., each word)
* `{. @ I. @ e.&'aeiouAEIOU'` finds the index of the first vowel in that
word
* `({.;' ';~}.)` splits the word into leading consonants (if any) and a
tail, with a space at the end (each in a "box", so J doesn't pad them to matching lengths)
* `,` flattens the 2r x 3c matrix formed by the preceding into a
6-element list
* `3 1 2 0 4{` takes all those elements but the trailing space, swapping the lead
segments of the words
* `;` unboxes and concatenates the elements
* `(`...`)&.stdin''` does roughly the same as Perl's `-p`, reading stdin and echoing the result of "..." to stdout
* the explicit `exit` suppresses J's prompt for more input
[Answer]
## Perl, 43 (question v1), 91 79 (question v2) [107 to handle numerals in the phrase]
**v1**
Run with `-p` option (counted as 3 chars).
```
$p='([^aeiou]*)(.+)';s/$p $p/$3$2 $1$4/i
```
Same technique as the Ruby answers.
Using `-p` saves 9 characters over bracketing the code with `$_=<>;` and `;print` for explicit IO.
**v2**
Run with `-lp` (counted as 4 chars).
```
push@a,$1while s/\b([^ aeiouy\d]+)(?=[aeiouy])/$n++/ei;unshift@a,pop@a;s/(\d+)/$a[$1]/g
```
Rotates all the consonant-starts of words one word forward.
*Updated:* Add vowel lookahead, so it handles "to the nth degree" more gracefully ("do te nth thegree", not "do te th nthegree").
*Numerals:* user unknown asked about handling "There is no winner in 2011", because of the numerals. Adding markers around the numbers my solution uses, it can handle that:
```
push@a,$1while s/\b([^ aeiouy\0\d]+)(?=[aeiouy])/"\0".$n++."\0"/ei;unshift@a,pop@a;s/\0(\d+)\0/$a[$1]/g
```
Small question, big discussion....
[Answer]
### CSharp - 236
```
List<string> f(string w) {var t="aeiou".ToCharArray();var q=w.Split(' ').Where(c=>!t.Contains(c[0]));var i=q.Count()-1;return q.Select(c=>q.Select(x=>x.Substring(0,x.IndexOfAny(t))).ToList()[i--]+c.Substring(c.IndexOfAny(t))).ToList();}
```
[Answer]
## Scala 244
```
val s=readLine
def f(a:String,b:String)=a.replaceAll("^[^aeiouy]+",b.replaceAll("[aeiouy].*",""))
val l=("((^| )[^aeiouyAEIOUY]+)([^ ]+)".r findAllIn s map(_.trim)).toList
println(s.replaceAll(l(0),f(l(0),l(1))).replaceAll(l(1),f(l(1),l(0))))
```
My code contains 4 `y` (one of them lowercase) to handle `why` and `rythm` in a useful manner.
---
### Scala 248, updated for new challenge (change *all* consonantic words)
```
val w=readLine.split(" ")
val c=w.filter(_.matches("[^aeiouyAEIOUY].*"))
val l=c.size
var k=0
println((for(i<-0 to w.size-1)yield{if(w(i)==c(k%l)){k+=1
c(k-1).replaceAll("^[^aeiouy]+",c(k%l).replaceAll("[aeiouy].*",""))}else w(i)}).mkString(" "))
```
### ungolfed, and test cases:
```
val samples = List ("bad salad", "I tell smooth", "Sentence with vowel in the end", "tain bruck is faboo")
def konsInit (s: String) = s.matches ("[^aeiouyAEIOUY].*")
def flipInit (a: String, b: String) = a.replaceAll ("^[^aeiouy]+", b.replaceAll ("[aeiouy].*", ""))
def spoonize (sentence: String) {
val words = sentence.split (" ")
val kwords = words.filter (konsInit);
val len = kwords.size
var k = 0
val spoonies = for (i <- 0 to words.size-1) yield {
if (words (i) == kwords (k%len)) {
k += 1
flipInit (kwords (k-1), kwords (k%len))
} else words (i)
}
println (spoonies.mkString (" "))
}
samples.foreach (spoonize)
```
>
> sad balad
>
> I smell tooth
>
> wentence vith thowel in Se end
>
>
>
The last example can't be shown.
] |
[Question]
[
Given two numbers \$N\$ and \$x\$, find the number of \$x\$-digit numbers whose product of digits is \$N\$
\$N <10^6\$ and \$x <12\$
```
Sample Input (N x):
8 3
Sample Output:
10
```
[Answer]
### Golfscript ~~42~~ 31
```
~10\?.10/\,>{10base{*}*1$=},,\;
```
**Input:** Expects the numbers `N` and `x` as command line arguments (separated by space).
The program can be tested [here](http://golfscript.apphb.com/?c=Oyc4IDMnCgp%2BMTBcPy4xMC9cLD57MTBiYXNleyp9KjEkPX0sLFw7).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) 2, 13 bytes
```
{h.&t~lℕẹ≜×}ᶜ
```
[Try it online!](https://tio.run/nexus/brachylog2#ASAA3///e2guJnR@bOKEleG6ueKJnMOXfeG2nP//WzgsM13/Wg "Brachylog – TIO Nexus")
## Explanation
```
{h.&t~lℕẹ≜×}ᶜ
{ }ᶜ Count the number of
≜ values at this point
&t formed via taking the last element of the input,
ℕ generating an integer
~l of that length,
ẹ and splitting it into digits
× such that the product of those digits
h. is the first element of {the input}
```
One neat golfing trick used here is that unlike almost all metapredicates, `ᶜ` doesn't care at all about the actual value of `.` (which is normally used to construct an output for the metapredicates); as such, `.` can be used like any other variable (saving a byte because it appears implicitly before `}`). There are no implicit labelisations anywhere here, so I had to add an explicit labelisation using `≜` to give `ᶜ` something to count.
[Answer]
## Scala 107:
```
def f(N:Int,x:Int,s:Int=1):Int=if(s==N&&x==0)1 else
if(s>N||x==0)0 else
((1 to 9).map(i=>f(N,x-1,s*i))).sum
```
ungolfed, debugfriendly version:
```
def findProduct (N: Int, sofar: Int, togo:Int, collected:String=""):Int={
if (sofar == N && togo == 0) {
println (collected)
1
} else
if (sofar > N || togo == 0) 0 else
(1 to 9).map (x=> findProduct (N, sofar*x, togo-1, collected + " " + x)).sum
}
```
Invocation with debugging output:
```
scala> findProduct (3, 1, 8)
1 1 1 1 1 1 1 3
1 1 1 1 1 1 3 1
1 1 1 1 1 3 1 1
1 1 1 1 3 1 1 1
1 1 1 3 1 1 1 1
1 1 3 1 1 1 1 1
1 3 1 1 1 1 1 1
3 1 1 1 1 1 1 1
res175: Int = 8
scala> findProduct (8, 1, 3)
1 1 8
1 2 4
1 4 2
1 8 1
2 1 4
2 2 2
2 4 1
4 1 2
4 2 1
8 1 1
res176: Int = 10
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
⁵Ḷṗ⁸P€ċ
```
[Try it online!](https://tio.run/##AR8A4P9qZWxsef//4oG14bi24bmX4oG4UOKCrMSL////M/84 "Jelly – Try It Online")
Fun fact, this (as far as I can tell) would've worked, atom-for-atom, when [ais523's answer was posted](https://codegolf.stackexchange.com/a/116191/66833).
## How it works
```
⁵Ḷṗ⁸P€ċ - Main link. Takes N on the left and x on the right
⁵ - 10
Ḷ - Ḷowered range; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
⁸ - N
ṗ - Cartesian power; Yield all N-length sublists of [0, 1, ..., 9]
€ - Over each:
P - Take the product
ċ - Count occurrences of x
```
[Answer]
### C# 128
```
int Z(int n,int x){var i=(int)Math.Pow(10,x-1);return Enumerable.Range(i,i*9).Count(j=>(j+"").Aggregate(1,(a,c)=>a*(c-48))==n);}
```
This C# method returns the number of `x`-digit numbers whose product of digits is `n`. It requires that namespaces `System` and `System.Linq` are imported in the current context.
Online version: <http://ideone.com/0krup>
[Answer]
## Haskell 117 chars
```
import Data.Char
main = print $ f 3 8
f n t = length[x|x<-[10^(n-1)..(10^n-1)],foldr(*)1(map digitToInt $ show x)==t]
```
[Answer]
# K, 49
```
{+/x=*/'"I"$''${x@&~x in y}.!:'"i"$10 xexp y,y-1}
```
.
```
k){+/x=*/'"I"$''${x@&~x in y}.!:'"i"$10 xexp y,y-1}[8;3]
10
```
[Answer]
# J, 40 bytes
```
[:+/[=[:*/"1(10#~])#:(10^<:@])}.[:i.10^]
```
Generates all `x`-digit numbers, convert each to base 10, then find the product of each number, and test whether each number is equal to the left hand side, and then find the sum of each boolean.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
,’⁵*r/ḊDP€ċƓ
```
[Try it online!](https://tio.run/nexus/jelly#ARwA4///LOKAmeKBtSpyL@G4ikRQ4oKsxIvGk///OP8z "Jelly – TIO Nexus")
Takes \$x\$ as a command line argument and \$N\$ on standard input.
## Explanation
```
,’⁵*r/ḊDP€ċƓ
, On {the input} and
’ {the input} minus 1
⁵* take 10 to the power of each of those numbers
r/ then form a range between them
Ḋ without its first element;
D treat each element as a list of digits,
P€ take the product of each of those digit lists,
ċ then count the number of times
Ɠ the value from standard input appears
```
The hard part is generating the list of numbers with *x* digits; the lowest such number is \$10^{x-1}\$, the highest is \$10^x-1\$ The range here is generated via first generating the pair \$(x,x-1)\$, then taking 10 to the power of both of those, and then generating the range between them. The range includes both endpoints by default; just in case *N* happens to be 0, we need to remove the top end of the range (which comes first because it's a "backwards" range) using `Ḋ`.
[Answer]
# Python, 164 bytes
```
from itertools import *
N,x=map(int,raw_input().split())
print len([c for c in product([d for d in range(1,10)if N%d==0],repeat=x) if reduce(lambda x,y:x*y,c)==N])
```
] |
Subsets and Splits